chunk-vite-node-externalize.8d8032d0.mjs 316 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731
  1. import { a as resolve, j as join, b as basename, d as dirname, c as distDir, e as rootDir, p as picocolors, i as isAbsolute, r as relative, f as configFiles, g as defaultPort, n as normalize, t as toNamespacedPath, E as EXIT_CODE_RESTART } from './chunk-constants.71e8a211.mjs';
  2. import { p as pLimit, g as getCoverageProvider, C as CoverageProviderMap } from './chunk-integrations-coverage.99c020eb.mjs';
  3. import { g as getEnvPackageName } from './chunk-env-node.ceb43f1c.mjs';
  4. import { A as AggregateErrorPonyfill, s as slash$2, o as isNode, p as relativePath, z as getTests, e as getFullName, x as hasFailed, B as hasFailedSnapshot, C as getSuites, j as notNullish, v as shuffle, t as toArray$1, n as noop$1, D as deepMerge, b as getCallLastIndex, E as ensurePackageInstalled, F as stdout } from './chunk-mock-date.2917be60.mjs';
  5. import { loadConfigFromFile, normalizePath, createServer, mergeConfig } from 'vite';
  6. import path$a from 'path';
  7. import url, { fileURLToPath } from 'url';
  8. import process$1 from 'process';
  9. import fs$8, { promises, existsSync, readFileSync } from 'fs';
  10. import require$$0, { cpus, hostname } from 'os';
  11. import util$2 from 'util';
  12. import require$$0$1 from 'stream';
  13. import require$$2 from 'events';
  14. import { c as commonjsGlobal } from './vendor-_commonjsHelpers.4da45ef5.mjs';
  15. import { c as createBirpc, V as ViteNodeRunner } from './chunk-vite-node-client.da0a17ff.mjs';
  16. import { performance } from 'perf_hooks';
  17. import createDebug from 'debug';
  18. import { i as isNodeBuiltin, a as isValidNodeImport, s as slash$1, t as toArray, b as toFilePath, w as withInlineSourcemap } from './chunk-vite-node-utils.473cd0b2.mjs';
  19. import { MessageChannel } from 'worker_threads';
  20. import { Tinypool } from 'tinypool';
  21. import { c as stripAnsi, d as cliTruncate, p as parseStacktrace, i as interpretSourcePos, e as stringWidth, h as ansiStyles, j as sliceAnsi, s as stringify$5, u as unifiedDiff, b as posToNumber, l as lineSplitRE } from './chunk-utils-source-map.2be5aa48.mjs';
  22. import { b as safeSetInterval, c as safeClearInterval, s as safeSetTimeout, a as safeClearTimeout } from './chunk-utils-timers.b48455ed.mjs';
  23. import { resolveModule } from 'local-pkg';
  24. import { createHash } from 'crypto';
  25. import { o as onetime } from './vendor-index.9d9196cc.mjs';
  26. import { s as signalExit } from './vendor-index.29636037.mjs';
  27. import MagicString from './chunk-magic-string.56b2b543.mjs';
  28. import { stripLiteral } from 'strip-literal';
  29. import require$$0$2 from 'readline';
  30. import { p as prompts } from './vendor-index.ae96af6e.mjs';
  31. var version$1 = "0.23.4";
  32. class EndError extends Error {
  33. constructor(value) {
  34. super();
  35. this.value = value;
  36. }
  37. }
  38. // The input can also be a promise, so we await it.
  39. const testElement = async (element, tester) => tester(await element);
  40. // The input can also be a promise, so we `Promise.all()` them both.
  41. const finder = async element => {
  42. const values = await Promise.all(element);
  43. if (values[1] === true) {
  44. throw new EndError(values[0]);
  45. }
  46. return false;
  47. };
  48. async function pLocate(
  49. iterable,
  50. tester,
  51. {
  52. concurrency = Number.POSITIVE_INFINITY,
  53. preserveOrder = true,
  54. } = {},
  55. ) {
  56. const limit = pLimit(concurrency);
  57. // Start all the promises concurrently with optional limit.
  58. const items = [...iterable].map(element => [element, limit(testElement, element, tester)]);
  59. // Check the promises either serially or concurrently.
  60. const checkLimit = pLimit(preserveOrder ? 1 : Number.POSITIVE_INFINITY);
  61. try {
  62. await Promise.all(items.map(element => checkLimit(finder, element)));
  63. } catch (error) {
  64. if (error instanceof EndError) {
  65. return error.value;
  66. }
  67. throw error;
  68. }
  69. }
  70. const typeMappings = {
  71. directory: 'isDirectory',
  72. file: 'isFile',
  73. };
  74. function checkType(type) {
  75. if (Object.hasOwnProperty.call(typeMappings, type)) {
  76. return;
  77. }
  78. throw new Error(`Invalid type specified: ${type}`);
  79. }
  80. const matchType = (type, stat) => stat[typeMappings[type]]();
  81. const toPath$1 = urlOrPath => urlOrPath instanceof URL ? fileURLToPath(urlOrPath) : urlOrPath;
  82. async function locatePath(
  83. paths,
  84. {
  85. cwd = process$1.cwd(),
  86. type = 'file',
  87. allowSymlinks = true,
  88. concurrency,
  89. preserveOrder,
  90. } = {},
  91. ) {
  92. checkType(type);
  93. cwd = toPath$1(cwd);
  94. const statFunction = allowSymlinks ? promises.stat : promises.lstat;
  95. return pLocate(paths, async path_ => {
  96. try {
  97. const stat = await statFunction(path$a.resolve(cwd, path_));
  98. return matchType(type, stat);
  99. } catch {
  100. return false;
  101. }
  102. }, {concurrency, preserveOrder});
  103. }
  104. const toPath = urlOrPath => urlOrPath instanceof URL ? fileURLToPath(urlOrPath) : urlOrPath;
  105. const findUpStop = Symbol('findUpStop');
  106. async function findUpMultiple(name, options = {}) {
  107. let directory = path$a.resolve(toPath(options.cwd) || '');
  108. const {root} = path$a.parse(directory);
  109. const stopAt = path$a.resolve(directory, options.stopAt || root);
  110. const limit = options.limit || Number.POSITIVE_INFINITY;
  111. const paths = [name].flat();
  112. const runMatcher = async locateOptions => {
  113. if (typeof name !== 'function') {
  114. return locatePath(paths, locateOptions);
  115. }
  116. const foundPath = await name(locateOptions.cwd);
  117. if (typeof foundPath === 'string') {
  118. return locatePath([foundPath], locateOptions);
  119. }
  120. return foundPath;
  121. };
  122. const matches = [];
  123. // eslint-disable-next-line no-constant-condition
  124. while (true) {
  125. // eslint-disable-next-line no-await-in-loop
  126. const foundPath = await runMatcher({...options, cwd: directory});
  127. if (foundPath === findUpStop) {
  128. break;
  129. }
  130. if (foundPath) {
  131. matches.push(path$a.resolve(directory, foundPath));
  132. }
  133. if (directory === stopAt || matches.length >= limit) {
  134. break;
  135. }
  136. directory = path$a.dirname(directory);
  137. }
  138. return matches;
  139. }
  140. async function findUp(name, options = {}) {
  141. const matches = await findUpMultiple(name, {...options, limit: 1});
  142. return matches[0];
  143. }
  144. var tasks = {};
  145. var utils$k = {};
  146. var array$1 = {};
  147. Object.defineProperty(array$1, "__esModule", { value: true });
  148. array$1.splitWhen = array$1.flatten = void 0;
  149. function flatten(items) {
  150. return items.reduce((collection, item) => [].concat(collection, item), []);
  151. }
  152. array$1.flatten = flatten;
  153. function splitWhen(items, predicate) {
  154. const result = [[]];
  155. let groupIndex = 0;
  156. for (const item of items) {
  157. if (predicate(item)) {
  158. groupIndex++;
  159. result[groupIndex] = [];
  160. }
  161. else {
  162. result[groupIndex].push(item);
  163. }
  164. }
  165. return result;
  166. }
  167. array$1.splitWhen = splitWhen;
  168. var errno$1 = {};
  169. Object.defineProperty(errno$1, "__esModule", { value: true });
  170. errno$1.isEnoentCodeError = void 0;
  171. function isEnoentCodeError(error) {
  172. return error.code === 'ENOENT';
  173. }
  174. errno$1.isEnoentCodeError = isEnoentCodeError;
  175. var fs$7 = {};
  176. Object.defineProperty(fs$7, "__esModule", { value: true });
  177. fs$7.createDirentFromStats = void 0;
  178. class DirentFromStats$1 {
  179. constructor(name, stats) {
  180. this.name = name;
  181. this.isBlockDevice = stats.isBlockDevice.bind(stats);
  182. this.isCharacterDevice = stats.isCharacterDevice.bind(stats);
  183. this.isDirectory = stats.isDirectory.bind(stats);
  184. this.isFIFO = stats.isFIFO.bind(stats);
  185. this.isFile = stats.isFile.bind(stats);
  186. this.isSocket = stats.isSocket.bind(stats);
  187. this.isSymbolicLink = stats.isSymbolicLink.bind(stats);
  188. }
  189. }
  190. function createDirentFromStats$1(name, stats) {
  191. return new DirentFromStats$1(name, stats);
  192. }
  193. fs$7.createDirentFromStats = createDirentFromStats$1;
  194. var path$9 = {};
  195. Object.defineProperty(path$9, "__esModule", { value: true });
  196. path$9.removeLeadingDotSegment = path$9.escape = path$9.makeAbsolute = path$9.unixify = void 0;
  197. const path$8 = path$a;
  198. const LEADING_DOT_SEGMENT_CHARACTERS_COUNT = 2; // ./ or .\\
  199. const UNESCAPED_GLOB_SYMBOLS_RE = /(\\?)([()*?[\]{|}]|^!|[!+@](?=\())/g;
  200. /**
  201. * Designed to work only with simple paths: `dir\\file`.
  202. */
  203. function unixify(filepath) {
  204. return filepath.replace(/\\/g, '/');
  205. }
  206. path$9.unixify = unixify;
  207. function makeAbsolute(cwd, filepath) {
  208. return path$8.resolve(cwd, filepath);
  209. }
  210. path$9.makeAbsolute = makeAbsolute;
  211. function escape(pattern) {
  212. return pattern.replace(UNESCAPED_GLOB_SYMBOLS_RE, '\\$2');
  213. }
  214. path$9.escape = escape;
  215. function removeLeadingDotSegment(entry) {
  216. // We do not use `startsWith` because this is 10x slower than current implementation for some cases.
  217. // eslint-disable-next-line @typescript-eslint/prefer-string-starts-ends-with
  218. if (entry.charAt(0) === '.') {
  219. const secondCharactery = entry.charAt(1);
  220. if (secondCharactery === '/' || secondCharactery === '\\') {
  221. return entry.slice(LEADING_DOT_SEGMENT_CHARACTERS_COUNT);
  222. }
  223. }
  224. return entry;
  225. }
  226. path$9.removeLeadingDotSegment = removeLeadingDotSegment;
  227. var pattern$1 = {};
  228. /*!
  229. * is-extglob <https://github.com/jonschlinkert/is-extglob>
  230. *
  231. * Copyright (c) 2014-2016, Jon Schlinkert.
  232. * Licensed under the MIT License.
  233. */
  234. var isExtglob$1 = function isExtglob(str) {
  235. if (typeof str !== 'string' || str === '') {
  236. return false;
  237. }
  238. var match;
  239. while ((match = /(\\).|([@?!+*]\(.*\))/g.exec(str))) {
  240. if (match[2]) return true;
  241. str = str.slice(match.index + match[0].length);
  242. }
  243. return false;
  244. };
  245. /*!
  246. * is-glob <https://github.com/jonschlinkert/is-glob>
  247. *
  248. * Copyright (c) 2014-2017, Jon Schlinkert.
  249. * Released under the MIT License.
  250. */
  251. var isExtglob = isExtglob$1;
  252. var chars = { '{': '}', '(': ')', '[': ']'};
  253. var strictCheck = function(str) {
  254. if (str[0] === '!') {
  255. return true;
  256. }
  257. var index = 0;
  258. var pipeIndex = -2;
  259. var closeSquareIndex = -2;
  260. var closeCurlyIndex = -2;
  261. var closeParenIndex = -2;
  262. var backSlashIndex = -2;
  263. while (index < str.length) {
  264. if (str[index] === '*') {
  265. return true;
  266. }
  267. if (str[index + 1] === '?' && /[\].+)]/.test(str[index])) {
  268. return true;
  269. }
  270. if (closeSquareIndex !== -1 && str[index] === '[' && str[index + 1] !== ']') {
  271. if (closeSquareIndex < index) {
  272. closeSquareIndex = str.indexOf(']', index);
  273. }
  274. if (closeSquareIndex > index) {
  275. if (backSlashIndex === -1 || backSlashIndex > closeSquareIndex) {
  276. return true;
  277. }
  278. backSlashIndex = str.indexOf('\\', index);
  279. if (backSlashIndex === -1 || backSlashIndex > closeSquareIndex) {
  280. return true;
  281. }
  282. }
  283. }
  284. if (closeCurlyIndex !== -1 && str[index] === '{' && str[index + 1] !== '}') {
  285. closeCurlyIndex = str.indexOf('}', index);
  286. if (closeCurlyIndex > index) {
  287. backSlashIndex = str.indexOf('\\', index);
  288. if (backSlashIndex === -1 || backSlashIndex > closeCurlyIndex) {
  289. return true;
  290. }
  291. }
  292. }
  293. if (closeParenIndex !== -1 && str[index] === '(' && str[index + 1] === '?' && /[:!=]/.test(str[index + 2]) && str[index + 3] !== ')') {
  294. closeParenIndex = str.indexOf(')', index);
  295. if (closeParenIndex > index) {
  296. backSlashIndex = str.indexOf('\\', index);
  297. if (backSlashIndex === -1 || backSlashIndex > closeParenIndex) {
  298. return true;
  299. }
  300. }
  301. }
  302. if (pipeIndex !== -1 && str[index] === '(' && str[index + 1] !== '|') {
  303. if (pipeIndex < index) {
  304. pipeIndex = str.indexOf('|', index);
  305. }
  306. if (pipeIndex !== -1 && str[pipeIndex + 1] !== ')') {
  307. closeParenIndex = str.indexOf(')', pipeIndex);
  308. if (closeParenIndex > pipeIndex) {
  309. backSlashIndex = str.indexOf('\\', pipeIndex);
  310. if (backSlashIndex === -1 || backSlashIndex > closeParenIndex) {
  311. return true;
  312. }
  313. }
  314. }
  315. }
  316. if (str[index] === '\\') {
  317. var open = str[index + 1];
  318. index += 2;
  319. var close = chars[open];
  320. if (close) {
  321. var n = str.indexOf(close, index);
  322. if (n !== -1) {
  323. index = n + 1;
  324. }
  325. }
  326. if (str[index] === '!') {
  327. return true;
  328. }
  329. } else {
  330. index++;
  331. }
  332. }
  333. return false;
  334. };
  335. var relaxedCheck = function(str) {
  336. if (str[0] === '!') {
  337. return true;
  338. }
  339. var index = 0;
  340. while (index < str.length) {
  341. if (/[*?{}()[\]]/.test(str[index])) {
  342. return true;
  343. }
  344. if (str[index] === '\\') {
  345. var open = str[index + 1];
  346. index += 2;
  347. var close = chars[open];
  348. if (close) {
  349. var n = str.indexOf(close, index);
  350. if (n !== -1) {
  351. index = n + 1;
  352. }
  353. }
  354. if (str[index] === '!') {
  355. return true;
  356. }
  357. } else {
  358. index++;
  359. }
  360. }
  361. return false;
  362. };
  363. var isGlob$1 = function isGlob(str, options) {
  364. if (typeof str !== 'string' || str === '') {
  365. return false;
  366. }
  367. if (isExtglob(str)) {
  368. return true;
  369. }
  370. var check = strictCheck;
  371. // optionally relax check
  372. if (options && options.strict === false) {
  373. check = relaxedCheck;
  374. }
  375. return check(str);
  376. };
  377. var isGlob = isGlob$1;
  378. var pathPosixDirname = path$a.posix.dirname;
  379. var isWin32 = require$$0.platform() === 'win32';
  380. var slash = '/';
  381. var backslash = /\\/g;
  382. var enclosure = /[\{\[].*[\}\]]$/;
  383. var globby = /(^|[^\\])([\{\[]|\([^\)]+$)/;
  384. var escaped = /\\([\!\*\?\|\[\]\(\)\{\}])/g;
  385. /**
  386. * @param {string} str
  387. * @param {Object} opts
  388. * @param {boolean} [opts.flipBackslashes=true]
  389. * @returns {string}
  390. */
  391. var globParent$1 = function globParent(str, opts) {
  392. var options = Object.assign({ flipBackslashes: true }, opts);
  393. // flip windows path separators
  394. if (options.flipBackslashes && isWin32 && str.indexOf(slash) < 0) {
  395. str = str.replace(backslash, slash);
  396. }
  397. // special case for strings ending in enclosure containing path separator
  398. if (enclosure.test(str)) {
  399. str += slash;
  400. }
  401. // preserves full path in case of trailing path separator
  402. str += 'a';
  403. // remove path parts that are globby
  404. do {
  405. str = pathPosixDirname(str);
  406. } while (isGlob(str) || globby.test(str));
  407. // remove escape chars and return result
  408. return str.replace(escaped, '$1');
  409. };
  410. var utils$j = {};
  411. (function (exports) {
  412. exports.isInteger = num => {
  413. if (typeof num === 'number') {
  414. return Number.isInteger(num);
  415. }
  416. if (typeof num === 'string' && num.trim() !== '') {
  417. return Number.isInteger(Number(num));
  418. }
  419. return false;
  420. };
  421. /**
  422. * Find a node of the given type
  423. */
  424. exports.find = (node, type) => node.nodes.find(node => node.type === type);
  425. /**
  426. * Find a node of the given type
  427. */
  428. exports.exceedsLimit = (min, max, step = 1, limit) => {
  429. if (limit === false) return false;
  430. if (!exports.isInteger(min) || !exports.isInteger(max)) return false;
  431. return ((Number(max) - Number(min)) / Number(step)) >= limit;
  432. };
  433. /**
  434. * Escape the given node with '\\' before node.value
  435. */
  436. exports.escapeNode = (block, n = 0, type) => {
  437. let node = block.nodes[n];
  438. if (!node) return;
  439. if ((type && node.type === type) || node.type === 'open' || node.type === 'close') {
  440. if (node.escaped !== true) {
  441. node.value = '\\' + node.value;
  442. node.escaped = true;
  443. }
  444. }
  445. };
  446. /**
  447. * Returns true if the given brace node should be enclosed in literal braces
  448. */
  449. exports.encloseBrace = node => {
  450. if (node.type !== 'brace') return false;
  451. if ((node.commas >> 0 + node.ranges >> 0) === 0) {
  452. node.invalid = true;
  453. return true;
  454. }
  455. return false;
  456. };
  457. /**
  458. * Returns true if a brace node is invalid.
  459. */
  460. exports.isInvalidBrace = block => {
  461. if (block.type !== 'brace') return false;
  462. if (block.invalid === true || block.dollar) return true;
  463. if ((block.commas >> 0 + block.ranges >> 0) === 0) {
  464. block.invalid = true;
  465. return true;
  466. }
  467. if (block.open !== true || block.close !== true) {
  468. block.invalid = true;
  469. return true;
  470. }
  471. return false;
  472. };
  473. /**
  474. * Returns true if a node is an open or close node
  475. */
  476. exports.isOpenOrClose = node => {
  477. if (node.type === 'open' || node.type === 'close') {
  478. return true;
  479. }
  480. return node.open === true || node.close === true;
  481. };
  482. /**
  483. * Reduce an array of text nodes.
  484. */
  485. exports.reduce = nodes => nodes.reduce((acc, node) => {
  486. if (node.type === 'text') acc.push(node.value);
  487. if (node.type === 'range') node.type = 'text';
  488. return acc;
  489. }, []);
  490. /**
  491. * Flatten an array
  492. */
  493. exports.flatten = (...args) => {
  494. const result = [];
  495. const flat = arr => {
  496. for (let i = 0; i < arr.length; i++) {
  497. let ele = arr[i];
  498. Array.isArray(ele) ? flat(ele) : ele !== void 0 && result.push(ele);
  499. }
  500. return result;
  501. };
  502. flat(args);
  503. return result;
  504. };
  505. } (utils$j));
  506. const utils$i = utils$j;
  507. var stringify$4 = (ast, options = {}) => {
  508. let stringify = (node, parent = {}) => {
  509. let invalidBlock = options.escapeInvalid && utils$i.isInvalidBrace(parent);
  510. let invalidNode = node.invalid === true && options.escapeInvalid === true;
  511. let output = '';
  512. if (node.value) {
  513. if ((invalidBlock || invalidNode) && utils$i.isOpenOrClose(node)) {
  514. return '\\' + node.value;
  515. }
  516. return node.value;
  517. }
  518. if (node.value) {
  519. return node.value;
  520. }
  521. if (node.nodes) {
  522. for (let child of node.nodes) {
  523. output += stringify(child);
  524. }
  525. }
  526. return output;
  527. };
  528. return stringify(ast);
  529. };
  530. /*!
  531. * is-number <https://github.com/jonschlinkert/is-number>
  532. *
  533. * Copyright (c) 2014-present, Jon Schlinkert.
  534. * Released under the MIT License.
  535. */
  536. var isNumber$2 = function(num) {
  537. if (typeof num === 'number') {
  538. return num - num === 0;
  539. }
  540. if (typeof num === 'string' && num.trim() !== '') {
  541. return Number.isFinite ? Number.isFinite(+num) : isFinite(+num);
  542. }
  543. return false;
  544. };
  545. /*!
  546. * to-regex-range <https://github.com/micromatch/to-regex-range>
  547. *
  548. * Copyright (c) 2015-present, Jon Schlinkert.
  549. * Released under the MIT License.
  550. */
  551. const isNumber$1 = isNumber$2;
  552. const toRegexRange$1 = (min, max, options) => {
  553. if (isNumber$1(min) === false) {
  554. throw new TypeError('toRegexRange: expected the first argument to be a number');
  555. }
  556. if (max === void 0 || min === max) {
  557. return String(min);
  558. }
  559. if (isNumber$1(max) === false) {
  560. throw new TypeError('toRegexRange: expected the second argument to be a number.');
  561. }
  562. let opts = { relaxZeros: true, ...options };
  563. if (typeof opts.strictZeros === 'boolean') {
  564. opts.relaxZeros = opts.strictZeros === false;
  565. }
  566. let relax = String(opts.relaxZeros);
  567. let shorthand = String(opts.shorthand);
  568. let capture = String(opts.capture);
  569. let wrap = String(opts.wrap);
  570. let cacheKey = min + ':' + max + '=' + relax + shorthand + capture + wrap;
  571. if (toRegexRange$1.cache.hasOwnProperty(cacheKey)) {
  572. return toRegexRange$1.cache[cacheKey].result;
  573. }
  574. let a = Math.min(min, max);
  575. let b = Math.max(min, max);
  576. if (Math.abs(a - b) === 1) {
  577. let result = min + '|' + max;
  578. if (opts.capture) {
  579. return `(${result})`;
  580. }
  581. if (opts.wrap === false) {
  582. return result;
  583. }
  584. return `(?:${result})`;
  585. }
  586. let isPadded = hasPadding(min) || hasPadding(max);
  587. let state = { min, max, a, b };
  588. let positives = [];
  589. let negatives = [];
  590. if (isPadded) {
  591. state.isPadded = isPadded;
  592. state.maxLen = String(state.max).length;
  593. }
  594. if (a < 0) {
  595. let newMin = b < 0 ? Math.abs(b) : 1;
  596. negatives = splitToPatterns(newMin, Math.abs(a), state, opts);
  597. a = state.a = 0;
  598. }
  599. if (b >= 0) {
  600. positives = splitToPatterns(a, b, state, opts);
  601. }
  602. state.negatives = negatives;
  603. state.positives = positives;
  604. state.result = collatePatterns(negatives, positives);
  605. if (opts.capture === true) {
  606. state.result = `(${state.result})`;
  607. } else if (opts.wrap !== false && (positives.length + negatives.length) > 1) {
  608. state.result = `(?:${state.result})`;
  609. }
  610. toRegexRange$1.cache[cacheKey] = state;
  611. return state.result;
  612. };
  613. function collatePatterns(neg, pos, options) {
  614. let onlyNegative = filterPatterns(neg, pos, '-', false) || [];
  615. let onlyPositive = filterPatterns(pos, neg, '', false) || [];
  616. let intersected = filterPatterns(neg, pos, '-?', true) || [];
  617. let subpatterns = onlyNegative.concat(intersected).concat(onlyPositive);
  618. return subpatterns.join('|');
  619. }
  620. function splitToRanges(min, max) {
  621. let nines = 1;
  622. let zeros = 1;
  623. let stop = countNines(min, nines);
  624. let stops = new Set([max]);
  625. while (min <= stop && stop <= max) {
  626. stops.add(stop);
  627. nines += 1;
  628. stop = countNines(min, nines);
  629. }
  630. stop = countZeros(max + 1, zeros) - 1;
  631. while (min < stop && stop <= max) {
  632. stops.add(stop);
  633. zeros += 1;
  634. stop = countZeros(max + 1, zeros) - 1;
  635. }
  636. stops = [...stops];
  637. stops.sort(compare);
  638. return stops;
  639. }
  640. /**
  641. * Convert a range to a regex pattern
  642. * @param {Number} `start`
  643. * @param {Number} `stop`
  644. * @return {String}
  645. */
  646. function rangeToPattern(start, stop, options) {
  647. if (start === stop) {
  648. return { pattern: start, count: [], digits: 0 };
  649. }
  650. let zipped = zip(start, stop);
  651. let digits = zipped.length;
  652. let pattern = '';
  653. let count = 0;
  654. for (let i = 0; i < digits; i++) {
  655. let [startDigit, stopDigit] = zipped[i];
  656. if (startDigit === stopDigit) {
  657. pattern += startDigit;
  658. } else if (startDigit !== '0' || stopDigit !== '9') {
  659. pattern += toCharacterClass(startDigit, stopDigit);
  660. } else {
  661. count++;
  662. }
  663. }
  664. if (count) {
  665. pattern += options.shorthand === true ? '\\d' : '[0-9]';
  666. }
  667. return { pattern, count: [count], digits };
  668. }
  669. function splitToPatterns(min, max, tok, options) {
  670. let ranges = splitToRanges(min, max);
  671. let tokens = [];
  672. let start = min;
  673. let prev;
  674. for (let i = 0; i < ranges.length; i++) {
  675. let max = ranges[i];
  676. let obj = rangeToPattern(String(start), String(max), options);
  677. let zeros = '';
  678. if (!tok.isPadded && prev && prev.pattern === obj.pattern) {
  679. if (prev.count.length > 1) {
  680. prev.count.pop();
  681. }
  682. prev.count.push(obj.count[0]);
  683. prev.string = prev.pattern + toQuantifier(prev.count);
  684. start = max + 1;
  685. continue;
  686. }
  687. if (tok.isPadded) {
  688. zeros = padZeros(max, tok, options);
  689. }
  690. obj.string = zeros + obj.pattern + toQuantifier(obj.count);
  691. tokens.push(obj);
  692. start = max + 1;
  693. prev = obj;
  694. }
  695. return tokens;
  696. }
  697. function filterPatterns(arr, comparison, prefix, intersection, options) {
  698. let result = [];
  699. for (let ele of arr) {
  700. let { string } = ele;
  701. // only push if _both_ are negative...
  702. if (!intersection && !contains(comparison, 'string', string)) {
  703. result.push(prefix + string);
  704. }
  705. // or _both_ are positive
  706. if (intersection && contains(comparison, 'string', string)) {
  707. result.push(prefix + string);
  708. }
  709. }
  710. return result;
  711. }
  712. /**
  713. * Zip strings
  714. */
  715. function zip(a, b) {
  716. let arr = [];
  717. for (let i = 0; i < a.length; i++) arr.push([a[i], b[i]]);
  718. return arr;
  719. }
  720. function compare(a, b) {
  721. return a > b ? 1 : b > a ? -1 : 0;
  722. }
  723. function contains(arr, key, val) {
  724. return arr.some(ele => ele[key] === val);
  725. }
  726. function countNines(min, len) {
  727. return Number(String(min).slice(0, -len) + '9'.repeat(len));
  728. }
  729. function countZeros(integer, zeros) {
  730. return integer - (integer % Math.pow(10, zeros));
  731. }
  732. function toQuantifier(digits) {
  733. let [start = 0, stop = ''] = digits;
  734. if (stop || start > 1) {
  735. return `{${start + (stop ? ',' + stop : '')}}`;
  736. }
  737. return '';
  738. }
  739. function toCharacterClass(a, b, options) {
  740. return `[${a}${(b - a === 1) ? '' : '-'}${b}]`;
  741. }
  742. function hasPadding(str) {
  743. return /^-?(0+)\d/.test(str);
  744. }
  745. function padZeros(value, tok, options) {
  746. if (!tok.isPadded) {
  747. return value;
  748. }
  749. let diff = Math.abs(tok.maxLen - String(value).length);
  750. let relax = options.relaxZeros !== false;
  751. switch (diff) {
  752. case 0:
  753. return '';
  754. case 1:
  755. return relax ? '0?' : '0';
  756. case 2:
  757. return relax ? '0{0,2}' : '00';
  758. default: {
  759. return relax ? `0{0,${diff}}` : `0{${diff}}`;
  760. }
  761. }
  762. }
  763. /**
  764. * Cache
  765. */
  766. toRegexRange$1.cache = {};
  767. toRegexRange$1.clearCache = () => (toRegexRange$1.cache = {});
  768. /**
  769. * Expose `toRegexRange`
  770. */
  771. var toRegexRange_1 = toRegexRange$1;
  772. /*!
  773. * fill-range <https://github.com/jonschlinkert/fill-range>
  774. *
  775. * Copyright (c) 2014-present, Jon Schlinkert.
  776. * Licensed under the MIT License.
  777. */
  778. const util$1 = util$2;
  779. const toRegexRange = toRegexRange_1;
  780. const isObject$1 = val => val !== null && typeof val === 'object' && !Array.isArray(val);
  781. const transform$1 = toNumber => {
  782. return value => toNumber === true ? Number(value) : String(value);
  783. };
  784. const isValidValue = value => {
  785. return typeof value === 'number' || (typeof value === 'string' && value !== '');
  786. };
  787. const isNumber = num => Number.isInteger(+num);
  788. const zeros = input => {
  789. let value = `${input}`;
  790. let index = -1;
  791. if (value[0] === '-') value = value.slice(1);
  792. if (value === '0') return false;
  793. while (value[++index] === '0');
  794. return index > 0;
  795. };
  796. const stringify$3 = (start, end, options) => {
  797. if (typeof start === 'string' || typeof end === 'string') {
  798. return true;
  799. }
  800. return options.stringify === true;
  801. };
  802. const pad = (input, maxLength, toNumber) => {
  803. if (maxLength > 0) {
  804. let dash = input[0] === '-' ? '-' : '';
  805. if (dash) input = input.slice(1);
  806. input = (dash + input.padStart(dash ? maxLength - 1 : maxLength, '0'));
  807. }
  808. if (toNumber === false) {
  809. return String(input);
  810. }
  811. return input;
  812. };
  813. const toMaxLen = (input, maxLength) => {
  814. let negative = input[0] === '-' ? '-' : '';
  815. if (negative) {
  816. input = input.slice(1);
  817. maxLength--;
  818. }
  819. while (input.length < maxLength) input = '0' + input;
  820. return negative ? ('-' + input) : input;
  821. };
  822. const toSequence = (parts, options) => {
  823. parts.negatives.sort((a, b) => a < b ? -1 : a > b ? 1 : 0);
  824. parts.positives.sort((a, b) => a < b ? -1 : a > b ? 1 : 0);
  825. let prefix = options.capture ? '' : '?:';
  826. let positives = '';
  827. let negatives = '';
  828. let result;
  829. if (parts.positives.length) {
  830. positives = parts.positives.join('|');
  831. }
  832. if (parts.negatives.length) {
  833. negatives = `-(${prefix}${parts.negatives.join('|')})`;
  834. }
  835. if (positives && negatives) {
  836. result = `${positives}|${negatives}`;
  837. } else {
  838. result = positives || negatives;
  839. }
  840. if (options.wrap) {
  841. return `(${prefix}${result})`;
  842. }
  843. return result;
  844. };
  845. const toRange = (a, b, isNumbers, options) => {
  846. if (isNumbers) {
  847. return toRegexRange(a, b, { wrap: false, ...options });
  848. }
  849. let start = String.fromCharCode(a);
  850. if (a === b) return start;
  851. let stop = String.fromCharCode(b);
  852. return `[${start}-${stop}]`;
  853. };
  854. const toRegex = (start, end, options) => {
  855. if (Array.isArray(start)) {
  856. let wrap = options.wrap === true;
  857. let prefix = options.capture ? '' : '?:';
  858. return wrap ? `(${prefix}${start.join('|')})` : start.join('|');
  859. }
  860. return toRegexRange(start, end, options);
  861. };
  862. const rangeError = (...args) => {
  863. return new RangeError('Invalid range arguments: ' + util$1.inspect(...args));
  864. };
  865. const invalidRange = (start, end, options) => {
  866. if (options.strictRanges === true) throw rangeError([start, end]);
  867. return [];
  868. };
  869. const invalidStep = (step, options) => {
  870. if (options.strictRanges === true) {
  871. throw new TypeError(`Expected step "${step}" to be a number`);
  872. }
  873. return [];
  874. };
  875. const fillNumbers = (start, end, step = 1, options = {}) => {
  876. let a = Number(start);
  877. let b = Number(end);
  878. if (!Number.isInteger(a) || !Number.isInteger(b)) {
  879. if (options.strictRanges === true) throw rangeError([start, end]);
  880. return [];
  881. }
  882. // fix negative zero
  883. if (a === 0) a = 0;
  884. if (b === 0) b = 0;
  885. let descending = a > b;
  886. let startString = String(start);
  887. let endString = String(end);
  888. let stepString = String(step);
  889. step = Math.max(Math.abs(step), 1);
  890. let padded = zeros(startString) || zeros(endString) || zeros(stepString);
  891. let maxLen = padded ? Math.max(startString.length, endString.length, stepString.length) : 0;
  892. let toNumber = padded === false && stringify$3(start, end, options) === false;
  893. let format = options.transform || transform$1(toNumber);
  894. if (options.toRegex && step === 1) {
  895. return toRange(toMaxLen(start, maxLen), toMaxLen(end, maxLen), true, options);
  896. }
  897. let parts = { negatives: [], positives: [] };
  898. let push = num => parts[num < 0 ? 'negatives' : 'positives'].push(Math.abs(num));
  899. let range = [];
  900. let index = 0;
  901. while (descending ? a >= b : a <= b) {
  902. if (options.toRegex === true && step > 1) {
  903. push(a);
  904. } else {
  905. range.push(pad(format(a, index), maxLen, toNumber));
  906. }
  907. a = descending ? a - step : a + step;
  908. index++;
  909. }
  910. if (options.toRegex === true) {
  911. return step > 1
  912. ? toSequence(parts, options)
  913. : toRegex(range, null, { wrap: false, ...options });
  914. }
  915. return range;
  916. };
  917. const fillLetters = (start, end, step = 1, options = {}) => {
  918. if ((!isNumber(start) && start.length > 1) || (!isNumber(end) && end.length > 1)) {
  919. return invalidRange(start, end, options);
  920. }
  921. let format = options.transform || (val => String.fromCharCode(val));
  922. let a = `${start}`.charCodeAt(0);
  923. let b = `${end}`.charCodeAt(0);
  924. let descending = a > b;
  925. let min = Math.min(a, b);
  926. let max = Math.max(a, b);
  927. if (options.toRegex && step === 1) {
  928. return toRange(min, max, false, options);
  929. }
  930. let range = [];
  931. let index = 0;
  932. while (descending ? a >= b : a <= b) {
  933. range.push(format(a, index));
  934. a = descending ? a - step : a + step;
  935. index++;
  936. }
  937. if (options.toRegex === true) {
  938. return toRegex(range, null, { wrap: false, options });
  939. }
  940. return range;
  941. };
  942. const fill$2 = (start, end, step, options = {}) => {
  943. if (end == null && isValidValue(start)) {
  944. return [start];
  945. }
  946. if (!isValidValue(start) || !isValidValue(end)) {
  947. return invalidRange(start, end, options);
  948. }
  949. if (typeof step === 'function') {
  950. return fill$2(start, end, 1, { transform: step });
  951. }
  952. if (isObject$1(step)) {
  953. return fill$2(start, end, 0, step);
  954. }
  955. let opts = { ...options };
  956. if (opts.capture === true) opts.wrap = true;
  957. step = step || opts.step || 1;
  958. if (!isNumber(step)) {
  959. if (step != null && !isObject$1(step)) return invalidStep(step, opts);
  960. return fill$2(start, end, 1, step);
  961. }
  962. if (isNumber(start) && isNumber(end)) {
  963. return fillNumbers(start, end, step, opts);
  964. }
  965. return fillLetters(start, end, Math.max(Math.abs(step), 1), opts);
  966. };
  967. var fillRange = fill$2;
  968. const fill$1 = fillRange;
  969. const utils$h = utils$j;
  970. const compile$1 = (ast, options = {}) => {
  971. let walk = (node, parent = {}) => {
  972. let invalidBlock = utils$h.isInvalidBrace(parent);
  973. let invalidNode = node.invalid === true && options.escapeInvalid === true;
  974. let invalid = invalidBlock === true || invalidNode === true;
  975. let prefix = options.escapeInvalid === true ? '\\' : '';
  976. let output = '';
  977. if (node.isOpen === true) {
  978. return prefix + node.value;
  979. }
  980. if (node.isClose === true) {
  981. return prefix + node.value;
  982. }
  983. if (node.type === 'open') {
  984. return invalid ? (prefix + node.value) : '(';
  985. }
  986. if (node.type === 'close') {
  987. return invalid ? (prefix + node.value) : ')';
  988. }
  989. if (node.type === 'comma') {
  990. return node.prev.type === 'comma' ? '' : (invalid ? node.value : '|');
  991. }
  992. if (node.value) {
  993. return node.value;
  994. }
  995. if (node.nodes && node.ranges > 0) {
  996. let args = utils$h.reduce(node.nodes);
  997. let range = fill$1(...args, { ...options, wrap: false, toRegex: true });
  998. if (range.length !== 0) {
  999. return args.length > 1 && range.length > 1 ? `(${range})` : range;
  1000. }
  1001. }
  1002. if (node.nodes) {
  1003. for (let child of node.nodes) {
  1004. output += walk(child, node);
  1005. }
  1006. }
  1007. return output;
  1008. };
  1009. return walk(ast);
  1010. };
  1011. var compile_1 = compile$1;
  1012. const fill = fillRange;
  1013. const stringify$2 = stringify$4;
  1014. const utils$g = utils$j;
  1015. const append = (queue = '', stash = '', enclose = false) => {
  1016. let result = [];
  1017. queue = [].concat(queue);
  1018. stash = [].concat(stash);
  1019. if (!stash.length) return queue;
  1020. if (!queue.length) {
  1021. return enclose ? utils$g.flatten(stash).map(ele => `{${ele}}`) : stash;
  1022. }
  1023. for (let item of queue) {
  1024. if (Array.isArray(item)) {
  1025. for (let value of item) {
  1026. result.push(append(value, stash, enclose));
  1027. }
  1028. } else {
  1029. for (let ele of stash) {
  1030. if (enclose === true && typeof ele === 'string') ele = `{${ele}}`;
  1031. result.push(Array.isArray(ele) ? append(item, ele, enclose) : (item + ele));
  1032. }
  1033. }
  1034. }
  1035. return utils$g.flatten(result);
  1036. };
  1037. const expand$1 = (ast, options = {}) => {
  1038. let rangeLimit = options.rangeLimit === void 0 ? 1000 : options.rangeLimit;
  1039. let walk = (node, parent = {}) => {
  1040. node.queue = [];
  1041. let p = parent;
  1042. let q = parent.queue;
  1043. while (p.type !== 'brace' && p.type !== 'root' && p.parent) {
  1044. p = p.parent;
  1045. q = p.queue;
  1046. }
  1047. if (node.invalid || node.dollar) {
  1048. q.push(append(q.pop(), stringify$2(node, options)));
  1049. return;
  1050. }
  1051. if (node.type === 'brace' && node.invalid !== true && node.nodes.length === 2) {
  1052. q.push(append(q.pop(), ['{}']));
  1053. return;
  1054. }
  1055. if (node.nodes && node.ranges > 0) {
  1056. let args = utils$g.reduce(node.nodes);
  1057. if (utils$g.exceedsLimit(...args, options.step, rangeLimit)) {
  1058. throw new RangeError('expanded array length exceeds range limit. Use options.rangeLimit to increase or disable the limit.');
  1059. }
  1060. let range = fill(...args, options);
  1061. if (range.length === 0) {
  1062. range = stringify$2(node, options);
  1063. }
  1064. q.push(append(q.pop(), range));
  1065. node.nodes = [];
  1066. return;
  1067. }
  1068. let enclose = utils$g.encloseBrace(node);
  1069. let queue = node.queue;
  1070. let block = node;
  1071. while (block.type !== 'brace' && block.type !== 'root' && block.parent) {
  1072. block = block.parent;
  1073. queue = block.queue;
  1074. }
  1075. for (let i = 0; i < node.nodes.length; i++) {
  1076. let child = node.nodes[i];
  1077. if (child.type === 'comma' && node.type === 'brace') {
  1078. if (i === 1) queue.push('');
  1079. queue.push('');
  1080. continue;
  1081. }
  1082. if (child.type === 'close') {
  1083. q.push(append(q.pop(), queue, enclose));
  1084. continue;
  1085. }
  1086. if (child.value && child.type !== 'open') {
  1087. queue.push(append(queue.pop(), child.value));
  1088. continue;
  1089. }
  1090. if (child.nodes) {
  1091. walk(child, node);
  1092. }
  1093. }
  1094. return queue;
  1095. };
  1096. return utils$g.flatten(walk(ast));
  1097. };
  1098. var expand_1 = expand$1;
  1099. var constants$4 = {
  1100. MAX_LENGTH: 1024 * 64,
  1101. // Digits
  1102. CHAR_0: '0', /* 0 */
  1103. CHAR_9: '9', /* 9 */
  1104. // Alphabet chars.
  1105. CHAR_UPPERCASE_A: 'A', /* A */
  1106. CHAR_LOWERCASE_A: 'a', /* a */
  1107. CHAR_UPPERCASE_Z: 'Z', /* Z */
  1108. CHAR_LOWERCASE_Z: 'z', /* z */
  1109. CHAR_LEFT_PARENTHESES: '(', /* ( */
  1110. CHAR_RIGHT_PARENTHESES: ')', /* ) */
  1111. CHAR_ASTERISK: '*', /* * */
  1112. // Non-alphabetic chars.
  1113. CHAR_AMPERSAND: '&', /* & */
  1114. CHAR_AT: '@', /* @ */
  1115. CHAR_BACKSLASH: '\\', /* \ */
  1116. CHAR_BACKTICK: '`', /* ` */
  1117. CHAR_CARRIAGE_RETURN: '\r', /* \r */
  1118. CHAR_CIRCUMFLEX_ACCENT: '^', /* ^ */
  1119. CHAR_COLON: ':', /* : */
  1120. CHAR_COMMA: ',', /* , */
  1121. CHAR_DOLLAR: '$', /* . */
  1122. CHAR_DOT: '.', /* . */
  1123. CHAR_DOUBLE_QUOTE: '"', /* " */
  1124. CHAR_EQUAL: '=', /* = */
  1125. CHAR_EXCLAMATION_MARK: '!', /* ! */
  1126. CHAR_FORM_FEED: '\f', /* \f */
  1127. CHAR_FORWARD_SLASH: '/', /* / */
  1128. CHAR_HASH: '#', /* # */
  1129. CHAR_HYPHEN_MINUS: '-', /* - */
  1130. CHAR_LEFT_ANGLE_BRACKET: '<', /* < */
  1131. CHAR_LEFT_CURLY_BRACE: '{', /* { */
  1132. CHAR_LEFT_SQUARE_BRACKET: '[', /* [ */
  1133. CHAR_LINE_FEED: '\n', /* \n */
  1134. CHAR_NO_BREAK_SPACE: '\u00A0', /* \u00A0 */
  1135. CHAR_PERCENT: '%', /* % */
  1136. CHAR_PLUS: '+', /* + */
  1137. CHAR_QUESTION_MARK: '?', /* ? */
  1138. CHAR_RIGHT_ANGLE_BRACKET: '>', /* > */
  1139. CHAR_RIGHT_CURLY_BRACE: '}', /* } */
  1140. CHAR_RIGHT_SQUARE_BRACKET: ']', /* ] */
  1141. CHAR_SEMICOLON: ';', /* ; */
  1142. CHAR_SINGLE_QUOTE: '\'', /* ' */
  1143. CHAR_SPACE: ' ', /* */
  1144. CHAR_TAB: '\t', /* \t */
  1145. CHAR_UNDERSCORE: '_', /* _ */
  1146. CHAR_VERTICAL_LINE: '|', /* | */
  1147. CHAR_ZERO_WIDTH_NOBREAK_SPACE: '\uFEFF' /* \uFEFF */
  1148. };
  1149. const stringify$1 = stringify$4;
  1150. /**
  1151. * Constants
  1152. */
  1153. const {
  1154. MAX_LENGTH: MAX_LENGTH$1,
  1155. CHAR_BACKSLASH, /* \ */
  1156. CHAR_BACKTICK, /* ` */
  1157. CHAR_COMMA: CHAR_COMMA$1, /* , */
  1158. CHAR_DOT: CHAR_DOT$1, /* . */
  1159. CHAR_LEFT_PARENTHESES: CHAR_LEFT_PARENTHESES$1, /* ( */
  1160. CHAR_RIGHT_PARENTHESES: CHAR_RIGHT_PARENTHESES$1, /* ) */
  1161. CHAR_LEFT_CURLY_BRACE: CHAR_LEFT_CURLY_BRACE$1, /* { */
  1162. CHAR_RIGHT_CURLY_BRACE: CHAR_RIGHT_CURLY_BRACE$1, /* } */
  1163. CHAR_LEFT_SQUARE_BRACKET: CHAR_LEFT_SQUARE_BRACKET$1, /* [ */
  1164. CHAR_RIGHT_SQUARE_BRACKET: CHAR_RIGHT_SQUARE_BRACKET$1, /* ] */
  1165. CHAR_DOUBLE_QUOTE, /* " */
  1166. CHAR_SINGLE_QUOTE, /* ' */
  1167. CHAR_NO_BREAK_SPACE,
  1168. CHAR_ZERO_WIDTH_NOBREAK_SPACE
  1169. } = constants$4;
  1170. /**
  1171. * parse
  1172. */
  1173. const parse$3 = (input, options = {}) => {
  1174. if (typeof input !== 'string') {
  1175. throw new TypeError('Expected a string');
  1176. }
  1177. let opts = options || {};
  1178. let max = typeof opts.maxLength === 'number' ? Math.min(MAX_LENGTH$1, opts.maxLength) : MAX_LENGTH$1;
  1179. if (input.length > max) {
  1180. throw new SyntaxError(`Input length (${input.length}), exceeds max characters (${max})`);
  1181. }
  1182. let ast = { type: 'root', input, nodes: [] };
  1183. let stack = [ast];
  1184. let block = ast;
  1185. let prev = ast;
  1186. let brackets = 0;
  1187. let length = input.length;
  1188. let index = 0;
  1189. let depth = 0;
  1190. let value;
  1191. /**
  1192. * Helpers
  1193. */
  1194. const advance = () => input[index++];
  1195. const push = node => {
  1196. if (node.type === 'text' && prev.type === 'dot') {
  1197. prev.type = 'text';
  1198. }
  1199. if (prev && prev.type === 'text' && node.type === 'text') {
  1200. prev.value += node.value;
  1201. return;
  1202. }
  1203. block.nodes.push(node);
  1204. node.parent = block;
  1205. node.prev = prev;
  1206. prev = node;
  1207. return node;
  1208. };
  1209. push({ type: 'bos' });
  1210. while (index < length) {
  1211. block = stack[stack.length - 1];
  1212. value = advance();
  1213. /**
  1214. * Invalid chars
  1215. */
  1216. if (value === CHAR_ZERO_WIDTH_NOBREAK_SPACE || value === CHAR_NO_BREAK_SPACE) {
  1217. continue;
  1218. }
  1219. /**
  1220. * Escaped chars
  1221. */
  1222. if (value === CHAR_BACKSLASH) {
  1223. push({ type: 'text', value: (options.keepEscaping ? value : '') + advance() });
  1224. continue;
  1225. }
  1226. /**
  1227. * Right square bracket (literal): ']'
  1228. */
  1229. if (value === CHAR_RIGHT_SQUARE_BRACKET$1) {
  1230. push({ type: 'text', value: '\\' + value });
  1231. continue;
  1232. }
  1233. /**
  1234. * Left square bracket: '['
  1235. */
  1236. if (value === CHAR_LEFT_SQUARE_BRACKET$1) {
  1237. brackets++;
  1238. let next;
  1239. while (index < length && (next = advance())) {
  1240. value += next;
  1241. if (next === CHAR_LEFT_SQUARE_BRACKET$1) {
  1242. brackets++;
  1243. continue;
  1244. }
  1245. if (next === CHAR_BACKSLASH) {
  1246. value += advance();
  1247. continue;
  1248. }
  1249. if (next === CHAR_RIGHT_SQUARE_BRACKET$1) {
  1250. brackets--;
  1251. if (brackets === 0) {
  1252. break;
  1253. }
  1254. }
  1255. }
  1256. push({ type: 'text', value });
  1257. continue;
  1258. }
  1259. /**
  1260. * Parentheses
  1261. */
  1262. if (value === CHAR_LEFT_PARENTHESES$1) {
  1263. block = push({ type: 'paren', nodes: [] });
  1264. stack.push(block);
  1265. push({ type: 'text', value });
  1266. continue;
  1267. }
  1268. if (value === CHAR_RIGHT_PARENTHESES$1) {
  1269. if (block.type !== 'paren') {
  1270. push({ type: 'text', value });
  1271. continue;
  1272. }
  1273. block = stack.pop();
  1274. push({ type: 'text', value });
  1275. block = stack[stack.length - 1];
  1276. continue;
  1277. }
  1278. /**
  1279. * Quotes: '|"|`
  1280. */
  1281. if (value === CHAR_DOUBLE_QUOTE || value === CHAR_SINGLE_QUOTE || value === CHAR_BACKTICK) {
  1282. let open = value;
  1283. let next;
  1284. if (options.keepQuotes !== true) {
  1285. value = '';
  1286. }
  1287. while (index < length && (next = advance())) {
  1288. if (next === CHAR_BACKSLASH) {
  1289. value += next + advance();
  1290. continue;
  1291. }
  1292. if (next === open) {
  1293. if (options.keepQuotes === true) value += next;
  1294. break;
  1295. }
  1296. value += next;
  1297. }
  1298. push({ type: 'text', value });
  1299. continue;
  1300. }
  1301. /**
  1302. * Left curly brace: '{'
  1303. */
  1304. if (value === CHAR_LEFT_CURLY_BRACE$1) {
  1305. depth++;
  1306. let dollar = prev.value && prev.value.slice(-1) === '$' || block.dollar === true;
  1307. let brace = {
  1308. type: 'brace',
  1309. open: true,
  1310. close: false,
  1311. dollar,
  1312. depth,
  1313. commas: 0,
  1314. ranges: 0,
  1315. nodes: []
  1316. };
  1317. block = push(brace);
  1318. stack.push(block);
  1319. push({ type: 'open', value });
  1320. continue;
  1321. }
  1322. /**
  1323. * Right curly brace: '}'
  1324. */
  1325. if (value === CHAR_RIGHT_CURLY_BRACE$1) {
  1326. if (block.type !== 'brace') {
  1327. push({ type: 'text', value });
  1328. continue;
  1329. }
  1330. let type = 'close';
  1331. block = stack.pop();
  1332. block.close = true;
  1333. push({ type, value });
  1334. depth--;
  1335. block = stack[stack.length - 1];
  1336. continue;
  1337. }
  1338. /**
  1339. * Comma: ','
  1340. */
  1341. if (value === CHAR_COMMA$1 && depth > 0) {
  1342. if (block.ranges > 0) {
  1343. block.ranges = 0;
  1344. let open = block.nodes.shift();
  1345. block.nodes = [open, { type: 'text', value: stringify$1(block) }];
  1346. }
  1347. push({ type: 'comma', value });
  1348. block.commas++;
  1349. continue;
  1350. }
  1351. /**
  1352. * Dot: '.'
  1353. */
  1354. if (value === CHAR_DOT$1 && depth > 0 && block.commas === 0) {
  1355. let siblings = block.nodes;
  1356. if (depth === 0 || siblings.length === 0) {
  1357. push({ type: 'text', value });
  1358. continue;
  1359. }
  1360. if (prev.type === 'dot') {
  1361. block.range = [];
  1362. prev.value += value;
  1363. prev.type = 'range';
  1364. if (block.nodes.length !== 3 && block.nodes.length !== 5) {
  1365. block.invalid = true;
  1366. block.ranges = 0;
  1367. prev.type = 'text';
  1368. continue;
  1369. }
  1370. block.ranges++;
  1371. block.args = [];
  1372. continue;
  1373. }
  1374. if (prev.type === 'range') {
  1375. siblings.pop();
  1376. let before = siblings[siblings.length - 1];
  1377. before.value += prev.value + value;
  1378. prev = before;
  1379. block.ranges--;
  1380. continue;
  1381. }
  1382. push({ type: 'dot', value });
  1383. continue;
  1384. }
  1385. /**
  1386. * Text
  1387. */
  1388. push({ type: 'text', value });
  1389. }
  1390. // Mark imbalanced braces and brackets as invalid
  1391. do {
  1392. block = stack.pop();
  1393. if (block.type !== 'root') {
  1394. block.nodes.forEach(node => {
  1395. if (!node.nodes) {
  1396. if (node.type === 'open') node.isOpen = true;
  1397. if (node.type === 'close') node.isClose = true;
  1398. if (!node.nodes) node.type = 'text';
  1399. node.invalid = true;
  1400. }
  1401. });
  1402. // get the location of the block on parent.nodes (block's siblings)
  1403. let parent = stack[stack.length - 1];
  1404. let index = parent.nodes.indexOf(block);
  1405. // replace the (invalid) block with it's nodes
  1406. parent.nodes.splice(index, 1, ...block.nodes);
  1407. }
  1408. } while (stack.length > 0);
  1409. push({ type: 'eos' });
  1410. return ast;
  1411. };
  1412. var parse_1$1 = parse$3;
  1413. const stringify = stringify$4;
  1414. const compile = compile_1;
  1415. const expand = expand_1;
  1416. const parse$2 = parse_1$1;
  1417. /**
  1418. * Expand the given pattern or create a regex-compatible string.
  1419. *
  1420. * ```js
  1421. * const braces = require('braces');
  1422. * console.log(braces('{a,b,c}', { compile: true })); //=> ['(a|b|c)']
  1423. * console.log(braces('{a,b,c}')); //=> ['a', 'b', 'c']
  1424. * ```
  1425. * @param {String} `str`
  1426. * @param {Object} `options`
  1427. * @return {String}
  1428. * @api public
  1429. */
  1430. const braces$1 = (input, options = {}) => {
  1431. let output = [];
  1432. if (Array.isArray(input)) {
  1433. for (let pattern of input) {
  1434. let result = braces$1.create(pattern, options);
  1435. if (Array.isArray(result)) {
  1436. output.push(...result);
  1437. } else {
  1438. output.push(result);
  1439. }
  1440. }
  1441. } else {
  1442. output = [].concat(braces$1.create(input, options));
  1443. }
  1444. if (options && options.expand === true && options.nodupes === true) {
  1445. output = [...new Set(output)];
  1446. }
  1447. return output;
  1448. };
  1449. /**
  1450. * Parse the given `str` with the given `options`.
  1451. *
  1452. * ```js
  1453. * // braces.parse(pattern, [, options]);
  1454. * const ast = braces.parse('a/{b,c}/d');
  1455. * console.log(ast);
  1456. * ```
  1457. * @param {String} pattern Brace pattern to parse
  1458. * @param {Object} options
  1459. * @return {Object} Returns an AST
  1460. * @api public
  1461. */
  1462. braces$1.parse = (input, options = {}) => parse$2(input, options);
  1463. /**
  1464. * Creates a braces string from an AST, or an AST node.
  1465. *
  1466. * ```js
  1467. * const braces = require('braces');
  1468. * let ast = braces.parse('foo/{a,b}/bar');
  1469. * console.log(stringify(ast.nodes[2])); //=> '{a,b}'
  1470. * ```
  1471. * @param {String} `input` Brace pattern or AST.
  1472. * @param {Object} `options`
  1473. * @return {Array} Returns an array of expanded values.
  1474. * @api public
  1475. */
  1476. braces$1.stringify = (input, options = {}) => {
  1477. if (typeof input === 'string') {
  1478. return stringify(braces$1.parse(input, options), options);
  1479. }
  1480. return stringify(input, options);
  1481. };
  1482. /**
  1483. * Compiles a brace pattern into a regex-compatible, optimized string.
  1484. * This method is called by the main [braces](#braces) function by default.
  1485. *
  1486. * ```js
  1487. * const braces = require('braces');
  1488. * console.log(braces.compile('a/{b,c}/d'));
  1489. * //=> ['a/(b|c)/d']
  1490. * ```
  1491. * @param {String} `input` Brace pattern or AST.
  1492. * @param {Object} `options`
  1493. * @return {Array} Returns an array of expanded values.
  1494. * @api public
  1495. */
  1496. braces$1.compile = (input, options = {}) => {
  1497. if (typeof input === 'string') {
  1498. input = braces$1.parse(input, options);
  1499. }
  1500. return compile(input, options);
  1501. };
  1502. /**
  1503. * Expands a brace pattern into an array. This method is called by the
  1504. * main [braces](#braces) function when `options.expand` is true. Before
  1505. * using this method it's recommended that you read the [performance notes](#performance))
  1506. * and advantages of using [.compile](#compile) instead.
  1507. *
  1508. * ```js
  1509. * const braces = require('braces');
  1510. * console.log(braces.expand('a/{b,c}/d'));
  1511. * //=> ['a/b/d', 'a/c/d'];
  1512. * ```
  1513. * @param {String} `pattern` Brace pattern
  1514. * @param {Object} `options`
  1515. * @return {Array} Returns an array of expanded values.
  1516. * @api public
  1517. */
  1518. braces$1.expand = (input, options = {}) => {
  1519. if (typeof input === 'string') {
  1520. input = braces$1.parse(input, options);
  1521. }
  1522. let result = expand(input, options);
  1523. // filter out empty strings if specified
  1524. if (options.noempty === true) {
  1525. result = result.filter(Boolean);
  1526. }
  1527. // filter out duplicates if specified
  1528. if (options.nodupes === true) {
  1529. result = [...new Set(result)];
  1530. }
  1531. return result;
  1532. };
  1533. /**
  1534. * Processes a brace pattern and returns either an expanded array
  1535. * (if `options.expand` is true), a highly optimized regex-compatible string.
  1536. * This method is called by the main [braces](#braces) function.
  1537. *
  1538. * ```js
  1539. * const braces = require('braces');
  1540. * console.log(braces.create('user-{200..300}/project-{a,b,c}-{1..10}'))
  1541. * //=> 'user-(20[0-9]|2[1-9][0-9]|300)/project-(a|b|c)-([1-9]|10)'
  1542. * ```
  1543. * @param {String} `pattern` Brace pattern
  1544. * @param {Object} `options`
  1545. * @return {Array} Returns an array of expanded values.
  1546. * @api public
  1547. */
  1548. braces$1.create = (input, options = {}) => {
  1549. if (input === '' || input.length < 3) {
  1550. return [input];
  1551. }
  1552. return options.expand !== true
  1553. ? braces$1.compile(input, options)
  1554. : braces$1.expand(input, options);
  1555. };
  1556. /**
  1557. * Expose "braces"
  1558. */
  1559. var braces_1 = braces$1;
  1560. var picomatch$2 = {exports: {}};
  1561. var utils$f = {};
  1562. const path$7 = path$a;
  1563. const WIN_SLASH = '\\\\/';
  1564. const WIN_NO_SLASH = `[^${WIN_SLASH}]`;
  1565. /**
  1566. * Posix glob regex
  1567. */
  1568. const DOT_LITERAL = '\\.';
  1569. const PLUS_LITERAL = '\\+';
  1570. const QMARK_LITERAL = '\\?';
  1571. const SLASH_LITERAL = '\\/';
  1572. const ONE_CHAR = '(?=.)';
  1573. const QMARK = '[^/]';
  1574. const END_ANCHOR = `(?:${SLASH_LITERAL}|$)`;
  1575. const START_ANCHOR = `(?:^|${SLASH_LITERAL})`;
  1576. const DOTS_SLASH = `${DOT_LITERAL}{1,2}${END_ANCHOR}`;
  1577. const NO_DOT = `(?!${DOT_LITERAL})`;
  1578. const NO_DOTS = `(?!${START_ANCHOR}${DOTS_SLASH})`;
  1579. const NO_DOT_SLASH = `(?!${DOT_LITERAL}{0,1}${END_ANCHOR})`;
  1580. const NO_DOTS_SLASH = `(?!${DOTS_SLASH})`;
  1581. const QMARK_NO_DOT = `[^.${SLASH_LITERAL}]`;
  1582. const STAR = `${QMARK}*?`;
  1583. const POSIX_CHARS = {
  1584. DOT_LITERAL,
  1585. PLUS_LITERAL,
  1586. QMARK_LITERAL,
  1587. SLASH_LITERAL,
  1588. ONE_CHAR,
  1589. QMARK,
  1590. END_ANCHOR,
  1591. DOTS_SLASH,
  1592. NO_DOT,
  1593. NO_DOTS,
  1594. NO_DOT_SLASH,
  1595. NO_DOTS_SLASH,
  1596. QMARK_NO_DOT,
  1597. STAR,
  1598. START_ANCHOR
  1599. };
  1600. /**
  1601. * Windows glob regex
  1602. */
  1603. const WINDOWS_CHARS = {
  1604. ...POSIX_CHARS,
  1605. SLASH_LITERAL: `[${WIN_SLASH}]`,
  1606. QMARK: WIN_NO_SLASH,
  1607. STAR: `${WIN_NO_SLASH}*?`,
  1608. DOTS_SLASH: `${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$)`,
  1609. NO_DOT: `(?!${DOT_LITERAL})`,
  1610. NO_DOTS: `(?!(?:^|[${WIN_SLASH}])${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$))`,
  1611. NO_DOT_SLASH: `(?!${DOT_LITERAL}{0,1}(?:[${WIN_SLASH}]|$))`,
  1612. NO_DOTS_SLASH: `(?!${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$))`,
  1613. QMARK_NO_DOT: `[^.${WIN_SLASH}]`,
  1614. START_ANCHOR: `(?:^|[${WIN_SLASH}])`,
  1615. END_ANCHOR: `(?:[${WIN_SLASH}]|$)`
  1616. };
  1617. /**
  1618. * POSIX Bracket Regex
  1619. */
  1620. const POSIX_REGEX_SOURCE$1 = {
  1621. alnum: 'a-zA-Z0-9',
  1622. alpha: 'a-zA-Z',
  1623. ascii: '\\x00-\\x7F',
  1624. blank: ' \\t',
  1625. cntrl: '\\x00-\\x1F\\x7F',
  1626. digit: '0-9',
  1627. graph: '\\x21-\\x7E',
  1628. lower: 'a-z',
  1629. print: '\\x20-\\x7E ',
  1630. punct: '\\-!"#$%&\'()\\*+,./:;<=>?@[\\]^_`{|}~',
  1631. space: ' \\t\\r\\n\\v\\f',
  1632. upper: 'A-Z',
  1633. word: 'A-Za-z0-9_',
  1634. xdigit: 'A-Fa-f0-9'
  1635. };
  1636. var constants$3 = {
  1637. MAX_LENGTH: 1024 * 64,
  1638. POSIX_REGEX_SOURCE: POSIX_REGEX_SOURCE$1,
  1639. // regular expressions
  1640. REGEX_BACKSLASH: /\\(?![*+?^${}(|)[\]])/g,
  1641. REGEX_NON_SPECIAL_CHARS: /^[^@![\].,$*+?^{}()|\\/]+/,
  1642. REGEX_SPECIAL_CHARS: /[-*+?.^${}(|)[\]]/,
  1643. REGEX_SPECIAL_CHARS_BACKREF: /(\\?)((\W)(\3*))/g,
  1644. REGEX_SPECIAL_CHARS_GLOBAL: /([-*+?.^${}(|)[\]])/g,
  1645. REGEX_REMOVE_BACKSLASH: /(?:\[.*?[^\\]\]|\\(?=.))/g,
  1646. // Replace globs with equivalent patterns to reduce parsing time.
  1647. REPLACEMENTS: {
  1648. '***': '*',
  1649. '**/**': '**',
  1650. '**/**/**': '**'
  1651. },
  1652. // Digits
  1653. CHAR_0: 48, /* 0 */
  1654. CHAR_9: 57, /* 9 */
  1655. // Alphabet chars.
  1656. CHAR_UPPERCASE_A: 65, /* A */
  1657. CHAR_LOWERCASE_A: 97, /* a */
  1658. CHAR_UPPERCASE_Z: 90, /* Z */
  1659. CHAR_LOWERCASE_Z: 122, /* z */
  1660. CHAR_LEFT_PARENTHESES: 40, /* ( */
  1661. CHAR_RIGHT_PARENTHESES: 41, /* ) */
  1662. CHAR_ASTERISK: 42, /* * */
  1663. // Non-alphabetic chars.
  1664. CHAR_AMPERSAND: 38, /* & */
  1665. CHAR_AT: 64, /* @ */
  1666. CHAR_BACKWARD_SLASH: 92, /* \ */
  1667. CHAR_CARRIAGE_RETURN: 13, /* \r */
  1668. CHAR_CIRCUMFLEX_ACCENT: 94, /* ^ */
  1669. CHAR_COLON: 58, /* : */
  1670. CHAR_COMMA: 44, /* , */
  1671. CHAR_DOT: 46, /* . */
  1672. CHAR_DOUBLE_QUOTE: 34, /* " */
  1673. CHAR_EQUAL: 61, /* = */
  1674. CHAR_EXCLAMATION_MARK: 33, /* ! */
  1675. CHAR_FORM_FEED: 12, /* \f */
  1676. CHAR_FORWARD_SLASH: 47, /* / */
  1677. CHAR_GRAVE_ACCENT: 96, /* ` */
  1678. CHAR_HASH: 35, /* # */
  1679. CHAR_HYPHEN_MINUS: 45, /* - */
  1680. CHAR_LEFT_ANGLE_BRACKET: 60, /* < */
  1681. CHAR_LEFT_CURLY_BRACE: 123, /* { */
  1682. CHAR_LEFT_SQUARE_BRACKET: 91, /* [ */
  1683. CHAR_LINE_FEED: 10, /* \n */
  1684. CHAR_NO_BREAK_SPACE: 160, /* \u00A0 */
  1685. CHAR_PERCENT: 37, /* % */
  1686. CHAR_PLUS: 43, /* + */
  1687. CHAR_QUESTION_MARK: 63, /* ? */
  1688. CHAR_RIGHT_ANGLE_BRACKET: 62, /* > */
  1689. CHAR_RIGHT_CURLY_BRACE: 125, /* } */
  1690. CHAR_RIGHT_SQUARE_BRACKET: 93, /* ] */
  1691. CHAR_SEMICOLON: 59, /* ; */
  1692. CHAR_SINGLE_QUOTE: 39, /* ' */
  1693. CHAR_SPACE: 32, /* */
  1694. CHAR_TAB: 9, /* \t */
  1695. CHAR_UNDERSCORE: 95, /* _ */
  1696. CHAR_VERTICAL_LINE: 124, /* | */
  1697. CHAR_ZERO_WIDTH_NOBREAK_SPACE: 65279, /* \uFEFF */
  1698. SEP: path$7.sep,
  1699. /**
  1700. * Create EXTGLOB_CHARS
  1701. */
  1702. extglobChars(chars) {
  1703. return {
  1704. '!': { type: 'negate', open: '(?:(?!(?:', close: `))${chars.STAR})` },
  1705. '?': { type: 'qmark', open: '(?:', close: ')?' },
  1706. '+': { type: 'plus', open: '(?:', close: ')+' },
  1707. '*': { type: 'star', open: '(?:', close: ')*' },
  1708. '@': { type: 'at', open: '(?:', close: ')' }
  1709. };
  1710. },
  1711. /**
  1712. * Create GLOB_CHARS
  1713. */
  1714. globChars(win32) {
  1715. return win32 === true ? WINDOWS_CHARS : POSIX_CHARS;
  1716. }
  1717. };
  1718. (function (exports) {
  1719. const path = path$a;
  1720. const win32 = process.platform === 'win32';
  1721. const {
  1722. REGEX_BACKSLASH,
  1723. REGEX_REMOVE_BACKSLASH,
  1724. REGEX_SPECIAL_CHARS,
  1725. REGEX_SPECIAL_CHARS_GLOBAL
  1726. } = constants$3;
  1727. exports.isObject = val => val !== null && typeof val === 'object' && !Array.isArray(val);
  1728. exports.hasRegexChars = str => REGEX_SPECIAL_CHARS.test(str);
  1729. exports.isRegexChar = str => str.length === 1 && exports.hasRegexChars(str);
  1730. exports.escapeRegex = str => str.replace(REGEX_SPECIAL_CHARS_GLOBAL, '\\$1');
  1731. exports.toPosixSlashes = str => str.replace(REGEX_BACKSLASH, '/');
  1732. exports.removeBackslashes = str => {
  1733. return str.replace(REGEX_REMOVE_BACKSLASH, match => {
  1734. return match === '\\' ? '' : match;
  1735. });
  1736. };
  1737. exports.supportsLookbehinds = () => {
  1738. const segs = process.version.slice(1).split('.').map(Number);
  1739. if (segs.length === 3 && segs[0] >= 9 || (segs[0] === 8 && segs[1] >= 10)) {
  1740. return true;
  1741. }
  1742. return false;
  1743. };
  1744. exports.isWindows = options => {
  1745. if (options && typeof options.windows === 'boolean') {
  1746. return options.windows;
  1747. }
  1748. return win32 === true || path.sep === '\\';
  1749. };
  1750. exports.escapeLast = (input, char, lastIdx) => {
  1751. const idx = input.lastIndexOf(char, lastIdx);
  1752. if (idx === -1) return input;
  1753. if (input[idx - 1] === '\\') return exports.escapeLast(input, char, idx - 1);
  1754. return `${input.slice(0, idx)}\\${input.slice(idx)}`;
  1755. };
  1756. exports.removePrefix = (input, state = {}) => {
  1757. let output = input;
  1758. if (output.startsWith('./')) {
  1759. output = output.slice(2);
  1760. state.prefix = './';
  1761. }
  1762. return output;
  1763. };
  1764. exports.wrapOutput = (input, state = {}, options = {}) => {
  1765. const prepend = options.contains ? '' : '^';
  1766. const append = options.contains ? '' : '$';
  1767. let output = `${prepend}(?:${input})${append}`;
  1768. if (state.negated === true) {
  1769. output = `(?:^(?!${output}).*$)`;
  1770. }
  1771. return output;
  1772. };
  1773. } (utils$f));
  1774. const utils$e = utils$f;
  1775. const {
  1776. CHAR_ASTERISK, /* * */
  1777. CHAR_AT, /* @ */
  1778. CHAR_BACKWARD_SLASH, /* \ */
  1779. CHAR_COMMA, /* , */
  1780. CHAR_DOT, /* . */
  1781. CHAR_EXCLAMATION_MARK, /* ! */
  1782. CHAR_FORWARD_SLASH, /* / */
  1783. CHAR_LEFT_CURLY_BRACE, /* { */
  1784. CHAR_LEFT_PARENTHESES, /* ( */
  1785. CHAR_LEFT_SQUARE_BRACKET, /* [ */
  1786. CHAR_PLUS, /* + */
  1787. CHAR_QUESTION_MARK, /* ? */
  1788. CHAR_RIGHT_CURLY_BRACE, /* } */
  1789. CHAR_RIGHT_PARENTHESES, /* ) */
  1790. CHAR_RIGHT_SQUARE_BRACKET /* ] */
  1791. } = constants$3;
  1792. const isPathSeparator = code => {
  1793. return code === CHAR_FORWARD_SLASH || code === CHAR_BACKWARD_SLASH;
  1794. };
  1795. const depth = token => {
  1796. if (token.isPrefix !== true) {
  1797. token.depth = token.isGlobstar ? Infinity : 1;
  1798. }
  1799. };
  1800. /**
  1801. * Quickly scans a glob pattern and returns an object with a handful of
  1802. * useful properties, like `isGlob`, `path` (the leading non-glob, if it exists),
  1803. * `glob` (the actual pattern), `negated` (true if the path starts with `!` but not
  1804. * with `!(`) and `negatedExtglob` (true if the path starts with `!(`).
  1805. *
  1806. * ```js
  1807. * const pm = require('picomatch');
  1808. * console.log(pm.scan('foo/bar/*.js'));
  1809. * { isGlob: true, input: 'foo/bar/*.js', base: 'foo/bar', glob: '*.js' }
  1810. * ```
  1811. * @param {String} `str`
  1812. * @param {Object} `options`
  1813. * @return {Object} Returns an object with tokens and regex source string.
  1814. * @api public
  1815. */
  1816. const scan$1 = (input, options) => {
  1817. const opts = options || {};
  1818. const length = input.length - 1;
  1819. const scanToEnd = opts.parts === true || opts.scanToEnd === true;
  1820. const slashes = [];
  1821. const tokens = [];
  1822. const parts = [];
  1823. let str = input;
  1824. let index = -1;
  1825. let start = 0;
  1826. let lastIndex = 0;
  1827. let isBrace = false;
  1828. let isBracket = false;
  1829. let isGlob = false;
  1830. let isExtglob = false;
  1831. let isGlobstar = false;
  1832. let braceEscaped = false;
  1833. let backslashes = false;
  1834. let negated = false;
  1835. let negatedExtglob = false;
  1836. let finished = false;
  1837. let braces = 0;
  1838. let prev;
  1839. let code;
  1840. let token = { value: '', depth: 0, isGlob: false };
  1841. const eos = () => index >= length;
  1842. const peek = () => str.charCodeAt(index + 1);
  1843. const advance = () => {
  1844. prev = code;
  1845. return str.charCodeAt(++index);
  1846. };
  1847. while (index < length) {
  1848. code = advance();
  1849. let next;
  1850. if (code === CHAR_BACKWARD_SLASH) {
  1851. backslashes = token.backslashes = true;
  1852. code = advance();
  1853. if (code === CHAR_LEFT_CURLY_BRACE) {
  1854. braceEscaped = true;
  1855. }
  1856. continue;
  1857. }
  1858. if (braceEscaped === true || code === CHAR_LEFT_CURLY_BRACE) {
  1859. braces++;
  1860. while (eos() !== true && (code = advance())) {
  1861. if (code === CHAR_BACKWARD_SLASH) {
  1862. backslashes = token.backslashes = true;
  1863. advance();
  1864. continue;
  1865. }
  1866. if (code === CHAR_LEFT_CURLY_BRACE) {
  1867. braces++;
  1868. continue;
  1869. }
  1870. if (braceEscaped !== true && code === CHAR_DOT && (code = advance()) === CHAR_DOT) {
  1871. isBrace = token.isBrace = true;
  1872. isGlob = token.isGlob = true;
  1873. finished = true;
  1874. if (scanToEnd === true) {
  1875. continue;
  1876. }
  1877. break;
  1878. }
  1879. if (braceEscaped !== true && code === CHAR_COMMA) {
  1880. isBrace = token.isBrace = true;
  1881. isGlob = token.isGlob = true;
  1882. finished = true;
  1883. if (scanToEnd === true) {
  1884. continue;
  1885. }
  1886. break;
  1887. }
  1888. if (code === CHAR_RIGHT_CURLY_BRACE) {
  1889. braces--;
  1890. if (braces === 0) {
  1891. braceEscaped = false;
  1892. isBrace = token.isBrace = true;
  1893. finished = true;
  1894. break;
  1895. }
  1896. }
  1897. }
  1898. if (scanToEnd === true) {
  1899. continue;
  1900. }
  1901. break;
  1902. }
  1903. if (code === CHAR_FORWARD_SLASH) {
  1904. slashes.push(index);
  1905. tokens.push(token);
  1906. token = { value: '', depth: 0, isGlob: false };
  1907. if (finished === true) continue;
  1908. if (prev === CHAR_DOT && index === (start + 1)) {
  1909. start += 2;
  1910. continue;
  1911. }
  1912. lastIndex = index + 1;
  1913. continue;
  1914. }
  1915. if (opts.noext !== true) {
  1916. const isExtglobChar = code === CHAR_PLUS
  1917. || code === CHAR_AT
  1918. || code === CHAR_ASTERISK
  1919. || code === CHAR_QUESTION_MARK
  1920. || code === CHAR_EXCLAMATION_MARK;
  1921. if (isExtglobChar === true && peek() === CHAR_LEFT_PARENTHESES) {
  1922. isGlob = token.isGlob = true;
  1923. isExtglob = token.isExtglob = true;
  1924. finished = true;
  1925. if (code === CHAR_EXCLAMATION_MARK && index === start) {
  1926. negatedExtglob = true;
  1927. }
  1928. if (scanToEnd === true) {
  1929. while (eos() !== true && (code = advance())) {
  1930. if (code === CHAR_BACKWARD_SLASH) {
  1931. backslashes = token.backslashes = true;
  1932. code = advance();
  1933. continue;
  1934. }
  1935. if (code === CHAR_RIGHT_PARENTHESES) {
  1936. isGlob = token.isGlob = true;
  1937. finished = true;
  1938. break;
  1939. }
  1940. }
  1941. continue;
  1942. }
  1943. break;
  1944. }
  1945. }
  1946. if (code === CHAR_ASTERISK) {
  1947. if (prev === CHAR_ASTERISK) isGlobstar = token.isGlobstar = true;
  1948. isGlob = token.isGlob = true;
  1949. finished = true;
  1950. if (scanToEnd === true) {
  1951. continue;
  1952. }
  1953. break;
  1954. }
  1955. if (code === CHAR_QUESTION_MARK) {
  1956. isGlob = token.isGlob = true;
  1957. finished = true;
  1958. if (scanToEnd === true) {
  1959. continue;
  1960. }
  1961. break;
  1962. }
  1963. if (code === CHAR_LEFT_SQUARE_BRACKET) {
  1964. while (eos() !== true && (next = advance())) {
  1965. if (next === CHAR_BACKWARD_SLASH) {
  1966. backslashes = token.backslashes = true;
  1967. advance();
  1968. continue;
  1969. }
  1970. if (next === CHAR_RIGHT_SQUARE_BRACKET) {
  1971. isBracket = token.isBracket = true;
  1972. isGlob = token.isGlob = true;
  1973. finished = true;
  1974. break;
  1975. }
  1976. }
  1977. if (scanToEnd === true) {
  1978. continue;
  1979. }
  1980. break;
  1981. }
  1982. if (opts.nonegate !== true && code === CHAR_EXCLAMATION_MARK && index === start) {
  1983. negated = token.negated = true;
  1984. start++;
  1985. continue;
  1986. }
  1987. if (opts.noparen !== true && code === CHAR_LEFT_PARENTHESES) {
  1988. isGlob = token.isGlob = true;
  1989. if (scanToEnd === true) {
  1990. while (eos() !== true && (code = advance())) {
  1991. if (code === CHAR_LEFT_PARENTHESES) {
  1992. backslashes = token.backslashes = true;
  1993. code = advance();
  1994. continue;
  1995. }
  1996. if (code === CHAR_RIGHT_PARENTHESES) {
  1997. finished = true;
  1998. break;
  1999. }
  2000. }
  2001. continue;
  2002. }
  2003. break;
  2004. }
  2005. if (isGlob === true) {
  2006. finished = true;
  2007. if (scanToEnd === true) {
  2008. continue;
  2009. }
  2010. break;
  2011. }
  2012. }
  2013. if (opts.noext === true) {
  2014. isExtglob = false;
  2015. isGlob = false;
  2016. }
  2017. let base = str;
  2018. let prefix = '';
  2019. let glob = '';
  2020. if (start > 0) {
  2021. prefix = str.slice(0, start);
  2022. str = str.slice(start);
  2023. lastIndex -= start;
  2024. }
  2025. if (base && isGlob === true && lastIndex > 0) {
  2026. base = str.slice(0, lastIndex);
  2027. glob = str.slice(lastIndex);
  2028. } else if (isGlob === true) {
  2029. base = '';
  2030. glob = str;
  2031. } else {
  2032. base = str;
  2033. }
  2034. if (base && base !== '' && base !== '/' && base !== str) {
  2035. if (isPathSeparator(base.charCodeAt(base.length - 1))) {
  2036. base = base.slice(0, -1);
  2037. }
  2038. }
  2039. if (opts.unescape === true) {
  2040. if (glob) glob = utils$e.removeBackslashes(glob);
  2041. if (base && backslashes === true) {
  2042. base = utils$e.removeBackslashes(base);
  2043. }
  2044. }
  2045. const state = {
  2046. prefix,
  2047. input,
  2048. start,
  2049. base,
  2050. glob,
  2051. isBrace,
  2052. isBracket,
  2053. isGlob,
  2054. isExtglob,
  2055. isGlobstar,
  2056. negated,
  2057. negatedExtglob
  2058. };
  2059. if (opts.tokens === true) {
  2060. state.maxDepth = 0;
  2061. if (!isPathSeparator(code)) {
  2062. tokens.push(token);
  2063. }
  2064. state.tokens = tokens;
  2065. }
  2066. if (opts.parts === true || opts.tokens === true) {
  2067. let prevIndex;
  2068. for (let idx = 0; idx < slashes.length; idx++) {
  2069. const n = prevIndex ? prevIndex + 1 : start;
  2070. const i = slashes[idx];
  2071. const value = input.slice(n, i);
  2072. if (opts.tokens) {
  2073. if (idx === 0 && start !== 0) {
  2074. tokens[idx].isPrefix = true;
  2075. tokens[idx].value = prefix;
  2076. } else {
  2077. tokens[idx].value = value;
  2078. }
  2079. depth(tokens[idx]);
  2080. state.maxDepth += tokens[idx].depth;
  2081. }
  2082. if (idx !== 0 || value !== '') {
  2083. parts.push(value);
  2084. }
  2085. prevIndex = i;
  2086. }
  2087. if (prevIndex && prevIndex + 1 < input.length) {
  2088. const value = input.slice(prevIndex + 1);
  2089. parts.push(value);
  2090. if (opts.tokens) {
  2091. tokens[tokens.length - 1].value = value;
  2092. depth(tokens[tokens.length - 1]);
  2093. state.maxDepth += tokens[tokens.length - 1].depth;
  2094. }
  2095. }
  2096. state.slashes = slashes;
  2097. state.parts = parts;
  2098. }
  2099. return state;
  2100. };
  2101. var scan_1 = scan$1;
  2102. const constants$2 = constants$3;
  2103. const utils$d = utils$f;
  2104. /**
  2105. * Constants
  2106. */
  2107. const {
  2108. MAX_LENGTH,
  2109. POSIX_REGEX_SOURCE,
  2110. REGEX_NON_SPECIAL_CHARS,
  2111. REGEX_SPECIAL_CHARS_BACKREF,
  2112. REPLACEMENTS
  2113. } = constants$2;
  2114. /**
  2115. * Helpers
  2116. */
  2117. const expandRange = (args, options) => {
  2118. if (typeof options.expandRange === 'function') {
  2119. return options.expandRange(...args, options);
  2120. }
  2121. args.sort();
  2122. const value = `[${args.join('-')}]`;
  2123. try {
  2124. /* eslint-disable-next-line no-new */
  2125. new RegExp(value);
  2126. } catch (ex) {
  2127. return args.map(v => utils$d.escapeRegex(v)).join('..');
  2128. }
  2129. return value;
  2130. };
  2131. /**
  2132. * Create the message for a syntax error
  2133. */
  2134. const syntaxError = (type, char) => {
  2135. return `Missing ${type}: "${char}" - use "\\\\${char}" to match literal characters`;
  2136. };
  2137. /**
  2138. * Parse the given input string.
  2139. * @param {String} input
  2140. * @param {Object} options
  2141. * @return {Object}
  2142. */
  2143. const parse$1 = (input, options) => {
  2144. if (typeof input !== 'string') {
  2145. throw new TypeError('Expected a string');
  2146. }
  2147. input = REPLACEMENTS[input] || input;
  2148. const opts = { ...options };
  2149. const max = typeof opts.maxLength === 'number' ? Math.min(MAX_LENGTH, opts.maxLength) : MAX_LENGTH;
  2150. let len = input.length;
  2151. if (len > max) {
  2152. throw new SyntaxError(`Input length: ${len}, exceeds maximum allowed length: ${max}`);
  2153. }
  2154. const bos = { type: 'bos', value: '', output: opts.prepend || '' };
  2155. const tokens = [bos];
  2156. const capture = opts.capture ? '' : '?:';
  2157. const win32 = utils$d.isWindows(options);
  2158. // create constants based on platform, for windows or posix
  2159. const PLATFORM_CHARS = constants$2.globChars(win32);
  2160. const EXTGLOB_CHARS = constants$2.extglobChars(PLATFORM_CHARS);
  2161. const {
  2162. DOT_LITERAL,
  2163. PLUS_LITERAL,
  2164. SLASH_LITERAL,
  2165. ONE_CHAR,
  2166. DOTS_SLASH,
  2167. NO_DOT,
  2168. NO_DOT_SLASH,
  2169. NO_DOTS_SLASH,
  2170. QMARK,
  2171. QMARK_NO_DOT,
  2172. STAR,
  2173. START_ANCHOR
  2174. } = PLATFORM_CHARS;
  2175. const globstar = opts => {
  2176. return `(${capture}(?:(?!${START_ANCHOR}${opts.dot ? DOTS_SLASH : DOT_LITERAL}).)*?)`;
  2177. };
  2178. const nodot = opts.dot ? '' : NO_DOT;
  2179. const qmarkNoDot = opts.dot ? QMARK : QMARK_NO_DOT;
  2180. let star = opts.bash === true ? globstar(opts) : STAR;
  2181. if (opts.capture) {
  2182. star = `(${star})`;
  2183. }
  2184. // minimatch options support
  2185. if (typeof opts.noext === 'boolean') {
  2186. opts.noextglob = opts.noext;
  2187. }
  2188. const state = {
  2189. input,
  2190. index: -1,
  2191. start: 0,
  2192. dot: opts.dot === true,
  2193. consumed: '',
  2194. output: '',
  2195. prefix: '',
  2196. backtrack: false,
  2197. negated: false,
  2198. brackets: 0,
  2199. braces: 0,
  2200. parens: 0,
  2201. quotes: 0,
  2202. globstar: false,
  2203. tokens
  2204. };
  2205. input = utils$d.removePrefix(input, state);
  2206. len = input.length;
  2207. const extglobs = [];
  2208. const braces = [];
  2209. const stack = [];
  2210. let prev = bos;
  2211. let value;
  2212. /**
  2213. * Tokenizing helpers
  2214. */
  2215. const eos = () => state.index === len - 1;
  2216. const peek = state.peek = (n = 1) => input[state.index + n];
  2217. const advance = state.advance = () => input[++state.index] || '';
  2218. const remaining = () => input.slice(state.index + 1);
  2219. const consume = (value = '', num = 0) => {
  2220. state.consumed += value;
  2221. state.index += num;
  2222. };
  2223. const append = token => {
  2224. state.output += token.output != null ? token.output : token.value;
  2225. consume(token.value);
  2226. };
  2227. const negate = () => {
  2228. let count = 1;
  2229. while (peek() === '!' && (peek(2) !== '(' || peek(3) === '?')) {
  2230. advance();
  2231. state.start++;
  2232. count++;
  2233. }
  2234. if (count % 2 === 0) {
  2235. return false;
  2236. }
  2237. state.negated = true;
  2238. state.start++;
  2239. return true;
  2240. };
  2241. const increment = type => {
  2242. state[type]++;
  2243. stack.push(type);
  2244. };
  2245. const decrement = type => {
  2246. state[type]--;
  2247. stack.pop();
  2248. };
  2249. /**
  2250. * Push tokens onto the tokens array. This helper speeds up
  2251. * tokenizing by 1) helping us avoid backtracking as much as possible,
  2252. * and 2) helping us avoid creating extra tokens when consecutive
  2253. * characters are plain text. This improves performance and simplifies
  2254. * lookbehinds.
  2255. */
  2256. const push = tok => {
  2257. if (prev.type === 'globstar') {
  2258. const isBrace = state.braces > 0 && (tok.type === 'comma' || tok.type === 'brace');
  2259. const isExtglob = tok.extglob === true || (extglobs.length && (tok.type === 'pipe' || tok.type === 'paren'));
  2260. if (tok.type !== 'slash' && tok.type !== 'paren' && !isBrace && !isExtglob) {
  2261. state.output = state.output.slice(0, -prev.output.length);
  2262. prev.type = 'star';
  2263. prev.value = '*';
  2264. prev.output = star;
  2265. state.output += prev.output;
  2266. }
  2267. }
  2268. if (extglobs.length && tok.type !== 'paren') {
  2269. extglobs[extglobs.length - 1].inner += tok.value;
  2270. }
  2271. if (tok.value || tok.output) append(tok);
  2272. if (prev && prev.type === 'text' && tok.type === 'text') {
  2273. prev.value += tok.value;
  2274. prev.output = (prev.output || '') + tok.value;
  2275. return;
  2276. }
  2277. tok.prev = prev;
  2278. tokens.push(tok);
  2279. prev = tok;
  2280. };
  2281. const extglobOpen = (type, value) => {
  2282. const token = { ...EXTGLOB_CHARS[value], conditions: 1, inner: '' };
  2283. token.prev = prev;
  2284. token.parens = state.parens;
  2285. token.output = state.output;
  2286. const output = (opts.capture ? '(' : '') + token.open;
  2287. increment('parens');
  2288. push({ type, value, output: state.output ? '' : ONE_CHAR });
  2289. push({ type: 'paren', extglob: true, value: advance(), output });
  2290. extglobs.push(token);
  2291. };
  2292. const extglobClose = token => {
  2293. let output = token.close + (opts.capture ? ')' : '');
  2294. let rest;
  2295. if (token.type === 'negate') {
  2296. let extglobStar = star;
  2297. if (token.inner && token.inner.length > 1 && token.inner.includes('/')) {
  2298. extglobStar = globstar(opts);
  2299. }
  2300. if (extglobStar !== star || eos() || /^\)+$/.test(remaining())) {
  2301. output = token.close = `)$))${extglobStar}`;
  2302. }
  2303. if (token.inner.includes('*') && (rest = remaining()) && /^\.[^\\/.]+$/.test(rest)) {
  2304. // Any non-magical string (`.ts`) or even nested expression (`.{ts,tsx}`) can follow after the closing parenthesis.
  2305. // In this case, we need to parse the string and use it in the output of the original pattern.
  2306. // Suitable patterns: `/!(*.d).ts`, `/!(*.d).{ts,tsx}`, `**/!(*-dbg).@(js)`.
  2307. //
  2308. // Disabling the `fastpaths` option due to a problem with parsing strings as `.ts` in the pattern like `**/!(*.d).ts`.
  2309. const expression = parse$1(rest, { ...options, fastpaths: false }).output;
  2310. output = token.close = `)${expression})${extglobStar})`;
  2311. }
  2312. if (token.prev.type === 'bos') {
  2313. state.negatedExtglob = true;
  2314. }
  2315. }
  2316. push({ type: 'paren', extglob: true, value, output });
  2317. decrement('parens');
  2318. };
  2319. /**
  2320. * Fast paths
  2321. */
  2322. if (opts.fastpaths !== false && !/(^[*!]|[/()[\]{}"])/.test(input)) {
  2323. let backslashes = false;
  2324. let output = input.replace(REGEX_SPECIAL_CHARS_BACKREF, (m, esc, chars, first, rest, index) => {
  2325. if (first === '\\') {
  2326. backslashes = true;
  2327. return m;
  2328. }
  2329. if (first === '?') {
  2330. if (esc) {
  2331. return esc + first + (rest ? QMARK.repeat(rest.length) : '');
  2332. }
  2333. if (index === 0) {
  2334. return qmarkNoDot + (rest ? QMARK.repeat(rest.length) : '');
  2335. }
  2336. return QMARK.repeat(chars.length);
  2337. }
  2338. if (first === '.') {
  2339. return DOT_LITERAL.repeat(chars.length);
  2340. }
  2341. if (first === '*') {
  2342. if (esc) {
  2343. return esc + first + (rest ? star : '');
  2344. }
  2345. return star;
  2346. }
  2347. return esc ? m : `\\${m}`;
  2348. });
  2349. if (backslashes === true) {
  2350. if (opts.unescape === true) {
  2351. output = output.replace(/\\/g, '');
  2352. } else {
  2353. output = output.replace(/\\+/g, m => {
  2354. return m.length % 2 === 0 ? '\\\\' : (m ? '\\' : '');
  2355. });
  2356. }
  2357. }
  2358. if (output === input && opts.contains === true) {
  2359. state.output = input;
  2360. return state;
  2361. }
  2362. state.output = utils$d.wrapOutput(output, state, options);
  2363. return state;
  2364. }
  2365. /**
  2366. * Tokenize input until we reach end-of-string
  2367. */
  2368. while (!eos()) {
  2369. value = advance();
  2370. if (value === '\u0000') {
  2371. continue;
  2372. }
  2373. /**
  2374. * Escaped characters
  2375. */
  2376. if (value === '\\') {
  2377. const next = peek();
  2378. if (next === '/' && opts.bash !== true) {
  2379. continue;
  2380. }
  2381. if (next === '.' || next === ';') {
  2382. continue;
  2383. }
  2384. if (!next) {
  2385. value += '\\';
  2386. push({ type: 'text', value });
  2387. continue;
  2388. }
  2389. // collapse slashes to reduce potential for exploits
  2390. const match = /^\\+/.exec(remaining());
  2391. let slashes = 0;
  2392. if (match && match[0].length > 2) {
  2393. slashes = match[0].length;
  2394. state.index += slashes;
  2395. if (slashes % 2 !== 0) {
  2396. value += '\\';
  2397. }
  2398. }
  2399. if (opts.unescape === true) {
  2400. value = advance();
  2401. } else {
  2402. value += advance();
  2403. }
  2404. if (state.brackets === 0) {
  2405. push({ type: 'text', value });
  2406. continue;
  2407. }
  2408. }
  2409. /**
  2410. * If we're inside a regex character class, continue
  2411. * until we reach the closing bracket.
  2412. */
  2413. if (state.brackets > 0 && (value !== ']' || prev.value === '[' || prev.value === '[^')) {
  2414. if (opts.posix !== false && value === ':') {
  2415. const inner = prev.value.slice(1);
  2416. if (inner.includes('[')) {
  2417. prev.posix = true;
  2418. if (inner.includes(':')) {
  2419. const idx = prev.value.lastIndexOf('[');
  2420. const pre = prev.value.slice(0, idx);
  2421. const rest = prev.value.slice(idx + 2);
  2422. const posix = POSIX_REGEX_SOURCE[rest];
  2423. if (posix) {
  2424. prev.value = pre + posix;
  2425. state.backtrack = true;
  2426. advance();
  2427. if (!bos.output && tokens.indexOf(prev) === 1) {
  2428. bos.output = ONE_CHAR;
  2429. }
  2430. continue;
  2431. }
  2432. }
  2433. }
  2434. }
  2435. if ((value === '[' && peek() !== ':') || (value === '-' && peek() === ']')) {
  2436. value = `\\${value}`;
  2437. }
  2438. if (value === ']' && (prev.value === '[' || prev.value === '[^')) {
  2439. value = `\\${value}`;
  2440. }
  2441. if (opts.posix === true && value === '!' && prev.value === '[') {
  2442. value = '^';
  2443. }
  2444. prev.value += value;
  2445. append({ value });
  2446. continue;
  2447. }
  2448. /**
  2449. * If we're inside a quoted string, continue
  2450. * until we reach the closing double quote.
  2451. */
  2452. if (state.quotes === 1 && value !== '"') {
  2453. value = utils$d.escapeRegex(value);
  2454. prev.value += value;
  2455. append({ value });
  2456. continue;
  2457. }
  2458. /**
  2459. * Double quotes
  2460. */
  2461. if (value === '"') {
  2462. state.quotes = state.quotes === 1 ? 0 : 1;
  2463. if (opts.keepQuotes === true) {
  2464. push({ type: 'text', value });
  2465. }
  2466. continue;
  2467. }
  2468. /**
  2469. * Parentheses
  2470. */
  2471. if (value === '(') {
  2472. increment('parens');
  2473. push({ type: 'paren', value });
  2474. continue;
  2475. }
  2476. if (value === ')') {
  2477. if (state.parens === 0 && opts.strictBrackets === true) {
  2478. throw new SyntaxError(syntaxError('opening', '('));
  2479. }
  2480. const extglob = extglobs[extglobs.length - 1];
  2481. if (extglob && state.parens === extglob.parens + 1) {
  2482. extglobClose(extglobs.pop());
  2483. continue;
  2484. }
  2485. push({ type: 'paren', value, output: state.parens ? ')' : '\\)' });
  2486. decrement('parens');
  2487. continue;
  2488. }
  2489. /**
  2490. * Square brackets
  2491. */
  2492. if (value === '[') {
  2493. if (opts.nobracket === true || !remaining().includes(']')) {
  2494. if (opts.nobracket !== true && opts.strictBrackets === true) {
  2495. throw new SyntaxError(syntaxError('closing', ']'));
  2496. }
  2497. value = `\\${value}`;
  2498. } else {
  2499. increment('brackets');
  2500. }
  2501. push({ type: 'bracket', value });
  2502. continue;
  2503. }
  2504. if (value === ']') {
  2505. if (opts.nobracket === true || (prev && prev.type === 'bracket' && prev.value.length === 1)) {
  2506. push({ type: 'text', value, output: `\\${value}` });
  2507. continue;
  2508. }
  2509. if (state.brackets === 0) {
  2510. if (opts.strictBrackets === true) {
  2511. throw new SyntaxError(syntaxError('opening', '['));
  2512. }
  2513. push({ type: 'text', value, output: `\\${value}` });
  2514. continue;
  2515. }
  2516. decrement('brackets');
  2517. const prevValue = prev.value.slice(1);
  2518. if (prev.posix !== true && prevValue[0] === '^' && !prevValue.includes('/')) {
  2519. value = `/${value}`;
  2520. }
  2521. prev.value += value;
  2522. append({ value });
  2523. // when literal brackets are explicitly disabled
  2524. // assume we should match with a regex character class
  2525. if (opts.literalBrackets === false || utils$d.hasRegexChars(prevValue)) {
  2526. continue;
  2527. }
  2528. const escaped = utils$d.escapeRegex(prev.value);
  2529. state.output = state.output.slice(0, -prev.value.length);
  2530. // when literal brackets are explicitly enabled
  2531. // assume we should escape the brackets to match literal characters
  2532. if (opts.literalBrackets === true) {
  2533. state.output += escaped;
  2534. prev.value = escaped;
  2535. continue;
  2536. }
  2537. // when the user specifies nothing, try to match both
  2538. prev.value = `(${capture}${escaped}|${prev.value})`;
  2539. state.output += prev.value;
  2540. continue;
  2541. }
  2542. /**
  2543. * Braces
  2544. */
  2545. if (value === '{' && opts.nobrace !== true) {
  2546. increment('braces');
  2547. const open = {
  2548. type: 'brace',
  2549. value,
  2550. output: '(',
  2551. outputIndex: state.output.length,
  2552. tokensIndex: state.tokens.length
  2553. };
  2554. braces.push(open);
  2555. push(open);
  2556. continue;
  2557. }
  2558. if (value === '}') {
  2559. const brace = braces[braces.length - 1];
  2560. if (opts.nobrace === true || !brace) {
  2561. push({ type: 'text', value, output: value });
  2562. continue;
  2563. }
  2564. let output = ')';
  2565. if (brace.dots === true) {
  2566. const arr = tokens.slice();
  2567. const range = [];
  2568. for (let i = arr.length - 1; i >= 0; i--) {
  2569. tokens.pop();
  2570. if (arr[i].type === 'brace') {
  2571. break;
  2572. }
  2573. if (arr[i].type !== 'dots') {
  2574. range.unshift(arr[i].value);
  2575. }
  2576. }
  2577. output = expandRange(range, opts);
  2578. state.backtrack = true;
  2579. }
  2580. if (brace.comma !== true && brace.dots !== true) {
  2581. const out = state.output.slice(0, brace.outputIndex);
  2582. const toks = state.tokens.slice(brace.tokensIndex);
  2583. brace.value = brace.output = '\\{';
  2584. value = output = '\\}';
  2585. state.output = out;
  2586. for (const t of toks) {
  2587. state.output += (t.output || t.value);
  2588. }
  2589. }
  2590. push({ type: 'brace', value, output });
  2591. decrement('braces');
  2592. braces.pop();
  2593. continue;
  2594. }
  2595. /**
  2596. * Pipes
  2597. */
  2598. if (value === '|') {
  2599. if (extglobs.length > 0) {
  2600. extglobs[extglobs.length - 1].conditions++;
  2601. }
  2602. push({ type: 'text', value });
  2603. continue;
  2604. }
  2605. /**
  2606. * Commas
  2607. */
  2608. if (value === ',') {
  2609. let output = value;
  2610. const brace = braces[braces.length - 1];
  2611. if (brace && stack[stack.length - 1] === 'braces') {
  2612. brace.comma = true;
  2613. output = '|';
  2614. }
  2615. push({ type: 'comma', value, output });
  2616. continue;
  2617. }
  2618. /**
  2619. * Slashes
  2620. */
  2621. if (value === '/') {
  2622. // if the beginning of the glob is "./", advance the start
  2623. // to the current index, and don't add the "./" characters
  2624. // to the state. This greatly simplifies lookbehinds when
  2625. // checking for BOS characters like "!" and "." (not "./")
  2626. if (prev.type === 'dot' && state.index === state.start + 1) {
  2627. state.start = state.index + 1;
  2628. state.consumed = '';
  2629. state.output = '';
  2630. tokens.pop();
  2631. prev = bos; // reset "prev" to the first token
  2632. continue;
  2633. }
  2634. push({ type: 'slash', value, output: SLASH_LITERAL });
  2635. continue;
  2636. }
  2637. /**
  2638. * Dots
  2639. */
  2640. if (value === '.') {
  2641. if (state.braces > 0 && prev.type === 'dot') {
  2642. if (prev.value === '.') prev.output = DOT_LITERAL;
  2643. const brace = braces[braces.length - 1];
  2644. prev.type = 'dots';
  2645. prev.output += value;
  2646. prev.value += value;
  2647. brace.dots = true;
  2648. continue;
  2649. }
  2650. if ((state.braces + state.parens) === 0 && prev.type !== 'bos' && prev.type !== 'slash') {
  2651. push({ type: 'text', value, output: DOT_LITERAL });
  2652. continue;
  2653. }
  2654. push({ type: 'dot', value, output: DOT_LITERAL });
  2655. continue;
  2656. }
  2657. /**
  2658. * Question marks
  2659. */
  2660. if (value === '?') {
  2661. const isGroup = prev && prev.value === '(';
  2662. if (!isGroup && opts.noextglob !== true && peek() === '(' && peek(2) !== '?') {
  2663. extglobOpen('qmark', value);
  2664. continue;
  2665. }
  2666. if (prev && prev.type === 'paren') {
  2667. const next = peek();
  2668. let output = value;
  2669. if (next === '<' && !utils$d.supportsLookbehinds()) {
  2670. throw new Error('Node.js v10 or higher is required for regex lookbehinds');
  2671. }
  2672. if ((prev.value === '(' && !/[!=<:]/.test(next)) || (next === '<' && !/<([!=]|\w+>)/.test(remaining()))) {
  2673. output = `\\${value}`;
  2674. }
  2675. push({ type: 'text', value, output });
  2676. continue;
  2677. }
  2678. if (opts.dot !== true && (prev.type === 'slash' || prev.type === 'bos')) {
  2679. push({ type: 'qmark', value, output: QMARK_NO_DOT });
  2680. continue;
  2681. }
  2682. push({ type: 'qmark', value, output: QMARK });
  2683. continue;
  2684. }
  2685. /**
  2686. * Exclamation
  2687. */
  2688. if (value === '!') {
  2689. if (opts.noextglob !== true && peek() === '(') {
  2690. if (peek(2) !== '?' || !/[!=<:]/.test(peek(3))) {
  2691. extglobOpen('negate', value);
  2692. continue;
  2693. }
  2694. }
  2695. if (opts.nonegate !== true && state.index === 0) {
  2696. negate();
  2697. continue;
  2698. }
  2699. }
  2700. /**
  2701. * Plus
  2702. */
  2703. if (value === '+') {
  2704. if (opts.noextglob !== true && peek() === '(' && peek(2) !== '?') {
  2705. extglobOpen('plus', value);
  2706. continue;
  2707. }
  2708. if ((prev && prev.value === '(') || opts.regex === false) {
  2709. push({ type: 'plus', value, output: PLUS_LITERAL });
  2710. continue;
  2711. }
  2712. if ((prev && (prev.type === 'bracket' || prev.type === 'paren' || prev.type === 'brace')) || state.parens > 0) {
  2713. push({ type: 'plus', value });
  2714. continue;
  2715. }
  2716. push({ type: 'plus', value: PLUS_LITERAL });
  2717. continue;
  2718. }
  2719. /**
  2720. * Plain text
  2721. */
  2722. if (value === '@') {
  2723. if (opts.noextglob !== true && peek() === '(' && peek(2) !== '?') {
  2724. push({ type: 'at', extglob: true, value, output: '' });
  2725. continue;
  2726. }
  2727. push({ type: 'text', value });
  2728. continue;
  2729. }
  2730. /**
  2731. * Plain text
  2732. */
  2733. if (value !== '*') {
  2734. if (value === '$' || value === '^') {
  2735. value = `\\${value}`;
  2736. }
  2737. const match = REGEX_NON_SPECIAL_CHARS.exec(remaining());
  2738. if (match) {
  2739. value += match[0];
  2740. state.index += match[0].length;
  2741. }
  2742. push({ type: 'text', value });
  2743. continue;
  2744. }
  2745. /**
  2746. * Stars
  2747. */
  2748. if (prev && (prev.type === 'globstar' || prev.star === true)) {
  2749. prev.type = 'star';
  2750. prev.star = true;
  2751. prev.value += value;
  2752. prev.output = star;
  2753. state.backtrack = true;
  2754. state.globstar = true;
  2755. consume(value);
  2756. continue;
  2757. }
  2758. let rest = remaining();
  2759. if (opts.noextglob !== true && /^\([^?]/.test(rest)) {
  2760. extglobOpen('star', value);
  2761. continue;
  2762. }
  2763. if (prev.type === 'star') {
  2764. if (opts.noglobstar === true) {
  2765. consume(value);
  2766. continue;
  2767. }
  2768. const prior = prev.prev;
  2769. const before = prior.prev;
  2770. const isStart = prior.type === 'slash' || prior.type === 'bos';
  2771. const afterStar = before && (before.type === 'star' || before.type === 'globstar');
  2772. if (opts.bash === true && (!isStart || (rest[0] && rest[0] !== '/'))) {
  2773. push({ type: 'star', value, output: '' });
  2774. continue;
  2775. }
  2776. const isBrace = state.braces > 0 && (prior.type === 'comma' || prior.type === 'brace');
  2777. const isExtglob = extglobs.length && (prior.type === 'pipe' || prior.type === 'paren');
  2778. if (!isStart && prior.type !== 'paren' && !isBrace && !isExtglob) {
  2779. push({ type: 'star', value, output: '' });
  2780. continue;
  2781. }
  2782. // strip consecutive `/**/`
  2783. while (rest.slice(0, 3) === '/**') {
  2784. const after = input[state.index + 4];
  2785. if (after && after !== '/') {
  2786. break;
  2787. }
  2788. rest = rest.slice(3);
  2789. consume('/**', 3);
  2790. }
  2791. if (prior.type === 'bos' && eos()) {
  2792. prev.type = 'globstar';
  2793. prev.value += value;
  2794. prev.output = globstar(opts);
  2795. state.output = prev.output;
  2796. state.globstar = true;
  2797. consume(value);
  2798. continue;
  2799. }
  2800. if (prior.type === 'slash' && prior.prev.type !== 'bos' && !afterStar && eos()) {
  2801. state.output = state.output.slice(0, -(prior.output + prev.output).length);
  2802. prior.output = `(?:${prior.output}`;
  2803. prev.type = 'globstar';
  2804. prev.output = globstar(opts) + (opts.strictSlashes ? ')' : '|$)');
  2805. prev.value += value;
  2806. state.globstar = true;
  2807. state.output += prior.output + prev.output;
  2808. consume(value);
  2809. continue;
  2810. }
  2811. if (prior.type === 'slash' && prior.prev.type !== 'bos' && rest[0] === '/') {
  2812. const end = rest[1] !== void 0 ? '|$' : '';
  2813. state.output = state.output.slice(0, -(prior.output + prev.output).length);
  2814. prior.output = `(?:${prior.output}`;
  2815. prev.type = 'globstar';
  2816. prev.output = `${globstar(opts)}${SLASH_LITERAL}|${SLASH_LITERAL}${end})`;
  2817. prev.value += value;
  2818. state.output += prior.output + prev.output;
  2819. state.globstar = true;
  2820. consume(value + advance());
  2821. push({ type: 'slash', value: '/', output: '' });
  2822. continue;
  2823. }
  2824. if (prior.type === 'bos' && rest[0] === '/') {
  2825. prev.type = 'globstar';
  2826. prev.value += value;
  2827. prev.output = `(?:^|${SLASH_LITERAL}|${globstar(opts)}${SLASH_LITERAL})`;
  2828. state.output = prev.output;
  2829. state.globstar = true;
  2830. consume(value + advance());
  2831. push({ type: 'slash', value: '/', output: '' });
  2832. continue;
  2833. }
  2834. // remove single star from output
  2835. state.output = state.output.slice(0, -prev.output.length);
  2836. // reset previous token to globstar
  2837. prev.type = 'globstar';
  2838. prev.output = globstar(opts);
  2839. prev.value += value;
  2840. // reset output with globstar
  2841. state.output += prev.output;
  2842. state.globstar = true;
  2843. consume(value);
  2844. continue;
  2845. }
  2846. const token = { type: 'star', value, output: star };
  2847. if (opts.bash === true) {
  2848. token.output = '.*?';
  2849. if (prev.type === 'bos' || prev.type === 'slash') {
  2850. token.output = nodot + token.output;
  2851. }
  2852. push(token);
  2853. continue;
  2854. }
  2855. if (prev && (prev.type === 'bracket' || prev.type === 'paren') && opts.regex === true) {
  2856. token.output = value;
  2857. push(token);
  2858. continue;
  2859. }
  2860. if (state.index === state.start || prev.type === 'slash' || prev.type === 'dot') {
  2861. if (prev.type === 'dot') {
  2862. state.output += NO_DOT_SLASH;
  2863. prev.output += NO_DOT_SLASH;
  2864. } else if (opts.dot === true) {
  2865. state.output += NO_DOTS_SLASH;
  2866. prev.output += NO_DOTS_SLASH;
  2867. } else {
  2868. state.output += nodot;
  2869. prev.output += nodot;
  2870. }
  2871. if (peek() !== '*') {
  2872. state.output += ONE_CHAR;
  2873. prev.output += ONE_CHAR;
  2874. }
  2875. }
  2876. push(token);
  2877. }
  2878. while (state.brackets > 0) {
  2879. if (opts.strictBrackets === true) throw new SyntaxError(syntaxError('closing', ']'));
  2880. state.output = utils$d.escapeLast(state.output, '[');
  2881. decrement('brackets');
  2882. }
  2883. while (state.parens > 0) {
  2884. if (opts.strictBrackets === true) throw new SyntaxError(syntaxError('closing', ')'));
  2885. state.output = utils$d.escapeLast(state.output, '(');
  2886. decrement('parens');
  2887. }
  2888. while (state.braces > 0) {
  2889. if (opts.strictBrackets === true) throw new SyntaxError(syntaxError('closing', '}'));
  2890. state.output = utils$d.escapeLast(state.output, '{');
  2891. decrement('braces');
  2892. }
  2893. if (opts.strictSlashes !== true && (prev.type === 'star' || prev.type === 'bracket')) {
  2894. push({ type: 'maybe_slash', value: '', output: `${SLASH_LITERAL}?` });
  2895. }
  2896. // rebuild the output if we had to backtrack at any point
  2897. if (state.backtrack === true) {
  2898. state.output = '';
  2899. for (const token of state.tokens) {
  2900. state.output += token.output != null ? token.output : token.value;
  2901. if (token.suffix) {
  2902. state.output += token.suffix;
  2903. }
  2904. }
  2905. }
  2906. return state;
  2907. };
  2908. /**
  2909. * Fast paths for creating regular expressions for common glob patterns.
  2910. * This can significantly speed up processing and has very little downside
  2911. * impact when none of the fast paths match.
  2912. */
  2913. parse$1.fastpaths = (input, options) => {
  2914. const opts = { ...options };
  2915. const max = typeof opts.maxLength === 'number' ? Math.min(MAX_LENGTH, opts.maxLength) : MAX_LENGTH;
  2916. const len = input.length;
  2917. if (len > max) {
  2918. throw new SyntaxError(`Input length: ${len}, exceeds maximum allowed length: ${max}`);
  2919. }
  2920. input = REPLACEMENTS[input] || input;
  2921. const win32 = utils$d.isWindows(options);
  2922. // create constants based on platform, for windows or posix
  2923. const {
  2924. DOT_LITERAL,
  2925. SLASH_LITERAL,
  2926. ONE_CHAR,
  2927. DOTS_SLASH,
  2928. NO_DOT,
  2929. NO_DOTS,
  2930. NO_DOTS_SLASH,
  2931. STAR,
  2932. START_ANCHOR
  2933. } = constants$2.globChars(win32);
  2934. const nodot = opts.dot ? NO_DOTS : NO_DOT;
  2935. const slashDot = opts.dot ? NO_DOTS_SLASH : NO_DOT;
  2936. const capture = opts.capture ? '' : '?:';
  2937. const state = { negated: false, prefix: '' };
  2938. let star = opts.bash === true ? '.*?' : STAR;
  2939. if (opts.capture) {
  2940. star = `(${star})`;
  2941. }
  2942. const globstar = opts => {
  2943. if (opts.noglobstar === true) return star;
  2944. return `(${capture}(?:(?!${START_ANCHOR}${opts.dot ? DOTS_SLASH : DOT_LITERAL}).)*?)`;
  2945. };
  2946. const create = str => {
  2947. switch (str) {
  2948. case '*':
  2949. return `${nodot}${ONE_CHAR}${star}`;
  2950. case '.*':
  2951. return `${DOT_LITERAL}${ONE_CHAR}${star}`;
  2952. case '*.*':
  2953. return `${nodot}${star}${DOT_LITERAL}${ONE_CHAR}${star}`;
  2954. case '*/*':
  2955. return `${nodot}${star}${SLASH_LITERAL}${ONE_CHAR}${slashDot}${star}`;
  2956. case '**':
  2957. return nodot + globstar(opts);
  2958. case '**/*':
  2959. return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${slashDot}${ONE_CHAR}${star}`;
  2960. case '**/*.*':
  2961. return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${slashDot}${star}${DOT_LITERAL}${ONE_CHAR}${star}`;
  2962. case '**/.*':
  2963. return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${DOT_LITERAL}${ONE_CHAR}${star}`;
  2964. default: {
  2965. const match = /^(.*?)\.(\w+)$/.exec(str);
  2966. if (!match) return;
  2967. const source = create(match[1]);
  2968. if (!source) return;
  2969. return source + DOT_LITERAL + match[2];
  2970. }
  2971. }
  2972. };
  2973. const output = utils$d.removePrefix(input, state);
  2974. let source = create(output);
  2975. if (source && opts.strictSlashes !== true) {
  2976. source += `${SLASH_LITERAL}?`;
  2977. }
  2978. return source;
  2979. };
  2980. var parse_1 = parse$1;
  2981. const path$6 = path$a;
  2982. const scan = scan_1;
  2983. const parse = parse_1;
  2984. const utils$c = utils$f;
  2985. const constants$1 = constants$3;
  2986. const isObject = val => val && typeof val === 'object' && !Array.isArray(val);
  2987. /**
  2988. * Creates a matcher function from one or more glob patterns. The
  2989. * returned function takes a string to match as its first argument,
  2990. * and returns true if the string is a match. The returned matcher
  2991. * function also takes a boolean as the second argument that, when true,
  2992. * returns an object with additional information.
  2993. *
  2994. * ```js
  2995. * const picomatch = require('picomatch');
  2996. * // picomatch(glob[, options]);
  2997. *
  2998. * const isMatch = picomatch('*.!(*a)');
  2999. * console.log(isMatch('a.a')); //=> false
  3000. * console.log(isMatch('a.b')); //=> true
  3001. * ```
  3002. * @name picomatch
  3003. * @param {String|Array} `globs` One or more glob patterns.
  3004. * @param {Object=} `options`
  3005. * @return {Function=} Returns a matcher function.
  3006. * @api public
  3007. */
  3008. const picomatch$1 = (glob, options, returnState = false) => {
  3009. if (Array.isArray(glob)) {
  3010. const fns = glob.map(input => picomatch$1(input, options, returnState));
  3011. const arrayMatcher = str => {
  3012. for (const isMatch of fns) {
  3013. const state = isMatch(str);
  3014. if (state) return state;
  3015. }
  3016. return false;
  3017. };
  3018. return arrayMatcher;
  3019. }
  3020. const isState = isObject(glob) && glob.tokens && glob.input;
  3021. if (glob === '' || (typeof glob !== 'string' && !isState)) {
  3022. throw new TypeError('Expected pattern to be a non-empty string');
  3023. }
  3024. const opts = options || {};
  3025. const posix = utils$c.isWindows(options);
  3026. const regex = isState
  3027. ? picomatch$1.compileRe(glob, options)
  3028. : picomatch$1.makeRe(glob, options, false, true);
  3029. const state = regex.state;
  3030. delete regex.state;
  3031. let isIgnored = () => false;
  3032. if (opts.ignore) {
  3033. const ignoreOpts = { ...options, ignore: null, onMatch: null, onResult: null };
  3034. isIgnored = picomatch$1(opts.ignore, ignoreOpts, returnState);
  3035. }
  3036. const matcher = (input, returnObject = false) => {
  3037. const { isMatch, match, output } = picomatch$1.test(input, regex, options, { glob, posix });
  3038. const result = { glob, state, regex, posix, input, output, match, isMatch };
  3039. if (typeof opts.onResult === 'function') {
  3040. opts.onResult(result);
  3041. }
  3042. if (isMatch === false) {
  3043. result.isMatch = false;
  3044. return returnObject ? result : false;
  3045. }
  3046. if (isIgnored(input)) {
  3047. if (typeof opts.onIgnore === 'function') {
  3048. opts.onIgnore(result);
  3049. }
  3050. result.isMatch = false;
  3051. return returnObject ? result : false;
  3052. }
  3053. if (typeof opts.onMatch === 'function') {
  3054. opts.onMatch(result);
  3055. }
  3056. return returnObject ? result : true;
  3057. };
  3058. if (returnState) {
  3059. matcher.state = state;
  3060. }
  3061. return matcher;
  3062. };
  3063. /**
  3064. * Test `input` with the given `regex`. This is used by the main
  3065. * `picomatch()` function to test the input string.
  3066. *
  3067. * ```js
  3068. * const picomatch = require('picomatch');
  3069. * // picomatch.test(input, regex[, options]);
  3070. *
  3071. * console.log(picomatch.test('foo/bar', /^(?:([^/]*?)\/([^/]*?))$/));
  3072. * // { isMatch: true, match: [ 'foo/', 'foo', 'bar' ], output: 'foo/bar' }
  3073. * ```
  3074. * @param {String} `input` String to test.
  3075. * @param {RegExp} `regex`
  3076. * @return {Object} Returns an object with matching info.
  3077. * @api public
  3078. */
  3079. picomatch$1.test = (input, regex, options, { glob, posix } = {}) => {
  3080. if (typeof input !== 'string') {
  3081. throw new TypeError('Expected input to be a string');
  3082. }
  3083. if (input === '') {
  3084. return { isMatch: false, output: '' };
  3085. }
  3086. const opts = options || {};
  3087. const format = opts.format || (posix ? utils$c.toPosixSlashes : null);
  3088. let match = input === glob;
  3089. let output = (match && format) ? format(input) : input;
  3090. if (match === false) {
  3091. output = format ? format(input) : input;
  3092. match = output === glob;
  3093. }
  3094. if (match === false || opts.capture === true) {
  3095. if (opts.matchBase === true || opts.basename === true) {
  3096. match = picomatch$1.matchBase(input, regex, options, posix);
  3097. } else {
  3098. match = regex.exec(output);
  3099. }
  3100. }
  3101. return { isMatch: Boolean(match), match, output };
  3102. };
  3103. /**
  3104. * Match the basename of a filepath.
  3105. *
  3106. * ```js
  3107. * const picomatch = require('picomatch');
  3108. * // picomatch.matchBase(input, glob[, options]);
  3109. * console.log(picomatch.matchBase('foo/bar.js', '*.js'); // true
  3110. * ```
  3111. * @param {String} `input` String to test.
  3112. * @param {RegExp|String} `glob` Glob pattern or regex created by [.makeRe](#makeRe).
  3113. * @return {Boolean}
  3114. * @api public
  3115. */
  3116. picomatch$1.matchBase = (input, glob, options, posix = utils$c.isWindows(options)) => {
  3117. const regex = glob instanceof RegExp ? glob : picomatch$1.makeRe(glob, options);
  3118. return regex.test(path$6.basename(input));
  3119. };
  3120. /**
  3121. * Returns true if **any** of the given glob `patterns` match the specified `string`.
  3122. *
  3123. * ```js
  3124. * const picomatch = require('picomatch');
  3125. * // picomatch.isMatch(string, patterns[, options]);
  3126. *
  3127. * console.log(picomatch.isMatch('a.a', ['b.*', '*.a'])); //=> true
  3128. * console.log(picomatch.isMatch('a.a', 'b.*')); //=> false
  3129. * ```
  3130. * @param {String|Array} str The string to test.
  3131. * @param {String|Array} patterns One or more glob patterns to use for matching.
  3132. * @param {Object} [options] See available [options](#options).
  3133. * @return {Boolean} Returns true if any patterns match `str`
  3134. * @api public
  3135. */
  3136. picomatch$1.isMatch = (str, patterns, options) => picomatch$1(patterns, options)(str);
  3137. /**
  3138. * Parse a glob pattern to create the source string for a regular
  3139. * expression.
  3140. *
  3141. * ```js
  3142. * const picomatch = require('picomatch');
  3143. * const result = picomatch.parse(pattern[, options]);
  3144. * ```
  3145. * @param {String} `pattern`
  3146. * @param {Object} `options`
  3147. * @return {Object} Returns an object with useful properties and output to be used as a regex source string.
  3148. * @api public
  3149. */
  3150. picomatch$1.parse = (pattern, options) => {
  3151. if (Array.isArray(pattern)) return pattern.map(p => picomatch$1.parse(p, options));
  3152. return parse(pattern, { ...options, fastpaths: false });
  3153. };
  3154. /**
  3155. * Scan a glob pattern to separate the pattern into segments.
  3156. *
  3157. * ```js
  3158. * const picomatch = require('picomatch');
  3159. * // picomatch.scan(input[, options]);
  3160. *
  3161. * const result = picomatch.scan('!./foo/*.js');
  3162. * console.log(result);
  3163. * { prefix: '!./',
  3164. * input: '!./foo/*.js',
  3165. * start: 3,
  3166. * base: 'foo',
  3167. * glob: '*.js',
  3168. * isBrace: false,
  3169. * isBracket: false,
  3170. * isGlob: true,
  3171. * isExtglob: false,
  3172. * isGlobstar: false,
  3173. * negated: true }
  3174. * ```
  3175. * @param {String} `input` Glob pattern to scan.
  3176. * @param {Object} `options`
  3177. * @return {Object} Returns an object with
  3178. * @api public
  3179. */
  3180. picomatch$1.scan = (input, options) => scan(input, options);
  3181. /**
  3182. * Compile a regular expression from the `state` object returned by the
  3183. * [parse()](#parse) method.
  3184. *
  3185. * @param {Object} `state`
  3186. * @param {Object} `options`
  3187. * @param {Boolean} `returnOutput` Intended for implementors, this argument allows you to return the raw output from the parser.
  3188. * @param {Boolean} `returnState` Adds the state to a `state` property on the returned regex. Useful for implementors and debugging.
  3189. * @return {RegExp}
  3190. * @api public
  3191. */
  3192. picomatch$1.compileRe = (state, options, returnOutput = false, returnState = false) => {
  3193. if (returnOutput === true) {
  3194. return state.output;
  3195. }
  3196. const opts = options || {};
  3197. const prepend = opts.contains ? '' : '^';
  3198. const append = opts.contains ? '' : '$';
  3199. let source = `${prepend}(?:${state.output})${append}`;
  3200. if (state && state.negated === true) {
  3201. source = `^(?!${source}).*$`;
  3202. }
  3203. const regex = picomatch$1.toRegex(source, options);
  3204. if (returnState === true) {
  3205. regex.state = state;
  3206. }
  3207. return regex;
  3208. };
  3209. /**
  3210. * Create a regular expression from a parsed glob pattern.
  3211. *
  3212. * ```js
  3213. * const picomatch = require('picomatch');
  3214. * const state = picomatch.parse('*.js');
  3215. * // picomatch.compileRe(state[, options]);
  3216. *
  3217. * console.log(picomatch.compileRe(state));
  3218. * //=> /^(?:(?!\.)(?=.)[^/]*?\.js)$/
  3219. * ```
  3220. * @param {String} `state` The object returned from the `.parse` method.
  3221. * @param {Object} `options`
  3222. * @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.
  3223. * @param {Boolean} `returnState` Implementors may use this argument to return the state from the parsed glob with the returned regular expression.
  3224. * @return {RegExp} Returns a regex created from the given pattern.
  3225. * @api public
  3226. */
  3227. picomatch$1.makeRe = (input, options = {}, returnOutput = false, returnState = false) => {
  3228. if (!input || typeof input !== 'string') {
  3229. throw new TypeError('Expected a non-empty string');
  3230. }
  3231. let parsed = { negated: false, fastpaths: true };
  3232. if (options.fastpaths !== false && (input[0] === '.' || input[0] === '*')) {
  3233. parsed.output = parse.fastpaths(input, options);
  3234. }
  3235. if (!parsed.output) {
  3236. parsed = parse(input, options);
  3237. }
  3238. return picomatch$1.compileRe(parsed, options, returnOutput, returnState);
  3239. };
  3240. /**
  3241. * Create a regular expression from the given regex source string.
  3242. *
  3243. * ```js
  3244. * const picomatch = require('picomatch');
  3245. * // picomatch.toRegex(source[, options]);
  3246. *
  3247. * const { output } = picomatch.parse('*.js');
  3248. * console.log(picomatch.toRegex(output));
  3249. * //=> /^(?:(?!\.)(?=.)[^/]*?\.js)$/
  3250. * ```
  3251. * @param {String} `source` Regular expression source string.
  3252. * @param {Object} `options`
  3253. * @return {RegExp}
  3254. * @api public
  3255. */
  3256. picomatch$1.toRegex = (source, options) => {
  3257. try {
  3258. const opts = options || {};
  3259. return new RegExp(source, opts.flags || (opts.nocase ? 'i' : ''));
  3260. } catch (err) {
  3261. if (options && options.debug === true) throw err;
  3262. return /$^/;
  3263. }
  3264. };
  3265. /**
  3266. * Picomatch constants.
  3267. * @return {Object}
  3268. */
  3269. picomatch$1.constants = constants$1;
  3270. /**
  3271. * Expose "picomatch"
  3272. */
  3273. var picomatch_1 = picomatch$1;
  3274. (function (module) {
  3275. module.exports = picomatch_1;
  3276. } (picomatch$2));
  3277. const util = util$2;
  3278. const braces = braces_1;
  3279. const picomatch = picomatch$2.exports;
  3280. const utils$b = utils$f;
  3281. const isEmptyString = val => val === '' || val === './';
  3282. /**
  3283. * Returns an array of strings that match one or more glob patterns.
  3284. *
  3285. * ```js
  3286. * const mm = require('micromatch');
  3287. * // mm(list, patterns[, options]);
  3288. *
  3289. * console.log(mm(['a.js', 'a.txt'], ['*.js']));
  3290. * //=> [ 'a.js' ]
  3291. * ```
  3292. * @param {String|Array<string>} `list` List of strings to match.
  3293. * @param {String|Array<string>} `patterns` One or more glob patterns to use for matching.
  3294. * @param {Object} `options` See available [options](#options)
  3295. * @return {Array} Returns an array of matches
  3296. * @summary false
  3297. * @api public
  3298. */
  3299. const micromatch$1 = (list, patterns, options) => {
  3300. patterns = [].concat(patterns);
  3301. list = [].concat(list);
  3302. let omit = new Set();
  3303. let keep = new Set();
  3304. let items = new Set();
  3305. let negatives = 0;
  3306. let onResult = state => {
  3307. items.add(state.output);
  3308. if (options && options.onResult) {
  3309. options.onResult(state);
  3310. }
  3311. };
  3312. for (let i = 0; i < patterns.length; i++) {
  3313. let isMatch = picomatch(String(patterns[i]), { ...options, onResult }, true);
  3314. let negated = isMatch.state.negated || isMatch.state.negatedExtglob;
  3315. if (negated) negatives++;
  3316. for (let item of list) {
  3317. let matched = isMatch(item, true);
  3318. let match = negated ? !matched.isMatch : matched.isMatch;
  3319. if (!match) continue;
  3320. if (negated) {
  3321. omit.add(matched.output);
  3322. } else {
  3323. omit.delete(matched.output);
  3324. keep.add(matched.output);
  3325. }
  3326. }
  3327. }
  3328. let result = negatives === patterns.length ? [...items] : [...keep];
  3329. let matches = result.filter(item => !omit.has(item));
  3330. if (options && matches.length === 0) {
  3331. if (options.failglob === true) {
  3332. throw new Error(`No matches found for "${patterns.join(', ')}"`);
  3333. }
  3334. if (options.nonull === true || options.nullglob === true) {
  3335. return options.unescape ? patterns.map(p => p.replace(/\\/g, '')) : patterns;
  3336. }
  3337. }
  3338. return matches;
  3339. };
  3340. /**
  3341. * Backwards compatibility
  3342. */
  3343. micromatch$1.match = micromatch$1;
  3344. /**
  3345. * Returns a matcher function from the given glob `pattern` and `options`.
  3346. * The returned function takes a string to match as its only argument and returns
  3347. * true if the string is a match.
  3348. *
  3349. * ```js
  3350. * const mm = require('micromatch');
  3351. * // mm.matcher(pattern[, options]);
  3352. *
  3353. * const isMatch = mm.matcher('*.!(*a)');
  3354. * console.log(isMatch('a.a')); //=> false
  3355. * console.log(isMatch('a.b')); //=> true
  3356. * ```
  3357. * @param {String} `pattern` Glob pattern
  3358. * @param {Object} `options`
  3359. * @return {Function} Returns a matcher function.
  3360. * @api public
  3361. */
  3362. micromatch$1.matcher = (pattern, options) => picomatch(pattern, options);
  3363. /**
  3364. * Returns true if **any** of the given glob `patterns` match the specified `string`.
  3365. *
  3366. * ```js
  3367. * const mm = require('micromatch');
  3368. * // mm.isMatch(string, patterns[, options]);
  3369. *
  3370. * console.log(mm.isMatch('a.a', ['b.*', '*.a'])); //=> true
  3371. * console.log(mm.isMatch('a.a', 'b.*')); //=> false
  3372. * ```
  3373. * @param {String} `str` The string to test.
  3374. * @param {String|Array} `patterns` One or more glob patterns to use for matching.
  3375. * @param {Object} `[options]` See available [options](#options).
  3376. * @return {Boolean} Returns true if any patterns match `str`
  3377. * @api public
  3378. */
  3379. micromatch$1.isMatch = (str, patterns, options) => picomatch(patterns, options)(str);
  3380. /**
  3381. * Backwards compatibility
  3382. */
  3383. micromatch$1.any = micromatch$1.isMatch;
  3384. /**
  3385. * Returns a list of strings that _**do not match any**_ of the given `patterns`.
  3386. *
  3387. * ```js
  3388. * const mm = require('micromatch');
  3389. * // mm.not(list, patterns[, options]);
  3390. *
  3391. * console.log(mm.not(['a.a', 'b.b', 'c.c'], '*.a'));
  3392. * //=> ['b.b', 'c.c']
  3393. * ```
  3394. * @param {Array} `list` Array of strings to match.
  3395. * @param {String|Array} `patterns` One or more glob pattern to use for matching.
  3396. * @param {Object} `options` See available [options](#options) for changing how matches are performed
  3397. * @return {Array} Returns an array of strings that **do not match** the given patterns.
  3398. * @api public
  3399. */
  3400. micromatch$1.not = (list, patterns, options = {}) => {
  3401. patterns = [].concat(patterns).map(String);
  3402. let result = new Set();
  3403. let items = [];
  3404. let onResult = state => {
  3405. if (options.onResult) options.onResult(state);
  3406. items.push(state.output);
  3407. };
  3408. let matches = new Set(micromatch$1(list, patterns, { ...options, onResult }));
  3409. for (let item of items) {
  3410. if (!matches.has(item)) {
  3411. result.add(item);
  3412. }
  3413. }
  3414. return [...result];
  3415. };
  3416. /**
  3417. * Returns true if the given `string` contains the given pattern. Similar
  3418. * to [.isMatch](#isMatch) but the pattern can match any part of the string.
  3419. *
  3420. * ```js
  3421. * var mm = require('micromatch');
  3422. * // mm.contains(string, pattern[, options]);
  3423. *
  3424. * console.log(mm.contains('aa/bb/cc', '*b'));
  3425. * //=> true
  3426. * console.log(mm.contains('aa/bb/cc', '*d'));
  3427. * //=> false
  3428. * ```
  3429. * @param {String} `str` The string to match.
  3430. * @param {String|Array} `patterns` Glob pattern to use for matching.
  3431. * @param {Object} `options` See available [options](#options) for changing how matches are performed
  3432. * @return {Boolean} Returns true if any of the patterns matches any part of `str`.
  3433. * @api public
  3434. */
  3435. micromatch$1.contains = (str, pattern, options) => {
  3436. if (typeof str !== 'string') {
  3437. throw new TypeError(`Expected a string: "${util.inspect(str)}"`);
  3438. }
  3439. if (Array.isArray(pattern)) {
  3440. return pattern.some(p => micromatch$1.contains(str, p, options));
  3441. }
  3442. if (typeof pattern === 'string') {
  3443. if (isEmptyString(str) || isEmptyString(pattern)) {
  3444. return false;
  3445. }
  3446. if (str.includes(pattern) || (str.startsWith('./') && str.slice(2).includes(pattern))) {
  3447. return true;
  3448. }
  3449. }
  3450. return micromatch$1.isMatch(str, pattern, { ...options, contains: true });
  3451. };
  3452. /**
  3453. * Filter the keys of the given object with the given `glob` pattern
  3454. * and `options`. Does not attempt to match nested keys. If you need this feature,
  3455. * use [glob-object][] instead.
  3456. *
  3457. * ```js
  3458. * const mm = require('micromatch');
  3459. * // mm.matchKeys(object, patterns[, options]);
  3460. *
  3461. * const obj = { aa: 'a', ab: 'b', ac: 'c' };
  3462. * console.log(mm.matchKeys(obj, '*b'));
  3463. * //=> { ab: 'b' }
  3464. * ```
  3465. * @param {Object} `object` The object with keys to filter.
  3466. * @param {String|Array} `patterns` One or more glob patterns to use for matching.
  3467. * @param {Object} `options` See available [options](#options) for changing how matches are performed
  3468. * @return {Object} Returns an object with only keys that match the given patterns.
  3469. * @api public
  3470. */
  3471. micromatch$1.matchKeys = (obj, patterns, options) => {
  3472. if (!utils$b.isObject(obj)) {
  3473. throw new TypeError('Expected the first argument to be an object');
  3474. }
  3475. let keys = micromatch$1(Object.keys(obj), patterns, options);
  3476. let res = {};
  3477. for (let key of keys) res[key] = obj[key];
  3478. return res;
  3479. };
  3480. /**
  3481. * Returns true if some of the strings in the given `list` match any of the given glob `patterns`.
  3482. *
  3483. * ```js
  3484. * const mm = require('micromatch');
  3485. * // mm.some(list, patterns[, options]);
  3486. *
  3487. * console.log(mm.some(['foo.js', 'bar.js'], ['*.js', '!foo.js']));
  3488. * // true
  3489. * console.log(mm.some(['foo.js'], ['*.js', '!foo.js']));
  3490. * // false
  3491. * ```
  3492. * @param {String|Array} `list` The string or array of strings to test. Returns as soon as the first match is found.
  3493. * @param {String|Array} `patterns` One or more glob patterns to use for matching.
  3494. * @param {Object} `options` See available [options](#options) for changing how matches are performed
  3495. * @return {Boolean} Returns true if any `patterns` matches any of the strings in `list`
  3496. * @api public
  3497. */
  3498. micromatch$1.some = (list, patterns, options) => {
  3499. let items = [].concat(list);
  3500. for (let pattern of [].concat(patterns)) {
  3501. let isMatch = picomatch(String(pattern), options);
  3502. if (items.some(item => isMatch(item))) {
  3503. return true;
  3504. }
  3505. }
  3506. return false;
  3507. };
  3508. /**
  3509. * Returns true if every string in the given `list` matches
  3510. * any of the given glob `patterns`.
  3511. *
  3512. * ```js
  3513. * const mm = require('micromatch');
  3514. * // mm.every(list, patterns[, options]);
  3515. *
  3516. * console.log(mm.every('foo.js', ['foo.js']));
  3517. * // true
  3518. * console.log(mm.every(['foo.js', 'bar.js'], ['*.js']));
  3519. * // true
  3520. * console.log(mm.every(['foo.js', 'bar.js'], ['*.js', '!foo.js']));
  3521. * // false
  3522. * console.log(mm.every(['foo.js'], ['*.js', '!foo.js']));
  3523. * // false
  3524. * ```
  3525. * @param {String|Array} `list` The string or array of strings to test.
  3526. * @param {String|Array} `patterns` One or more glob patterns to use for matching.
  3527. * @param {Object} `options` See available [options](#options) for changing how matches are performed
  3528. * @return {Boolean} Returns true if all `patterns` matches all of the strings in `list`
  3529. * @api public
  3530. */
  3531. micromatch$1.every = (list, patterns, options) => {
  3532. let items = [].concat(list);
  3533. for (let pattern of [].concat(patterns)) {
  3534. let isMatch = picomatch(String(pattern), options);
  3535. if (!items.every(item => isMatch(item))) {
  3536. return false;
  3537. }
  3538. }
  3539. return true;
  3540. };
  3541. /**
  3542. * Returns true if **all** of the given `patterns` match
  3543. * the specified string.
  3544. *
  3545. * ```js
  3546. * const mm = require('micromatch');
  3547. * // mm.all(string, patterns[, options]);
  3548. *
  3549. * console.log(mm.all('foo.js', ['foo.js']));
  3550. * // true
  3551. *
  3552. * console.log(mm.all('foo.js', ['*.js', '!foo.js']));
  3553. * // false
  3554. *
  3555. * console.log(mm.all('foo.js', ['*.js', 'foo.js']));
  3556. * // true
  3557. *
  3558. * console.log(mm.all('foo.js', ['*.js', 'f*', '*o*', '*o.js']));
  3559. * // true
  3560. * ```
  3561. * @param {String|Array} `str` The string to test.
  3562. * @param {String|Array} `patterns` One or more glob patterns to use for matching.
  3563. * @param {Object} `options` See available [options](#options) for changing how matches are performed
  3564. * @return {Boolean} Returns true if any patterns match `str`
  3565. * @api public
  3566. */
  3567. micromatch$1.all = (str, patterns, options) => {
  3568. if (typeof str !== 'string') {
  3569. throw new TypeError(`Expected a string: "${util.inspect(str)}"`);
  3570. }
  3571. return [].concat(patterns).every(p => picomatch(p, options)(str));
  3572. };
  3573. /**
  3574. * Returns an array of matches captured by `pattern` in `string, or `null` if the pattern did not match.
  3575. *
  3576. * ```js
  3577. * const mm = require('micromatch');
  3578. * // mm.capture(pattern, string[, options]);
  3579. *
  3580. * console.log(mm.capture('test/*.js', 'test/foo.js'));
  3581. * //=> ['foo']
  3582. * console.log(mm.capture('test/*.js', 'foo/bar.css'));
  3583. * //=> null
  3584. * ```
  3585. * @param {String} `glob` Glob pattern to use for matching.
  3586. * @param {String} `input` String to match
  3587. * @param {Object} `options` See available [options](#options) for changing how matches are performed
  3588. * @return {Array|null} Returns an array of captures if the input matches the glob pattern, otherwise `null`.
  3589. * @api public
  3590. */
  3591. micromatch$1.capture = (glob, input, options) => {
  3592. let posix = utils$b.isWindows(options);
  3593. let regex = picomatch.makeRe(String(glob), { ...options, capture: true });
  3594. let match = regex.exec(posix ? utils$b.toPosixSlashes(input) : input);
  3595. if (match) {
  3596. return match.slice(1).map(v => v === void 0 ? '' : v);
  3597. }
  3598. };
  3599. /**
  3600. * Create a regular expression from the given glob `pattern`.
  3601. *
  3602. * ```js
  3603. * const mm = require('micromatch');
  3604. * // mm.makeRe(pattern[, options]);
  3605. *
  3606. * console.log(mm.makeRe('*.js'));
  3607. * //=> /^(?:(\.[\\\/])?(?!\.)(?=.)[^\/]*?\.js)$/
  3608. * ```
  3609. * @param {String} `pattern` A glob pattern to convert to regex.
  3610. * @param {Object} `options`
  3611. * @return {RegExp} Returns a regex created from the given pattern.
  3612. * @api public
  3613. */
  3614. micromatch$1.makeRe = (...args) => picomatch.makeRe(...args);
  3615. /**
  3616. * Scan a glob pattern to separate the pattern into segments. Used
  3617. * by the [split](#split) method.
  3618. *
  3619. * ```js
  3620. * const mm = require('micromatch');
  3621. * const state = mm.scan(pattern[, options]);
  3622. * ```
  3623. * @param {String} `pattern`
  3624. * @param {Object} `options`
  3625. * @return {Object} Returns an object with
  3626. * @api public
  3627. */
  3628. micromatch$1.scan = (...args) => picomatch.scan(...args);
  3629. /**
  3630. * Parse a glob pattern to create the source string for a regular
  3631. * expression.
  3632. *
  3633. * ```js
  3634. * const mm = require('micromatch');
  3635. * const state = mm.parse(pattern[, options]);
  3636. * ```
  3637. * @param {String} `glob`
  3638. * @param {Object} `options`
  3639. * @return {Object} Returns an object with useful properties and output to be used as regex source string.
  3640. * @api public
  3641. */
  3642. micromatch$1.parse = (patterns, options) => {
  3643. let res = [];
  3644. for (let pattern of [].concat(patterns || [])) {
  3645. for (let str of braces(String(pattern), options)) {
  3646. res.push(picomatch.parse(str, options));
  3647. }
  3648. }
  3649. return res;
  3650. };
  3651. /**
  3652. * Process the given brace `pattern`.
  3653. *
  3654. * ```js
  3655. * const { braces } = require('micromatch');
  3656. * console.log(braces('foo/{a,b,c}/bar'));
  3657. * //=> [ 'foo/(a|b|c)/bar' ]
  3658. *
  3659. * console.log(braces('foo/{a,b,c}/bar', { expand: true }));
  3660. * //=> [ 'foo/a/bar', 'foo/b/bar', 'foo/c/bar' ]
  3661. * ```
  3662. * @param {String} `pattern` String with brace pattern to process.
  3663. * @param {Object} `options` Any [options](#options) to change how expansion is performed. See the [braces][] library for all available options.
  3664. * @return {Array}
  3665. * @api public
  3666. */
  3667. micromatch$1.braces = (pattern, options) => {
  3668. if (typeof pattern !== 'string') throw new TypeError('Expected a string');
  3669. if ((options && options.nobrace === true) || !/\{.*\}/.test(pattern)) {
  3670. return [pattern];
  3671. }
  3672. return braces(pattern, options);
  3673. };
  3674. /**
  3675. * Expand braces
  3676. */
  3677. micromatch$1.braceExpand = (pattern, options) => {
  3678. if (typeof pattern !== 'string') throw new TypeError('Expected a string');
  3679. return micromatch$1.braces(pattern, { ...options, expand: true });
  3680. };
  3681. /**
  3682. * Expose micromatch
  3683. */
  3684. var micromatch_1 = micromatch$1;
  3685. Object.defineProperty(pattern$1, "__esModule", { value: true });
  3686. 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;
  3687. const path$5 = path$a;
  3688. const globParent = globParent$1;
  3689. const micromatch = micromatch_1;
  3690. const GLOBSTAR = '**';
  3691. const ESCAPE_SYMBOL = '\\';
  3692. const COMMON_GLOB_SYMBOLS_RE = /[*?]|^!/;
  3693. const REGEX_CHARACTER_CLASS_SYMBOLS_RE = /\[[^[]*]/;
  3694. const REGEX_GROUP_SYMBOLS_RE = /(?:^|[^!*+?@])\([^(]*\|[^|]*\)/;
  3695. const GLOB_EXTENSION_SYMBOLS_RE = /[!*+?@]\([^(]*\)/;
  3696. const BRACE_EXPANSION_SEPARATORS_RE = /,|\.\./;
  3697. function isStaticPattern(pattern, options = {}) {
  3698. return !isDynamicPattern(pattern, options);
  3699. }
  3700. pattern$1.isStaticPattern = isStaticPattern;
  3701. function isDynamicPattern(pattern, options = {}) {
  3702. /**
  3703. * A special case with an empty string is necessary for matching patterns that start with a forward slash.
  3704. * An empty string cannot be a dynamic pattern.
  3705. * For example, the pattern `/lib/*` will be spread into parts: '', 'lib', '*'.
  3706. */
  3707. if (pattern === '') {
  3708. return false;
  3709. }
  3710. /**
  3711. * When the `caseSensitiveMatch` option is disabled, all patterns must be marked as dynamic, because we cannot check
  3712. * filepath directly (without read directory).
  3713. */
  3714. if (options.caseSensitiveMatch === false || pattern.includes(ESCAPE_SYMBOL)) {
  3715. return true;
  3716. }
  3717. if (COMMON_GLOB_SYMBOLS_RE.test(pattern) || REGEX_CHARACTER_CLASS_SYMBOLS_RE.test(pattern) || REGEX_GROUP_SYMBOLS_RE.test(pattern)) {
  3718. return true;
  3719. }
  3720. if (options.extglob !== false && GLOB_EXTENSION_SYMBOLS_RE.test(pattern)) {
  3721. return true;
  3722. }
  3723. if (options.braceExpansion !== false && hasBraceExpansion(pattern)) {
  3724. return true;
  3725. }
  3726. return false;
  3727. }
  3728. pattern$1.isDynamicPattern = isDynamicPattern;
  3729. function hasBraceExpansion(pattern) {
  3730. const openingBraceIndex = pattern.indexOf('{');
  3731. if (openingBraceIndex === -1) {
  3732. return false;
  3733. }
  3734. const closingBraceIndex = pattern.indexOf('}', openingBraceIndex + 1);
  3735. if (closingBraceIndex === -1) {
  3736. return false;
  3737. }
  3738. const braceContent = pattern.slice(openingBraceIndex, closingBraceIndex);
  3739. return BRACE_EXPANSION_SEPARATORS_RE.test(braceContent);
  3740. }
  3741. function convertToPositivePattern(pattern) {
  3742. return isNegativePattern(pattern) ? pattern.slice(1) : pattern;
  3743. }
  3744. pattern$1.convertToPositivePattern = convertToPositivePattern;
  3745. function convertToNegativePattern(pattern) {
  3746. return '!' + pattern;
  3747. }
  3748. pattern$1.convertToNegativePattern = convertToNegativePattern;
  3749. function isNegativePattern(pattern) {
  3750. return pattern.startsWith('!') && pattern[1] !== '(';
  3751. }
  3752. pattern$1.isNegativePattern = isNegativePattern;
  3753. function isPositivePattern(pattern) {
  3754. return !isNegativePattern(pattern);
  3755. }
  3756. pattern$1.isPositivePattern = isPositivePattern;
  3757. function getNegativePatterns(patterns) {
  3758. return patterns.filter(isNegativePattern);
  3759. }
  3760. pattern$1.getNegativePatterns = getNegativePatterns;
  3761. function getPositivePatterns$1(patterns) {
  3762. return patterns.filter(isPositivePattern);
  3763. }
  3764. pattern$1.getPositivePatterns = getPositivePatterns$1;
  3765. /**
  3766. * Returns patterns that can be applied inside the current directory.
  3767. *
  3768. * @example
  3769. * // ['./*', '*', 'a/*']
  3770. * getPatternsInsideCurrentDirectory(['./*', '*', 'a/*', '../*', './../*'])
  3771. */
  3772. function getPatternsInsideCurrentDirectory(patterns) {
  3773. return patterns.filter((pattern) => !isPatternRelatedToParentDirectory(pattern));
  3774. }
  3775. pattern$1.getPatternsInsideCurrentDirectory = getPatternsInsideCurrentDirectory;
  3776. /**
  3777. * Returns patterns to be expanded relative to (outside) the current directory.
  3778. *
  3779. * @example
  3780. * // ['../*', './../*']
  3781. * getPatternsInsideCurrentDirectory(['./*', '*', 'a/*', '../*', './../*'])
  3782. */
  3783. function getPatternsOutsideCurrentDirectory(patterns) {
  3784. return patterns.filter(isPatternRelatedToParentDirectory);
  3785. }
  3786. pattern$1.getPatternsOutsideCurrentDirectory = getPatternsOutsideCurrentDirectory;
  3787. function isPatternRelatedToParentDirectory(pattern) {
  3788. return pattern.startsWith('..') || pattern.startsWith('./..');
  3789. }
  3790. pattern$1.isPatternRelatedToParentDirectory = isPatternRelatedToParentDirectory;
  3791. function getBaseDirectory(pattern) {
  3792. return globParent(pattern, { flipBackslashes: false });
  3793. }
  3794. pattern$1.getBaseDirectory = getBaseDirectory;
  3795. function hasGlobStar(pattern) {
  3796. return pattern.includes(GLOBSTAR);
  3797. }
  3798. pattern$1.hasGlobStar = hasGlobStar;
  3799. function endsWithSlashGlobStar(pattern) {
  3800. return pattern.endsWith('/' + GLOBSTAR);
  3801. }
  3802. pattern$1.endsWithSlashGlobStar = endsWithSlashGlobStar;
  3803. function isAffectDepthOfReadingPattern(pattern) {
  3804. const basename = path$5.basename(pattern);
  3805. return endsWithSlashGlobStar(pattern) || isStaticPattern(basename);
  3806. }
  3807. pattern$1.isAffectDepthOfReadingPattern = isAffectDepthOfReadingPattern;
  3808. function expandPatternsWithBraceExpansion(patterns) {
  3809. return patterns.reduce((collection, pattern) => {
  3810. return collection.concat(expandBraceExpansion(pattern));
  3811. }, []);
  3812. }
  3813. pattern$1.expandPatternsWithBraceExpansion = expandPatternsWithBraceExpansion;
  3814. function expandBraceExpansion(pattern) {
  3815. return micromatch.braces(pattern, {
  3816. expand: true,
  3817. nodupes: true
  3818. });
  3819. }
  3820. pattern$1.expandBraceExpansion = expandBraceExpansion;
  3821. function getPatternParts(pattern, options) {
  3822. let { parts } = micromatch.scan(pattern, Object.assign(Object.assign({}, options), { parts: true }));
  3823. /**
  3824. * The scan method returns an empty array in some cases.
  3825. * See micromatch/picomatch#58 for more details.
  3826. */
  3827. if (parts.length === 0) {
  3828. parts = [pattern];
  3829. }
  3830. /**
  3831. * The scan method does not return an empty part for the pattern with a forward slash.
  3832. * This is another part of micromatch/picomatch#58.
  3833. */
  3834. if (parts[0].startsWith('/')) {
  3835. parts[0] = parts[0].slice(1);
  3836. parts.unshift('');
  3837. }
  3838. return parts;
  3839. }
  3840. pattern$1.getPatternParts = getPatternParts;
  3841. function makeRe(pattern, options) {
  3842. return micromatch.makeRe(pattern, options);
  3843. }
  3844. pattern$1.makeRe = makeRe;
  3845. function convertPatternsToRe(patterns, options) {
  3846. return patterns.map((pattern) => makeRe(pattern, options));
  3847. }
  3848. pattern$1.convertPatternsToRe = convertPatternsToRe;
  3849. function matchAny(entry, patternsRe) {
  3850. return patternsRe.some((patternRe) => patternRe.test(entry));
  3851. }
  3852. pattern$1.matchAny = matchAny;
  3853. var stream$4 = {};
  3854. /*
  3855. * merge2
  3856. * https://github.com/teambition/merge2
  3857. *
  3858. * Copyright (c) 2014-2020 Teambition
  3859. * Licensed under the MIT license.
  3860. */
  3861. const Stream = require$$0$1;
  3862. const PassThrough = Stream.PassThrough;
  3863. const slice = Array.prototype.slice;
  3864. var merge2_1 = merge2$1;
  3865. function merge2$1 () {
  3866. const streamsQueue = [];
  3867. const args = slice.call(arguments);
  3868. let merging = false;
  3869. let options = args[args.length - 1];
  3870. if (options && !Array.isArray(options) && options.pipe == null) {
  3871. args.pop();
  3872. } else {
  3873. options = {};
  3874. }
  3875. const doEnd = options.end !== false;
  3876. const doPipeError = options.pipeError === true;
  3877. if (options.objectMode == null) {
  3878. options.objectMode = true;
  3879. }
  3880. if (options.highWaterMark == null) {
  3881. options.highWaterMark = 64 * 1024;
  3882. }
  3883. const mergedStream = PassThrough(options);
  3884. function addStream () {
  3885. for (let i = 0, len = arguments.length; i < len; i++) {
  3886. streamsQueue.push(pauseStreams(arguments[i], options));
  3887. }
  3888. mergeStream();
  3889. return this
  3890. }
  3891. function mergeStream () {
  3892. if (merging) {
  3893. return
  3894. }
  3895. merging = true;
  3896. let streams = streamsQueue.shift();
  3897. if (!streams) {
  3898. process.nextTick(endStream);
  3899. return
  3900. }
  3901. if (!Array.isArray(streams)) {
  3902. streams = [streams];
  3903. }
  3904. let pipesCount = streams.length + 1;
  3905. function next () {
  3906. if (--pipesCount > 0) {
  3907. return
  3908. }
  3909. merging = false;
  3910. mergeStream();
  3911. }
  3912. function pipe (stream) {
  3913. function onend () {
  3914. stream.removeListener('merge2UnpipeEnd', onend);
  3915. stream.removeListener('end', onend);
  3916. if (doPipeError) {
  3917. stream.removeListener('error', onerror);
  3918. }
  3919. next();
  3920. }
  3921. function onerror (err) {
  3922. mergedStream.emit('error', err);
  3923. }
  3924. // skip ended stream
  3925. if (stream._readableState.endEmitted) {
  3926. return next()
  3927. }
  3928. stream.on('merge2UnpipeEnd', onend);
  3929. stream.on('end', onend);
  3930. if (doPipeError) {
  3931. stream.on('error', onerror);
  3932. }
  3933. stream.pipe(mergedStream, { end: false });
  3934. // compatible for old stream
  3935. stream.resume();
  3936. }
  3937. for (let i = 0; i < streams.length; i++) {
  3938. pipe(streams[i]);
  3939. }
  3940. next();
  3941. }
  3942. function endStream () {
  3943. merging = false;
  3944. // emit 'queueDrain' when all streams merged.
  3945. mergedStream.emit('queueDrain');
  3946. if (doEnd) {
  3947. mergedStream.end();
  3948. }
  3949. }
  3950. mergedStream.setMaxListeners(0);
  3951. mergedStream.add = addStream;
  3952. mergedStream.on('unpipe', function (stream) {
  3953. stream.emit('merge2UnpipeEnd');
  3954. });
  3955. if (args.length) {
  3956. addStream.apply(null, args);
  3957. }
  3958. return mergedStream
  3959. }
  3960. // check and pause streams for pipe.
  3961. function pauseStreams (streams, options) {
  3962. if (!Array.isArray(streams)) {
  3963. // Backwards-compat with old-style streams
  3964. if (!streams._readableState && streams.pipe) {
  3965. streams = streams.pipe(PassThrough(options));
  3966. }
  3967. if (!streams._readableState || !streams.pause || !streams.pipe) {
  3968. throw new Error('Only readable stream can be merged.')
  3969. }
  3970. streams.pause();
  3971. } else {
  3972. for (let i = 0, len = streams.length; i < len; i++) {
  3973. streams[i] = pauseStreams(streams[i], options);
  3974. }
  3975. }
  3976. return streams
  3977. }
  3978. Object.defineProperty(stream$4, "__esModule", { value: true });
  3979. stream$4.merge = void 0;
  3980. const merge2 = merge2_1;
  3981. function merge(streams) {
  3982. const mergedStream = merge2(streams);
  3983. streams.forEach((stream) => {
  3984. stream.once('error', (error) => mergedStream.emit('error', error));
  3985. });
  3986. mergedStream.once('close', () => propagateCloseEventToSources(streams));
  3987. mergedStream.once('end', () => propagateCloseEventToSources(streams));
  3988. return mergedStream;
  3989. }
  3990. stream$4.merge = merge;
  3991. function propagateCloseEventToSources(streams) {
  3992. streams.forEach((stream) => stream.emit('close'));
  3993. }
  3994. var string$1 = {};
  3995. Object.defineProperty(string$1, "__esModule", { value: true });
  3996. string$1.isEmpty = string$1.isString = void 0;
  3997. function isString(input) {
  3998. return typeof input === 'string';
  3999. }
  4000. string$1.isString = isString;
  4001. function isEmpty(input) {
  4002. return input === '';
  4003. }
  4004. string$1.isEmpty = isEmpty;
  4005. Object.defineProperty(utils$k, "__esModule", { value: true });
  4006. utils$k.string = utils$k.stream = utils$k.pattern = utils$k.path = utils$k.fs = utils$k.errno = utils$k.array = void 0;
  4007. const array = array$1;
  4008. utils$k.array = array;
  4009. const errno = errno$1;
  4010. utils$k.errno = errno;
  4011. const fs$6 = fs$7;
  4012. utils$k.fs = fs$6;
  4013. const path$4 = path$9;
  4014. utils$k.path = path$4;
  4015. const pattern = pattern$1;
  4016. utils$k.pattern = pattern;
  4017. const stream$3 = stream$4;
  4018. utils$k.stream = stream$3;
  4019. const string = string$1;
  4020. utils$k.string = string;
  4021. Object.defineProperty(tasks, "__esModule", { value: true });
  4022. tasks.convertPatternGroupToTask = tasks.convertPatternGroupsToTasks = tasks.groupPatternsByBaseDirectory = tasks.getNegativePatternsAsPositive = tasks.getPositivePatterns = tasks.convertPatternsToTasks = tasks.generate = void 0;
  4023. const utils$a = utils$k;
  4024. function generate(patterns, settings) {
  4025. const positivePatterns = getPositivePatterns(patterns);
  4026. const negativePatterns = getNegativePatternsAsPositive(patterns, settings.ignore);
  4027. const staticPatterns = positivePatterns.filter((pattern) => utils$a.pattern.isStaticPattern(pattern, settings));
  4028. const dynamicPatterns = positivePatterns.filter((pattern) => utils$a.pattern.isDynamicPattern(pattern, settings));
  4029. const staticTasks = convertPatternsToTasks(staticPatterns, negativePatterns, /* dynamic */ false);
  4030. const dynamicTasks = convertPatternsToTasks(dynamicPatterns, negativePatterns, /* dynamic */ true);
  4031. return staticTasks.concat(dynamicTasks);
  4032. }
  4033. tasks.generate = generate;
  4034. /**
  4035. * Returns tasks grouped by basic pattern directories.
  4036. *
  4037. * Patterns that can be found inside (`./`) and outside (`../`) the current directory are handled separately.
  4038. * This is necessary because directory traversal starts at the base directory and goes deeper.
  4039. */
  4040. function convertPatternsToTasks(positive, negative, dynamic) {
  4041. const tasks = [];
  4042. const patternsOutsideCurrentDirectory = utils$a.pattern.getPatternsOutsideCurrentDirectory(positive);
  4043. const patternsInsideCurrentDirectory = utils$a.pattern.getPatternsInsideCurrentDirectory(positive);
  4044. const outsideCurrentDirectoryGroup = groupPatternsByBaseDirectory(patternsOutsideCurrentDirectory);
  4045. const insideCurrentDirectoryGroup = groupPatternsByBaseDirectory(patternsInsideCurrentDirectory);
  4046. tasks.push(...convertPatternGroupsToTasks(outsideCurrentDirectoryGroup, negative, dynamic));
  4047. /*
  4048. * For the sake of reducing future accesses to the file system, we merge all tasks within the current directory
  4049. * into a global task, if at least one pattern refers to the root (`.`). In this case, the global task covers the rest.
  4050. */
  4051. if ('.' in insideCurrentDirectoryGroup) {
  4052. tasks.push(convertPatternGroupToTask('.', patternsInsideCurrentDirectory, negative, dynamic));
  4053. }
  4054. else {
  4055. tasks.push(...convertPatternGroupsToTasks(insideCurrentDirectoryGroup, negative, dynamic));
  4056. }
  4057. return tasks;
  4058. }
  4059. tasks.convertPatternsToTasks = convertPatternsToTasks;
  4060. function getPositivePatterns(patterns) {
  4061. return utils$a.pattern.getPositivePatterns(patterns);
  4062. }
  4063. tasks.getPositivePatterns = getPositivePatterns;
  4064. function getNegativePatternsAsPositive(patterns, ignore) {
  4065. const negative = utils$a.pattern.getNegativePatterns(patterns).concat(ignore);
  4066. const positive = negative.map(utils$a.pattern.convertToPositivePattern);
  4067. return positive;
  4068. }
  4069. tasks.getNegativePatternsAsPositive = getNegativePatternsAsPositive;
  4070. function groupPatternsByBaseDirectory(patterns) {
  4071. const group = {};
  4072. return patterns.reduce((collection, pattern) => {
  4073. const base = utils$a.pattern.getBaseDirectory(pattern);
  4074. if (base in collection) {
  4075. collection[base].push(pattern);
  4076. }
  4077. else {
  4078. collection[base] = [pattern];
  4079. }
  4080. return collection;
  4081. }, group);
  4082. }
  4083. tasks.groupPatternsByBaseDirectory = groupPatternsByBaseDirectory;
  4084. function convertPatternGroupsToTasks(positive, negative, dynamic) {
  4085. return Object.keys(positive).map((base) => {
  4086. return convertPatternGroupToTask(base, positive[base], negative, dynamic);
  4087. });
  4088. }
  4089. tasks.convertPatternGroupsToTasks = convertPatternGroupsToTasks;
  4090. function convertPatternGroupToTask(base, positive, negative, dynamic) {
  4091. return {
  4092. dynamic,
  4093. positive,
  4094. negative,
  4095. base,
  4096. patterns: [].concat(positive, negative.map(utils$a.pattern.convertToNegativePattern))
  4097. };
  4098. }
  4099. tasks.convertPatternGroupToTask = convertPatternGroupToTask;
  4100. var patterns = {};
  4101. Object.defineProperty(patterns, "__esModule", { value: true });
  4102. patterns.removeDuplicateSlashes = patterns.transform = void 0;
  4103. /**
  4104. * Matches a sequence of two or more consecutive slashes, excluding the first two slashes at the beginning of the string.
  4105. * The latter is due to the presence of the device path at the beginning of the UNC path.
  4106. * @todo rewrite to negative lookbehind with the next major release.
  4107. */
  4108. const DOUBLE_SLASH_RE = /(?!^)\/{2,}/g;
  4109. function transform(patterns) {
  4110. return patterns.map((pattern) => removeDuplicateSlashes(pattern));
  4111. }
  4112. patterns.transform = transform;
  4113. /**
  4114. * This package only works with forward slashes as a path separator.
  4115. * Because of this, we cannot use the standard `path.normalize` method, because on Windows platform it will use of backslashes.
  4116. */
  4117. function removeDuplicateSlashes(pattern) {
  4118. return pattern.replace(DOUBLE_SLASH_RE, '/');
  4119. }
  4120. patterns.removeDuplicateSlashes = removeDuplicateSlashes;
  4121. var async$7 = {};
  4122. var async$6 = {};
  4123. var out$3 = {};
  4124. var async$5 = {};
  4125. var async$4 = {};
  4126. var out$2 = {};
  4127. var async$3 = {};
  4128. var out$1 = {};
  4129. var async$2 = {};
  4130. Object.defineProperty(async$2, "__esModule", { value: true });
  4131. async$2.read = void 0;
  4132. function read$3(path, settings, callback) {
  4133. settings.fs.lstat(path, (lstatError, lstat) => {
  4134. if (lstatError !== null) {
  4135. callFailureCallback$2(callback, lstatError);
  4136. return;
  4137. }
  4138. if (!lstat.isSymbolicLink() || !settings.followSymbolicLink) {
  4139. callSuccessCallback$2(callback, lstat);
  4140. return;
  4141. }
  4142. settings.fs.stat(path, (statError, stat) => {
  4143. if (statError !== null) {
  4144. if (settings.throwErrorOnBrokenSymbolicLink) {
  4145. callFailureCallback$2(callback, statError);
  4146. return;
  4147. }
  4148. callSuccessCallback$2(callback, lstat);
  4149. return;
  4150. }
  4151. if (settings.markSymbolicLink) {
  4152. stat.isSymbolicLink = () => true;
  4153. }
  4154. callSuccessCallback$2(callback, stat);
  4155. });
  4156. });
  4157. }
  4158. async$2.read = read$3;
  4159. function callFailureCallback$2(callback, error) {
  4160. callback(error);
  4161. }
  4162. function callSuccessCallback$2(callback, result) {
  4163. callback(null, result);
  4164. }
  4165. var sync$7 = {};
  4166. Object.defineProperty(sync$7, "__esModule", { value: true });
  4167. sync$7.read = void 0;
  4168. function read$2(path, settings) {
  4169. const lstat = settings.fs.lstatSync(path);
  4170. if (!lstat.isSymbolicLink() || !settings.followSymbolicLink) {
  4171. return lstat;
  4172. }
  4173. try {
  4174. const stat = settings.fs.statSync(path);
  4175. if (settings.markSymbolicLink) {
  4176. stat.isSymbolicLink = () => true;
  4177. }
  4178. return stat;
  4179. }
  4180. catch (error) {
  4181. if (!settings.throwErrorOnBrokenSymbolicLink) {
  4182. return lstat;
  4183. }
  4184. throw error;
  4185. }
  4186. }
  4187. sync$7.read = read$2;
  4188. var settings$3 = {};
  4189. var fs$5 = {};
  4190. (function (exports) {
  4191. Object.defineProperty(exports, "__esModule", { value: true });
  4192. exports.createFileSystemAdapter = exports.FILE_SYSTEM_ADAPTER = void 0;
  4193. const fs = fs$8;
  4194. exports.FILE_SYSTEM_ADAPTER = {
  4195. lstat: fs.lstat,
  4196. stat: fs.stat,
  4197. lstatSync: fs.lstatSync,
  4198. statSync: fs.statSync
  4199. };
  4200. function createFileSystemAdapter(fsMethods) {
  4201. if (fsMethods === undefined) {
  4202. return exports.FILE_SYSTEM_ADAPTER;
  4203. }
  4204. return Object.assign(Object.assign({}, exports.FILE_SYSTEM_ADAPTER), fsMethods);
  4205. }
  4206. exports.createFileSystemAdapter = createFileSystemAdapter;
  4207. } (fs$5));
  4208. Object.defineProperty(settings$3, "__esModule", { value: true });
  4209. const fs$4 = fs$5;
  4210. class Settings$2 {
  4211. constructor(_options = {}) {
  4212. this._options = _options;
  4213. this.followSymbolicLink = this._getValue(this._options.followSymbolicLink, true);
  4214. this.fs = fs$4.createFileSystemAdapter(this._options.fs);
  4215. this.markSymbolicLink = this._getValue(this._options.markSymbolicLink, false);
  4216. this.throwErrorOnBrokenSymbolicLink = this._getValue(this._options.throwErrorOnBrokenSymbolicLink, true);
  4217. }
  4218. _getValue(option, value) {
  4219. return option !== null && option !== void 0 ? option : value;
  4220. }
  4221. }
  4222. settings$3.default = Settings$2;
  4223. Object.defineProperty(out$1, "__esModule", { value: true });
  4224. out$1.statSync = out$1.stat = out$1.Settings = void 0;
  4225. const async$1 = async$2;
  4226. const sync$6 = sync$7;
  4227. const settings_1$3 = settings$3;
  4228. out$1.Settings = settings_1$3.default;
  4229. function stat(path, optionsOrSettingsOrCallback, callback) {
  4230. if (typeof optionsOrSettingsOrCallback === 'function') {
  4231. async$1.read(path, getSettings$2(), optionsOrSettingsOrCallback);
  4232. return;
  4233. }
  4234. async$1.read(path, getSettings$2(optionsOrSettingsOrCallback), callback);
  4235. }
  4236. out$1.stat = stat;
  4237. function statSync(path, optionsOrSettings) {
  4238. const settings = getSettings$2(optionsOrSettings);
  4239. return sync$6.read(path, settings);
  4240. }
  4241. out$1.statSync = statSync;
  4242. function getSettings$2(settingsOrOptions = {}) {
  4243. if (settingsOrOptions instanceof settings_1$3.default) {
  4244. return settingsOrOptions;
  4245. }
  4246. return new settings_1$3.default(settingsOrOptions);
  4247. }
  4248. /*! queue-microtask. MIT License. Feross Aboukhadijeh <https://feross.org/opensource> */
  4249. let promise;
  4250. var queueMicrotask_1 = typeof queueMicrotask === 'function'
  4251. ? queueMicrotask.bind(typeof window !== 'undefined' ? window : commonjsGlobal)
  4252. // reuse resolved promise, and allocate it lazily
  4253. : cb => (promise || (promise = Promise.resolve()))
  4254. .then(cb)
  4255. .catch(err => setTimeout(() => { throw err }, 0));
  4256. /*! run-parallel. MIT License. Feross Aboukhadijeh <https://feross.org/opensource> */
  4257. var runParallel_1 = runParallel;
  4258. const queueMicrotask$1 = queueMicrotask_1;
  4259. function runParallel (tasks, cb) {
  4260. let results, pending, keys;
  4261. let isSync = true;
  4262. if (Array.isArray(tasks)) {
  4263. results = [];
  4264. pending = tasks.length;
  4265. } else {
  4266. keys = Object.keys(tasks);
  4267. results = {};
  4268. pending = keys.length;
  4269. }
  4270. function done (err) {
  4271. function end () {
  4272. if (cb) cb(err, results);
  4273. cb = null;
  4274. }
  4275. if (isSync) queueMicrotask$1(end);
  4276. else end();
  4277. }
  4278. function each (i, err, result) {
  4279. results[i] = result;
  4280. if (--pending === 0 || err) {
  4281. done(err);
  4282. }
  4283. }
  4284. if (!pending) {
  4285. // empty
  4286. done(null);
  4287. } else if (keys) {
  4288. // object
  4289. keys.forEach(function (key) {
  4290. tasks[key](function (err, result) { each(key, err, result); });
  4291. });
  4292. } else {
  4293. // array
  4294. tasks.forEach(function (task, i) {
  4295. task(function (err, result) { each(i, err, result); });
  4296. });
  4297. }
  4298. isSync = false;
  4299. }
  4300. var constants = {};
  4301. Object.defineProperty(constants, "__esModule", { value: true });
  4302. constants.IS_SUPPORT_READDIR_WITH_FILE_TYPES = void 0;
  4303. const NODE_PROCESS_VERSION_PARTS = process.versions.node.split('.');
  4304. if (NODE_PROCESS_VERSION_PARTS[0] === undefined || NODE_PROCESS_VERSION_PARTS[1] === undefined) {
  4305. throw new Error(`Unexpected behavior. The 'process.versions.node' variable has invalid value: ${process.versions.node}`);
  4306. }
  4307. const MAJOR_VERSION = Number.parseInt(NODE_PROCESS_VERSION_PARTS[0], 10);
  4308. const MINOR_VERSION = Number.parseInt(NODE_PROCESS_VERSION_PARTS[1], 10);
  4309. const SUPPORTED_MAJOR_VERSION = 10;
  4310. const SUPPORTED_MINOR_VERSION = 10;
  4311. const IS_MATCHED_BY_MAJOR = MAJOR_VERSION > SUPPORTED_MAJOR_VERSION;
  4312. const IS_MATCHED_BY_MAJOR_AND_MINOR = MAJOR_VERSION === SUPPORTED_MAJOR_VERSION && MINOR_VERSION >= SUPPORTED_MINOR_VERSION;
  4313. /**
  4314. * IS `true` for Node.js 10.10 and greater.
  4315. */
  4316. constants.IS_SUPPORT_READDIR_WITH_FILE_TYPES = IS_MATCHED_BY_MAJOR || IS_MATCHED_BY_MAJOR_AND_MINOR;
  4317. var utils$9 = {};
  4318. var fs$3 = {};
  4319. Object.defineProperty(fs$3, "__esModule", { value: true });
  4320. fs$3.createDirentFromStats = void 0;
  4321. class DirentFromStats {
  4322. constructor(name, stats) {
  4323. this.name = name;
  4324. this.isBlockDevice = stats.isBlockDevice.bind(stats);
  4325. this.isCharacterDevice = stats.isCharacterDevice.bind(stats);
  4326. this.isDirectory = stats.isDirectory.bind(stats);
  4327. this.isFIFO = stats.isFIFO.bind(stats);
  4328. this.isFile = stats.isFile.bind(stats);
  4329. this.isSocket = stats.isSocket.bind(stats);
  4330. this.isSymbolicLink = stats.isSymbolicLink.bind(stats);
  4331. }
  4332. }
  4333. function createDirentFromStats(name, stats) {
  4334. return new DirentFromStats(name, stats);
  4335. }
  4336. fs$3.createDirentFromStats = createDirentFromStats;
  4337. Object.defineProperty(utils$9, "__esModule", { value: true });
  4338. utils$9.fs = void 0;
  4339. const fs$2 = fs$3;
  4340. utils$9.fs = fs$2;
  4341. var common$6 = {};
  4342. Object.defineProperty(common$6, "__esModule", { value: true });
  4343. common$6.joinPathSegments = void 0;
  4344. function joinPathSegments$1(a, b, separator) {
  4345. /**
  4346. * The correct handling of cases when the first segment is a root (`/`, `C:/`) or UNC path (`//?/C:/`).
  4347. */
  4348. if (a.endsWith(separator)) {
  4349. return a + b;
  4350. }
  4351. return a + separator + b;
  4352. }
  4353. common$6.joinPathSegments = joinPathSegments$1;
  4354. Object.defineProperty(async$3, "__esModule", { value: true });
  4355. async$3.readdir = async$3.readdirWithFileTypes = async$3.read = void 0;
  4356. const fsStat$5 = out$1;
  4357. const rpl = runParallel_1;
  4358. const constants_1$1 = constants;
  4359. const utils$8 = utils$9;
  4360. const common$5 = common$6;
  4361. function read$1(directory, settings, callback) {
  4362. if (!settings.stats && constants_1$1.IS_SUPPORT_READDIR_WITH_FILE_TYPES) {
  4363. readdirWithFileTypes$1(directory, settings, callback);
  4364. return;
  4365. }
  4366. readdir$1(directory, settings, callback);
  4367. }
  4368. async$3.read = read$1;
  4369. function readdirWithFileTypes$1(directory, settings, callback) {
  4370. settings.fs.readdir(directory, { withFileTypes: true }, (readdirError, dirents) => {
  4371. if (readdirError !== null) {
  4372. callFailureCallback$1(callback, readdirError);
  4373. return;
  4374. }
  4375. const entries = dirents.map((dirent) => ({
  4376. dirent,
  4377. name: dirent.name,
  4378. path: common$5.joinPathSegments(directory, dirent.name, settings.pathSegmentSeparator)
  4379. }));
  4380. if (!settings.followSymbolicLinks) {
  4381. callSuccessCallback$1(callback, entries);
  4382. return;
  4383. }
  4384. const tasks = entries.map((entry) => makeRplTaskEntry(entry, settings));
  4385. rpl(tasks, (rplError, rplEntries) => {
  4386. if (rplError !== null) {
  4387. callFailureCallback$1(callback, rplError);
  4388. return;
  4389. }
  4390. callSuccessCallback$1(callback, rplEntries);
  4391. });
  4392. });
  4393. }
  4394. async$3.readdirWithFileTypes = readdirWithFileTypes$1;
  4395. function makeRplTaskEntry(entry, settings) {
  4396. return (done) => {
  4397. if (!entry.dirent.isSymbolicLink()) {
  4398. done(null, entry);
  4399. return;
  4400. }
  4401. settings.fs.stat(entry.path, (statError, stats) => {
  4402. if (statError !== null) {
  4403. if (settings.throwErrorOnBrokenSymbolicLink) {
  4404. done(statError);
  4405. return;
  4406. }
  4407. done(null, entry);
  4408. return;
  4409. }
  4410. entry.dirent = utils$8.fs.createDirentFromStats(entry.name, stats);
  4411. done(null, entry);
  4412. });
  4413. };
  4414. }
  4415. function readdir$1(directory, settings, callback) {
  4416. settings.fs.readdir(directory, (readdirError, names) => {
  4417. if (readdirError !== null) {
  4418. callFailureCallback$1(callback, readdirError);
  4419. return;
  4420. }
  4421. const tasks = names.map((name) => {
  4422. const path = common$5.joinPathSegments(directory, name, settings.pathSegmentSeparator);
  4423. return (done) => {
  4424. fsStat$5.stat(path, settings.fsStatSettings, (error, stats) => {
  4425. if (error !== null) {
  4426. done(error);
  4427. return;
  4428. }
  4429. const entry = {
  4430. name,
  4431. path,
  4432. dirent: utils$8.fs.createDirentFromStats(name, stats)
  4433. };
  4434. if (settings.stats) {
  4435. entry.stats = stats;
  4436. }
  4437. done(null, entry);
  4438. });
  4439. };
  4440. });
  4441. rpl(tasks, (rplError, entries) => {
  4442. if (rplError !== null) {
  4443. callFailureCallback$1(callback, rplError);
  4444. return;
  4445. }
  4446. callSuccessCallback$1(callback, entries);
  4447. });
  4448. });
  4449. }
  4450. async$3.readdir = readdir$1;
  4451. function callFailureCallback$1(callback, error) {
  4452. callback(error);
  4453. }
  4454. function callSuccessCallback$1(callback, result) {
  4455. callback(null, result);
  4456. }
  4457. var sync$5 = {};
  4458. Object.defineProperty(sync$5, "__esModule", { value: true });
  4459. sync$5.readdir = sync$5.readdirWithFileTypes = sync$5.read = void 0;
  4460. const fsStat$4 = out$1;
  4461. const constants_1 = constants;
  4462. const utils$7 = utils$9;
  4463. const common$4 = common$6;
  4464. function read(directory, settings) {
  4465. if (!settings.stats && constants_1.IS_SUPPORT_READDIR_WITH_FILE_TYPES) {
  4466. return readdirWithFileTypes(directory, settings);
  4467. }
  4468. return readdir(directory, settings);
  4469. }
  4470. sync$5.read = read;
  4471. function readdirWithFileTypes(directory, settings) {
  4472. const dirents = settings.fs.readdirSync(directory, { withFileTypes: true });
  4473. return dirents.map((dirent) => {
  4474. const entry = {
  4475. dirent,
  4476. name: dirent.name,
  4477. path: common$4.joinPathSegments(directory, dirent.name, settings.pathSegmentSeparator)
  4478. };
  4479. if (entry.dirent.isSymbolicLink() && settings.followSymbolicLinks) {
  4480. try {
  4481. const stats = settings.fs.statSync(entry.path);
  4482. entry.dirent = utils$7.fs.createDirentFromStats(entry.name, stats);
  4483. }
  4484. catch (error) {
  4485. if (settings.throwErrorOnBrokenSymbolicLink) {
  4486. throw error;
  4487. }
  4488. }
  4489. }
  4490. return entry;
  4491. });
  4492. }
  4493. sync$5.readdirWithFileTypes = readdirWithFileTypes;
  4494. function readdir(directory, settings) {
  4495. const names = settings.fs.readdirSync(directory);
  4496. return names.map((name) => {
  4497. const entryPath = common$4.joinPathSegments(directory, name, settings.pathSegmentSeparator);
  4498. const stats = fsStat$4.statSync(entryPath, settings.fsStatSettings);
  4499. const entry = {
  4500. name,
  4501. path: entryPath,
  4502. dirent: utils$7.fs.createDirentFromStats(name, stats)
  4503. };
  4504. if (settings.stats) {
  4505. entry.stats = stats;
  4506. }
  4507. return entry;
  4508. });
  4509. }
  4510. sync$5.readdir = readdir;
  4511. var settings$2 = {};
  4512. var fs$1 = {};
  4513. (function (exports) {
  4514. Object.defineProperty(exports, "__esModule", { value: true });
  4515. exports.createFileSystemAdapter = exports.FILE_SYSTEM_ADAPTER = void 0;
  4516. const fs = fs$8;
  4517. exports.FILE_SYSTEM_ADAPTER = {
  4518. lstat: fs.lstat,
  4519. stat: fs.stat,
  4520. lstatSync: fs.lstatSync,
  4521. statSync: fs.statSync,
  4522. readdir: fs.readdir,
  4523. readdirSync: fs.readdirSync
  4524. };
  4525. function createFileSystemAdapter(fsMethods) {
  4526. if (fsMethods === undefined) {
  4527. return exports.FILE_SYSTEM_ADAPTER;
  4528. }
  4529. return Object.assign(Object.assign({}, exports.FILE_SYSTEM_ADAPTER), fsMethods);
  4530. }
  4531. exports.createFileSystemAdapter = createFileSystemAdapter;
  4532. } (fs$1));
  4533. Object.defineProperty(settings$2, "__esModule", { value: true });
  4534. const path$3 = path$a;
  4535. const fsStat$3 = out$1;
  4536. const fs = fs$1;
  4537. class Settings$1 {
  4538. constructor(_options = {}) {
  4539. this._options = _options;
  4540. this.followSymbolicLinks = this._getValue(this._options.followSymbolicLinks, false);
  4541. this.fs = fs.createFileSystemAdapter(this._options.fs);
  4542. this.pathSegmentSeparator = this._getValue(this._options.pathSegmentSeparator, path$3.sep);
  4543. this.stats = this._getValue(this._options.stats, false);
  4544. this.throwErrorOnBrokenSymbolicLink = this._getValue(this._options.throwErrorOnBrokenSymbolicLink, true);
  4545. this.fsStatSettings = new fsStat$3.Settings({
  4546. followSymbolicLink: this.followSymbolicLinks,
  4547. fs: this.fs,
  4548. throwErrorOnBrokenSymbolicLink: this.throwErrorOnBrokenSymbolicLink
  4549. });
  4550. }
  4551. _getValue(option, value) {
  4552. return option !== null && option !== void 0 ? option : value;
  4553. }
  4554. }
  4555. settings$2.default = Settings$1;
  4556. Object.defineProperty(out$2, "__esModule", { value: true });
  4557. out$2.Settings = out$2.scandirSync = out$2.scandir = void 0;
  4558. const async = async$3;
  4559. const sync$4 = sync$5;
  4560. const settings_1$2 = settings$2;
  4561. out$2.Settings = settings_1$2.default;
  4562. function scandir(path, optionsOrSettingsOrCallback, callback) {
  4563. if (typeof optionsOrSettingsOrCallback === 'function') {
  4564. async.read(path, getSettings$1(), optionsOrSettingsOrCallback);
  4565. return;
  4566. }
  4567. async.read(path, getSettings$1(optionsOrSettingsOrCallback), callback);
  4568. }
  4569. out$2.scandir = scandir;
  4570. function scandirSync(path, optionsOrSettings) {
  4571. const settings = getSettings$1(optionsOrSettings);
  4572. return sync$4.read(path, settings);
  4573. }
  4574. out$2.scandirSync = scandirSync;
  4575. function getSettings$1(settingsOrOptions = {}) {
  4576. if (settingsOrOptions instanceof settings_1$2.default) {
  4577. return settingsOrOptions;
  4578. }
  4579. return new settings_1$2.default(settingsOrOptions);
  4580. }
  4581. var queue = {exports: {}};
  4582. function reusify$1 (Constructor) {
  4583. var head = new Constructor();
  4584. var tail = head;
  4585. function get () {
  4586. var current = head;
  4587. if (current.next) {
  4588. head = current.next;
  4589. } else {
  4590. head = new Constructor();
  4591. tail = head;
  4592. }
  4593. current.next = null;
  4594. return current
  4595. }
  4596. function release (obj) {
  4597. tail.next = obj;
  4598. tail = obj;
  4599. }
  4600. return {
  4601. get: get,
  4602. release: release
  4603. }
  4604. }
  4605. var reusify_1 = reusify$1;
  4606. /* eslint-disable no-var */
  4607. var reusify = reusify_1;
  4608. function fastqueue (context, worker, concurrency) {
  4609. if (typeof context === 'function') {
  4610. concurrency = worker;
  4611. worker = context;
  4612. context = null;
  4613. }
  4614. if (concurrency < 1) {
  4615. throw new Error('fastqueue concurrency must be greater than 1')
  4616. }
  4617. var cache = reusify(Task);
  4618. var queueHead = null;
  4619. var queueTail = null;
  4620. var _running = 0;
  4621. var errorHandler = null;
  4622. var self = {
  4623. push: push,
  4624. drain: noop,
  4625. saturated: noop,
  4626. pause: pause,
  4627. paused: false,
  4628. concurrency: concurrency,
  4629. running: running,
  4630. resume: resume,
  4631. idle: idle,
  4632. length: length,
  4633. getQueue: getQueue,
  4634. unshift: unshift,
  4635. empty: noop,
  4636. kill: kill,
  4637. killAndDrain: killAndDrain,
  4638. error: error
  4639. };
  4640. return self
  4641. function running () {
  4642. return _running
  4643. }
  4644. function pause () {
  4645. self.paused = true;
  4646. }
  4647. function length () {
  4648. var current = queueHead;
  4649. var counter = 0;
  4650. while (current) {
  4651. current = current.next;
  4652. counter++;
  4653. }
  4654. return counter
  4655. }
  4656. function getQueue () {
  4657. var current = queueHead;
  4658. var tasks = [];
  4659. while (current) {
  4660. tasks.push(current.value);
  4661. current = current.next;
  4662. }
  4663. return tasks
  4664. }
  4665. function resume () {
  4666. if (!self.paused) return
  4667. self.paused = false;
  4668. for (var i = 0; i < self.concurrency; i++) {
  4669. _running++;
  4670. release();
  4671. }
  4672. }
  4673. function idle () {
  4674. return _running === 0 && self.length() === 0
  4675. }
  4676. function push (value, done) {
  4677. var current = cache.get();
  4678. current.context = context;
  4679. current.release = release;
  4680. current.value = value;
  4681. current.callback = done || noop;
  4682. current.errorHandler = errorHandler;
  4683. if (_running === self.concurrency || self.paused) {
  4684. if (queueTail) {
  4685. queueTail.next = current;
  4686. queueTail = current;
  4687. } else {
  4688. queueHead = current;
  4689. queueTail = current;
  4690. self.saturated();
  4691. }
  4692. } else {
  4693. _running++;
  4694. worker.call(context, current.value, current.worked);
  4695. }
  4696. }
  4697. function unshift (value, done) {
  4698. var current = cache.get();
  4699. current.context = context;
  4700. current.release = release;
  4701. current.value = value;
  4702. current.callback = done || noop;
  4703. if (_running === self.concurrency || self.paused) {
  4704. if (queueHead) {
  4705. current.next = queueHead;
  4706. queueHead = current;
  4707. } else {
  4708. queueHead = current;
  4709. queueTail = current;
  4710. self.saturated();
  4711. }
  4712. } else {
  4713. _running++;
  4714. worker.call(context, current.value, current.worked);
  4715. }
  4716. }
  4717. function release (holder) {
  4718. if (holder) {
  4719. cache.release(holder);
  4720. }
  4721. var next = queueHead;
  4722. if (next) {
  4723. if (!self.paused) {
  4724. if (queueTail === queueHead) {
  4725. queueTail = null;
  4726. }
  4727. queueHead = next.next;
  4728. next.next = null;
  4729. worker.call(context, next.value, next.worked);
  4730. if (queueTail === null) {
  4731. self.empty();
  4732. }
  4733. } else {
  4734. _running--;
  4735. }
  4736. } else if (--_running === 0) {
  4737. self.drain();
  4738. }
  4739. }
  4740. function kill () {
  4741. queueHead = null;
  4742. queueTail = null;
  4743. self.drain = noop;
  4744. }
  4745. function killAndDrain () {
  4746. queueHead = null;
  4747. queueTail = null;
  4748. self.drain();
  4749. self.drain = noop;
  4750. }
  4751. function error (handler) {
  4752. errorHandler = handler;
  4753. }
  4754. }
  4755. function noop () {}
  4756. function Task () {
  4757. this.value = null;
  4758. this.callback = noop;
  4759. this.next = null;
  4760. this.release = noop;
  4761. this.context = null;
  4762. this.errorHandler = null;
  4763. var self = this;
  4764. this.worked = function worked (err, result) {
  4765. var callback = self.callback;
  4766. var errorHandler = self.errorHandler;
  4767. var val = self.value;
  4768. self.value = null;
  4769. self.callback = noop;
  4770. if (self.errorHandler) {
  4771. errorHandler(err, val);
  4772. }
  4773. callback.call(self.context, err, result);
  4774. self.release(self);
  4775. };
  4776. }
  4777. function queueAsPromised (context, worker, concurrency) {
  4778. if (typeof context === 'function') {
  4779. concurrency = worker;
  4780. worker = context;
  4781. context = null;
  4782. }
  4783. function asyncWrapper (arg, cb) {
  4784. worker.call(this, arg)
  4785. .then(function (res) {
  4786. cb(null, res);
  4787. }, cb);
  4788. }
  4789. var queue = fastqueue(context, asyncWrapper, concurrency);
  4790. var pushCb = queue.push;
  4791. var unshiftCb = queue.unshift;
  4792. queue.push = push;
  4793. queue.unshift = unshift;
  4794. queue.drained = drained;
  4795. return queue
  4796. function push (value) {
  4797. var p = new Promise(function (resolve, reject) {
  4798. pushCb(value, function (err, result) {
  4799. if (err) {
  4800. reject(err);
  4801. return
  4802. }
  4803. resolve(result);
  4804. });
  4805. });
  4806. // Let's fork the promise chain to
  4807. // make the error bubble up to the user but
  4808. // not lead to a unhandledRejection
  4809. p.catch(noop);
  4810. return p
  4811. }
  4812. function unshift (value) {
  4813. var p = new Promise(function (resolve, reject) {
  4814. unshiftCb(value, function (err, result) {
  4815. if (err) {
  4816. reject(err);
  4817. return
  4818. }
  4819. resolve(result);
  4820. });
  4821. });
  4822. // Let's fork the promise chain to
  4823. // make the error bubble up to the user but
  4824. // not lead to a unhandledRejection
  4825. p.catch(noop);
  4826. return p
  4827. }
  4828. function drained () {
  4829. var previousDrain = queue.drain;
  4830. var p = new Promise(function (resolve) {
  4831. queue.drain = function () {
  4832. previousDrain();
  4833. resolve();
  4834. };
  4835. });
  4836. return p
  4837. }
  4838. }
  4839. queue.exports = fastqueue;
  4840. queue.exports.promise = queueAsPromised;
  4841. var common$3 = {};
  4842. Object.defineProperty(common$3, "__esModule", { value: true });
  4843. common$3.joinPathSegments = common$3.replacePathSegmentSeparator = common$3.isAppliedFilter = common$3.isFatalError = void 0;
  4844. function isFatalError(settings, error) {
  4845. if (settings.errorFilter === null) {
  4846. return true;
  4847. }
  4848. return !settings.errorFilter(error);
  4849. }
  4850. common$3.isFatalError = isFatalError;
  4851. function isAppliedFilter(filter, value) {
  4852. return filter === null || filter(value);
  4853. }
  4854. common$3.isAppliedFilter = isAppliedFilter;
  4855. function replacePathSegmentSeparator(filepath, separator) {
  4856. return filepath.split(/[/\\]/).join(separator);
  4857. }
  4858. common$3.replacePathSegmentSeparator = replacePathSegmentSeparator;
  4859. function joinPathSegments(a, b, separator) {
  4860. if (a === '') {
  4861. return b;
  4862. }
  4863. /**
  4864. * The correct handling of cases when the first segment is a root (`/`, `C:/`) or UNC path (`//?/C:/`).
  4865. */
  4866. if (a.endsWith(separator)) {
  4867. return a + b;
  4868. }
  4869. return a + separator + b;
  4870. }
  4871. common$3.joinPathSegments = joinPathSegments;
  4872. var reader$1 = {};
  4873. Object.defineProperty(reader$1, "__esModule", { value: true });
  4874. const common$2 = common$3;
  4875. class Reader$1 {
  4876. constructor(_root, _settings) {
  4877. this._root = _root;
  4878. this._settings = _settings;
  4879. this._root = common$2.replacePathSegmentSeparator(_root, _settings.pathSegmentSeparator);
  4880. }
  4881. }
  4882. reader$1.default = Reader$1;
  4883. Object.defineProperty(async$4, "__esModule", { value: true });
  4884. const events_1 = require$$2;
  4885. const fsScandir$2 = out$2;
  4886. const fastq = queue.exports;
  4887. const common$1 = common$3;
  4888. const reader_1$4 = reader$1;
  4889. class AsyncReader extends reader_1$4.default {
  4890. constructor(_root, _settings) {
  4891. super(_root, _settings);
  4892. this._settings = _settings;
  4893. this._scandir = fsScandir$2.scandir;
  4894. this._emitter = new events_1.EventEmitter();
  4895. this._queue = fastq(this._worker.bind(this), this._settings.concurrency);
  4896. this._isFatalError = false;
  4897. this._isDestroyed = false;
  4898. this._queue.drain = () => {
  4899. if (!this._isFatalError) {
  4900. this._emitter.emit('end');
  4901. }
  4902. };
  4903. }
  4904. read() {
  4905. this._isFatalError = false;
  4906. this._isDestroyed = false;
  4907. setImmediate(() => {
  4908. this._pushToQueue(this._root, this._settings.basePath);
  4909. });
  4910. return this._emitter;
  4911. }
  4912. get isDestroyed() {
  4913. return this._isDestroyed;
  4914. }
  4915. destroy() {
  4916. if (this._isDestroyed) {
  4917. throw new Error('The reader is already destroyed');
  4918. }
  4919. this._isDestroyed = true;
  4920. this._queue.killAndDrain();
  4921. }
  4922. onEntry(callback) {
  4923. this._emitter.on('entry', callback);
  4924. }
  4925. onError(callback) {
  4926. this._emitter.once('error', callback);
  4927. }
  4928. onEnd(callback) {
  4929. this._emitter.once('end', callback);
  4930. }
  4931. _pushToQueue(directory, base) {
  4932. const queueItem = { directory, base };
  4933. this._queue.push(queueItem, (error) => {
  4934. if (error !== null) {
  4935. this._handleError(error);
  4936. }
  4937. });
  4938. }
  4939. _worker(item, done) {
  4940. this._scandir(item.directory, this._settings.fsScandirSettings, (error, entries) => {
  4941. if (error !== null) {
  4942. done(error, undefined);
  4943. return;
  4944. }
  4945. for (const entry of entries) {
  4946. this._handleEntry(entry, item.base);
  4947. }
  4948. done(null, undefined);
  4949. });
  4950. }
  4951. _handleError(error) {
  4952. if (this._isDestroyed || !common$1.isFatalError(this._settings, error)) {
  4953. return;
  4954. }
  4955. this._isFatalError = true;
  4956. this._isDestroyed = true;
  4957. this._emitter.emit('error', error);
  4958. }
  4959. _handleEntry(entry, base) {
  4960. if (this._isDestroyed || this._isFatalError) {
  4961. return;
  4962. }
  4963. const fullpath = entry.path;
  4964. if (base !== undefined) {
  4965. entry.path = common$1.joinPathSegments(base, entry.name, this._settings.pathSegmentSeparator);
  4966. }
  4967. if (common$1.isAppliedFilter(this._settings.entryFilter, entry)) {
  4968. this._emitEntry(entry);
  4969. }
  4970. if (entry.dirent.isDirectory() && common$1.isAppliedFilter(this._settings.deepFilter, entry)) {
  4971. this._pushToQueue(fullpath, base === undefined ? undefined : entry.path);
  4972. }
  4973. }
  4974. _emitEntry(entry) {
  4975. this._emitter.emit('entry', entry);
  4976. }
  4977. }
  4978. async$4.default = AsyncReader;
  4979. Object.defineProperty(async$5, "__esModule", { value: true });
  4980. const async_1$4 = async$4;
  4981. class AsyncProvider {
  4982. constructor(_root, _settings) {
  4983. this._root = _root;
  4984. this._settings = _settings;
  4985. this._reader = new async_1$4.default(this._root, this._settings);
  4986. this._storage = [];
  4987. }
  4988. read(callback) {
  4989. this._reader.onError((error) => {
  4990. callFailureCallback(callback, error);
  4991. });
  4992. this._reader.onEntry((entry) => {
  4993. this._storage.push(entry);
  4994. });
  4995. this._reader.onEnd(() => {
  4996. callSuccessCallback(callback, this._storage);
  4997. });
  4998. this._reader.read();
  4999. }
  5000. }
  5001. async$5.default = AsyncProvider;
  5002. function callFailureCallback(callback, error) {
  5003. callback(error);
  5004. }
  5005. function callSuccessCallback(callback, entries) {
  5006. callback(null, entries);
  5007. }
  5008. var stream$2 = {};
  5009. Object.defineProperty(stream$2, "__esModule", { value: true });
  5010. const stream_1$5 = require$$0$1;
  5011. const async_1$3 = async$4;
  5012. class StreamProvider {
  5013. constructor(_root, _settings) {
  5014. this._root = _root;
  5015. this._settings = _settings;
  5016. this._reader = new async_1$3.default(this._root, this._settings);
  5017. this._stream = new stream_1$5.Readable({
  5018. objectMode: true,
  5019. read: () => { },
  5020. destroy: () => {
  5021. if (!this._reader.isDestroyed) {
  5022. this._reader.destroy();
  5023. }
  5024. }
  5025. });
  5026. }
  5027. read() {
  5028. this._reader.onError((error) => {
  5029. this._stream.emit('error', error);
  5030. });
  5031. this._reader.onEntry((entry) => {
  5032. this._stream.push(entry);
  5033. });
  5034. this._reader.onEnd(() => {
  5035. this._stream.push(null);
  5036. });
  5037. this._reader.read();
  5038. return this._stream;
  5039. }
  5040. }
  5041. stream$2.default = StreamProvider;
  5042. var sync$3 = {};
  5043. var sync$2 = {};
  5044. Object.defineProperty(sync$2, "__esModule", { value: true });
  5045. const fsScandir$1 = out$2;
  5046. const common = common$3;
  5047. const reader_1$3 = reader$1;
  5048. class SyncReader extends reader_1$3.default {
  5049. constructor() {
  5050. super(...arguments);
  5051. this._scandir = fsScandir$1.scandirSync;
  5052. this._storage = [];
  5053. this._queue = new Set();
  5054. }
  5055. read() {
  5056. this._pushToQueue(this._root, this._settings.basePath);
  5057. this._handleQueue();
  5058. return this._storage;
  5059. }
  5060. _pushToQueue(directory, base) {
  5061. this._queue.add({ directory, base });
  5062. }
  5063. _handleQueue() {
  5064. for (const item of this._queue.values()) {
  5065. this._handleDirectory(item.directory, item.base);
  5066. }
  5067. }
  5068. _handleDirectory(directory, base) {
  5069. try {
  5070. const entries = this._scandir(directory, this._settings.fsScandirSettings);
  5071. for (const entry of entries) {
  5072. this._handleEntry(entry, base);
  5073. }
  5074. }
  5075. catch (error) {
  5076. this._handleError(error);
  5077. }
  5078. }
  5079. _handleError(error) {
  5080. if (!common.isFatalError(this._settings, error)) {
  5081. return;
  5082. }
  5083. throw error;
  5084. }
  5085. _handleEntry(entry, base) {
  5086. const fullpath = entry.path;
  5087. if (base !== undefined) {
  5088. entry.path = common.joinPathSegments(base, entry.name, this._settings.pathSegmentSeparator);
  5089. }
  5090. if (common.isAppliedFilter(this._settings.entryFilter, entry)) {
  5091. this._pushToStorage(entry);
  5092. }
  5093. if (entry.dirent.isDirectory() && common.isAppliedFilter(this._settings.deepFilter, entry)) {
  5094. this._pushToQueue(fullpath, base === undefined ? undefined : entry.path);
  5095. }
  5096. }
  5097. _pushToStorage(entry) {
  5098. this._storage.push(entry);
  5099. }
  5100. }
  5101. sync$2.default = SyncReader;
  5102. Object.defineProperty(sync$3, "__esModule", { value: true });
  5103. const sync_1$3 = sync$2;
  5104. class SyncProvider {
  5105. constructor(_root, _settings) {
  5106. this._root = _root;
  5107. this._settings = _settings;
  5108. this._reader = new sync_1$3.default(this._root, this._settings);
  5109. }
  5110. read() {
  5111. return this._reader.read();
  5112. }
  5113. }
  5114. sync$3.default = SyncProvider;
  5115. var settings$1 = {};
  5116. Object.defineProperty(settings$1, "__esModule", { value: true });
  5117. const path$2 = path$a;
  5118. const fsScandir = out$2;
  5119. class Settings {
  5120. constructor(_options = {}) {
  5121. this._options = _options;
  5122. this.basePath = this._getValue(this._options.basePath, undefined);
  5123. this.concurrency = this._getValue(this._options.concurrency, Number.POSITIVE_INFINITY);
  5124. this.deepFilter = this._getValue(this._options.deepFilter, null);
  5125. this.entryFilter = this._getValue(this._options.entryFilter, null);
  5126. this.errorFilter = this._getValue(this._options.errorFilter, null);
  5127. this.pathSegmentSeparator = this._getValue(this._options.pathSegmentSeparator, path$2.sep);
  5128. this.fsScandirSettings = new fsScandir.Settings({
  5129. followSymbolicLinks: this._options.followSymbolicLinks,
  5130. fs: this._options.fs,
  5131. pathSegmentSeparator: this._options.pathSegmentSeparator,
  5132. stats: this._options.stats,
  5133. throwErrorOnBrokenSymbolicLink: this._options.throwErrorOnBrokenSymbolicLink
  5134. });
  5135. }
  5136. _getValue(option, value) {
  5137. return option !== null && option !== void 0 ? option : value;
  5138. }
  5139. }
  5140. settings$1.default = Settings;
  5141. Object.defineProperty(out$3, "__esModule", { value: true });
  5142. out$3.Settings = out$3.walkStream = out$3.walkSync = out$3.walk = void 0;
  5143. const async_1$2 = async$5;
  5144. const stream_1$4 = stream$2;
  5145. const sync_1$2 = sync$3;
  5146. const settings_1$1 = settings$1;
  5147. out$3.Settings = settings_1$1.default;
  5148. function walk(directory, optionsOrSettingsOrCallback, callback) {
  5149. if (typeof optionsOrSettingsOrCallback === 'function') {
  5150. new async_1$2.default(directory, getSettings()).read(optionsOrSettingsOrCallback);
  5151. return;
  5152. }
  5153. new async_1$2.default(directory, getSettings(optionsOrSettingsOrCallback)).read(callback);
  5154. }
  5155. out$3.walk = walk;
  5156. function walkSync(directory, optionsOrSettings) {
  5157. const settings = getSettings(optionsOrSettings);
  5158. const provider = new sync_1$2.default(directory, settings);
  5159. return provider.read();
  5160. }
  5161. out$3.walkSync = walkSync;
  5162. function walkStream(directory, optionsOrSettings) {
  5163. const settings = getSettings(optionsOrSettings);
  5164. const provider = new stream_1$4.default(directory, settings);
  5165. return provider.read();
  5166. }
  5167. out$3.walkStream = walkStream;
  5168. function getSettings(settingsOrOptions = {}) {
  5169. if (settingsOrOptions instanceof settings_1$1.default) {
  5170. return settingsOrOptions;
  5171. }
  5172. return new settings_1$1.default(settingsOrOptions);
  5173. }
  5174. var reader = {};
  5175. Object.defineProperty(reader, "__esModule", { value: true });
  5176. const path$1 = path$a;
  5177. const fsStat$2 = out$1;
  5178. const utils$6 = utils$k;
  5179. class Reader {
  5180. constructor(_settings) {
  5181. this._settings = _settings;
  5182. this._fsStatSettings = new fsStat$2.Settings({
  5183. followSymbolicLink: this._settings.followSymbolicLinks,
  5184. fs: this._settings.fs,
  5185. throwErrorOnBrokenSymbolicLink: this._settings.followSymbolicLinks
  5186. });
  5187. }
  5188. _getFullEntryPath(filepath) {
  5189. return path$1.resolve(this._settings.cwd, filepath);
  5190. }
  5191. _makeEntry(stats, pattern) {
  5192. const entry = {
  5193. name: pattern,
  5194. path: pattern,
  5195. dirent: utils$6.fs.createDirentFromStats(pattern, stats)
  5196. };
  5197. if (this._settings.stats) {
  5198. entry.stats = stats;
  5199. }
  5200. return entry;
  5201. }
  5202. _isFatalError(error) {
  5203. return !utils$6.errno.isEnoentCodeError(error) && !this._settings.suppressErrors;
  5204. }
  5205. }
  5206. reader.default = Reader;
  5207. var stream$1 = {};
  5208. Object.defineProperty(stream$1, "__esModule", { value: true });
  5209. const stream_1$3 = require$$0$1;
  5210. const fsStat$1 = out$1;
  5211. const fsWalk$2 = out$3;
  5212. const reader_1$2 = reader;
  5213. class ReaderStream extends reader_1$2.default {
  5214. constructor() {
  5215. super(...arguments);
  5216. this._walkStream = fsWalk$2.walkStream;
  5217. this._stat = fsStat$1.stat;
  5218. }
  5219. dynamic(root, options) {
  5220. return this._walkStream(root, options);
  5221. }
  5222. static(patterns, options) {
  5223. const filepaths = patterns.map(this._getFullEntryPath, this);
  5224. const stream = new stream_1$3.PassThrough({ objectMode: true });
  5225. stream._write = (index, _enc, done) => {
  5226. return this._getEntry(filepaths[index], patterns[index], options)
  5227. .then((entry) => {
  5228. if (entry !== null && options.entryFilter(entry)) {
  5229. stream.push(entry);
  5230. }
  5231. if (index === filepaths.length - 1) {
  5232. stream.end();
  5233. }
  5234. done();
  5235. })
  5236. .catch(done);
  5237. };
  5238. for (let i = 0; i < filepaths.length; i++) {
  5239. stream.write(i);
  5240. }
  5241. return stream;
  5242. }
  5243. _getEntry(filepath, pattern, options) {
  5244. return this._getStat(filepath)
  5245. .then((stats) => this._makeEntry(stats, pattern))
  5246. .catch((error) => {
  5247. if (options.errorFilter(error)) {
  5248. return null;
  5249. }
  5250. throw error;
  5251. });
  5252. }
  5253. _getStat(filepath) {
  5254. return new Promise((resolve, reject) => {
  5255. this._stat(filepath, this._fsStatSettings, (error, stats) => {
  5256. return error === null ? resolve(stats) : reject(error);
  5257. });
  5258. });
  5259. }
  5260. }
  5261. stream$1.default = ReaderStream;
  5262. Object.defineProperty(async$6, "__esModule", { value: true });
  5263. const fsWalk$1 = out$3;
  5264. const reader_1$1 = reader;
  5265. const stream_1$2 = stream$1;
  5266. class ReaderAsync extends reader_1$1.default {
  5267. constructor() {
  5268. super(...arguments);
  5269. this._walkAsync = fsWalk$1.walk;
  5270. this._readerStream = new stream_1$2.default(this._settings);
  5271. }
  5272. dynamic(root, options) {
  5273. return new Promise((resolve, reject) => {
  5274. this._walkAsync(root, options, (error, entries) => {
  5275. if (error === null) {
  5276. resolve(entries);
  5277. }
  5278. else {
  5279. reject(error);
  5280. }
  5281. });
  5282. });
  5283. }
  5284. async static(patterns, options) {
  5285. const entries = [];
  5286. const stream = this._readerStream.static(patterns, options);
  5287. // After #235, replace it with an asynchronous iterator.
  5288. return new Promise((resolve, reject) => {
  5289. stream.once('error', reject);
  5290. stream.on('data', (entry) => entries.push(entry));
  5291. stream.once('end', () => resolve(entries));
  5292. });
  5293. }
  5294. }
  5295. async$6.default = ReaderAsync;
  5296. var provider = {};
  5297. var deep = {};
  5298. var partial = {};
  5299. var matcher = {};
  5300. Object.defineProperty(matcher, "__esModule", { value: true });
  5301. const utils$5 = utils$k;
  5302. class Matcher {
  5303. constructor(_patterns, _settings, _micromatchOptions) {
  5304. this._patterns = _patterns;
  5305. this._settings = _settings;
  5306. this._micromatchOptions = _micromatchOptions;
  5307. this._storage = [];
  5308. this._fillStorage();
  5309. }
  5310. _fillStorage() {
  5311. /**
  5312. * The original pattern may include `{,*,**,a/*}`, which will lead to problems with matching (unresolved level).
  5313. * So, before expand patterns with brace expansion into separated patterns.
  5314. */
  5315. const patterns = utils$5.pattern.expandPatternsWithBraceExpansion(this._patterns);
  5316. for (const pattern of patterns) {
  5317. const segments = this._getPatternSegments(pattern);
  5318. const sections = this._splitSegmentsIntoSections(segments);
  5319. this._storage.push({
  5320. complete: sections.length <= 1,
  5321. pattern,
  5322. segments,
  5323. sections
  5324. });
  5325. }
  5326. }
  5327. _getPatternSegments(pattern) {
  5328. const parts = utils$5.pattern.getPatternParts(pattern, this._micromatchOptions);
  5329. return parts.map((part) => {
  5330. const dynamic = utils$5.pattern.isDynamicPattern(part, this._settings);
  5331. if (!dynamic) {
  5332. return {
  5333. dynamic: false,
  5334. pattern: part
  5335. };
  5336. }
  5337. return {
  5338. dynamic: true,
  5339. pattern: part,
  5340. patternRe: utils$5.pattern.makeRe(part, this._micromatchOptions)
  5341. };
  5342. });
  5343. }
  5344. _splitSegmentsIntoSections(segments) {
  5345. return utils$5.array.splitWhen(segments, (segment) => segment.dynamic && utils$5.pattern.hasGlobStar(segment.pattern));
  5346. }
  5347. }
  5348. matcher.default = Matcher;
  5349. Object.defineProperty(partial, "__esModule", { value: true });
  5350. const matcher_1 = matcher;
  5351. class PartialMatcher extends matcher_1.default {
  5352. match(filepath) {
  5353. const parts = filepath.split('/');
  5354. const levels = parts.length;
  5355. const patterns = this._storage.filter((info) => !info.complete || info.segments.length > levels);
  5356. for (const pattern of patterns) {
  5357. const section = pattern.sections[0];
  5358. /**
  5359. * In this case, the pattern has a globstar and we must read all directories unconditionally,
  5360. * but only if the level has reached the end of the first group.
  5361. *
  5362. * fixtures/{a,b}/**
  5363. * ^ true/false ^ always true
  5364. */
  5365. if (!pattern.complete && levels > section.length) {
  5366. return true;
  5367. }
  5368. const match = parts.every((part, index) => {
  5369. const segment = pattern.segments[index];
  5370. if (segment.dynamic && segment.patternRe.test(part)) {
  5371. return true;
  5372. }
  5373. if (!segment.dynamic && segment.pattern === part) {
  5374. return true;
  5375. }
  5376. return false;
  5377. });
  5378. if (match) {
  5379. return true;
  5380. }
  5381. }
  5382. return false;
  5383. }
  5384. }
  5385. partial.default = PartialMatcher;
  5386. Object.defineProperty(deep, "__esModule", { value: true });
  5387. const utils$4 = utils$k;
  5388. const partial_1 = partial;
  5389. class DeepFilter {
  5390. constructor(_settings, _micromatchOptions) {
  5391. this._settings = _settings;
  5392. this._micromatchOptions = _micromatchOptions;
  5393. }
  5394. getFilter(basePath, positive, negative) {
  5395. const matcher = this._getMatcher(positive);
  5396. const negativeRe = this._getNegativePatternsRe(negative);
  5397. return (entry) => this._filter(basePath, entry, matcher, negativeRe);
  5398. }
  5399. _getMatcher(patterns) {
  5400. return new partial_1.default(patterns, this._settings, this._micromatchOptions);
  5401. }
  5402. _getNegativePatternsRe(patterns) {
  5403. const affectDepthOfReadingPatterns = patterns.filter(utils$4.pattern.isAffectDepthOfReadingPattern);
  5404. return utils$4.pattern.convertPatternsToRe(affectDepthOfReadingPatterns, this._micromatchOptions);
  5405. }
  5406. _filter(basePath, entry, matcher, negativeRe) {
  5407. if (this._isSkippedByDeep(basePath, entry.path)) {
  5408. return false;
  5409. }
  5410. if (this._isSkippedSymbolicLink(entry)) {
  5411. return false;
  5412. }
  5413. const filepath = utils$4.path.removeLeadingDotSegment(entry.path);
  5414. if (this._isSkippedByPositivePatterns(filepath, matcher)) {
  5415. return false;
  5416. }
  5417. return this._isSkippedByNegativePatterns(filepath, negativeRe);
  5418. }
  5419. _isSkippedByDeep(basePath, entryPath) {
  5420. /**
  5421. * Avoid unnecessary depth calculations when it doesn't matter.
  5422. */
  5423. if (this._settings.deep === Infinity) {
  5424. return false;
  5425. }
  5426. return this._getEntryLevel(basePath, entryPath) >= this._settings.deep;
  5427. }
  5428. _getEntryLevel(basePath, entryPath) {
  5429. const entryPathDepth = entryPath.split('/').length;
  5430. if (basePath === '') {
  5431. return entryPathDepth;
  5432. }
  5433. const basePathDepth = basePath.split('/').length;
  5434. return entryPathDepth - basePathDepth;
  5435. }
  5436. _isSkippedSymbolicLink(entry) {
  5437. return !this._settings.followSymbolicLinks && entry.dirent.isSymbolicLink();
  5438. }
  5439. _isSkippedByPositivePatterns(entryPath, matcher) {
  5440. return !this._settings.baseNameMatch && !matcher.match(entryPath);
  5441. }
  5442. _isSkippedByNegativePatterns(entryPath, patternsRe) {
  5443. return !utils$4.pattern.matchAny(entryPath, patternsRe);
  5444. }
  5445. }
  5446. deep.default = DeepFilter;
  5447. var entry$1 = {};
  5448. Object.defineProperty(entry$1, "__esModule", { value: true });
  5449. const utils$3 = utils$k;
  5450. class EntryFilter {
  5451. constructor(_settings, _micromatchOptions) {
  5452. this._settings = _settings;
  5453. this._micromatchOptions = _micromatchOptions;
  5454. this.index = new Map();
  5455. }
  5456. getFilter(positive, negative) {
  5457. const positiveRe = utils$3.pattern.convertPatternsToRe(positive, this._micromatchOptions);
  5458. const negativeRe = utils$3.pattern.convertPatternsToRe(negative, this._micromatchOptions);
  5459. return (entry) => this._filter(entry, positiveRe, negativeRe);
  5460. }
  5461. _filter(entry, positiveRe, negativeRe) {
  5462. if (this._settings.unique && this._isDuplicateEntry(entry)) {
  5463. return false;
  5464. }
  5465. if (this._onlyFileFilter(entry) || this._onlyDirectoryFilter(entry)) {
  5466. return false;
  5467. }
  5468. if (this._isSkippedByAbsoluteNegativePatterns(entry.path, negativeRe)) {
  5469. return false;
  5470. }
  5471. const filepath = this._settings.baseNameMatch ? entry.name : entry.path;
  5472. const isDirectory = entry.dirent.isDirectory();
  5473. const isMatched = this._isMatchToPatterns(filepath, positiveRe, isDirectory) && !this._isMatchToPatterns(entry.path, negativeRe, isDirectory);
  5474. if (this._settings.unique && isMatched) {
  5475. this._createIndexRecord(entry);
  5476. }
  5477. return isMatched;
  5478. }
  5479. _isDuplicateEntry(entry) {
  5480. return this.index.has(entry.path);
  5481. }
  5482. _createIndexRecord(entry) {
  5483. this.index.set(entry.path, undefined);
  5484. }
  5485. _onlyFileFilter(entry) {
  5486. return this._settings.onlyFiles && !entry.dirent.isFile();
  5487. }
  5488. _onlyDirectoryFilter(entry) {
  5489. return this._settings.onlyDirectories && !entry.dirent.isDirectory();
  5490. }
  5491. _isSkippedByAbsoluteNegativePatterns(entryPath, patternsRe) {
  5492. if (!this._settings.absolute) {
  5493. return false;
  5494. }
  5495. const fullpath = utils$3.path.makeAbsolute(this._settings.cwd, entryPath);
  5496. return utils$3.pattern.matchAny(fullpath, patternsRe);
  5497. }
  5498. _isMatchToPatterns(entryPath, patternsRe, isDirectory) {
  5499. const filepath = utils$3.path.removeLeadingDotSegment(entryPath);
  5500. // Trying to match files and directories by patterns.
  5501. const isMatched = utils$3.pattern.matchAny(filepath, patternsRe);
  5502. // A pattern with a trailling slash can be used for directory matching.
  5503. // To apply such pattern, we need to add a tralling slash to the path.
  5504. if (!isMatched && isDirectory) {
  5505. return utils$3.pattern.matchAny(filepath + '/', patternsRe);
  5506. }
  5507. return isMatched;
  5508. }
  5509. }
  5510. entry$1.default = EntryFilter;
  5511. var error = {};
  5512. Object.defineProperty(error, "__esModule", { value: true });
  5513. const utils$2 = utils$k;
  5514. class ErrorFilter {
  5515. constructor(_settings) {
  5516. this._settings = _settings;
  5517. }
  5518. getFilter() {
  5519. return (error) => this._isNonFatalError(error);
  5520. }
  5521. _isNonFatalError(error) {
  5522. return utils$2.errno.isEnoentCodeError(error) || this._settings.suppressErrors;
  5523. }
  5524. }
  5525. error.default = ErrorFilter;
  5526. var entry = {};
  5527. Object.defineProperty(entry, "__esModule", { value: true });
  5528. const utils$1 = utils$k;
  5529. class EntryTransformer {
  5530. constructor(_settings) {
  5531. this._settings = _settings;
  5532. }
  5533. getTransformer() {
  5534. return (entry) => this._transform(entry);
  5535. }
  5536. _transform(entry) {
  5537. let filepath = entry.path;
  5538. if (this._settings.absolute) {
  5539. filepath = utils$1.path.makeAbsolute(this._settings.cwd, filepath);
  5540. filepath = utils$1.path.unixify(filepath);
  5541. }
  5542. if (this._settings.markDirectories && entry.dirent.isDirectory()) {
  5543. filepath += '/';
  5544. }
  5545. if (!this._settings.objectMode) {
  5546. return filepath;
  5547. }
  5548. return Object.assign(Object.assign({}, entry), { path: filepath });
  5549. }
  5550. }
  5551. entry.default = EntryTransformer;
  5552. Object.defineProperty(provider, "__esModule", { value: true });
  5553. const path = path$a;
  5554. const deep_1 = deep;
  5555. const entry_1 = entry$1;
  5556. const error_1 = error;
  5557. const entry_2 = entry;
  5558. class Provider {
  5559. constructor(_settings) {
  5560. this._settings = _settings;
  5561. this.errorFilter = new error_1.default(this._settings);
  5562. this.entryFilter = new entry_1.default(this._settings, this._getMicromatchOptions());
  5563. this.deepFilter = new deep_1.default(this._settings, this._getMicromatchOptions());
  5564. this.entryTransformer = new entry_2.default(this._settings);
  5565. }
  5566. _getRootDirectory(task) {
  5567. return path.resolve(this._settings.cwd, task.base);
  5568. }
  5569. _getReaderOptions(task) {
  5570. const basePath = task.base === '.' ? '' : task.base;
  5571. return {
  5572. basePath,
  5573. pathSegmentSeparator: '/',
  5574. concurrency: this._settings.concurrency,
  5575. deepFilter: this.deepFilter.getFilter(basePath, task.positive, task.negative),
  5576. entryFilter: this.entryFilter.getFilter(task.positive, task.negative),
  5577. errorFilter: this.errorFilter.getFilter(),
  5578. followSymbolicLinks: this._settings.followSymbolicLinks,
  5579. fs: this._settings.fs,
  5580. stats: this._settings.stats,
  5581. throwErrorOnBrokenSymbolicLink: this._settings.throwErrorOnBrokenSymbolicLink,
  5582. transform: this.entryTransformer.getTransformer()
  5583. };
  5584. }
  5585. _getMicromatchOptions() {
  5586. return {
  5587. dot: this._settings.dot,
  5588. matchBase: this._settings.baseNameMatch,
  5589. nobrace: !this._settings.braceExpansion,
  5590. nocase: !this._settings.caseSensitiveMatch,
  5591. noext: !this._settings.extglob,
  5592. noglobstar: !this._settings.globstar,
  5593. posix: true,
  5594. strictSlashes: false
  5595. };
  5596. }
  5597. }
  5598. provider.default = Provider;
  5599. Object.defineProperty(async$7, "__esModule", { value: true });
  5600. const async_1$1 = async$6;
  5601. const provider_1$2 = provider;
  5602. class ProviderAsync extends provider_1$2.default {
  5603. constructor() {
  5604. super(...arguments);
  5605. this._reader = new async_1$1.default(this._settings);
  5606. }
  5607. async read(task) {
  5608. const root = this._getRootDirectory(task);
  5609. const options = this._getReaderOptions(task);
  5610. const entries = await this.api(root, task, options);
  5611. return entries.map((entry) => options.transform(entry));
  5612. }
  5613. api(root, task, options) {
  5614. if (task.dynamic) {
  5615. return this._reader.dynamic(root, options);
  5616. }
  5617. return this._reader.static(task.patterns, options);
  5618. }
  5619. }
  5620. async$7.default = ProviderAsync;
  5621. var stream = {};
  5622. Object.defineProperty(stream, "__esModule", { value: true });
  5623. const stream_1$1 = require$$0$1;
  5624. const stream_2 = stream$1;
  5625. const provider_1$1 = provider;
  5626. class ProviderStream extends provider_1$1.default {
  5627. constructor() {
  5628. super(...arguments);
  5629. this._reader = new stream_2.default(this._settings);
  5630. }
  5631. read(task) {
  5632. const root = this._getRootDirectory(task);
  5633. const options = this._getReaderOptions(task);
  5634. const source = this.api(root, task, options);
  5635. const destination = new stream_1$1.Readable({ objectMode: true, read: () => { } });
  5636. source
  5637. .once('error', (error) => destination.emit('error', error))
  5638. .on('data', (entry) => destination.emit('data', options.transform(entry)))
  5639. .once('end', () => destination.emit('end'));
  5640. destination
  5641. .once('close', () => source.destroy());
  5642. return destination;
  5643. }
  5644. api(root, task, options) {
  5645. if (task.dynamic) {
  5646. return this._reader.dynamic(root, options);
  5647. }
  5648. return this._reader.static(task.patterns, options);
  5649. }
  5650. }
  5651. stream.default = ProviderStream;
  5652. var sync$1 = {};
  5653. var sync = {};
  5654. Object.defineProperty(sync, "__esModule", { value: true });
  5655. const fsStat = out$1;
  5656. const fsWalk = out$3;
  5657. const reader_1 = reader;
  5658. class ReaderSync extends reader_1.default {
  5659. constructor() {
  5660. super(...arguments);
  5661. this._walkSync = fsWalk.walkSync;
  5662. this._statSync = fsStat.statSync;
  5663. }
  5664. dynamic(root, options) {
  5665. return this._walkSync(root, options);
  5666. }
  5667. static(patterns, options) {
  5668. const entries = [];
  5669. for (const pattern of patterns) {
  5670. const filepath = this._getFullEntryPath(pattern);
  5671. const entry = this._getEntry(filepath, pattern, options);
  5672. if (entry === null || !options.entryFilter(entry)) {
  5673. continue;
  5674. }
  5675. entries.push(entry);
  5676. }
  5677. return entries;
  5678. }
  5679. _getEntry(filepath, pattern, options) {
  5680. try {
  5681. const stats = this._getStat(filepath);
  5682. return this._makeEntry(stats, pattern);
  5683. }
  5684. catch (error) {
  5685. if (options.errorFilter(error)) {
  5686. return null;
  5687. }
  5688. throw error;
  5689. }
  5690. }
  5691. _getStat(filepath) {
  5692. return this._statSync(filepath, this._fsStatSettings);
  5693. }
  5694. }
  5695. sync.default = ReaderSync;
  5696. Object.defineProperty(sync$1, "__esModule", { value: true });
  5697. const sync_1$1 = sync;
  5698. const provider_1 = provider;
  5699. class ProviderSync extends provider_1.default {
  5700. constructor() {
  5701. super(...arguments);
  5702. this._reader = new sync_1$1.default(this._settings);
  5703. }
  5704. read(task) {
  5705. const root = this._getRootDirectory(task);
  5706. const options = this._getReaderOptions(task);
  5707. const entries = this.api(root, task, options);
  5708. return entries.map(options.transform);
  5709. }
  5710. api(root, task, options) {
  5711. if (task.dynamic) {
  5712. return this._reader.dynamic(root, options);
  5713. }
  5714. return this._reader.static(task.patterns, options);
  5715. }
  5716. }
  5717. sync$1.default = ProviderSync;
  5718. var settings = {};
  5719. (function (exports) {
  5720. Object.defineProperty(exports, "__esModule", { value: true });
  5721. exports.DEFAULT_FILE_SYSTEM_ADAPTER = void 0;
  5722. const fs = fs$8;
  5723. const os = require$$0;
  5724. /**
  5725. * The `os.cpus` method can return zero. We expect the number of cores to be greater than zero.
  5726. * https://github.com/nodejs/node/blob/7faeddf23a98c53896f8b574a6e66589e8fb1eb8/lib/os.js#L106-L107
  5727. */
  5728. const CPU_COUNT = Math.max(os.cpus().length, 1);
  5729. exports.DEFAULT_FILE_SYSTEM_ADAPTER = {
  5730. lstat: fs.lstat,
  5731. lstatSync: fs.lstatSync,
  5732. stat: fs.stat,
  5733. statSync: fs.statSync,
  5734. readdir: fs.readdir,
  5735. readdirSync: fs.readdirSync
  5736. };
  5737. class Settings {
  5738. constructor(_options = {}) {
  5739. this._options = _options;
  5740. this.absolute = this._getValue(this._options.absolute, false);
  5741. this.baseNameMatch = this._getValue(this._options.baseNameMatch, false);
  5742. this.braceExpansion = this._getValue(this._options.braceExpansion, true);
  5743. this.caseSensitiveMatch = this._getValue(this._options.caseSensitiveMatch, true);
  5744. this.concurrency = this._getValue(this._options.concurrency, CPU_COUNT);
  5745. this.cwd = this._getValue(this._options.cwd, process.cwd());
  5746. this.deep = this._getValue(this._options.deep, Infinity);
  5747. this.dot = this._getValue(this._options.dot, false);
  5748. this.extglob = this._getValue(this._options.extglob, true);
  5749. this.followSymbolicLinks = this._getValue(this._options.followSymbolicLinks, true);
  5750. this.fs = this._getFileSystemMethods(this._options.fs);
  5751. this.globstar = this._getValue(this._options.globstar, true);
  5752. this.ignore = this._getValue(this._options.ignore, []);
  5753. this.markDirectories = this._getValue(this._options.markDirectories, false);
  5754. this.objectMode = this._getValue(this._options.objectMode, false);
  5755. this.onlyDirectories = this._getValue(this._options.onlyDirectories, false);
  5756. this.onlyFiles = this._getValue(this._options.onlyFiles, true);
  5757. this.stats = this._getValue(this._options.stats, false);
  5758. this.suppressErrors = this._getValue(this._options.suppressErrors, false);
  5759. this.throwErrorOnBrokenSymbolicLink = this._getValue(this._options.throwErrorOnBrokenSymbolicLink, false);
  5760. this.unique = this._getValue(this._options.unique, true);
  5761. if (this.onlyDirectories) {
  5762. this.onlyFiles = false;
  5763. }
  5764. if (this.stats) {
  5765. this.objectMode = true;
  5766. }
  5767. }
  5768. _getValue(option, value) {
  5769. return option === undefined ? value : option;
  5770. }
  5771. _getFileSystemMethods(methods = {}) {
  5772. return Object.assign(Object.assign({}, exports.DEFAULT_FILE_SYSTEM_ADAPTER), methods);
  5773. }
  5774. }
  5775. exports.default = Settings;
  5776. } (settings));
  5777. const taskManager = tasks;
  5778. const patternManager = patterns;
  5779. const async_1 = async$7;
  5780. const stream_1 = stream;
  5781. const sync_1 = sync$1;
  5782. const settings_1 = settings;
  5783. const utils = utils$k;
  5784. async function FastGlob(source, options) {
  5785. assertPatternsInput(source);
  5786. const works = getWorks(source, async_1.default, options);
  5787. const result = await Promise.all(works);
  5788. return utils.array.flatten(result);
  5789. }
  5790. // https://github.com/typescript-eslint/typescript-eslint/issues/60
  5791. // eslint-disable-next-line no-redeclare
  5792. (function (FastGlob) {
  5793. function sync(source, options) {
  5794. assertPatternsInput(source);
  5795. const works = getWorks(source, sync_1.default, options);
  5796. return utils.array.flatten(works);
  5797. }
  5798. FastGlob.sync = sync;
  5799. function stream(source, options) {
  5800. assertPatternsInput(source);
  5801. const works = getWorks(source, stream_1.default, options);
  5802. /**
  5803. * The stream returned by the provider cannot work with an asynchronous iterator.
  5804. * To support asynchronous iterators, regardless of the number of tasks, we always multiplex streams.
  5805. * This affects performance (+25%). I don't see best solution right now.
  5806. */
  5807. return utils.stream.merge(works);
  5808. }
  5809. FastGlob.stream = stream;
  5810. function generateTasks(source, options) {
  5811. assertPatternsInput(source);
  5812. const patterns = patternManager.transform([].concat(source));
  5813. const settings = new settings_1.default(options);
  5814. return taskManager.generate(patterns, settings);
  5815. }
  5816. FastGlob.generateTasks = generateTasks;
  5817. function isDynamicPattern(source, options) {
  5818. assertPatternsInput(source);
  5819. const settings = new settings_1.default(options);
  5820. return utils.pattern.isDynamicPattern(source, settings);
  5821. }
  5822. FastGlob.isDynamicPattern = isDynamicPattern;
  5823. function escapePath(source) {
  5824. assertPatternsInput(source);
  5825. return utils.path.escape(source);
  5826. }
  5827. FastGlob.escapePath = escapePath;
  5828. })(FastGlob || (FastGlob = {}));
  5829. function getWorks(source, _Provider, options) {
  5830. const patterns = patternManager.transform([].concat(source));
  5831. const settings = new settings_1.default(options);
  5832. const tasks = taskManager.generate(patterns, settings);
  5833. const provider = new _Provider(settings);
  5834. return tasks.map(provider.read, provider);
  5835. }
  5836. function assertPatternsInput(input) {
  5837. const source = [].concat(input);
  5838. const isValidSource = source.every((item) => utils.string.isString(item) && !utils.string.isEmpty(item));
  5839. if (!isValidSource) {
  5840. throw new TypeError('Patterns must be a string (non empty) or an array of strings');
  5841. }
  5842. }
  5843. var out = FastGlob;
  5844. const ESM_EXT_RE = /\.(es|esm|esm-browser|esm-bundler|es6|module)\.js$/;
  5845. const ESM_FOLDER_RE = /\/(es|esm)\/(.*\.js)$/;
  5846. const defaultInline = [
  5847. /virtual:/,
  5848. /\.[mc]?ts$/
  5849. ];
  5850. const depsExternal = [
  5851. /\.cjs\.js$/,
  5852. /\.mjs$/
  5853. ];
  5854. function guessCJSversion(id) {
  5855. if (id.match(ESM_EXT_RE)) {
  5856. for (const i of [
  5857. id.replace(ESM_EXT_RE, ".mjs"),
  5858. id.replace(ESM_EXT_RE, ".umd.js"),
  5859. id.replace(ESM_EXT_RE, ".cjs.js"),
  5860. id.replace(ESM_EXT_RE, ".js")
  5861. ]) {
  5862. if (existsSync(i))
  5863. return i;
  5864. }
  5865. }
  5866. if (id.match(ESM_FOLDER_RE)) {
  5867. for (const i of [
  5868. id.replace(ESM_FOLDER_RE, "/umd/$1"),
  5869. id.replace(ESM_FOLDER_RE, "/cjs/$1"),
  5870. id.replace(ESM_FOLDER_RE, "/lib/$1"),
  5871. id.replace(ESM_FOLDER_RE, "/$1")
  5872. ]) {
  5873. if (existsSync(i))
  5874. return i;
  5875. }
  5876. }
  5877. }
  5878. const _defaultExternalizeCache = /* @__PURE__ */ new Map();
  5879. async function shouldExternalize(id, options, cache = _defaultExternalizeCache) {
  5880. if (!cache.has(id))
  5881. cache.set(id, _shouldExternalize(id, options));
  5882. return cache.get(id);
  5883. }
  5884. async function _shouldExternalize(id, options) {
  5885. if (isNodeBuiltin(id))
  5886. return id;
  5887. if (id.startsWith("data:"))
  5888. return id;
  5889. id = patchWindowsImportPath(id);
  5890. if (matchExternalizePattern(id, options == null ? void 0 : options.inline))
  5891. return false;
  5892. if (matchExternalizePattern(id, options == null ? void 0 : options.external))
  5893. return id;
  5894. const isNodeModule = id.includes("/node_modules/");
  5895. const guessCJS = isNodeModule && (options == null ? void 0 : options.fallbackCJS);
  5896. id = guessCJS ? guessCJSversion(id) || id : id;
  5897. if (matchExternalizePattern(id, defaultInline))
  5898. return false;
  5899. if (matchExternalizePattern(id, depsExternal))
  5900. return id;
  5901. const isDist = id.includes("/dist/");
  5902. if ((isNodeModule || isDist) && await isValidNodeImport(id))
  5903. return id;
  5904. return false;
  5905. }
  5906. function matchExternalizePattern(id, patterns) {
  5907. if (patterns == null)
  5908. return false;
  5909. if (patterns === true)
  5910. return true;
  5911. for (const ex of patterns) {
  5912. if (typeof ex === "string") {
  5913. if (id.includes(`/node_modules/${ex}/`))
  5914. return true;
  5915. } else {
  5916. if (ex.test(id))
  5917. return true;
  5918. }
  5919. }
  5920. return false;
  5921. }
  5922. function patchWindowsImportPath(path) {
  5923. if (path.match(/^\w:\\/))
  5924. return `file:///${slash$1(path)}`;
  5925. else if (path.match(/^\w:\//))
  5926. return `file:///${path}`;
  5927. else
  5928. return path;
  5929. }
  5930. const debugRequest = createDebug("vite-node:server:request");
  5931. const RealDate = Date;
  5932. class ViteNodeServer {
  5933. constructor(server, options = {}) {
  5934. this.server = server;
  5935. this.options = options;
  5936. this.fetchPromiseMap = /* @__PURE__ */ new Map();
  5937. this.transformPromiseMap = /* @__PURE__ */ new Map();
  5938. this.fetchCache = /* @__PURE__ */ new Map();
  5939. this.externalizeCache = /* @__PURE__ */ new Map();
  5940. var _a, _b;
  5941. const ssrOptions = server.config.ssr;
  5942. if (ssrOptions) {
  5943. options.deps ?? (options.deps = {});
  5944. if (ssrOptions.noExternal === true) {
  5945. (_a = options.deps).inline ?? (_a.inline = true);
  5946. } else if (options.deps.inline !== true) {
  5947. (_b = options.deps).inline ?? (_b.inline = []);
  5948. options.deps.inline.push(...toArray(ssrOptions.noExternal));
  5949. }
  5950. }
  5951. if (process.env.VITE_NODE_DEBUG_DUMP) {
  5952. options.debug = Object.assign({
  5953. dumpModules: !!process.env.VITE_NODE_DEBUG_DUMP,
  5954. loadDumppedModules: process.env.VITE_NODE_DEBUG_DUMP === "load"
  5955. }, options.debug ?? {});
  5956. }
  5957. if (options.debug)
  5958. import('./chunk-vite-node-debug.536c4c5b.mjs').then((r) => this.debugger = new r.Debugger(server.config.root, options.debug));
  5959. }
  5960. shouldExternalize(id) {
  5961. return shouldExternalize(id, this.options.deps, this.externalizeCache);
  5962. }
  5963. async resolveId(id, importer) {
  5964. if (importer && !importer.startsWith(this.server.config.root))
  5965. importer = resolve(this.server.config.root, importer);
  5966. const mode = importer && this.getTransformMode(importer) || "ssr";
  5967. return this.server.pluginContainer.resolveId(id, importer, { ssr: mode === "ssr" });
  5968. }
  5969. async fetchModule(id) {
  5970. if (!this.fetchPromiseMap.has(id)) {
  5971. this.fetchPromiseMap.set(
  5972. id,
  5973. this._fetchModule(id).then((r) => {
  5974. return this.options.sourcemap !== true ? { ...r, map: void 0 } : r;
  5975. }).finally(() => {
  5976. this.fetchPromiseMap.delete(id);
  5977. })
  5978. );
  5979. }
  5980. return this.fetchPromiseMap.get(id);
  5981. }
  5982. async transformRequest(id) {
  5983. if (!this.transformPromiseMap.has(id)) {
  5984. this.transformPromiseMap.set(
  5985. id,
  5986. this._transformRequest(id).finally(() => {
  5987. this.transformPromiseMap.delete(id);
  5988. })
  5989. );
  5990. }
  5991. return this.transformPromiseMap.get(id);
  5992. }
  5993. getTransformMode(id) {
  5994. var _a, _b, _c, _d;
  5995. const withoutQuery = id.split("?")[0];
  5996. if ((_b = (_a = this.options.transformMode) == null ? void 0 : _a.web) == null ? void 0 : _b.some((r) => withoutQuery.match(r)))
  5997. return "web";
  5998. if ((_d = (_c = this.options.transformMode) == null ? void 0 : _c.ssr) == null ? void 0 : _d.some((r) => withoutQuery.match(r)))
  5999. return "ssr";
  6000. if (withoutQuery.match(/\.([cm]?[jt]sx?|json)$/))
  6001. return "ssr";
  6002. return "web";
  6003. }
  6004. async _fetchModule(id) {
  6005. var _a;
  6006. let result;
  6007. const filePath = toFilePath(id, this.server.config.root);
  6008. const module = this.server.moduleGraph.getModuleById(id);
  6009. const timestamp = (module == null ? void 0 : module.lastHMRTimestamp) || RealDate.now();
  6010. const cache = this.fetchCache.get(filePath);
  6011. if (timestamp && cache && cache.timestamp >= timestamp)
  6012. return cache.result;
  6013. const externalize = await this.shouldExternalize(filePath);
  6014. let duration;
  6015. if (externalize) {
  6016. result = { externalize };
  6017. (_a = this.debugger) == null ? void 0 : _a.recordExternalize(id, externalize);
  6018. } else {
  6019. const start = performance.now();
  6020. const r = await this._transformRequest(id);
  6021. duration = performance.now() - start;
  6022. result = { code: r == null ? void 0 : r.code, map: r == null ? void 0 : r.map };
  6023. }
  6024. this.fetchCache.set(filePath, {
  6025. duration,
  6026. timestamp,
  6027. result
  6028. });
  6029. return result;
  6030. }
  6031. async _transformRequest(id) {
  6032. var _a, _b, _c, _d;
  6033. debugRequest(id);
  6034. let result = null;
  6035. if ((_a = this.options.debug) == null ? void 0 : _a.loadDumppedModules) {
  6036. result = await ((_b = this.debugger) == null ? void 0 : _b.loadDump(id)) ?? null;
  6037. if (result)
  6038. return result;
  6039. }
  6040. if (this.getTransformMode(id) === "web") {
  6041. result = await this.server.transformRequest(id);
  6042. if (result)
  6043. result = await this.server.ssrTransform(result.code, result.map, id);
  6044. } else {
  6045. result = await this.server.transformRequest(id, { ssr: true });
  6046. }
  6047. const sourcemap = this.options.sourcemap ?? "inline";
  6048. if (sourcemap === "inline" && result && !id.includes("node_modules"))
  6049. withInlineSourcemap(result);
  6050. if ((_c = this.options.debug) == null ? void 0 : _c.dumpModules)
  6051. await ((_d = this.debugger) == null ? void 0 : _d.dumpFile(id, result));
  6052. return result;
  6053. }
  6054. }
  6055. class SnapshotManager {
  6056. constructor(options) {
  6057. this.options = options;
  6058. this.summary = void 0;
  6059. this.extension = ".snap";
  6060. this.clear();
  6061. }
  6062. clear() {
  6063. this.summary = emptySummary(this.options);
  6064. }
  6065. add(result) {
  6066. addSnapshotResult(this.summary, result);
  6067. }
  6068. resolvePath(testPath) {
  6069. const resolver = this.options.resolveSnapshotPath || (() => {
  6070. return join(
  6071. join(
  6072. dirname(testPath),
  6073. "__snapshots__"
  6074. ),
  6075. `${basename(testPath)}${this.extension}`
  6076. );
  6077. });
  6078. return resolver(testPath, this.extension);
  6079. }
  6080. }
  6081. function emptySummary(options) {
  6082. const summary = {
  6083. added: 0,
  6084. failure: false,
  6085. filesAdded: 0,
  6086. filesRemoved: 0,
  6087. filesRemovedList: [],
  6088. filesUnmatched: 0,
  6089. filesUpdated: 0,
  6090. matched: 0,
  6091. total: 0,
  6092. unchecked: 0,
  6093. uncheckedKeysByFile: [],
  6094. unmatched: 0,
  6095. updated: 0,
  6096. didUpdate: options.updateSnapshot === "all"
  6097. };
  6098. return summary;
  6099. }
  6100. function addSnapshotResult(summary, result) {
  6101. if (result.added)
  6102. summary.filesAdded++;
  6103. if (result.fileDeleted)
  6104. summary.filesRemoved++;
  6105. if (result.unmatched)
  6106. summary.filesUnmatched++;
  6107. if (result.updated)
  6108. summary.filesUpdated++;
  6109. summary.added += result.added;
  6110. summary.matched += result.matched;
  6111. summary.unchecked += result.unchecked;
  6112. if (result.uncheckedKeys && result.uncheckedKeys.length > 0) {
  6113. summary.uncheckedKeysByFile.push({
  6114. filePath: result.filepath,
  6115. keys: result.uncheckedKeys
  6116. });
  6117. }
  6118. summary.unmatched += result.unmatched;
  6119. summary.updated += result.updated;
  6120. summary.total += result.added + result.matched + result.unmatched + result.updated;
  6121. }
  6122. const workerPath = url.pathToFileURL(resolve(distDir, "./worker.mjs")).href;
  6123. const loaderPath = url.pathToFileURL(resolve(distDir, "./loader.mjs")).href;
  6124. const suppressLoaderWarningsPath = resolve(rootDir, "./suppress-warnings.cjs");
  6125. function createPool(ctx) {
  6126. var _a, _b, _c;
  6127. const threadsCount = ctx.config.watch ? Math.max(Math.floor(cpus().length / 2), 1) : Math.max(cpus().length - 1, 1);
  6128. const maxThreads = ctx.config.maxThreads ?? threadsCount;
  6129. const minThreads = ctx.config.minThreads ?? threadsCount;
  6130. const conditions = ((_a = ctx.server.config.resolve.conditions) == null ? void 0 : _a.flatMap((c) => ["-C", c])) || [];
  6131. const options = {
  6132. filename: workerPath,
  6133. useAtomics: false,
  6134. maxThreads,
  6135. minThreads,
  6136. execArgv: ctx.config.deps.registerNodeLoader ? [
  6137. "--require",
  6138. suppressLoaderWarningsPath,
  6139. "--experimental-loader",
  6140. loaderPath,
  6141. ...conditions
  6142. ] : conditions
  6143. };
  6144. if (ctx.config.isolate) {
  6145. options.isolateWorkers = true;
  6146. options.concurrentTasksPerWorker = 1;
  6147. }
  6148. if (!ctx.config.threads) {
  6149. options.concurrentTasksPerWorker = 1;
  6150. options.maxThreads = 1;
  6151. options.minThreads = 1;
  6152. }
  6153. (_c = (_b = ctx.coverageProvider) == null ? void 0 : _b.onBeforeFilesRun) == null ? void 0 : _c.call(_b);
  6154. options.env = {
  6155. TEST: "true",
  6156. VITEST: "true",
  6157. NODE_ENV: ctx.config.mode || "test",
  6158. VITEST_MODE: ctx.config.watch ? "WATCH" : "RUN",
  6159. ...process.env,
  6160. ...ctx.config.env
  6161. };
  6162. const pool = new Tinypool(options);
  6163. const runWithFiles = (name) => {
  6164. let id = 0;
  6165. async function runFiles(config, files, invalidates = []) {
  6166. ctx.state.clearFiles(files);
  6167. const { workerPort, port } = createChannel(ctx);
  6168. const workerId = ++id;
  6169. const data = {
  6170. port: workerPort,
  6171. config,
  6172. files,
  6173. invalidates,
  6174. workerId
  6175. };
  6176. try {
  6177. await pool.run(data, { transferList: [workerPort], name });
  6178. } finally {
  6179. port.close();
  6180. workerPort.close();
  6181. }
  6182. }
  6183. const Sequencer = ctx.config.sequence.sequencer;
  6184. const sequencer = new Sequencer(ctx);
  6185. return async (files, invalidates) => {
  6186. const config = ctx.getSerializableConfig();
  6187. if (config.shard)
  6188. files = await sequencer.shard(files);
  6189. files = await sequencer.sort(files);
  6190. if (!ctx.config.threads) {
  6191. await runFiles(config, files);
  6192. } else {
  6193. const results = await Promise.allSettled(files.map((file) => runFiles(config, [file], invalidates)));
  6194. const errors = results.filter((r) => r.status === "rejected").map((r) => r.reason);
  6195. if (errors.length > 0)
  6196. throw new AggregateErrorPonyfill(errors, "Errors occurred while running tests. For more information, see serialized error.");
  6197. }
  6198. };
  6199. };
  6200. return {
  6201. runTests: runWithFiles("run"),
  6202. close: async () => {
  6203. }
  6204. };
  6205. }
  6206. function createChannel(ctx) {
  6207. const channel = new MessageChannel();
  6208. const port = channel.port2;
  6209. const workerPort = channel.port1;
  6210. createBirpc(
  6211. {
  6212. onWorkerExit(code) {
  6213. process.exit(code || 1);
  6214. },
  6215. snapshotSaved(snapshot) {
  6216. ctx.snapshot.add(snapshot);
  6217. },
  6218. resolveSnapshotPath(testPath) {
  6219. return ctx.snapshot.resolvePath(testPath);
  6220. },
  6221. async getSourceMap(id, force) {
  6222. if (force) {
  6223. const mod = ctx.server.moduleGraph.getModuleById(id);
  6224. if (mod)
  6225. ctx.server.moduleGraph.invalidateModule(mod);
  6226. }
  6227. const r = await ctx.vitenode.transformRequest(id);
  6228. return r == null ? void 0 : r.map;
  6229. },
  6230. fetch(id) {
  6231. return ctx.vitenode.fetchModule(id);
  6232. },
  6233. resolveId(id, importer) {
  6234. return ctx.vitenode.resolveId(id, importer);
  6235. },
  6236. onPathsCollected(paths) {
  6237. ctx.state.collectPaths(paths);
  6238. ctx.report("onPathsCollected", paths);
  6239. },
  6240. onCollected(files) {
  6241. ctx.state.collectFiles(files);
  6242. ctx.report("onCollected", files);
  6243. },
  6244. onAfterSuiteRun(meta) {
  6245. var _a;
  6246. (_a = ctx.coverageProvider) == null ? void 0 : _a.onAfterSuiteRun(meta);
  6247. },
  6248. onTaskUpdate(packs) {
  6249. ctx.state.updateTasks(packs);
  6250. ctx.report("onTaskUpdate", packs);
  6251. },
  6252. onUserConsoleLog(log) {
  6253. ctx.state.updateUserLog(log);
  6254. ctx.report("onUserConsoleLog", log);
  6255. },
  6256. onUnhandledRejection(err) {
  6257. ctx.state.catchError(err, "Unhandled Rejection");
  6258. },
  6259. onFinished(files) {
  6260. ctx.report("onFinished", files, ctx.state.getUnhandledErrors());
  6261. }
  6262. },
  6263. {
  6264. post(v) {
  6265. port.postMessage(v);
  6266. },
  6267. on(fn) {
  6268. port.on("message", fn);
  6269. }
  6270. }
  6271. );
  6272. return { workerPort, port };
  6273. }
  6274. const F_RIGHT = "\u2192";
  6275. const F_DOWN = "\u2193";
  6276. const F_DOWN_RIGHT = "\u21B3";
  6277. const F_POINTER = "\u276F";
  6278. const F_DOT = "\xB7";
  6279. const F_CHECK = "\u2713";
  6280. const F_CROSS = "\xD7";
  6281. const F_LONG_DASH = "\u23AF";
  6282. const spinnerMap = /* @__PURE__ */ new WeakMap();
  6283. const hookSpinnerMap = /* @__PURE__ */ new WeakMap();
  6284. const pointer = picocolors.exports.yellow(F_POINTER);
  6285. const skipped = picocolors.exports.dim(picocolors.exports.gray(F_DOWN));
  6286. function getCols(delta = 0) {
  6287. var _a;
  6288. let length = (_a = process.stdout) == null ? void 0 : _a.columns;
  6289. if (!length || isNaN(length))
  6290. length = 30;
  6291. return Math.max(length + delta, 0);
  6292. }
  6293. function divider(text, left, right) {
  6294. const cols = getCols();
  6295. if (text) {
  6296. const textLength = stripAnsi(text).length;
  6297. if (left == null && right != null) {
  6298. left = cols - textLength - right;
  6299. } else {
  6300. left = left ?? Math.floor((cols - textLength) / 2);
  6301. right = cols - textLength - left;
  6302. }
  6303. left = Math.max(0, left);
  6304. right = Math.max(0, right);
  6305. return `${F_LONG_DASH.repeat(left)}${text}${F_LONG_DASH.repeat(right)}`;
  6306. }
  6307. return F_LONG_DASH.repeat(cols);
  6308. }
  6309. function formatTestPath(root, path) {
  6310. var _a;
  6311. if (isAbsolute(path))
  6312. path = relative(root, path);
  6313. const dir = dirname(path);
  6314. const ext = ((_a = path.match(/(\.(spec|test)\.[cm]?[tj]sx?)$/)) == null ? void 0 : _a[0]) || "";
  6315. const base = basename(path, ext);
  6316. return slash$2(picocolors.exports.dim(`${dir}/`) + picocolors.exports.bold(base)) + picocolors.exports.dim(ext);
  6317. }
  6318. function renderSnapshotSummary(rootDir, snapshots) {
  6319. const summary = [];
  6320. if (snapshots.added)
  6321. summary.push(picocolors.exports.bold(picocolors.exports.green(`${snapshots.added} written`)));
  6322. if (snapshots.unmatched)
  6323. summary.push(picocolors.exports.bold(picocolors.exports.red(`${snapshots.unmatched} failed`)));
  6324. if (snapshots.updated)
  6325. summary.push(picocolors.exports.bold(picocolors.exports.green(`${snapshots.updated} updated `)));
  6326. if (snapshots.filesRemoved) {
  6327. if (snapshots.didUpdate)
  6328. summary.push(picocolors.exports.bold(picocolors.exports.green(`${snapshots.filesRemoved} files removed `)));
  6329. else
  6330. summary.push(picocolors.exports.bold(picocolors.exports.yellow(`${snapshots.filesRemoved} files obsolete `)));
  6331. }
  6332. if (snapshots.filesRemovedList && snapshots.filesRemovedList.length) {
  6333. const [head, ...tail] = snapshots.filesRemovedList;
  6334. summary.push(`${picocolors.exports.gray(F_DOWN_RIGHT)} ${formatTestPath(rootDir, head)}`);
  6335. tail.forEach((key) => {
  6336. summary.push(` ${picocolors.exports.gray(F_DOT)} ${formatTestPath(rootDir, key)}`);
  6337. });
  6338. }
  6339. if (snapshots.unchecked) {
  6340. if (snapshots.didUpdate)
  6341. summary.push(picocolors.exports.bold(picocolors.exports.green(`${snapshots.unchecked} removed`)));
  6342. else
  6343. summary.push(picocolors.exports.bold(picocolors.exports.yellow(`${snapshots.unchecked} obsolete`)));
  6344. snapshots.uncheckedKeysByFile.forEach((uncheckedFile) => {
  6345. summary.push(`${picocolors.exports.gray(F_DOWN_RIGHT)} ${formatTestPath(rootDir, uncheckedFile.filePath)}`);
  6346. uncheckedFile.keys.forEach((key) => summary.push(` ${picocolors.exports.gray(F_DOT)} ${key}`));
  6347. });
  6348. }
  6349. return summary;
  6350. }
  6351. function getStateString(tasks, name = "tests") {
  6352. if (tasks.length === 0)
  6353. return picocolors.exports.dim(`no ${name}`);
  6354. const passed = tasks.filter((i) => {
  6355. var _a;
  6356. return ((_a = i.result) == null ? void 0 : _a.state) === "pass";
  6357. });
  6358. const failed = tasks.filter((i) => {
  6359. var _a;
  6360. return ((_a = i.result) == null ? void 0 : _a.state) === "fail";
  6361. });
  6362. const skipped2 = tasks.filter((i) => i.mode === "skip");
  6363. const todo = tasks.filter((i) => i.mode === "todo");
  6364. return [
  6365. failed.length ? picocolors.exports.bold(picocolors.exports.red(`${failed.length} failed`)) : null,
  6366. passed.length ? picocolors.exports.bold(picocolors.exports.green(`${passed.length} passed`)) : null,
  6367. skipped2.length ? picocolors.exports.yellow(`${skipped2.length} skipped`) : null,
  6368. todo.length ? picocolors.exports.gray(`${todo.length} todo`) : null
  6369. ].filter(Boolean).join(picocolors.exports.dim(" | ")) + picocolors.exports.gray(` (${tasks.length})`);
  6370. }
  6371. function getStateSymbol(task) {
  6372. if (task.mode === "skip" || task.mode === "todo")
  6373. return skipped;
  6374. if (!task.result)
  6375. return picocolors.exports.gray("\xB7");
  6376. if (task.result.state === "run") {
  6377. if (task.type === "suite")
  6378. return pointer;
  6379. let spinner = spinnerMap.get(task);
  6380. if (!spinner) {
  6381. spinner = elegantSpinner();
  6382. spinnerMap.set(task, spinner);
  6383. }
  6384. return picocolors.exports.yellow(spinner());
  6385. }
  6386. if (task.result.state === "pass") {
  6387. return task.type === "benchmark" ? picocolors.exports.green(F_DOT) : picocolors.exports.green(F_CHECK);
  6388. }
  6389. if (task.result.state === "fail") {
  6390. return task.type === "suite" ? pointer : picocolors.exports.red(F_CROSS);
  6391. }
  6392. return " ";
  6393. }
  6394. function getHookStateSymbol(task, hookName) {
  6395. var _a, _b;
  6396. const state = (_b = (_a = task.result) == null ? void 0 : _a.hooks) == null ? void 0 : _b[hookName];
  6397. if (state && state === "run") {
  6398. let spinnerMap2 = hookSpinnerMap.get(task);
  6399. if (!spinnerMap2) {
  6400. spinnerMap2 = /* @__PURE__ */ new Map();
  6401. hookSpinnerMap.set(task, spinnerMap2);
  6402. }
  6403. let spinner = spinnerMap2.get(hookName);
  6404. if (!spinner) {
  6405. spinner = elegantSpinner();
  6406. spinnerMap2.set(hookName, spinner);
  6407. }
  6408. return picocolors.exports.yellow(spinner());
  6409. }
  6410. }
  6411. const spinnerFrames = process.platform === "win32" ? ["-", "\\", "|", "/"] : ["\u280B", "\u2819", "\u2839", "\u2838", "\u283C", "\u2834", "\u2826", "\u2827", "\u2807", "\u280F"];
  6412. function elegantSpinner() {
  6413. let index = 0;
  6414. return () => {
  6415. index = ++index % spinnerFrames.length;
  6416. return spinnerFrames[index];
  6417. };
  6418. }
  6419. function formatTimeString(date) {
  6420. return date.toTimeString().split(" ")[0];
  6421. }
  6422. var _a;
  6423. const BADGE_PADDING = " ";
  6424. const HELP_HINT = `${picocolors.exports.dim("press ")}${picocolors.exports.bold("h")}${picocolors.exports.dim(" to show help")}`;
  6425. const HELP_UPDATE_SNAP = picocolors.exports.dim("press ") + picocolors.exports.bold(picocolors.exports.yellow("u")) + picocolors.exports.dim(" to update snapshot");
  6426. const HELP_QUITE = `${picocolors.exports.dim("press ")}${picocolors.exports.bold("q")}${picocolors.exports.dim(" to quit")}`;
  6427. const WAIT_FOR_CHANGE_PASS = `
  6428. ${picocolors.exports.bold(picocolors.exports.inverse(picocolors.exports.green(" PASS ")))}${picocolors.exports.green(" Waiting for file changes...")}`;
  6429. const WAIT_FOR_CHANGE_FAIL = `
  6430. ${picocolors.exports.bold(picocolors.exports.inverse(picocolors.exports.red(" FAIL ")))}${picocolors.exports.red(" Tests failed. Watching for file changes...")}`;
  6431. const DURATION_LONG$1 = 300;
  6432. const LAST_RUN_LOG_TIMEOUT = 1500;
  6433. class BaseReporter {
  6434. constructor() {
  6435. this.start = 0;
  6436. this.end = 0;
  6437. this.isTTY = isNode && ((_a = process.stdout) == null ? void 0 : _a.isTTY) && !process.env.CI;
  6438. this.ctx = void 0;
  6439. this._filesInWatchMode = /* @__PURE__ */ new Map();
  6440. this._lastRunTimeout = 0;
  6441. this._lastRunCount = 0;
  6442. this._timeStart = new Date();
  6443. this.registerUnhandledRejection();
  6444. }
  6445. get mode() {
  6446. return this.ctx.config.mode;
  6447. }
  6448. onInit(ctx) {
  6449. this.ctx = ctx;
  6450. ctx.logger.printBanner();
  6451. this.start = performance.now();
  6452. }
  6453. relative(path) {
  6454. return relativePath(this.ctx.config.root, path);
  6455. }
  6456. async onFinished(files = this.ctx.state.getFiles(), errors = this.ctx.state.getUnhandledErrors()) {
  6457. this.end = performance.now();
  6458. await this.reportSummary(files);
  6459. if (errors.length) {
  6460. if (!this.ctx.config.dangerouslyIgnoreUnhandledErrors)
  6461. process.exitCode = 1;
  6462. this.ctx.logger.printUnhandledErrors(errors);
  6463. }
  6464. }
  6465. onTaskUpdate(packs) {
  6466. var _a2, _b, _c;
  6467. if (this.isTTY)
  6468. return;
  6469. const logger = this.ctx.logger;
  6470. for (const pack of packs) {
  6471. const task = this.ctx.state.idMap.get(pack[0]);
  6472. if (task && "filepath" in task && ((_a2 = task.result) == null ? void 0 : _a2.state) && ((_b = task.result) == null ? void 0 : _b.state) !== "run") {
  6473. const tests = getTests(task);
  6474. const failed = tests.filter((t) => {
  6475. var _a3;
  6476. return ((_a3 = t.result) == null ? void 0 : _a3.state) === "fail";
  6477. });
  6478. const skipped = tests.filter((t) => t.mode === "skip" || t.mode === "todo");
  6479. let state = picocolors.exports.dim(`${tests.length} test${tests.length > 1 ? "s" : ""}`);
  6480. if (failed.length)
  6481. state += ` ${picocolors.exports.dim("|")} ${picocolors.exports.red(`${failed.length} failed`)}`;
  6482. if (skipped.length)
  6483. state += ` ${picocolors.exports.dim("|")} ${picocolors.exports.yellow(`${skipped.length} skipped`)}`;
  6484. let suffix = picocolors.exports.dim(" (") + state + picocolors.exports.dim(")");
  6485. if (task.result.duration) {
  6486. const color = task.result.duration > DURATION_LONG$1 ? picocolors.exports.yellow : picocolors.exports.gray;
  6487. suffix += color(` ${Math.round(task.result.duration)}${picocolors.exports.dim("ms")}`);
  6488. }
  6489. if (this.ctx.config.logHeapUsage && task.result.heap != null)
  6490. suffix += picocolors.exports.magenta(` ${Math.floor(task.result.heap / 1024 / 1024)} MB heap used`);
  6491. logger.log(` ${getStateSymbol(task)} ${task.name} ${suffix}`);
  6492. for (const test of failed) {
  6493. logger.log(picocolors.exports.red(` ${pointer} ${getFullName(test)}`));
  6494. logger.log(picocolors.exports.red(` ${F_RIGHT} ${(_c = test.result.error) == null ? void 0 : _c.message}`));
  6495. }
  6496. }
  6497. }
  6498. }
  6499. async onWatcherStart() {
  6500. this.resetLastRunLog();
  6501. const files = this.ctx.state.getFiles();
  6502. const errors = this.ctx.state.getUnhandledErrors();
  6503. const failed = errors.length > 0 || hasFailed(files);
  6504. const failedSnap = hasFailedSnapshot(files);
  6505. if (failed)
  6506. this.ctx.logger.log(WAIT_FOR_CHANGE_FAIL);
  6507. else
  6508. this.ctx.logger.log(WAIT_FOR_CHANGE_PASS);
  6509. const hints = [HELP_HINT];
  6510. if (failedSnap)
  6511. hints.unshift(HELP_UPDATE_SNAP);
  6512. else
  6513. hints.push(HELP_QUITE);
  6514. this.ctx.logger.log(BADGE_PADDING + hints.join(picocolors.exports.dim(", ")));
  6515. if (this._lastRunCount) {
  6516. const LAST_RUN_TEXT = `rerun x${this._lastRunCount}`;
  6517. const LAST_RUN_TEXTS = [
  6518. picocolors.exports.blue(LAST_RUN_TEXT),
  6519. picocolors.exports.gray(LAST_RUN_TEXT),
  6520. picocolors.exports.dim(picocolors.exports.gray(LAST_RUN_TEXT))
  6521. ];
  6522. this.ctx.logger.logUpdate(BADGE_PADDING + LAST_RUN_TEXTS[0]);
  6523. this._lastRunTimeout = 0;
  6524. this._lastRunTimer = safeSetInterval(
  6525. () => {
  6526. this._lastRunTimeout += 1;
  6527. if (this._lastRunTimeout >= LAST_RUN_TEXTS.length)
  6528. this.resetLastRunLog();
  6529. else
  6530. this.ctx.logger.logUpdate(BADGE_PADDING + LAST_RUN_TEXTS[this._lastRunTimeout]);
  6531. },
  6532. LAST_RUN_LOG_TIMEOUT / LAST_RUN_TEXTS.length
  6533. );
  6534. }
  6535. }
  6536. resetLastRunLog() {
  6537. safeClearInterval(this._lastRunTimer);
  6538. this._lastRunTimer = void 0;
  6539. this.ctx.logger.logUpdate.clear();
  6540. }
  6541. async onWatcherRerun(files, trigger) {
  6542. this.resetLastRunLog();
  6543. this.watchFilters = files;
  6544. files.forEach((filepath) => {
  6545. let reruns = this._filesInWatchMode.get(filepath) ?? 0;
  6546. this._filesInWatchMode.set(filepath, ++reruns);
  6547. });
  6548. const BADGE = picocolors.exports.inverse(picocolors.exports.bold(picocolors.exports.blue(" RERUN ")));
  6549. const TRIGGER = trigger ? picocolors.exports.dim(` ${this.relative(trigger)}`) : "";
  6550. if (files.length > 1) {
  6551. this.ctx.logger.clearScreen(`
  6552. ${BADGE}${TRIGGER}
  6553. `, true);
  6554. this._lastRunCount = 0;
  6555. } else if (files.length === 1) {
  6556. const rerun = this._filesInWatchMode.get(files[0]) ?? 1;
  6557. this._lastRunCount = rerun;
  6558. this.ctx.logger.clearScreen(`
  6559. ${BADGE}${TRIGGER} ${picocolors.exports.blue(`x${rerun}`)}
  6560. `);
  6561. }
  6562. this._timeStart = new Date();
  6563. this.start = performance.now();
  6564. }
  6565. onUserConsoleLog(log) {
  6566. if (!this.shouldLog(log))
  6567. return;
  6568. const task = log.taskId ? this.ctx.state.idMap.get(log.taskId) : void 0;
  6569. this.ctx.logger.log(picocolors.exports.gray(log.type + picocolors.exports.dim(` | ${task ? getFullName(task) : "unknown test"}`)));
  6570. process[log.type].write(`${log.content}
  6571. `);
  6572. }
  6573. shouldLog(log) {
  6574. var _a2, _b;
  6575. if (this.ctx.config.silent)
  6576. return false;
  6577. const shouldIgnore = (_b = (_a2 = this.ctx.config).onConsoleLog) == null ? void 0 : _b.call(_a2, log.content, log.type);
  6578. if (shouldIgnore === false)
  6579. return shouldIgnore;
  6580. return true;
  6581. }
  6582. onServerRestart(reason) {
  6583. this.ctx.logger.log(picocolors.exports.bold(picocolors.exports.magenta(
  6584. reason === "config" ? "\nRestarting due to config changes..." : "\nRestarting Vitest..."
  6585. )));
  6586. }
  6587. async reportSummary(files) {
  6588. await this.printErrorsSummary(files);
  6589. if (this.mode === "benchmark")
  6590. await this.reportBenchmarkSummary(files);
  6591. else
  6592. await this.reportTestSummary(files);
  6593. }
  6594. async reportTestSummary(files) {
  6595. const tests = getTests(files);
  6596. const logger = this.ctx.logger;
  6597. const executionTime = this.end - this.start;
  6598. const collectTime = files.reduce((acc, test) => acc + Math.max(0, test.collectDuration || 0), 0);
  6599. const setupTime = files.reduce((acc, test) => acc + Math.max(0, test.setupDuration || 0), 0);
  6600. const testsTime = files.reduce((acc, test) => {
  6601. var _a2;
  6602. return acc + Math.max(0, ((_a2 = test.result) == null ? void 0 : _a2.duration) || 0);
  6603. }, 0);
  6604. const transformTime = Array.from(this.ctx.vitenode.fetchCache.values()).reduce((a, b) => a + ((b == null ? void 0 : b.duration) || 0), 0);
  6605. const threadTime = collectTime + testsTime + setupTime;
  6606. const padTitle = (str) => picocolors.exports.dim(`${str.padStart(10)} `);
  6607. const time = (time2) => {
  6608. if (time2 > 1e3)
  6609. return `${(time2 / 1e3).toFixed(2)}s`;
  6610. return `${Math.round(time2)}ms`;
  6611. };
  6612. const snapshotOutput = renderSnapshotSummary(this.ctx.config.root, this.ctx.snapshot.summary);
  6613. if (snapshotOutput.length) {
  6614. logger.log(snapshotOutput.map(
  6615. (t, i) => i === 0 ? `${padTitle("Snapshots")} ${t}` : `${padTitle("")} ${t}`
  6616. ).join("\n"));
  6617. if (snapshotOutput.length > 1)
  6618. logger.log();
  6619. }
  6620. logger.log(padTitle("Test Files"), getStateString(files));
  6621. logger.log(padTitle("Tests"), getStateString(tests));
  6622. logger.log(padTitle("Start at"), formatTimeString(this._timeStart));
  6623. if (this.watchFilters)
  6624. logger.log(padTitle("Duration"), time(threadTime));
  6625. else
  6626. logger.log(padTitle("Duration"), time(executionTime) + picocolors.exports.dim(` (transform ${time(transformTime)}, setup ${time(setupTime)}, collect ${time(collectTime)}, tests ${time(testsTime)})`));
  6627. logger.log();
  6628. }
  6629. async printErrorsSummary(files) {
  6630. const logger = this.ctx.logger;
  6631. const suites = getSuites(files);
  6632. const tests = getTests(files);
  6633. const failedSuites = suites.filter((i) => {
  6634. var _a2;
  6635. return (_a2 = i.result) == null ? void 0 : _a2.error;
  6636. });
  6637. const failedTests = tests.filter((i) => {
  6638. var _a2;
  6639. return ((_a2 = i.result) == null ? void 0 : _a2.state) === "fail";
  6640. });
  6641. const failedTotal = failedSuites.length + failedTests.length;
  6642. let current = 1;
  6643. const errorDivider = () => logger.error(`${picocolors.exports.red(picocolors.exports.dim(divider(`[${current++}/${failedTotal}]`, void 0, 1)))}
  6644. `);
  6645. if (failedSuites.length) {
  6646. logger.error(picocolors.exports.red(divider(picocolors.exports.bold(picocolors.exports.inverse(` Failed Suites ${failedSuites.length} `)))));
  6647. logger.error();
  6648. await this.printTaskErrors(failedSuites, errorDivider);
  6649. }
  6650. if (failedTests.length) {
  6651. logger.error(picocolors.exports.red(divider(picocolors.exports.bold(picocolors.exports.inverse(` Failed Tests ${failedTests.length} `)))));
  6652. logger.error();
  6653. await this.printTaskErrors(failedTests, errorDivider);
  6654. }
  6655. return tests;
  6656. }
  6657. async reportBenchmarkSummary(files) {
  6658. const logger = this.ctx.logger;
  6659. const benchs = getTests(files);
  6660. const topBenchs = benchs.filter((i) => {
  6661. var _a2, _b;
  6662. return ((_b = (_a2 = i.result) == null ? void 0 : _a2.benchmark) == null ? void 0 : _b.rank) === 1;
  6663. });
  6664. logger.log(`
  6665. ${picocolors.exports.cyan(picocolors.exports.inverse(picocolors.exports.bold(" BENCH ")))} ${picocolors.exports.cyan("Summary")}
  6666. `);
  6667. for (const bench of topBenchs) {
  6668. const group = bench.suite;
  6669. const groupName = getFullName(group);
  6670. logger.log(` ${bench.name}${picocolors.exports.dim(` - ${groupName}`)}`);
  6671. const siblings = group.tasks.filter((i) => {
  6672. var _a2;
  6673. return ((_a2 = i.result) == null ? void 0 : _a2.benchmark) && i !== bench;
  6674. }).sort((a, b) => a.result.benchmark.rank - b.result.benchmark.rank);
  6675. for (const sibling of siblings) {
  6676. const number = `${(sibling.result.benchmark.mean / bench.result.benchmark.mean).toFixed(2)}x`;
  6677. logger.log(` ${picocolors.exports.green(number)} ${picocolors.exports.gray("faster than")} ${sibling.name}`);
  6678. }
  6679. logger.log("");
  6680. }
  6681. }
  6682. async printTaskErrors(tasks, errorDivider) {
  6683. var _a2;
  6684. const errorsQueue = [];
  6685. for (const task of tasks) {
  6686. const error = (_a2 = task.result) == null ? void 0 : _a2.error;
  6687. const errorItem = (error == null ? void 0 : error.stackStr) && errorsQueue.find((i) => {
  6688. var _a3;
  6689. return ((_a3 = i[0]) == null ? void 0 : _a3.stackStr) === error.stackStr;
  6690. });
  6691. if (errorItem)
  6692. errorItem[1].push(task);
  6693. else
  6694. errorsQueue.push([error, [task]]);
  6695. }
  6696. for (const [error, tasks2] of errorsQueue) {
  6697. for (const task of tasks2) {
  6698. const filepath = (task == null ? void 0 : task.filepath) || "";
  6699. let name = getFullName(task);
  6700. if (filepath)
  6701. name = `${name} ${picocolors.exports.dim(`[ ${this.relative(filepath)} ]`)}`;
  6702. this.ctx.logger.error(`${picocolors.exports.red(picocolors.exports.bold(picocolors.exports.inverse(" FAIL ")))} ${name}`);
  6703. }
  6704. await this.ctx.logger.printError(error);
  6705. errorDivider();
  6706. await Promise.resolve();
  6707. }
  6708. }
  6709. registerUnhandledRejection() {
  6710. process.on("unhandledRejection", async (err) => {
  6711. process.exitCode = 1;
  6712. await this.ctx.logger.printError(err, true, "Unhandled Rejection");
  6713. this.ctx.logger.error("\n\n");
  6714. process.exit(1);
  6715. });
  6716. }
  6717. }
  6718. const DURATION_LONG = 300;
  6719. const outputMap = /* @__PURE__ */ new WeakMap();
  6720. function formatFilepath(path) {
  6721. const lastSlash = Math.max(path.lastIndexOf("/") + 1, 0);
  6722. const basename = path.slice(lastSlash);
  6723. let firstDot = basename.indexOf(".");
  6724. if (firstDot < 0)
  6725. firstDot = basename.length;
  6726. firstDot += lastSlash;
  6727. return picocolors.exports.dim(path.slice(0, lastSlash)) + path.slice(lastSlash, firstDot) + picocolors.exports.dim(path.slice(firstDot));
  6728. }
  6729. function formatNumber(number) {
  6730. const res = String(number.toFixed(number < 100 ? 4 : 2)).split(".");
  6731. return res[0].replace(/(?=(?:\d{3})+$)(?!\b)/g, ",") + (res[1] ? `.${res[1]}` : "");
  6732. }
  6733. function renderHookState(task, hookName, level = 0) {
  6734. var _a, _b;
  6735. const state = (_b = (_a = task.result) == null ? void 0 : _a.hooks) == null ? void 0 : _b[hookName];
  6736. if (state && state === "run")
  6737. return `${" ".repeat(level)} ${getHookStateSymbol(task, hookName)} ${picocolors.exports.dim(`[ ${hookName} ]`)}`;
  6738. return "";
  6739. }
  6740. function renderBenchmarkItems(result) {
  6741. return [
  6742. result.name,
  6743. formatNumber(result.hz || 0),
  6744. formatNumber(result.p99 || 0),
  6745. `\xB1${result.rme.toFixed(2)}%`,
  6746. result.samples.length.toString()
  6747. ];
  6748. }
  6749. function renderBenchmark(task, tasks) {
  6750. var _a;
  6751. const result = (_a = task.result) == null ? void 0 : _a.benchmark;
  6752. if (!result)
  6753. return task.name;
  6754. const benchs = tasks.map((i) => {
  6755. var _a2;
  6756. return i.type === "benchmark" ? (_a2 = i.result) == null ? void 0 : _a2.benchmark : void 0;
  6757. }).filter(notNullish);
  6758. const allItems = benchs.map(renderBenchmarkItems);
  6759. const items = renderBenchmarkItems(result);
  6760. const padded = items.map((i, idx) => {
  6761. const width = Math.max(...allItems.map((i2) => i2[idx].length));
  6762. return idx ? i.padStart(width, " ") : i.padEnd(width, " ");
  6763. });
  6764. return [
  6765. padded[0],
  6766. picocolors.exports.dim(" "),
  6767. picocolors.exports.blue(padded[1]),
  6768. picocolors.exports.dim(" ops/sec "),
  6769. picocolors.exports.cyan(padded[3]),
  6770. picocolors.exports.dim(` (${padded[4]} samples)`),
  6771. result.rank === 1 ? picocolors.exports.bold(picocolors.exports.green(" fastest")) : result.rank === benchs.length && benchs.length > 2 ? picocolors.exports.bold(picocolors.exports.gray(" slowest")) : ""
  6772. ].join("");
  6773. }
  6774. function renderTree(tasks, options, level = 0) {
  6775. var _a, _b, _c, _d, _e, _f;
  6776. let output = [];
  6777. for (const task of tasks) {
  6778. let suffix = "";
  6779. const prefix = ` ${getStateSymbol(task)} `;
  6780. if (task.type === "test" && ((_a = task.result) == null ? void 0 : _a.retryCount) && task.result.retryCount > 1)
  6781. suffix += picocolors.exports.yellow(` (retry x${task.result.retryCount})`);
  6782. if (task.type === "suite")
  6783. suffix += picocolors.exports.dim(` (${getTests(task).length})`);
  6784. if (task.mode === "skip" || task.mode === "todo")
  6785. suffix += ` ${picocolors.exports.dim(picocolors.exports.gray("[skipped]"))}`;
  6786. if (((_b = task.result) == null ? void 0 : _b.duration) != null) {
  6787. if (task.result.duration > DURATION_LONG)
  6788. suffix += picocolors.exports.yellow(` ${Math.round(task.result.duration)}${picocolors.exports.dim("ms")}`);
  6789. }
  6790. if (options.showHeap && ((_c = task.result) == null ? void 0 : _c.heap) != null)
  6791. suffix += picocolors.exports.magenta(` ${Math.floor(task.result.heap / 1024 / 1024)} MB heap used`);
  6792. let name = task.name;
  6793. if (level === 0)
  6794. name = formatFilepath(name);
  6795. const padding = " ".repeat(level);
  6796. const body = task.type === "benchmark" ? renderBenchmark(task, tasks) : name;
  6797. output.push(padding + prefix + body + suffix);
  6798. if (((_d = task.result) == null ? void 0 : _d.state) !== "pass" && outputMap.get(task) != null) {
  6799. let data = outputMap.get(task);
  6800. if (typeof data === "string") {
  6801. data = stripAnsi(data.trim().split("\n").filter(Boolean).pop());
  6802. if (data === "")
  6803. data = void 0;
  6804. }
  6805. if (data != null) {
  6806. const out = `${" ".repeat(level)}${F_RIGHT} ${data}`;
  6807. output.push(` ${picocolors.exports.gray(cliTruncate(out, getCols(-3)))}`);
  6808. }
  6809. }
  6810. output = output.concat(renderHookState(task, "beforeAll", level + 1));
  6811. output = output.concat(renderHookState(task, "beforeEach", level + 1));
  6812. if (task.type === "suite" && task.tasks.length > 0) {
  6813. if (((_e = task.result) == null ? void 0 : _e.state) === "fail" || ((_f = task.result) == null ? void 0 : _f.state) === "run" || options.renderSucceed)
  6814. output = output.concat(renderTree(task.tasks, options, level + 1));
  6815. }
  6816. output = output.concat(renderHookState(task, "afterAll", level + 1));
  6817. output = output.concat(renderHookState(task, "afterEach", level + 1));
  6818. }
  6819. return output.filter(Boolean).join("\n");
  6820. }
  6821. const createListRenderer = (_tasks, options) => {
  6822. let tasks = _tasks;
  6823. let timer;
  6824. const log = options.logger.logUpdate;
  6825. function update() {
  6826. log(renderTree(tasks, options));
  6827. }
  6828. return {
  6829. start() {
  6830. if (timer)
  6831. return this;
  6832. timer = safeSetInterval(update, 200);
  6833. return this;
  6834. },
  6835. update(_tasks2) {
  6836. tasks = _tasks2;
  6837. update();
  6838. return this;
  6839. },
  6840. async stop() {
  6841. if (timer) {
  6842. safeClearInterval(timer);
  6843. timer = void 0;
  6844. }
  6845. log.clear();
  6846. options.logger.log(renderTree(tasks, options));
  6847. return this;
  6848. },
  6849. clear() {
  6850. log.clear();
  6851. }
  6852. };
  6853. };
  6854. class DefaultReporter extends BaseReporter {
  6855. constructor() {
  6856. super(...arguments);
  6857. this.rendererOptions = {};
  6858. }
  6859. async onTestRemoved(trigger) {
  6860. await this.stopListRender();
  6861. this.ctx.logger.clearScreen(picocolors.exports.yellow("Test removed...") + (trigger ? picocolors.exports.dim(` [ ${this.relative(trigger)} ]
  6862. `) : ""), true);
  6863. const files = this.ctx.state.getFiles(this.watchFilters);
  6864. createListRenderer(files, this.rendererOptions).stop();
  6865. this.ctx.logger.log();
  6866. await super.reportSummary(files);
  6867. super.onWatcherStart();
  6868. }
  6869. onCollected() {
  6870. if (this.isTTY) {
  6871. this.rendererOptions.logger = this.ctx.logger;
  6872. this.rendererOptions.showHeap = this.ctx.config.logHeapUsage;
  6873. const files = this.ctx.state.getFiles(this.watchFilters);
  6874. if (!this.renderer)
  6875. this.renderer = createListRenderer(files, this.rendererOptions).start();
  6876. else
  6877. this.renderer.update(files);
  6878. }
  6879. }
  6880. async onFinished(files = this.ctx.state.getFiles(), errors = this.ctx.state.getUnhandledErrors()) {
  6881. await this.stopListRender();
  6882. this.ctx.logger.log();
  6883. await super.onFinished(files, errors);
  6884. }
  6885. async onWatcherStart() {
  6886. await this.stopListRender();
  6887. await super.onWatcherStart();
  6888. }
  6889. async stopListRender() {
  6890. var _a;
  6891. await ((_a = this.renderer) == null ? void 0 : _a.stop());
  6892. this.renderer = void 0;
  6893. }
  6894. async onWatcherRerun(files, trigger) {
  6895. await this.stopListRender();
  6896. await super.onWatcherRerun(files, trigger);
  6897. }
  6898. onUserConsoleLog(log) {
  6899. var _a;
  6900. if (!this.shouldLog(log))
  6901. return;
  6902. (_a = this.renderer) == null ? void 0 : _a.clear();
  6903. super.onUserConsoleLog(log);
  6904. }
  6905. }
  6906. const check = picocolors.exports.green("\xB7");
  6907. const cross = picocolors.exports.red("x");
  6908. const pending = picocolors.exports.yellow("*");
  6909. const skip = picocolors.exports.dim(picocolors.exports.gray("-"));
  6910. function render(tasks) {
  6911. const all = getTests(tasks);
  6912. return all.map((i) => {
  6913. var _a;
  6914. if (i.mode === "skip" || i.mode === "todo")
  6915. return skip;
  6916. switch ((_a = i.result) == null ? void 0 : _a.state) {
  6917. case "pass":
  6918. return check;
  6919. case "fail":
  6920. return cross;
  6921. default:
  6922. return pending;
  6923. }
  6924. }).join("");
  6925. }
  6926. const createDotRenderer = (_tasks, options) => {
  6927. let tasks = _tasks;
  6928. let timer;
  6929. const log = options.logger.logUpdate;
  6930. function update() {
  6931. log(render(tasks));
  6932. }
  6933. return {
  6934. start() {
  6935. if (timer)
  6936. return this;
  6937. timer = safeSetInterval(update, 200);
  6938. return this;
  6939. },
  6940. update(_tasks2) {
  6941. tasks = _tasks2;
  6942. update();
  6943. return this;
  6944. },
  6945. async stop() {
  6946. if (timer) {
  6947. safeClearInterval(timer);
  6948. timer = void 0;
  6949. }
  6950. log.clear();
  6951. options.logger.log(render(tasks));
  6952. return this;
  6953. },
  6954. clear() {
  6955. log.clear();
  6956. }
  6957. };
  6958. };
  6959. class DotReporter extends BaseReporter {
  6960. onCollected() {
  6961. if (this.isTTY) {
  6962. const files = this.ctx.state.getFiles(this.watchFilters);
  6963. if (!this.renderer)
  6964. this.renderer = createDotRenderer(files, { logger: this.ctx.logger }).start();
  6965. else
  6966. this.renderer.update(files);
  6967. }
  6968. }
  6969. async onFinished(files = this.ctx.state.getFiles(), errors = this.ctx.state.getUnhandledErrors()) {
  6970. await this.stopListRender();
  6971. this.ctx.logger.log();
  6972. await super.onFinished(files, errors);
  6973. }
  6974. async onWatcherStart() {
  6975. await this.stopListRender();
  6976. super.onWatcherStart();
  6977. }
  6978. async stopListRender() {
  6979. var _a;
  6980. (_a = this.renderer) == null ? void 0 : _a.stop();
  6981. this.renderer = void 0;
  6982. await new Promise((resolve) => safeSetTimeout(resolve, 10));
  6983. }
  6984. async onWatcherRerun(files, trigger) {
  6985. await this.stopListRender();
  6986. await super.onWatcherRerun(files, trigger);
  6987. }
  6988. onUserConsoleLog(log) {
  6989. var _a;
  6990. (_a = this.renderer) == null ? void 0 : _a.clear();
  6991. super.onUserConsoleLog(log);
  6992. }
  6993. }
  6994. const getOutputFile = (config, reporter) => {
  6995. if (!(config == null ? void 0 : config.outputFile))
  6996. return;
  6997. if (typeof config.outputFile === "string")
  6998. return config.outputFile;
  6999. return config.outputFile[reporter];
  7000. };
  7001. const StatusMap = {
  7002. fail: "failed",
  7003. only: "pending",
  7004. pass: "passed",
  7005. run: "pending",
  7006. skip: "skipped",
  7007. todo: "todo"
  7008. };
  7009. class JsonReporter$1 {
  7010. constructor() {
  7011. this.start = 0;
  7012. }
  7013. onInit(ctx) {
  7014. this.ctx = ctx;
  7015. this.start = Date.now();
  7016. }
  7017. async logTasks(files) {
  7018. var _a, _b;
  7019. const suites = getSuites(files);
  7020. const numTotalTestSuites = suites.length;
  7021. const tests = getTests(files);
  7022. const numTotalTests = tests.length;
  7023. const numFailedTestSuites = suites.filter((s) => {
  7024. var _a2;
  7025. return (_a2 = s.result) == null ? void 0 : _a2.error;
  7026. }).length;
  7027. const numPassedTestSuites = numTotalTestSuites - numFailedTestSuites;
  7028. const numPendingTestSuites = suites.filter((s) => {
  7029. var _a2;
  7030. return ((_a2 = s.result) == null ? void 0 : _a2.state) === "run";
  7031. }).length;
  7032. const numFailedTests = tests.filter((t) => {
  7033. var _a2;
  7034. return ((_a2 = t.result) == null ? void 0 : _a2.state) === "fail";
  7035. }).length;
  7036. const numPassedTests = numTotalTests - numFailedTests;
  7037. const numPendingTests = tests.filter((t) => {
  7038. var _a2;
  7039. return ((_a2 = t.result) == null ? void 0 : _a2.state) === "run";
  7040. }).length;
  7041. const numTodoTests = tests.filter((t) => t.mode === "todo").length;
  7042. const testResults = [];
  7043. const success = numFailedTestSuites === 0 && numFailedTests === 0;
  7044. for (const file of files) {
  7045. const tests2 = getTests([file]);
  7046. let startTime = tests2.reduce((prev, next) => {
  7047. var _a2;
  7048. return Math.min(prev, ((_a2 = next.result) == null ? void 0 : _a2.startTime) ?? Infinity);
  7049. }, Infinity);
  7050. if (startTime === Infinity)
  7051. startTime = this.start;
  7052. const endTime = tests2.reduce((prev, next) => {
  7053. var _a2, _b2;
  7054. return Math.max(prev, (((_a2 = next.result) == null ? void 0 : _a2.startTime) ?? 0) + (((_b2 = next.result) == null ? void 0 : _b2.duration) ?? 0));
  7055. }, startTime);
  7056. const assertionResults = await Promise.all(tests2.map(async (t) => {
  7057. var _a2, _b2, _c, _d;
  7058. const ancestorTitles = [];
  7059. let iter = t.suite;
  7060. while (iter) {
  7061. ancestorTitles.push(iter.name);
  7062. iter = iter.suite;
  7063. }
  7064. ancestorTitles.reverse();
  7065. return {
  7066. ancestorTitles,
  7067. fullName: ancestorTitles.length > 0 ? `${ancestorTitles.join(" ")} ${t.name}` : t.name,
  7068. status: StatusMap[((_a2 = t.result) == null ? void 0 : _a2.state) || t.mode] || "skipped",
  7069. title: t.name,
  7070. duration: (_b2 = t.result) == null ? void 0 : _b2.duration,
  7071. failureMessages: ((_d = (_c = t.result) == null ? void 0 : _c.error) == null ? void 0 : _d.message) == null ? [] : [t.result.error.message],
  7072. location: await this.getFailureLocation(t)
  7073. };
  7074. }));
  7075. if (tests2.some((t) => {
  7076. var _a2;
  7077. return ((_a2 = t.result) == null ? void 0 : _a2.state) === "run";
  7078. })) {
  7079. this.ctx.logger.warn("WARNING: Some tests are still running when generating the JSON report.This is likely an internal bug in Vitest.Please report it to https://github.com/vitest-dev/vitest/issues");
  7080. }
  7081. testResults.push({
  7082. assertionResults,
  7083. startTime,
  7084. endTime,
  7085. status: tests2.every((t) => {
  7086. var _a2, _b2, _c;
  7087. return ((_a2 = t.result) == null ? void 0 : _a2.state) === "pass" || ((_b2 = t.result) == null ? void 0 : _b2.state) === "skip" || ((_c = t.result) == null ? void 0 : _c.state) === "todo";
  7088. }) ? "passed" : "failed",
  7089. message: ((_b = (_a = file.result) == null ? void 0 : _a.error) == null ? void 0 : _b.message) ?? "",
  7090. name: file.filepath
  7091. });
  7092. }
  7093. const result = {
  7094. numTotalTestSuites,
  7095. numPassedTestSuites,
  7096. numFailedTestSuites,
  7097. numPendingTestSuites,
  7098. numTotalTests,
  7099. numPassedTests,
  7100. numFailedTests,
  7101. numPendingTests,
  7102. numTodoTests,
  7103. startTime: this.start,
  7104. success,
  7105. testResults
  7106. };
  7107. await this.writeReport(JSON.stringify(result, null, 2));
  7108. }
  7109. async onFinished(files = this.ctx.state.getFiles()) {
  7110. await this.logTasks(files);
  7111. }
  7112. async writeReport(report) {
  7113. const outputFile = getOutputFile(this.ctx.config, "json");
  7114. if (outputFile) {
  7115. const reportFile = resolve(this.ctx.config.root, outputFile);
  7116. const outputDirectory = dirname(reportFile);
  7117. if (!existsSync(outputDirectory))
  7118. await promises.mkdir(outputDirectory, { recursive: true });
  7119. await promises.writeFile(reportFile, report, "utf-8");
  7120. this.ctx.logger.log(`JSON report written to ${reportFile}`);
  7121. } else {
  7122. this.ctx.logger.log(report);
  7123. }
  7124. }
  7125. async getFailureLocation(test) {
  7126. var _a;
  7127. const error = (_a = test.result) == null ? void 0 : _a.error;
  7128. if (!error)
  7129. return;
  7130. const stack = parseStacktrace(error);
  7131. await interpretSourcePos(stack, this.ctx);
  7132. const frame = stack[stack.length - 1];
  7133. if (!frame)
  7134. return;
  7135. const pos = frame.sourcePos || frame;
  7136. return { line: pos.line, column: pos.column };
  7137. }
  7138. }
  7139. class VerboseReporter extends DefaultReporter {
  7140. constructor() {
  7141. super();
  7142. this.rendererOptions.renderSucceed = true;
  7143. }
  7144. onTaskUpdate(packs) {
  7145. var _a, _b, _c;
  7146. if (this.isTTY)
  7147. return;
  7148. for (const pack of packs) {
  7149. const task = this.ctx.state.idMap.get(pack[0]);
  7150. if (task && task.type === "test" && ((_a = task.result) == null ? void 0 : _a.state) && ((_b = task.result) == null ? void 0 : _b.state) !== "run") {
  7151. let title = ` ${getStateSymbol(task)} ${getFullName(task)}`;
  7152. if (this.ctx.config.logHeapUsage && task.result.heap != null)
  7153. title += picocolors.exports.magenta(` ${Math.floor(task.result.heap / 1024 / 1024)} MB heap used`);
  7154. this.ctx.logger.log(title);
  7155. if (task.result.state === "fail")
  7156. this.ctx.logger.log(picocolors.exports.red(` ${F_RIGHT} ${(_c = task.result.error) == null ? void 0 : _c.message}`));
  7157. }
  7158. }
  7159. }
  7160. }
  7161. class IndentedLogger {
  7162. constructor(baseLog) {
  7163. this.baseLog = baseLog;
  7164. this.currentIndent = "";
  7165. }
  7166. indent() {
  7167. this.currentIndent += " ";
  7168. }
  7169. unindent() {
  7170. this.currentIndent = this.currentIndent.substring(0, this.currentIndent.length - 4);
  7171. }
  7172. log(text) {
  7173. return this.baseLog(this.currentIndent + text);
  7174. }
  7175. }
  7176. function yamlString(str) {
  7177. return `"${str.replace(/"/g, '\\"')}"`;
  7178. }
  7179. function tapString(str) {
  7180. return str.replace(/\\/g, "\\\\").replace(/#/g, "\\#").replace(/\n/g, " ");
  7181. }
  7182. class TapReporter {
  7183. onInit(ctx) {
  7184. this.ctx = ctx;
  7185. this.logger = new IndentedLogger(ctx.logger.log.bind(ctx.logger));
  7186. }
  7187. static getComment(task) {
  7188. var _a;
  7189. if (task.mode === "skip")
  7190. return " # SKIP";
  7191. else if (task.mode === "todo")
  7192. return " # TODO";
  7193. else if (((_a = task.result) == null ? void 0 : _a.duration) != null)
  7194. return ` # time=${task.result.duration.toFixed(2)}ms`;
  7195. else
  7196. return "";
  7197. }
  7198. logErrorDetails(error, stack) {
  7199. this.logger.log(`name: ${yamlString(error.name)}`);
  7200. this.logger.log(`message: ${yamlString(error.message)}`);
  7201. if (stack) {
  7202. this.logger.log(`stack: ${yamlString(`${stack.file}:${stack.line}:${stack.column}`)}`);
  7203. }
  7204. }
  7205. logTasks(tasks) {
  7206. var _a, _b;
  7207. this.logger.log(`1..${tasks.length}`);
  7208. for (const [i, task] of tasks.entries()) {
  7209. const id = i + 1;
  7210. const ok = ((_a = task.result) == null ? void 0 : _a.state) === "pass" || task.mode === "skip" || task.mode === "todo" ? "ok" : "not ok";
  7211. const comment = TapReporter.getComment(task);
  7212. if (task.type === "suite" && task.tasks.length > 0) {
  7213. this.logger.log(`${ok} ${id} - ${tapString(task.name)}${comment} {`);
  7214. this.logger.indent();
  7215. this.logTasks(task.tasks);
  7216. this.logger.unindent();
  7217. this.logger.log("}");
  7218. } else {
  7219. this.logger.log(`${ok} ${id} - ${tapString(task.name)}${comment}`);
  7220. if (((_b = task.result) == null ? void 0 : _b.state) === "fail" && task.result.error) {
  7221. this.logger.indent();
  7222. const error = task.result.error;
  7223. const stacks = parseStacktrace(error);
  7224. const stack = stacks[0];
  7225. this.logger.log("---");
  7226. this.logger.log("error:");
  7227. this.logger.indent();
  7228. this.logErrorDetails(error);
  7229. this.logger.unindent();
  7230. if (stack)
  7231. this.logger.log(`at: ${yamlString(`${stack.file}:${stack.line}:${stack.column}`)}`);
  7232. if (error.showDiff) {
  7233. this.logger.log(`actual: ${yamlString(error.actual)}`);
  7234. this.logger.log(`expected: ${yamlString(error.expected)}`);
  7235. }
  7236. this.logger.log("...");
  7237. this.logger.unindent();
  7238. }
  7239. }
  7240. }
  7241. }
  7242. async onFinished(files = this.ctx.state.getFiles()) {
  7243. this.logger.log("TAP version 13");
  7244. this.logTasks(files);
  7245. }
  7246. }
  7247. function flattenTasks$1(task, baseName = "") {
  7248. const base = baseName ? `${baseName} > ` : "";
  7249. if (task.type === "suite") {
  7250. return task.tasks.flatMap((child) => flattenTasks$1(child, `${base}${task.name}`));
  7251. } else {
  7252. return [{
  7253. ...task,
  7254. name: `${base}${task.name}`
  7255. }];
  7256. }
  7257. }
  7258. function removeInvalidXMLCharacters(value, removeDiscouragedChars) {
  7259. let regex = /((?:[\0-\x08\x0B\f\x0E-\x1F\uFFFD\uFFFE\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF]))/g;
  7260. value = String(value || "").replace(regex, "");
  7261. if (removeDiscouragedChars) {
  7262. regex = new RegExp(
  7263. "([\\x7F-\\x84]|[\\x86-\\x9F]|[\\uFDD0-\\uFDEF]|(?:\\uD83F[\\uDFFE\\uDFFF])|(?:\\uD87F[\\uDFFE\\uDFFF])|(?:\\uD8BF[\\uDFFE\\uDFFF])|(?:\\uD8FF[\\uDFFE\\uDFFF])|(?:\\uD93F[\\uDFFE\\uDFFF])|(?:\\uD97F[\\uDFFE\\uDFFF])|(?:\\uD9BF[\\uDFFE\\uDFFF])|(?:\\uD9FF[\\uDFFE\\uDFFF])|(?:\\uDA3F[\\uDFFE\\uDFFF])|(?:\\uDA7F[\\uDFFE\\uDFFF])|(?:\\uDABF[\\uDFFE\\uDFFF])|(?:\\uDAFF[\\uDFFE\\uDFFF])|(?:\\uDB3F[\\uDFFE\\uDFFF])|(?:\\uDB7F[\\uDFFE\\uDFFF])|(?:\\uDBBF[\\uDFFE\\uDFFF])|(?:\\uDBFF[\\uDFFE\\uDFFF])(?:[\\0-\\t\\x0B\\f\\x0E-\\u2027\\u202A-\\uD7FF\\uE000-\\uFFFF]|[\\uD800-\\uDBFF][\\uDC00-\\uDFFF]|[\\uD800-\\uDBFF](?![\\uDC00-\\uDFFF])|(?:[^\\uD800-\\uDBFF]|^)[\\uDC00-\\uDFFF]))",
  7264. "g"
  7265. );
  7266. value = value.replace(regex, "");
  7267. }
  7268. return value;
  7269. }
  7270. function escapeXML(value) {
  7271. return removeInvalidXMLCharacters(
  7272. String(value).replace(/&/g, "&amp;").replace(/"/g, "&quot;").replace(/'/g, "&apos;").replace(/</g, "&lt;").replace(/>/g, "&gt;"),
  7273. true
  7274. );
  7275. }
  7276. function getDuration(task) {
  7277. var _a;
  7278. const duration = ((_a = task.result) == null ? void 0 : _a.duration) ?? 0;
  7279. return (duration / 1e3).toLocaleString(void 0, { useGrouping: false, maximumFractionDigits: 10 });
  7280. }
  7281. class JUnitReporter {
  7282. async onInit(ctx) {
  7283. this.ctx = ctx;
  7284. const outputFile = getOutputFile(this.ctx.config, "junit");
  7285. if (outputFile) {
  7286. this.reportFile = resolve(this.ctx.config.root, outputFile);
  7287. const outputDirectory = dirname(this.reportFile);
  7288. if (!existsSync(outputDirectory))
  7289. await promises.mkdir(outputDirectory, { recursive: true });
  7290. const fileFd = await promises.open(this.reportFile, "w+");
  7291. this.baseLog = async (text) => await promises.writeFile(fileFd, `${text}
  7292. `);
  7293. } else {
  7294. this.baseLog = async (text) => this.ctx.logger.log(text);
  7295. }
  7296. this.logger = new IndentedLogger(this.baseLog);
  7297. }
  7298. async writeElement(name, attrs, children) {
  7299. const pairs = [];
  7300. for (const key in attrs) {
  7301. const attr = attrs[key];
  7302. if (attr === void 0)
  7303. continue;
  7304. pairs.push(`${key}="${escapeXML(attr)}"`);
  7305. }
  7306. await this.logger.log(`<${name}${pairs.length ? ` ${pairs.join(" ")}` : ""}>`);
  7307. this.logger.indent();
  7308. await children.call(this);
  7309. this.logger.unindent();
  7310. await this.logger.log(`</${name}>`);
  7311. }
  7312. async writeErrorDetails(error) {
  7313. const errorName = error.name ?? error.nameStr ?? "Unknown Error";
  7314. const errorDetails = `${errorName}: ${error.message}`;
  7315. await this.baseLog(escapeXML(errorDetails));
  7316. const stack = parseStacktrace(error);
  7317. for (const frame of stack) {
  7318. const pos = frame.sourcePos ?? frame;
  7319. const path = relative(this.ctx.config.root, frame.file);
  7320. await this.baseLog(` ${F_POINTER} ${[frame.method, `${path}:${pos.line}:${pos.column}`].filter(Boolean).join(" ")}`);
  7321. if (frame.file in this.ctx.state.filesMap)
  7322. break;
  7323. }
  7324. }
  7325. async writeLogs(task, type) {
  7326. if (task.logs == null || task.logs.length === 0)
  7327. return;
  7328. const logType = type === "err" ? "stderr" : "stdout";
  7329. const logs = task.logs.filter((log) => log.type === logType);
  7330. if (logs.length === 0)
  7331. return;
  7332. await this.writeElement(`system-${type}`, {}, async () => {
  7333. for (const log of logs)
  7334. await this.baseLog(escapeXML(log.content));
  7335. });
  7336. }
  7337. async writeTasks(tasks, filename) {
  7338. for (const task of tasks) {
  7339. await this.writeElement("testcase", {
  7340. classname: filename,
  7341. name: task.name,
  7342. time: getDuration(task)
  7343. }, async () => {
  7344. var _a;
  7345. await this.writeLogs(task, "out");
  7346. await this.writeLogs(task, "err");
  7347. if (task.mode === "skip" || task.mode === "todo")
  7348. this.logger.log("<skipped/>");
  7349. if (((_a = task.result) == null ? void 0 : _a.state) === "fail") {
  7350. const error = task.result.error;
  7351. await this.writeElement("failure", {
  7352. message: error == null ? void 0 : error.message,
  7353. type: (error == null ? void 0 : error.name) ?? (error == null ? void 0 : error.nameStr)
  7354. }, async () => {
  7355. if (!error)
  7356. return;
  7357. await this.writeErrorDetails(error);
  7358. });
  7359. }
  7360. });
  7361. }
  7362. }
  7363. async onFinished(files = this.ctx.state.getFiles()) {
  7364. await this.logger.log('<?xml version="1.0" encoding="UTF-8" ?>');
  7365. const transformed = files.map((file) => {
  7366. const tasks = file.tasks.flatMap((task) => flattenTasks$1(task));
  7367. const stats = tasks.reduce(
  7368. (stats2, task) => {
  7369. var _a, _b;
  7370. return {
  7371. passed: stats2.passed + Number(((_a = task.result) == null ? void 0 : _a.state) === "pass"),
  7372. failures: stats2.failures + Number(((_b = task.result) == null ? void 0 : _b.state) === "fail"),
  7373. skipped: stats2.skipped + Number(task.mode === "skip" || task.mode === "todo")
  7374. };
  7375. },
  7376. {
  7377. passed: 0,
  7378. failures: 0,
  7379. skipped: 0
  7380. }
  7381. );
  7382. return {
  7383. ...file,
  7384. tasks,
  7385. stats
  7386. };
  7387. });
  7388. await this.writeElement("testsuites", {}, async () => {
  7389. for (const file of transformed) {
  7390. await this.writeElement("testsuite", {
  7391. name: file.name,
  7392. timestamp: new Date().toISOString(),
  7393. hostname: hostname(),
  7394. tests: file.tasks.length,
  7395. failures: file.stats.failures,
  7396. errors: 0,
  7397. skipped: file.stats.skipped,
  7398. time: getDuration(file)
  7399. }, async () => {
  7400. await this.writeTasks(file.tasks, file.name);
  7401. });
  7402. }
  7403. });
  7404. if (this.reportFile)
  7405. this.ctx.logger.log(`JUNIT report written to ${this.reportFile}`);
  7406. }
  7407. }
  7408. function flattenTasks(task, baseName = "") {
  7409. const base = baseName ? `${baseName} > ` : "";
  7410. if (task.type === "suite" && task.tasks.length > 0) {
  7411. return task.tasks.flatMap((child) => flattenTasks(child, `${base}${task.name}`));
  7412. } else {
  7413. return [{
  7414. ...task,
  7415. name: `${base}${task.name}`
  7416. }];
  7417. }
  7418. }
  7419. class TapFlatReporter extends TapReporter {
  7420. onInit(ctx) {
  7421. super.onInit(ctx);
  7422. }
  7423. async onFinished(files = this.ctx.state.getFiles()) {
  7424. this.ctx.logger.log("TAP version 13");
  7425. const flatTasks = files.flatMap((task) => flattenTasks(task));
  7426. this.logTasks(flatTasks);
  7427. }
  7428. }
  7429. class JsonReporter {
  7430. constructor() {
  7431. this.start = 0;
  7432. }
  7433. onInit(ctx) {
  7434. this.ctx = ctx;
  7435. }
  7436. async logTasks(files) {
  7437. var _a;
  7438. const suites = getSuites(files);
  7439. const numTotalTestSuites = suites.length;
  7440. const tests = getTests(files);
  7441. const numTotalTests = tests.length;
  7442. const testResults = {};
  7443. const outputFile = getOutputFile(this.ctx.config.benchmark, "json");
  7444. for (const file of files) {
  7445. const tests2 = getTests([file]);
  7446. for (const test of tests2) {
  7447. const res = (_a = test.result) == null ? void 0 : _a.benchmark;
  7448. if (!res || test.mode === "skip")
  7449. continue;
  7450. if (!outputFile)
  7451. res.samples = "ignore on terminal";
  7452. testResults[test.suite.name] = (testResults[test.suite.name] || []).concat(res);
  7453. }
  7454. if (tests2.some((t) => {
  7455. var _a2;
  7456. return ((_a2 = t.result) == null ? void 0 : _a2.state) === "run";
  7457. })) {
  7458. this.ctx.logger.warn("WARNING: Some tests are still running when generating the json report.This is likely an internal bug in Vitest.Please report it to https://github.com/vitest-dev/vitest/issues");
  7459. }
  7460. }
  7461. const result = {
  7462. numTotalTestSuites,
  7463. numTotalTests,
  7464. testResults
  7465. };
  7466. await this.writeReport(JSON.stringify(result, null, 2));
  7467. }
  7468. async onFinished(files = this.ctx.state.getFiles()) {
  7469. await this.logTasks(files);
  7470. }
  7471. async writeReport(report) {
  7472. const outputFile = getOutputFile(this.ctx.config.benchmark, "json");
  7473. if (outputFile) {
  7474. const reportFile = resolve(this.ctx.config.root, outputFile);
  7475. const outputDirectory = dirname(reportFile);
  7476. if (!existsSync(outputDirectory))
  7477. await promises.mkdir(outputDirectory, { recursive: true });
  7478. await promises.writeFile(reportFile, report, "utf-8");
  7479. this.ctx.logger.log(`json report written to ${reportFile}`);
  7480. } else {
  7481. this.ctx.logger.log(report);
  7482. }
  7483. }
  7484. }
  7485. const BenchmarkReportsMap = {
  7486. default: VerboseReporter,
  7487. json: JsonReporter
  7488. };
  7489. const ReportersMap = {
  7490. "default": DefaultReporter,
  7491. "verbose": VerboseReporter,
  7492. "dot": DotReporter,
  7493. "json": JsonReporter$1,
  7494. "tap": TapReporter,
  7495. "tap-flat": TapFlatReporter,
  7496. "junit": JUnitReporter
  7497. };
  7498. async function loadCustomReporterModule(path, runner) {
  7499. let customReporterModule;
  7500. try {
  7501. customReporterModule = await runner.executeId(path);
  7502. } catch (customReporterModuleError) {
  7503. throw new Error(`Failed to load custom Reporter from ${path}`, { cause: customReporterModuleError });
  7504. }
  7505. if (customReporterModule.default === null || customReporterModule.default === void 0)
  7506. throw new Error(`Custom reporter loaded from ${path} was not the default export`);
  7507. return customReporterModule.default;
  7508. }
  7509. function createReporters(reporterReferences, runner) {
  7510. const promisedReporters = reporterReferences.map(async (referenceOrInstance) => {
  7511. if (typeof referenceOrInstance === "string") {
  7512. if (referenceOrInstance in ReportersMap) {
  7513. const BuiltinReporter = ReportersMap[referenceOrInstance];
  7514. return new BuiltinReporter();
  7515. } else {
  7516. const CustomReporter = await loadCustomReporterModule(referenceOrInstance, runner);
  7517. return new CustomReporter();
  7518. }
  7519. }
  7520. return referenceOrInstance;
  7521. });
  7522. return Promise.all(promisedReporters);
  7523. }
  7524. function createBenchmarkReporters(reporterReferences, runner) {
  7525. const promisedReporters = reporterReferences.map(async (referenceOrInstance) => {
  7526. if (typeof referenceOrInstance === "string") {
  7527. if (referenceOrInstance in BenchmarkReportsMap) {
  7528. const BuiltinReporter = BenchmarkReportsMap[referenceOrInstance];
  7529. return new BuiltinReporter();
  7530. } else {
  7531. const CustomReporter = await loadCustomReporterModule(referenceOrInstance, runner);
  7532. return new CustomReporter();
  7533. }
  7534. }
  7535. return referenceOrInstance;
  7536. });
  7537. return Promise.all(promisedReporters);
  7538. }
  7539. const isAggregateError = (err) => {
  7540. if (typeof AggregateError !== "undefined" && err instanceof AggregateError)
  7541. return true;
  7542. return err instanceof Error && "errors" in err;
  7543. };
  7544. class StateManager {
  7545. constructor() {
  7546. this.filesMap = /* @__PURE__ */ new Map();
  7547. this.pathsSet = /* @__PURE__ */ new Set();
  7548. this.collectingPromise = void 0;
  7549. this.idMap = /* @__PURE__ */ new Map();
  7550. this.taskFileMap = /* @__PURE__ */ new WeakMap();
  7551. this.errorsSet = /* @__PURE__ */ new Set();
  7552. }
  7553. catchError(err, type) {
  7554. if (isAggregateError(err))
  7555. return err.errors.forEach((error) => this.catchError(error, type));
  7556. err.type = type;
  7557. this.errorsSet.add(err);
  7558. }
  7559. clearErrors() {
  7560. this.errorsSet.clear();
  7561. }
  7562. getUnhandledErrors() {
  7563. return Array.from(this.errorsSet.values());
  7564. }
  7565. startCollectingPaths() {
  7566. let _resolve;
  7567. const promise = new Promise((resolve) => {
  7568. _resolve = resolve;
  7569. });
  7570. this.collectingPromise = { promise, resolve: _resolve };
  7571. }
  7572. finishCollectingPaths() {
  7573. var _a;
  7574. (_a = this.collectingPromise) == null ? void 0 : _a.resolve();
  7575. this.collectingPromise = void 0;
  7576. }
  7577. async getPaths() {
  7578. var _a;
  7579. await ((_a = this.collectingPromise) == null ? void 0 : _a.promise);
  7580. return Array.from(this.pathsSet);
  7581. }
  7582. getFiles(keys) {
  7583. if (keys)
  7584. return keys.map((key) => this.filesMap.get(key)).filter(Boolean);
  7585. return Array.from(this.filesMap.values());
  7586. }
  7587. getFilepaths() {
  7588. return Array.from(this.filesMap.keys());
  7589. }
  7590. getFailedFilepaths() {
  7591. return this.getFiles().filter((i) => {
  7592. var _a;
  7593. return ((_a = i.result) == null ? void 0 : _a.state) === "fail";
  7594. }).map((i) => i.filepath);
  7595. }
  7596. collectPaths(paths = []) {
  7597. paths.forEach((path) => {
  7598. this.pathsSet.add(path);
  7599. });
  7600. }
  7601. collectFiles(files = []) {
  7602. files.forEach((file) => {
  7603. this.filesMap.set(file.filepath, file);
  7604. this.updateId(file);
  7605. });
  7606. }
  7607. clearFiles(paths = []) {
  7608. paths.forEach((path) => {
  7609. this.filesMap.delete(path);
  7610. });
  7611. }
  7612. updateId(task) {
  7613. if (this.idMap.get(task.id) === task)
  7614. return;
  7615. this.idMap.set(task.id, task);
  7616. if (task.type === "suite") {
  7617. task.tasks.forEach((task2) => {
  7618. this.updateId(task2);
  7619. });
  7620. }
  7621. }
  7622. updateTasks(packs) {
  7623. for (const [id, result] of packs) {
  7624. if (this.idMap.has(id))
  7625. this.idMap.get(id).result = result;
  7626. }
  7627. }
  7628. updateUserLog(log) {
  7629. const task = log.taskId && this.idMap.get(log.taskId);
  7630. if (task) {
  7631. if (!task.logs)
  7632. task.logs = [];
  7633. task.logs.push(log);
  7634. }
  7635. }
  7636. }
  7637. const defaultInclude = ["**/*.{test,spec}.{js,mjs,cjs,ts,mts,cts,jsx,tsx}"];
  7638. const defaultExclude = ["**/node_modules/**", "**/dist/**", "**/cypress/**", "**/.{idea,git,cache,output,temp}/**"];
  7639. const benchmarkConfigDefaults = {
  7640. include: ["**/*.{bench,benchmark}.{js,mjs,cjs,ts,mts,cts,jsx,tsx}"],
  7641. exclude: defaultExclude,
  7642. includeSource: [],
  7643. reporters: ["default"]
  7644. };
  7645. const defaultCoverageExcludes = [
  7646. "coverage/**",
  7647. "dist/**",
  7648. "packages/*/test{,s}/**",
  7649. "**/*.d.ts",
  7650. "cypress/**",
  7651. "test{,s}/**",
  7652. "test{,-*}.{js,cjs,mjs,ts,tsx,jsx}",
  7653. "**/*{.,-}test.{js,cjs,mjs,ts,tsx,jsx}",
  7654. "**/*{.,-}spec.{js,cjs,mjs,ts,tsx,jsx}",
  7655. "**/__tests__/**",
  7656. "**/{karma,rollup,webpack,vite,vitest,jest,ava,babel,nyc,cypress}.config.{js,cjs,mjs,ts}",
  7657. "**/.{eslint,mocha,prettier}rc.{js,cjs,yml}"
  7658. ];
  7659. const coverageConfigDefaults = {
  7660. provider: "c8",
  7661. enabled: false,
  7662. clean: true,
  7663. cleanOnRerun: false,
  7664. reportsDirectory: "./coverage",
  7665. excludeNodeModules: true,
  7666. exclude: defaultCoverageExcludes,
  7667. reporter: ["text", "html", "clover", "json"],
  7668. allowExternal: false,
  7669. extension: [".js", ".cjs", ".mjs", ".ts", ".tsx", ".jsx", ".vue", ".svelte"]
  7670. };
  7671. const fakeTimersDefaults = {
  7672. loopLimit: 1e4,
  7673. shouldClearNativeTimers: true,
  7674. toFake: [
  7675. "setTimeout",
  7676. "clearTimeout",
  7677. "setInterval",
  7678. "clearInterval",
  7679. "setImmediate",
  7680. "clearImmediate",
  7681. "Date"
  7682. ]
  7683. };
  7684. const config = {
  7685. allowOnly: !process.env.CI,
  7686. watch: !process.env.CI,
  7687. globals: false,
  7688. environment: "node",
  7689. threads: true,
  7690. clearMocks: false,
  7691. restoreMocks: false,
  7692. mockReset: false,
  7693. include: defaultInclude,
  7694. exclude: defaultExclude,
  7695. testTimeout: 5e3,
  7696. hookTimeout: 1e4,
  7697. teardownTimeout: 1e3,
  7698. isolate: true,
  7699. watchExclude: ["**/node_modules/**", "**/dist/**"],
  7700. forceRerunTriggers: [
  7701. "**/package.json/**",
  7702. "**/vitest.config.*/**",
  7703. "**/vite.config.*/**"
  7704. ],
  7705. update: false,
  7706. reporters: [],
  7707. silent: false,
  7708. api: false,
  7709. ui: false,
  7710. uiBase: "/__vitest__/",
  7711. open: true,
  7712. css: {
  7713. include: []
  7714. },
  7715. coverage: coverageConfigDefaults,
  7716. fakeTimers: fakeTimersDefaults,
  7717. maxConcurrency: 5,
  7718. dangerouslyIgnoreUnhandledErrors: false
  7719. };
  7720. const configDefaults = Object.freeze(config);
  7721. class FilesStatsCache {
  7722. constructor() {
  7723. this.cache = /* @__PURE__ */ new Map();
  7724. }
  7725. getStats(fsPath) {
  7726. return this.cache.get(fsPath);
  7727. }
  7728. async updateStats(fsPath) {
  7729. if (!fs$8.existsSync(fsPath))
  7730. return;
  7731. const stats = await fs$8.promises.stat(fsPath);
  7732. this.cache.set(fsPath, { size: stats.size });
  7733. }
  7734. removeStats(fsPath) {
  7735. this.cache.delete(fsPath);
  7736. }
  7737. }
  7738. class ResultsCache {
  7739. constructor() {
  7740. this.cache = /* @__PURE__ */ new Map();
  7741. this.cachePath = null;
  7742. this.version = version$1;
  7743. this.root = "/";
  7744. }
  7745. getCachePath() {
  7746. return this.cachePath;
  7747. }
  7748. setConfig(root, config) {
  7749. this.root = root;
  7750. if (config)
  7751. this.cachePath = resolve(config.dir, "results.json");
  7752. }
  7753. getResults(fsPath) {
  7754. return this.cache.get(fsPath == null ? void 0 : fsPath.slice(this.root.length));
  7755. }
  7756. async readFromCache() {
  7757. if (!this.cachePath)
  7758. return;
  7759. if (fs$8.existsSync(this.cachePath)) {
  7760. const resultsCache = await fs$8.promises.readFile(this.cachePath, "utf8");
  7761. const { results, version: version2 } = JSON.parse(resultsCache);
  7762. this.cache = new Map(results);
  7763. this.version = version2;
  7764. }
  7765. }
  7766. updateResults(files) {
  7767. files.forEach((file) => {
  7768. var _a;
  7769. const result = file.result;
  7770. if (!result)
  7771. return;
  7772. const duration = result.duration || 0;
  7773. const relativePath = (_a = file.filepath) == null ? void 0 : _a.slice(this.root.length);
  7774. this.cache.set(relativePath, {
  7775. duration: duration >= 0 ? duration : 0,
  7776. failed: result.state === "fail"
  7777. });
  7778. });
  7779. }
  7780. removeFromCache(filepath) {
  7781. this.cache.delete(filepath);
  7782. }
  7783. async writeToCache() {
  7784. if (!this.cachePath)
  7785. return;
  7786. const results = Array.from(this.cache.entries());
  7787. const cacheDirname = dirname(this.cachePath);
  7788. if (!fs$8.existsSync(cacheDirname))
  7789. await fs$8.promises.mkdir(cacheDirname, { recursive: true });
  7790. const cache = JSON.stringify({
  7791. version: this.version,
  7792. results
  7793. });
  7794. await fs$8.promises.writeFile(this.cachePath, cache);
  7795. }
  7796. }
  7797. class VitestCache {
  7798. constructor() {
  7799. this.results = new ResultsCache();
  7800. this.stats = new FilesStatsCache();
  7801. }
  7802. getFileTestResults(id) {
  7803. return this.results.getResults(id);
  7804. }
  7805. getFileStats(id) {
  7806. return this.stats.getStats(id);
  7807. }
  7808. static resolveCacheDir(root, dir) {
  7809. return resolve(root, slash$2(dir || "node_modules/.vitest"));
  7810. }
  7811. static async clearCache(options) {
  7812. var _a;
  7813. const root = resolve(options.root || process.cwd());
  7814. const configPath = options.config ? resolve(root, options.config) : await findUp(configFiles, { cwd: root });
  7815. const config = await loadConfigFromFile({ command: "serve", mode: "test" }, configPath);
  7816. const cache = (_a = config == null ? void 0 : config.config.test) == null ? void 0 : _a.cache;
  7817. if (cache === false)
  7818. throw new Error("Cache is disabled");
  7819. const cachePath = VitestCache.resolveCacheDir(root, cache == null ? void 0 : cache.dir);
  7820. let cleared = false;
  7821. if (fs$8.existsSync(cachePath)) {
  7822. fs$8.rmSync(cachePath, { recursive: true, force: true });
  7823. cleared = true;
  7824. }
  7825. return { dir: cachePath, cleared };
  7826. }
  7827. }
  7828. class BaseSequencer {
  7829. constructor(ctx) {
  7830. this.ctx = ctx;
  7831. }
  7832. async shard(files) {
  7833. const { config } = this.ctx;
  7834. const { index, count } = config.shard;
  7835. const shardSize = Math.ceil(files.length / count);
  7836. const shardStart = shardSize * (index - 1);
  7837. const shardEnd = shardSize * index;
  7838. return [...files].map((file) => {
  7839. const fullPath = resolve(slash$1(config.root), slash$1(file));
  7840. const specPath = fullPath == null ? void 0 : fullPath.slice(config.root.length);
  7841. return {
  7842. file,
  7843. hash: createHash("sha1").update(specPath).digest("hex")
  7844. };
  7845. }).sort((a, b) => a.hash < b.hash ? -1 : a.hash > b.hash ? 1 : 0).slice(shardStart, shardEnd).map(({ file }) => file);
  7846. }
  7847. async sort(files) {
  7848. const cache = this.ctx.cache;
  7849. return [...files].sort((a, b) => {
  7850. const aState = cache.getFileTestResults(a);
  7851. const bState = cache.getFileTestResults(b);
  7852. if (!aState || !bState) {
  7853. const statsA = cache.getFileStats(a);
  7854. const statsB = cache.getFileStats(b);
  7855. if (!statsA || !statsB)
  7856. return !statsA && statsB ? -1 : !statsB && statsA ? 1 : 0;
  7857. return statsB.size - statsA.size;
  7858. }
  7859. if (aState.failed && !bState.failed)
  7860. return -1;
  7861. if (!aState.failed && bState.failed)
  7862. return 1;
  7863. return bState.duration - aState.duration;
  7864. });
  7865. }
  7866. }
  7867. class RandomSequencer extends BaseSequencer {
  7868. async sort(files) {
  7869. const { sequence } = this.ctx.config;
  7870. const seed = (sequence == null ? void 0 : sequence.seed) ?? Date.now();
  7871. return shuffle(files, seed);
  7872. }
  7873. }
  7874. const extraInlineDeps = [
  7875. /^(?!.*(?:node_modules)).*\.mjs$/,
  7876. /^(?!.*(?:node_modules)).*\.cjs\.js$/,
  7877. /vite\w*\/dist\/client\/env.mjs/,
  7878. /\/vitest\/dist\//,
  7879. /vitest-virtual-\w+\/dist/,
  7880. /@vitest\/dist/,
  7881. "@nuxt/test-utils"
  7882. ];
  7883. function resolveApiConfig(options) {
  7884. let api;
  7885. if ((options.ui || options.browser) && !options.api)
  7886. api = { port: defaultPort };
  7887. else if (options.api === true)
  7888. api = { port: defaultPort };
  7889. else if (typeof options.api === "number")
  7890. api = { port: options.api };
  7891. if (typeof options.api === "object") {
  7892. if (api) {
  7893. if (options.api.port)
  7894. api.port = options.api.port;
  7895. if (options.api.strictPort)
  7896. api.strictPort = options.api.strictPort;
  7897. if (options.api.host)
  7898. api.host = options.api.host;
  7899. } else {
  7900. api = { ...options.api };
  7901. }
  7902. }
  7903. if (api) {
  7904. if (!api.port)
  7905. api.port = defaultPort;
  7906. }
  7907. return api;
  7908. }
  7909. function resolveConfig(mode, options, viteConfig) {
  7910. var _a, _b, _c, _d, _e, _f;
  7911. if (options.dom) {
  7912. if (((_a = viteConfig.test) == null ? void 0 : _a.environment) != null && viteConfig.test.environment !== "happy-dom") {
  7913. console.warn(
  7914. picocolors.exports.yellow(
  7915. `${picocolors.exports.inverse(picocolors.exports.yellow(" Vitest "))} Your config.test.environment ("${viteConfig.test.environment}") conflicts with --dom flag ("happy-dom"), ignoring "${viteConfig.test.environment}"`
  7916. )
  7917. );
  7918. }
  7919. options.environment = "happy-dom";
  7920. }
  7921. const resolved = {
  7922. ...configDefaults,
  7923. ...options,
  7924. root: viteConfig.root,
  7925. mode
  7926. };
  7927. if (viteConfig.base !== "/")
  7928. resolved.base = viteConfig.base;
  7929. if (options.shard) {
  7930. if (resolved.watch)
  7931. throw new Error("You cannot use --shard option with enabled watch");
  7932. const [indexString, countString] = options.shard.split("/");
  7933. const index = Math.abs(parseInt(indexString, 10));
  7934. const count = Math.abs(parseInt(countString, 10));
  7935. if (isNaN(count) || count <= 0)
  7936. throw new Error("--shard <count> must be a positive number");
  7937. if (isNaN(index) || index <= 0 || index > count)
  7938. throw new Error("--shard <index> must be a positive number less then <count>");
  7939. resolved.shard = { index, count };
  7940. }
  7941. resolved.deps = resolved.deps || {};
  7942. if (resolved.deps.inline !== true) {
  7943. const ssrOptions = viteConfig.ssr;
  7944. if ((ssrOptions == null ? void 0 : ssrOptions.noExternal) === true && resolved.deps.inline == null) {
  7945. resolved.deps.inline = true;
  7946. } else {
  7947. (_b = resolved.deps).inline ?? (_b.inline = []);
  7948. resolved.deps.inline.push(...extraInlineDeps);
  7949. }
  7950. }
  7951. (_c = resolved.deps).registerNodeLoader ?? (_c.registerNodeLoader = false);
  7952. resolved.testNamePattern = resolved.testNamePattern ? resolved.testNamePattern instanceof RegExp ? resolved.testNamePattern : new RegExp(resolved.testNamePattern) : void 0;
  7953. const CI = !!process.env.CI;
  7954. const UPDATE_SNAPSHOT = resolved.update || process.env.UPDATE_SNAPSHOT;
  7955. resolved.snapshotOptions = {
  7956. snapshotFormat: resolved.snapshotFormat || {},
  7957. updateSnapshot: CI && !UPDATE_SNAPSHOT ? "none" : UPDATE_SNAPSHOT ? "all" : "new",
  7958. resolveSnapshotPath: options.resolveSnapshotPath
  7959. };
  7960. if (options.resolveSnapshotPath)
  7961. delete resolved.resolveSnapshotPath;
  7962. if (process.env.VITEST_MAX_THREADS)
  7963. resolved.maxThreads = parseInt(process.env.VITEST_MAX_THREADS);
  7964. if (process.env.VITEST_MIN_THREADS)
  7965. resolved.minThreads = parseInt(process.env.VITEST_MIN_THREADS);
  7966. if (mode === "benchmark") {
  7967. resolved.benchmark = {
  7968. ...benchmarkConfigDefaults,
  7969. ...resolved.benchmark
  7970. };
  7971. resolved.coverage.enabled = false;
  7972. resolved.include = resolved.benchmark.include;
  7973. resolved.exclude = resolved.benchmark.exclude;
  7974. resolved.includeSource = resolved.benchmark.includeSource;
  7975. const reporters = Array.from(/* @__PURE__ */ new Set([
  7976. ...toArray$1(resolved.benchmark.reporters),
  7977. ...toArray$1(options.reporter)
  7978. ])).filter(Boolean);
  7979. if (reporters.length)
  7980. resolved.benchmark.reporters = reporters;
  7981. else
  7982. resolved.benchmark.reporters = ["default"];
  7983. if (options.outputFile)
  7984. resolved.benchmark.outputFile = options.outputFile;
  7985. }
  7986. resolved.setupFiles = toArray$1(resolved.setupFiles || []).map(
  7987. (file) => normalize(
  7988. resolveModule(file, { paths: [resolved.root] }) ?? resolve(resolved.root, file)
  7989. )
  7990. );
  7991. resolved.api = resolveApiConfig(options);
  7992. if (options.related)
  7993. resolved.related = toArray$1(options.related).map((file) => resolve(resolved.root, file));
  7994. if (mode !== "benchmark") {
  7995. resolved.reporters = Array.from(/* @__PURE__ */ new Set([
  7996. ...toArray$1(resolved.reporters),
  7997. ...toArray$1(resolved.reporter)
  7998. ])).filter(Boolean);
  7999. }
  8000. if (!resolved.reporters.length)
  8001. resolved.reporters.push("default");
  8002. if (resolved.changed)
  8003. resolved.passWithNoTests ?? (resolved.passWithNoTests = true);
  8004. resolved.css ?? (resolved.css = {});
  8005. if (typeof resolved.css === "object") {
  8006. (_d = resolved.css).modules ?? (_d.modules = {});
  8007. (_e = resolved.css.modules).classNameStrategy ?? (_e.classNameStrategy = "stable");
  8008. }
  8009. resolved.cache ?? (resolved.cache = { dir: "" });
  8010. if (resolved.cache)
  8011. resolved.cache.dir = VitestCache.resolveCacheDir(resolved.root, resolved.cache.dir);
  8012. if (!((_f = resolved.sequence) == null ? void 0 : _f.sequencer)) {
  8013. resolved.sequence ?? (resolved.sequence = {});
  8014. resolved.sequence.sequencer = resolved.sequence.shuffle ? RandomSequencer : BaseSequencer;
  8015. }
  8016. return resolved;
  8017. }
  8018. const ESC = '\u001B[';
  8019. const OSC = '\u001B]';
  8020. const BEL = '\u0007';
  8021. const SEP = ';';
  8022. const isTerminalApp = process.env.TERM_PROGRAM === 'Apple_Terminal';
  8023. const ansiEscapes = {};
  8024. ansiEscapes.cursorTo = (x, y) => {
  8025. if (typeof x !== 'number') {
  8026. throw new TypeError('The `x` argument is required');
  8027. }
  8028. if (typeof y !== 'number') {
  8029. return ESC + (x + 1) + 'G';
  8030. }
  8031. return ESC + (y + 1) + ';' + (x + 1) + 'H';
  8032. };
  8033. ansiEscapes.cursorMove = (x, y) => {
  8034. if (typeof x !== 'number') {
  8035. throw new TypeError('The `x` argument is required');
  8036. }
  8037. let returnValue = '';
  8038. if (x < 0) {
  8039. returnValue += ESC + (-x) + 'D';
  8040. } else if (x > 0) {
  8041. returnValue += ESC + x + 'C';
  8042. }
  8043. if (y < 0) {
  8044. returnValue += ESC + (-y) + 'A';
  8045. } else if (y > 0) {
  8046. returnValue += ESC + y + 'B';
  8047. }
  8048. return returnValue;
  8049. };
  8050. ansiEscapes.cursorUp = (count = 1) => ESC + count + 'A';
  8051. ansiEscapes.cursorDown = (count = 1) => ESC + count + 'B';
  8052. ansiEscapes.cursorForward = (count = 1) => ESC + count + 'C';
  8053. ansiEscapes.cursorBackward = (count = 1) => ESC + count + 'D';
  8054. ansiEscapes.cursorLeft = ESC + 'G';
  8055. ansiEscapes.cursorSavePosition = isTerminalApp ? '\u001B7' : ESC + 's';
  8056. ansiEscapes.cursorRestorePosition = isTerminalApp ? '\u001B8' : ESC + 'u';
  8057. ansiEscapes.cursorGetPosition = ESC + '6n';
  8058. ansiEscapes.cursorNextLine = ESC + 'E';
  8059. ansiEscapes.cursorPrevLine = ESC + 'F';
  8060. ansiEscapes.cursorHide = ESC + '?25l';
  8061. ansiEscapes.cursorShow = ESC + '?25h';
  8062. ansiEscapes.eraseLines = count => {
  8063. let clear = '';
  8064. for (let i = 0; i < count; i++) {
  8065. clear += ansiEscapes.eraseLine + (i < count - 1 ? ansiEscapes.cursorUp() : '');
  8066. }
  8067. if (count) {
  8068. clear += ansiEscapes.cursorLeft;
  8069. }
  8070. return clear;
  8071. };
  8072. ansiEscapes.eraseEndLine = ESC + 'K';
  8073. ansiEscapes.eraseStartLine = ESC + '1K';
  8074. ansiEscapes.eraseLine = ESC + '2K';
  8075. ansiEscapes.eraseDown = ESC + 'J';
  8076. ansiEscapes.eraseUp = ESC + '1J';
  8077. ansiEscapes.eraseScreen = ESC + '2J';
  8078. ansiEscapes.scrollUp = ESC + 'S';
  8079. ansiEscapes.scrollDown = ESC + 'T';
  8080. ansiEscapes.clearScreen = '\u001Bc';
  8081. ansiEscapes.clearTerminal = process.platform === 'win32' ?
  8082. `${ansiEscapes.eraseScreen}${ESC}0f` :
  8083. // 1. Erases the screen (Only done in case `2` is not supported)
  8084. // 2. Erases the whole screen including scrollback buffer
  8085. // 3. Moves cursor to the top-left position
  8086. // More info: https://www.real-world-systems.com/docs/ANSIcode.html
  8087. `${ansiEscapes.eraseScreen}${ESC}3J${ESC}H`;
  8088. ansiEscapes.beep = BEL;
  8089. ansiEscapes.link = (text, url) => {
  8090. return [
  8091. OSC,
  8092. '8',
  8093. SEP,
  8094. SEP,
  8095. url,
  8096. BEL,
  8097. text,
  8098. OSC,
  8099. '8',
  8100. SEP,
  8101. SEP,
  8102. BEL
  8103. ].join('');
  8104. };
  8105. ansiEscapes.image = (buffer, options = {}) => {
  8106. let returnValue = `${OSC}1337;File=inline=1`;
  8107. if (options.width) {
  8108. returnValue += `;width=${options.width}`;
  8109. }
  8110. if (options.height) {
  8111. returnValue += `;height=${options.height}`;
  8112. }
  8113. if (options.preserveAspectRatio === false) {
  8114. returnValue += ';preserveAspectRatio=0';
  8115. }
  8116. return returnValue + ':' + buffer.toString('base64') + BEL;
  8117. };
  8118. ansiEscapes.iTerm = {
  8119. setCwd: (cwd = process.cwd()) => `${OSC}50;CurrentDir=${cwd}${BEL}`,
  8120. annotation: (message, options = {}) => {
  8121. let returnValue = `${OSC}1337;`;
  8122. const hasX = typeof options.x !== 'undefined';
  8123. const hasY = typeof options.y !== 'undefined';
  8124. if ((hasX || hasY) && !(hasX && hasY && typeof options.length !== 'undefined')) {
  8125. throw new Error('`x`, `y` and `length` must be defined when `x` or `y` is defined');
  8126. }
  8127. message = message.replace(/\|/g, '');
  8128. returnValue += options.isHidden ? 'AddHiddenAnnotation=' : 'AddAnnotation=';
  8129. if (options.length > 0) {
  8130. returnValue +=
  8131. (hasX ?
  8132. [message, options.length, options.x, options.y] :
  8133. [options.length, message]).join('|');
  8134. } else {
  8135. returnValue += message;
  8136. }
  8137. return returnValue + BEL;
  8138. }
  8139. };
  8140. const restoreCursor = onetime.exports(() => {
  8141. signalExit.exports(() => {
  8142. process$1.stderr.write('\u001B[?25h');
  8143. }, {alwaysLast: true});
  8144. });
  8145. let isHidden = false;
  8146. const cliCursor = {};
  8147. cliCursor.show = (writableStream = process$1.stderr) => {
  8148. if (!writableStream.isTTY) {
  8149. return;
  8150. }
  8151. isHidden = false;
  8152. writableStream.write('\u001B[?25h');
  8153. };
  8154. cliCursor.hide = (writableStream = process$1.stderr) => {
  8155. if (!writableStream.isTTY) {
  8156. return;
  8157. }
  8158. restoreCursor();
  8159. isHidden = true;
  8160. writableStream.write('\u001B[?25l');
  8161. };
  8162. cliCursor.toggle = (force, writableStream) => {
  8163. if (force !== undefined) {
  8164. isHidden = force;
  8165. }
  8166. if (isHidden) {
  8167. cliCursor.show(writableStream);
  8168. } else {
  8169. cliCursor.hide(writableStream);
  8170. }
  8171. };
  8172. const ESCAPES = new Set([
  8173. '\u001B',
  8174. '\u009B',
  8175. ]);
  8176. const END_CODE = 39;
  8177. const ANSI_ESCAPE_BELL = '\u0007';
  8178. const ANSI_CSI = '[';
  8179. const ANSI_OSC = ']';
  8180. const ANSI_SGR_TERMINATOR = 'm';
  8181. const ANSI_ESCAPE_LINK = `${ANSI_OSC}8;;`;
  8182. const wrapAnsiCode = code => `${ESCAPES.values().next().value}${ANSI_CSI}${code}${ANSI_SGR_TERMINATOR}`;
  8183. const wrapAnsiHyperlink = uri => `${ESCAPES.values().next().value}${ANSI_ESCAPE_LINK}${uri}${ANSI_ESCAPE_BELL}`;
  8184. // Calculate the length of words split on ' ', ignoring
  8185. // the extra characters added by ansi escape codes
  8186. const wordLengths = string => string.split(' ').map(character => stringWidth(character));
  8187. // Wrap a long word across multiple rows
  8188. // Ansi escape codes do not count towards length
  8189. const wrapWord = (rows, word, columns) => {
  8190. const characters = [...word];
  8191. let isInsideEscape = false;
  8192. let isInsideLinkEscape = false;
  8193. let visible = stringWidth(stripAnsi(rows[rows.length - 1]));
  8194. for (const [index, character] of characters.entries()) {
  8195. const characterLength = stringWidth(character);
  8196. if (visible + characterLength <= columns) {
  8197. rows[rows.length - 1] += character;
  8198. } else {
  8199. rows.push(character);
  8200. visible = 0;
  8201. }
  8202. if (ESCAPES.has(character)) {
  8203. isInsideEscape = true;
  8204. isInsideLinkEscape = characters.slice(index + 1).join('').startsWith(ANSI_ESCAPE_LINK);
  8205. }
  8206. if (isInsideEscape) {
  8207. if (isInsideLinkEscape) {
  8208. if (character === ANSI_ESCAPE_BELL) {
  8209. isInsideEscape = false;
  8210. isInsideLinkEscape = false;
  8211. }
  8212. } else if (character === ANSI_SGR_TERMINATOR) {
  8213. isInsideEscape = false;
  8214. }
  8215. continue;
  8216. }
  8217. visible += characterLength;
  8218. if (visible === columns && index < characters.length - 1) {
  8219. rows.push('');
  8220. visible = 0;
  8221. }
  8222. }
  8223. // It's possible that the last row we copy over is only
  8224. // ansi escape characters, handle this edge-case
  8225. if (!visible && rows[rows.length - 1].length > 0 && rows.length > 1) {
  8226. rows[rows.length - 2] += rows.pop();
  8227. }
  8228. };
  8229. // Trims spaces from a string ignoring invisible sequences
  8230. const stringVisibleTrimSpacesRight = string => {
  8231. const words = string.split(' ');
  8232. let last = words.length;
  8233. while (last > 0) {
  8234. if (stringWidth(words[last - 1]) > 0) {
  8235. break;
  8236. }
  8237. last--;
  8238. }
  8239. if (last === words.length) {
  8240. return string;
  8241. }
  8242. return words.slice(0, last).join(' ') + words.slice(last).join('');
  8243. };
  8244. // The wrap-ansi module can be invoked in either 'hard' or 'soft' wrap mode
  8245. //
  8246. // 'hard' will never allow a string to take up more than columns characters
  8247. //
  8248. // 'soft' allows long words to expand past the column length
  8249. const exec = (string, columns, options = {}) => {
  8250. if (options.trim !== false && string.trim() === '') {
  8251. return '';
  8252. }
  8253. let returnValue = '';
  8254. let escapeCode;
  8255. let escapeUrl;
  8256. const lengths = wordLengths(string);
  8257. let rows = [''];
  8258. for (const [index, word] of string.split(' ').entries()) {
  8259. if (options.trim !== false) {
  8260. rows[rows.length - 1] = rows[rows.length - 1].trimStart();
  8261. }
  8262. let rowLength = stringWidth(rows[rows.length - 1]);
  8263. if (index !== 0) {
  8264. if (rowLength >= columns && (options.wordWrap === false || options.trim === false)) {
  8265. // If we start with a new word but the current row length equals the length of the columns, add a new row
  8266. rows.push('');
  8267. rowLength = 0;
  8268. }
  8269. if (rowLength > 0 || options.trim === false) {
  8270. rows[rows.length - 1] += ' ';
  8271. rowLength++;
  8272. }
  8273. }
  8274. // In 'hard' wrap mode, the length of a line is never allowed to extend past 'columns'
  8275. if (options.hard && lengths[index] > columns) {
  8276. const remainingColumns = (columns - rowLength);
  8277. const breaksStartingThisLine = 1 + Math.floor((lengths[index] - remainingColumns - 1) / columns);
  8278. const breaksStartingNextLine = Math.floor((lengths[index] - 1) / columns);
  8279. if (breaksStartingNextLine < breaksStartingThisLine) {
  8280. rows.push('');
  8281. }
  8282. wrapWord(rows, word, columns);
  8283. continue;
  8284. }
  8285. if (rowLength + lengths[index] > columns && rowLength > 0 && lengths[index] > 0) {
  8286. if (options.wordWrap === false && rowLength < columns) {
  8287. wrapWord(rows, word, columns);
  8288. continue;
  8289. }
  8290. rows.push('');
  8291. }
  8292. if (rowLength + lengths[index] > columns && options.wordWrap === false) {
  8293. wrapWord(rows, word, columns);
  8294. continue;
  8295. }
  8296. rows[rows.length - 1] += word;
  8297. }
  8298. if (options.trim !== false) {
  8299. rows = rows.map(row => stringVisibleTrimSpacesRight(row));
  8300. }
  8301. const pre = [...rows.join('\n')];
  8302. for (const [index, character] of pre.entries()) {
  8303. returnValue += character;
  8304. if (ESCAPES.has(character)) {
  8305. const {groups} = new RegExp(`(?:\\${ANSI_CSI}(?<code>\\d+)m|\\${ANSI_ESCAPE_LINK}(?<uri>.*)${ANSI_ESCAPE_BELL})`).exec(pre.slice(index).join('')) || {groups: {}};
  8306. if (groups.code !== undefined) {
  8307. const code = Number.parseFloat(groups.code);
  8308. escapeCode = code === END_CODE ? undefined : code;
  8309. } else if (groups.uri !== undefined) {
  8310. escapeUrl = groups.uri.length === 0 ? undefined : groups.uri;
  8311. }
  8312. }
  8313. const code = ansiStyles.codes.get(Number(escapeCode));
  8314. if (pre[index + 1] === '\n') {
  8315. if (escapeUrl) {
  8316. returnValue += wrapAnsiHyperlink('');
  8317. }
  8318. if (escapeCode && code) {
  8319. returnValue += wrapAnsiCode(code);
  8320. }
  8321. } else if (character === '\n') {
  8322. if (escapeCode && code) {
  8323. returnValue += wrapAnsiCode(escapeCode);
  8324. }
  8325. if (escapeUrl) {
  8326. returnValue += wrapAnsiHyperlink(escapeUrl);
  8327. }
  8328. }
  8329. }
  8330. return returnValue;
  8331. };
  8332. // For each newline, invoke the method separately
  8333. function wrapAnsi(string, columns, options) {
  8334. return String(string)
  8335. .normalize()
  8336. .replace(/\r\n/g, '\n')
  8337. .split('\n')
  8338. .map(line => exec(line, columns, options))
  8339. .join('\n');
  8340. }
  8341. const defaultTerminalHeight = 24;
  8342. const getWidth = stream => {
  8343. const {columns} = stream;
  8344. if (!columns) {
  8345. return 80;
  8346. }
  8347. return columns;
  8348. };
  8349. const fitToTerminalHeight = (stream, text) => {
  8350. const terminalHeight = stream.rows || defaultTerminalHeight;
  8351. const lines = text.split('\n');
  8352. const toRemove = lines.length - terminalHeight;
  8353. if (toRemove <= 0) {
  8354. return text;
  8355. }
  8356. return sliceAnsi(
  8357. text,
  8358. stripAnsi(lines.slice(0, toRemove).join('\n')).length + 1,
  8359. );
  8360. };
  8361. function createLogUpdate(stream, {showCursor = false} = {}) {
  8362. let previousLineCount = 0;
  8363. let previousWidth = getWidth(stream);
  8364. let previousOutput = '';
  8365. const render = (...arguments_) => {
  8366. if (!showCursor) {
  8367. cliCursor.hide();
  8368. }
  8369. let output = arguments_.join(' ') + '\n';
  8370. output = fitToTerminalHeight(stream, output);
  8371. const width = getWidth(stream);
  8372. if (output === previousOutput && previousWidth === width) {
  8373. return;
  8374. }
  8375. previousOutput = output;
  8376. previousWidth = width;
  8377. output = wrapAnsi(output, width, {
  8378. trim: false,
  8379. hard: true,
  8380. wordWrap: false,
  8381. });
  8382. stream.write(ansiEscapes.eraseLines(previousLineCount) + output);
  8383. previousLineCount = output.split('\n').length;
  8384. };
  8385. render.clear = () => {
  8386. stream.write(ansiEscapes.eraseLines(previousLineCount));
  8387. previousOutput = '';
  8388. previousWidth = getWidth(stream);
  8389. previousLineCount = 0;
  8390. };
  8391. render.done = () => {
  8392. previousOutput = '';
  8393. previousWidth = getWidth(stream);
  8394. previousLineCount = 0;
  8395. if (!showCursor) {
  8396. cliCursor.show();
  8397. }
  8398. };
  8399. return render;
  8400. }
  8401. createLogUpdate(process$1.stdout);
  8402. createLogUpdate(process$1.stderr);
  8403. var version = "0.23.4";
  8404. function fileFromParsedStack(stack) {
  8405. var _a, _b;
  8406. if ((_b = (_a = stack == null ? void 0 : stack.sourcePos) == null ? void 0 : _a.source) == null ? void 0 : _b.startsWith(".."))
  8407. return join(stack.file, "../", stack.sourcePos.source);
  8408. return stack.file;
  8409. }
  8410. async function printError(error, ctx, options = {}) {
  8411. const { showCodeFrame = true, fullStack = false, type } = options;
  8412. let e = error;
  8413. if (typeof error === "string") {
  8414. e = {
  8415. message: error.split(/\n/g)[0],
  8416. stack: error
  8417. };
  8418. }
  8419. const stacks = parseStacktrace(e, fullStack);
  8420. await interpretSourcePos(stacks, ctx);
  8421. const nearest = stacks.find(
  8422. (stack) => ctx.server.moduleGraph.getModuleById(stack.file) && existsSync(stack.file)
  8423. );
  8424. const errorProperties = getErrorProperties(e);
  8425. if (type)
  8426. printErrorType(type, ctx);
  8427. printErrorMessage(e, ctx.logger);
  8428. printStack(ctx, stacks, nearest, errorProperties, (s, pos) => {
  8429. if (showCodeFrame && s === nearest && nearest) {
  8430. const file = fileFromParsedStack(nearest);
  8431. if (existsSync(file)) {
  8432. const sourceCode = readFileSync(file, "utf-8");
  8433. ctx.logger.log(picocolors.exports.yellow(generateCodeFrame(sourceCode, 4, pos)));
  8434. }
  8435. }
  8436. });
  8437. if (e.cause && "name" in e.cause) {
  8438. e.cause.name = `Caused by: ${e.cause.name}`;
  8439. await printError(e.cause, ctx, { fullStack, showCodeFrame: false });
  8440. }
  8441. handleImportOutsideModuleError(e.stack || e.stackStr || "", ctx);
  8442. if (e.showDiff || e.showDiff === void 0 && e.actual && e.expected) {
  8443. displayDiff(stringify$5(e.actual), stringify$5(e.expected), ctx.logger.console, {
  8444. outputTruncateLength: ctx.config.outputTruncateLength,
  8445. outputDiffLines: ctx.config.outputDiffLines
  8446. });
  8447. }
  8448. }
  8449. function printErrorType(type, ctx) {
  8450. ctx.logger.error(`
  8451. ${picocolors.exports.red(divider(picocolors.exports.bold(picocolors.exports.inverse(` ${type} `))))}`);
  8452. }
  8453. const skipErrorProperties = [
  8454. "message",
  8455. "name",
  8456. "nameStr",
  8457. "stack",
  8458. "cause",
  8459. "stacks",
  8460. "stackStr",
  8461. "type",
  8462. "showDiff",
  8463. "actual",
  8464. "expected",
  8465. "constructor",
  8466. "toString"
  8467. ];
  8468. function getErrorProperties(e) {
  8469. const errorObject = /* @__PURE__ */ Object.create(null);
  8470. if (e.name === "AssertionError")
  8471. return errorObject;
  8472. for (const key of Object.getOwnPropertyNames(e)) {
  8473. if (!skipErrorProperties.includes(key))
  8474. errorObject[key] = e[key];
  8475. }
  8476. return errorObject;
  8477. }
  8478. const esmErrors = [
  8479. "Cannot use import statement outside a module",
  8480. "Unexpected token 'export'"
  8481. ];
  8482. function handleImportOutsideModuleError(stack, ctx) {
  8483. if (!esmErrors.some((e) => stack.includes(e)))
  8484. return;
  8485. const path = normalize(stack.split("\n")[0].trim());
  8486. let name = path.split("/node_modules/").pop() || "";
  8487. if (name == null ? void 0 : name.startsWith("@"))
  8488. name = name.split("/").slice(0, 2).join("/");
  8489. else
  8490. name = name.split("/")[0];
  8491. ctx.logger.error(picocolors.exports.yellow(
  8492. `Module ${path} seems to be an ES Module but shipped in a CommonJS package. You might want to create an issue to the package ${picocolors.exports.bold(`"${name}"`)} asking them to ship the file in .mjs extension or add "type": "module" in their package.json.
  8493. As a temporary workaround you can try to inline the package by updating your config:
  8494. ` + picocolors.exports.gray(picocolors.exports.dim("// vitest.config.js")) + "\n" + picocolors.exports.green(`export default {
  8495. test: {
  8496. deps: {
  8497. inline: [
  8498. ${picocolors.exports.yellow(picocolors.exports.bold(`"${name}"`))}
  8499. ]
  8500. }
  8501. }
  8502. }
  8503. `)
  8504. ));
  8505. }
  8506. function displayDiff(actual, expected, console, options) {
  8507. console.error(picocolors.exports.gray(unifiedDiff(actual, expected, options)) + "\n");
  8508. }
  8509. function printErrorMessage(error, logger) {
  8510. const errorName = error.name || error.nameStr || "Unknown Error";
  8511. logger.error(picocolors.exports.red(`${picocolors.exports.bold(errorName)}: ${error.message}`));
  8512. }
  8513. function printStack(ctx, stack, highlight, errorProperties, onStack) {
  8514. if (!stack.length)
  8515. return;
  8516. const logger = ctx.logger;
  8517. for (const frame of stack) {
  8518. const pos = frame.sourcePos || frame;
  8519. const color = frame === highlight ? picocolors.exports.yellow : picocolors.exports.gray;
  8520. const file = fileFromParsedStack(frame);
  8521. const path = relative(ctx.config.root, file);
  8522. logger.log(color(` ${picocolors.exports.dim(F_POINTER)} ${[frame.method, picocolors.exports.dim(`${path}:${pos.line}:${pos.column}`)].filter(Boolean).join(" ")}`));
  8523. onStack == null ? void 0 : onStack(frame, pos);
  8524. if (frame.file in ctx.state.filesMap)
  8525. break;
  8526. }
  8527. logger.log();
  8528. const hasProperties = Object.keys(errorProperties).length > 0;
  8529. if (hasProperties) {
  8530. logger.log(picocolors.exports.red(picocolors.exports.dim(divider())));
  8531. const propertiesString = stringify$5(errorProperties, 10, { printBasicPrototype: false });
  8532. logger.log(picocolors.exports.red(picocolors.exports.bold("Serialized Error:")), picocolors.exports.gray(propertiesString));
  8533. }
  8534. }
  8535. function generateCodeFrame(source, indent = 0, start = 0, end, range = 2) {
  8536. var _a;
  8537. start = posToNumber(source, start);
  8538. end = end || start;
  8539. const lines = source.split(lineSplitRE);
  8540. let count = 0;
  8541. let res = [];
  8542. const columns = ((_a = process.stdout) == null ? void 0 : _a.columns) || 80;
  8543. function lineNo(no = "") {
  8544. return picocolors.exports.gray(`${String(no).padStart(3, " ")}| `);
  8545. }
  8546. for (let i = 0; i < lines.length; i++) {
  8547. count += lines[i].length + 1;
  8548. if (count >= start) {
  8549. for (let j = i - range; j <= i + range || end > count; j++) {
  8550. if (j < 0 || j >= lines.length)
  8551. continue;
  8552. const lineLength = lines[j].length;
  8553. if (lineLength > 200)
  8554. return "";
  8555. res.push(lineNo(j + 1) + cliTruncate(lines[j].replace(/\t/g, " "), columns - 5 - indent));
  8556. if (j === i) {
  8557. const pad = start - (count - lineLength);
  8558. const length = Math.max(1, end > count ? lineLength - pad : end - start);
  8559. res.push(lineNo() + " ".repeat(pad) + picocolors.exports.red("^".repeat(length)));
  8560. } else if (j > i) {
  8561. if (end > count) {
  8562. const length = Math.max(1, Math.min(end - count, lineLength));
  8563. res.push(lineNo() + picocolors.exports.red("^".repeat(length)));
  8564. }
  8565. count += lineLength + 1;
  8566. }
  8567. }
  8568. break;
  8569. }
  8570. }
  8571. if (indent)
  8572. res = res.map((line) => " ".repeat(indent) + line);
  8573. return res.join("\n");
  8574. }
  8575. class Logger {
  8576. constructor(ctx, console = globalThis.console) {
  8577. this.ctx = ctx;
  8578. this.console = console;
  8579. this.outputStream = process.stdout;
  8580. this.errorStream = process.stderr;
  8581. this.logUpdate = createLogUpdate(process.stdout);
  8582. }
  8583. log(...args) {
  8584. this._clearScreen();
  8585. this.console.log(...args);
  8586. }
  8587. error(...args) {
  8588. this._clearScreen();
  8589. this.console.error(...args);
  8590. }
  8591. warn(...args) {
  8592. this._clearScreen();
  8593. this.console.warn(...args);
  8594. }
  8595. clearScreen(message, force = false) {
  8596. if (this.ctx.server.config.clearScreen === false) {
  8597. this.console.log(message);
  8598. return;
  8599. }
  8600. this._clearScreenPending = message;
  8601. if (force)
  8602. this._clearScreen();
  8603. }
  8604. _clearScreen() {
  8605. if (!this._clearScreenPending)
  8606. return;
  8607. const log = this._clearScreenPending;
  8608. this._clearScreenPending = void 0;
  8609. this.console.log(`\x1B[1;1H\x1B[J${log}`);
  8610. }
  8611. printError(err, fullStack = false, type) {
  8612. return printError(err, this.ctx, {
  8613. fullStack,
  8614. type,
  8615. showCodeFrame: true
  8616. });
  8617. }
  8618. printNoTestFound(filters) {
  8619. const config = this.ctx.config;
  8620. const comma = picocolors.exports.dim(", ");
  8621. if (filters == null ? void 0 : filters.length)
  8622. this.console.error(picocolors.exports.dim("filter: ") + picocolors.exports.yellow(filters.join(comma)));
  8623. if (config.include)
  8624. this.console.error(picocolors.exports.dim("include: ") + picocolors.exports.yellow(config.include.join(comma)));
  8625. if (config.exclude)
  8626. this.console.error(picocolors.exports.dim("exclude: ") + picocolors.exports.yellow(config.exclude.join(comma)));
  8627. if (config.watchExclude)
  8628. this.console.error(picocolors.exports.dim("watch exclude: ") + picocolors.exports.yellow(config.watchExclude.join(comma)));
  8629. if (config.passWithNoTests)
  8630. this.log(`No ${config.mode} files found, exiting with code 0
  8631. `);
  8632. else
  8633. this.error(picocolors.exports.red(`
  8634. No ${config.mode} files found, exiting with code 1`));
  8635. }
  8636. printBanner() {
  8637. var _a, _b, _c;
  8638. this.log();
  8639. const versionTest = this.ctx.config.watch ? picocolors.exports.blue(`v${version}`) : picocolors.exports.cyan(`v${version}`);
  8640. const mode = this.ctx.config.watch ? picocolors.exports.blue(" DEV ") : picocolors.exports.cyan(" RUN ");
  8641. this.log(`${picocolors.exports.inverse(picocolors.exports.bold(mode))} ${versionTest} ${picocolors.exports.gray(this.ctx.config.root)}`);
  8642. if (this.ctx.config.browser)
  8643. this.log(picocolors.exports.dim(picocolors.exports.green(` Browser runner started at http://${((_a = this.ctx.config.api) == null ? void 0 : _a.host) || "localhost"}:${picocolors.exports.bold(`${this.ctx.server.config.server.port}`)}`)));
  8644. else if (this.ctx.config.ui)
  8645. this.log(picocolors.exports.dim(picocolors.exports.green(` UI started at http://${((_b = this.ctx.config.api) == null ? void 0 : _b.host) || "localhost"}:${picocolors.exports.bold(`${this.ctx.server.config.server.port}`)}${this.ctx.config.uiBase}`)));
  8646. else if (this.ctx.config.api)
  8647. this.log(picocolors.exports.dim(picocolors.exports.green(` API started at http://${((_c = this.ctx.config.api) == null ? void 0 : _c.host) || "localhost"}:${picocolors.exports.bold(`${this.ctx.config.api.port}`)}`)));
  8648. if (this.ctx.coverageProvider)
  8649. this.log(picocolors.exports.dim(" Coverage enabled with ") + picocolors.exports.yellow(this.ctx.coverageProvider.name));
  8650. this.log();
  8651. }
  8652. async printUnhandledErrors(errors) {
  8653. const errorMessage = picocolors.exports.red(picocolors.exports.bold(
  8654. `
  8655. Vitest caught ${errors.length} unhandled error${errors.length > 1 ? "s" : ""} during the test run.
  8656. This might cause false positive tests. Resolve unhandled errors to make sure your tests are not affected.`
  8657. ));
  8658. this.log(picocolors.exports.red(divider(picocolors.exports.bold(picocolors.exports.inverse(" Unhandled Errors ")))));
  8659. this.log(errorMessage);
  8660. await Promise.all(errors.map(async (err) => {
  8661. await this.printError(err, true, err.type || "Unhandled Error");
  8662. }));
  8663. this.log(picocolors.exports.red(divider()));
  8664. }
  8665. }
  8666. const WATCHER_DEBOUNCE = 100;
  8667. class Vitest {
  8668. constructor(mode) {
  8669. this.mode = mode;
  8670. this.config = void 0;
  8671. this.server = void 0;
  8672. this.state = void 0;
  8673. this.snapshot = void 0;
  8674. this.cache = void 0;
  8675. this.reporters = void 0;
  8676. this.vitenode = void 0;
  8677. this.invalidates = /* @__PURE__ */ new Set();
  8678. this.changedTests = /* @__PURE__ */ new Set();
  8679. this.isFirstRun = true;
  8680. this.restartsCount = 0;
  8681. this.runner = void 0;
  8682. this._onRestartListeners = [];
  8683. this.unregisterWatcher = noop$1;
  8684. this.logger = new Logger(this);
  8685. }
  8686. async setServer(options, server) {
  8687. var _a, _b, _c;
  8688. (_a = this.unregisterWatcher) == null ? void 0 : _a.call(this);
  8689. safeClearTimeout(this._rerunTimer);
  8690. this.restartsCount += 1;
  8691. (_b = this.pool) == null ? void 0 : _b.close();
  8692. this.pool = void 0;
  8693. const resolved = resolveConfig(this.mode, options, server.config);
  8694. this.server = server;
  8695. this.config = resolved;
  8696. this.state = new StateManager();
  8697. this.cache = new VitestCache();
  8698. this.snapshot = new SnapshotManager({ ...resolved.snapshotOptions });
  8699. if (this.config.watch)
  8700. this.registerWatcher();
  8701. this.vitenode = new ViteNodeServer(server, this.config);
  8702. const node = this.vitenode;
  8703. this.runner = new ViteNodeRunner({
  8704. root: server.config.root,
  8705. base: server.config.base,
  8706. fetchModule(id) {
  8707. return node.fetchModule(id);
  8708. },
  8709. resolveId(id, importer) {
  8710. return node.resolveId(id, importer);
  8711. }
  8712. });
  8713. if (this.config.watch) {
  8714. const serverRestart = server.restart;
  8715. server.restart = async (...args) => {
  8716. await Promise.all(this._onRestartListeners.map((fn) => fn()));
  8717. return await serverRestart(...args);
  8718. };
  8719. server.watcher.on("change", async (file) => {
  8720. file = normalizePath(file);
  8721. const isConfig = file === server.config.configFile;
  8722. if (isConfig) {
  8723. await Promise.all(this._onRestartListeners.map((fn) => fn("config")));
  8724. await serverRestart();
  8725. }
  8726. });
  8727. }
  8728. this.reporters = resolved.mode === "benchmark" ? await createBenchmarkReporters(toArray$1((_c = resolved.benchmark) == null ? void 0 : _c.reporters), this.runner) : await createReporters(resolved.reporters, this.runner);
  8729. this.runningPromise = void 0;
  8730. this.cache.results.setConfig(resolved.root, resolved.cache);
  8731. try {
  8732. await this.cache.results.readFromCache();
  8733. } catch (err) {
  8734. this.logger.error(`[vitest] Error, while trying to parse cache in ${this.cache.results.getCachePath()}:`, err);
  8735. }
  8736. }
  8737. async initCoverageProvider() {
  8738. if (this.coverageProvider !== void 0)
  8739. return;
  8740. this.coverageProvider = await getCoverageProvider(this.config.coverage);
  8741. if (this.coverageProvider) {
  8742. await this.coverageProvider.initialize(this);
  8743. this.config.coverage = this.coverageProvider.resolveOptions();
  8744. }
  8745. return this.coverageProvider;
  8746. }
  8747. getSerializableConfig() {
  8748. return deepMerge(
  8749. {
  8750. ...this.config,
  8751. reporters: [],
  8752. snapshotOptions: {
  8753. ...this.config.snapshotOptions,
  8754. resolveSnapshotPath: void 0
  8755. },
  8756. onConsoleLog: void 0,
  8757. sequence: {
  8758. ...this.config.sequence,
  8759. sequencer: void 0
  8760. }
  8761. },
  8762. this.configOverride || {}
  8763. );
  8764. }
  8765. async start(filters) {
  8766. var _a;
  8767. try {
  8768. await this.initCoverageProvider();
  8769. await ((_a = this.coverageProvider) == null ? void 0 : _a.clean(this.config.coverage.clean));
  8770. } catch (e) {
  8771. this.logger.error(e);
  8772. process.exit(1);
  8773. }
  8774. await this.report("onInit", this);
  8775. const files = await this.filterTestsBySource(
  8776. await this.globTestFiles(filters)
  8777. );
  8778. if (!files.length) {
  8779. const exitCode = this.config.passWithNoTests ? 0 : 1;
  8780. this.logger.printNoTestFound(filters);
  8781. process.exit(exitCode);
  8782. }
  8783. await Promise.all(files.map((file) => this.cache.stats.updateStats(file)));
  8784. await this.runFiles(files);
  8785. if (this.coverageProvider) {
  8786. this.logger.log(picocolors.exports.blue(" % ") + picocolors.exports.dim("Coverage report from ") + picocolors.exports.yellow(this.coverageProvider.name));
  8787. await this.coverageProvider.reportCoverage();
  8788. }
  8789. if (this.config.watch && !this.config.browser)
  8790. await this.report("onWatcherStart");
  8791. }
  8792. async getTestDependencies(filepath) {
  8793. const deps = /* @__PURE__ */ new Set();
  8794. const addImports = async (filepath2) => {
  8795. const transformed = await this.vitenode.transformRequest(filepath2);
  8796. if (!transformed)
  8797. return;
  8798. const dependencies = [...transformed.deps || [], ...transformed.dynamicDeps || []];
  8799. for (const dep of dependencies) {
  8800. const path = await this.server.pluginContainer.resolveId(dep, filepath2, { ssr: true });
  8801. const fsPath = path && !path.external && path.id.split("?")[0];
  8802. if (fsPath && !fsPath.includes("node_modules") && !deps.has(fsPath) && existsSync(fsPath)) {
  8803. deps.add(fsPath);
  8804. await addImports(fsPath);
  8805. }
  8806. }
  8807. };
  8808. await addImports(filepath);
  8809. return deps;
  8810. }
  8811. async filterTestsBySource(tests) {
  8812. if (this.config.changed && !this.config.related) {
  8813. const { VitestGit } = await import('./chunk-node-git.a44b4872.mjs');
  8814. const vitestGit = new VitestGit(this.config.root);
  8815. const related2 = await vitestGit.findChangedFiles({
  8816. changedSince: this.config.changed
  8817. });
  8818. if (!related2) {
  8819. this.logger.error(picocolors.exports.red("Could not find Git root. Have you initialized git with `git init`?\n"));
  8820. process.exit(1);
  8821. }
  8822. this.config.related = Array.from(new Set(related2));
  8823. }
  8824. const related = this.config.related;
  8825. if (!related)
  8826. return tests;
  8827. const forceRerunTriggers = this.config.forceRerunTriggers;
  8828. if (forceRerunTriggers.length && micromatch_1(related, forceRerunTriggers).length)
  8829. return tests;
  8830. if (!related.length)
  8831. return [];
  8832. const testDeps = await Promise.all(
  8833. tests.map(async (filepath) => {
  8834. const deps = await this.getTestDependencies(filepath);
  8835. return [filepath, deps];
  8836. })
  8837. );
  8838. const runningTests = [];
  8839. for (const [filepath, deps] of testDeps) {
  8840. if (deps.size && related.some((path) => path === filepath || deps.has(path)))
  8841. runningTests.push(filepath);
  8842. }
  8843. return runningTests;
  8844. }
  8845. async runFiles(paths) {
  8846. await this.runningPromise;
  8847. this.state.startCollectingPaths();
  8848. this.runningPromise = (async () => {
  8849. if (!this.pool)
  8850. this.pool = createPool(this);
  8851. const invalidates = Array.from(this.invalidates);
  8852. this.invalidates.clear();
  8853. this.snapshot.clear();
  8854. this.state.clearErrors();
  8855. try {
  8856. await this.pool.runTests(paths, invalidates);
  8857. } catch (err) {
  8858. this.state.catchError(err, "Unhandled Error");
  8859. }
  8860. const files = this.state.getFiles();
  8861. if (hasFailed(files))
  8862. process.exitCode = 1;
  8863. if (!this.config.browser)
  8864. await this.report("onFinished", files, this.state.getUnhandledErrors());
  8865. this.cache.results.updateResults(files);
  8866. await this.cache.results.writeToCache();
  8867. })().finally(() => {
  8868. this.runningPromise = void 0;
  8869. this.state.finishCollectingPaths();
  8870. });
  8871. return await this.runningPromise;
  8872. }
  8873. async rerunFiles(files = this.state.getFilepaths(), trigger) {
  8874. await this.report("onWatcherRerun", files, trigger);
  8875. await this.runFiles(files);
  8876. if (!this.config.browser)
  8877. await this.report("onWatcherStart");
  8878. }
  8879. async changeNamePattern(pattern, files = this.state.getFilepaths(), trigger) {
  8880. this.config.testNamePattern = pattern ? new RegExp(pattern) : void 0;
  8881. await this.rerunFiles(files, trigger);
  8882. }
  8883. async changeFilenamePattern(pattern) {
  8884. const files = this.state.getFilepaths();
  8885. if (!pattern)
  8886. return await this.rerunFiles(files, "reset filename pattern");
  8887. const filteredFiles = await this.globTestFiles([pattern]);
  8888. await this.rerunFiles(filteredFiles, "change filename pattern");
  8889. }
  8890. async rerunFailed() {
  8891. await this.rerunFiles(this.state.getFailedFilepaths(), "rerun failed");
  8892. }
  8893. async updateSnapshot(files) {
  8894. files = files || [
  8895. ...this.state.getFailedFilepaths(),
  8896. ...this.snapshot.summary.uncheckedKeysByFile.map((s) => s.filePath)
  8897. ];
  8898. this.configOverride = {
  8899. snapshotOptions: {
  8900. updateSnapshot: "all"
  8901. }
  8902. };
  8903. try {
  8904. await this.rerunFiles(files, "update snapshot");
  8905. } finally {
  8906. this.configOverride = void 0;
  8907. }
  8908. }
  8909. async scheduleRerun(triggerId) {
  8910. const currentCount = this.restartsCount;
  8911. safeClearTimeout(this._rerunTimer);
  8912. await this.runningPromise;
  8913. safeClearTimeout(this._rerunTimer);
  8914. if (this.restartsCount !== currentCount)
  8915. return;
  8916. this._rerunTimer = safeSetTimeout(async () => {
  8917. var _a;
  8918. if (this.changedTests.size === 0) {
  8919. this.invalidates.clear();
  8920. return;
  8921. }
  8922. if (this.restartsCount !== currentCount)
  8923. return;
  8924. this.isFirstRun = false;
  8925. this.snapshot.clear();
  8926. const files = Array.from(this.changedTests);
  8927. this.changedTests.clear();
  8928. if (this.coverageProvider && this.config.coverage.cleanOnRerun)
  8929. await this.coverageProvider.clean();
  8930. await this.report("onWatcherRerun", files, triggerId);
  8931. await this.runFiles(files);
  8932. await ((_a = this.coverageProvider) == null ? void 0 : _a.reportCoverage());
  8933. if (!this.config.browser)
  8934. await this.report("onWatcherStart");
  8935. }, WATCHER_DEBOUNCE);
  8936. }
  8937. registerWatcher() {
  8938. const onChange = (id) => {
  8939. id = slash$2(id);
  8940. const needsRerun = this.handleFileChanged(id);
  8941. if (needsRerun)
  8942. this.scheduleRerun(id);
  8943. };
  8944. const onUnlink = (id) => {
  8945. id = slash$2(id);
  8946. this.invalidates.add(id);
  8947. if (this.state.filesMap.has(id)) {
  8948. this.state.filesMap.delete(id);
  8949. this.cache.results.removeFromCache(id);
  8950. this.cache.stats.removeStats(id);
  8951. this.changedTests.delete(id);
  8952. this.report("onTestRemoved", id);
  8953. }
  8954. };
  8955. const onAdd = async (id) => {
  8956. id = slash$2(id);
  8957. if (await this.isTargetFile(id)) {
  8958. this.changedTests.add(id);
  8959. await this.cache.stats.updateStats(id);
  8960. this.scheduleRerun(id);
  8961. }
  8962. };
  8963. const watcher = this.server.watcher;
  8964. if (this.config.forceRerunTriggers.length)
  8965. watcher.add(this.config.forceRerunTriggers);
  8966. watcher.unwatch(this.config.watchExclude);
  8967. watcher.on("change", onChange);
  8968. watcher.on("unlink", onUnlink);
  8969. watcher.on("add", onAdd);
  8970. this.unregisterWatcher = () => {
  8971. watcher.off("change", onChange);
  8972. watcher.off("unlink", onUnlink);
  8973. watcher.off("add", onAdd);
  8974. this.unregisterWatcher = noop$1;
  8975. };
  8976. }
  8977. handleFileChanged(id) {
  8978. if (this.changedTests.has(id) || this.invalidates.has(id))
  8979. return false;
  8980. if (micromatch_1.isMatch(id, this.config.forceRerunTriggers)) {
  8981. this.state.getFilepaths().forEach((file) => this.changedTests.add(file));
  8982. return true;
  8983. }
  8984. const mod = this.server.moduleGraph.getModuleById(id);
  8985. if (!mod)
  8986. return false;
  8987. this.invalidates.add(id);
  8988. if (this.state.filesMap.has(id)) {
  8989. this.changedTests.add(id);
  8990. return true;
  8991. }
  8992. let rerun = false;
  8993. mod.importers.forEach((i) => {
  8994. if (!i.id)
  8995. return;
  8996. const heedsRerun = this.handleFileChanged(i.id);
  8997. if (heedsRerun)
  8998. rerun = true;
  8999. });
  9000. return rerun;
  9001. }
  9002. async close() {
  9003. var _a;
  9004. if (!this.closingPromise) {
  9005. this.closingPromise = Promise.allSettled([
  9006. (_a = this.pool) == null ? void 0 : _a.close(),
  9007. this.server.close()
  9008. ].filter(Boolean)).then((results) => {
  9009. results.filter((r) => r.status === "rejected").forEach((err) => {
  9010. this.logger.error("error during close", err.reason);
  9011. });
  9012. });
  9013. }
  9014. return this.closingPromise;
  9015. }
  9016. async exit(force = false) {
  9017. safeSetTimeout(() => {
  9018. console.warn(`close timed out after ${this.config.teardownTimeout}ms`);
  9019. process.exit();
  9020. }, this.config.teardownTimeout).unref();
  9021. await this.close();
  9022. if (force)
  9023. process.exit();
  9024. }
  9025. async report(name, ...args) {
  9026. await Promise.all(this.reporters.map((r) => {
  9027. var _a;
  9028. return (_a = r[name]) == null ? void 0 : _a.call(
  9029. r,
  9030. ...args
  9031. );
  9032. }));
  9033. }
  9034. async globTestFiles(filters = []) {
  9035. const { include, exclude, includeSource } = this.config;
  9036. const globOptions = {
  9037. absolute: true,
  9038. cwd: this.config.dir || this.config.root,
  9039. ignore: exclude
  9040. };
  9041. let testFiles = await out(include, globOptions);
  9042. if (filters.length && process.platform === "win32")
  9043. filters = filters.map((f) => toNamespacedPath(f));
  9044. if (filters.length)
  9045. testFiles = testFiles.filter((i) => filters.some((f) => i.includes(f)));
  9046. if (includeSource) {
  9047. let files = await out(includeSource, globOptions);
  9048. if (filters.length)
  9049. files = files.filter((i) => filters.some((f) => i.includes(f)));
  9050. await Promise.all(files.map(async (file) => {
  9051. try {
  9052. const code = await promises.readFile(file, "utf-8");
  9053. if (this.isInSourceTestFile(code))
  9054. testFiles.push(file);
  9055. } catch {
  9056. return null;
  9057. }
  9058. }));
  9059. }
  9060. return testFiles;
  9061. }
  9062. async isTargetFile(id, source) {
  9063. var _a;
  9064. const relativeId = relative(this.config.dir || this.config.root, id);
  9065. if (micromatch_1.isMatch(relativeId, this.config.exclude))
  9066. return false;
  9067. if (micromatch_1.isMatch(relativeId, this.config.include))
  9068. return true;
  9069. if (((_a = this.config.includeSource) == null ? void 0 : _a.length) && micromatch_1.isMatch(relativeId, this.config.includeSource)) {
  9070. source = source || await promises.readFile(id, "utf-8");
  9071. return this.isInSourceTestFile(source);
  9072. }
  9073. return false;
  9074. }
  9075. isInSourceTestFile(code) {
  9076. return code.includes("import.meta.vitest");
  9077. }
  9078. onServerRestart(fn) {
  9079. this._onRestartListeners.push(fn);
  9080. }
  9081. }
  9082. function generateCssFilenameHash(filepath) {
  9083. return createHash("md5").update(filepath).digest("hex").slice(0, 6);
  9084. }
  9085. function generateScopedClassName(strategy, name, filename) {
  9086. if (strategy === "scoped")
  9087. return null;
  9088. if (strategy === "non-scoped")
  9089. return name;
  9090. const hash = generateCssFilenameHash(filename);
  9091. return `_${name}_${hash}`;
  9092. }
  9093. const EnvReplacerPlugin = () => {
  9094. return {
  9095. name: "vitest:env-replacer",
  9096. enforce: "pre",
  9097. transform(code) {
  9098. if (!/\bimport\.meta\.env\b/g.test(code))
  9099. return null;
  9100. let s = null;
  9101. const envs = stripLiteral(code).matchAll(/\bimport\.meta\.env\b/g);
  9102. for (const env of envs) {
  9103. s || (s = new MagicString(code));
  9104. const startIndex = env.index;
  9105. const endIndex = startIndex + env[0].length;
  9106. s.overwrite(startIndex, endIndex, "process.env");
  9107. }
  9108. if (s) {
  9109. return {
  9110. code: s.toString(),
  9111. map: s.generateMap({ hires: true })
  9112. };
  9113. }
  9114. }
  9115. };
  9116. };
  9117. async function loadGlobalSetupFiles(ctx) {
  9118. var _a;
  9119. const server = ctx.server;
  9120. const runner = ctx.runner;
  9121. const globalSetupFiles = toArray$1((_a = server.config.test) == null ? void 0 : _a.globalSetup);
  9122. return Promise.all(globalSetupFiles.map((file) => loadGlobalSetupFile(file, runner)));
  9123. }
  9124. async function loadGlobalSetupFile(file, runner) {
  9125. const m = await runner.executeFile(file);
  9126. for (const exp of ["default", "setup", "teardown"]) {
  9127. if (m[exp] != null && typeof m[exp] !== "function")
  9128. throw new Error(`invalid export in globalSetup file ${file}: ${exp} must be a function`);
  9129. }
  9130. if (m.default) {
  9131. return {
  9132. file,
  9133. setup: m.default
  9134. };
  9135. } else if (m.setup || m.teardown) {
  9136. return {
  9137. file,
  9138. setup: m.setup,
  9139. teardown: m.teardown
  9140. };
  9141. } else {
  9142. throw new Error(`invalid globalSetup file ${file}. Must export setup, teardown or have a default export`);
  9143. }
  9144. }
  9145. const GlobalSetupPlugin = (ctx) => {
  9146. let globalSetupFiles;
  9147. return {
  9148. name: "vitest:global-setup-plugin",
  9149. enforce: "pre",
  9150. async buildStart() {
  9151. var _a, _b;
  9152. if (!((_a = ctx.server.config.test) == null ? void 0 : _a.globalSetup))
  9153. return;
  9154. globalSetupFiles = await loadGlobalSetupFiles(ctx);
  9155. try {
  9156. for (const globalSetupFile of globalSetupFiles) {
  9157. const teardown = await ((_b = globalSetupFile.setup) == null ? void 0 : _b.call(globalSetupFile));
  9158. if (teardown == null || !!globalSetupFile.teardown)
  9159. continue;
  9160. if (typeof teardown !== "function")
  9161. throw new Error(`invalid return value in globalSetup file ${globalSetupFile.file}. Must return a function`);
  9162. globalSetupFile.teardown = teardown;
  9163. }
  9164. } catch (e) {
  9165. ctx.logger.error(`
  9166. ${picocolors.exports.red(divider(picocolors.exports.bold(picocolors.exports.inverse(" Error during global setup "))))}`);
  9167. await ctx.logger.printError(e);
  9168. process.exit(1);
  9169. }
  9170. },
  9171. async buildEnd() {
  9172. var _a;
  9173. if (globalSetupFiles == null ? void 0 : globalSetupFiles.length) {
  9174. for (const globalSetupFile of globalSetupFiles.reverse()) {
  9175. try {
  9176. await ((_a = globalSetupFile.teardown) == null ? void 0 : _a.call(globalSetupFile));
  9177. } catch (error) {
  9178. ctx.logger.error(`error during global teardown of ${globalSetupFile.file}`, error);
  9179. }
  9180. }
  9181. }
  9182. }
  9183. };
  9184. };
  9185. const hoistRegexp = /^ *\b((?:vitest|vi)\s*.\s*(mock|unmock)\(["`'\s]+(.*[@\w_-]+)["`'\s]+)[),]{1};?/gm;
  9186. const vitestRegexp = /import {[^}]*}.*(?=["'`]vitest["`']).*/gm;
  9187. function hoistMocks(code) {
  9188. let m;
  9189. const mocks = code.matchAll(hoistRegexp);
  9190. for (const mockResult of mocks) {
  9191. const lastIndex = getMockLastIndex(code.slice(mockResult.index));
  9192. if (lastIndex === null)
  9193. continue;
  9194. const startIndex = mockResult.index;
  9195. const { insideComment, insideString } = getIndexStatus(code, startIndex);
  9196. if (insideComment || insideString)
  9197. continue;
  9198. const endIndex = startIndex + lastIndex;
  9199. m ?? (m = new MagicString(code));
  9200. m.prepend(`${m.slice(startIndex, endIndex)}
  9201. `);
  9202. m.remove(startIndex, endIndex);
  9203. }
  9204. return m;
  9205. }
  9206. const API_NOT_FOUND_ERROR = `There are some problems in resolving the mocks API.
  9207. You may encounter this issue when importing the mocks API from another module other than 'vitest'.
  9208. To fix this issue you can either:
  9209. - import the mocks API directly from 'vitest'
  9210. - enable the 'globals' options`;
  9211. const MocksPlugin = () => {
  9212. return {
  9213. name: "vitest:mock-plugin",
  9214. enforce: "post",
  9215. async transform(code) {
  9216. const m = hoistMocks(code);
  9217. if (m) {
  9218. const vitestImports = code.matchAll(vitestRegexp);
  9219. let found = false;
  9220. for (const match of vitestImports) {
  9221. const indexStart = match.index;
  9222. const indexEnd = match[0].length + indexStart;
  9223. m.remove(indexStart, indexEnd);
  9224. m.prepend(`${match[0]}
  9225. `);
  9226. found = true;
  9227. }
  9228. if (!found) {
  9229. m.prepend(`try { vi } catch (_) { try { vitest } catch (__){ throw new Error(${JSON.stringify(API_NOT_FOUND_ERROR)}) } }
  9230. `);
  9231. }
  9232. return {
  9233. code: m.toString(),
  9234. map: m.generateMap({ hires: true })
  9235. };
  9236. }
  9237. }
  9238. };
  9239. };
  9240. function getMockLastIndex(code) {
  9241. const index = getCallLastIndex(code);
  9242. if (index === null)
  9243. return null;
  9244. return code[index + 1] === ";" ? index + 2 : index + 1;
  9245. }
  9246. function getIndexStatus(code, from) {
  9247. let index = 0;
  9248. let commentStarted = false;
  9249. let commentEnded = true;
  9250. let multilineCommentStarted = false;
  9251. let multilineCommentEnded = true;
  9252. let inString = null;
  9253. let beforeChar = null;
  9254. while (index <= from) {
  9255. const char = code[index];
  9256. const sub = code[index] + code[index + 1];
  9257. if (!inString) {
  9258. if (sub === "/*") {
  9259. multilineCommentStarted = true;
  9260. multilineCommentEnded = false;
  9261. }
  9262. if (sub === "*/" && multilineCommentStarted) {
  9263. multilineCommentStarted = false;
  9264. multilineCommentEnded = true;
  9265. }
  9266. if (sub === "//") {
  9267. commentStarted = true;
  9268. commentEnded = false;
  9269. }
  9270. if ((char === "\n" || sub === "\r\n") && commentStarted) {
  9271. commentStarted = false;
  9272. commentEnded = true;
  9273. }
  9274. }
  9275. if (!multilineCommentStarted && !commentStarted) {
  9276. const isCharString = char === '"' || char === "'" || char === "`";
  9277. if (isCharString && beforeChar !== "\\") {
  9278. if (inString === char)
  9279. inString = null;
  9280. else if (!inString)
  9281. inString = char;
  9282. }
  9283. }
  9284. beforeChar = code[index];
  9285. index++;
  9286. }
  9287. return {
  9288. insideComment: !multilineCommentEnded || !commentEnded,
  9289. insideString: inString !== null
  9290. };
  9291. }
  9292. const cssLangs = "\\.(css|less|sass|scss|styl|stylus|pcss|postcss)($|\\?)";
  9293. const cssLangRE = new RegExp(cssLangs);
  9294. const cssModuleRE = new RegExp(`\\.module${cssLangs}`);
  9295. const isCSS = (id) => {
  9296. return cssLangRE.test(id);
  9297. };
  9298. const isCSSModule = (id) => {
  9299. return cssModuleRE.test(id);
  9300. };
  9301. const getCSSModuleProxyReturn = (strategy, filename) => {
  9302. if (strategy === "non-scoped")
  9303. return "style";
  9304. const hash = generateCssFilenameHash(filename);
  9305. return `\`_\${style}_${hash}\``;
  9306. };
  9307. function CSSEnablerPlugin(ctx) {
  9308. const shouldProcessCSS = (id) => {
  9309. const { css } = ctx.config;
  9310. if (typeof css === "boolean")
  9311. return css;
  9312. if (toArray$1(css.exclude).some((re) => re.test(id)))
  9313. return false;
  9314. if (toArray$1(css.include).some((re) => re.test(id)))
  9315. return true;
  9316. return false;
  9317. };
  9318. return [
  9319. {
  9320. name: "vitest:css-disable",
  9321. enforce: "pre",
  9322. transform(code, id) {
  9323. if (!isCSS(id))
  9324. return;
  9325. if (!shouldProcessCSS(id))
  9326. return { code: "" };
  9327. }
  9328. },
  9329. {
  9330. name: "vitest:css-empty-post",
  9331. enforce: "post",
  9332. transform(_, id) {
  9333. var _a;
  9334. if (!isCSS(id) || shouldProcessCSS(id))
  9335. return;
  9336. if (isCSSModule(id)) {
  9337. const scopeStrategy = typeof ctx.config.css !== "boolean" && ((_a = ctx.config.css.modules) == null ? void 0 : _a.classNameStrategy) || "stable";
  9338. const proxyReturn = getCSSModuleProxyReturn(scopeStrategy, relative(ctx.config.root, id));
  9339. const code = `export default new Proxy(Object.create(null), {
  9340. get(_, style) {
  9341. return ${proxyReturn};
  9342. },
  9343. })`;
  9344. return { code };
  9345. }
  9346. return { code: "" };
  9347. }
  9348. }
  9349. ];
  9350. }
  9351. function CoverageTransform(ctx) {
  9352. return {
  9353. name: "vitest:coverage-transform",
  9354. transform(srcCode, id) {
  9355. var _a, _b;
  9356. return (_b = (_a = ctx.coverageProvider) == null ? void 0 : _a.onFileTransform) == null ? void 0 : _b.call(_a, srcCode, id, this);
  9357. }
  9358. };
  9359. }
  9360. async function VitestPlugin(options = {}, ctx = new Vitest("test")) {
  9361. const getRoot = () => {
  9362. var _a;
  9363. return ((_a = ctx.config) == null ? void 0 : _a.root) || options.root || process.cwd();
  9364. };
  9365. async function UIPlugin() {
  9366. await ensurePackageInstalled("@vitest/ui", getRoot());
  9367. return (await import('@vitest/ui')).default(options.uiBase);
  9368. }
  9369. async function BrowserPlugin() {
  9370. await ensurePackageInstalled("@vitest/browser", getRoot());
  9371. return (await import('@vitest/browser')).default("/");
  9372. }
  9373. return [
  9374. {
  9375. name: "vitest",
  9376. enforce: "pre",
  9377. options() {
  9378. this.meta.watchMode = false;
  9379. },
  9380. config(viteConfig) {
  9381. var _a, _b, _c;
  9382. const preOptions = deepMerge({}, configDefaults, options, viteConfig.test ?? {});
  9383. preOptions.api = resolveApiConfig(preOptions);
  9384. if (viteConfig.define) {
  9385. delete viteConfig.define["import.meta.vitest"];
  9386. delete viteConfig.define["process.env"];
  9387. }
  9388. const defines = {};
  9389. for (const key in viteConfig.define) {
  9390. const val = viteConfig.define[key];
  9391. let replacement;
  9392. try {
  9393. replacement = typeof val === "string" ? JSON.parse(val) : val;
  9394. } catch {
  9395. continue;
  9396. }
  9397. if (key.startsWith("import.meta.env.")) {
  9398. const envKey = key.slice("import.meta.env.".length);
  9399. process.env[envKey] = replacement;
  9400. delete viteConfig.define[key];
  9401. } else if (key.startsWith("process.env.")) {
  9402. const envKey = key.slice("process.env.".length);
  9403. process.env[envKey] = replacement;
  9404. delete viteConfig.define[key];
  9405. } else if (!key.includes(".")) {
  9406. defines[key] = replacement;
  9407. delete viteConfig.define[key];
  9408. }
  9409. }
  9410. options.defines = defines;
  9411. let open;
  9412. if (preOptions.ui && preOptions.open)
  9413. open = preOptions.uiBase ?? "/__vitest__/";
  9414. else if (preOptions.browser)
  9415. open = "/";
  9416. const config = {
  9417. resolve: {
  9418. mainFields: [],
  9419. alias: preOptions.alias
  9420. },
  9421. server: {
  9422. ...preOptions.api,
  9423. watch: {
  9424. ignored: preOptions.watchExclude
  9425. },
  9426. open,
  9427. hmr: false,
  9428. preTransformRequests: false
  9429. }
  9430. };
  9431. const classNameStrategy = preOptions.css && ((_b = (_a = preOptions.css) == null ? void 0 : _a.modules) == null ? void 0 : _b.classNameStrategy);
  9432. if (classNameStrategy !== "scoped") {
  9433. config.css ?? (config.css = {});
  9434. (_c = config.css).modules ?? (_c.modules = {});
  9435. config.css.modules.generateScopedName = (name, filename) => {
  9436. const root = getRoot();
  9437. return generateScopedClassName(classNameStrategy, name, relative(root, filename));
  9438. };
  9439. }
  9440. if (!options.browser) {
  9441. Object.assign(config, {
  9442. cacheDir: void 0,
  9443. optimizeDeps: {
  9444. disabled: true,
  9445. entries: []
  9446. }
  9447. });
  9448. }
  9449. return config;
  9450. },
  9451. async configResolved(viteConfig) {
  9452. var _a, _b, _c, _d;
  9453. const viteConfigTest = viteConfig.test || {};
  9454. if (viteConfigTest.watch === false)
  9455. viteConfigTest.run = true;
  9456. if ("alias" in viteConfigTest)
  9457. delete viteConfigTest.alias;
  9458. options = deepMerge(
  9459. {},
  9460. configDefaults,
  9461. viteConfigTest,
  9462. options
  9463. );
  9464. options.api = resolveApiConfig(options);
  9465. const { PROD, DEV, ...envs } = viteConfig.env;
  9466. (_a = process.env).PROD ?? (_a.PROD = PROD ? "1" : "");
  9467. (_b = process.env).DEV ?? (_b.DEV = DEV ? "1" : "");
  9468. (_c = process.env).SSR ?? (_c.SSR = "1");
  9469. for (const name in envs)
  9470. (_d = process.env)[name] ?? (_d[name] = envs[name]);
  9471. },
  9472. async configureServer(server) {
  9473. try {
  9474. await ctx.setServer(options, server);
  9475. if (options.api && options.watch)
  9476. (await import('./chunk-api-setup.11cfd513.mjs')).setup(ctx);
  9477. } catch (err) {
  9478. ctx.logger.printError(err, true);
  9479. process.exit(1);
  9480. }
  9481. if (!options.watch)
  9482. await server.watcher.close();
  9483. }
  9484. },
  9485. EnvReplacerPlugin(),
  9486. MocksPlugin(),
  9487. GlobalSetupPlugin(ctx),
  9488. ...options.browser ? await BrowserPlugin() : [],
  9489. ...CSSEnablerPlugin(ctx),
  9490. CoverageTransform(ctx),
  9491. options.ui ? await UIPlugin() : null
  9492. ].filter(notNullish);
  9493. }
  9494. async function createVitest(mode, options, viteOverrides = {}) {
  9495. var _a;
  9496. const ctx = new Vitest(mode);
  9497. const root = resolve(options.root || process.cwd());
  9498. const configPath = options.config ? resolve(root, options.config) : await findUp(configFiles, { cwd: root });
  9499. const config = {
  9500. logLevel: "error",
  9501. configFile: configPath,
  9502. mode: options.mode || process.env.NODE_ENV || mode,
  9503. plugins: await VitestPlugin(options, ctx)
  9504. };
  9505. const server = await createServer(mergeConfig(config, mergeConfig(viteOverrides, { root: options.root })));
  9506. if ((_a = ctx.config.api) == null ? void 0 : _a.port)
  9507. await server.listen();
  9508. else
  9509. await server.pluginContainer.buildStart({});
  9510. return ctx;
  9511. }
  9512. const keys = [
  9513. ["a", "rerun all tests"],
  9514. ["f", "rerun only failed tests"],
  9515. ["u", "update snapshot"],
  9516. ["p", "filter by a filename"],
  9517. ["t", "filter by a test name regex pattern"],
  9518. ["q", "quit"]
  9519. ];
  9520. function printShortcutsHelp() {
  9521. stdout().write(
  9522. `
  9523. ${picocolors.exports.bold(" Watch Usage")}
  9524. ${keys.map((i) => picocolors.exports.dim(" press ") + picocolors.exports.reset(picocolors.exports.bold(i[0])) + picocolors.exports.dim(` to ${i[1]}`)).join("\n")}
  9525. `
  9526. );
  9527. }
  9528. function registerConsoleShortcuts(ctx) {
  9529. let latestFilename = "";
  9530. async function _keypressHandler(str, key) {
  9531. if (str === "" || str === "\x1B" || key && key.ctrl && key.name === "c")
  9532. return ctx.exit(true);
  9533. if (ctx.runningPromise)
  9534. return;
  9535. const name = key == null ? void 0 : key.name;
  9536. if (name === "h")
  9537. return printShortcutsHelp();
  9538. if (name === "u")
  9539. return ctx.updateSnapshot();
  9540. if (name === "a" || name === "return")
  9541. return ctx.changeNamePattern("");
  9542. if (name === "f")
  9543. return ctx.rerunFailed();
  9544. if (name === "t")
  9545. return inputNamePattern();
  9546. if (name === "p")
  9547. return inputFilePattern();
  9548. if (name === "q")
  9549. return ctx.exit(true);
  9550. }
  9551. async function keypressHandler(str, key) {
  9552. await _keypressHandler(str, key);
  9553. }
  9554. async function inputNamePattern() {
  9555. off();
  9556. const { filter = "" } = await prompts([{
  9557. name: "filter",
  9558. type: "text",
  9559. message: "Input test name pattern (RegExp)",
  9560. initial: String(ctx.config.testNamePattern || "")
  9561. }]);
  9562. await ctx.changeNamePattern(filter, void 0, "change pattern");
  9563. on();
  9564. }
  9565. async function inputFilePattern() {
  9566. off();
  9567. const { filter = "" } = await prompts([{
  9568. name: "filter",
  9569. type: "text",
  9570. message: "Input filename pattern",
  9571. initial: latestFilename
  9572. }]);
  9573. latestFilename = filter;
  9574. await ctx.changeFilenamePattern(filter);
  9575. on();
  9576. }
  9577. let rl;
  9578. function on() {
  9579. off();
  9580. rl = require$$0$2.createInterface({ input: process.stdin, escapeCodeTimeout: 50 });
  9581. require$$0$2.emitKeypressEvents(process.stdin, rl);
  9582. if (process.stdin.isTTY)
  9583. process.stdin.setRawMode(true);
  9584. process.stdin.on("keypress", keypressHandler);
  9585. }
  9586. function off() {
  9587. rl == null ? void 0 : rl.close();
  9588. rl = void 0;
  9589. process.stdin.removeListener("keypress", keypressHandler);
  9590. if (process.stdin.isTTY)
  9591. process.stdin.setRawMode(false);
  9592. }
  9593. on();
  9594. }
  9595. async function startVitest(mode, cliFilters, options, viteOverrides) {
  9596. var _a;
  9597. process.env.TEST = "true";
  9598. process.env.VITEST = "true";
  9599. (_a = process.env).NODE_ENV ?? (_a.NODE_ENV = options.mode || "test");
  9600. if (options.run)
  9601. options.watch = false;
  9602. if (options.browser)
  9603. options.threads = false;
  9604. const root = resolve(options.root || process.cwd());
  9605. if (!await ensurePackageInstalled("vite", root)) {
  9606. process.exitCode = 1;
  9607. return false;
  9608. }
  9609. if (typeof options.coverage === "boolean")
  9610. options.coverage = { enabled: options.coverage };
  9611. const ctx = await createVitest(mode, options, viteOverrides);
  9612. if (mode !== "benchmark" && ctx.config.coverage.enabled) {
  9613. const provider = ctx.config.coverage.provider || "c8";
  9614. if (typeof provider === "string") {
  9615. const requiredPackages = CoverageProviderMap[provider];
  9616. if (!await ensurePackageInstalled(requiredPackages, root)) {
  9617. process.exitCode = 1;
  9618. return false;
  9619. }
  9620. }
  9621. }
  9622. const environmentPackage = getEnvPackageName(ctx.config.environment);
  9623. if (environmentPackage && !await ensurePackageInstalled(environmentPackage, root)) {
  9624. process.exitCode = 1;
  9625. return false;
  9626. }
  9627. if (process.stdin.isTTY && ctx.config.watch)
  9628. registerConsoleShortcuts(ctx);
  9629. ctx.onServerRestart((reason) => {
  9630. ctx.report("onServerRestart", reason);
  9631. if (process.env.VITEST_CLI_WRAPPER)
  9632. process.exit(EXIT_CODE_RESTART);
  9633. else
  9634. ctx.start(cliFilters);
  9635. });
  9636. try {
  9637. await ctx.start(cliFilters);
  9638. } catch (e) {
  9639. process.exitCode = 1;
  9640. await ctx.logger.printError(e, true, "Unhandled Error");
  9641. ctx.logger.error("\n\n");
  9642. return false;
  9643. }
  9644. if (!ctx.config.watch) {
  9645. await ctx.exit();
  9646. return !process.exitCode;
  9647. }
  9648. return true;
  9649. }
  9650. export { BaseSequencer as B, VitestPlugin as V, createVitest as c, divider as d, startVitest as s, version$1 as v };