watch.js 196 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406
  1. /*
  2. @license
  3. Rollup.js v2.40.0
  4. Fri, 26 Feb 2021 14:39:44 GMT - commit 0a0958ff926554abe9916178f56762ba71301ddd
  5. https://github.com/rollup/rollup
  6. Released under the MIT License.
  7. */
  8. import require$$0$2, { sep, resolve } from 'path';
  9. import require$$0$1 from 'util';
  10. import { defaultOnWarn, ensureArray as ensureArray$1, warnUnknownOptions, getAugmentedNamespace, fseventsImporter, rollupInternal } from './rollup.js';
  11. import require$$0$3 from 'events';
  12. import fs$4 from 'fs';
  13. import require$$1 from 'stream';
  14. import require$$2, { platform } from 'os';
  15. import 'crypto';
  16. var utils$8 = {};
  17. (function (exports) {
  18. exports.isInteger = num => {
  19. if (typeof num === 'number') {
  20. return Number.isInteger(num);
  21. }
  22. if (typeof num === 'string' && num.trim() !== '') {
  23. return Number.isInteger(Number(num));
  24. }
  25. return false;
  26. };
  27. /**
  28. * Find a node of the given type
  29. */
  30. exports.find = (node, type) => node.nodes.find(node => node.type === type);
  31. /**
  32. * Find a node of the given type
  33. */
  34. exports.exceedsLimit = (min, max, step = 1, limit) => {
  35. if (limit === false) return false;
  36. if (!exports.isInteger(min) || !exports.isInteger(max)) return false;
  37. return ((Number(max) - Number(min)) / Number(step)) >= limit;
  38. };
  39. /**
  40. * Escape the given node with '\\' before node.value
  41. */
  42. exports.escapeNode = (block, n = 0, type) => {
  43. let node = block.nodes[n];
  44. if (!node) return;
  45. if ((type && node.type === type) || node.type === 'open' || node.type === 'close') {
  46. if (node.escaped !== true) {
  47. node.value = '\\' + node.value;
  48. node.escaped = true;
  49. }
  50. }
  51. };
  52. /**
  53. * Returns true if the given brace node should be enclosed in literal braces
  54. */
  55. exports.encloseBrace = node => {
  56. if (node.type !== 'brace') return false;
  57. if ((node.commas >> 0 + node.ranges >> 0) === 0) {
  58. node.invalid = true;
  59. return true;
  60. }
  61. return false;
  62. };
  63. /**
  64. * Returns true if a brace node is invalid.
  65. */
  66. exports.isInvalidBrace = block => {
  67. if (block.type !== 'brace') return false;
  68. if (block.invalid === true || block.dollar) return true;
  69. if ((block.commas >> 0 + block.ranges >> 0) === 0) {
  70. block.invalid = true;
  71. return true;
  72. }
  73. if (block.open !== true || block.close !== true) {
  74. block.invalid = true;
  75. return true;
  76. }
  77. return false;
  78. };
  79. /**
  80. * Returns true if a node is an open or close node
  81. */
  82. exports.isOpenOrClose = node => {
  83. if (node.type === 'open' || node.type === 'close') {
  84. return true;
  85. }
  86. return node.open === true || node.close === true;
  87. };
  88. /**
  89. * Reduce an array of text nodes.
  90. */
  91. exports.reduce = nodes => nodes.reduce((acc, node) => {
  92. if (node.type === 'text') acc.push(node.value);
  93. if (node.type === 'range') node.type = 'text';
  94. return acc;
  95. }, []);
  96. /**
  97. * Flatten an array
  98. */
  99. exports.flatten = (...args) => {
  100. const result = [];
  101. const flat = arr => {
  102. for (let i = 0; i < arr.length; i++) {
  103. let ele = arr[i];
  104. Array.isArray(ele) ? flat(ele) : ele !== void 0 && result.push(ele);
  105. }
  106. return result;
  107. };
  108. flat(args);
  109. return result;
  110. };
  111. }(utils$8));
  112. const utils$7 = utils$8;
  113. var stringify$4 = (ast, options = {}) => {
  114. let stringify = (node, parent = {}) => {
  115. let invalidBlock = options.escapeInvalid && utils$7.isInvalidBrace(parent);
  116. let invalidNode = node.invalid === true && options.escapeInvalid === true;
  117. let output = '';
  118. if (node.value) {
  119. if ((invalidBlock || invalidNode) && utils$7.isOpenOrClose(node)) {
  120. return '\\' + node.value;
  121. }
  122. return node.value;
  123. }
  124. if (node.value) {
  125. return node.value;
  126. }
  127. if (node.nodes) {
  128. for (let child of node.nodes) {
  129. output += stringify(child);
  130. }
  131. }
  132. return output;
  133. };
  134. return stringify(ast);
  135. };
  136. /*!
  137. * is-number <https://github.com/jonschlinkert/is-number>
  138. *
  139. * Copyright (c) 2014-present, Jon Schlinkert.
  140. * Released under the MIT License.
  141. */
  142. var isNumber$2 = function(num) {
  143. if (typeof num === 'number') {
  144. return num - num === 0;
  145. }
  146. if (typeof num === 'string' && num.trim() !== '') {
  147. return Number.isFinite ? Number.isFinite(+num) : isFinite(+num);
  148. }
  149. return false;
  150. };
  151. /*!
  152. * to-regex-range <https://github.com/micromatch/to-regex-range>
  153. *
  154. * Copyright (c) 2015-present, Jon Schlinkert.
  155. * Released under the MIT License.
  156. */
  157. const isNumber$1 = isNumber$2;
  158. const toRegexRange$1 = (min, max, options) => {
  159. if (isNumber$1(min) === false) {
  160. throw new TypeError('toRegexRange: expected the first argument to be a number');
  161. }
  162. if (max === void 0 || min === max) {
  163. return String(min);
  164. }
  165. if (isNumber$1(max) === false) {
  166. throw new TypeError('toRegexRange: expected the second argument to be a number.');
  167. }
  168. let opts = { relaxZeros: true, ...options };
  169. if (typeof opts.strictZeros === 'boolean') {
  170. opts.relaxZeros = opts.strictZeros === false;
  171. }
  172. let relax = String(opts.relaxZeros);
  173. let shorthand = String(opts.shorthand);
  174. let capture = String(opts.capture);
  175. let wrap = String(opts.wrap);
  176. let cacheKey = min + ':' + max + '=' + relax + shorthand + capture + wrap;
  177. if (toRegexRange$1.cache.hasOwnProperty(cacheKey)) {
  178. return toRegexRange$1.cache[cacheKey].result;
  179. }
  180. let a = Math.min(min, max);
  181. let b = Math.max(min, max);
  182. if (Math.abs(a - b) === 1) {
  183. let result = min + '|' + max;
  184. if (opts.capture) {
  185. return `(${result})`;
  186. }
  187. if (opts.wrap === false) {
  188. return result;
  189. }
  190. return `(?:${result})`;
  191. }
  192. let isPadded = hasPadding(min) || hasPadding(max);
  193. let state = { min, max, a, b };
  194. let positives = [];
  195. let negatives = [];
  196. if (isPadded) {
  197. state.isPadded = isPadded;
  198. state.maxLen = String(state.max).length;
  199. }
  200. if (a < 0) {
  201. let newMin = b < 0 ? Math.abs(b) : 1;
  202. negatives = splitToPatterns(newMin, Math.abs(a), state, opts);
  203. a = state.a = 0;
  204. }
  205. if (b >= 0) {
  206. positives = splitToPatterns(a, b, state, opts);
  207. }
  208. state.negatives = negatives;
  209. state.positives = positives;
  210. state.result = collatePatterns(negatives, positives);
  211. if (opts.capture === true) {
  212. state.result = `(${state.result})`;
  213. } else if (opts.wrap !== false && (positives.length + negatives.length) > 1) {
  214. state.result = `(?:${state.result})`;
  215. }
  216. toRegexRange$1.cache[cacheKey] = state;
  217. return state.result;
  218. };
  219. function collatePatterns(neg, pos, options) {
  220. let onlyNegative = filterPatterns(neg, pos, '-', false) || [];
  221. let onlyPositive = filterPatterns(pos, neg, '', false) || [];
  222. let intersected = filterPatterns(neg, pos, '-?', true) || [];
  223. let subpatterns = onlyNegative.concat(intersected).concat(onlyPositive);
  224. return subpatterns.join('|');
  225. }
  226. function splitToRanges(min, max) {
  227. let nines = 1;
  228. let zeros = 1;
  229. let stop = countNines(min, nines);
  230. let stops = new Set([max]);
  231. while (min <= stop && stop <= max) {
  232. stops.add(stop);
  233. nines += 1;
  234. stop = countNines(min, nines);
  235. }
  236. stop = countZeros(max + 1, zeros) - 1;
  237. while (min < stop && stop <= max) {
  238. stops.add(stop);
  239. zeros += 1;
  240. stop = countZeros(max + 1, zeros) - 1;
  241. }
  242. stops = [...stops];
  243. stops.sort(compare);
  244. return stops;
  245. }
  246. /**
  247. * Convert a range to a regex pattern
  248. * @param {Number} `start`
  249. * @param {Number} `stop`
  250. * @return {String}
  251. */
  252. function rangeToPattern(start, stop, options) {
  253. if (start === stop) {
  254. return { pattern: start, count: [], digits: 0 };
  255. }
  256. let zipped = zip(start, stop);
  257. let digits = zipped.length;
  258. let pattern = '';
  259. let count = 0;
  260. for (let i = 0; i < digits; i++) {
  261. let [startDigit, stopDigit] = zipped[i];
  262. if (startDigit === stopDigit) {
  263. pattern += startDigit;
  264. } else if (startDigit !== '0' || stopDigit !== '9') {
  265. pattern += toCharacterClass(startDigit, stopDigit);
  266. } else {
  267. count++;
  268. }
  269. }
  270. if (count) {
  271. pattern += options.shorthand === true ? '\\d' : '[0-9]';
  272. }
  273. return { pattern, count: [count], digits };
  274. }
  275. function splitToPatterns(min, max, tok, options) {
  276. let ranges = splitToRanges(min, max);
  277. let tokens = [];
  278. let start = min;
  279. let prev;
  280. for (let i = 0; i < ranges.length; i++) {
  281. let max = ranges[i];
  282. let obj = rangeToPattern(String(start), String(max), options);
  283. let zeros = '';
  284. if (!tok.isPadded && prev && prev.pattern === obj.pattern) {
  285. if (prev.count.length > 1) {
  286. prev.count.pop();
  287. }
  288. prev.count.push(obj.count[0]);
  289. prev.string = prev.pattern + toQuantifier(prev.count);
  290. start = max + 1;
  291. continue;
  292. }
  293. if (tok.isPadded) {
  294. zeros = padZeros(max, tok, options);
  295. }
  296. obj.string = zeros + obj.pattern + toQuantifier(obj.count);
  297. tokens.push(obj);
  298. start = max + 1;
  299. prev = obj;
  300. }
  301. return tokens;
  302. }
  303. function filterPatterns(arr, comparison, prefix, intersection, options) {
  304. let result = [];
  305. for (let ele of arr) {
  306. let { string } = ele;
  307. // only push if _both_ are negative...
  308. if (!intersection && !contains(comparison, 'string', string)) {
  309. result.push(prefix + string);
  310. }
  311. // or _both_ are positive
  312. if (intersection && contains(comparison, 'string', string)) {
  313. result.push(prefix + string);
  314. }
  315. }
  316. return result;
  317. }
  318. /**
  319. * Zip strings
  320. */
  321. function zip(a, b) {
  322. let arr = [];
  323. for (let i = 0; i < a.length; i++) arr.push([a[i], b[i]]);
  324. return arr;
  325. }
  326. function compare(a, b) {
  327. return a > b ? 1 : b > a ? -1 : 0;
  328. }
  329. function contains(arr, key, val) {
  330. return arr.some(ele => ele[key] === val);
  331. }
  332. function countNines(min, len) {
  333. return Number(String(min).slice(0, -len) + '9'.repeat(len));
  334. }
  335. function countZeros(integer, zeros) {
  336. return integer - (integer % Math.pow(10, zeros));
  337. }
  338. function toQuantifier(digits) {
  339. let [start = 0, stop = ''] = digits;
  340. if (stop || start > 1) {
  341. return `{${start + (stop ? ',' + stop : '')}}`;
  342. }
  343. return '';
  344. }
  345. function toCharacterClass(a, b, options) {
  346. return `[${a}${(b - a === 1) ? '' : '-'}${b}]`;
  347. }
  348. function hasPadding(str) {
  349. return /^-?(0+)\d/.test(str);
  350. }
  351. function padZeros(value, tok, options) {
  352. if (!tok.isPadded) {
  353. return value;
  354. }
  355. let diff = Math.abs(tok.maxLen - String(value).length);
  356. let relax = options.relaxZeros !== false;
  357. switch (diff) {
  358. case 0:
  359. return '';
  360. case 1:
  361. return relax ? '0?' : '0';
  362. case 2:
  363. return relax ? '0{0,2}' : '00';
  364. default: {
  365. return relax ? `0{0,${diff}}` : `0{${diff}}`;
  366. }
  367. }
  368. }
  369. /**
  370. * Cache
  371. */
  372. toRegexRange$1.cache = {};
  373. toRegexRange$1.clearCache = () => (toRegexRange$1.cache = {});
  374. /**
  375. * Expose `toRegexRange`
  376. */
  377. var toRegexRange_1 = toRegexRange$1;
  378. /*!
  379. * fill-range <https://github.com/jonschlinkert/fill-range>
  380. *
  381. * Copyright (c) 2014-present, Jon Schlinkert.
  382. * Licensed under the MIT License.
  383. */
  384. const util$1 = require$$0$1;
  385. const toRegexRange = toRegexRange_1;
  386. const isObject$1 = val => val !== null && typeof val === 'object' && !Array.isArray(val);
  387. const transform = toNumber => {
  388. return value => toNumber === true ? Number(value) : String(value);
  389. };
  390. const isValidValue = value => {
  391. return typeof value === 'number' || (typeof value === 'string' && value !== '');
  392. };
  393. const isNumber = num => Number.isInteger(+num);
  394. const zeros = input => {
  395. let value = `${input}`;
  396. let index = -1;
  397. if (value[0] === '-') value = value.slice(1);
  398. if (value === '0') return false;
  399. while (value[++index] === '0');
  400. return index > 0;
  401. };
  402. const stringify$3 = (start, end, options) => {
  403. if (typeof start === 'string' || typeof end === 'string') {
  404. return true;
  405. }
  406. return options.stringify === true;
  407. };
  408. const pad = (input, maxLength, toNumber) => {
  409. if (maxLength > 0) {
  410. let dash = input[0] === '-' ? '-' : '';
  411. if (dash) input = input.slice(1);
  412. input = (dash + input.padStart(dash ? maxLength - 1 : maxLength, '0'));
  413. }
  414. if (toNumber === false) {
  415. return String(input);
  416. }
  417. return input;
  418. };
  419. const toMaxLen = (input, maxLength) => {
  420. let negative = input[0] === '-' ? '-' : '';
  421. if (negative) {
  422. input = input.slice(1);
  423. maxLength--;
  424. }
  425. while (input.length < maxLength) input = '0' + input;
  426. return negative ? ('-' + input) : input;
  427. };
  428. const toSequence = (parts, options) => {
  429. parts.negatives.sort((a, b) => a < b ? -1 : a > b ? 1 : 0);
  430. parts.positives.sort((a, b) => a < b ? -1 : a > b ? 1 : 0);
  431. let prefix = options.capture ? '' : '?:';
  432. let positives = '';
  433. let negatives = '';
  434. let result;
  435. if (parts.positives.length) {
  436. positives = parts.positives.join('|');
  437. }
  438. if (parts.negatives.length) {
  439. negatives = `-(${prefix}${parts.negatives.join('|')})`;
  440. }
  441. if (positives && negatives) {
  442. result = `${positives}|${negatives}`;
  443. } else {
  444. result = positives || negatives;
  445. }
  446. if (options.wrap) {
  447. return `(${prefix}${result})`;
  448. }
  449. return result;
  450. };
  451. const toRange = (a, b, isNumbers, options) => {
  452. if (isNumbers) {
  453. return toRegexRange(a, b, { wrap: false, ...options });
  454. }
  455. let start = String.fromCharCode(a);
  456. if (a === b) return start;
  457. let stop = String.fromCharCode(b);
  458. return `[${start}-${stop}]`;
  459. };
  460. const toRegex = (start, end, options) => {
  461. if (Array.isArray(start)) {
  462. let wrap = options.wrap === true;
  463. let prefix = options.capture ? '' : '?:';
  464. return wrap ? `(${prefix}${start.join('|')})` : start.join('|');
  465. }
  466. return toRegexRange(start, end, options);
  467. };
  468. const rangeError = (...args) => {
  469. return new RangeError('Invalid range arguments: ' + util$1.inspect(...args));
  470. };
  471. const invalidRange = (start, end, options) => {
  472. if (options.strictRanges === true) throw rangeError([start, end]);
  473. return [];
  474. };
  475. const invalidStep = (step, options) => {
  476. if (options.strictRanges === true) {
  477. throw new TypeError(`Expected step "${step}" to be a number`);
  478. }
  479. return [];
  480. };
  481. const fillNumbers = (start, end, step = 1, options = {}) => {
  482. let a = Number(start);
  483. let b = Number(end);
  484. if (!Number.isInteger(a) || !Number.isInteger(b)) {
  485. if (options.strictRanges === true) throw rangeError([start, end]);
  486. return [];
  487. }
  488. // fix negative zero
  489. if (a === 0) a = 0;
  490. if (b === 0) b = 0;
  491. let descending = a > b;
  492. let startString = String(start);
  493. let endString = String(end);
  494. let stepString = String(step);
  495. step = Math.max(Math.abs(step), 1);
  496. let padded = zeros(startString) || zeros(endString) || zeros(stepString);
  497. let maxLen = padded ? Math.max(startString.length, endString.length, stepString.length) : 0;
  498. let toNumber = padded === false && stringify$3(start, end, options) === false;
  499. let format = options.transform || transform(toNumber);
  500. if (options.toRegex && step === 1) {
  501. return toRange(toMaxLen(start, maxLen), toMaxLen(end, maxLen), true, options);
  502. }
  503. let parts = { negatives: [], positives: [] };
  504. let push = num => parts[num < 0 ? 'negatives' : 'positives'].push(Math.abs(num));
  505. let range = [];
  506. let index = 0;
  507. while (descending ? a >= b : a <= b) {
  508. if (options.toRegex === true && step > 1) {
  509. push(a);
  510. } else {
  511. range.push(pad(format(a, index), maxLen, toNumber));
  512. }
  513. a = descending ? a - step : a + step;
  514. index++;
  515. }
  516. if (options.toRegex === true) {
  517. return step > 1
  518. ? toSequence(parts, options)
  519. : toRegex(range, null, { wrap: false, ...options });
  520. }
  521. return range;
  522. };
  523. const fillLetters = (start, end, step = 1, options = {}) => {
  524. if ((!isNumber(start) && start.length > 1) || (!isNumber(end) && end.length > 1)) {
  525. return invalidRange(start, end, options);
  526. }
  527. let format = options.transform || (val => String.fromCharCode(val));
  528. let a = `${start}`.charCodeAt(0);
  529. let b = `${end}`.charCodeAt(0);
  530. let descending = a > b;
  531. let min = Math.min(a, b);
  532. let max = Math.max(a, b);
  533. if (options.toRegex && step === 1) {
  534. return toRange(min, max, false, options);
  535. }
  536. let range = [];
  537. let index = 0;
  538. while (descending ? a >= b : a <= b) {
  539. range.push(format(a, index));
  540. a = descending ? a - step : a + step;
  541. index++;
  542. }
  543. if (options.toRegex === true) {
  544. return toRegex(range, null, { wrap: false, options });
  545. }
  546. return range;
  547. };
  548. const fill$2 = (start, end, step, options = {}) => {
  549. if (end == null && isValidValue(start)) {
  550. return [start];
  551. }
  552. if (!isValidValue(start) || !isValidValue(end)) {
  553. return invalidRange(start, end, options);
  554. }
  555. if (typeof step === 'function') {
  556. return fill$2(start, end, 1, { transform: step });
  557. }
  558. if (isObject$1(step)) {
  559. return fill$2(start, end, 0, step);
  560. }
  561. let opts = { ...options };
  562. if (opts.capture === true) opts.wrap = true;
  563. step = step || opts.step || 1;
  564. if (!isNumber(step)) {
  565. if (step != null && !isObject$1(step)) return invalidStep(step, opts);
  566. return fill$2(start, end, 1, step);
  567. }
  568. if (isNumber(start) && isNumber(end)) {
  569. return fillNumbers(start, end, step, opts);
  570. }
  571. return fillLetters(start, end, Math.max(Math.abs(step), 1), opts);
  572. };
  573. var fillRange = fill$2;
  574. const fill$1 = fillRange;
  575. const utils$6 = utils$8;
  576. const compile$1 = (ast, options = {}) => {
  577. let walk = (node, parent = {}) => {
  578. let invalidBlock = utils$6.isInvalidBrace(parent);
  579. let invalidNode = node.invalid === true && options.escapeInvalid === true;
  580. let invalid = invalidBlock === true || invalidNode === true;
  581. let prefix = options.escapeInvalid === true ? '\\' : '';
  582. let output = '';
  583. if (node.isOpen === true) {
  584. return prefix + node.value;
  585. }
  586. if (node.isClose === true) {
  587. return prefix + node.value;
  588. }
  589. if (node.type === 'open') {
  590. return invalid ? (prefix + node.value) : '(';
  591. }
  592. if (node.type === 'close') {
  593. return invalid ? (prefix + node.value) : ')';
  594. }
  595. if (node.type === 'comma') {
  596. return node.prev.type === 'comma' ? '' : (invalid ? node.value : '|');
  597. }
  598. if (node.value) {
  599. return node.value;
  600. }
  601. if (node.nodes && node.ranges > 0) {
  602. let args = utils$6.reduce(node.nodes);
  603. let range = fill$1(...args, { ...options, wrap: false, toRegex: true });
  604. if (range.length !== 0) {
  605. return args.length > 1 && range.length > 1 ? `(${range})` : range;
  606. }
  607. }
  608. if (node.nodes) {
  609. for (let child of node.nodes) {
  610. output += walk(child, node);
  611. }
  612. }
  613. return output;
  614. };
  615. return walk(ast);
  616. };
  617. var compile_1 = compile$1;
  618. const fill = fillRange;
  619. const stringify$2 = stringify$4;
  620. const utils$5 = utils$8;
  621. const append = (queue = '', stash = '', enclose = false) => {
  622. let result = [];
  623. queue = [].concat(queue);
  624. stash = [].concat(stash);
  625. if (!stash.length) return queue;
  626. if (!queue.length) {
  627. return enclose ? utils$5.flatten(stash).map(ele => `{${ele}}`) : stash;
  628. }
  629. for (let item of queue) {
  630. if (Array.isArray(item)) {
  631. for (let value of item) {
  632. result.push(append(value, stash, enclose));
  633. }
  634. } else {
  635. for (let ele of stash) {
  636. if (enclose === true && typeof ele === 'string') ele = `{${ele}}`;
  637. result.push(Array.isArray(ele) ? append(item, ele, enclose) : (item + ele));
  638. }
  639. }
  640. }
  641. return utils$5.flatten(result);
  642. };
  643. const expand$1 = (ast, options = {}) => {
  644. let rangeLimit = options.rangeLimit === void 0 ? 1000 : options.rangeLimit;
  645. let walk = (node, parent = {}) => {
  646. node.queue = [];
  647. let p = parent;
  648. let q = parent.queue;
  649. while (p.type !== 'brace' && p.type !== 'root' && p.parent) {
  650. p = p.parent;
  651. q = p.queue;
  652. }
  653. if (node.invalid || node.dollar) {
  654. q.push(append(q.pop(), stringify$2(node, options)));
  655. return;
  656. }
  657. if (node.type === 'brace' && node.invalid !== true && node.nodes.length === 2) {
  658. q.push(append(q.pop(), ['{}']));
  659. return;
  660. }
  661. if (node.nodes && node.ranges > 0) {
  662. let args = utils$5.reduce(node.nodes);
  663. if (utils$5.exceedsLimit(...args, options.step, rangeLimit)) {
  664. throw new RangeError('expanded array length exceeds range limit. Use options.rangeLimit to increase or disable the limit.');
  665. }
  666. let range = fill(...args, options);
  667. if (range.length === 0) {
  668. range = stringify$2(node, options);
  669. }
  670. q.push(append(q.pop(), range));
  671. node.nodes = [];
  672. return;
  673. }
  674. let enclose = utils$5.encloseBrace(node);
  675. let queue = node.queue;
  676. let block = node;
  677. while (block.type !== 'brace' && block.type !== 'root' && block.parent) {
  678. block = block.parent;
  679. queue = block.queue;
  680. }
  681. for (let i = 0; i < node.nodes.length; i++) {
  682. let child = node.nodes[i];
  683. if (child.type === 'comma' && node.type === 'brace') {
  684. if (i === 1) queue.push('');
  685. queue.push('');
  686. continue;
  687. }
  688. if (child.type === 'close') {
  689. q.push(append(q.pop(), queue, enclose));
  690. continue;
  691. }
  692. if (child.value && child.type !== 'open') {
  693. queue.push(append(queue.pop(), child.value));
  694. continue;
  695. }
  696. if (child.nodes) {
  697. walk(child, node);
  698. }
  699. }
  700. return queue;
  701. };
  702. return utils$5.flatten(walk(ast));
  703. };
  704. var expand_1 = expand$1;
  705. var constants$4 = {
  706. MAX_LENGTH: 1024 * 64,
  707. // Digits
  708. CHAR_0: '0', /* 0 */
  709. CHAR_9: '9', /* 9 */
  710. // Alphabet chars.
  711. CHAR_UPPERCASE_A: 'A', /* A */
  712. CHAR_LOWERCASE_A: 'a', /* a */
  713. CHAR_UPPERCASE_Z: 'Z', /* Z */
  714. CHAR_LOWERCASE_Z: 'z', /* z */
  715. CHAR_LEFT_PARENTHESES: '(', /* ( */
  716. CHAR_RIGHT_PARENTHESES: ')', /* ) */
  717. CHAR_ASTERISK: '*', /* * */
  718. // Non-alphabetic chars.
  719. CHAR_AMPERSAND: '&', /* & */
  720. CHAR_AT: '@', /* @ */
  721. CHAR_BACKSLASH: '\\', /* \ */
  722. CHAR_BACKTICK: '`', /* ` */
  723. CHAR_CARRIAGE_RETURN: '\r', /* \r */
  724. CHAR_CIRCUMFLEX_ACCENT: '^', /* ^ */
  725. CHAR_COLON: ':', /* : */
  726. CHAR_COMMA: ',', /* , */
  727. CHAR_DOLLAR: '$', /* . */
  728. CHAR_DOT: '.', /* . */
  729. CHAR_DOUBLE_QUOTE: '"', /* " */
  730. CHAR_EQUAL: '=', /* = */
  731. CHAR_EXCLAMATION_MARK: '!', /* ! */
  732. CHAR_FORM_FEED: '\f', /* \f */
  733. CHAR_FORWARD_SLASH: '/', /* / */
  734. CHAR_HASH: '#', /* # */
  735. CHAR_HYPHEN_MINUS: '-', /* - */
  736. CHAR_LEFT_ANGLE_BRACKET: '<', /* < */
  737. CHAR_LEFT_CURLY_BRACE: '{', /* { */
  738. CHAR_LEFT_SQUARE_BRACKET: '[', /* [ */
  739. CHAR_LINE_FEED: '\n', /* \n */
  740. CHAR_NO_BREAK_SPACE: '\u00A0', /* \u00A0 */
  741. CHAR_PERCENT: '%', /* % */
  742. CHAR_PLUS: '+', /* + */
  743. CHAR_QUESTION_MARK: '?', /* ? */
  744. CHAR_RIGHT_ANGLE_BRACKET: '>', /* > */
  745. CHAR_RIGHT_CURLY_BRACE: '}', /* } */
  746. CHAR_RIGHT_SQUARE_BRACKET: ']', /* ] */
  747. CHAR_SEMICOLON: ';', /* ; */
  748. CHAR_SINGLE_QUOTE: '\'', /* ' */
  749. CHAR_SPACE: ' ', /* */
  750. CHAR_TAB: '\t', /* \t */
  751. CHAR_UNDERSCORE: '_', /* _ */
  752. CHAR_VERTICAL_LINE: '|', /* | */
  753. CHAR_ZERO_WIDTH_NOBREAK_SPACE: '\uFEFF' /* \uFEFF */
  754. };
  755. const stringify$1 = stringify$4;
  756. /**
  757. * Constants
  758. */
  759. const {
  760. MAX_LENGTH: MAX_LENGTH$1,
  761. CHAR_BACKSLASH, /* \ */
  762. CHAR_BACKTICK, /* ` */
  763. CHAR_COMMA: CHAR_COMMA$1, /* , */
  764. CHAR_DOT: CHAR_DOT$1, /* . */
  765. CHAR_LEFT_PARENTHESES: CHAR_LEFT_PARENTHESES$1, /* ( */
  766. CHAR_RIGHT_PARENTHESES: CHAR_RIGHT_PARENTHESES$1, /* ) */
  767. CHAR_LEFT_CURLY_BRACE: CHAR_LEFT_CURLY_BRACE$1, /* { */
  768. CHAR_RIGHT_CURLY_BRACE: CHAR_RIGHT_CURLY_BRACE$1, /* } */
  769. CHAR_LEFT_SQUARE_BRACKET: CHAR_LEFT_SQUARE_BRACKET$1, /* [ */
  770. CHAR_RIGHT_SQUARE_BRACKET: CHAR_RIGHT_SQUARE_BRACKET$1, /* ] */
  771. CHAR_DOUBLE_QUOTE, /* " */
  772. CHAR_SINGLE_QUOTE, /* ' */
  773. CHAR_NO_BREAK_SPACE,
  774. CHAR_ZERO_WIDTH_NOBREAK_SPACE
  775. } = constants$4;
  776. /**
  777. * parse
  778. */
  779. const parse$3 = (input, options = {}) => {
  780. if (typeof input !== 'string') {
  781. throw new TypeError('Expected a string');
  782. }
  783. let opts = options || {};
  784. let max = typeof opts.maxLength === 'number' ? Math.min(MAX_LENGTH$1, opts.maxLength) : MAX_LENGTH$1;
  785. if (input.length > max) {
  786. throw new SyntaxError(`Input length (${input.length}), exceeds max characters (${max})`);
  787. }
  788. let ast = { type: 'root', input, nodes: [] };
  789. let stack = [ast];
  790. let block = ast;
  791. let prev = ast;
  792. let brackets = 0;
  793. let length = input.length;
  794. let index = 0;
  795. let depth = 0;
  796. let value;
  797. /**
  798. * Helpers
  799. */
  800. const advance = () => input[index++];
  801. const push = node => {
  802. if (node.type === 'text' && prev.type === 'dot') {
  803. prev.type = 'text';
  804. }
  805. if (prev && prev.type === 'text' && node.type === 'text') {
  806. prev.value += node.value;
  807. return;
  808. }
  809. block.nodes.push(node);
  810. node.parent = block;
  811. node.prev = prev;
  812. prev = node;
  813. return node;
  814. };
  815. push({ type: 'bos' });
  816. while (index < length) {
  817. block = stack[stack.length - 1];
  818. value = advance();
  819. /**
  820. * Invalid chars
  821. */
  822. if (value === CHAR_ZERO_WIDTH_NOBREAK_SPACE || value === CHAR_NO_BREAK_SPACE) {
  823. continue;
  824. }
  825. /**
  826. * Escaped chars
  827. */
  828. if (value === CHAR_BACKSLASH) {
  829. push({ type: 'text', value: (options.keepEscaping ? value : '') + advance() });
  830. continue;
  831. }
  832. /**
  833. * Right square bracket (literal): ']'
  834. */
  835. if (value === CHAR_RIGHT_SQUARE_BRACKET$1) {
  836. push({ type: 'text', value: '\\' + value });
  837. continue;
  838. }
  839. /**
  840. * Left square bracket: '['
  841. */
  842. if (value === CHAR_LEFT_SQUARE_BRACKET$1) {
  843. brackets++;
  844. let next;
  845. while (index < length && (next = advance())) {
  846. value += next;
  847. if (next === CHAR_LEFT_SQUARE_BRACKET$1) {
  848. brackets++;
  849. continue;
  850. }
  851. if (next === CHAR_BACKSLASH) {
  852. value += advance();
  853. continue;
  854. }
  855. if (next === CHAR_RIGHT_SQUARE_BRACKET$1) {
  856. brackets--;
  857. if (brackets === 0) {
  858. break;
  859. }
  860. }
  861. }
  862. push({ type: 'text', value });
  863. continue;
  864. }
  865. /**
  866. * Parentheses
  867. */
  868. if (value === CHAR_LEFT_PARENTHESES$1) {
  869. block = push({ type: 'paren', nodes: [] });
  870. stack.push(block);
  871. push({ type: 'text', value });
  872. continue;
  873. }
  874. if (value === CHAR_RIGHT_PARENTHESES$1) {
  875. if (block.type !== 'paren') {
  876. push({ type: 'text', value });
  877. continue;
  878. }
  879. block = stack.pop();
  880. push({ type: 'text', value });
  881. block = stack[stack.length - 1];
  882. continue;
  883. }
  884. /**
  885. * Quotes: '|"|`
  886. */
  887. if (value === CHAR_DOUBLE_QUOTE || value === CHAR_SINGLE_QUOTE || value === CHAR_BACKTICK) {
  888. let open = value;
  889. let next;
  890. if (options.keepQuotes !== true) {
  891. value = '';
  892. }
  893. while (index < length && (next = advance())) {
  894. if (next === CHAR_BACKSLASH) {
  895. value += next + advance();
  896. continue;
  897. }
  898. if (next === open) {
  899. if (options.keepQuotes === true) value += next;
  900. break;
  901. }
  902. value += next;
  903. }
  904. push({ type: 'text', value });
  905. continue;
  906. }
  907. /**
  908. * Left curly brace: '{'
  909. */
  910. if (value === CHAR_LEFT_CURLY_BRACE$1) {
  911. depth++;
  912. let dollar = prev.value && prev.value.slice(-1) === '$' || block.dollar === true;
  913. let brace = {
  914. type: 'brace',
  915. open: true,
  916. close: false,
  917. dollar,
  918. depth,
  919. commas: 0,
  920. ranges: 0,
  921. nodes: []
  922. };
  923. block = push(brace);
  924. stack.push(block);
  925. push({ type: 'open', value });
  926. continue;
  927. }
  928. /**
  929. * Right curly brace: '}'
  930. */
  931. if (value === CHAR_RIGHT_CURLY_BRACE$1) {
  932. if (block.type !== 'brace') {
  933. push({ type: 'text', value });
  934. continue;
  935. }
  936. let type = 'close';
  937. block = stack.pop();
  938. block.close = true;
  939. push({ type, value });
  940. depth--;
  941. block = stack[stack.length - 1];
  942. continue;
  943. }
  944. /**
  945. * Comma: ','
  946. */
  947. if (value === CHAR_COMMA$1 && depth > 0) {
  948. if (block.ranges > 0) {
  949. block.ranges = 0;
  950. let open = block.nodes.shift();
  951. block.nodes = [open, { type: 'text', value: stringify$1(block) }];
  952. }
  953. push({ type: 'comma', value });
  954. block.commas++;
  955. continue;
  956. }
  957. /**
  958. * Dot: '.'
  959. */
  960. if (value === CHAR_DOT$1 && depth > 0 && block.commas === 0) {
  961. let siblings = block.nodes;
  962. if (depth === 0 || siblings.length === 0) {
  963. push({ type: 'text', value });
  964. continue;
  965. }
  966. if (prev.type === 'dot') {
  967. block.range = [];
  968. prev.value += value;
  969. prev.type = 'range';
  970. if (block.nodes.length !== 3 && block.nodes.length !== 5) {
  971. block.invalid = true;
  972. block.ranges = 0;
  973. prev.type = 'text';
  974. continue;
  975. }
  976. block.ranges++;
  977. block.args = [];
  978. continue;
  979. }
  980. if (prev.type === 'range') {
  981. siblings.pop();
  982. let before = siblings[siblings.length - 1];
  983. before.value += prev.value + value;
  984. prev = before;
  985. block.ranges--;
  986. continue;
  987. }
  988. push({ type: 'dot', value });
  989. continue;
  990. }
  991. /**
  992. * Text
  993. */
  994. push({ type: 'text', value });
  995. }
  996. // Mark imbalanced braces and brackets as invalid
  997. do {
  998. block = stack.pop();
  999. if (block.type !== 'root') {
  1000. block.nodes.forEach(node => {
  1001. if (!node.nodes) {
  1002. if (node.type === 'open') node.isOpen = true;
  1003. if (node.type === 'close') node.isClose = true;
  1004. if (!node.nodes) node.type = 'text';
  1005. node.invalid = true;
  1006. }
  1007. });
  1008. // get the location of the block on parent.nodes (block's siblings)
  1009. let parent = stack[stack.length - 1];
  1010. let index = parent.nodes.indexOf(block);
  1011. // replace the (invalid) block with it's nodes
  1012. parent.nodes.splice(index, 1, ...block.nodes);
  1013. }
  1014. } while (stack.length > 0);
  1015. push({ type: 'eos' });
  1016. return ast;
  1017. };
  1018. var parse_1$1 = parse$3;
  1019. const stringify = stringify$4;
  1020. const compile = compile_1;
  1021. const expand = expand_1;
  1022. const parse$2 = parse_1$1;
  1023. /**
  1024. * Expand the given pattern or create a regex-compatible string.
  1025. *
  1026. * ```js
  1027. * const braces = require('braces');
  1028. * console.log(braces('{a,b,c}', { compile: true })); //=> ['(a|b|c)']
  1029. * console.log(braces('{a,b,c}')); //=> ['a', 'b', 'c']
  1030. * ```
  1031. * @param {String} `str`
  1032. * @param {Object} `options`
  1033. * @return {String}
  1034. * @api public
  1035. */
  1036. const braces$2 = (input, options = {}) => {
  1037. let output = [];
  1038. if (Array.isArray(input)) {
  1039. for (let pattern of input) {
  1040. let result = braces$2.create(pattern, options);
  1041. if (Array.isArray(result)) {
  1042. output.push(...result);
  1043. } else {
  1044. output.push(result);
  1045. }
  1046. }
  1047. } else {
  1048. output = [].concat(braces$2.create(input, options));
  1049. }
  1050. if (options && options.expand === true && options.nodupes === true) {
  1051. output = [...new Set(output)];
  1052. }
  1053. return output;
  1054. };
  1055. /**
  1056. * Parse the given `str` with the given `options`.
  1057. *
  1058. * ```js
  1059. * // braces.parse(pattern, [, options]);
  1060. * const ast = braces.parse('a/{b,c}/d');
  1061. * console.log(ast);
  1062. * ```
  1063. * @param {String} pattern Brace pattern to parse
  1064. * @param {Object} options
  1065. * @return {Object} Returns an AST
  1066. * @api public
  1067. */
  1068. braces$2.parse = (input, options = {}) => parse$2(input, options);
  1069. /**
  1070. * Creates a braces string from an AST, or an AST node.
  1071. *
  1072. * ```js
  1073. * const braces = require('braces');
  1074. * let ast = braces.parse('foo/{a,b}/bar');
  1075. * console.log(stringify(ast.nodes[2])); //=> '{a,b}'
  1076. * ```
  1077. * @param {String} `input` Brace pattern or AST.
  1078. * @param {Object} `options`
  1079. * @return {Array} Returns an array of expanded values.
  1080. * @api public
  1081. */
  1082. braces$2.stringify = (input, options = {}) => {
  1083. if (typeof input === 'string') {
  1084. return stringify(braces$2.parse(input, options), options);
  1085. }
  1086. return stringify(input, options);
  1087. };
  1088. /**
  1089. * Compiles a brace pattern into a regex-compatible, optimized string.
  1090. * This method is called by the main [braces](#braces) function by default.
  1091. *
  1092. * ```js
  1093. * const braces = require('braces');
  1094. * console.log(braces.compile('a/{b,c}/d'));
  1095. * //=> ['a/(b|c)/d']
  1096. * ```
  1097. * @param {String} `input` Brace pattern or AST.
  1098. * @param {Object} `options`
  1099. * @return {Array} Returns an array of expanded values.
  1100. * @api public
  1101. */
  1102. braces$2.compile = (input, options = {}) => {
  1103. if (typeof input === 'string') {
  1104. input = braces$2.parse(input, options);
  1105. }
  1106. return compile(input, options);
  1107. };
  1108. /**
  1109. * Expands a brace pattern into an array. This method is called by the
  1110. * main [braces](#braces) function when `options.expand` is true. Before
  1111. * using this method it's recommended that you read the [performance notes](#performance))
  1112. * and advantages of using [.compile](#compile) instead.
  1113. *
  1114. * ```js
  1115. * const braces = require('braces');
  1116. * console.log(braces.expand('a/{b,c}/d'));
  1117. * //=> ['a/b/d', 'a/c/d'];
  1118. * ```
  1119. * @param {String} `pattern` Brace pattern
  1120. * @param {Object} `options`
  1121. * @return {Array} Returns an array of expanded values.
  1122. * @api public
  1123. */
  1124. braces$2.expand = (input, options = {}) => {
  1125. if (typeof input === 'string') {
  1126. input = braces$2.parse(input, options);
  1127. }
  1128. let result = expand(input, options);
  1129. // filter out empty strings if specified
  1130. if (options.noempty === true) {
  1131. result = result.filter(Boolean);
  1132. }
  1133. // filter out duplicates if specified
  1134. if (options.nodupes === true) {
  1135. result = [...new Set(result)];
  1136. }
  1137. return result;
  1138. };
  1139. /**
  1140. * Processes a brace pattern and returns either an expanded array
  1141. * (if `options.expand` is true), a highly optimized regex-compatible string.
  1142. * This method is called by the main [braces](#braces) function.
  1143. *
  1144. * ```js
  1145. * const braces = require('braces');
  1146. * console.log(braces.create('user-{200..300}/project-{a,b,c}-{1..10}'))
  1147. * //=> 'user-(20[0-9]|2[1-9][0-9]|300)/project-(a|b|c)-([1-9]|10)'
  1148. * ```
  1149. * @param {String} `pattern` Brace pattern
  1150. * @param {Object} `options`
  1151. * @return {Array} Returns an array of expanded values.
  1152. * @api public
  1153. */
  1154. braces$2.create = (input, options = {}) => {
  1155. if (input === '' || input.length < 3) {
  1156. return [input];
  1157. }
  1158. return options.expand !== true
  1159. ? braces$2.compile(input, options)
  1160. : braces$2.expand(input, options);
  1161. };
  1162. /**
  1163. * Expose "braces"
  1164. */
  1165. var braces_1 = braces$2;
  1166. var utils$4 = {};
  1167. const path$2 = require$$0$2;
  1168. const WIN_SLASH = '\\\\/';
  1169. const WIN_NO_SLASH = `[^${WIN_SLASH}]`;
  1170. /**
  1171. * Posix glob regex
  1172. */
  1173. const DOT_LITERAL = '\\.';
  1174. const PLUS_LITERAL = '\\+';
  1175. const QMARK_LITERAL = '\\?';
  1176. const SLASH_LITERAL = '\\/';
  1177. const ONE_CHAR = '(?=.)';
  1178. const QMARK = '[^/]';
  1179. const END_ANCHOR = `(?:${SLASH_LITERAL}|$)`;
  1180. const START_ANCHOR = `(?:^|${SLASH_LITERAL})`;
  1181. const DOTS_SLASH = `${DOT_LITERAL}{1,2}${END_ANCHOR}`;
  1182. const NO_DOT = `(?!${DOT_LITERAL})`;
  1183. const NO_DOTS = `(?!${START_ANCHOR}${DOTS_SLASH})`;
  1184. const NO_DOT_SLASH = `(?!${DOT_LITERAL}{0,1}${END_ANCHOR})`;
  1185. const NO_DOTS_SLASH = `(?!${DOTS_SLASH})`;
  1186. const QMARK_NO_DOT = `[^.${SLASH_LITERAL}]`;
  1187. const STAR$1 = `${QMARK}*?`;
  1188. const POSIX_CHARS = {
  1189. DOT_LITERAL,
  1190. PLUS_LITERAL,
  1191. QMARK_LITERAL,
  1192. SLASH_LITERAL,
  1193. ONE_CHAR,
  1194. QMARK,
  1195. END_ANCHOR,
  1196. DOTS_SLASH,
  1197. NO_DOT,
  1198. NO_DOTS,
  1199. NO_DOT_SLASH,
  1200. NO_DOTS_SLASH,
  1201. QMARK_NO_DOT,
  1202. STAR: STAR$1,
  1203. START_ANCHOR
  1204. };
  1205. /**
  1206. * Windows glob regex
  1207. */
  1208. const WINDOWS_CHARS = {
  1209. ...POSIX_CHARS,
  1210. SLASH_LITERAL: `[${WIN_SLASH}]`,
  1211. QMARK: WIN_NO_SLASH,
  1212. STAR: `${WIN_NO_SLASH}*?`,
  1213. DOTS_SLASH: `${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$)`,
  1214. NO_DOT: `(?!${DOT_LITERAL})`,
  1215. NO_DOTS: `(?!(?:^|[${WIN_SLASH}])${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$))`,
  1216. NO_DOT_SLASH: `(?!${DOT_LITERAL}{0,1}(?:[${WIN_SLASH}]|$))`,
  1217. NO_DOTS_SLASH: `(?!${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$))`,
  1218. QMARK_NO_DOT: `[^.${WIN_SLASH}]`,
  1219. START_ANCHOR: `(?:^|[${WIN_SLASH}])`,
  1220. END_ANCHOR: `(?:[${WIN_SLASH}]|$)`
  1221. };
  1222. /**
  1223. * POSIX Bracket Regex
  1224. */
  1225. const POSIX_REGEX_SOURCE$1 = {
  1226. alnum: 'a-zA-Z0-9',
  1227. alpha: 'a-zA-Z',
  1228. ascii: '\\x00-\\x7F',
  1229. blank: ' \\t',
  1230. cntrl: '\\x00-\\x1F\\x7F',
  1231. digit: '0-9',
  1232. graph: '\\x21-\\x7E',
  1233. lower: 'a-z',
  1234. print: '\\x20-\\x7E ',
  1235. punct: '\\-!"#$%&\'()\\*+,./:;<=>?@[\\]^_`{|}~',
  1236. space: ' \\t\\r\\n\\v\\f',
  1237. upper: 'A-Z',
  1238. word: 'A-Za-z0-9_',
  1239. xdigit: 'A-Fa-f0-9'
  1240. };
  1241. var constants$3 = {
  1242. MAX_LENGTH: 1024 * 64,
  1243. POSIX_REGEX_SOURCE: POSIX_REGEX_SOURCE$1,
  1244. // regular expressions
  1245. REGEX_BACKSLASH: /\\(?![*+?^${}(|)[\]])/g,
  1246. REGEX_NON_SPECIAL_CHARS: /^[^@![\].,$*+?^{}()|\\/]+/,
  1247. REGEX_SPECIAL_CHARS: /[-*+?.^${}(|)[\]]/,
  1248. REGEX_SPECIAL_CHARS_BACKREF: /(\\?)((\W)(\3*))/g,
  1249. REGEX_SPECIAL_CHARS_GLOBAL: /([-*+?.^${}(|)[\]])/g,
  1250. REGEX_REMOVE_BACKSLASH: /(?:\[.*?[^\\]\]|\\(?=.))/g,
  1251. // Replace globs with equivalent patterns to reduce parsing time.
  1252. REPLACEMENTS: {
  1253. '***': '*',
  1254. '**/**': '**',
  1255. '**/**/**': '**'
  1256. },
  1257. // Digits
  1258. CHAR_0: 48, /* 0 */
  1259. CHAR_9: 57, /* 9 */
  1260. // Alphabet chars.
  1261. CHAR_UPPERCASE_A: 65, /* A */
  1262. CHAR_LOWERCASE_A: 97, /* a */
  1263. CHAR_UPPERCASE_Z: 90, /* Z */
  1264. CHAR_LOWERCASE_Z: 122, /* z */
  1265. CHAR_LEFT_PARENTHESES: 40, /* ( */
  1266. CHAR_RIGHT_PARENTHESES: 41, /* ) */
  1267. CHAR_ASTERISK: 42, /* * */
  1268. // Non-alphabetic chars.
  1269. CHAR_AMPERSAND: 38, /* & */
  1270. CHAR_AT: 64, /* @ */
  1271. CHAR_BACKWARD_SLASH: 92, /* \ */
  1272. CHAR_CARRIAGE_RETURN: 13, /* \r */
  1273. CHAR_CIRCUMFLEX_ACCENT: 94, /* ^ */
  1274. CHAR_COLON: 58, /* : */
  1275. CHAR_COMMA: 44, /* , */
  1276. CHAR_DOT: 46, /* . */
  1277. CHAR_DOUBLE_QUOTE: 34, /* " */
  1278. CHAR_EQUAL: 61, /* = */
  1279. CHAR_EXCLAMATION_MARK: 33, /* ! */
  1280. CHAR_FORM_FEED: 12, /* \f */
  1281. CHAR_FORWARD_SLASH: 47, /* / */
  1282. CHAR_GRAVE_ACCENT: 96, /* ` */
  1283. CHAR_HASH: 35, /* # */
  1284. CHAR_HYPHEN_MINUS: 45, /* - */
  1285. CHAR_LEFT_ANGLE_BRACKET: 60, /* < */
  1286. CHAR_LEFT_CURLY_BRACE: 123, /* { */
  1287. CHAR_LEFT_SQUARE_BRACKET: 91, /* [ */
  1288. CHAR_LINE_FEED: 10, /* \n */
  1289. CHAR_NO_BREAK_SPACE: 160, /* \u00A0 */
  1290. CHAR_PERCENT: 37, /* % */
  1291. CHAR_PLUS: 43, /* + */
  1292. CHAR_QUESTION_MARK: 63, /* ? */
  1293. CHAR_RIGHT_ANGLE_BRACKET: 62, /* > */
  1294. CHAR_RIGHT_CURLY_BRACE: 125, /* } */
  1295. CHAR_RIGHT_SQUARE_BRACKET: 93, /* ] */
  1296. CHAR_SEMICOLON: 59, /* ; */
  1297. CHAR_SINGLE_QUOTE: 39, /* ' */
  1298. CHAR_SPACE: 32, /* */
  1299. CHAR_TAB: 9, /* \t */
  1300. CHAR_UNDERSCORE: 95, /* _ */
  1301. CHAR_VERTICAL_LINE: 124, /* | */
  1302. CHAR_ZERO_WIDTH_NOBREAK_SPACE: 65279, /* \uFEFF */
  1303. SEP: path$2.sep,
  1304. /**
  1305. * Create EXTGLOB_CHARS
  1306. */
  1307. extglobChars(chars) {
  1308. return {
  1309. '!': { type: 'negate', open: '(?:(?!(?:', close: `))${chars.STAR})` },
  1310. '?': { type: 'qmark', open: '(?:', close: ')?' },
  1311. '+': { type: 'plus', open: '(?:', close: ')+' },
  1312. '*': { type: 'star', open: '(?:', close: ')*' },
  1313. '@': { type: 'at', open: '(?:', close: ')' }
  1314. };
  1315. },
  1316. /**
  1317. * Create GLOB_CHARS
  1318. */
  1319. globChars(win32) {
  1320. return win32 === true ? WINDOWS_CHARS : POSIX_CHARS;
  1321. }
  1322. };
  1323. (function (exports) {
  1324. const path = require$$0$2;
  1325. const win32 = process.platform === 'win32';
  1326. const {
  1327. REGEX_BACKSLASH,
  1328. REGEX_REMOVE_BACKSLASH,
  1329. REGEX_SPECIAL_CHARS,
  1330. REGEX_SPECIAL_CHARS_GLOBAL
  1331. } = constants$3;
  1332. exports.isObject = val => val !== null && typeof val === 'object' && !Array.isArray(val);
  1333. exports.hasRegexChars = str => REGEX_SPECIAL_CHARS.test(str);
  1334. exports.isRegexChar = str => str.length === 1 && exports.hasRegexChars(str);
  1335. exports.escapeRegex = str => str.replace(REGEX_SPECIAL_CHARS_GLOBAL, '\\$1');
  1336. exports.toPosixSlashes = str => str.replace(REGEX_BACKSLASH, '/');
  1337. exports.removeBackslashes = str => {
  1338. return str.replace(REGEX_REMOVE_BACKSLASH, match => {
  1339. return match === '\\' ? '' : match;
  1340. });
  1341. };
  1342. exports.supportsLookbehinds = () => {
  1343. const segs = process.version.slice(1).split('.').map(Number);
  1344. if (segs.length === 3 && segs[0] >= 9 || (segs[0] === 8 && segs[1] >= 10)) {
  1345. return true;
  1346. }
  1347. return false;
  1348. };
  1349. exports.isWindows = options => {
  1350. if (options && typeof options.windows === 'boolean') {
  1351. return options.windows;
  1352. }
  1353. return win32 === true || path.sep === '\\';
  1354. };
  1355. exports.escapeLast = (input, char, lastIdx) => {
  1356. const idx = input.lastIndexOf(char, lastIdx);
  1357. if (idx === -1) return input;
  1358. if (input[idx - 1] === '\\') return exports.escapeLast(input, char, idx - 1);
  1359. return `${input.slice(0, idx)}\\${input.slice(idx)}`;
  1360. };
  1361. exports.removePrefix = (input, state = {}) => {
  1362. let output = input;
  1363. if (output.startsWith('./')) {
  1364. output = output.slice(2);
  1365. state.prefix = './';
  1366. }
  1367. return output;
  1368. };
  1369. exports.wrapOutput = (input, state = {}, options = {}) => {
  1370. const prepend = options.contains ? '' : '^';
  1371. const append = options.contains ? '' : '$';
  1372. let output = `${prepend}(?:${input})${append}`;
  1373. if (state.negated === true) {
  1374. output = `(?:^(?!${output}).*$)`;
  1375. }
  1376. return output;
  1377. };
  1378. }(utils$4));
  1379. const utils$3 = utils$4;
  1380. const {
  1381. CHAR_ASTERISK, /* * */
  1382. CHAR_AT, /* @ */
  1383. CHAR_BACKWARD_SLASH, /* \ */
  1384. CHAR_COMMA, /* , */
  1385. CHAR_DOT, /* . */
  1386. CHAR_EXCLAMATION_MARK, /* ! */
  1387. CHAR_FORWARD_SLASH, /* / */
  1388. CHAR_LEFT_CURLY_BRACE, /* { */
  1389. CHAR_LEFT_PARENTHESES, /* ( */
  1390. CHAR_LEFT_SQUARE_BRACKET, /* [ */
  1391. CHAR_PLUS, /* + */
  1392. CHAR_QUESTION_MARK, /* ? */
  1393. CHAR_RIGHT_CURLY_BRACE, /* } */
  1394. CHAR_RIGHT_PARENTHESES, /* ) */
  1395. CHAR_RIGHT_SQUARE_BRACKET /* ] */
  1396. } = constants$3;
  1397. const isPathSeparator = code => {
  1398. return code === CHAR_FORWARD_SLASH || code === CHAR_BACKWARD_SLASH;
  1399. };
  1400. const depth = token => {
  1401. if (token.isPrefix !== true) {
  1402. token.depth = token.isGlobstar ? Infinity : 1;
  1403. }
  1404. };
  1405. /**
  1406. * Quickly scans a glob pattern and returns an object with a handful of
  1407. * useful properties, like `isGlob`, `path` (the leading non-glob, if it exists),
  1408. * `glob` (the actual pattern), and `negated` (true if the path starts with `!`).
  1409. *
  1410. * ```js
  1411. * const pm = require('picomatch');
  1412. * console.log(pm.scan('foo/bar/*.js'));
  1413. * { isGlob: true, input: 'foo/bar/*.js', base: 'foo/bar', glob: '*.js' }
  1414. * ```
  1415. * @param {String} `str`
  1416. * @param {Object} `options`
  1417. * @return {Object} Returns an object with tokens and regex source string.
  1418. * @api public
  1419. */
  1420. const scan$1 = (input, options) => {
  1421. const opts = options || {};
  1422. const length = input.length - 1;
  1423. const scanToEnd = opts.parts === true || opts.scanToEnd === true;
  1424. const slashes = [];
  1425. const tokens = [];
  1426. const parts = [];
  1427. let str = input;
  1428. let index = -1;
  1429. let start = 0;
  1430. let lastIndex = 0;
  1431. let isBrace = false;
  1432. let isBracket = false;
  1433. let isGlob = false;
  1434. let isExtglob = false;
  1435. let isGlobstar = false;
  1436. let braceEscaped = false;
  1437. let backslashes = false;
  1438. let negated = false;
  1439. let finished = false;
  1440. let braces = 0;
  1441. let prev;
  1442. let code;
  1443. let token = { value: '', depth: 0, isGlob: false };
  1444. const eos = () => index >= length;
  1445. const peek = () => str.charCodeAt(index + 1);
  1446. const advance = () => {
  1447. prev = code;
  1448. return str.charCodeAt(++index);
  1449. };
  1450. while (index < length) {
  1451. code = advance();
  1452. let next;
  1453. if (code === CHAR_BACKWARD_SLASH) {
  1454. backslashes = token.backslashes = true;
  1455. code = advance();
  1456. if (code === CHAR_LEFT_CURLY_BRACE) {
  1457. braceEscaped = true;
  1458. }
  1459. continue;
  1460. }
  1461. if (braceEscaped === true || code === CHAR_LEFT_CURLY_BRACE) {
  1462. braces++;
  1463. while (eos() !== true && (code = advance())) {
  1464. if (code === CHAR_BACKWARD_SLASH) {
  1465. backslashes = token.backslashes = true;
  1466. advance();
  1467. continue;
  1468. }
  1469. if (code === CHAR_LEFT_CURLY_BRACE) {
  1470. braces++;
  1471. continue;
  1472. }
  1473. if (braceEscaped !== true && code === CHAR_DOT && (code = advance()) === CHAR_DOT) {
  1474. isBrace = token.isBrace = true;
  1475. isGlob = token.isGlob = true;
  1476. finished = true;
  1477. if (scanToEnd === true) {
  1478. continue;
  1479. }
  1480. break;
  1481. }
  1482. if (braceEscaped !== true && code === CHAR_COMMA) {
  1483. isBrace = token.isBrace = true;
  1484. isGlob = token.isGlob = true;
  1485. finished = true;
  1486. if (scanToEnd === true) {
  1487. continue;
  1488. }
  1489. break;
  1490. }
  1491. if (code === CHAR_RIGHT_CURLY_BRACE) {
  1492. braces--;
  1493. if (braces === 0) {
  1494. braceEscaped = false;
  1495. isBrace = token.isBrace = true;
  1496. finished = true;
  1497. break;
  1498. }
  1499. }
  1500. }
  1501. if (scanToEnd === true) {
  1502. continue;
  1503. }
  1504. break;
  1505. }
  1506. if (code === CHAR_FORWARD_SLASH) {
  1507. slashes.push(index);
  1508. tokens.push(token);
  1509. token = { value: '', depth: 0, isGlob: false };
  1510. if (finished === true) continue;
  1511. if (prev === CHAR_DOT && index === (start + 1)) {
  1512. start += 2;
  1513. continue;
  1514. }
  1515. lastIndex = index + 1;
  1516. continue;
  1517. }
  1518. if (opts.noext !== true) {
  1519. const isExtglobChar = code === CHAR_PLUS
  1520. || code === CHAR_AT
  1521. || code === CHAR_ASTERISK
  1522. || code === CHAR_QUESTION_MARK
  1523. || code === CHAR_EXCLAMATION_MARK;
  1524. if (isExtglobChar === true && peek() === CHAR_LEFT_PARENTHESES) {
  1525. isGlob = token.isGlob = true;
  1526. isExtglob = token.isExtglob = true;
  1527. finished = true;
  1528. if (scanToEnd === true) {
  1529. while (eos() !== true && (code = advance())) {
  1530. if (code === CHAR_BACKWARD_SLASH) {
  1531. backslashes = token.backslashes = true;
  1532. code = advance();
  1533. continue;
  1534. }
  1535. if (code === CHAR_RIGHT_PARENTHESES) {
  1536. isGlob = token.isGlob = true;
  1537. finished = true;
  1538. break;
  1539. }
  1540. }
  1541. continue;
  1542. }
  1543. break;
  1544. }
  1545. }
  1546. if (code === CHAR_ASTERISK) {
  1547. if (prev === CHAR_ASTERISK) isGlobstar = token.isGlobstar = true;
  1548. isGlob = token.isGlob = true;
  1549. finished = true;
  1550. if (scanToEnd === true) {
  1551. continue;
  1552. }
  1553. break;
  1554. }
  1555. if (code === CHAR_QUESTION_MARK) {
  1556. isGlob = token.isGlob = true;
  1557. finished = true;
  1558. if (scanToEnd === true) {
  1559. continue;
  1560. }
  1561. break;
  1562. }
  1563. if (code === CHAR_LEFT_SQUARE_BRACKET) {
  1564. while (eos() !== true && (next = advance())) {
  1565. if (next === CHAR_BACKWARD_SLASH) {
  1566. backslashes = token.backslashes = true;
  1567. advance();
  1568. continue;
  1569. }
  1570. if (next === CHAR_RIGHT_SQUARE_BRACKET) {
  1571. isBracket = token.isBracket = true;
  1572. isGlob = token.isGlob = true;
  1573. finished = true;
  1574. if (scanToEnd === true) {
  1575. continue;
  1576. }
  1577. break;
  1578. }
  1579. }
  1580. }
  1581. if (opts.nonegate !== true && code === CHAR_EXCLAMATION_MARK && index === start) {
  1582. negated = token.negated = true;
  1583. start++;
  1584. continue;
  1585. }
  1586. if (opts.noparen !== true && code === CHAR_LEFT_PARENTHESES) {
  1587. isGlob = token.isGlob = true;
  1588. if (scanToEnd === true) {
  1589. while (eos() !== true && (code = advance())) {
  1590. if (code === CHAR_LEFT_PARENTHESES) {
  1591. backslashes = token.backslashes = true;
  1592. code = advance();
  1593. continue;
  1594. }
  1595. if (code === CHAR_RIGHT_PARENTHESES) {
  1596. finished = true;
  1597. break;
  1598. }
  1599. }
  1600. continue;
  1601. }
  1602. break;
  1603. }
  1604. if (isGlob === true) {
  1605. finished = true;
  1606. if (scanToEnd === true) {
  1607. continue;
  1608. }
  1609. break;
  1610. }
  1611. }
  1612. if (opts.noext === true) {
  1613. isExtglob = false;
  1614. isGlob = false;
  1615. }
  1616. let base = str;
  1617. let prefix = '';
  1618. let glob = '';
  1619. if (start > 0) {
  1620. prefix = str.slice(0, start);
  1621. str = str.slice(start);
  1622. lastIndex -= start;
  1623. }
  1624. if (base && isGlob === true && lastIndex > 0) {
  1625. base = str.slice(0, lastIndex);
  1626. glob = str.slice(lastIndex);
  1627. } else if (isGlob === true) {
  1628. base = '';
  1629. glob = str;
  1630. } else {
  1631. base = str;
  1632. }
  1633. if (base && base !== '' && base !== '/' && base !== str) {
  1634. if (isPathSeparator(base.charCodeAt(base.length - 1))) {
  1635. base = base.slice(0, -1);
  1636. }
  1637. }
  1638. if (opts.unescape === true) {
  1639. if (glob) glob = utils$3.removeBackslashes(glob);
  1640. if (base && backslashes === true) {
  1641. base = utils$3.removeBackslashes(base);
  1642. }
  1643. }
  1644. const state = {
  1645. prefix,
  1646. input,
  1647. start,
  1648. base,
  1649. glob,
  1650. isBrace,
  1651. isBracket,
  1652. isGlob,
  1653. isExtglob,
  1654. isGlobstar,
  1655. negated
  1656. };
  1657. if (opts.tokens === true) {
  1658. state.maxDepth = 0;
  1659. if (!isPathSeparator(code)) {
  1660. tokens.push(token);
  1661. }
  1662. state.tokens = tokens;
  1663. }
  1664. if (opts.parts === true || opts.tokens === true) {
  1665. let prevIndex;
  1666. for (let idx = 0; idx < slashes.length; idx++) {
  1667. const n = prevIndex ? prevIndex + 1 : start;
  1668. const i = slashes[idx];
  1669. const value = input.slice(n, i);
  1670. if (opts.tokens) {
  1671. if (idx === 0 && start !== 0) {
  1672. tokens[idx].isPrefix = true;
  1673. tokens[idx].value = prefix;
  1674. } else {
  1675. tokens[idx].value = value;
  1676. }
  1677. depth(tokens[idx]);
  1678. state.maxDepth += tokens[idx].depth;
  1679. }
  1680. if (idx !== 0 || value !== '') {
  1681. parts.push(value);
  1682. }
  1683. prevIndex = i;
  1684. }
  1685. if (prevIndex && prevIndex + 1 < input.length) {
  1686. const value = input.slice(prevIndex + 1);
  1687. parts.push(value);
  1688. if (opts.tokens) {
  1689. tokens[tokens.length - 1].value = value;
  1690. depth(tokens[tokens.length - 1]);
  1691. state.maxDepth += tokens[tokens.length - 1].depth;
  1692. }
  1693. }
  1694. state.slashes = slashes;
  1695. state.parts = parts;
  1696. }
  1697. return state;
  1698. };
  1699. var scan_1 = scan$1;
  1700. const constants$2 = constants$3;
  1701. const utils$2 = utils$4;
  1702. /**
  1703. * Constants
  1704. */
  1705. const {
  1706. MAX_LENGTH,
  1707. POSIX_REGEX_SOURCE,
  1708. REGEX_NON_SPECIAL_CHARS,
  1709. REGEX_SPECIAL_CHARS_BACKREF,
  1710. REPLACEMENTS
  1711. } = constants$2;
  1712. /**
  1713. * Helpers
  1714. */
  1715. const expandRange = (args, options) => {
  1716. if (typeof options.expandRange === 'function') {
  1717. return options.expandRange(...args, options);
  1718. }
  1719. args.sort();
  1720. const value = `[${args.join('-')}]`;
  1721. return value;
  1722. };
  1723. /**
  1724. * Create the message for a syntax error
  1725. */
  1726. const syntaxError = (type, char) => {
  1727. return `Missing ${type}: "${char}" - use "\\\\${char}" to match literal characters`;
  1728. };
  1729. /**
  1730. * Parse the given input string.
  1731. * @param {String} input
  1732. * @param {Object} options
  1733. * @return {Object}
  1734. */
  1735. const parse$1 = (input, options) => {
  1736. if (typeof input !== 'string') {
  1737. throw new TypeError('Expected a string');
  1738. }
  1739. input = REPLACEMENTS[input] || input;
  1740. const opts = { ...options };
  1741. const max = typeof opts.maxLength === 'number' ? Math.min(MAX_LENGTH, opts.maxLength) : MAX_LENGTH;
  1742. let len = input.length;
  1743. if (len > max) {
  1744. throw new SyntaxError(`Input length: ${len}, exceeds maximum allowed length: ${max}`);
  1745. }
  1746. const bos = { type: 'bos', value: '', output: opts.prepend || '' };
  1747. const tokens = [bos];
  1748. const capture = opts.capture ? '' : '?:';
  1749. const win32 = utils$2.isWindows(options);
  1750. // create constants based on platform, for windows or posix
  1751. const PLATFORM_CHARS = constants$2.globChars(win32);
  1752. const EXTGLOB_CHARS = constants$2.extglobChars(PLATFORM_CHARS);
  1753. const {
  1754. DOT_LITERAL,
  1755. PLUS_LITERAL,
  1756. SLASH_LITERAL,
  1757. ONE_CHAR,
  1758. DOTS_SLASH,
  1759. NO_DOT,
  1760. NO_DOT_SLASH,
  1761. NO_DOTS_SLASH,
  1762. QMARK,
  1763. QMARK_NO_DOT,
  1764. STAR,
  1765. START_ANCHOR
  1766. } = PLATFORM_CHARS;
  1767. const globstar = (opts) => {
  1768. return `(${capture}(?:(?!${START_ANCHOR}${opts.dot ? DOTS_SLASH : DOT_LITERAL}).)*?)`;
  1769. };
  1770. const nodot = opts.dot ? '' : NO_DOT;
  1771. const qmarkNoDot = opts.dot ? QMARK : QMARK_NO_DOT;
  1772. let star = opts.bash === true ? globstar(opts) : STAR;
  1773. if (opts.capture) {
  1774. star = `(${star})`;
  1775. }
  1776. // minimatch options support
  1777. if (typeof opts.noext === 'boolean') {
  1778. opts.noextglob = opts.noext;
  1779. }
  1780. const state = {
  1781. input,
  1782. index: -1,
  1783. start: 0,
  1784. dot: opts.dot === true,
  1785. consumed: '',
  1786. output: '',
  1787. prefix: '',
  1788. backtrack: false,
  1789. negated: false,
  1790. brackets: 0,
  1791. braces: 0,
  1792. parens: 0,
  1793. quotes: 0,
  1794. globstar: false,
  1795. tokens
  1796. };
  1797. input = utils$2.removePrefix(input, state);
  1798. len = input.length;
  1799. const extglobs = [];
  1800. const braces = [];
  1801. const stack = [];
  1802. let prev = bos;
  1803. let value;
  1804. /**
  1805. * Tokenizing helpers
  1806. */
  1807. const eos = () => state.index === len - 1;
  1808. const peek = state.peek = (n = 1) => input[state.index + n];
  1809. const advance = state.advance = () => input[++state.index];
  1810. const remaining = () => input.slice(state.index + 1);
  1811. const consume = (value = '', num = 0) => {
  1812. state.consumed += value;
  1813. state.index += num;
  1814. };
  1815. const append = token => {
  1816. state.output += token.output != null ? token.output : token.value;
  1817. consume(token.value);
  1818. };
  1819. const negate = () => {
  1820. let count = 1;
  1821. while (peek() === '!' && (peek(2) !== '(' || peek(3) === '?')) {
  1822. advance();
  1823. state.start++;
  1824. count++;
  1825. }
  1826. if (count % 2 === 0) {
  1827. return false;
  1828. }
  1829. state.negated = true;
  1830. state.start++;
  1831. return true;
  1832. };
  1833. const increment = type => {
  1834. state[type]++;
  1835. stack.push(type);
  1836. };
  1837. const decrement = type => {
  1838. state[type]--;
  1839. stack.pop();
  1840. };
  1841. /**
  1842. * Push tokens onto the tokens array. This helper speeds up
  1843. * tokenizing by 1) helping us avoid backtracking as much as possible,
  1844. * and 2) helping us avoid creating extra tokens when consecutive
  1845. * characters are plain text. This improves performance and simplifies
  1846. * lookbehinds.
  1847. */
  1848. const push = tok => {
  1849. if (prev.type === 'globstar') {
  1850. const isBrace = state.braces > 0 && (tok.type === 'comma' || tok.type === 'brace');
  1851. const isExtglob = tok.extglob === true || (extglobs.length && (tok.type === 'pipe' || tok.type === 'paren'));
  1852. if (tok.type !== 'slash' && tok.type !== 'paren' && !isBrace && !isExtglob) {
  1853. state.output = state.output.slice(0, -prev.output.length);
  1854. prev.type = 'star';
  1855. prev.value = '*';
  1856. prev.output = star;
  1857. state.output += prev.output;
  1858. }
  1859. }
  1860. if (extglobs.length && tok.type !== 'paren' && !EXTGLOB_CHARS[tok.value]) {
  1861. extglobs[extglobs.length - 1].inner += tok.value;
  1862. }
  1863. if (tok.value || tok.output) append(tok);
  1864. if (prev && prev.type === 'text' && tok.type === 'text') {
  1865. prev.value += tok.value;
  1866. prev.output = (prev.output || '') + tok.value;
  1867. return;
  1868. }
  1869. tok.prev = prev;
  1870. tokens.push(tok);
  1871. prev = tok;
  1872. };
  1873. const extglobOpen = (type, value) => {
  1874. const token = { ...EXTGLOB_CHARS[value], conditions: 1, inner: '' };
  1875. token.prev = prev;
  1876. token.parens = state.parens;
  1877. token.output = state.output;
  1878. const output = (opts.capture ? '(' : '') + token.open;
  1879. increment('parens');
  1880. push({ type, value, output: state.output ? '' : ONE_CHAR });
  1881. push({ type: 'paren', extglob: true, value: advance(), output });
  1882. extglobs.push(token);
  1883. };
  1884. const extglobClose = token => {
  1885. let output = token.close + (opts.capture ? ')' : '');
  1886. if (token.type === 'negate') {
  1887. let extglobStar = star;
  1888. if (token.inner && token.inner.length > 1 && token.inner.includes('/')) {
  1889. extglobStar = globstar(opts);
  1890. }
  1891. if (extglobStar !== star || eos() || /^\)+$/.test(remaining())) {
  1892. output = token.close = `)$))${extglobStar}`;
  1893. }
  1894. if (token.prev.type === 'bos' && eos()) {
  1895. state.negatedExtglob = true;
  1896. }
  1897. }
  1898. push({ type: 'paren', extglob: true, value, output });
  1899. decrement('parens');
  1900. };
  1901. /**
  1902. * Fast paths
  1903. */
  1904. if (opts.fastpaths !== false && !/(^[*!]|[/()[\]{}"])/.test(input)) {
  1905. let backslashes = false;
  1906. let output = input.replace(REGEX_SPECIAL_CHARS_BACKREF, (m, esc, chars, first, rest, index) => {
  1907. if (first === '\\') {
  1908. backslashes = true;
  1909. return m;
  1910. }
  1911. if (first === '?') {
  1912. if (esc) {
  1913. return esc + first + (rest ? QMARK.repeat(rest.length) : '');
  1914. }
  1915. if (index === 0) {
  1916. return qmarkNoDot + (rest ? QMARK.repeat(rest.length) : '');
  1917. }
  1918. return QMARK.repeat(chars.length);
  1919. }
  1920. if (first === '.') {
  1921. return DOT_LITERAL.repeat(chars.length);
  1922. }
  1923. if (first === '*') {
  1924. if (esc) {
  1925. return esc + first + (rest ? star : '');
  1926. }
  1927. return star;
  1928. }
  1929. return esc ? m : `\\${m}`;
  1930. });
  1931. if (backslashes === true) {
  1932. if (opts.unescape === true) {
  1933. output = output.replace(/\\/g, '');
  1934. } else {
  1935. output = output.replace(/\\+/g, m => {
  1936. return m.length % 2 === 0 ? '\\\\' : (m ? '\\' : '');
  1937. });
  1938. }
  1939. }
  1940. if (output === input && opts.contains === true) {
  1941. state.output = input;
  1942. return state;
  1943. }
  1944. state.output = utils$2.wrapOutput(output, state, options);
  1945. return state;
  1946. }
  1947. /**
  1948. * Tokenize input until we reach end-of-string
  1949. */
  1950. while (!eos()) {
  1951. value = advance();
  1952. if (value === '\u0000') {
  1953. continue;
  1954. }
  1955. /**
  1956. * Escaped characters
  1957. */
  1958. if (value === '\\') {
  1959. const next = peek();
  1960. if (next === '/' && opts.bash !== true) {
  1961. continue;
  1962. }
  1963. if (next === '.' || next === ';') {
  1964. continue;
  1965. }
  1966. if (!next) {
  1967. value += '\\';
  1968. push({ type: 'text', value });
  1969. continue;
  1970. }
  1971. // collapse slashes to reduce potential for exploits
  1972. const match = /^\\+/.exec(remaining());
  1973. let slashes = 0;
  1974. if (match && match[0].length > 2) {
  1975. slashes = match[0].length;
  1976. state.index += slashes;
  1977. if (slashes % 2 !== 0) {
  1978. value += '\\';
  1979. }
  1980. }
  1981. if (opts.unescape === true) {
  1982. value = advance() || '';
  1983. } else {
  1984. value += advance() || '';
  1985. }
  1986. if (state.brackets === 0) {
  1987. push({ type: 'text', value });
  1988. continue;
  1989. }
  1990. }
  1991. /**
  1992. * If we're inside a regex character class, continue
  1993. * until we reach the closing bracket.
  1994. */
  1995. if (state.brackets > 0 && (value !== ']' || prev.value === '[' || prev.value === '[^')) {
  1996. if (opts.posix !== false && value === ':') {
  1997. const inner = prev.value.slice(1);
  1998. if (inner.includes('[')) {
  1999. prev.posix = true;
  2000. if (inner.includes(':')) {
  2001. const idx = prev.value.lastIndexOf('[');
  2002. const pre = prev.value.slice(0, idx);
  2003. const rest = prev.value.slice(idx + 2);
  2004. const posix = POSIX_REGEX_SOURCE[rest];
  2005. if (posix) {
  2006. prev.value = pre + posix;
  2007. state.backtrack = true;
  2008. advance();
  2009. if (!bos.output && tokens.indexOf(prev) === 1) {
  2010. bos.output = ONE_CHAR;
  2011. }
  2012. continue;
  2013. }
  2014. }
  2015. }
  2016. }
  2017. if ((value === '[' && peek() !== ':') || (value === '-' && peek() === ']')) {
  2018. value = `\\${value}`;
  2019. }
  2020. if (value === ']' && (prev.value === '[' || prev.value === '[^')) {
  2021. value = `\\${value}`;
  2022. }
  2023. if (opts.posix === true && value === '!' && prev.value === '[') {
  2024. value = '^';
  2025. }
  2026. prev.value += value;
  2027. append({ value });
  2028. continue;
  2029. }
  2030. /**
  2031. * If we're inside a quoted string, continue
  2032. * until we reach the closing double quote.
  2033. */
  2034. if (state.quotes === 1 && value !== '"') {
  2035. value = utils$2.escapeRegex(value);
  2036. prev.value += value;
  2037. append({ value });
  2038. continue;
  2039. }
  2040. /**
  2041. * Double quotes
  2042. */
  2043. if (value === '"') {
  2044. state.quotes = state.quotes === 1 ? 0 : 1;
  2045. if (opts.keepQuotes === true) {
  2046. push({ type: 'text', value });
  2047. }
  2048. continue;
  2049. }
  2050. /**
  2051. * Parentheses
  2052. */
  2053. if (value === '(') {
  2054. increment('parens');
  2055. push({ type: 'paren', value });
  2056. continue;
  2057. }
  2058. if (value === ')') {
  2059. if (state.parens === 0 && opts.strictBrackets === true) {
  2060. throw new SyntaxError(syntaxError('opening', '('));
  2061. }
  2062. const extglob = extglobs[extglobs.length - 1];
  2063. if (extglob && state.parens === extglob.parens + 1) {
  2064. extglobClose(extglobs.pop());
  2065. continue;
  2066. }
  2067. push({ type: 'paren', value, output: state.parens ? ')' : '\\)' });
  2068. decrement('parens');
  2069. continue;
  2070. }
  2071. /**
  2072. * Square brackets
  2073. */
  2074. if (value === '[') {
  2075. if (opts.nobracket === true || !remaining().includes(']')) {
  2076. if (opts.nobracket !== true && opts.strictBrackets === true) {
  2077. throw new SyntaxError(syntaxError('closing', ']'));
  2078. }
  2079. value = `\\${value}`;
  2080. } else {
  2081. increment('brackets');
  2082. }
  2083. push({ type: 'bracket', value });
  2084. continue;
  2085. }
  2086. if (value === ']') {
  2087. if (opts.nobracket === true || (prev && prev.type === 'bracket' && prev.value.length === 1)) {
  2088. push({ type: 'text', value, output: `\\${value}` });
  2089. continue;
  2090. }
  2091. if (state.brackets === 0) {
  2092. if (opts.strictBrackets === true) {
  2093. throw new SyntaxError(syntaxError('opening', '['));
  2094. }
  2095. push({ type: 'text', value, output: `\\${value}` });
  2096. continue;
  2097. }
  2098. decrement('brackets');
  2099. const prevValue = prev.value.slice(1);
  2100. if (prev.posix !== true && prevValue[0] === '^' && !prevValue.includes('/')) {
  2101. value = `/${value}`;
  2102. }
  2103. prev.value += value;
  2104. append({ value });
  2105. // when literal brackets are explicitly disabled
  2106. // assume we should match with a regex character class
  2107. if (opts.literalBrackets === false || utils$2.hasRegexChars(prevValue)) {
  2108. continue;
  2109. }
  2110. const escaped = utils$2.escapeRegex(prev.value);
  2111. state.output = state.output.slice(0, -prev.value.length);
  2112. // when literal brackets are explicitly enabled
  2113. // assume we should escape the brackets to match literal characters
  2114. if (opts.literalBrackets === true) {
  2115. state.output += escaped;
  2116. prev.value = escaped;
  2117. continue;
  2118. }
  2119. // when the user specifies nothing, try to match both
  2120. prev.value = `(${capture}${escaped}|${prev.value})`;
  2121. state.output += prev.value;
  2122. continue;
  2123. }
  2124. /**
  2125. * Braces
  2126. */
  2127. if (value === '{' && opts.nobrace !== true) {
  2128. increment('braces');
  2129. const open = {
  2130. type: 'brace',
  2131. value,
  2132. output: '(',
  2133. outputIndex: state.output.length,
  2134. tokensIndex: state.tokens.length
  2135. };
  2136. braces.push(open);
  2137. push(open);
  2138. continue;
  2139. }
  2140. if (value === '}') {
  2141. const brace = braces[braces.length - 1];
  2142. if (opts.nobrace === true || !brace) {
  2143. push({ type: 'text', value, output: value });
  2144. continue;
  2145. }
  2146. let output = ')';
  2147. if (brace.dots === true) {
  2148. const arr = tokens.slice();
  2149. const range = [];
  2150. for (let i = arr.length - 1; i >= 0; i--) {
  2151. tokens.pop();
  2152. if (arr[i].type === 'brace') {
  2153. break;
  2154. }
  2155. if (arr[i].type !== 'dots') {
  2156. range.unshift(arr[i].value);
  2157. }
  2158. }
  2159. output = expandRange(range, opts);
  2160. state.backtrack = true;
  2161. }
  2162. if (brace.comma !== true && brace.dots !== true) {
  2163. const out = state.output.slice(0, brace.outputIndex);
  2164. const toks = state.tokens.slice(brace.tokensIndex);
  2165. brace.value = brace.output = '\\{';
  2166. value = output = '\\}';
  2167. state.output = out;
  2168. for (const t of toks) {
  2169. state.output += (t.output || t.value);
  2170. }
  2171. }
  2172. push({ type: 'brace', value, output });
  2173. decrement('braces');
  2174. braces.pop();
  2175. continue;
  2176. }
  2177. /**
  2178. * Pipes
  2179. */
  2180. if (value === '|') {
  2181. if (extglobs.length > 0) {
  2182. extglobs[extglobs.length - 1].conditions++;
  2183. }
  2184. push({ type: 'text', value });
  2185. continue;
  2186. }
  2187. /**
  2188. * Commas
  2189. */
  2190. if (value === ',') {
  2191. let output = value;
  2192. const brace = braces[braces.length - 1];
  2193. if (brace && stack[stack.length - 1] === 'braces') {
  2194. brace.comma = true;
  2195. output = '|';
  2196. }
  2197. push({ type: 'comma', value, output });
  2198. continue;
  2199. }
  2200. /**
  2201. * Slashes
  2202. */
  2203. if (value === '/') {
  2204. // if the beginning of the glob is "./", advance the start
  2205. // to the current index, and don't add the "./" characters
  2206. // to the state. This greatly simplifies lookbehinds when
  2207. // checking for BOS characters like "!" and "." (not "./")
  2208. if (prev.type === 'dot' && state.index === state.start + 1) {
  2209. state.start = state.index + 1;
  2210. state.consumed = '';
  2211. state.output = '';
  2212. tokens.pop();
  2213. prev = bos; // reset "prev" to the first token
  2214. continue;
  2215. }
  2216. push({ type: 'slash', value, output: SLASH_LITERAL });
  2217. continue;
  2218. }
  2219. /**
  2220. * Dots
  2221. */
  2222. if (value === '.') {
  2223. if (state.braces > 0 && prev.type === 'dot') {
  2224. if (prev.value === '.') prev.output = DOT_LITERAL;
  2225. const brace = braces[braces.length - 1];
  2226. prev.type = 'dots';
  2227. prev.output += value;
  2228. prev.value += value;
  2229. brace.dots = true;
  2230. continue;
  2231. }
  2232. if ((state.braces + state.parens) === 0 && prev.type !== 'bos' && prev.type !== 'slash') {
  2233. push({ type: 'text', value, output: DOT_LITERAL });
  2234. continue;
  2235. }
  2236. push({ type: 'dot', value, output: DOT_LITERAL });
  2237. continue;
  2238. }
  2239. /**
  2240. * Question marks
  2241. */
  2242. if (value === '?') {
  2243. const isGroup = prev && prev.value === '(';
  2244. if (!isGroup && opts.noextglob !== true && peek() === '(' && peek(2) !== '?') {
  2245. extglobOpen('qmark', value);
  2246. continue;
  2247. }
  2248. if (prev && prev.type === 'paren') {
  2249. const next = peek();
  2250. let output = value;
  2251. if (next === '<' && !utils$2.supportsLookbehinds()) {
  2252. throw new Error('Node.js v10 or higher is required for regex lookbehinds');
  2253. }
  2254. if ((prev.value === '(' && !/[!=<:]/.test(next)) || (next === '<' && !/<([!=]|\w+>)/.test(remaining()))) {
  2255. output = `\\${value}`;
  2256. }
  2257. push({ type: 'text', value, output });
  2258. continue;
  2259. }
  2260. if (opts.dot !== true && (prev.type === 'slash' || prev.type === 'bos')) {
  2261. push({ type: 'qmark', value, output: QMARK_NO_DOT });
  2262. continue;
  2263. }
  2264. push({ type: 'qmark', value, output: QMARK });
  2265. continue;
  2266. }
  2267. /**
  2268. * Exclamation
  2269. */
  2270. if (value === '!') {
  2271. if (opts.noextglob !== true && peek() === '(') {
  2272. if (peek(2) !== '?' || !/[!=<:]/.test(peek(3))) {
  2273. extglobOpen('negate', value);
  2274. continue;
  2275. }
  2276. }
  2277. if (opts.nonegate !== true && state.index === 0) {
  2278. negate();
  2279. continue;
  2280. }
  2281. }
  2282. /**
  2283. * Plus
  2284. */
  2285. if (value === '+') {
  2286. if (opts.noextglob !== true && peek() === '(' && peek(2) !== '?') {
  2287. extglobOpen('plus', value);
  2288. continue;
  2289. }
  2290. if ((prev && prev.value === '(') || opts.regex === false) {
  2291. push({ type: 'plus', value, output: PLUS_LITERAL });
  2292. continue;
  2293. }
  2294. if ((prev && (prev.type === 'bracket' || prev.type === 'paren' || prev.type === 'brace')) || state.parens > 0) {
  2295. push({ type: 'plus', value });
  2296. continue;
  2297. }
  2298. push({ type: 'plus', value: PLUS_LITERAL });
  2299. continue;
  2300. }
  2301. /**
  2302. * Plain text
  2303. */
  2304. if (value === '@') {
  2305. if (opts.noextglob !== true && peek() === '(' && peek(2) !== '?') {
  2306. push({ type: 'at', extglob: true, value, output: '' });
  2307. continue;
  2308. }
  2309. push({ type: 'text', value });
  2310. continue;
  2311. }
  2312. /**
  2313. * Plain text
  2314. */
  2315. if (value !== '*') {
  2316. if (value === '$' || value === '^') {
  2317. value = `\\${value}`;
  2318. }
  2319. const match = REGEX_NON_SPECIAL_CHARS.exec(remaining());
  2320. if (match) {
  2321. value += match[0];
  2322. state.index += match[0].length;
  2323. }
  2324. push({ type: 'text', value });
  2325. continue;
  2326. }
  2327. /**
  2328. * Stars
  2329. */
  2330. if (prev && (prev.type === 'globstar' || prev.star === true)) {
  2331. prev.type = 'star';
  2332. prev.star = true;
  2333. prev.value += value;
  2334. prev.output = star;
  2335. state.backtrack = true;
  2336. state.globstar = true;
  2337. consume(value);
  2338. continue;
  2339. }
  2340. let rest = remaining();
  2341. if (opts.noextglob !== true && /^\([^?]/.test(rest)) {
  2342. extglobOpen('star', value);
  2343. continue;
  2344. }
  2345. if (prev.type === 'star') {
  2346. if (opts.noglobstar === true) {
  2347. consume(value);
  2348. continue;
  2349. }
  2350. const prior = prev.prev;
  2351. const before = prior.prev;
  2352. const isStart = prior.type === 'slash' || prior.type === 'bos';
  2353. const afterStar = before && (before.type === 'star' || before.type === 'globstar');
  2354. if (opts.bash === true && (!isStart || (rest[0] && rest[0] !== '/'))) {
  2355. push({ type: 'star', value, output: '' });
  2356. continue;
  2357. }
  2358. const isBrace = state.braces > 0 && (prior.type === 'comma' || prior.type === 'brace');
  2359. const isExtglob = extglobs.length && (prior.type === 'pipe' || prior.type === 'paren');
  2360. if (!isStart && prior.type !== 'paren' && !isBrace && !isExtglob) {
  2361. push({ type: 'star', value, output: '' });
  2362. continue;
  2363. }
  2364. // strip consecutive `/**/`
  2365. while (rest.slice(0, 3) === '/**') {
  2366. const after = input[state.index + 4];
  2367. if (after && after !== '/') {
  2368. break;
  2369. }
  2370. rest = rest.slice(3);
  2371. consume('/**', 3);
  2372. }
  2373. if (prior.type === 'bos' && eos()) {
  2374. prev.type = 'globstar';
  2375. prev.value += value;
  2376. prev.output = globstar(opts);
  2377. state.output = prev.output;
  2378. state.globstar = true;
  2379. consume(value);
  2380. continue;
  2381. }
  2382. if (prior.type === 'slash' && prior.prev.type !== 'bos' && !afterStar && eos()) {
  2383. state.output = state.output.slice(0, -(prior.output + prev.output).length);
  2384. prior.output = `(?:${prior.output}`;
  2385. prev.type = 'globstar';
  2386. prev.output = globstar(opts) + (opts.strictSlashes ? ')' : '|$)');
  2387. prev.value += value;
  2388. state.globstar = true;
  2389. state.output += prior.output + prev.output;
  2390. consume(value);
  2391. continue;
  2392. }
  2393. if (prior.type === 'slash' && prior.prev.type !== 'bos' && rest[0] === '/') {
  2394. const end = rest[1] !== void 0 ? '|$' : '';
  2395. state.output = state.output.slice(0, -(prior.output + prev.output).length);
  2396. prior.output = `(?:${prior.output}`;
  2397. prev.type = 'globstar';
  2398. prev.output = `${globstar(opts)}${SLASH_LITERAL}|${SLASH_LITERAL}${end})`;
  2399. prev.value += value;
  2400. state.output += prior.output + prev.output;
  2401. state.globstar = true;
  2402. consume(value + advance());
  2403. push({ type: 'slash', value: '/', output: '' });
  2404. continue;
  2405. }
  2406. if (prior.type === 'bos' && rest[0] === '/') {
  2407. prev.type = 'globstar';
  2408. prev.value += value;
  2409. prev.output = `(?:^|${SLASH_LITERAL}|${globstar(opts)}${SLASH_LITERAL})`;
  2410. state.output = prev.output;
  2411. state.globstar = true;
  2412. consume(value + advance());
  2413. push({ type: 'slash', value: '/', output: '' });
  2414. continue;
  2415. }
  2416. // remove single star from output
  2417. state.output = state.output.slice(0, -prev.output.length);
  2418. // reset previous token to globstar
  2419. prev.type = 'globstar';
  2420. prev.output = globstar(opts);
  2421. prev.value += value;
  2422. // reset output with globstar
  2423. state.output += prev.output;
  2424. state.globstar = true;
  2425. consume(value);
  2426. continue;
  2427. }
  2428. const token = { type: 'star', value, output: star };
  2429. if (opts.bash === true) {
  2430. token.output = '.*?';
  2431. if (prev.type === 'bos' || prev.type === 'slash') {
  2432. token.output = nodot + token.output;
  2433. }
  2434. push(token);
  2435. continue;
  2436. }
  2437. if (prev && (prev.type === 'bracket' || prev.type === 'paren') && opts.regex === true) {
  2438. token.output = value;
  2439. push(token);
  2440. continue;
  2441. }
  2442. if (state.index === state.start || prev.type === 'slash' || prev.type === 'dot') {
  2443. if (prev.type === 'dot') {
  2444. state.output += NO_DOT_SLASH;
  2445. prev.output += NO_DOT_SLASH;
  2446. } else if (opts.dot === true) {
  2447. state.output += NO_DOTS_SLASH;
  2448. prev.output += NO_DOTS_SLASH;
  2449. } else {
  2450. state.output += nodot;
  2451. prev.output += nodot;
  2452. }
  2453. if (peek() !== '*') {
  2454. state.output += ONE_CHAR;
  2455. prev.output += ONE_CHAR;
  2456. }
  2457. }
  2458. push(token);
  2459. }
  2460. while (state.brackets > 0) {
  2461. if (opts.strictBrackets === true) throw new SyntaxError(syntaxError('closing', ']'));
  2462. state.output = utils$2.escapeLast(state.output, '[');
  2463. decrement('brackets');
  2464. }
  2465. while (state.parens > 0) {
  2466. if (opts.strictBrackets === true) throw new SyntaxError(syntaxError('closing', ')'));
  2467. state.output = utils$2.escapeLast(state.output, '(');
  2468. decrement('parens');
  2469. }
  2470. while (state.braces > 0) {
  2471. if (opts.strictBrackets === true) throw new SyntaxError(syntaxError('closing', '}'));
  2472. state.output = utils$2.escapeLast(state.output, '{');
  2473. decrement('braces');
  2474. }
  2475. if (opts.strictSlashes !== true && (prev.type === 'star' || prev.type === 'bracket')) {
  2476. push({ type: 'maybe_slash', value: '', output: `${SLASH_LITERAL}?` });
  2477. }
  2478. // rebuild the output if we had to backtrack at any point
  2479. if (state.backtrack === true) {
  2480. state.output = '';
  2481. for (const token of state.tokens) {
  2482. state.output += token.output != null ? token.output : token.value;
  2483. if (token.suffix) {
  2484. state.output += token.suffix;
  2485. }
  2486. }
  2487. }
  2488. return state;
  2489. };
  2490. /**
  2491. * Fast paths for creating regular expressions for common glob patterns.
  2492. * This can significantly speed up processing and has very little downside
  2493. * impact when none of the fast paths match.
  2494. */
  2495. parse$1.fastpaths = (input, options) => {
  2496. const opts = { ...options };
  2497. const max = typeof opts.maxLength === 'number' ? Math.min(MAX_LENGTH, opts.maxLength) : MAX_LENGTH;
  2498. const len = input.length;
  2499. if (len > max) {
  2500. throw new SyntaxError(`Input length: ${len}, exceeds maximum allowed length: ${max}`);
  2501. }
  2502. input = REPLACEMENTS[input] || input;
  2503. const win32 = utils$2.isWindows(options);
  2504. // create constants based on platform, for windows or posix
  2505. const {
  2506. DOT_LITERAL,
  2507. SLASH_LITERAL,
  2508. ONE_CHAR,
  2509. DOTS_SLASH,
  2510. NO_DOT,
  2511. NO_DOTS,
  2512. NO_DOTS_SLASH,
  2513. STAR,
  2514. START_ANCHOR
  2515. } = constants$2.globChars(win32);
  2516. const nodot = opts.dot ? NO_DOTS : NO_DOT;
  2517. const slashDot = opts.dot ? NO_DOTS_SLASH : NO_DOT;
  2518. const capture = opts.capture ? '' : '?:';
  2519. const state = { negated: false, prefix: '' };
  2520. let star = opts.bash === true ? '.*?' : STAR;
  2521. if (opts.capture) {
  2522. star = `(${star})`;
  2523. }
  2524. const globstar = (opts) => {
  2525. if (opts.noglobstar === true) return star;
  2526. return `(${capture}(?:(?!${START_ANCHOR}${opts.dot ? DOTS_SLASH : DOT_LITERAL}).)*?)`;
  2527. };
  2528. const create = str => {
  2529. switch (str) {
  2530. case '*':
  2531. return `${nodot}${ONE_CHAR}${star}`;
  2532. case '.*':
  2533. return `${DOT_LITERAL}${ONE_CHAR}${star}`;
  2534. case '*.*':
  2535. return `${nodot}${star}${DOT_LITERAL}${ONE_CHAR}${star}`;
  2536. case '*/*':
  2537. return `${nodot}${star}${SLASH_LITERAL}${ONE_CHAR}${slashDot}${star}`;
  2538. case '**':
  2539. return nodot + globstar(opts);
  2540. case '**/*':
  2541. return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${slashDot}${ONE_CHAR}${star}`;
  2542. case '**/*.*':
  2543. return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${slashDot}${star}${DOT_LITERAL}${ONE_CHAR}${star}`;
  2544. case '**/.*':
  2545. return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${DOT_LITERAL}${ONE_CHAR}${star}`;
  2546. default: {
  2547. const match = /^(.*?)\.(\w+)$/.exec(str);
  2548. if (!match) return;
  2549. const source = create(match[1]);
  2550. if (!source) return;
  2551. return source + DOT_LITERAL + match[2];
  2552. }
  2553. }
  2554. };
  2555. const output = utils$2.removePrefix(input, state);
  2556. let source = create(output);
  2557. if (source && opts.strictSlashes !== true) {
  2558. source += `${SLASH_LITERAL}?`;
  2559. }
  2560. return source;
  2561. };
  2562. var parse_1 = parse$1;
  2563. const path$1 = require$$0$2;
  2564. const scan = scan_1;
  2565. const parse = parse_1;
  2566. const utils$1 = utils$4;
  2567. const constants$1 = constants$3;
  2568. const isObject = val => val && typeof val === 'object' && !Array.isArray(val);
  2569. /**
  2570. * Creates a matcher function from one or more glob patterns. The
  2571. * returned function takes a string to match as its first argument,
  2572. * and returns true if the string is a match. The returned matcher
  2573. * function also takes a boolean as the second argument that, when true,
  2574. * returns an object with additional information.
  2575. *
  2576. * ```js
  2577. * const picomatch = require('picomatch');
  2578. * // picomatch(glob[, options]);
  2579. *
  2580. * const isMatch = picomatch('*.!(*a)');
  2581. * console.log(isMatch('a.a')); //=> false
  2582. * console.log(isMatch('a.b')); //=> true
  2583. * ```
  2584. * @name picomatch
  2585. * @param {String|Array} `globs` One or more glob patterns.
  2586. * @param {Object=} `options`
  2587. * @return {Function=} Returns a matcher function.
  2588. * @api public
  2589. */
  2590. const picomatch$4 = (glob, options, returnState = false) => {
  2591. if (Array.isArray(glob)) {
  2592. const fns = glob.map(input => picomatch$4(input, options, returnState));
  2593. const arrayMatcher = str => {
  2594. for (const isMatch of fns) {
  2595. const state = isMatch(str);
  2596. if (state) return state;
  2597. }
  2598. return false;
  2599. };
  2600. return arrayMatcher;
  2601. }
  2602. const isState = isObject(glob) && glob.tokens && glob.input;
  2603. if (glob === '' || (typeof glob !== 'string' && !isState)) {
  2604. throw new TypeError('Expected pattern to be a non-empty string');
  2605. }
  2606. const opts = options || {};
  2607. const posix = utils$1.isWindows(options);
  2608. const regex = isState
  2609. ? picomatch$4.compileRe(glob, options)
  2610. : picomatch$4.makeRe(glob, options, false, true);
  2611. const state = regex.state;
  2612. delete regex.state;
  2613. let isIgnored = () => false;
  2614. if (opts.ignore) {
  2615. const ignoreOpts = { ...options, ignore: null, onMatch: null, onResult: null };
  2616. isIgnored = picomatch$4(opts.ignore, ignoreOpts, returnState);
  2617. }
  2618. const matcher = (input, returnObject = false) => {
  2619. const { isMatch, match, output } = picomatch$4.test(input, regex, options, { glob, posix });
  2620. const result = { glob, state, regex, posix, input, output, match, isMatch };
  2621. if (typeof opts.onResult === 'function') {
  2622. opts.onResult(result);
  2623. }
  2624. if (isMatch === false) {
  2625. result.isMatch = false;
  2626. return returnObject ? result : false;
  2627. }
  2628. if (isIgnored(input)) {
  2629. if (typeof opts.onIgnore === 'function') {
  2630. opts.onIgnore(result);
  2631. }
  2632. result.isMatch = false;
  2633. return returnObject ? result : false;
  2634. }
  2635. if (typeof opts.onMatch === 'function') {
  2636. opts.onMatch(result);
  2637. }
  2638. return returnObject ? result : true;
  2639. };
  2640. if (returnState) {
  2641. matcher.state = state;
  2642. }
  2643. return matcher;
  2644. };
  2645. /**
  2646. * Test `input` with the given `regex`. This is used by the main
  2647. * `picomatch()` function to test the input string.
  2648. *
  2649. * ```js
  2650. * const picomatch = require('picomatch');
  2651. * // picomatch.test(input, regex[, options]);
  2652. *
  2653. * console.log(picomatch.test('foo/bar', /^(?:([^/]*?)\/([^/]*?))$/));
  2654. * // { isMatch: true, match: [ 'foo/', 'foo', 'bar' ], output: 'foo/bar' }
  2655. * ```
  2656. * @param {String} `input` String to test.
  2657. * @param {RegExp} `regex`
  2658. * @return {Object} Returns an object with matching info.
  2659. * @api public
  2660. */
  2661. picomatch$4.test = (input, regex, options, { glob, posix } = {}) => {
  2662. if (typeof input !== 'string') {
  2663. throw new TypeError('Expected input to be a string');
  2664. }
  2665. if (input === '') {
  2666. return { isMatch: false, output: '' };
  2667. }
  2668. const opts = options || {};
  2669. const format = opts.format || (posix ? utils$1.toPosixSlashes : null);
  2670. let match = input === glob;
  2671. let output = (match && format) ? format(input) : input;
  2672. if (match === false) {
  2673. output = format ? format(input) : input;
  2674. match = output === glob;
  2675. }
  2676. if (match === false || opts.capture === true) {
  2677. if (opts.matchBase === true || opts.basename === true) {
  2678. match = picomatch$4.matchBase(input, regex, options, posix);
  2679. } else {
  2680. match = regex.exec(output);
  2681. }
  2682. }
  2683. return { isMatch: Boolean(match), match, output };
  2684. };
  2685. /**
  2686. * Match the basename of a filepath.
  2687. *
  2688. * ```js
  2689. * const picomatch = require('picomatch');
  2690. * // picomatch.matchBase(input, glob[, options]);
  2691. * console.log(picomatch.matchBase('foo/bar.js', '*.js'); // true
  2692. * ```
  2693. * @param {String} `input` String to test.
  2694. * @param {RegExp|String} `glob` Glob pattern or regex created by [.makeRe](#makeRe).
  2695. * @return {Boolean}
  2696. * @api public
  2697. */
  2698. picomatch$4.matchBase = (input, glob, options, posix = utils$1.isWindows(options)) => {
  2699. const regex = glob instanceof RegExp ? glob : picomatch$4.makeRe(glob, options);
  2700. return regex.test(path$1.basename(input));
  2701. };
  2702. /**
  2703. * Returns true if **any** of the given glob `patterns` match the specified `string`.
  2704. *
  2705. * ```js
  2706. * const picomatch = require('picomatch');
  2707. * // picomatch.isMatch(string, patterns[, options]);
  2708. *
  2709. * console.log(picomatch.isMatch('a.a', ['b.*', '*.a'])); //=> true
  2710. * console.log(picomatch.isMatch('a.a', 'b.*')); //=> false
  2711. * ```
  2712. * @param {String|Array} str The string to test.
  2713. * @param {String|Array} patterns One or more glob patterns to use for matching.
  2714. * @param {Object} [options] See available [options](#options).
  2715. * @return {Boolean} Returns true if any patterns match `str`
  2716. * @api public
  2717. */
  2718. picomatch$4.isMatch = (str, patterns, options) => picomatch$4(patterns, options)(str);
  2719. /**
  2720. * Parse a glob pattern to create the source string for a regular
  2721. * expression.
  2722. *
  2723. * ```js
  2724. * const picomatch = require('picomatch');
  2725. * const result = picomatch.parse(pattern[, options]);
  2726. * ```
  2727. * @param {String} `pattern`
  2728. * @param {Object} `options`
  2729. * @return {Object} Returns an object with useful properties and output to be used as a regex source string.
  2730. * @api public
  2731. */
  2732. picomatch$4.parse = (pattern, options) => {
  2733. if (Array.isArray(pattern)) return pattern.map(p => picomatch$4.parse(p, options));
  2734. return parse(pattern, { ...options, fastpaths: false });
  2735. };
  2736. /**
  2737. * Scan a glob pattern to separate the pattern into segments.
  2738. *
  2739. * ```js
  2740. * const picomatch = require('picomatch');
  2741. * // picomatch.scan(input[, options]);
  2742. *
  2743. * const result = picomatch.scan('!./foo/*.js');
  2744. * console.log(result);
  2745. * { prefix: '!./',
  2746. * input: '!./foo/*.js',
  2747. * start: 3,
  2748. * base: 'foo',
  2749. * glob: '*.js',
  2750. * isBrace: false,
  2751. * isBracket: false,
  2752. * isGlob: true,
  2753. * isExtglob: false,
  2754. * isGlobstar: false,
  2755. * negated: true }
  2756. * ```
  2757. * @param {String} `input` Glob pattern to scan.
  2758. * @param {Object} `options`
  2759. * @return {Object} Returns an object with
  2760. * @api public
  2761. */
  2762. picomatch$4.scan = (input, options) => scan(input, options);
  2763. /**
  2764. * Create a regular expression from a parsed glob pattern.
  2765. *
  2766. * ```js
  2767. * const picomatch = require('picomatch');
  2768. * const state = picomatch.parse('*.js');
  2769. * // picomatch.compileRe(state[, options]);
  2770. *
  2771. * console.log(picomatch.compileRe(state));
  2772. * //=> /^(?:(?!\.)(?=.)[^/]*?\.js)$/
  2773. * ```
  2774. * @param {String} `state` The object returned from the `.parse` method.
  2775. * @param {Object} `options`
  2776. * @return {RegExp} Returns a regex created from the given pattern.
  2777. * @api public
  2778. */
  2779. picomatch$4.compileRe = (parsed, options, returnOutput = false, returnState = false) => {
  2780. if (returnOutput === true) {
  2781. return parsed.output;
  2782. }
  2783. const opts = options || {};
  2784. const prepend = opts.contains ? '' : '^';
  2785. const append = opts.contains ? '' : '$';
  2786. let source = `${prepend}(?:${parsed.output})${append}`;
  2787. if (parsed && parsed.negated === true) {
  2788. source = `^(?!${source}).*$`;
  2789. }
  2790. const regex = picomatch$4.toRegex(source, options);
  2791. if (returnState === true) {
  2792. regex.state = parsed;
  2793. }
  2794. return regex;
  2795. };
  2796. picomatch$4.makeRe = (input, options, returnOutput = false, returnState = false) => {
  2797. if (!input || typeof input !== 'string') {
  2798. throw new TypeError('Expected a non-empty string');
  2799. }
  2800. const opts = options || {};
  2801. let parsed = { negated: false, fastpaths: true };
  2802. let prefix = '';
  2803. let output;
  2804. if (input.startsWith('./')) {
  2805. input = input.slice(2);
  2806. prefix = parsed.prefix = './';
  2807. }
  2808. if (opts.fastpaths !== false && (input[0] === '.' || input[0] === '*')) {
  2809. output = parse.fastpaths(input, options);
  2810. }
  2811. if (output === undefined) {
  2812. parsed = parse(input, options);
  2813. parsed.prefix = prefix + (parsed.prefix || '');
  2814. } else {
  2815. parsed.output = output;
  2816. }
  2817. return picomatch$4.compileRe(parsed, options, returnOutput, returnState);
  2818. };
  2819. /**
  2820. * Create a regular expression from the given regex source string.
  2821. *
  2822. * ```js
  2823. * const picomatch = require('picomatch');
  2824. * // picomatch.toRegex(source[, options]);
  2825. *
  2826. * const { output } = picomatch.parse('*.js');
  2827. * console.log(picomatch.toRegex(output));
  2828. * //=> /^(?:(?!\.)(?=.)[^/]*?\.js)$/
  2829. * ```
  2830. * @param {String} `source` Regular expression source string.
  2831. * @param {Object} `options`
  2832. * @return {RegExp}
  2833. * @api public
  2834. */
  2835. picomatch$4.toRegex = (source, options) => {
  2836. try {
  2837. const opts = options || {};
  2838. return new RegExp(source, opts.flags || (opts.nocase ? 'i' : ''));
  2839. } catch (err) {
  2840. if (options && options.debug === true) throw err;
  2841. return /$^/;
  2842. }
  2843. };
  2844. /**
  2845. * Picomatch constants.
  2846. * @return {Object}
  2847. */
  2848. picomatch$4.constants = constants$1;
  2849. /**
  2850. * Expose "picomatch"
  2851. */
  2852. var picomatch_1 = picomatch$4;
  2853. var picomatch$3 = picomatch_1;
  2854. const util = require$$0$1;
  2855. const braces$1 = braces_1;
  2856. const picomatch$2 = picomatch$3;
  2857. const utils = utils$4;
  2858. const isEmptyString = val => typeof val === 'string' && (val === '' || val === './');
  2859. /**
  2860. * Returns an array of strings that match one or more glob patterns.
  2861. *
  2862. * ```js
  2863. * const mm = require('micromatch');
  2864. * // mm(list, patterns[, options]);
  2865. *
  2866. * console.log(mm(['a.js', 'a.txt'], ['*.js']));
  2867. * //=> [ 'a.js' ]
  2868. * ```
  2869. * @param {String|Array<string>} list List of strings to match.
  2870. * @param {String|Array<string>} patterns One or more glob patterns to use for matching.
  2871. * @param {Object} options See available [options](#options)
  2872. * @return {Array} Returns an array of matches
  2873. * @summary false
  2874. * @api public
  2875. */
  2876. const micromatch = (list, patterns, options) => {
  2877. patterns = [].concat(patterns);
  2878. list = [].concat(list);
  2879. let omit = new Set();
  2880. let keep = new Set();
  2881. let items = new Set();
  2882. let negatives = 0;
  2883. let onResult = state => {
  2884. items.add(state.output);
  2885. if (options && options.onResult) {
  2886. options.onResult(state);
  2887. }
  2888. };
  2889. for (let i = 0; i < patterns.length; i++) {
  2890. let isMatch = picomatch$2(String(patterns[i]), { ...options, onResult }, true);
  2891. let negated = isMatch.state.negated || isMatch.state.negatedExtglob;
  2892. if (negated) negatives++;
  2893. for (let item of list) {
  2894. let matched = isMatch(item, true);
  2895. let match = negated ? !matched.isMatch : matched.isMatch;
  2896. if (!match) continue;
  2897. if (negated) {
  2898. omit.add(matched.output);
  2899. } else {
  2900. omit.delete(matched.output);
  2901. keep.add(matched.output);
  2902. }
  2903. }
  2904. }
  2905. let result = negatives === patterns.length ? [...items] : [...keep];
  2906. let matches = result.filter(item => !omit.has(item));
  2907. if (options && matches.length === 0) {
  2908. if (options.failglob === true) {
  2909. throw new Error(`No matches found for "${patterns.join(', ')}"`);
  2910. }
  2911. if (options.nonull === true || options.nullglob === true) {
  2912. return options.unescape ? patterns.map(p => p.replace(/\\/g, '')) : patterns;
  2913. }
  2914. }
  2915. return matches;
  2916. };
  2917. /**
  2918. * Backwards compatibility
  2919. */
  2920. micromatch.match = micromatch;
  2921. /**
  2922. * Returns a matcher function from the given glob `pattern` and `options`.
  2923. * The returned function takes a string to match as its only argument and returns
  2924. * true if the string is a match.
  2925. *
  2926. * ```js
  2927. * const mm = require('micromatch');
  2928. * // mm.matcher(pattern[, options]);
  2929. *
  2930. * const isMatch = mm.matcher('*.!(*a)');
  2931. * console.log(isMatch('a.a')); //=> false
  2932. * console.log(isMatch('a.b')); //=> true
  2933. * ```
  2934. * @param {String} `pattern` Glob pattern
  2935. * @param {Object} `options`
  2936. * @return {Function} Returns a matcher function.
  2937. * @api public
  2938. */
  2939. micromatch.matcher = (pattern, options) => picomatch$2(pattern, options);
  2940. /**
  2941. * Returns true if **any** of the given glob `patterns` match the specified `string`.
  2942. *
  2943. * ```js
  2944. * const mm = require('micromatch');
  2945. * // mm.isMatch(string, patterns[, options]);
  2946. *
  2947. * console.log(mm.isMatch('a.a', ['b.*', '*.a'])); //=> true
  2948. * console.log(mm.isMatch('a.a', 'b.*')); //=> false
  2949. * ```
  2950. * @param {String} str The string to test.
  2951. * @param {String|Array} patterns One or more glob patterns to use for matching.
  2952. * @param {Object} [options] See available [options](#options).
  2953. * @return {Boolean} Returns true if any patterns match `str`
  2954. * @api public
  2955. */
  2956. micromatch.isMatch = (str, patterns, options) => picomatch$2(patterns, options)(str);
  2957. /**
  2958. * Backwards compatibility
  2959. */
  2960. micromatch.any = micromatch.isMatch;
  2961. /**
  2962. * Returns a list of strings that _**do not match any**_ of the given `patterns`.
  2963. *
  2964. * ```js
  2965. * const mm = require('micromatch');
  2966. * // mm.not(list, patterns[, options]);
  2967. *
  2968. * console.log(mm.not(['a.a', 'b.b', 'c.c'], '*.a'));
  2969. * //=> ['b.b', 'c.c']
  2970. * ```
  2971. * @param {Array} `list` Array of strings to match.
  2972. * @param {String|Array} `patterns` One or more glob pattern to use for matching.
  2973. * @param {Object} `options` See available [options](#options) for changing how matches are performed
  2974. * @return {Array} Returns an array of strings that **do not match** the given patterns.
  2975. * @api public
  2976. */
  2977. micromatch.not = (list, patterns, options = {}) => {
  2978. patterns = [].concat(patterns).map(String);
  2979. let result = new Set();
  2980. let items = [];
  2981. let onResult = state => {
  2982. if (options.onResult) options.onResult(state);
  2983. items.push(state.output);
  2984. };
  2985. let matches = micromatch(list, patterns, { ...options, onResult });
  2986. for (let item of items) {
  2987. if (!matches.includes(item)) {
  2988. result.add(item);
  2989. }
  2990. }
  2991. return [...result];
  2992. };
  2993. /**
  2994. * Returns true if the given `string` contains the given pattern. Similar
  2995. * to [.isMatch](#isMatch) but the pattern can match any part of the string.
  2996. *
  2997. * ```js
  2998. * var mm = require('micromatch');
  2999. * // mm.contains(string, pattern[, options]);
  3000. *
  3001. * console.log(mm.contains('aa/bb/cc', '*b'));
  3002. * //=> true
  3003. * console.log(mm.contains('aa/bb/cc', '*d'));
  3004. * //=> false
  3005. * ```
  3006. * @param {String} `str` The string to match.
  3007. * @param {String|Array} `patterns` Glob pattern to use for matching.
  3008. * @param {Object} `options` See available [options](#options) for changing how matches are performed
  3009. * @return {Boolean} Returns true if the patter matches any part of `str`.
  3010. * @api public
  3011. */
  3012. micromatch.contains = (str, pattern, options) => {
  3013. if (typeof str !== 'string') {
  3014. throw new TypeError(`Expected a string: "${util.inspect(str)}"`);
  3015. }
  3016. if (Array.isArray(pattern)) {
  3017. return pattern.some(p => micromatch.contains(str, p, options));
  3018. }
  3019. if (typeof pattern === 'string') {
  3020. if (isEmptyString(str) || isEmptyString(pattern)) {
  3021. return false;
  3022. }
  3023. if (str.includes(pattern) || (str.startsWith('./') && str.slice(2).includes(pattern))) {
  3024. return true;
  3025. }
  3026. }
  3027. return micromatch.isMatch(str, pattern, { ...options, contains: true });
  3028. };
  3029. /**
  3030. * Filter the keys of the given object with the given `glob` pattern
  3031. * and `options`. Does not attempt to match nested keys. If you need this feature,
  3032. * use [glob-object][] instead.
  3033. *
  3034. * ```js
  3035. * const mm = require('micromatch');
  3036. * // mm.matchKeys(object, patterns[, options]);
  3037. *
  3038. * const obj = { aa: 'a', ab: 'b', ac: 'c' };
  3039. * console.log(mm.matchKeys(obj, '*b'));
  3040. * //=> { ab: 'b' }
  3041. * ```
  3042. * @param {Object} `object` The object with keys to filter.
  3043. * @param {String|Array} `patterns` One or more glob patterns to use for matching.
  3044. * @param {Object} `options` See available [options](#options) for changing how matches are performed
  3045. * @return {Object} Returns an object with only keys that match the given patterns.
  3046. * @api public
  3047. */
  3048. micromatch.matchKeys = (obj, patterns, options) => {
  3049. if (!utils.isObject(obj)) {
  3050. throw new TypeError('Expected the first argument to be an object');
  3051. }
  3052. let keys = micromatch(Object.keys(obj), patterns, options);
  3053. let res = {};
  3054. for (let key of keys) res[key] = obj[key];
  3055. return res;
  3056. };
  3057. /**
  3058. * Returns true if some of the strings in the given `list` match any of the given glob `patterns`.
  3059. *
  3060. * ```js
  3061. * const mm = require('micromatch');
  3062. * // mm.some(list, patterns[, options]);
  3063. *
  3064. * console.log(mm.some(['foo.js', 'bar.js'], ['*.js', '!foo.js']));
  3065. * // true
  3066. * console.log(mm.some(['foo.js'], ['*.js', '!foo.js']));
  3067. * // false
  3068. * ```
  3069. * @param {String|Array} `list` The string or array of strings to test. Returns as soon as the first match is found.
  3070. * @param {String|Array} `patterns` One or more glob patterns to use for matching.
  3071. * @param {Object} `options` See available [options](#options) for changing how matches are performed
  3072. * @return {Boolean} Returns true if any patterns match `str`
  3073. * @api public
  3074. */
  3075. micromatch.some = (list, patterns, options) => {
  3076. let items = [].concat(list);
  3077. for (let pattern of [].concat(patterns)) {
  3078. let isMatch = picomatch$2(String(pattern), options);
  3079. if (items.some(item => isMatch(item))) {
  3080. return true;
  3081. }
  3082. }
  3083. return false;
  3084. };
  3085. /**
  3086. * Returns true if every string in the given `list` matches
  3087. * any of the given glob `patterns`.
  3088. *
  3089. * ```js
  3090. * const mm = require('micromatch');
  3091. * // mm.every(list, patterns[, options]);
  3092. *
  3093. * console.log(mm.every('foo.js', ['foo.js']));
  3094. * // true
  3095. * console.log(mm.every(['foo.js', 'bar.js'], ['*.js']));
  3096. * // true
  3097. * console.log(mm.every(['foo.js', 'bar.js'], ['*.js', '!foo.js']));
  3098. * // false
  3099. * console.log(mm.every(['foo.js'], ['*.js', '!foo.js']));
  3100. * // false
  3101. * ```
  3102. * @param {String|Array} `list` The string or array of strings to test.
  3103. * @param {String|Array} `patterns` One or more glob patterns to use for matching.
  3104. * @param {Object} `options` See available [options](#options) for changing how matches are performed
  3105. * @return {Boolean} Returns true if any patterns match `str`
  3106. * @api public
  3107. */
  3108. micromatch.every = (list, patterns, options) => {
  3109. let items = [].concat(list);
  3110. for (let pattern of [].concat(patterns)) {
  3111. let isMatch = picomatch$2(String(pattern), options);
  3112. if (!items.every(item => isMatch(item))) {
  3113. return false;
  3114. }
  3115. }
  3116. return true;
  3117. };
  3118. /**
  3119. * Returns true if **all** of the given `patterns` match
  3120. * the specified string.
  3121. *
  3122. * ```js
  3123. * const mm = require('micromatch');
  3124. * // mm.all(string, patterns[, options]);
  3125. *
  3126. * console.log(mm.all('foo.js', ['foo.js']));
  3127. * // true
  3128. *
  3129. * console.log(mm.all('foo.js', ['*.js', '!foo.js']));
  3130. * // false
  3131. *
  3132. * console.log(mm.all('foo.js', ['*.js', 'foo.js']));
  3133. * // true
  3134. *
  3135. * console.log(mm.all('foo.js', ['*.js', 'f*', '*o*', '*o.js']));
  3136. * // true
  3137. * ```
  3138. * @param {String|Array} `str` The string to test.
  3139. * @param {String|Array} `patterns` One or more glob patterns to use for matching.
  3140. * @param {Object} `options` See available [options](#options) for changing how matches are performed
  3141. * @return {Boolean} Returns true if any patterns match `str`
  3142. * @api public
  3143. */
  3144. micromatch.all = (str, patterns, options) => {
  3145. if (typeof str !== 'string') {
  3146. throw new TypeError(`Expected a string: "${util.inspect(str)}"`);
  3147. }
  3148. return [].concat(patterns).every(p => picomatch$2(p, options)(str));
  3149. };
  3150. /**
  3151. * Returns an array of matches captured by `pattern` in `string, or `null` if the pattern did not match.
  3152. *
  3153. * ```js
  3154. * const mm = require('micromatch');
  3155. * // mm.capture(pattern, string[, options]);
  3156. *
  3157. * console.log(mm.capture('test/*.js', 'test/foo.js'));
  3158. * //=> ['foo']
  3159. * console.log(mm.capture('test/*.js', 'foo/bar.css'));
  3160. * //=> null
  3161. * ```
  3162. * @param {String} `glob` Glob pattern to use for matching.
  3163. * @param {String} `input` String to match
  3164. * @param {Object} `options` See available [options](#options) for changing how matches are performed
  3165. * @return {Boolean} Returns an array of captures if the input matches the glob pattern, otherwise `null`.
  3166. * @api public
  3167. */
  3168. micromatch.capture = (glob, input, options) => {
  3169. let posix = utils.isWindows(options);
  3170. let regex = picomatch$2.makeRe(String(glob), { ...options, capture: true });
  3171. let match = regex.exec(posix ? utils.toPosixSlashes(input) : input);
  3172. if (match) {
  3173. return match.slice(1).map(v => v === void 0 ? '' : v);
  3174. }
  3175. };
  3176. /**
  3177. * Create a regular expression from the given glob `pattern`.
  3178. *
  3179. * ```js
  3180. * const mm = require('micromatch');
  3181. * // mm.makeRe(pattern[, options]);
  3182. *
  3183. * console.log(mm.makeRe('*.js'));
  3184. * //=> /^(?:(\.[\\\/])?(?!\.)(?=.)[^\/]*?\.js)$/
  3185. * ```
  3186. * @param {String} `pattern` A glob pattern to convert to regex.
  3187. * @param {Object} `options`
  3188. * @return {RegExp} Returns a regex created from the given pattern.
  3189. * @api public
  3190. */
  3191. micromatch.makeRe = (...args) => picomatch$2.makeRe(...args);
  3192. /**
  3193. * Scan a glob pattern to separate the pattern into segments. Used
  3194. * by the [split](#split) method.
  3195. *
  3196. * ```js
  3197. * const mm = require('micromatch');
  3198. * const state = mm.scan(pattern[, options]);
  3199. * ```
  3200. * @param {String} `pattern`
  3201. * @param {Object} `options`
  3202. * @return {Object} Returns an object with
  3203. * @api public
  3204. */
  3205. micromatch.scan = (...args) => picomatch$2.scan(...args);
  3206. /**
  3207. * Parse a glob pattern to create the source string for a regular
  3208. * expression.
  3209. *
  3210. * ```js
  3211. * const mm = require('micromatch');
  3212. * const state = mm(pattern[, options]);
  3213. * ```
  3214. * @param {String} `glob`
  3215. * @param {Object} `options`
  3216. * @return {Object} Returns an object with useful properties and output to be used as regex source string.
  3217. * @api public
  3218. */
  3219. micromatch.parse = (patterns, options) => {
  3220. let res = [];
  3221. for (let pattern of [].concat(patterns || [])) {
  3222. for (let str of braces$1(String(pattern), options)) {
  3223. res.push(picomatch$2.parse(str, options));
  3224. }
  3225. }
  3226. return res;
  3227. };
  3228. /**
  3229. * Process the given brace `pattern`.
  3230. *
  3231. * ```js
  3232. * const { braces } = require('micromatch');
  3233. * console.log(braces('foo/{a,b,c}/bar'));
  3234. * //=> [ 'foo/(a|b|c)/bar' ]
  3235. *
  3236. * console.log(braces('foo/{a,b,c}/bar', { expand: true }));
  3237. * //=> [ 'foo/a/bar', 'foo/b/bar', 'foo/c/bar' ]
  3238. * ```
  3239. * @param {String} `pattern` String with brace pattern to process.
  3240. * @param {Object} `options` Any [options](#options) to change how expansion is performed. See the [braces][] library for all available options.
  3241. * @return {Array}
  3242. * @api public
  3243. */
  3244. micromatch.braces = (pattern, options) => {
  3245. if (typeof pattern !== 'string') throw new TypeError('Expected a string');
  3246. if ((options && options.nobrace === true) || !/\{.*\}/.test(pattern)) {
  3247. return [pattern];
  3248. }
  3249. return braces$1(pattern, options);
  3250. };
  3251. /**
  3252. * Expand braces
  3253. */
  3254. micromatch.braceExpand = (pattern, options) => {
  3255. if (typeof pattern !== 'string') throw new TypeError('Expected a string');
  3256. return micromatch.braces(pattern, { ...options, expand: true });
  3257. };
  3258. /**
  3259. * Expose micromatch
  3260. */
  3261. var micromatch_1 = micromatch;
  3262. function ensureArray(thing) {
  3263. if (Array.isArray(thing))
  3264. return thing;
  3265. if (thing == undefined)
  3266. return [];
  3267. return [thing];
  3268. }
  3269. function getMatcherString(id, resolutionBase) {
  3270. if (resolutionBase === false) {
  3271. return id;
  3272. }
  3273. return resolve(...(typeof resolutionBase === 'string' ? [resolutionBase, id] : [id]));
  3274. }
  3275. const createFilter = function createFilter(include, exclude, options) {
  3276. const resolutionBase = options && options.resolve;
  3277. const getMatcher = (id) => {
  3278. return id instanceof RegExp
  3279. ? id
  3280. : {
  3281. test: micromatch_1.matcher(getMatcherString(id, resolutionBase)
  3282. .split(sep)
  3283. .join('/'), { dot: true })
  3284. };
  3285. };
  3286. const includeMatchers = ensureArray(include).map(getMatcher);
  3287. const excludeMatchers = ensureArray(exclude).map(getMatcher);
  3288. return function (id) {
  3289. if (typeof id !== 'string')
  3290. return false;
  3291. if (/\0/.test(id))
  3292. return false;
  3293. id = id.split(sep).join('/');
  3294. for (let i = 0; i < excludeMatchers.length; ++i) {
  3295. const matcher = excludeMatchers[i];
  3296. if (matcher.test(id))
  3297. return false;
  3298. }
  3299. for (let i = 0; i < includeMatchers.length; ++i) {
  3300. const matcher = includeMatchers[i];
  3301. if (matcher.test(id))
  3302. return true;
  3303. }
  3304. return !includeMatchers.length;
  3305. };
  3306. };
  3307. const commandAliases = {
  3308. c: 'config',
  3309. d: 'dir',
  3310. e: 'external',
  3311. f: 'format',
  3312. g: 'globals',
  3313. h: 'help',
  3314. i: 'input',
  3315. m: 'sourcemap',
  3316. n: 'name',
  3317. o: 'file',
  3318. p: 'plugin',
  3319. v: 'version',
  3320. w: 'watch'
  3321. };
  3322. function mergeOptions(config, rawCommandOptions = { external: [], globals: undefined }, defaultOnWarnHandler = defaultOnWarn) {
  3323. const command = getCommandOptions(rawCommandOptions);
  3324. const inputOptions = mergeInputOptions(config, command, defaultOnWarnHandler);
  3325. const warn = inputOptions.onwarn;
  3326. if (command.output) {
  3327. Object.assign(command, command.output);
  3328. }
  3329. const outputOptionsArray = ensureArray$1(config.output);
  3330. if (outputOptionsArray.length === 0)
  3331. outputOptionsArray.push({});
  3332. const outputOptions = outputOptionsArray.map(singleOutputOptions => mergeOutputOptions(singleOutputOptions, command, warn));
  3333. warnUnknownOptions(command, Object.keys(inputOptions).concat(Object.keys(outputOptions[0]).filter(option => option !== 'sourcemapPathTransform'), Object.keys(commandAliases), 'config', 'environment', 'plugin', 'silent', 'failAfterWarnings', 'stdin', 'waitForBundleInput'), 'CLI flags', warn, /^_$|output$|config/);
  3334. inputOptions.output = outputOptions;
  3335. return inputOptions;
  3336. }
  3337. function getCommandOptions(rawCommandOptions) {
  3338. const external = rawCommandOptions.external && typeof rawCommandOptions.external === 'string'
  3339. ? rawCommandOptions.external.split(',')
  3340. : [];
  3341. return {
  3342. ...rawCommandOptions,
  3343. external,
  3344. globals: typeof rawCommandOptions.globals === 'string'
  3345. ? rawCommandOptions.globals.split(',').reduce((globals, globalDefinition) => {
  3346. const [id, variableName] = globalDefinition.split(':');
  3347. globals[id] = variableName;
  3348. if (external.indexOf(id) === -1) {
  3349. external.push(id);
  3350. }
  3351. return globals;
  3352. }, Object.create(null))
  3353. : undefined
  3354. };
  3355. }
  3356. function mergeInputOptions(config, overrides, defaultOnWarnHandler) {
  3357. const getOption = (name) => { var _a; return (_a = overrides[name]) !== null && _a !== void 0 ? _a : config[name]; };
  3358. const inputOptions = {
  3359. acorn: getOption('acorn'),
  3360. acornInjectPlugins: config.acornInjectPlugins,
  3361. cache: config.cache,
  3362. context: getOption('context'),
  3363. experimentalCacheExpiry: getOption('experimentalCacheExpiry'),
  3364. external: getExternal(config, overrides),
  3365. inlineDynamicImports: getOption('inlineDynamicImports'),
  3366. input: getOption('input') || [],
  3367. manualChunks: getOption('manualChunks'),
  3368. moduleContext: getOption('moduleContext'),
  3369. onwarn: getOnWarn(config, defaultOnWarnHandler),
  3370. perf: getOption('perf'),
  3371. plugins: ensureArray$1(config.plugins),
  3372. preserveEntrySignatures: getOption('preserveEntrySignatures'),
  3373. preserveModules: getOption('preserveModules'),
  3374. preserveSymlinks: getOption('preserveSymlinks'),
  3375. shimMissingExports: getOption('shimMissingExports'),
  3376. strictDeprecations: getOption('strictDeprecations'),
  3377. treeshake: getObjectOption(config, overrides, 'treeshake'),
  3378. watch: getWatch(config, overrides, 'watch')
  3379. };
  3380. warnUnknownOptions(config, Object.keys(inputOptions), 'input options', inputOptions.onwarn, /^output$/);
  3381. return inputOptions;
  3382. }
  3383. const getExternal = (config, overrides) => {
  3384. const configExternal = config.external;
  3385. return typeof configExternal === 'function'
  3386. ? (source, importer, isResolved) => configExternal(source, importer, isResolved) || overrides.external.indexOf(source) !== -1
  3387. : ensureArray$1(configExternal).concat(overrides.external);
  3388. };
  3389. const getOnWarn = (config, defaultOnWarnHandler) => config.onwarn
  3390. ? warning => config.onwarn(warning, defaultOnWarnHandler)
  3391. : defaultOnWarnHandler;
  3392. const getObjectOption = (config, overrides, name) => {
  3393. const commandOption = normalizeObjectOptionValue(overrides[name]);
  3394. const configOption = normalizeObjectOptionValue(config[name]);
  3395. if (commandOption !== undefined) {
  3396. return commandOption && { ...configOption, ...commandOption };
  3397. }
  3398. return configOption;
  3399. };
  3400. const getWatch = (config, overrides, name) => config.watch !== false && getObjectOption(config, overrides, name);
  3401. const normalizeObjectOptionValue = (optionValue) => {
  3402. if (!optionValue) {
  3403. return optionValue;
  3404. }
  3405. if (Array.isArray(optionValue)) {
  3406. return optionValue.reduce((result, value) => value && result && { ...result, ...value }, {});
  3407. }
  3408. if (typeof optionValue !== 'object') {
  3409. return {};
  3410. }
  3411. return optionValue;
  3412. };
  3413. function mergeOutputOptions(config, overrides, warn) {
  3414. const getOption = (name) => { var _a; return (_a = overrides[name]) !== null && _a !== void 0 ? _a : config[name]; };
  3415. const outputOptions = {
  3416. amd: getObjectOption(config, overrides, 'amd'),
  3417. assetFileNames: getOption('assetFileNames'),
  3418. banner: getOption('banner'),
  3419. chunkFileNames: getOption('chunkFileNames'),
  3420. compact: getOption('compact'),
  3421. dir: getOption('dir'),
  3422. dynamicImportFunction: getOption('dynamicImportFunction'),
  3423. entryFileNames: getOption('entryFileNames'),
  3424. esModule: getOption('esModule'),
  3425. exports: getOption('exports'),
  3426. extend: getOption('extend'),
  3427. externalLiveBindings: getOption('externalLiveBindings'),
  3428. file: getOption('file'),
  3429. footer: getOption('footer'),
  3430. format: getOption('format'),
  3431. freeze: getOption('freeze'),
  3432. globals: getOption('globals'),
  3433. hoistTransitiveImports: getOption('hoistTransitiveImports'),
  3434. indent: getOption('indent'),
  3435. inlineDynamicImports: getOption('inlineDynamicImports'),
  3436. interop: getOption('interop'),
  3437. intro: getOption('intro'),
  3438. manualChunks: getOption('manualChunks'),
  3439. minifyInternalExports: getOption('minifyInternalExports'),
  3440. name: getOption('name'),
  3441. namespaceToStringTag: getOption('namespaceToStringTag'),
  3442. noConflict: getOption('noConflict'),
  3443. outro: getOption('outro'),
  3444. paths: getOption('paths'),
  3445. plugins: ensureArray$1(config.plugins),
  3446. preferConst: getOption('preferConst'),
  3447. preserveModules: getOption('preserveModules'),
  3448. preserveModulesRoot: getOption('preserveModulesRoot'),
  3449. sourcemap: getOption('sourcemap'),
  3450. sourcemapExcludeSources: getOption('sourcemapExcludeSources'),
  3451. sourcemapFile: getOption('sourcemapFile'),
  3452. sourcemapPathTransform: getOption('sourcemapPathTransform'),
  3453. strict: getOption('strict'),
  3454. systemNullSetters: getOption('systemNullSetters'),
  3455. validate: getOption('validate')
  3456. };
  3457. warnUnknownOptions(config, Object.keys(outputOptions), 'output options', warn);
  3458. return outputOptions;
  3459. }
  3460. var chokidar = {};
  3461. const fs$3 = fs$4;
  3462. const { Readable } = require$$1;
  3463. const sysPath$3 = require$$0$2;
  3464. const { promisify: promisify$3 } = require$$0$1;
  3465. const picomatch$1 = picomatch$3;
  3466. const readdir$1 = promisify$3(fs$3.readdir);
  3467. const stat$3 = promisify$3(fs$3.stat);
  3468. const lstat$2 = promisify$3(fs$3.lstat);
  3469. const realpath$1 = promisify$3(fs$3.realpath);
  3470. /**
  3471. * @typedef {Object} EntryInfo
  3472. * @property {String} path
  3473. * @property {String} fullPath
  3474. * @property {fs.Stats=} stats
  3475. * @property {fs.Dirent=} dirent
  3476. * @property {String} basename
  3477. */
  3478. const BANG$2 = '!';
  3479. const NORMAL_FLOW_ERRORS = new Set(['ENOENT', 'EPERM', 'EACCES', 'ELOOP']);
  3480. const FILE_TYPE = 'files';
  3481. const DIR_TYPE = 'directories';
  3482. const FILE_DIR_TYPE = 'files_directories';
  3483. const EVERYTHING_TYPE = 'all';
  3484. const ALL_TYPES = [FILE_TYPE, DIR_TYPE, FILE_DIR_TYPE, EVERYTHING_TYPE];
  3485. const isNormalFlowError = error => NORMAL_FLOW_ERRORS.has(error.code);
  3486. const normalizeFilter = filter => {
  3487. if (filter === undefined) return;
  3488. if (typeof filter === 'function') return filter;
  3489. if (typeof filter === 'string') {
  3490. const glob = picomatch$1(filter.trim());
  3491. return entry => glob(entry.basename);
  3492. }
  3493. if (Array.isArray(filter)) {
  3494. const positive = [];
  3495. const negative = [];
  3496. for (const item of filter) {
  3497. const trimmed = item.trim();
  3498. if (trimmed.charAt(0) === BANG$2) {
  3499. negative.push(picomatch$1(trimmed.slice(1)));
  3500. } else {
  3501. positive.push(picomatch$1(trimmed));
  3502. }
  3503. }
  3504. if (negative.length > 0) {
  3505. if (positive.length > 0) {
  3506. return entry =>
  3507. positive.some(f => f(entry.basename)) && !negative.some(f => f(entry.basename));
  3508. }
  3509. return entry => !negative.some(f => f(entry.basename));
  3510. }
  3511. return entry => positive.some(f => f(entry.basename));
  3512. }
  3513. };
  3514. class ReaddirpStream extends Readable {
  3515. static get defaultOptions() {
  3516. return {
  3517. root: '.',
  3518. /* eslint-disable no-unused-vars */
  3519. fileFilter: (path) => true,
  3520. directoryFilter: (path) => true,
  3521. /* eslint-enable no-unused-vars */
  3522. type: FILE_TYPE,
  3523. lstat: false,
  3524. depth: 2147483648,
  3525. alwaysStat: false
  3526. };
  3527. }
  3528. constructor(options = {}) {
  3529. super({
  3530. objectMode: true,
  3531. autoDestroy: true,
  3532. highWaterMark: options.highWaterMark || 4096
  3533. });
  3534. const opts = { ...ReaddirpStream.defaultOptions, ...options };
  3535. const { root, type } = opts;
  3536. this._fileFilter = normalizeFilter(opts.fileFilter);
  3537. this._directoryFilter = normalizeFilter(opts.directoryFilter);
  3538. const statMethod = opts.lstat ? lstat$2 : stat$3;
  3539. // Use bigint stats if it's windows and stat() supports options (node 10+).
  3540. if (process.platform === 'win32' && stat$3.length === 3) {
  3541. this._stat = path => statMethod(path, { bigint: true });
  3542. } else {
  3543. this._stat = statMethod;
  3544. }
  3545. this._maxDepth = opts.depth;
  3546. this._wantsDir = [DIR_TYPE, FILE_DIR_TYPE, EVERYTHING_TYPE].includes(type);
  3547. this._wantsFile = [FILE_TYPE, FILE_DIR_TYPE, EVERYTHING_TYPE].includes(type);
  3548. this._wantsEverything = type === EVERYTHING_TYPE;
  3549. this._root = sysPath$3.resolve(root);
  3550. this._isDirent = ('Dirent' in fs$3) && !opts.alwaysStat;
  3551. this._statsProp = this._isDirent ? 'dirent' : 'stats';
  3552. this._rdOptions = { encoding: 'utf8', withFileTypes: this._isDirent };
  3553. // Launch stream with one parent, the root dir.
  3554. this.parents = [this._exploreDir(root, 1)];
  3555. this.reading = false;
  3556. this.parent = undefined;
  3557. }
  3558. async _read(batch) {
  3559. if (this.reading) return;
  3560. this.reading = true;
  3561. try {
  3562. while (!this.destroyed && batch > 0) {
  3563. const { path, depth, files = [] } = this.parent || {};
  3564. if (files.length > 0) {
  3565. const slice = files.splice(0, batch).map(dirent => this._formatEntry(dirent, path));
  3566. for (const entry of await Promise.all(slice)) {
  3567. if (this.destroyed) return;
  3568. const entryType = await this._getEntryType(entry);
  3569. if (entryType === 'directory' && this._directoryFilter(entry)) {
  3570. if (depth <= this._maxDepth) {
  3571. this.parents.push(this._exploreDir(entry.fullPath, depth + 1));
  3572. }
  3573. if (this._wantsDir) {
  3574. this.push(entry);
  3575. batch--;
  3576. }
  3577. } else if ((entryType === 'file' || this._includeAsFile(entry)) && this._fileFilter(entry)) {
  3578. if (this._wantsFile) {
  3579. this.push(entry);
  3580. batch--;
  3581. }
  3582. }
  3583. }
  3584. } else {
  3585. const parent = this.parents.pop();
  3586. if (!parent) {
  3587. this.push(null);
  3588. break;
  3589. }
  3590. this.parent = await parent;
  3591. if (this.destroyed) return;
  3592. }
  3593. }
  3594. } catch (error) {
  3595. this.destroy(error);
  3596. } finally {
  3597. this.reading = false;
  3598. }
  3599. }
  3600. async _exploreDir(path, depth) {
  3601. let files;
  3602. try {
  3603. files = await readdir$1(path, this._rdOptions);
  3604. } catch (error) {
  3605. this._onError(error);
  3606. }
  3607. return {files, depth, path};
  3608. }
  3609. async _formatEntry(dirent, path) {
  3610. let entry;
  3611. try {
  3612. const basename = this._isDirent ? dirent.name : dirent;
  3613. const fullPath = sysPath$3.resolve(sysPath$3.join(path, basename));
  3614. entry = {path: sysPath$3.relative(this._root, fullPath), fullPath, basename};
  3615. entry[this._statsProp] = this._isDirent ? dirent : await this._stat(fullPath);
  3616. } catch (err) {
  3617. this._onError(err);
  3618. }
  3619. return entry;
  3620. }
  3621. _onError(err) {
  3622. if (isNormalFlowError(err) && !this.destroyed) {
  3623. this.emit('warn', err);
  3624. } else {
  3625. this.destroy(err);
  3626. }
  3627. }
  3628. async _getEntryType(entry) {
  3629. // entry may be undefined, because a warning or an error were emitted
  3630. // and the statsProp is undefined
  3631. const stats = entry && entry[this._statsProp];
  3632. if (!stats) {
  3633. return;
  3634. }
  3635. if (stats.isFile()) {
  3636. return 'file';
  3637. }
  3638. if (stats.isDirectory()) {
  3639. return 'directory';
  3640. }
  3641. if (stats && stats.isSymbolicLink()) {
  3642. const full = entry.fullPath;
  3643. try {
  3644. const entryRealPath = await realpath$1(full);
  3645. const entryRealPathStats = await lstat$2(entryRealPath);
  3646. if (entryRealPathStats.isFile()) {
  3647. return 'file';
  3648. }
  3649. if (entryRealPathStats.isDirectory()) {
  3650. const len = entryRealPath.length;
  3651. if (full.startsWith(entryRealPath) && full.substr(len, 1) === sysPath$3.sep) {
  3652. return this._onError(new Error(
  3653. `Circular symlink detected: "${full}" points to "${entryRealPath}"`
  3654. ));
  3655. }
  3656. return 'directory';
  3657. }
  3658. } catch (error) {
  3659. this._onError(error);
  3660. }
  3661. }
  3662. }
  3663. _includeAsFile(entry) {
  3664. const stats = entry && entry[this._statsProp];
  3665. return stats && this._wantsEverything && !stats.isDirectory();
  3666. }
  3667. }
  3668. /**
  3669. * @typedef {Object} ReaddirpArguments
  3670. * @property {Function=} fileFilter
  3671. * @property {Function=} directoryFilter
  3672. * @property {String=} type
  3673. * @property {Number=} depth
  3674. * @property {String=} root
  3675. * @property {Boolean=} lstat
  3676. * @property {Boolean=} bigint
  3677. */
  3678. /**
  3679. * Main function which ends up calling readdirRec and reads all files and directories in given root recursively.
  3680. * @param {String} root Root directory
  3681. * @param {ReaddirpArguments=} options Options to specify root (start directory), filters and recursion depth
  3682. */
  3683. const readdirp$1 = (root, options = {}) => {
  3684. let type = options.entryType || options.type;
  3685. if (type === 'both') type = FILE_DIR_TYPE; // backwards-compatibility
  3686. if (type) options.type = type;
  3687. if (!root) {
  3688. throw new Error('readdirp: root argument is required. Usage: readdirp(root, options)');
  3689. } else if (typeof root !== 'string') {
  3690. throw new TypeError('readdirp: root argument must be a string. Usage: readdirp(root, options)');
  3691. } else if (type && !ALL_TYPES.includes(type)) {
  3692. throw new Error(`readdirp: Invalid type passed. Use one of ${ALL_TYPES.join(', ')}`);
  3693. }
  3694. options.root = root;
  3695. return new ReaddirpStream(options);
  3696. };
  3697. const readdirpPromise = (root, options = {}) => {
  3698. return new Promise((resolve, reject) => {
  3699. const files = [];
  3700. readdirp$1(root, options)
  3701. .on('data', entry => files.push(entry))
  3702. .on('end', () => resolve(files))
  3703. .on('error', error => reject(error));
  3704. });
  3705. };
  3706. readdirp$1.promise = readdirpPromise;
  3707. readdirp$1.ReaddirpStream = ReaddirpStream;
  3708. readdirp$1.default = readdirp$1;
  3709. var readdirp_1 = readdirp$1;
  3710. var anymatch$2 = {exports: {}};
  3711. /*!
  3712. * normalize-path <https://github.com/jonschlinkert/normalize-path>
  3713. *
  3714. * Copyright (c) 2014-2018, Jon Schlinkert.
  3715. * Released under the MIT License.
  3716. */
  3717. var normalizePath$2 = function(path, stripTrailing) {
  3718. if (typeof path !== 'string') {
  3719. throw new TypeError('expected path to be a string');
  3720. }
  3721. if (path === '\\' || path === '/') return '/';
  3722. var len = path.length;
  3723. if (len <= 1) return path;
  3724. // ensure that win32 namespaces has two leading slashes, so that the path is
  3725. // handled properly by the win32 version of path.parse() after being normalized
  3726. // https://msdn.microsoft.com/library/windows/desktop/aa365247(v=vs.85).aspx#namespaces
  3727. var prefix = '';
  3728. if (len > 4 && path[3] === '\\') {
  3729. var ch = path[2];
  3730. if ((ch === '?' || ch === '.') && path.slice(0, 2) === '\\\\') {
  3731. path = path.slice(2);
  3732. prefix = '//';
  3733. }
  3734. }
  3735. var segs = path.split(/[/\\]+/);
  3736. if (stripTrailing !== false && segs[segs.length - 1] === '') {
  3737. segs.pop();
  3738. }
  3739. return prefix + segs.join('/');
  3740. };
  3741. Object.defineProperty(anymatch$2.exports, "__esModule", { value: true });
  3742. const picomatch = picomatch$3;
  3743. const normalizePath$1 = normalizePath$2;
  3744. /**
  3745. * @typedef {(testString: string) => boolean} AnymatchFn
  3746. * @typedef {string|RegExp|AnymatchFn} AnymatchPattern
  3747. * @typedef {AnymatchPattern|AnymatchPattern[]} AnymatchMatcher
  3748. */
  3749. const BANG$1 = '!';
  3750. const DEFAULT_OPTIONS = {returnIndex: false};
  3751. const arrify$1 = (item) => Array.isArray(item) ? item : [item];
  3752. /**
  3753. * @param {AnymatchPattern} matcher
  3754. * @param {object} options
  3755. * @returns {AnymatchFn}
  3756. */
  3757. const createPattern = (matcher, options) => {
  3758. if (typeof matcher === 'function') {
  3759. return matcher;
  3760. }
  3761. if (typeof matcher === 'string') {
  3762. const glob = picomatch(matcher, options);
  3763. return (string) => matcher === string || glob(string);
  3764. }
  3765. if (matcher instanceof RegExp) {
  3766. return (string) => matcher.test(string);
  3767. }
  3768. return (string) => false;
  3769. };
  3770. /**
  3771. * @param {Array<Function>} patterns
  3772. * @param {Array<Function>} negPatterns
  3773. * @param {String|Array} args
  3774. * @param {Boolean} returnIndex
  3775. * @returns {boolean|number}
  3776. */
  3777. const matchPatterns = (patterns, negPatterns, args, returnIndex) => {
  3778. const isList = Array.isArray(args);
  3779. const _path = isList ? args[0] : args;
  3780. if (!isList && typeof _path !== 'string') {
  3781. throw new TypeError('anymatch: second argument must be a string: got ' +
  3782. Object.prototype.toString.call(_path))
  3783. }
  3784. const path = normalizePath$1(_path);
  3785. for (let index = 0; index < negPatterns.length; index++) {
  3786. const nglob = negPatterns[index];
  3787. if (nglob(path)) {
  3788. return returnIndex ? -1 : false;
  3789. }
  3790. }
  3791. const applied = isList && [path].concat(args.slice(1));
  3792. for (let index = 0; index < patterns.length; index++) {
  3793. const pattern = patterns[index];
  3794. if (isList ? pattern(...applied) : pattern(path)) {
  3795. return returnIndex ? index : true;
  3796. }
  3797. }
  3798. return returnIndex ? -1 : false;
  3799. };
  3800. /**
  3801. * @param {AnymatchMatcher} matchers
  3802. * @param {Array|string} testString
  3803. * @param {object} options
  3804. * @returns {boolean|number|Function}
  3805. */
  3806. const anymatch$1 = (matchers, testString, options = DEFAULT_OPTIONS) => {
  3807. if (matchers == null) {
  3808. throw new TypeError('anymatch: specify first argument');
  3809. }
  3810. const opts = typeof options === 'boolean' ? {returnIndex: options} : options;
  3811. const returnIndex = opts.returnIndex || false;
  3812. // Early cache for matchers.
  3813. const mtchers = arrify$1(matchers);
  3814. const negatedGlobs = mtchers
  3815. .filter(item => typeof item === 'string' && item.charAt(0) === BANG$1)
  3816. .map(item => item.slice(1))
  3817. .map(item => picomatch(item, opts));
  3818. const patterns = mtchers.map(matcher => createPattern(matcher, opts));
  3819. if (testString == null) {
  3820. return (testString, ri = false) => {
  3821. const returnIndex = typeof ri === 'boolean' ? ri : false;
  3822. return matchPatterns(patterns, negatedGlobs, testString, returnIndex);
  3823. }
  3824. }
  3825. return matchPatterns(patterns, negatedGlobs, testString, returnIndex);
  3826. };
  3827. anymatch$1.default = anymatch$1;
  3828. anymatch$2.exports = anymatch$1;
  3829. /*!
  3830. * is-extglob <https://github.com/jonschlinkert/is-extglob>
  3831. *
  3832. * Copyright (c) 2014-2016, Jon Schlinkert.
  3833. * Licensed under the MIT License.
  3834. */
  3835. var isExtglob$1 = function isExtglob(str) {
  3836. if (typeof str !== 'string' || str === '') {
  3837. return false;
  3838. }
  3839. var match;
  3840. while ((match = /(\\).|([@?!+*]\(.*\))/g.exec(str))) {
  3841. if (match[2]) return true;
  3842. str = str.slice(match.index + match[0].length);
  3843. }
  3844. return false;
  3845. };
  3846. /*!
  3847. * is-glob <https://github.com/jonschlinkert/is-glob>
  3848. *
  3849. * Copyright (c) 2014-2017, Jon Schlinkert.
  3850. * Released under the MIT License.
  3851. */
  3852. var isExtglob = isExtglob$1;
  3853. var chars = { '{': '}', '(': ')', '[': ']'};
  3854. var strictRegex = /\\(.)|(^!|\*|[\].+)]\?|\[[^\\\]]+\]|\{[^\\}]+\}|\(\?[:!=][^\\)]+\)|\([^|]+\|[^\\)]+\))/;
  3855. var relaxedRegex = /\\(.)|(^!|[*?{}()[\]]|\(\?)/;
  3856. var isGlob$2 = function isGlob(str, options) {
  3857. if (typeof str !== 'string' || str === '') {
  3858. return false;
  3859. }
  3860. if (isExtglob(str)) {
  3861. return true;
  3862. }
  3863. var regex = strictRegex;
  3864. var match;
  3865. // optionally relax regex
  3866. if (options && options.strict === false) {
  3867. regex = relaxedRegex;
  3868. }
  3869. while ((match = regex.exec(str))) {
  3870. if (match[2]) return true;
  3871. var idx = match.index + match[0].length;
  3872. // if an open bracket/brace/paren is escaped,
  3873. // set the index to the next closing character
  3874. var open = match[1];
  3875. var close = open ? chars[open] : null;
  3876. if (open && close) {
  3877. var n = str.indexOf(close, idx);
  3878. if (n !== -1) {
  3879. idx = n + 1;
  3880. }
  3881. }
  3882. str = str.slice(idx);
  3883. }
  3884. return false;
  3885. };
  3886. var isGlob$1 = isGlob$2;
  3887. var pathPosixDirname = require$$0$2.posix.dirname;
  3888. var isWin32 = require$$2.platform() === 'win32';
  3889. var slash = '/';
  3890. var backslash = /\\/g;
  3891. var enclosure = /[\{\[].*[\/]*.*[\}\]]$/;
  3892. var globby = /(^|[^\\])([\{\[]|\([^\)]+$)/;
  3893. var escaped = /\\([\!\*\?\|\[\]\(\)\{\}])/g;
  3894. /**
  3895. * @param {string} str
  3896. * @param {Object} opts
  3897. * @param {boolean} [opts.flipBackslashes=true]
  3898. */
  3899. var globParent$1 = function globParent(str, opts) {
  3900. var options = Object.assign({ flipBackslashes: true }, opts);
  3901. // flip windows path separators
  3902. if (options.flipBackslashes && isWin32 && str.indexOf(slash) < 0) {
  3903. str = str.replace(backslash, slash);
  3904. }
  3905. // special case for strings ending in enclosure containing path separator
  3906. if (enclosure.test(str)) {
  3907. str += slash;
  3908. }
  3909. // preserves full path in case of trailing path separator
  3910. str += 'a';
  3911. // remove path parts that are globby
  3912. do {
  3913. str = pathPosixDirname(str);
  3914. } while (isGlob$1(str) || globby.test(str));
  3915. // remove escape chars and return result
  3916. return str.replace(escaped, '$1');
  3917. };
  3918. var require$$0 = [
  3919. "3dm",
  3920. "3ds",
  3921. "3g2",
  3922. "3gp",
  3923. "7z",
  3924. "a",
  3925. "aac",
  3926. "adp",
  3927. "ai",
  3928. "aif",
  3929. "aiff",
  3930. "alz",
  3931. "ape",
  3932. "apk",
  3933. "appimage",
  3934. "ar",
  3935. "arj",
  3936. "asf",
  3937. "au",
  3938. "avi",
  3939. "bak",
  3940. "baml",
  3941. "bh",
  3942. "bin",
  3943. "bk",
  3944. "bmp",
  3945. "btif",
  3946. "bz2",
  3947. "bzip2",
  3948. "cab",
  3949. "caf",
  3950. "cgm",
  3951. "class",
  3952. "cmx",
  3953. "cpio",
  3954. "cr2",
  3955. "cur",
  3956. "dat",
  3957. "dcm",
  3958. "deb",
  3959. "dex",
  3960. "djvu",
  3961. "dll",
  3962. "dmg",
  3963. "dng",
  3964. "doc",
  3965. "docm",
  3966. "docx",
  3967. "dot",
  3968. "dotm",
  3969. "dra",
  3970. "DS_Store",
  3971. "dsk",
  3972. "dts",
  3973. "dtshd",
  3974. "dvb",
  3975. "dwg",
  3976. "dxf",
  3977. "ecelp4800",
  3978. "ecelp7470",
  3979. "ecelp9600",
  3980. "egg",
  3981. "eol",
  3982. "eot",
  3983. "epub",
  3984. "exe",
  3985. "f4v",
  3986. "fbs",
  3987. "fh",
  3988. "fla",
  3989. "flac",
  3990. "flatpak",
  3991. "fli",
  3992. "flv",
  3993. "fpx",
  3994. "fst",
  3995. "fvt",
  3996. "g3",
  3997. "gh",
  3998. "gif",
  3999. "graffle",
  4000. "gz",
  4001. "gzip",
  4002. "h261",
  4003. "h263",
  4004. "h264",
  4005. "icns",
  4006. "ico",
  4007. "ief",
  4008. "img",
  4009. "ipa",
  4010. "iso",
  4011. "jar",
  4012. "jpeg",
  4013. "jpg",
  4014. "jpgv",
  4015. "jpm",
  4016. "jxr",
  4017. "key",
  4018. "ktx",
  4019. "lha",
  4020. "lib",
  4021. "lvp",
  4022. "lz",
  4023. "lzh",
  4024. "lzma",
  4025. "lzo",
  4026. "m3u",
  4027. "m4a",
  4028. "m4v",
  4029. "mar",
  4030. "mdi",
  4031. "mht",
  4032. "mid",
  4033. "midi",
  4034. "mj2",
  4035. "mka",
  4036. "mkv",
  4037. "mmr",
  4038. "mng",
  4039. "mobi",
  4040. "mov",
  4041. "movie",
  4042. "mp3",
  4043. "mp4",
  4044. "mp4a",
  4045. "mpeg",
  4046. "mpg",
  4047. "mpga",
  4048. "mxu",
  4049. "nef",
  4050. "npx",
  4051. "numbers",
  4052. "nupkg",
  4053. "o",
  4054. "odp",
  4055. "ods",
  4056. "odt",
  4057. "oga",
  4058. "ogg",
  4059. "ogv",
  4060. "otf",
  4061. "ott",
  4062. "pages",
  4063. "pbm",
  4064. "pcx",
  4065. "pdb",
  4066. "pdf",
  4067. "pea",
  4068. "pgm",
  4069. "pic",
  4070. "png",
  4071. "pnm",
  4072. "pot",
  4073. "potm",
  4074. "potx",
  4075. "ppa",
  4076. "ppam",
  4077. "ppm",
  4078. "pps",
  4079. "ppsm",
  4080. "ppsx",
  4081. "ppt",
  4082. "pptm",
  4083. "pptx",
  4084. "psd",
  4085. "pya",
  4086. "pyc",
  4087. "pyo",
  4088. "pyv",
  4089. "qt",
  4090. "rar",
  4091. "ras",
  4092. "raw",
  4093. "resources",
  4094. "rgb",
  4095. "rip",
  4096. "rlc",
  4097. "rmf",
  4098. "rmvb",
  4099. "rpm",
  4100. "rtf",
  4101. "rz",
  4102. "s3m",
  4103. "s7z",
  4104. "scpt",
  4105. "sgi",
  4106. "shar",
  4107. "snap",
  4108. "sil",
  4109. "sketch",
  4110. "slk",
  4111. "smv",
  4112. "snk",
  4113. "so",
  4114. "stl",
  4115. "suo",
  4116. "sub",
  4117. "swf",
  4118. "tar",
  4119. "tbz",
  4120. "tbz2",
  4121. "tga",
  4122. "tgz",
  4123. "thmx",
  4124. "tif",
  4125. "tiff",
  4126. "tlz",
  4127. "ttc",
  4128. "ttf",
  4129. "txz",
  4130. "udf",
  4131. "uvh",
  4132. "uvi",
  4133. "uvm",
  4134. "uvp",
  4135. "uvs",
  4136. "uvu",
  4137. "viv",
  4138. "vob",
  4139. "war",
  4140. "wav",
  4141. "wax",
  4142. "wbmp",
  4143. "wdp",
  4144. "weba",
  4145. "webm",
  4146. "webp",
  4147. "whl",
  4148. "wim",
  4149. "wm",
  4150. "wma",
  4151. "wmv",
  4152. "wmx",
  4153. "woff",
  4154. "woff2",
  4155. "wrm",
  4156. "wvx",
  4157. "xbm",
  4158. "xif",
  4159. "xla",
  4160. "xlam",
  4161. "xls",
  4162. "xlsb",
  4163. "xlsm",
  4164. "xlsx",
  4165. "xlt",
  4166. "xltm",
  4167. "xltx",
  4168. "xm",
  4169. "xmind",
  4170. "xpi",
  4171. "xpm",
  4172. "xwd",
  4173. "xz",
  4174. "z",
  4175. "zip",
  4176. "zipx"
  4177. ];
  4178. var binaryExtensions$1 = require$$0;
  4179. const path = require$$0$2;
  4180. const binaryExtensions = binaryExtensions$1;
  4181. const extensions = new Set(binaryExtensions);
  4182. var isBinaryPath$1 = filePath => extensions.has(path.extname(filePath).slice(1).toLowerCase());
  4183. var constants = {};
  4184. (function (exports) {
  4185. const {sep} = require$$0$2;
  4186. const {platform} = process;
  4187. exports.EV_ALL = 'all';
  4188. exports.EV_READY = 'ready';
  4189. exports.EV_ADD = 'add';
  4190. exports.EV_CHANGE = 'change';
  4191. exports.EV_ADD_DIR = 'addDir';
  4192. exports.EV_UNLINK = 'unlink';
  4193. exports.EV_UNLINK_DIR = 'unlinkDir';
  4194. exports.EV_RAW = 'raw';
  4195. exports.EV_ERROR = 'error';
  4196. exports.STR_DATA = 'data';
  4197. exports.STR_END = 'end';
  4198. exports.STR_CLOSE = 'close';
  4199. exports.FSEVENT_CREATED = 'created';
  4200. exports.FSEVENT_MODIFIED = 'modified';
  4201. exports.FSEVENT_DELETED = 'deleted';
  4202. exports.FSEVENT_MOVED = 'moved';
  4203. exports.FSEVENT_CLONED = 'cloned';
  4204. exports.FSEVENT_UNKNOWN = 'unknown';
  4205. exports.FSEVENT_TYPE_FILE = 'file';
  4206. exports.FSEVENT_TYPE_DIRECTORY = 'directory';
  4207. exports.FSEVENT_TYPE_SYMLINK = 'symlink';
  4208. exports.KEY_LISTENERS = 'listeners';
  4209. exports.KEY_ERR = 'errHandlers';
  4210. exports.KEY_RAW = 'rawEmitters';
  4211. exports.HANDLER_KEYS = [exports.KEY_LISTENERS, exports.KEY_ERR, exports.KEY_RAW];
  4212. exports.DOT_SLASH = `.${sep}`;
  4213. exports.BACK_SLASH_RE = /\\/g;
  4214. exports.DOUBLE_SLASH_RE = /\/\//;
  4215. exports.SLASH_OR_BACK_SLASH_RE = /[/\\]/;
  4216. exports.DOT_RE = /\..*\.(sw[px])$|~$|\.subl.*\.tmp/;
  4217. exports.REPLACER_RE = /^\.[/\\]/;
  4218. exports.SLASH = '/';
  4219. exports.SLASH_SLASH = '//';
  4220. exports.BRACE_START = '{';
  4221. exports.BANG = '!';
  4222. exports.ONE_DOT = '.';
  4223. exports.TWO_DOTS = '..';
  4224. exports.STAR = '*';
  4225. exports.GLOBSTAR = '**';
  4226. exports.ROOT_GLOBSTAR = '/**/*';
  4227. exports.SLASH_GLOBSTAR = '/**';
  4228. exports.DIR_SUFFIX = 'Dir';
  4229. exports.ANYMATCH_OPTS = {dot: true};
  4230. exports.STRING_TYPE = 'string';
  4231. exports.FUNCTION_TYPE = 'function';
  4232. exports.EMPTY_STR = '';
  4233. exports.EMPTY_FN = () => {};
  4234. exports.IDENTITY_FN = val => val;
  4235. exports.isWindows = platform === 'win32';
  4236. exports.isMacos = platform === 'darwin';
  4237. exports.isLinux = platform === 'linux';
  4238. }(constants));
  4239. const fs$2 = fs$4;
  4240. const sysPath$2 = require$$0$2;
  4241. const { promisify: promisify$2 } = require$$0$1;
  4242. const isBinaryPath = isBinaryPath$1;
  4243. const {
  4244. isWindows: isWindows$1,
  4245. isLinux,
  4246. EMPTY_FN: EMPTY_FN$2,
  4247. EMPTY_STR: EMPTY_STR$1,
  4248. KEY_LISTENERS,
  4249. KEY_ERR,
  4250. KEY_RAW,
  4251. HANDLER_KEYS,
  4252. EV_CHANGE: EV_CHANGE$2,
  4253. EV_ADD: EV_ADD$2,
  4254. EV_ADD_DIR: EV_ADD_DIR$2,
  4255. EV_ERROR: EV_ERROR$2,
  4256. STR_DATA: STR_DATA$1,
  4257. STR_END: STR_END$2,
  4258. BRACE_START: BRACE_START$1,
  4259. STAR
  4260. } = constants;
  4261. const THROTTLE_MODE_WATCH = 'watch';
  4262. const open = promisify$2(fs$2.open);
  4263. const stat$2 = promisify$2(fs$2.stat);
  4264. const lstat$1 = promisify$2(fs$2.lstat);
  4265. const close = promisify$2(fs$2.close);
  4266. const fsrealpath = promisify$2(fs$2.realpath);
  4267. const statMethods$1 = { lstat: lstat$1, stat: stat$2 };
  4268. // TODO: emit errors properly. Example: EMFILE on Macos.
  4269. const foreach = (val, fn) => {
  4270. if (val instanceof Set) {
  4271. val.forEach(fn);
  4272. } else {
  4273. fn(val);
  4274. }
  4275. };
  4276. const addAndConvert = (main, prop, item) => {
  4277. let container = main[prop];
  4278. if (!(container instanceof Set)) {
  4279. main[prop] = container = new Set([container]);
  4280. }
  4281. container.add(item);
  4282. };
  4283. const clearItem = cont => key => {
  4284. const set = cont[key];
  4285. if (set instanceof Set) {
  4286. set.clear();
  4287. } else {
  4288. delete cont[key];
  4289. }
  4290. };
  4291. const delFromSet = (main, prop, item) => {
  4292. const container = main[prop];
  4293. if (container instanceof Set) {
  4294. container.delete(item);
  4295. } else if (container === item) {
  4296. delete main[prop];
  4297. }
  4298. };
  4299. const isEmptySet = (val) => val instanceof Set ? val.size === 0 : !val;
  4300. /**
  4301. * @typedef {String} Path
  4302. */
  4303. // fs_watch helpers
  4304. // object to hold per-process fs_watch instances
  4305. // (may be shared across chokidar FSWatcher instances)
  4306. /**
  4307. * @typedef {Object} FsWatchContainer
  4308. * @property {Set} listeners
  4309. * @property {Set} errHandlers
  4310. * @property {Set} rawEmitters
  4311. * @property {fs.FSWatcher=} watcher
  4312. * @property {Boolean=} watcherUnusable
  4313. */
  4314. /**
  4315. * @type {Map<String,FsWatchContainer>}
  4316. */
  4317. const FsWatchInstances = new Map();
  4318. /**
  4319. * Instantiates the fs_watch interface
  4320. * @param {String} path to be watched
  4321. * @param {Object} options to be passed to fs_watch
  4322. * @param {Function} listener main event handler
  4323. * @param {Function} errHandler emits info about errors
  4324. * @param {Function} emitRaw emits raw event data
  4325. * @returns {fs.FSWatcher} new fsevents instance
  4326. */
  4327. function createFsWatchInstance(path, options, listener, errHandler, emitRaw) {
  4328. const handleEvent = (rawEvent, evPath) => {
  4329. listener(path);
  4330. emitRaw(rawEvent, evPath, {watchedPath: path});
  4331. // emit based on events occurring for files from a directory's watcher in
  4332. // case the file's watcher misses it (and rely on throttling to de-dupe)
  4333. if (evPath && path !== evPath) {
  4334. fsWatchBroadcast(
  4335. sysPath$2.resolve(path, evPath), KEY_LISTENERS, sysPath$2.join(path, evPath)
  4336. );
  4337. }
  4338. };
  4339. try {
  4340. return fs$2.watch(path, options, handleEvent);
  4341. } catch (error) {
  4342. errHandler(error);
  4343. }
  4344. }
  4345. /**
  4346. * Helper for passing fs_watch event data to a collection of listeners
  4347. * @param {Path} fullPath absolute path bound to fs_watch instance
  4348. * @param {String} type listener type
  4349. * @param {*=} val1 arguments to be passed to listeners
  4350. * @param {*=} val2
  4351. * @param {*=} val3
  4352. */
  4353. const fsWatchBroadcast = (fullPath, type, val1, val2, val3) => {
  4354. const cont = FsWatchInstances.get(fullPath);
  4355. if (!cont) return;
  4356. foreach(cont[type], (listener) => {
  4357. listener(val1, val2, val3);
  4358. });
  4359. };
  4360. /**
  4361. * Instantiates the fs_watch interface or binds listeners
  4362. * to an existing one covering the same file system entry
  4363. * @param {String} path
  4364. * @param {String} fullPath absolute path
  4365. * @param {Object} options to be passed to fs_watch
  4366. * @param {Object} handlers container for event listener functions
  4367. */
  4368. const setFsWatchListener = (path, fullPath, options, handlers) => {
  4369. const {listener, errHandler, rawEmitter} = handlers;
  4370. let cont = FsWatchInstances.get(fullPath);
  4371. /** @type {fs.FSWatcher=} */
  4372. let watcher;
  4373. if (!options.persistent) {
  4374. watcher = createFsWatchInstance(
  4375. path, options, listener, errHandler, rawEmitter
  4376. );
  4377. return watcher.close.bind(watcher);
  4378. }
  4379. if (cont) {
  4380. addAndConvert(cont, KEY_LISTENERS, listener);
  4381. addAndConvert(cont, KEY_ERR, errHandler);
  4382. addAndConvert(cont, KEY_RAW, rawEmitter);
  4383. } else {
  4384. watcher = createFsWatchInstance(
  4385. path,
  4386. options,
  4387. fsWatchBroadcast.bind(null, fullPath, KEY_LISTENERS),
  4388. errHandler, // no need to use broadcast here
  4389. fsWatchBroadcast.bind(null, fullPath, KEY_RAW)
  4390. );
  4391. if (!watcher) return;
  4392. watcher.on(EV_ERROR$2, async (error) => {
  4393. const broadcastErr = fsWatchBroadcast.bind(null, fullPath, KEY_ERR);
  4394. cont.watcherUnusable = true; // documented since Node 10.4.1
  4395. // Workaround for https://github.com/joyent/node/issues/4337
  4396. if (isWindows$1 && error.code === 'EPERM') {
  4397. try {
  4398. const fd = await open(path, 'r');
  4399. await close(fd);
  4400. broadcastErr(error);
  4401. } catch (err) {}
  4402. } else {
  4403. broadcastErr(error);
  4404. }
  4405. });
  4406. cont = {
  4407. listeners: listener,
  4408. errHandlers: errHandler,
  4409. rawEmitters: rawEmitter,
  4410. watcher
  4411. };
  4412. FsWatchInstances.set(fullPath, cont);
  4413. }
  4414. // const index = cont.listeners.indexOf(listener);
  4415. // removes this instance's listeners and closes the underlying fs_watch
  4416. // instance if there are no more listeners left
  4417. return () => {
  4418. delFromSet(cont, KEY_LISTENERS, listener);
  4419. delFromSet(cont, KEY_ERR, errHandler);
  4420. delFromSet(cont, KEY_RAW, rawEmitter);
  4421. if (isEmptySet(cont.listeners)) {
  4422. // Check to protect against issue gh-730.
  4423. // if (cont.watcherUnusable) {
  4424. cont.watcher.close();
  4425. // }
  4426. FsWatchInstances.delete(fullPath);
  4427. HANDLER_KEYS.forEach(clearItem(cont));
  4428. cont.watcher = undefined;
  4429. Object.freeze(cont);
  4430. }
  4431. };
  4432. };
  4433. // fs_watchFile helpers
  4434. // object to hold per-process fs_watchFile instances
  4435. // (may be shared across chokidar FSWatcher instances)
  4436. const FsWatchFileInstances = new Map();
  4437. /**
  4438. * Instantiates the fs_watchFile interface or binds listeners
  4439. * to an existing one covering the same file system entry
  4440. * @param {String} path to be watched
  4441. * @param {String} fullPath absolute path
  4442. * @param {Object} options options to be passed to fs_watchFile
  4443. * @param {Object} handlers container for event listener functions
  4444. * @returns {Function} closer
  4445. */
  4446. const setFsWatchFileListener = (path, fullPath, options, handlers) => {
  4447. const {listener, rawEmitter} = handlers;
  4448. let cont = FsWatchFileInstances.get(fullPath);
  4449. const copts = cont && cont.options;
  4450. if (copts && (copts.persistent < options.persistent || copts.interval > options.interval)) {
  4451. fs$2.unwatchFile(fullPath);
  4452. cont = undefined;
  4453. }
  4454. /* eslint-enable no-unused-vars, prefer-destructuring */
  4455. if (cont) {
  4456. addAndConvert(cont, KEY_LISTENERS, listener);
  4457. addAndConvert(cont, KEY_RAW, rawEmitter);
  4458. } else {
  4459. // TODO
  4460. // listeners.add(listener);
  4461. // rawEmitters.add(rawEmitter);
  4462. cont = {
  4463. listeners: listener,
  4464. rawEmitters: rawEmitter,
  4465. options,
  4466. watcher: fs$2.watchFile(fullPath, options, (curr, prev) => {
  4467. foreach(cont.rawEmitters, (rawEmitter) => {
  4468. rawEmitter(EV_CHANGE$2, fullPath, {curr, prev});
  4469. });
  4470. const currmtime = curr.mtimeMs;
  4471. if (curr.size !== prev.size || currmtime > prev.mtimeMs || currmtime === 0) {
  4472. foreach(cont.listeners, (listener) => listener(path, curr));
  4473. }
  4474. })
  4475. };
  4476. FsWatchFileInstances.set(fullPath, cont);
  4477. }
  4478. // const index = cont.listeners.indexOf(listener);
  4479. // Removes this instance's listeners and closes the underlying fs_watchFile
  4480. // instance if there are no more listeners left.
  4481. return () => {
  4482. delFromSet(cont, KEY_LISTENERS, listener);
  4483. delFromSet(cont, KEY_RAW, rawEmitter);
  4484. if (isEmptySet(cont.listeners)) {
  4485. FsWatchFileInstances.delete(fullPath);
  4486. fs$2.unwatchFile(fullPath);
  4487. cont.options = cont.watcher = undefined;
  4488. Object.freeze(cont);
  4489. }
  4490. };
  4491. };
  4492. /**
  4493. * @mixin
  4494. */
  4495. class NodeFsHandler$1 {
  4496. /**
  4497. * @param {import("../index").FSWatcher} fsW
  4498. */
  4499. constructor(fsW) {
  4500. this.fsw = fsW;
  4501. this._boundHandleError = (error) => fsW._handleError(error);
  4502. }
  4503. /**
  4504. * Watch file for changes with fs_watchFile or fs_watch.
  4505. * @param {String} path to file or dir
  4506. * @param {Function} listener on fs change
  4507. * @returns {Function} closer for the watcher instance
  4508. */
  4509. _watchWithNodeFs(path, listener) {
  4510. const opts = this.fsw.options;
  4511. const directory = sysPath$2.dirname(path);
  4512. const basename = sysPath$2.basename(path);
  4513. const parent = this.fsw._getWatchedDir(directory);
  4514. parent.add(basename);
  4515. const absolutePath = sysPath$2.resolve(path);
  4516. const options = {persistent: opts.persistent};
  4517. if (!listener) listener = EMPTY_FN$2;
  4518. let closer;
  4519. if (opts.usePolling) {
  4520. options.interval = opts.enableBinaryInterval && isBinaryPath(basename) ?
  4521. opts.binaryInterval : opts.interval;
  4522. closer = setFsWatchFileListener(path, absolutePath, options, {
  4523. listener,
  4524. rawEmitter: this.fsw._emitRaw
  4525. });
  4526. } else {
  4527. closer = setFsWatchListener(path, absolutePath, options, {
  4528. listener,
  4529. errHandler: this._boundHandleError,
  4530. rawEmitter: this.fsw._emitRaw
  4531. });
  4532. }
  4533. return closer;
  4534. }
  4535. /**
  4536. * Watch a file and emit add event if warranted.
  4537. * @param {Path} file Path
  4538. * @param {fs.Stats} stats result of fs_stat
  4539. * @param {Boolean} initialAdd was the file added at watch instantiation?
  4540. * @returns {Function} closer for the watcher instance
  4541. */
  4542. _handleFile(file, stats, initialAdd) {
  4543. if (this.fsw.closed) {
  4544. return;
  4545. }
  4546. const dirname = sysPath$2.dirname(file);
  4547. const basename = sysPath$2.basename(file);
  4548. const parent = this.fsw._getWatchedDir(dirname);
  4549. // stats is always present
  4550. let prevStats = stats;
  4551. // if the file is already being watched, do nothing
  4552. if (parent.has(basename)) return;
  4553. const listener = async (path, newStats) => {
  4554. if (!this.fsw._throttle(THROTTLE_MODE_WATCH, file, 5)) return;
  4555. if (!newStats || newStats.mtimeMs === 0) {
  4556. try {
  4557. const newStats = await stat$2(file);
  4558. if (this.fsw.closed) return;
  4559. // Check that change event was not fired because of changed only accessTime.
  4560. const at = newStats.atimeMs;
  4561. const mt = newStats.mtimeMs;
  4562. if (!at || at <= mt || mt !== prevStats.mtimeMs) {
  4563. this.fsw._emit(EV_CHANGE$2, file, newStats);
  4564. }
  4565. if (isLinux && prevStats.ino !== newStats.ino) {
  4566. this.fsw._closeFile(path);
  4567. prevStats = newStats;
  4568. this.fsw._addPathCloser(path, this._watchWithNodeFs(file, listener));
  4569. } else {
  4570. prevStats = newStats;
  4571. }
  4572. } catch (error) {
  4573. // Fix issues where mtime is null but file is still present
  4574. this.fsw._remove(dirname, basename);
  4575. }
  4576. // add is about to be emitted if file not already tracked in parent
  4577. } else if (parent.has(basename)) {
  4578. // Check that change event was not fired because of changed only accessTime.
  4579. const at = newStats.atimeMs;
  4580. const mt = newStats.mtimeMs;
  4581. if (!at || at <= mt || mt !== prevStats.mtimeMs) {
  4582. this.fsw._emit(EV_CHANGE$2, file, newStats);
  4583. }
  4584. prevStats = newStats;
  4585. }
  4586. };
  4587. // kick off the watcher
  4588. const closer = this._watchWithNodeFs(file, listener);
  4589. // emit an add event if we're supposed to
  4590. if (!(initialAdd && this.fsw.options.ignoreInitial) && this.fsw._isntIgnored(file)) {
  4591. if (!this.fsw._throttle(EV_ADD$2, file, 0)) return;
  4592. this.fsw._emit(EV_ADD$2, file, stats);
  4593. }
  4594. return closer;
  4595. }
  4596. /**
  4597. * Handle symlinks encountered while reading a dir.
  4598. * @param {Object} entry returned by readdirp
  4599. * @param {String} directory path of dir being read
  4600. * @param {String} path of this item
  4601. * @param {String} item basename of this item
  4602. * @returns {Promise<Boolean>} true if no more processing is needed for this entry.
  4603. */
  4604. async _handleSymlink(entry, directory, path, item) {
  4605. if (this.fsw.closed) {
  4606. return;
  4607. }
  4608. const full = entry.fullPath;
  4609. const dir = this.fsw._getWatchedDir(directory);
  4610. if (!this.fsw.options.followSymlinks) {
  4611. // watch symlink directly (don't follow) and detect changes
  4612. this.fsw._incrReadyCount();
  4613. const linkPath = await fsrealpath(path);
  4614. if (this.fsw.closed) return;
  4615. if (dir.has(item)) {
  4616. if (this.fsw._symlinkPaths.get(full) !== linkPath) {
  4617. this.fsw._symlinkPaths.set(full, linkPath);
  4618. this.fsw._emit(EV_CHANGE$2, path, entry.stats);
  4619. }
  4620. } else {
  4621. dir.add(item);
  4622. this.fsw._symlinkPaths.set(full, linkPath);
  4623. this.fsw._emit(EV_ADD$2, path, entry.stats);
  4624. }
  4625. this.fsw._emitReady();
  4626. return true;
  4627. }
  4628. // don't follow the same symlink more than once
  4629. if (this.fsw._symlinkPaths.has(full)) {
  4630. return true;
  4631. }
  4632. this.fsw._symlinkPaths.set(full, true);
  4633. }
  4634. _handleRead(directory, initialAdd, wh, target, dir, depth, throttler) {
  4635. // Normalize the directory name on Windows
  4636. directory = sysPath$2.join(directory, EMPTY_STR$1);
  4637. if (!wh.hasGlob) {
  4638. throttler = this.fsw._throttle('readdir', directory, 1000);
  4639. if (!throttler) return;
  4640. }
  4641. const previous = this.fsw._getWatchedDir(wh.path);
  4642. const current = new Set();
  4643. let stream = this.fsw._readdirp(directory, {
  4644. fileFilter: entry => wh.filterPath(entry),
  4645. directoryFilter: entry => wh.filterDir(entry),
  4646. depth: 0
  4647. }).on(STR_DATA$1, async (entry) => {
  4648. if (this.fsw.closed) {
  4649. stream = undefined;
  4650. return;
  4651. }
  4652. const item = entry.path;
  4653. let path = sysPath$2.join(directory, item);
  4654. current.add(item);
  4655. if (entry.stats.isSymbolicLink() && await this._handleSymlink(entry, directory, path, item)) {
  4656. return;
  4657. }
  4658. if (this.fsw.closed) {
  4659. stream = undefined;
  4660. return;
  4661. }
  4662. // Files that present in current directory snapshot
  4663. // but absent in previous are added to watch list and
  4664. // emit `add` event.
  4665. if (item === target || !target && !previous.has(item)) {
  4666. this.fsw._incrReadyCount();
  4667. // ensure relativeness of path is preserved in case of watcher reuse
  4668. path = sysPath$2.join(dir, sysPath$2.relative(dir, path));
  4669. this._addToNodeFs(path, initialAdd, wh, depth + 1);
  4670. }
  4671. }).on(EV_ERROR$2, this._boundHandleError);
  4672. return new Promise(resolve =>
  4673. stream.once(STR_END$2, () => {
  4674. if (this.fsw.closed) {
  4675. stream = undefined;
  4676. return;
  4677. }
  4678. const wasThrottled = throttler ? throttler.clear() : false;
  4679. resolve();
  4680. // Files that absent in current directory snapshot
  4681. // but present in previous emit `remove` event
  4682. // and are removed from @watched[directory].
  4683. previous.getChildren().filter((item) => {
  4684. return item !== directory &&
  4685. !current.has(item) &&
  4686. // in case of intersecting globs;
  4687. // a path may have been filtered out of this readdir, but
  4688. // shouldn't be removed because it matches a different glob
  4689. (!wh.hasGlob || wh.filterPath({
  4690. fullPath: sysPath$2.resolve(directory, item)
  4691. }));
  4692. }).forEach((item) => {
  4693. this.fsw._remove(directory, item);
  4694. });
  4695. stream = undefined;
  4696. // one more time for any missed in case changes came in extremely quickly
  4697. if (wasThrottled) this._handleRead(directory, false, wh, target, dir, depth, throttler);
  4698. })
  4699. );
  4700. }
  4701. /**
  4702. * Read directory to add / remove files from `@watched` list and re-read it on change.
  4703. * @param {String} dir fs path
  4704. * @param {fs.Stats} stats
  4705. * @param {Boolean} initialAdd
  4706. * @param {Number} depth relative to user-supplied path
  4707. * @param {String} target child path targeted for watch
  4708. * @param {Object} wh Common watch helpers for this path
  4709. * @param {String} realpath
  4710. * @returns {Promise<Function>} closer for the watcher instance.
  4711. */
  4712. async _handleDir(dir, stats, initialAdd, depth, target, wh, realpath) {
  4713. const parentDir = this.fsw._getWatchedDir(sysPath$2.dirname(dir));
  4714. const tracked = parentDir.has(sysPath$2.basename(dir));
  4715. if (!(initialAdd && this.fsw.options.ignoreInitial) && !target && !tracked) {
  4716. if (!wh.hasGlob || wh.globFilter(dir)) this.fsw._emit(EV_ADD_DIR$2, dir, stats);
  4717. }
  4718. // ensure dir is tracked (harmless if redundant)
  4719. parentDir.add(sysPath$2.basename(dir));
  4720. this.fsw._getWatchedDir(dir);
  4721. let throttler;
  4722. let closer;
  4723. const oDepth = this.fsw.options.depth;
  4724. if ((oDepth == null || depth <= oDepth) && !this.fsw._symlinkPaths.has(realpath)) {
  4725. if (!target) {
  4726. await this._handleRead(dir, initialAdd, wh, target, dir, depth, throttler);
  4727. if (this.fsw.closed) return;
  4728. }
  4729. closer = this._watchWithNodeFs(dir, (dirPath, stats) => {
  4730. // if current directory is removed, do nothing
  4731. if (stats && stats.mtimeMs === 0) return;
  4732. this._handleRead(dirPath, false, wh, target, dir, depth, throttler);
  4733. });
  4734. }
  4735. return closer;
  4736. }
  4737. /**
  4738. * Handle added file, directory, or glob pattern.
  4739. * Delegates call to _handleFile / _handleDir after checks.
  4740. * @param {String} path to file or ir
  4741. * @param {Boolean} initialAdd was the file added at watch instantiation?
  4742. * @param {Object} priorWh depth relative to user-supplied path
  4743. * @param {Number} depth Child path actually targeted for watch
  4744. * @param {String=} target Child path actually targeted for watch
  4745. * @returns {Promise}
  4746. */
  4747. async _addToNodeFs(path, initialAdd, priorWh, depth, target) {
  4748. const ready = this.fsw._emitReady;
  4749. if (this.fsw._isIgnored(path) || this.fsw.closed) {
  4750. ready();
  4751. return false;
  4752. }
  4753. const wh = this.fsw._getWatchHelpers(path, depth);
  4754. if (!wh.hasGlob && priorWh) {
  4755. wh.hasGlob = priorWh.hasGlob;
  4756. wh.globFilter = priorWh.globFilter;
  4757. wh.filterPath = entry => priorWh.filterPath(entry);
  4758. wh.filterDir = entry => priorWh.filterDir(entry);
  4759. }
  4760. // evaluate what is at the path we're being asked to watch
  4761. try {
  4762. const stats = await statMethods$1[wh.statMethod](wh.watchPath);
  4763. if (this.fsw.closed) return;
  4764. if (this.fsw._isIgnored(wh.watchPath, stats)) {
  4765. ready();
  4766. return false;
  4767. }
  4768. const follow = this.fsw.options.followSymlinks && !path.includes(STAR) && !path.includes(BRACE_START$1);
  4769. let closer;
  4770. if (stats.isDirectory()) {
  4771. const absPath = sysPath$2.resolve(path);
  4772. const targetPath = follow ? await fsrealpath(path) : path;
  4773. if (this.fsw.closed) return;
  4774. closer = await this._handleDir(wh.watchPath, stats, initialAdd, depth, target, wh, targetPath);
  4775. if (this.fsw.closed) return;
  4776. // preserve this symlink's target path
  4777. if (absPath !== targetPath && targetPath !== undefined) {
  4778. this.fsw._symlinkPaths.set(absPath, targetPath);
  4779. }
  4780. } else if (stats.isSymbolicLink()) {
  4781. const targetPath = follow ? await fsrealpath(path) : path;
  4782. if (this.fsw.closed) return;
  4783. const parent = sysPath$2.dirname(wh.watchPath);
  4784. this.fsw._getWatchedDir(parent).add(wh.watchPath);
  4785. this.fsw._emit(EV_ADD$2, wh.watchPath, stats);
  4786. closer = await this._handleDir(parent, stats, initialAdd, depth, path, wh, targetPath);
  4787. if (this.fsw.closed) return;
  4788. // preserve this symlink's target path
  4789. if (targetPath !== undefined) {
  4790. this.fsw._symlinkPaths.set(sysPath$2.resolve(path), targetPath);
  4791. }
  4792. } else {
  4793. closer = this._handleFile(wh.watchPath, stats, initialAdd);
  4794. }
  4795. ready();
  4796. this.fsw._addPathCloser(path, closer);
  4797. return false;
  4798. } catch (error) {
  4799. if (this.fsw._handleError(error)) {
  4800. ready();
  4801. return path;
  4802. }
  4803. }
  4804. }
  4805. }
  4806. var nodefsHandler = NodeFsHandler$1;
  4807. var fseventsHandler = {exports: {}};
  4808. var require$$3 = /*@__PURE__*/getAugmentedNamespace(fseventsImporter);
  4809. const fs$1 = fs$4;
  4810. const sysPath$1 = require$$0$2;
  4811. const { promisify: promisify$1 } = require$$0$1;
  4812. let fsevents;
  4813. try {
  4814. fsevents = require$$3.getFsEvents();
  4815. } catch (error) {
  4816. if (process.env.CHOKIDAR_PRINT_FSEVENTS_REQUIRE_ERROR) console.error(error);
  4817. }
  4818. if (fsevents) {
  4819. // TODO: real check
  4820. const mtch = process.version.match(/v(\d+)\.(\d+)/);
  4821. if (mtch && mtch[1] && mtch[2]) {
  4822. const maj = Number.parseInt(mtch[1], 10);
  4823. const min = Number.parseInt(mtch[2], 10);
  4824. if (maj === 8 && min < 16) {
  4825. fsevents = undefined;
  4826. }
  4827. }
  4828. }
  4829. const {
  4830. EV_ADD: EV_ADD$1,
  4831. EV_CHANGE: EV_CHANGE$1,
  4832. EV_ADD_DIR: EV_ADD_DIR$1,
  4833. EV_UNLINK: EV_UNLINK$1,
  4834. EV_ERROR: EV_ERROR$1,
  4835. STR_DATA,
  4836. STR_END: STR_END$1,
  4837. FSEVENT_CREATED,
  4838. FSEVENT_MODIFIED,
  4839. FSEVENT_DELETED,
  4840. FSEVENT_MOVED,
  4841. // FSEVENT_CLONED,
  4842. FSEVENT_UNKNOWN,
  4843. FSEVENT_TYPE_FILE,
  4844. FSEVENT_TYPE_DIRECTORY,
  4845. FSEVENT_TYPE_SYMLINK,
  4846. ROOT_GLOBSTAR,
  4847. DIR_SUFFIX,
  4848. DOT_SLASH,
  4849. FUNCTION_TYPE: FUNCTION_TYPE$1,
  4850. EMPTY_FN: EMPTY_FN$1,
  4851. IDENTITY_FN
  4852. } = constants;
  4853. const Depth = (value) => isNaN(value) ? {} : {depth: value};
  4854. const stat$1 = promisify$1(fs$1.stat);
  4855. const lstat = promisify$1(fs$1.lstat);
  4856. const realpath = promisify$1(fs$1.realpath);
  4857. const statMethods = { stat: stat$1, lstat };
  4858. /**
  4859. * @typedef {String} Path
  4860. */
  4861. /**
  4862. * @typedef {Object} FsEventsWatchContainer
  4863. * @property {Set<Function>} listeners
  4864. * @property {Function} rawEmitter
  4865. * @property {{stop: Function}} watcher
  4866. */
  4867. // fsevents instance helper functions
  4868. /**
  4869. * Object to hold per-process fsevents instances (may be shared across chokidar FSWatcher instances)
  4870. * @type {Map<Path,FsEventsWatchContainer>}
  4871. */
  4872. const FSEventsWatchers = new Map();
  4873. // Threshold of duplicate path prefixes at which to start
  4874. // consolidating going forward
  4875. const consolidateThreshhold = 10;
  4876. const wrongEventFlags = new Set([
  4877. 69888, 70400, 71424, 72704, 73472, 131328, 131840, 262912
  4878. ]);
  4879. /**
  4880. * Instantiates the fsevents interface
  4881. * @param {Path} path path to be watched
  4882. * @param {Function} callback called when fsevents is bound and ready
  4883. * @returns {{stop: Function}} new fsevents instance
  4884. */
  4885. const createFSEventsInstance = (path, callback) => {
  4886. const stop = fsevents.watch(path, callback);
  4887. return {stop};
  4888. };
  4889. /**
  4890. * Instantiates the fsevents interface or binds listeners to an existing one covering
  4891. * the same file tree.
  4892. * @param {Path} path - to be watched
  4893. * @param {Path} realPath - real path for symlinks
  4894. * @param {Function} listener - called when fsevents emits events
  4895. * @param {Function} rawEmitter - passes data to listeners of the 'raw' event
  4896. * @returns {Function} closer
  4897. */
  4898. function setFSEventsListener(path, realPath, listener, rawEmitter) {
  4899. let watchPath = sysPath$1.extname(path) ? sysPath$1.dirname(path) : path;
  4900. const parentPath = sysPath$1.dirname(watchPath);
  4901. let cont = FSEventsWatchers.get(watchPath);
  4902. // If we've accumulated a substantial number of paths that
  4903. // could have been consolidated by watching one directory
  4904. // above the current one, create a watcher on the parent
  4905. // path instead, so that we do consolidate going forward.
  4906. if (couldConsolidate(parentPath)) {
  4907. watchPath = parentPath;
  4908. }
  4909. const resolvedPath = sysPath$1.resolve(path);
  4910. const hasSymlink = resolvedPath !== realPath;
  4911. const filteredListener = (fullPath, flags, info) => {
  4912. if (hasSymlink) fullPath = fullPath.replace(realPath, resolvedPath);
  4913. if (
  4914. fullPath === resolvedPath ||
  4915. !fullPath.indexOf(resolvedPath + sysPath$1.sep)
  4916. ) listener(fullPath, flags, info);
  4917. };
  4918. // check if there is already a watcher on a parent path
  4919. // modifies `watchPath` to the parent path when it finds a match
  4920. let watchedParent = false;
  4921. for (const watchedPath of FSEventsWatchers.keys()) {
  4922. if (realPath.indexOf(sysPath$1.resolve(watchedPath) + sysPath$1.sep) === 0) {
  4923. watchPath = watchedPath;
  4924. cont = FSEventsWatchers.get(watchPath);
  4925. watchedParent = true;
  4926. break;
  4927. }
  4928. }
  4929. if (cont || watchedParent) {
  4930. cont.listeners.add(filteredListener);
  4931. } else {
  4932. cont = {
  4933. listeners: new Set([filteredListener]),
  4934. rawEmitter,
  4935. watcher: createFSEventsInstance(watchPath, (fullPath, flags) => {
  4936. if (!cont.listeners.size) return;
  4937. const info = fsevents.getInfo(fullPath, flags);
  4938. cont.listeners.forEach(list => {
  4939. list(fullPath, flags, info);
  4940. });
  4941. cont.rawEmitter(info.event, fullPath, info);
  4942. })
  4943. };
  4944. FSEventsWatchers.set(watchPath, cont);
  4945. }
  4946. // removes this instance's listeners and closes the underlying fsevents
  4947. // instance if there are no more listeners left
  4948. return () => {
  4949. const lst = cont.listeners;
  4950. lst.delete(filteredListener);
  4951. if (!lst.size) {
  4952. FSEventsWatchers.delete(watchPath);
  4953. if (cont.watcher) return cont.watcher.stop().then(() => {
  4954. cont.rawEmitter = cont.watcher = undefined;
  4955. Object.freeze(cont);
  4956. });
  4957. }
  4958. };
  4959. }
  4960. // Decide whether or not we should start a new higher-level
  4961. // parent watcher
  4962. const couldConsolidate = (path) => {
  4963. let count = 0;
  4964. for (const watchPath of FSEventsWatchers.keys()) {
  4965. if (watchPath.indexOf(path) === 0) {
  4966. count++;
  4967. if (count >= consolidateThreshhold) {
  4968. return true;
  4969. }
  4970. }
  4971. }
  4972. return false;
  4973. };
  4974. // returns boolean indicating whether fsevents can be used
  4975. const canUse = () => fsevents && FSEventsWatchers.size < 128;
  4976. // determines subdirectory traversal levels from root to path
  4977. const calcDepth = (path, root) => {
  4978. let i = 0;
  4979. while (!path.indexOf(root) && (path = sysPath$1.dirname(path)) !== root) i++;
  4980. return i;
  4981. };
  4982. // returns boolean indicating whether the fsevents' event info has the same type
  4983. // as the one returned by fs.stat
  4984. const sameTypes = (info, stats) => (
  4985. info.type === FSEVENT_TYPE_DIRECTORY && stats.isDirectory() ||
  4986. info.type === FSEVENT_TYPE_SYMLINK && stats.isSymbolicLink() ||
  4987. info.type === FSEVENT_TYPE_FILE && stats.isFile()
  4988. );
  4989. /**
  4990. * @mixin
  4991. */
  4992. class FsEventsHandler$1 {
  4993. /**
  4994. * @param {import('../index').FSWatcher} fsw
  4995. */
  4996. constructor(fsw) {
  4997. this.fsw = fsw;
  4998. }
  4999. checkIgnored(path, stats) {
  5000. const ipaths = this.fsw._ignoredPaths;
  5001. if (this.fsw._isIgnored(path, stats)) {
  5002. ipaths.add(path);
  5003. if (stats && stats.isDirectory()) {
  5004. ipaths.add(path + ROOT_GLOBSTAR);
  5005. }
  5006. return true;
  5007. }
  5008. ipaths.delete(path);
  5009. ipaths.delete(path + ROOT_GLOBSTAR);
  5010. }
  5011. addOrChange(path, fullPath, realPath, parent, watchedDir, item, info, opts) {
  5012. const event = watchedDir.has(item) ? EV_CHANGE$1 : EV_ADD$1;
  5013. this.handleEvent(event, path, fullPath, realPath, parent, watchedDir, item, info, opts);
  5014. }
  5015. async checkExists(path, fullPath, realPath, parent, watchedDir, item, info, opts) {
  5016. try {
  5017. const stats = await stat$1(path);
  5018. if (this.fsw.closed) return;
  5019. if (sameTypes(info, stats)) {
  5020. this.addOrChange(path, fullPath, realPath, parent, watchedDir, item, info, opts);
  5021. } else {
  5022. this.handleEvent(EV_UNLINK$1, path, fullPath, realPath, parent, watchedDir, item, info, opts);
  5023. }
  5024. } catch (error) {
  5025. if (error.code === 'EACCES') {
  5026. this.addOrChange(path, fullPath, realPath, parent, watchedDir, item, info, opts);
  5027. } else {
  5028. this.handleEvent(EV_UNLINK$1, path, fullPath, realPath, parent, watchedDir, item, info, opts);
  5029. }
  5030. }
  5031. }
  5032. handleEvent(event, path, fullPath, realPath, parent, watchedDir, item, info, opts) {
  5033. if (this.fsw.closed || this.checkIgnored(path)) return;
  5034. if (event === EV_UNLINK$1) {
  5035. const isDirectory = info.type === FSEVENT_TYPE_DIRECTORY;
  5036. // suppress unlink events on never before seen files
  5037. if (isDirectory || watchedDir.has(item)) {
  5038. this.fsw._remove(parent, item, isDirectory);
  5039. }
  5040. } else {
  5041. if (event === EV_ADD$1) {
  5042. // track new directories
  5043. if (info.type === FSEVENT_TYPE_DIRECTORY) this.fsw._getWatchedDir(path);
  5044. if (info.type === FSEVENT_TYPE_SYMLINK && opts.followSymlinks) {
  5045. // push symlinks back to the top of the stack to get handled
  5046. const curDepth = opts.depth === undefined ?
  5047. undefined : calcDepth(fullPath, realPath) + 1;
  5048. return this._addToFsEvents(path, false, true, curDepth);
  5049. }
  5050. // track new paths
  5051. // (other than symlinks being followed, which will be tracked soon)
  5052. this.fsw._getWatchedDir(parent).add(item);
  5053. }
  5054. /**
  5055. * @type {'add'|'addDir'|'unlink'|'unlinkDir'}
  5056. */
  5057. const eventName = info.type === FSEVENT_TYPE_DIRECTORY ? event + DIR_SUFFIX : event;
  5058. this.fsw._emit(eventName, path);
  5059. if (eventName === EV_ADD_DIR$1) this._addToFsEvents(path, false, true);
  5060. }
  5061. }
  5062. /**
  5063. * Handle symlinks encountered during directory scan
  5064. * @param {String} watchPath - file/dir path to be watched with fsevents
  5065. * @param {String} realPath - real path (in case of symlinks)
  5066. * @param {Function} transform - path transformer
  5067. * @param {Function} globFilter - path filter in case a glob pattern was provided
  5068. * @returns {Function} closer for the watcher instance
  5069. */
  5070. _watchWithFsEvents(watchPath, realPath, transform, globFilter) {
  5071. if (this.fsw.closed || this.fsw._isIgnored(watchPath)) return;
  5072. const opts = this.fsw.options;
  5073. const watchCallback = async (fullPath, flags, info) => {
  5074. if (this.fsw.closed) return;
  5075. if (
  5076. opts.depth !== undefined &&
  5077. calcDepth(fullPath, realPath) > opts.depth
  5078. ) return;
  5079. const path = transform(sysPath$1.join(
  5080. watchPath, sysPath$1.relative(watchPath, fullPath)
  5081. ));
  5082. if (globFilter && !globFilter(path)) return;
  5083. // ensure directories are tracked
  5084. const parent = sysPath$1.dirname(path);
  5085. const item = sysPath$1.basename(path);
  5086. const watchedDir = this.fsw._getWatchedDir(
  5087. info.type === FSEVENT_TYPE_DIRECTORY ? path : parent
  5088. );
  5089. // correct for wrong events emitted
  5090. if (wrongEventFlags.has(flags) || info.event === FSEVENT_UNKNOWN) {
  5091. if (typeof opts.ignored === FUNCTION_TYPE$1) {
  5092. let stats;
  5093. try {
  5094. stats = await stat$1(path);
  5095. } catch (error) {}
  5096. if (this.fsw.closed) return;
  5097. if (this.checkIgnored(path, stats)) return;
  5098. if (sameTypes(info, stats)) {
  5099. this.addOrChange(path, fullPath, realPath, parent, watchedDir, item, info, opts);
  5100. } else {
  5101. this.handleEvent(EV_UNLINK$1, path, fullPath, realPath, parent, watchedDir, item, info, opts);
  5102. }
  5103. } else {
  5104. this.checkExists(path, fullPath, realPath, parent, watchedDir, item, info, opts);
  5105. }
  5106. } else {
  5107. switch (info.event) {
  5108. case FSEVENT_CREATED:
  5109. case FSEVENT_MODIFIED:
  5110. return this.addOrChange(path, fullPath, realPath, parent, watchedDir, item, info, opts);
  5111. case FSEVENT_DELETED:
  5112. case FSEVENT_MOVED:
  5113. return this.checkExists(path, fullPath, realPath, parent, watchedDir, item, info, opts);
  5114. }
  5115. }
  5116. };
  5117. const closer = setFSEventsListener(
  5118. watchPath,
  5119. realPath,
  5120. watchCallback,
  5121. this.fsw._emitRaw
  5122. );
  5123. this.fsw._emitReady();
  5124. return closer;
  5125. }
  5126. /**
  5127. * Handle symlinks encountered during directory scan
  5128. * @param {String} linkPath path to symlink
  5129. * @param {String} fullPath absolute path to the symlink
  5130. * @param {Function} transform pre-existing path transformer
  5131. * @param {Number} curDepth level of subdirectories traversed to where symlink is
  5132. * @returns {Promise<void>}
  5133. */
  5134. async _handleFsEventsSymlink(linkPath, fullPath, transform, curDepth) {
  5135. // don't follow the same symlink more than once
  5136. if (this.fsw.closed || this.fsw._symlinkPaths.has(fullPath)) return;
  5137. this.fsw._symlinkPaths.set(fullPath, true);
  5138. this.fsw._incrReadyCount();
  5139. try {
  5140. const linkTarget = await realpath(linkPath);
  5141. if (this.fsw.closed) return;
  5142. if (this.fsw._isIgnored(linkTarget)) {
  5143. return this.fsw._emitReady();
  5144. }
  5145. this.fsw._incrReadyCount();
  5146. // add the linkTarget for watching with a wrapper for transform
  5147. // that causes emitted paths to incorporate the link's path
  5148. this._addToFsEvents(linkTarget || linkPath, (path) => {
  5149. let aliasedPath = linkPath;
  5150. if (linkTarget && linkTarget !== DOT_SLASH) {
  5151. aliasedPath = path.replace(linkTarget, linkPath);
  5152. } else if (path !== DOT_SLASH) {
  5153. aliasedPath = sysPath$1.join(linkPath, path);
  5154. }
  5155. return transform(aliasedPath);
  5156. }, false, curDepth);
  5157. } catch(error) {
  5158. if (this.fsw._handleError(error)) {
  5159. return this.fsw._emitReady();
  5160. }
  5161. }
  5162. }
  5163. /**
  5164. *
  5165. * @param {Path} newPath
  5166. * @param {fs.Stats} stats
  5167. */
  5168. emitAdd(newPath, stats, processPath, opts, forceAdd) {
  5169. const pp = processPath(newPath);
  5170. const isDir = stats.isDirectory();
  5171. const dirObj = this.fsw._getWatchedDir(sysPath$1.dirname(pp));
  5172. const base = sysPath$1.basename(pp);
  5173. // ensure empty dirs get tracked
  5174. if (isDir) this.fsw._getWatchedDir(pp);
  5175. if (dirObj.has(base)) return;
  5176. dirObj.add(base);
  5177. if (!opts.ignoreInitial || forceAdd === true) {
  5178. this.fsw._emit(isDir ? EV_ADD_DIR$1 : EV_ADD$1, pp, stats);
  5179. }
  5180. }
  5181. initWatch(realPath, path, wh, processPath) {
  5182. if (this.fsw.closed) return;
  5183. const closer = this._watchWithFsEvents(
  5184. wh.watchPath,
  5185. sysPath$1.resolve(realPath || wh.watchPath),
  5186. processPath,
  5187. wh.globFilter
  5188. );
  5189. this.fsw._addPathCloser(path, closer);
  5190. }
  5191. /**
  5192. * Handle added path with fsevents
  5193. * @param {String} path file/dir path or glob pattern
  5194. * @param {Function|Boolean=} transform converts working path to what the user expects
  5195. * @param {Boolean=} forceAdd ensure add is emitted
  5196. * @param {Number=} priorDepth Level of subdirectories already traversed.
  5197. * @returns {Promise<void>}
  5198. */
  5199. async _addToFsEvents(path, transform, forceAdd, priorDepth) {
  5200. if (this.fsw.closed) {
  5201. return;
  5202. }
  5203. const opts = this.fsw.options;
  5204. const processPath = typeof transform === FUNCTION_TYPE$1 ? transform : IDENTITY_FN;
  5205. const wh = this.fsw._getWatchHelpers(path);
  5206. // evaluate what is at the path we're being asked to watch
  5207. try {
  5208. const stats = await statMethods[wh.statMethod](wh.watchPath);
  5209. if (this.fsw.closed) return;
  5210. if (this.fsw._isIgnored(wh.watchPath, stats)) {
  5211. throw null;
  5212. }
  5213. if (stats.isDirectory()) {
  5214. // emit addDir unless this is a glob parent
  5215. if (!wh.globFilter) this.emitAdd(processPath(path), stats, processPath, opts, forceAdd);
  5216. // don't recurse further if it would exceed depth setting
  5217. if (priorDepth && priorDepth > opts.depth) return;
  5218. // scan the contents of the dir
  5219. this.fsw._readdirp(wh.watchPath, {
  5220. fileFilter: entry => wh.filterPath(entry),
  5221. directoryFilter: entry => wh.filterDir(entry),
  5222. ...Depth(opts.depth - (priorDepth || 0))
  5223. }).on(STR_DATA, (entry) => {
  5224. // need to check filterPath on dirs b/c filterDir is less restrictive
  5225. if (this.fsw.closed) {
  5226. return;
  5227. }
  5228. if (entry.stats.isDirectory() && !wh.filterPath(entry)) return;
  5229. const joinedPath = sysPath$1.join(wh.watchPath, entry.path);
  5230. const {fullPath} = entry;
  5231. if (wh.followSymlinks && entry.stats.isSymbolicLink()) {
  5232. // preserve the current depth here since it can't be derived from
  5233. // real paths past the symlink
  5234. const curDepth = opts.depth === undefined ?
  5235. undefined : calcDepth(joinedPath, sysPath$1.resolve(wh.watchPath)) + 1;
  5236. this._handleFsEventsSymlink(joinedPath, fullPath, processPath, curDepth);
  5237. } else {
  5238. this.emitAdd(joinedPath, entry.stats, processPath, opts, forceAdd);
  5239. }
  5240. }).on(EV_ERROR$1, EMPTY_FN$1).on(STR_END$1, () => {
  5241. this.fsw._emitReady();
  5242. });
  5243. } else {
  5244. this.emitAdd(wh.watchPath, stats, processPath, opts, forceAdd);
  5245. this.fsw._emitReady();
  5246. }
  5247. } catch (error) {
  5248. if (!error || this.fsw._handleError(error)) {
  5249. // TODO: Strange thing: "should not choke on an ignored watch path" will be failed without 2 ready calls -__-
  5250. this.fsw._emitReady();
  5251. this.fsw._emitReady();
  5252. }
  5253. }
  5254. if (opts.persistent && forceAdd !== true) {
  5255. if (typeof transform === FUNCTION_TYPE$1) {
  5256. // realpath has already been resolved
  5257. this.initWatch(undefined, path, wh, processPath);
  5258. } else {
  5259. let realPath;
  5260. try {
  5261. realPath = await realpath(wh.watchPath);
  5262. } catch (e) {}
  5263. this.initWatch(realPath, path, wh, processPath);
  5264. }
  5265. }
  5266. }
  5267. }
  5268. fseventsHandler.exports = FsEventsHandler$1;
  5269. fseventsHandler.exports.canUse = canUse;
  5270. const { EventEmitter } = require$$0$3;
  5271. const fs = fs$4;
  5272. const sysPath = require$$0$2;
  5273. const { promisify } = require$$0$1;
  5274. const readdirp = readdirp_1;
  5275. const anymatch = anymatch$2.exports.default;
  5276. const globParent = globParent$1;
  5277. const isGlob = isGlob$2;
  5278. const braces = braces_1;
  5279. const normalizePath = normalizePath$2;
  5280. const NodeFsHandler = nodefsHandler;
  5281. const FsEventsHandler = fseventsHandler.exports;
  5282. const {
  5283. EV_ALL,
  5284. EV_READY,
  5285. EV_ADD,
  5286. EV_CHANGE,
  5287. EV_UNLINK,
  5288. EV_ADD_DIR,
  5289. EV_UNLINK_DIR,
  5290. EV_RAW,
  5291. EV_ERROR,
  5292. STR_CLOSE,
  5293. STR_END,
  5294. BACK_SLASH_RE,
  5295. DOUBLE_SLASH_RE,
  5296. SLASH_OR_BACK_SLASH_RE,
  5297. DOT_RE,
  5298. REPLACER_RE,
  5299. SLASH,
  5300. SLASH_SLASH,
  5301. BRACE_START,
  5302. BANG,
  5303. ONE_DOT,
  5304. TWO_DOTS,
  5305. GLOBSTAR,
  5306. SLASH_GLOBSTAR,
  5307. ANYMATCH_OPTS,
  5308. STRING_TYPE,
  5309. FUNCTION_TYPE,
  5310. EMPTY_STR,
  5311. EMPTY_FN,
  5312. isWindows,
  5313. isMacos
  5314. } = constants;
  5315. const stat = promisify(fs.stat);
  5316. const readdir = promisify(fs.readdir);
  5317. /**
  5318. * @typedef {String} Path
  5319. * @typedef {'all'|'add'|'addDir'|'change'|'unlink'|'unlinkDir'|'raw'|'error'|'ready'} EventName
  5320. * @typedef {'readdir'|'watch'|'add'|'remove'|'change'} ThrottleType
  5321. */
  5322. /**
  5323. *
  5324. * @typedef {Object} WatchHelpers
  5325. * @property {Boolean} followSymlinks
  5326. * @property {'stat'|'lstat'} statMethod
  5327. * @property {Path} path
  5328. * @property {Path} watchPath
  5329. * @property {Function} entryPath
  5330. * @property {Boolean} hasGlob
  5331. * @property {Object} globFilter
  5332. * @property {Function} filterPath
  5333. * @property {Function} filterDir
  5334. */
  5335. const arrify = (value = []) => Array.isArray(value) ? value : [value];
  5336. const flatten = (list, result = []) => {
  5337. list.forEach(item => {
  5338. if (Array.isArray(item)) {
  5339. flatten(item, result);
  5340. } else {
  5341. result.push(item);
  5342. }
  5343. });
  5344. return result;
  5345. };
  5346. const unifyPaths = (paths_) => {
  5347. /**
  5348. * @type {Array<String>}
  5349. */
  5350. const paths = flatten(arrify(paths_));
  5351. if (!paths.every(p => typeof p === STRING_TYPE)) {
  5352. throw new TypeError(`Non-string provided as watch path: ${paths}`);
  5353. }
  5354. return paths.map(normalizePathToUnix);
  5355. };
  5356. // If SLASH_SLASH occurs at the beginning of path, it is not replaced
  5357. // because "//StoragePC/DrivePool/Movies" is a valid network path
  5358. const toUnix = (string) => {
  5359. let str = string.replace(BACK_SLASH_RE, SLASH);
  5360. let prepend = false;
  5361. if (str.startsWith(SLASH_SLASH)) {
  5362. prepend = true;
  5363. }
  5364. while (str.match(DOUBLE_SLASH_RE)) {
  5365. str = str.replace(DOUBLE_SLASH_RE, SLASH);
  5366. }
  5367. if (prepend) {
  5368. str = SLASH + str;
  5369. }
  5370. return str;
  5371. };
  5372. // Our version of upath.normalize
  5373. // TODO: this is not equal to path-normalize module - investigate why
  5374. const normalizePathToUnix = (path) => toUnix(sysPath.normalize(toUnix(path)));
  5375. const normalizeIgnored = (cwd = EMPTY_STR) => (path) => {
  5376. if (typeof path !== STRING_TYPE) return path;
  5377. return normalizePathToUnix(sysPath.isAbsolute(path) ? path : sysPath.join(cwd, path));
  5378. };
  5379. const getAbsolutePath = (path, cwd) => {
  5380. if (sysPath.isAbsolute(path)) {
  5381. return path;
  5382. }
  5383. if (path.startsWith(BANG)) {
  5384. return BANG + sysPath.join(cwd, path.slice(1));
  5385. }
  5386. return sysPath.join(cwd, path);
  5387. };
  5388. const undef = (opts, key) => opts[key] === undefined;
  5389. /**
  5390. * Directory entry.
  5391. * @property {Path} path
  5392. * @property {Set<Path>} items
  5393. */
  5394. class DirEntry {
  5395. /**
  5396. * @param {Path} dir
  5397. * @param {Function} removeWatcher
  5398. */
  5399. constructor(dir, removeWatcher) {
  5400. this.path = dir;
  5401. this._removeWatcher = removeWatcher;
  5402. /** @type {Set<Path>} */
  5403. this.items = new Set();
  5404. }
  5405. add(item) {
  5406. const {items} = this;
  5407. if (!items) return;
  5408. if (item !== ONE_DOT && item !== TWO_DOTS) items.add(item);
  5409. }
  5410. async remove(item) {
  5411. const {items} = this;
  5412. if (!items) return;
  5413. items.delete(item);
  5414. if (items.size > 0) return;
  5415. const dir = this.path;
  5416. try {
  5417. await readdir(dir);
  5418. } catch (err) {
  5419. if (this._removeWatcher) {
  5420. this._removeWatcher(sysPath.dirname(dir), sysPath.basename(dir));
  5421. }
  5422. }
  5423. }
  5424. has(item) {
  5425. const {items} = this;
  5426. if (!items) return;
  5427. return items.has(item);
  5428. }
  5429. /**
  5430. * @returns {Array<String>}
  5431. */
  5432. getChildren() {
  5433. const {items} = this;
  5434. if (!items) return;
  5435. return [...items.values()];
  5436. }
  5437. dispose() {
  5438. this.items.clear();
  5439. delete this.path;
  5440. delete this._removeWatcher;
  5441. delete this.items;
  5442. Object.freeze(this);
  5443. }
  5444. }
  5445. const STAT_METHOD_F = 'stat';
  5446. const STAT_METHOD_L = 'lstat';
  5447. class WatchHelper {
  5448. constructor(path, watchPath, follow, fsw) {
  5449. this.fsw = fsw;
  5450. this.path = path = path.replace(REPLACER_RE, EMPTY_STR);
  5451. this.watchPath = watchPath;
  5452. this.fullWatchPath = sysPath.resolve(watchPath);
  5453. this.hasGlob = watchPath !== path;
  5454. /** @type {object|boolean} */
  5455. if (path === EMPTY_STR) this.hasGlob = false;
  5456. this.globSymlink = this.hasGlob && follow ? undefined : false;
  5457. this.globFilter = this.hasGlob ? anymatch(path, undefined, ANYMATCH_OPTS) : false;
  5458. this.dirParts = this.getDirParts(path);
  5459. this.dirParts.forEach((parts) => {
  5460. if (parts.length > 1) parts.pop();
  5461. });
  5462. this.followSymlinks = follow;
  5463. this.statMethod = follow ? STAT_METHOD_F : STAT_METHOD_L;
  5464. }
  5465. checkGlobSymlink(entry) {
  5466. // only need to resolve once
  5467. // first entry should always have entry.parentDir === EMPTY_STR
  5468. if (this.globSymlink === undefined) {
  5469. this.globSymlink = entry.fullParentDir === this.fullWatchPath ?
  5470. false : {realPath: entry.fullParentDir, linkPath: this.fullWatchPath};
  5471. }
  5472. if (this.globSymlink) {
  5473. return entry.fullPath.replace(this.globSymlink.realPath, this.globSymlink.linkPath);
  5474. }
  5475. return entry.fullPath;
  5476. }
  5477. entryPath(entry) {
  5478. return sysPath.join(this.watchPath,
  5479. sysPath.relative(this.watchPath, this.checkGlobSymlink(entry))
  5480. );
  5481. }
  5482. filterPath(entry) {
  5483. const {stats} = entry;
  5484. if (stats && stats.isSymbolicLink()) return this.filterDir(entry);
  5485. const resolvedPath = this.entryPath(entry);
  5486. const matchesGlob = this.hasGlob && typeof this.globFilter === FUNCTION_TYPE ?
  5487. this.globFilter(resolvedPath) : true;
  5488. return matchesGlob &&
  5489. this.fsw._isntIgnored(resolvedPath, stats) &&
  5490. this.fsw._hasReadPermissions(stats);
  5491. }
  5492. getDirParts(path) {
  5493. if (!this.hasGlob) return [];
  5494. const parts = [];
  5495. const expandedPath = path.includes(BRACE_START) ? braces.expand(path) : [path];
  5496. expandedPath.forEach((path) => {
  5497. parts.push(sysPath.relative(this.watchPath, path).split(SLASH_OR_BACK_SLASH_RE));
  5498. });
  5499. return parts;
  5500. }
  5501. filterDir(entry) {
  5502. if (this.hasGlob) {
  5503. const entryParts = this.getDirParts(this.checkGlobSymlink(entry));
  5504. let globstar = false;
  5505. this.unmatchedGlob = !this.dirParts.some((parts) => {
  5506. return parts.every((part, i) => {
  5507. if (part === GLOBSTAR) globstar = true;
  5508. return globstar || !entryParts[0][i] || anymatch(part, entryParts[0][i], ANYMATCH_OPTS);
  5509. });
  5510. });
  5511. }
  5512. return !this.unmatchedGlob && this.fsw._isntIgnored(this.entryPath(entry), entry.stats);
  5513. }
  5514. }
  5515. /**
  5516. * Watches files & directories for changes. Emitted events:
  5517. * `add`, `addDir`, `change`, `unlink`, `unlinkDir`, `all`, `error`
  5518. *
  5519. * new FSWatcher()
  5520. * .add(directories)
  5521. * .on('add', path => log('File', path, 'was added'))
  5522. */
  5523. class FSWatcher extends EventEmitter {
  5524. // Not indenting methods for history sake; for now.
  5525. constructor(_opts) {
  5526. super();
  5527. const opts = {};
  5528. if (_opts) Object.assign(opts, _opts); // for frozen objects
  5529. /** @type {Map<String, DirEntry>} */
  5530. this._watched = new Map();
  5531. /** @type {Map<String, Array>} */
  5532. this._closers = new Map();
  5533. /** @type {Set<String>} */
  5534. this._ignoredPaths = new Set();
  5535. /** @type {Map<ThrottleType, Map>} */
  5536. this._throttled = new Map();
  5537. /** @type {Map<Path, String|Boolean>} */
  5538. this._symlinkPaths = new Map();
  5539. this._streams = new Set();
  5540. this.closed = false;
  5541. // Set up default options.
  5542. if (undef(opts, 'persistent')) opts.persistent = true;
  5543. if (undef(opts, 'ignoreInitial')) opts.ignoreInitial = false;
  5544. if (undef(opts, 'ignorePermissionErrors')) opts.ignorePermissionErrors = false;
  5545. if (undef(opts, 'interval')) opts.interval = 100;
  5546. if (undef(opts, 'binaryInterval')) opts.binaryInterval = 300;
  5547. if (undef(opts, 'disableGlobbing')) opts.disableGlobbing = false;
  5548. opts.enableBinaryInterval = opts.binaryInterval !== opts.interval;
  5549. // Enable fsevents on OS X when polling isn't explicitly enabled.
  5550. if (undef(opts, 'useFsEvents')) opts.useFsEvents = !opts.usePolling;
  5551. // If we can't use fsevents, ensure the options reflect it's disabled.
  5552. const canUseFsEvents = FsEventsHandler.canUse();
  5553. if (!canUseFsEvents) opts.useFsEvents = false;
  5554. // Use polling on Mac if not using fsevents.
  5555. // Other platforms use non-polling fs_watch.
  5556. if (undef(opts, 'usePolling') && !opts.useFsEvents) {
  5557. opts.usePolling = isMacos;
  5558. }
  5559. // Global override (useful for end-developers that need to force polling for all
  5560. // instances of chokidar, regardless of usage/dependency depth)
  5561. const envPoll = process.env.CHOKIDAR_USEPOLLING;
  5562. if (envPoll !== undefined) {
  5563. const envLower = envPoll.toLowerCase();
  5564. if (envLower === 'false' || envLower === '0') {
  5565. opts.usePolling = false;
  5566. } else if (envLower === 'true' || envLower === '1') {
  5567. opts.usePolling = true;
  5568. } else {
  5569. opts.usePolling = !!envLower;
  5570. }
  5571. }
  5572. const envInterval = process.env.CHOKIDAR_INTERVAL;
  5573. if (envInterval) {
  5574. opts.interval = Number.parseInt(envInterval, 10);
  5575. }
  5576. // Editor atomic write normalization enabled by default with fs.watch
  5577. if (undef(opts, 'atomic')) opts.atomic = !opts.usePolling && !opts.useFsEvents;
  5578. if (opts.atomic) this._pendingUnlinks = new Map();
  5579. if (undef(opts, 'followSymlinks')) opts.followSymlinks = true;
  5580. if (undef(opts, 'awaitWriteFinish')) opts.awaitWriteFinish = false;
  5581. if (opts.awaitWriteFinish === true) opts.awaitWriteFinish = {};
  5582. const awf = opts.awaitWriteFinish;
  5583. if (awf) {
  5584. if (!awf.stabilityThreshold) awf.stabilityThreshold = 2000;
  5585. if (!awf.pollInterval) awf.pollInterval = 100;
  5586. this._pendingWrites = new Map();
  5587. }
  5588. if (opts.ignored) opts.ignored = arrify(opts.ignored);
  5589. let readyCalls = 0;
  5590. this._emitReady = () => {
  5591. readyCalls++;
  5592. if (readyCalls >= this._readyCount) {
  5593. this._emitReady = EMPTY_FN;
  5594. this._readyEmitted = true;
  5595. // use process.nextTick to allow time for listener to be bound
  5596. process.nextTick(() => this.emit(EV_READY));
  5597. }
  5598. };
  5599. this._emitRaw = (...args) => this.emit(EV_RAW, ...args);
  5600. this._readyEmitted = false;
  5601. this.options = opts;
  5602. // Initialize with proper watcher.
  5603. if (opts.useFsEvents) {
  5604. this._fsEventsHandler = new FsEventsHandler(this);
  5605. } else {
  5606. this._nodeFsHandler = new NodeFsHandler(this);
  5607. }
  5608. // You’re frozen when your heart’s not open.
  5609. Object.freeze(opts);
  5610. }
  5611. // Public methods
  5612. /**
  5613. * Adds paths to be watched on an existing FSWatcher instance
  5614. * @param {Path|Array<Path>} paths_
  5615. * @param {String=} _origAdd private; for handling non-existent paths to be watched
  5616. * @param {Boolean=} _internal private; indicates a non-user add
  5617. * @returns {FSWatcher} for chaining
  5618. */
  5619. add(paths_, _origAdd, _internal) {
  5620. const {cwd, disableGlobbing} = this.options;
  5621. this.closed = false;
  5622. let paths = unifyPaths(paths_);
  5623. if (cwd) {
  5624. paths = paths.map((path) => {
  5625. const absPath = getAbsolutePath(path, cwd);
  5626. // Check `path` instead of `absPath` because the cwd portion can't be a glob
  5627. if (disableGlobbing || !isGlob(path)) {
  5628. return absPath;
  5629. }
  5630. return normalizePath(absPath);
  5631. });
  5632. }
  5633. // set aside negated glob strings
  5634. paths = paths.filter((path) => {
  5635. if (path.startsWith(BANG)) {
  5636. this._ignoredPaths.add(path.slice(1));
  5637. return false;
  5638. }
  5639. // if a path is being added that was previously ignored, stop ignoring it
  5640. this._ignoredPaths.delete(path);
  5641. this._ignoredPaths.delete(path + SLASH_GLOBSTAR);
  5642. // reset the cached userIgnored anymatch fn
  5643. // to make ignoredPaths changes effective
  5644. this._userIgnored = undefined;
  5645. return true;
  5646. });
  5647. if (this.options.useFsEvents && this._fsEventsHandler) {
  5648. if (!this._readyCount) this._readyCount = paths.length;
  5649. if (this.options.persistent) this._readyCount *= 2;
  5650. paths.forEach((path) => this._fsEventsHandler._addToFsEvents(path));
  5651. } else {
  5652. if (!this._readyCount) this._readyCount = 0;
  5653. this._readyCount += paths.length;
  5654. Promise.all(
  5655. paths.map(async path => {
  5656. const res = await this._nodeFsHandler._addToNodeFs(path, !_internal, 0, 0, _origAdd);
  5657. if (res) this._emitReady();
  5658. return res;
  5659. })
  5660. ).then(results => {
  5661. if (this.closed) return;
  5662. results.filter(item => item).forEach(item => {
  5663. this.add(sysPath.dirname(item), sysPath.basename(_origAdd || item));
  5664. });
  5665. });
  5666. }
  5667. return this;
  5668. }
  5669. /**
  5670. * Close watchers or start ignoring events from specified paths.
  5671. * @param {Path|Array<Path>} paths_ - string or array of strings, file/directory paths and/or globs
  5672. * @returns {FSWatcher} for chaining
  5673. */
  5674. unwatch(paths_) {
  5675. if (this.closed) return this;
  5676. const paths = unifyPaths(paths_);
  5677. const {cwd} = this.options;
  5678. paths.forEach((path) => {
  5679. // convert to absolute path unless relative path already matches
  5680. if (!sysPath.isAbsolute(path) && !this._closers.has(path)) {
  5681. if (cwd) path = sysPath.join(cwd, path);
  5682. path = sysPath.resolve(path);
  5683. }
  5684. this._closePath(path);
  5685. this._ignoredPaths.add(path);
  5686. if (this._watched.has(path)) {
  5687. this._ignoredPaths.add(path + SLASH_GLOBSTAR);
  5688. }
  5689. // reset the cached userIgnored anymatch fn
  5690. // to make ignoredPaths changes effective
  5691. this._userIgnored = undefined;
  5692. });
  5693. return this;
  5694. }
  5695. /**
  5696. * Close watchers and remove all listeners from watched paths.
  5697. * @returns {Promise<void>}.
  5698. */
  5699. close() {
  5700. if (this.closed) return this._closePromise;
  5701. this.closed = true;
  5702. // Memory management.
  5703. this.removeAllListeners();
  5704. const closers = [];
  5705. this._closers.forEach(closerList => closerList.forEach(closer => {
  5706. const promise = closer();
  5707. if (promise instanceof Promise) closers.push(promise);
  5708. }));
  5709. this._streams.forEach(stream => stream.destroy());
  5710. this._userIgnored = undefined;
  5711. this._readyCount = 0;
  5712. this._readyEmitted = false;
  5713. this._watched.forEach(dirent => dirent.dispose());
  5714. ['closers', 'watched', 'streams', 'symlinkPaths', 'throttled'].forEach(key => {
  5715. this[`_${key}`].clear();
  5716. });
  5717. this._closePromise = closers.length ? Promise.all(closers).then(() => undefined) : Promise.resolve();
  5718. return this._closePromise;
  5719. }
  5720. /**
  5721. * Expose list of watched paths
  5722. * @returns {Object} for chaining
  5723. */
  5724. getWatched() {
  5725. const watchList = {};
  5726. this._watched.forEach((entry, dir) => {
  5727. const key = this.options.cwd ? sysPath.relative(this.options.cwd, dir) : dir;
  5728. watchList[key || ONE_DOT] = entry.getChildren().sort();
  5729. });
  5730. return watchList;
  5731. }
  5732. emitWithAll(event, args) {
  5733. this.emit(...args);
  5734. if (event !== EV_ERROR) this.emit(EV_ALL, ...args);
  5735. }
  5736. // Common helpers
  5737. // --------------
  5738. /**
  5739. * Normalize and emit events.
  5740. * Calling _emit DOES NOT MEAN emit() would be called!
  5741. * @param {EventName} event Type of event
  5742. * @param {Path} path File or directory path
  5743. * @param {*=} val1 arguments to be passed with event
  5744. * @param {*=} val2
  5745. * @param {*=} val3
  5746. * @returns the error if defined, otherwise the value of the FSWatcher instance's `closed` flag
  5747. */
  5748. async _emit(event, path, val1, val2, val3) {
  5749. if (this.closed) return;
  5750. const opts = this.options;
  5751. if (isWindows) path = sysPath.normalize(path);
  5752. if (opts.cwd) path = sysPath.relative(opts.cwd, path);
  5753. /** @type Array<any> */
  5754. const args = [event, path];
  5755. if (val3 !== undefined) args.push(val1, val2, val3);
  5756. else if (val2 !== undefined) args.push(val1, val2);
  5757. else if (val1 !== undefined) args.push(val1);
  5758. const awf = opts.awaitWriteFinish;
  5759. let pw;
  5760. if (awf && (pw = this._pendingWrites.get(path))) {
  5761. pw.lastChange = new Date();
  5762. return this;
  5763. }
  5764. if (opts.atomic) {
  5765. if (event === EV_UNLINK) {
  5766. this._pendingUnlinks.set(path, args);
  5767. setTimeout(() => {
  5768. this._pendingUnlinks.forEach((entry, path) => {
  5769. this.emit(...entry);
  5770. this.emit(EV_ALL, ...entry);
  5771. this._pendingUnlinks.delete(path);
  5772. });
  5773. }, typeof opts.atomic === 'number' ? opts.atomic : 100);
  5774. return this;
  5775. }
  5776. if (event === EV_ADD && this._pendingUnlinks.has(path)) {
  5777. event = args[0] = EV_CHANGE;
  5778. this._pendingUnlinks.delete(path);
  5779. }
  5780. }
  5781. if (awf && (event === EV_ADD || event === EV_CHANGE) && this._readyEmitted) {
  5782. const awfEmit = (err, stats) => {
  5783. if (err) {
  5784. event = args[0] = EV_ERROR;
  5785. args[1] = err;
  5786. this.emitWithAll(event, args);
  5787. } else if (stats) {
  5788. // if stats doesn't exist the file must have been deleted
  5789. if (args.length > 2) {
  5790. args[2] = stats;
  5791. } else {
  5792. args.push(stats);
  5793. }
  5794. this.emitWithAll(event, args);
  5795. }
  5796. };
  5797. this._awaitWriteFinish(path, awf.stabilityThreshold, event, awfEmit);
  5798. return this;
  5799. }
  5800. if (event === EV_CHANGE) {
  5801. const isThrottled = !this._throttle(EV_CHANGE, path, 50);
  5802. if (isThrottled) return this;
  5803. }
  5804. if (opts.alwaysStat && val1 === undefined &&
  5805. (event === EV_ADD || event === EV_ADD_DIR || event === EV_CHANGE)
  5806. ) {
  5807. const fullPath = opts.cwd ? sysPath.join(opts.cwd, path) : path;
  5808. let stats;
  5809. try {
  5810. stats = await stat(fullPath);
  5811. } catch (err) {}
  5812. // Suppress event when fs_stat fails, to avoid sending undefined 'stat'
  5813. if (!stats || this.closed) return;
  5814. args.push(stats);
  5815. }
  5816. this.emitWithAll(event, args);
  5817. return this;
  5818. }
  5819. /**
  5820. * Common handler for errors
  5821. * @param {Error} error
  5822. * @returns {Error|Boolean} The error if defined, otherwise the value of the FSWatcher instance's `closed` flag
  5823. */
  5824. _handleError(error) {
  5825. const code = error && error.code;
  5826. if (error && code !== 'ENOENT' && code !== 'ENOTDIR' &&
  5827. (!this.options.ignorePermissionErrors || (code !== 'EPERM' && code !== 'EACCES'))
  5828. ) {
  5829. this.emit(EV_ERROR, error);
  5830. }
  5831. return error || this.closed;
  5832. }
  5833. /**
  5834. * Helper utility for throttling
  5835. * @param {ThrottleType} actionType type being throttled
  5836. * @param {Path} path being acted upon
  5837. * @param {Number} timeout duration of time to suppress duplicate actions
  5838. * @returns {Object|false} tracking object or false if action should be suppressed
  5839. */
  5840. _throttle(actionType, path, timeout) {
  5841. if (!this._throttled.has(actionType)) {
  5842. this._throttled.set(actionType, new Map());
  5843. }
  5844. /** @type {Map<Path, Object>} */
  5845. const action = this._throttled.get(actionType);
  5846. /** @type {Object} */
  5847. const actionPath = action.get(path);
  5848. if (actionPath) {
  5849. actionPath.count++;
  5850. return false;
  5851. }
  5852. let timeoutObject;
  5853. const clear = () => {
  5854. const item = action.get(path);
  5855. const count = item ? item.count : 0;
  5856. action.delete(path);
  5857. clearTimeout(timeoutObject);
  5858. if (item) clearTimeout(item.timeoutObject);
  5859. return count;
  5860. };
  5861. timeoutObject = setTimeout(clear, timeout);
  5862. const thr = {timeoutObject, clear, count: 0};
  5863. action.set(path, thr);
  5864. return thr;
  5865. }
  5866. _incrReadyCount() {
  5867. return this._readyCount++;
  5868. }
  5869. /**
  5870. * Awaits write operation to finish.
  5871. * Polls a newly created file for size variations. When files size does not change for 'threshold' milliseconds calls callback.
  5872. * @param {Path} path being acted upon
  5873. * @param {Number} threshold Time in milliseconds a file size must be fixed before acknowledging write OP is finished
  5874. * @param {EventName} event
  5875. * @param {Function} awfEmit Callback to be called when ready for event to be emitted.
  5876. */
  5877. _awaitWriteFinish(path, threshold, event, awfEmit) {
  5878. let timeoutHandler;
  5879. let fullPath = path;
  5880. if (this.options.cwd && !sysPath.isAbsolute(path)) {
  5881. fullPath = sysPath.join(this.options.cwd, path);
  5882. }
  5883. const now = new Date();
  5884. const awaitWriteFinish = (prevStat) => {
  5885. fs.stat(fullPath, (err, curStat) => {
  5886. if (err || !this._pendingWrites.has(path)) {
  5887. if (err && err.code !== 'ENOENT') awfEmit(err);
  5888. return;
  5889. }
  5890. const now = Number(new Date());
  5891. if (prevStat && curStat.size !== prevStat.size) {
  5892. this._pendingWrites.get(path).lastChange = now;
  5893. }
  5894. const pw = this._pendingWrites.get(path);
  5895. const df = now - pw.lastChange;
  5896. if (df >= threshold) {
  5897. this._pendingWrites.delete(path);
  5898. awfEmit(undefined, curStat);
  5899. } else {
  5900. timeoutHandler = setTimeout(
  5901. awaitWriteFinish,
  5902. this.options.awaitWriteFinish.pollInterval,
  5903. curStat
  5904. );
  5905. }
  5906. });
  5907. };
  5908. if (!this._pendingWrites.has(path)) {
  5909. this._pendingWrites.set(path, {
  5910. lastChange: now,
  5911. cancelWait: () => {
  5912. this._pendingWrites.delete(path);
  5913. clearTimeout(timeoutHandler);
  5914. return event;
  5915. }
  5916. });
  5917. timeoutHandler = setTimeout(
  5918. awaitWriteFinish,
  5919. this.options.awaitWriteFinish.pollInterval
  5920. );
  5921. }
  5922. }
  5923. _getGlobIgnored() {
  5924. return [...this._ignoredPaths.values()];
  5925. }
  5926. /**
  5927. * Determines whether user has asked to ignore this path.
  5928. * @param {Path} path filepath or dir
  5929. * @param {fs.Stats=} stats result of fs.stat
  5930. * @returns {Boolean}
  5931. */
  5932. _isIgnored(path, stats) {
  5933. if (this.options.atomic && DOT_RE.test(path)) return true;
  5934. if (!this._userIgnored) {
  5935. const {cwd} = this.options;
  5936. const ign = this.options.ignored;
  5937. const ignored = ign && ign.map(normalizeIgnored(cwd));
  5938. const paths = arrify(ignored)
  5939. .filter((path) => typeof path === STRING_TYPE && !isGlob(path))
  5940. .map((path) => path + SLASH_GLOBSTAR);
  5941. const list = this._getGlobIgnored().map(normalizeIgnored(cwd)).concat(ignored, paths);
  5942. this._userIgnored = anymatch(list, undefined, ANYMATCH_OPTS);
  5943. }
  5944. return this._userIgnored([path, stats]);
  5945. }
  5946. _isntIgnored(path, stat) {
  5947. return !this._isIgnored(path, stat);
  5948. }
  5949. /**
  5950. * Provides a set of common helpers and properties relating to symlink and glob handling.
  5951. * @param {Path} path file, directory, or glob pattern being watched
  5952. * @param {Number=} depth at any depth > 0, this isn't a glob
  5953. * @returns {WatchHelper} object containing helpers for this path
  5954. */
  5955. _getWatchHelpers(path, depth) {
  5956. const watchPath = depth || this.options.disableGlobbing || !isGlob(path) ? path : globParent(path);
  5957. const follow = this.options.followSymlinks;
  5958. return new WatchHelper(path, watchPath, follow, this);
  5959. }
  5960. // Directory helpers
  5961. // -----------------
  5962. /**
  5963. * Provides directory tracking objects
  5964. * @param {String} directory path of the directory
  5965. * @returns {DirEntry} the directory's tracking object
  5966. */
  5967. _getWatchedDir(directory) {
  5968. if (!this._boundRemove) this._boundRemove = this._remove.bind(this);
  5969. const dir = sysPath.resolve(directory);
  5970. if (!this._watched.has(dir)) this._watched.set(dir, new DirEntry(dir, this._boundRemove));
  5971. return this._watched.get(dir);
  5972. }
  5973. // File helpers
  5974. // ------------
  5975. /**
  5976. * Check for read permissions.
  5977. * Based on this answer on SO: https://stackoverflow.com/a/11781404/1358405
  5978. * @param {fs.Stats} stats - object, result of fs_stat
  5979. * @returns {Boolean} indicates whether the file can be read
  5980. */
  5981. _hasReadPermissions(stats) {
  5982. if (this.options.ignorePermissionErrors) return true;
  5983. // stats.mode may be bigint
  5984. const md = stats && Number.parseInt(stats.mode, 10);
  5985. const st = md & 0o777;
  5986. const it = Number.parseInt(st.toString(8)[0], 10);
  5987. return Boolean(4 & it);
  5988. }
  5989. /**
  5990. * Handles emitting unlink events for
  5991. * files and directories, and via recursion, for
  5992. * files and directories within directories that are unlinked
  5993. * @param {String} directory within which the following item is located
  5994. * @param {String} item base path of item/directory
  5995. * @returns {void}
  5996. */
  5997. _remove(directory, item, isDirectory) {
  5998. // if what is being deleted is a directory, get that directory's paths
  5999. // for recursive deleting and cleaning of watched object
  6000. // if it is not a directory, nestedDirectoryChildren will be empty array
  6001. const path = sysPath.join(directory, item);
  6002. const fullPath = sysPath.resolve(path);
  6003. isDirectory = isDirectory != null
  6004. ? isDirectory
  6005. : this._watched.has(path) || this._watched.has(fullPath);
  6006. // prevent duplicate handling in case of arriving here nearly simultaneously
  6007. // via multiple paths (such as _handleFile and _handleDir)
  6008. if (!this._throttle('remove', path, 100)) return;
  6009. // if the only watched file is removed, watch for its return
  6010. if (!isDirectory && !this.options.useFsEvents && this._watched.size === 1) {
  6011. this.add(directory, item, true);
  6012. }
  6013. // This will create a new entry in the watched object in either case
  6014. // so we got to do the directory check beforehand
  6015. const wp = this._getWatchedDir(path);
  6016. const nestedDirectoryChildren = wp.getChildren();
  6017. // Recursively remove children directories / files.
  6018. nestedDirectoryChildren.forEach(nested => this._remove(path, nested));
  6019. // Check if item was on the watched list and remove it
  6020. const parent = this._getWatchedDir(directory);
  6021. const wasTracked = parent.has(item);
  6022. parent.remove(item);
  6023. // Fixes issue #1042 -> Relative paths were detected and added as symlinks
  6024. // (https://github.com/paulmillr/chokidar/blob/e1753ddbc9571bdc33b4a4af172d52cb6e611c10/lib/nodefs-handler.js#L612),
  6025. // but never removed from the map in case the path was deleted.
  6026. // This leads to an incorrect state if the path was recreated:
  6027. // https://github.com/paulmillr/chokidar/blob/e1753ddbc9571bdc33b4a4af172d52cb6e611c10/lib/nodefs-handler.js#L553
  6028. if (this._symlinkPaths.has(fullPath)) {
  6029. this._symlinkPaths.delete(fullPath);
  6030. }
  6031. // If we wait for this file to be fully written, cancel the wait.
  6032. let relPath = path;
  6033. if (this.options.cwd) relPath = sysPath.relative(this.options.cwd, path);
  6034. if (this.options.awaitWriteFinish && this._pendingWrites.has(relPath)) {
  6035. const event = this._pendingWrites.get(relPath).cancelWait();
  6036. if (event === EV_ADD) return;
  6037. }
  6038. // The Entry will either be a directory that just got removed
  6039. // or a bogus entry to a file, in either case we have to remove it
  6040. this._watched.delete(path);
  6041. this._watched.delete(fullPath);
  6042. const eventName = isDirectory ? EV_UNLINK_DIR : EV_UNLINK;
  6043. if (wasTracked && !this._isIgnored(path)) this._emit(eventName, path);
  6044. // Avoid conflicts if we later create another file with the same name
  6045. if (!this.options.useFsEvents) {
  6046. this._closePath(path);
  6047. }
  6048. }
  6049. /**
  6050. * Closes all watchers for a path
  6051. * @param {Path} path
  6052. */
  6053. _closePath(path) {
  6054. this._closeFile(path);
  6055. const dir = sysPath.dirname(path);
  6056. this._getWatchedDir(dir).remove(sysPath.basename(path));
  6057. }
  6058. /**
  6059. * Closes only file-specific watchers
  6060. * @param {Path} path
  6061. */
  6062. _closeFile(path) {
  6063. const closers = this._closers.get(path);
  6064. if (!closers) return;
  6065. closers.forEach(closer => closer());
  6066. this._closers.delete(path);
  6067. }
  6068. /**
  6069. *
  6070. * @param {Path} path
  6071. * @param {Function} closer
  6072. */
  6073. _addPathCloser(path, closer) {
  6074. if (!closer) return;
  6075. let list = this._closers.get(path);
  6076. if (!list) {
  6077. list = [];
  6078. this._closers.set(path, list);
  6079. }
  6080. list.push(closer);
  6081. }
  6082. _readdirp(root, opts) {
  6083. if (this.closed) return;
  6084. const options = {type: EV_ALL, alwaysStat: true, lstat: true, ...opts};
  6085. let stream = readdirp(root, options);
  6086. this._streams.add(stream);
  6087. stream.once(STR_CLOSE, () => {
  6088. stream = undefined;
  6089. });
  6090. stream.once(STR_END, () => {
  6091. if (stream) {
  6092. this._streams.delete(stream);
  6093. stream = undefined;
  6094. }
  6095. });
  6096. return stream;
  6097. }
  6098. }
  6099. // Export FSWatcher class
  6100. chokidar.FSWatcher = FSWatcher;
  6101. /**
  6102. * Instantiates watcher with paths to be tracked.
  6103. * @param {String|Array<String>} paths file/directory paths and/or globs
  6104. * @param {Object=} options chokidar opts
  6105. * @returns an instance of FSWatcher for chaining.
  6106. */
  6107. const watch = (paths, options) => {
  6108. const watcher = new FSWatcher(options);
  6109. watcher.add(paths);
  6110. return watcher;
  6111. };
  6112. chokidar.watch = watch;
  6113. class FileWatcher {
  6114. constructor(task, chokidarOptions) {
  6115. this.transformWatchers = new Map();
  6116. this.chokidarOptions = chokidarOptions;
  6117. this.task = task;
  6118. this.watcher = this.createWatcher(null);
  6119. }
  6120. close() {
  6121. this.watcher.close();
  6122. for (const watcher of this.transformWatchers.values()) {
  6123. watcher.close();
  6124. }
  6125. }
  6126. unwatch(id) {
  6127. this.watcher.unwatch(id);
  6128. const transformWatcher = this.transformWatchers.get(id);
  6129. if (transformWatcher) {
  6130. this.transformWatchers.delete(id);
  6131. transformWatcher.close();
  6132. }
  6133. }
  6134. watch(id, isTransformDependency) {
  6135. if (isTransformDependency) {
  6136. const watcher = this.transformWatchers.get(id) || this.createWatcher(id);
  6137. watcher.add(id);
  6138. this.transformWatchers.set(id, watcher);
  6139. }
  6140. else {
  6141. this.watcher.add(id);
  6142. }
  6143. }
  6144. createWatcher(transformWatcherId) {
  6145. const task = this.task;
  6146. const isLinux = platform() === 'linux';
  6147. const isTransformDependency = transformWatcherId !== null;
  6148. const handleChange = (id, event) => {
  6149. const changedId = transformWatcherId || id;
  6150. if (isLinux) {
  6151. // unwatching and watching fixes an issue with chokidar where on certain systems,
  6152. // a file that was unlinked and immediately recreated would create a change event
  6153. // but then no longer any further events
  6154. watcher.unwatch(changedId);
  6155. watcher.add(changedId);
  6156. }
  6157. task.invalidate(changedId, { isTransformDependency, event });
  6158. };
  6159. const watcher = chokidar
  6160. .watch([], this.chokidarOptions)
  6161. .on('add', id => handleChange(id, 'create'))
  6162. .on('change', id => handleChange(id, 'update'))
  6163. .on('unlink', id => handleChange(id, 'delete'));
  6164. return watcher;
  6165. }
  6166. }
  6167. const eventsRewrites = {
  6168. create: {
  6169. create: 'buggy',
  6170. delete: null,
  6171. update: 'create'
  6172. },
  6173. delete: {
  6174. create: 'update',
  6175. delete: 'buggy',
  6176. update: 'buggy'
  6177. },
  6178. update: {
  6179. create: 'buggy',
  6180. delete: 'delete',
  6181. update: 'update'
  6182. }
  6183. };
  6184. class Watcher {
  6185. constructor(configs, emitter) {
  6186. this.buildDelay = 0;
  6187. this.buildTimeout = null;
  6188. this.invalidatedIds = new Map();
  6189. this.rerun = false;
  6190. this.emitter = emitter;
  6191. emitter.close = this.close.bind(this);
  6192. this.tasks = configs.map(config => new Task(this, config));
  6193. this.buildDelay = configs.reduce((buildDelay, { watch }) => watch && typeof watch.buildDelay === 'number'
  6194. ? Math.max(buildDelay, watch.buildDelay)
  6195. : buildDelay, this.buildDelay);
  6196. this.running = true;
  6197. process.nextTick(() => this.run());
  6198. }
  6199. close() {
  6200. if (this.buildTimeout)
  6201. clearTimeout(this.buildTimeout);
  6202. for (const task of this.tasks) {
  6203. task.close();
  6204. }
  6205. this.emitter.emit('close');
  6206. this.emitter.removeAllListeners();
  6207. }
  6208. invalidate(file) {
  6209. if (file) {
  6210. const prevEvent = this.invalidatedIds.get(file.id);
  6211. const event = prevEvent ? eventsRewrites[prevEvent][file.event] : file.event;
  6212. if (event === 'buggy') {
  6213. //TODO: throws or warn? Currently just ignore, uses new event
  6214. this.invalidatedIds.set(file.id, file.event);
  6215. }
  6216. else if (event === null) {
  6217. this.invalidatedIds.delete(file.id);
  6218. }
  6219. else {
  6220. this.invalidatedIds.set(file.id, event);
  6221. }
  6222. }
  6223. if (this.running) {
  6224. this.rerun = true;
  6225. return;
  6226. }
  6227. if (this.buildTimeout)
  6228. clearTimeout(this.buildTimeout);
  6229. this.buildTimeout = setTimeout(() => {
  6230. this.buildTimeout = null;
  6231. for (const [id, event] of this.invalidatedIds.entries()) {
  6232. this.emitter.emit('change', id, { event });
  6233. }
  6234. this.invalidatedIds.clear();
  6235. this.emitter.emit('restart');
  6236. this.run();
  6237. }, this.buildDelay);
  6238. }
  6239. async run() {
  6240. this.running = true;
  6241. this.emitter.emit('event', {
  6242. code: 'START'
  6243. });
  6244. for (const task of this.tasks) {
  6245. await task.run();
  6246. }
  6247. this.running = false;
  6248. this.emitter.emit('event', {
  6249. code: 'END'
  6250. });
  6251. if (this.rerun) {
  6252. this.rerun = false;
  6253. this.invalidate();
  6254. }
  6255. }
  6256. }
  6257. class Task {
  6258. constructor(watcher, config) {
  6259. this.cache = { modules: [] };
  6260. this.watchFiles = [];
  6261. this.invalidated = true;
  6262. this.watcher = watcher;
  6263. this.closed = false;
  6264. this.watched = new Set();
  6265. this.skipWrite = Boolean(config.watch && config.watch.skipWrite);
  6266. this.options = mergeOptions(config);
  6267. this.outputs = this.options.output;
  6268. this.outputFiles = this.outputs.map(output => {
  6269. if (output.file || output.dir)
  6270. return resolve(output.file || output.dir);
  6271. return undefined;
  6272. });
  6273. const watchOptions = this.options.watch || {};
  6274. this.filter = createFilter(watchOptions.include, watchOptions.exclude);
  6275. this.fileWatcher = new FileWatcher(this, {
  6276. ...watchOptions.chokidar,
  6277. disableGlobbing: true,
  6278. ignoreInitial: true
  6279. });
  6280. }
  6281. close() {
  6282. this.closed = true;
  6283. this.fileWatcher.close();
  6284. }
  6285. invalidate(id, details) {
  6286. this.invalidated = true;
  6287. if (details.isTransformDependency) {
  6288. for (const module of this.cache.modules) {
  6289. if (module.transformDependencies.indexOf(id) === -1)
  6290. continue;
  6291. // effective invalidation
  6292. module.originalCode = null;
  6293. }
  6294. }
  6295. this.watcher.invalidate({ id, event: details.event });
  6296. }
  6297. async run() {
  6298. if (!this.invalidated)
  6299. return;
  6300. this.invalidated = false;
  6301. const options = {
  6302. ...this.options,
  6303. cache: this.cache
  6304. };
  6305. const start = Date.now();
  6306. this.watcher.emitter.emit('event', {
  6307. code: 'BUNDLE_START',
  6308. input: this.options.input,
  6309. output: this.outputFiles
  6310. });
  6311. let result = null;
  6312. try {
  6313. result = await rollupInternal(options, this.watcher.emitter);
  6314. if (this.closed) {
  6315. return;
  6316. }
  6317. this.updateWatchedFiles(result);
  6318. this.skipWrite || (await Promise.all(this.outputs.map(output => result.write(output))));
  6319. this.watcher.emitter.emit('event', {
  6320. code: 'BUNDLE_END',
  6321. duration: Date.now() - start,
  6322. input: this.options.input,
  6323. output: this.outputFiles,
  6324. result
  6325. });
  6326. }
  6327. catch (error) {
  6328. if (!this.closed) {
  6329. if (Array.isArray(error.watchFiles)) {
  6330. for (const id of error.watchFiles) {
  6331. this.watchFile(id);
  6332. }
  6333. }
  6334. if (error.id) {
  6335. this.cache.modules = this.cache.modules.filter(module => module.id !== error.id);
  6336. }
  6337. }
  6338. this.watcher.emitter.emit('event', {
  6339. code: 'ERROR',
  6340. error,
  6341. result
  6342. });
  6343. }
  6344. }
  6345. updateWatchedFiles(result) {
  6346. const previouslyWatched = this.watched;
  6347. this.watched = new Set();
  6348. this.watchFiles = result.watchFiles;
  6349. this.cache = result.cache;
  6350. for (const id of this.watchFiles) {
  6351. this.watchFile(id);
  6352. }
  6353. for (const module of this.cache.modules) {
  6354. for (const depId of module.transformDependencies) {
  6355. this.watchFile(depId, true);
  6356. }
  6357. }
  6358. for (const id of previouslyWatched) {
  6359. if (!this.watched.has(id)) {
  6360. this.fileWatcher.unwatch(id);
  6361. }
  6362. }
  6363. }
  6364. watchFile(id, isTransformDependency = false) {
  6365. if (!this.filter(id))
  6366. return;
  6367. this.watched.add(id);
  6368. if (this.outputFiles.some(file => file === id)) {
  6369. throw new Error('Cannot import the generated bundle');
  6370. }
  6371. // this is necessary to ensure that any 'renamed' files
  6372. // continue to be watched following an error
  6373. this.fileWatcher.watch(id, isTransformDependency);
  6374. }
  6375. }
  6376. export { Task, Watcher };