index.js 166 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479
  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. 'use strict';
  9. var require$$0$2 = require('events');
  10. var fs$4 = require('fs');
  11. var path$3 = require('path');
  12. var require$$0$1 = require('util');
  13. var require$$1 = require('stream');
  14. var require$$2 = require('os');
  15. var rollup = require('./rollup.js');
  16. var utils$7 = {};
  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$7));
  112. const utils$6 = utils$7;
  113. var stringify$4 = (ast, options = {}) => {
  114. let stringify = (node, parent = {}) => {
  115. let invalidBlock = options.escapeInvalid && utils$6.isInvalidBrace(parent);
  116. let invalidNode = node.invalid === true && options.escapeInvalid === true;
  117. let output = '';
  118. if (node.value) {
  119. if ((invalidBlock || invalidNode) && utils$6.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 = 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.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$5 = utils$7;
  576. const compile$1 = (ast, options = {}) => {
  577. let walk = (node, parent = {}) => {
  578. let invalidBlock = utils$5.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$5.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$4 = utils$7;
  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$4.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$4.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$4.reduce(node.nodes);
  663. if (utils$4.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$4.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$4.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$1 = (input, options = {}) => {
  1037. let output = [];
  1038. if (Array.isArray(input)) {
  1039. for (let pattern of input) {
  1040. let result = braces$1.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$1.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$1.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$1.stringify = (input, options = {}) => {
  1083. if (typeof input === 'string') {
  1084. return stringify(braces$1.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$1.compile = (input, options = {}) => {
  1103. if (typeof input === 'string') {
  1104. input = braces$1.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$1.expand = (input, options = {}) => {
  1125. if (typeof input === 'string') {
  1126. input = braces$1.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$1.create = (input, options = {}) => {
  1155. if (input === '' || input.length < 3) {
  1156. return [input];
  1157. }
  1158. return options.expand !== true
  1159. ? braces$1.compile(input, options)
  1160. : braces$1.expand(input, options);
  1161. };
  1162. /**
  1163. * Expose "braces"
  1164. */
  1165. var braces_1 = braces$1;
  1166. var utils$3 = {};
  1167. const path$2 = path$3;
  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 = path$3;
  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$3));
  1379. const utils$2 = utils$3;
  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$2.removeBackslashes(glob);
  1640. if (base && backslashes === true) {
  1641. base = utils$2.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$1 = utils$3;
  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$1.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$1.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$1.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$1.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$1.hasRegexChars(prevValue)) {
  2108. continue;
  2109. }
  2110. const escaped = utils$1.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$1.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$1.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$1.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$1.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$1.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$1.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 = path$3;
  2564. const scan = scan_1;
  2565. const parse = parse_1;
  2566. const utils = utils$3;
  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$3 = (glob, options, returnState = false) => {
  2591. if (Array.isArray(glob)) {
  2592. const fns = glob.map(input => picomatch$3(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.isWindows(options);
  2608. const regex = isState
  2609. ? picomatch$3.compileRe(glob, options)
  2610. : picomatch$3.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$3(opts.ignore, ignoreOpts, returnState);
  2617. }
  2618. const matcher = (input, returnObject = false) => {
  2619. const { isMatch, match, output } = picomatch$3.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$3.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.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$3.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$3.matchBase = (input, glob, options, posix = utils.isWindows(options)) => {
  2699. const regex = glob instanceof RegExp ? glob : picomatch$3.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$3.isMatch = (str, patterns, options) => picomatch$3(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$3.parse = (pattern, options) => {
  2733. if (Array.isArray(pattern)) return pattern.map(p => picomatch$3.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$3.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$3.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$3.toRegex(source, options);
  2791. if (returnState === true) {
  2792. regex.state = parsed;
  2793. }
  2794. return regex;
  2795. };
  2796. picomatch$3.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$3.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$3.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$3.constants = constants$1;
  2849. /**
  2850. * Expose "picomatch"
  2851. */
  2852. var picomatch_1 = picomatch$3;
  2853. var picomatch$2 = picomatch_1;
  2854. var chokidar = {};
  2855. const fs$3 = fs$4;
  2856. const { Readable } = require$$1;
  2857. const sysPath$3 = path$3;
  2858. const { promisify: promisify$3 } = require$$0$1;
  2859. const picomatch$1 = picomatch$2;
  2860. const readdir$1 = promisify$3(fs$3.readdir);
  2861. const stat$3 = promisify$3(fs$3.stat);
  2862. const lstat$2 = promisify$3(fs$3.lstat);
  2863. const realpath$1 = promisify$3(fs$3.realpath);
  2864. /**
  2865. * @typedef {Object} EntryInfo
  2866. * @property {String} path
  2867. * @property {String} fullPath
  2868. * @property {fs.Stats=} stats
  2869. * @property {fs.Dirent=} dirent
  2870. * @property {String} basename
  2871. */
  2872. const BANG$2 = '!';
  2873. const NORMAL_FLOW_ERRORS = new Set(['ENOENT', 'EPERM', 'EACCES', 'ELOOP']);
  2874. const FILE_TYPE = 'files';
  2875. const DIR_TYPE = 'directories';
  2876. const FILE_DIR_TYPE = 'files_directories';
  2877. const EVERYTHING_TYPE = 'all';
  2878. const ALL_TYPES = [FILE_TYPE, DIR_TYPE, FILE_DIR_TYPE, EVERYTHING_TYPE];
  2879. const isNormalFlowError = error => NORMAL_FLOW_ERRORS.has(error.code);
  2880. const normalizeFilter = filter => {
  2881. if (filter === undefined) return;
  2882. if (typeof filter === 'function') return filter;
  2883. if (typeof filter === 'string') {
  2884. const glob = picomatch$1(filter.trim());
  2885. return entry => glob(entry.basename);
  2886. }
  2887. if (Array.isArray(filter)) {
  2888. const positive = [];
  2889. const negative = [];
  2890. for (const item of filter) {
  2891. const trimmed = item.trim();
  2892. if (trimmed.charAt(0) === BANG$2) {
  2893. negative.push(picomatch$1(trimmed.slice(1)));
  2894. } else {
  2895. positive.push(picomatch$1(trimmed));
  2896. }
  2897. }
  2898. if (negative.length > 0) {
  2899. if (positive.length > 0) {
  2900. return entry =>
  2901. positive.some(f => f(entry.basename)) && !negative.some(f => f(entry.basename));
  2902. }
  2903. return entry => !negative.some(f => f(entry.basename));
  2904. }
  2905. return entry => positive.some(f => f(entry.basename));
  2906. }
  2907. };
  2908. class ReaddirpStream extends Readable {
  2909. static get defaultOptions() {
  2910. return {
  2911. root: '.',
  2912. /* eslint-disable no-unused-vars */
  2913. fileFilter: (path) => true,
  2914. directoryFilter: (path) => true,
  2915. /* eslint-enable no-unused-vars */
  2916. type: FILE_TYPE,
  2917. lstat: false,
  2918. depth: 2147483648,
  2919. alwaysStat: false
  2920. };
  2921. }
  2922. constructor(options = {}) {
  2923. super({
  2924. objectMode: true,
  2925. autoDestroy: true,
  2926. highWaterMark: options.highWaterMark || 4096
  2927. });
  2928. const opts = { ...ReaddirpStream.defaultOptions, ...options };
  2929. const { root, type } = opts;
  2930. this._fileFilter = normalizeFilter(opts.fileFilter);
  2931. this._directoryFilter = normalizeFilter(opts.directoryFilter);
  2932. const statMethod = opts.lstat ? lstat$2 : stat$3;
  2933. // Use bigint stats if it's windows and stat() supports options (node 10+).
  2934. if (process.platform === 'win32' && stat$3.length === 3) {
  2935. this._stat = path => statMethod(path, { bigint: true });
  2936. } else {
  2937. this._stat = statMethod;
  2938. }
  2939. this._maxDepth = opts.depth;
  2940. this._wantsDir = [DIR_TYPE, FILE_DIR_TYPE, EVERYTHING_TYPE].includes(type);
  2941. this._wantsFile = [FILE_TYPE, FILE_DIR_TYPE, EVERYTHING_TYPE].includes(type);
  2942. this._wantsEverything = type === EVERYTHING_TYPE;
  2943. this._root = sysPath$3.resolve(root);
  2944. this._isDirent = ('Dirent' in fs$3) && !opts.alwaysStat;
  2945. this._statsProp = this._isDirent ? 'dirent' : 'stats';
  2946. this._rdOptions = { encoding: 'utf8', withFileTypes: this._isDirent };
  2947. // Launch stream with one parent, the root dir.
  2948. this.parents = [this._exploreDir(root, 1)];
  2949. this.reading = false;
  2950. this.parent = undefined;
  2951. }
  2952. async _read(batch) {
  2953. if (this.reading) return;
  2954. this.reading = true;
  2955. try {
  2956. while (!this.destroyed && batch > 0) {
  2957. const { path, depth, files = [] } = this.parent || {};
  2958. if (files.length > 0) {
  2959. const slice = files.splice(0, batch).map(dirent => this._formatEntry(dirent, path));
  2960. for (const entry of await Promise.all(slice)) {
  2961. if (this.destroyed) return;
  2962. const entryType = await this._getEntryType(entry);
  2963. if (entryType === 'directory' && this._directoryFilter(entry)) {
  2964. if (depth <= this._maxDepth) {
  2965. this.parents.push(this._exploreDir(entry.fullPath, depth + 1));
  2966. }
  2967. if (this._wantsDir) {
  2968. this.push(entry);
  2969. batch--;
  2970. }
  2971. } else if ((entryType === 'file' || this._includeAsFile(entry)) && this._fileFilter(entry)) {
  2972. if (this._wantsFile) {
  2973. this.push(entry);
  2974. batch--;
  2975. }
  2976. }
  2977. }
  2978. } else {
  2979. const parent = this.parents.pop();
  2980. if (!parent) {
  2981. this.push(null);
  2982. break;
  2983. }
  2984. this.parent = await parent;
  2985. if (this.destroyed) return;
  2986. }
  2987. }
  2988. } catch (error) {
  2989. this.destroy(error);
  2990. } finally {
  2991. this.reading = false;
  2992. }
  2993. }
  2994. async _exploreDir(path, depth) {
  2995. let files;
  2996. try {
  2997. files = await readdir$1(path, this._rdOptions);
  2998. } catch (error) {
  2999. this._onError(error);
  3000. }
  3001. return {files, depth, path};
  3002. }
  3003. async _formatEntry(dirent, path) {
  3004. let entry;
  3005. try {
  3006. const basename = this._isDirent ? dirent.name : dirent;
  3007. const fullPath = sysPath$3.resolve(sysPath$3.join(path, basename));
  3008. entry = {path: sysPath$3.relative(this._root, fullPath), fullPath, basename};
  3009. entry[this._statsProp] = this._isDirent ? dirent : await this._stat(fullPath);
  3010. } catch (err) {
  3011. this._onError(err);
  3012. }
  3013. return entry;
  3014. }
  3015. _onError(err) {
  3016. if (isNormalFlowError(err) && !this.destroyed) {
  3017. this.emit('warn', err);
  3018. } else {
  3019. this.destroy(err);
  3020. }
  3021. }
  3022. async _getEntryType(entry) {
  3023. // entry may be undefined, because a warning or an error were emitted
  3024. // and the statsProp is undefined
  3025. const stats = entry && entry[this._statsProp];
  3026. if (!stats) {
  3027. return;
  3028. }
  3029. if (stats.isFile()) {
  3030. return 'file';
  3031. }
  3032. if (stats.isDirectory()) {
  3033. return 'directory';
  3034. }
  3035. if (stats && stats.isSymbolicLink()) {
  3036. const full = entry.fullPath;
  3037. try {
  3038. const entryRealPath = await realpath$1(full);
  3039. const entryRealPathStats = await lstat$2(entryRealPath);
  3040. if (entryRealPathStats.isFile()) {
  3041. return 'file';
  3042. }
  3043. if (entryRealPathStats.isDirectory()) {
  3044. const len = entryRealPath.length;
  3045. if (full.startsWith(entryRealPath) && full.substr(len, 1) === sysPath$3.sep) {
  3046. return this._onError(new Error(
  3047. `Circular symlink detected: "${full}" points to "${entryRealPath}"`
  3048. ));
  3049. }
  3050. return 'directory';
  3051. }
  3052. } catch (error) {
  3053. this._onError(error);
  3054. }
  3055. }
  3056. }
  3057. _includeAsFile(entry) {
  3058. const stats = entry && entry[this._statsProp];
  3059. return stats && this._wantsEverything && !stats.isDirectory();
  3060. }
  3061. }
  3062. /**
  3063. * @typedef {Object} ReaddirpArguments
  3064. * @property {Function=} fileFilter
  3065. * @property {Function=} directoryFilter
  3066. * @property {String=} type
  3067. * @property {Number=} depth
  3068. * @property {String=} root
  3069. * @property {Boolean=} lstat
  3070. * @property {Boolean=} bigint
  3071. */
  3072. /**
  3073. * Main function which ends up calling readdirRec and reads all files and directories in given root recursively.
  3074. * @param {String} root Root directory
  3075. * @param {ReaddirpArguments=} options Options to specify root (start directory), filters and recursion depth
  3076. */
  3077. const readdirp$1 = (root, options = {}) => {
  3078. let type = options.entryType || options.type;
  3079. if (type === 'both') type = FILE_DIR_TYPE; // backwards-compatibility
  3080. if (type) options.type = type;
  3081. if (!root) {
  3082. throw new Error('readdirp: root argument is required. Usage: readdirp(root, options)');
  3083. } else if (typeof root !== 'string') {
  3084. throw new TypeError('readdirp: root argument must be a string. Usage: readdirp(root, options)');
  3085. } else if (type && !ALL_TYPES.includes(type)) {
  3086. throw new Error(`readdirp: Invalid type passed. Use one of ${ALL_TYPES.join(', ')}`);
  3087. }
  3088. options.root = root;
  3089. return new ReaddirpStream(options);
  3090. };
  3091. const readdirpPromise = (root, options = {}) => {
  3092. return new Promise((resolve, reject) => {
  3093. const files = [];
  3094. readdirp$1(root, options)
  3095. .on('data', entry => files.push(entry))
  3096. .on('end', () => resolve(files))
  3097. .on('error', error => reject(error));
  3098. });
  3099. };
  3100. readdirp$1.promise = readdirpPromise;
  3101. readdirp$1.ReaddirpStream = ReaddirpStream;
  3102. readdirp$1.default = readdirp$1;
  3103. var readdirp_1 = readdirp$1;
  3104. var anymatch$2 = {exports: {}};
  3105. /*!
  3106. * normalize-path <https://github.com/jonschlinkert/normalize-path>
  3107. *
  3108. * Copyright (c) 2014-2018, Jon Schlinkert.
  3109. * Released under the MIT License.
  3110. */
  3111. var normalizePath$2 = function(path, stripTrailing) {
  3112. if (typeof path !== 'string') {
  3113. throw new TypeError('expected path to be a string');
  3114. }
  3115. if (path === '\\' || path === '/') return '/';
  3116. var len = path.length;
  3117. if (len <= 1) return path;
  3118. // ensure that win32 namespaces has two leading slashes, so that the path is
  3119. // handled properly by the win32 version of path.parse() after being normalized
  3120. // https://msdn.microsoft.com/library/windows/desktop/aa365247(v=vs.85).aspx#namespaces
  3121. var prefix = '';
  3122. if (len > 4 && path[3] === '\\') {
  3123. var ch = path[2];
  3124. if ((ch === '?' || ch === '.') && path.slice(0, 2) === '\\\\') {
  3125. path = path.slice(2);
  3126. prefix = '//';
  3127. }
  3128. }
  3129. var segs = path.split(/[/\\]+/);
  3130. if (stripTrailing !== false && segs[segs.length - 1] === '') {
  3131. segs.pop();
  3132. }
  3133. return prefix + segs.join('/');
  3134. };
  3135. Object.defineProperty(anymatch$2.exports, "__esModule", { value: true });
  3136. const picomatch = picomatch$2;
  3137. const normalizePath$1 = normalizePath$2;
  3138. /**
  3139. * @typedef {(testString: string) => boolean} AnymatchFn
  3140. * @typedef {string|RegExp|AnymatchFn} AnymatchPattern
  3141. * @typedef {AnymatchPattern|AnymatchPattern[]} AnymatchMatcher
  3142. */
  3143. const BANG$1 = '!';
  3144. const DEFAULT_OPTIONS = {returnIndex: false};
  3145. const arrify$1 = (item) => Array.isArray(item) ? item : [item];
  3146. /**
  3147. * @param {AnymatchPattern} matcher
  3148. * @param {object} options
  3149. * @returns {AnymatchFn}
  3150. */
  3151. const createPattern = (matcher, options) => {
  3152. if (typeof matcher === 'function') {
  3153. return matcher;
  3154. }
  3155. if (typeof matcher === 'string') {
  3156. const glob = picomatch(matcher, options);
  3157. return (string) => matcher === string || glob(string);
  3158. }
  3159. if (matcher instanceof RegExp) {
  3160. return (string) => matcher.test(string);
  3161. }
  3162. return (string) => false;
  3163. };
  3164. /**
  3165. * @param {Array<Function>} patterns
  3166. * @param {Array<Function>} negPatterns
  3167. * @param {String|Array} args
  3168. * @param {Boolean} returnIndex
  3169. * @returns {boolean|number}
  3170. */
  3171. const matchPatterns = (patterns, negPatterns, args, returnIndex) => {
  3172. const isList = Array.isArray(args);
  3173. const _path = isList ? args[0] : args;
  3174. if (!isList && typeof _path !== 'string') {
  3175. throw new TypeError('anymatch: second argument must be a string: got ' +
  3176. Object.prototype.toString.call(_path))
  3177. }
  3178. const path = normalizePath$1(_path);
  3179. for (let index = 0; index < negPatterns.length; index++) {
  3180. const nglob = negPatterns[index];
  3181. if (nglob(path)) {
  3182. return returnIndex ? -1 : false;
  3183. }
  3184. }
  3185. const applied = isList && [path].concat(args.slice(1));
  3186. for (let index = 0; index < patterns.length; index++) {
  3187. const pattern = patterns[index];
  3188. if (isList ? pattern(...applied) : pattern(path)) {
  3189. return returnIndex ? index : true;
  3190. }
  3191. }
  3192. return returnIndex ? -1 : false;
  3193. };
  3194. /**
  3195. * @param {AnymatchMatcher} matchers
  3196. * @param {Array|string} testString
  3197. * @param {object} options
  3198. * @returns {boolean|number|Function}
  3199. */
  3200. const anymatch$1 = (matchers, testString, options = DEFAULT_OPTIONS) => {
  3201. if (matchers == null) {
  3202. throw new TypeError('anymatch: specify first argument');
  3203. }
  3204. const opts = typeof options === 'boolean' ? {returnIndex: options} : options;
  3205. const returnIndex = opts.returnIndex || false;
  3206. // Early cache for matchers.
  3207. const mtchers = arrify$1(matchers);
  3208. const negatedGlobs = mtchers
  3209. .filter(item => typeof item === 'string' && item.charAt(0) === BANG$1)
  3210. .map(item => item.slice(1))
  3211. .map(item => picomatch(item, opts));
  3212. const patterns = mtchers.map(matcher => createPattern(matcher, opts));
  3213. if (testString == null) {
  3214. return (testString, ri = false) => {
  3215. const returnIndex = typeof ri === 'boolean' ? ri : false;
  3216. return matchPatterns(patterns, negatedGlobs, testString, returnIndex);
  3217. }
  3218. }
  3219. return matchPatterns(patterns, negatedGlobs, testString, returnIndex);
  3220. };
  3221. anymatch$1.default = anymatch$1;
  3222. anymatch$2.exports = anymatch$1;
  3223. /*!
  3224. * is-extglob <https://github.com/jonschlinkert/is-extglob>
  3225. *
  3226. * Copyright (c) 2014-2016, Jon Schlinkert.
  3227. * Licensed under the MIT License.
  3228. */
  3229. var isExtglob$1 = function isExtglob(str) {
  3230. if (typeof str !== 'string' || str === '') {
  3231. return false;
  3232. }
  3233. var match;
  3234. while ((match = /(\\).|([@?!+*]\(.*\))/g.exec(str))) {
  3235. if (match[2]) return true;
  3236. str = str.slice(match.index + match[0].length);
  3237. }
  3238. return false;
  3239. };
  3240. /*!
  3241. * is-glob <https://github.com/jonschlinkert/is-glob>
  3242. *
  3243. * Copyright (c) 2014-2017, Jon Schlinkert.
  3244. * Released under the MIT License.
  3245. */
  3246. var isExtglob = isExtglob$1;
  3247. var chars = { '{': '}', '(': ')', '[': ']'};
  3248. var strictRegex = /\\(.)|(^!|\*|[\].+)]\?|\[[^\\\]]+\]|\{[^\\}]+\}|\(\?[:!=][^\\)]+\)|\([^|]+\|[^\\)]+\))/;
  3249. var relaxedRegex = /\\(.)|(^!|[*?{}()[\]]|\(\?)/;
  3250. var isGlob$2 = function isGlob(str, options) {
  3251. if (typeof str !== 'string' || str === '') {
  3252. return false;
  3253. }
  3254. if (isExtglob(str)) {
  3255. return true;
  3256. }
  3257. var regex = strictRegex;
  3258. var match;
  3259. // optionally relax regex
  3260. if (options && options.strict === false) {
  3261. regex = relaxedRegex;
  3262. }
  3263. while ((match = regex.exec(str))) {
  3264. if (match[2]) return true;
  3265. var idx = match.index + match[0].length;
  3266. // if an open bracket/brace/paren is escaped,
  3267. // set the index to the next closing character
  3268. var open = match[1];
  3269. var close = open ? chars[open] : null;
  3270. if (open && close) {
  3271. var n = str.indexOf(close, idx);
  3272. if (n !== -1) {
  3273. idx = n + 1;
  3274. }
  3275. }
  3276. str = str.slice(idx);
  3277. }
  3278. return false;
  3279. };
  3280. var isGlob$1 = isGlob$2;
  3281. var pathPosixDirname = path$3.posix.dirname;
  3282. var isWin32 = require$$2.platform() === 'win32';
  3283. var slash = '/';
  3284. var backslash = /\\/g;
  3285. var enclosure = /[\{\[].*[\/]*.*[\}\]]$/;
  3286. var globby = /(^|[^\\])([\{\[]|\([^\)]+$)/;
  3287. var escaped = /\\([\!\*\?\|\[\]\(\)\{\}])/g;
  3288. /**
  3289. * @param {string} str
  3290. * @param {Object} opts
  3291. * @param {boolean} [opts.flipBackslashes=true]
  3292. */
  3293. var globParent$1 = function globParent(str, opts) {
  3294. var options = Object.assign({ flipBackslashes: true }, opts);
  3295. // flip windows path separators
  3296. if (options.flipBackslashes && isWin32 && str.indexOf(slash) < 0) {
  3297. str = str.replace(backslash, slash);
  3298. }
  3299. // special case for strings ending in enclosure containing path separator
  3300. if (enclosure.test(str)) {
  3301. str += slash;
  3302. }
  3303. // preserves full path in case of trailing path separator
  3304. str += 'a';
  3305. // remove path parts that are globby
  3306. do {
  3307. str = pathPosixDirname(str);
  3308. } while (isGlob$1(str) || globby.test(str));
  3309. // remove escape chars and return result
  3310. return str.replace(escaped, '$1');
  3311. };
  3312. var require$$0 = [
  3313. "3dm",
  3314. "3ds",
  3315. "3g2",
  3316. "3gp",
  3317. "7z",
  3318. "a",
  3319. "aac",
  3320. "adp",
  3321. "ai",
  3322. "aif",
  3323. "aiff",
  3324. "alz",
  3325. "ape",
  3326. "apk",
  3327. "appimage",
  3328. "ar",
  3329. "arj",
  3330. "asf",
  3331. "au",
  3332. "avi",
  3333. "bak",
  3334. "baml",
  3335. "bh",
  3336. "bin",
  3337. "bk",
  3338. "bmp",
  3339. "btif",
  3340. "bz2",
  3341. "bzip2",
  3342. "cab",
  3343. "caf",
  3344. "cgm",
  3345. "class",
  3346. "cmx",
  3347. "cpio",
  3348. "cr2",
  3349. "cur",
  3350. "dat",
  3351. "dcm",
  3352. "deb",
  3353. "dex",
  3354. "djvu",
  3355. "dll",
  3356. "dmg",
  3357. "dng",
  3358. "doc",
  3359. "docm",
  3360. "docx",
  3361. "dot",
  3362. "dotm",
  3363. "dra",
  3364. "DS_Store",
  3365. "dsk",
  3366. "dts",
  3367. "dtshd",
  3368. "dvb",
  3369. "dwg",
  3370. "dxf",
  3371. "ecelp4800",
  3372. "ecelp7470",
  3373. "ecelp9600",
  3374. "egg",
  3375. "eol",
  3376. "eot",
  3377. "epub",
  3378. "exe",
  3379. "f4v",
  3380. "fbs",
  3381. "fh",
  3382. "fla",
  3383. "flac",
  3384. "flatpak",
  3385. "fli",
  3386. "flv",
  3387. "fpx",
  3388. "fst",
  3389. "fvt",
  3390. "g3",
  3391. "gh",
  3392. "gif",
  3393. "graffle",
  3394. "gz",
  3395. "gzip",
  3396. "h261",
  3397. "h263",
  3398. "h264",
  3399. "icns",
  3400. "ico",
  3401. "ief",
  3402. "img",
  3403. "ipa",
  3404. "iso",
  3405. "jar",
  3406. "jpeg",
  3407. "jpg",
  3408. "jpgv",
  3409. "jpm",
  3410. "jxr",
  3411. "key",
  3412. "ktx",
  3413. "lha",
  3414. "lib",
  3415. "lvp",
  3416. "lz",
  3417. "lzh",
  3418. "lzma",
  3419. "lzo",
  3420. "m3u",
  3421. "m4a",
  3422. "m4v",
  3423. "mar",
  3424. "mdi",
  3425. "mht",
  3426. "mid",
  3427. "midi",
  3428. "mj2",
  3429. "mka",
  3430. "mkv",
  3431. "mmr",
  3432. "mng",
  3433. "mobi",
  3434. "mov",
  3435. "movie",
  3436. "mp3",
  3437. "mp4",
  3438. "mp4a",
  3439. "mpeg",
  3440. "mpg",
  3441. "mpga",
  3442. "mxu",
  3443. "nef",
  3444. "npx",
  3445. "numbers",
  3446. "nupkg",
  3447. "o",
  3448. "odp",
  3449. "ods",
  3450. "odt",
  3451. "oga",
  3452. "ogg",
  3453. "ogv",
  3454. "otf",
  3455. "ott",
  3456. "pages",
  3457. "pbm",
  3458. "pcx",
  3459. "pdb",
  3460. "pdf",
  3461. "pea",
  3462. "pgm",
  3463. "pic",
  3464. "png",
  3465. "pnm",
  3466. "pot",
  3467. "potm",
  3468. "potx",
  3469. "ppa",
  3470. "ppam",
  3471. "ppm",
  3472. "pps",
  3473. "ppsm",
  3474. "ppsx",
  3475. "ppt",
  3476. "pptm",
  3477. "pptx",
  3478. "psd",
  3479. "pya",
  3480. "pyc",
  3481. "pyo",
  3482. "pyv",
  3483. "qt",
  3484. "rar",
  3485. "ras",
  3486. "raw",
  3487. "resources",
  3488. "rgb",
  3489. "rip",
  3490. "rlc",
  3491. "rmf",
  3492. "rmvb",
  3493. "rpm",
  3494. "rtf",
  3495. "rz",
  3496. "s3m",
  3497. "s7z",
  3498. "scpt",
  3499. "sgi",
  3500. "shar",
  3501. "snap",
  3502. "sil",
  3503. "sketch",
  3504. "slk",
  3505. "smv",
  3506. "snk",
  3507. "so",
  3508. "stl",
  3509. "suo",
  3510. "sub",
  3511. "swf",
  3512. "tar",
  3513. "tbz",
  3514. "tbz2",
  3515. "tga",
  3516. "tgz",
  3517. "thmx",
  3518. "tif",
  3519. "tiff",
  3520. "tlz",
  3521. "ttc",
  3522. "ttf",
  3523. "txz",
  3524. "udf",
  3525. "uvh",
  3526. "uvi",
  3527. "uvm",
  3528. "uvp",
  3529. "uvs",
  3530. "uvu",
  3531. "viv",
  3532. "vob",
  3533. "war",
  3534. "wav",
  3535. "wax",
  3536. "wbmp",
  3537. "wdp",
  3538. "weba",
  3539. "webm",
  3540. "webp",
  3541. "whl",
  3542. "wim",
  3543. "wm",
  3544. "wma",
  3545. "wmv",
  3546. "wmx",
  3547. "woff",
  3548. "woff2",
  3549. "wrm",
  3550. "wvx",
  3551. "xbm",
  3552. "xif",
  3553. "xla",
  3554. "xlam",
  3555. "xls",
  3556. "xlsb",
  3557. "xlsm",
  3558. "xlsx",
  3559. "xlt",
  3560. "xltm",
  3561. "xltx",
  3562. "xm",
  3563. "xmind",
  3564. "xpi",
  3565. "xpm",
  3566. "xwd",
  3567. "xz",
  3568. "z",
  3569. "zip",
  3570. "zipx"
  3571. ];
  3572. var binaryExtensions$1 = require$$0;
  3573. const path = path$3;
  3574. const binaryExtensions = binaryExtensions$1;
  3575. const extensions = new Set(binaryExtensions);
  3576. var isBinaryPath$1 = filePath => extensions.has(path.extname(filePath).slice(1).toLowerCase());
  3577. var constants = {};
  3578. (function (exports) {
  3579. const {sep} = path$3;
  3580. const {platform} = process;
  3581. exports.EV_ALL = 'all';
  3582. exports.EV_READY = 'ready';
  3583. exports.EV_ADD = 'add';
  3584. exports.EV_CHANGE = 'change';
  3585. exports.EV_ADD_DIR = 'addDir';
  3586. exports.EV_UNLINK = 'unlink';
  3587. exports.EV_UNLINK_DIR = 'unlinkDir';
  3588. exports.EV_RAW = 'raw';
  3589. exports.EV_ERROR = 'error';
  3590. exports.STR_DATA = 'data';
  3591. exports.STR_END = 'end';
  3592. exports.STR_CLOSE = 'close';
  3593. exports.FSEVENT_CREATED = 'created';
  3594. exports.FSEVENT_MODIFIED = 'modified';
  3595. exports.FSEVENT_DELETED = 'deleted';
  3596. exports.FSEVENT_MOVED = 'moved';
  3597. exports.FSEVENT_CLONED = 'cloned';
  3598. exports.FSEVENT_UNKNOWN = 'unknown';
  3599. exports.FSEVENT_TYPE_FILE = 'file';
  3600. exports.FSEVENT_TYPE_DIRECTORY = 'directory';
  3601. exports.FSEVENT_TYPE_SYMLINK = 'symlink';
  3602. exports.KEY_LISTENERS = 'listeners';
  3603. exports.KEY_ERR = 'errHandlers';
  3604. exports.KEY_RAW = 'rawEmitters';
  3605. exports.HANDLER_KEYS = [exports.KEY_LISTENERS, exports.KEY_ERR, exports.KEY_RAW];
  3606. exports.DOT_SLASH = `.${sep}`;
  3607. exports.BACK_SLASH_RE = /\\/g;
  3608. exports.DOUBLE_SLASH_RE = /\/\//;
  3609. exports.SLASH_OR_BACK_SLASH_RE = /[/\\]/;
  3610. exports.DOT_RE = /\..*\.(sw[px])$|~$|\.subl.*\.tmp/;
  3611. exports.REPLACER_RE = /^\.[/\\]/;
  3612. exports.SLASH = '/';
  3613. exports.SLASH_SLASH = '//';
  3614. exports.BRACE_START = '{';
  3615. exports.BANG = '!';
  3616. exports.ONE_DOT = '.';
  3617. exports.TWO_DOTS = '..';
  3618. exports.STAR = '*';
  3619. exports.GLOBSTAR = '**';
  3620. exports.ROOT_GLOBSTAR = '/**/*';
  3621. exports.SLASH_GLOBSTAR = '/**';
  3622. exports.DIR_SUFFIX = 'Dir';
  3623. exports.ANYMATCH_OPTS = {dot: true};
  3624. exports.STRING_TYPE = 'string';
  3625. exports.FUNCTION_TYPE = 'function';
  3626. exports.EMPTY_STR = '';
  3627. exports.EMPTY_FN = () => {};
  3628. exports.IDENTITY_FN = val => val;
  3629. exports.isWindows = platform === 'win32';
  3630. exports.isMacos = platform === 'darwin';
  3631. exports.isLinux = platform === 'linux';
  3632. }(constants));
  3633. const fs$2 = fs$4;
  3634. const sysPath$2 = path$3;
  3635. const { promisify: promisify$2 } = require$$0$1;
  3636. const isBinaryPath = isBinaryPath$1;
  3637. const {
  3638. isWindows: isWindows$1,
  3639. isLinux,
  3640. EMPTY_FN: EMPTY_FN$2,
  3641. EMPTY_STR: EMPTY_STR$1,
  3642. KEY_LISTENERS,
  3643. KEY_ERR,
  3644. KEY_RAW,
  3645. HANDLER_KEYS,
  3646. EV_CHANGE: EV_CHANGE$2,
  3647. EV_ADD: EV_ADD$2,
  3648. EV_ADD_DIR: EV_ADD_DIR$2,
  3649. EV_ERROR: EV_ERROR$2,
  3650. STR_DATA: STR_DATA$1,
  3651. STR_END: STR_END$2,
  3652. BRACE_START: BRACE_START$1,
  3653. STAR
  3654. } = constants;
  3655. const THROTTLE_MODE_WATCH = 'watch';
  3656. const open = promisify$2(fs$2.open);
  3657. const stat$2 = promisify$2(fs$2.stat);
  3658. const lstat$1 = promisify$2(fs$2.lstat);
  3659. const close = promisify$2(fs$2.close);
  3660. const fsrealpath = promisify$2(fs$2.realpath);
  3661. const statMethods$1 = { lstat: lstat$1, stat: stat$2 };
  3662. // TODO: emit errors properly. Example: EMFILE on Macos.
  3663. const foreach = (val, fn) => {
  3664. if (val instanceof Set) {
  3665. val.forEach(fn);
  3666. } else {
  3667. fn(val);
  3668. }
  3669. };
  3670. const addAndConvert = (main, prop, item) => {
  3671. let container = main[prop];
  3672. if (!(container instanceof Set)) {
  3673. main[prop] = container = new Set([container]);
  3674. }
  3675. container.add(item);
  3676. };
  3677. const clearItem = cont => key => {
  3678. const set = cont[key];
  3679. if (set instanceof Set) {
  3680. set.clear();
  3681. } else {
  3682. delete cont[key];
  3683. }
  3684. };
  3685. const delFromSet = (main, prop, item) => {
  3686. const container = main[prop];
  3687. if (container instanceof Set) {
  3688. container.delete(item);
  3689. } else if (container === item) {
  3690. delete main[prop];
  3691. }
  3692. };
  3693. const isEmptySet = (val) => val instanceof Set ? val.size === 0 : !val;
  3694. /**
  3695. * @typedef {String} Path
  3696. */
  3697. // fs_watch helpers
  3698. // object to hold per-process fs_watch instances
  3699. // (may be shared across chokidar FSWatcher instances)
  3700. /**
  3701. * @typedef {Object} FsWatchContainer
  3702. * @property {Set} listeners
  3703. * @property {Set} errHandlers
  3704. * @property {Set} rawEmitters
  3705. * @property {fs.FSWatcher=} watcher
  3706. * @property {Boolean=} watcherUnusable
  3707. */
  3708. /**
  3709. * @type {Map<String,FsWatchContainer>}
  3710. */
  3711. const FsWatchInstances = new Map();
  3712. /**
  3713. * Instantiates the fs_watch interface
  3714. * @param {String} path to be watched
  3715. * @param {Object} options to be passed to fs_watch
  3716. * @param {Function} listener main event handler
  3717. * @param {Function} errHandler emits info about errors
  3718. * @param {Function} emitRaw emits raw event data
  3719. * @returns {fs.FSWatcher} new fsevents instance
  3720. */
  3721. function createFsWatchInstance(path, options, listener, errHandler, emitRaw) {
  3722. const handleEvent = (rawEvent, evPath) => {
  3723. listener(path);
  3724. emitRaw(rawEvent, evPath, {watchedPath: path});
  3725. // emit based on events occurring for files from a directory's watcher in
  3726. // case the file's watcher misses it (and rely on throttling to de-dupe)
  3727. if (evPath && path !== evPath) {
  3728. fsWatchBroadcast(
  3729. sysPath$2.resolve(path, evPath), KEY_LISTENERS, sysPath$2.join(path, evPath)
  3730. );
  3731. }
  3732. };
  3733. try {
  3734. return fs$2.watch(path, options, handleEvent);
  3735. } catch (error) {
  3736. errHandler(error);
  3737. }
  3738. }
  3739. /**
  3740. * Helper for passing fs_watch event data to a collection of listeners
  3741. * @param {Path} fullPath absolute path bound to fs_watch instance
  3742. * @param {String} type listener type
  3743. * @param {*=} val1 arguments to be passed to listeners
  3744. * @param {*=} val2
  3745. * @param {*=} val3
  3746. */
  3747. const fsWatchBroadcast = (fullPath, type, val1, val2, val3) => {
  3748. const cont = FsWatchInstances.get(fullPath);
  3749. if (!cont) return;
  3750. foreach(cont[type], (listener) => {
  3751. listener(val1, val2, val3);
  3752. });
  3753. };
  3754. /**
  3755. * Instantiates the fs_watch interface or binds listeners
  3756. * to an existing one covering the same file system entry
  3757. * @param {String} path
  3758. * @param {String} fullPath absolute path
  3759. * @param {Object} options to be passed to fs_watch
  3760. * @param {Object} handlers container for event listener functions
  3761. */
  3762. const setFsWatchListener = (path, fullPath, options, handlers) => {
  3763. const {listener, errHandler, rawEmitter} = handlers;
  3764. let cont = FsWatchInstances.get(fullPath);
  3765. /** @type {fs.FSWatcher=} */
  3766. let watcher;
  3767. if (!options.persistent) {
  3768. watcher = createFsWatchInstance(
  3769. path, options, listener, errHandler, rawEmitter
  3770. );
  3771. return watcher.close.bind(watcher);
  3772. }
  3773. if (cont) {
  3774. addAndConvert(cont, KEY_LISTENERS, listener);
  3775. addAndConvert(cont, KEY_ERR, errHandler);
  3776. addAndConvert(cont, KEY_RAW, rawEmitter);
  3777. } else {
  3778. watcher = createFsWatchInstance(
  3779. path,
  3780. options,
  3781. fsWatchBroadcast.bind(null, fullPath, KEY_LISTENERS),
  3782. errHandler, // no need to use broadcast here
  3783. fsWatchBroadcast.bind(null, fullPath, KEY_RAW)
  3784. );
  3785. if (!watcher) return;
  3786. watcher.on(EV_ERROR$2, async (error) => {
  3787. const broadcastErr = fsWatchBroadcast.bind(null, fullPath, KEY_ERR);
  3788. cont.watcherUnusable = true; // documented since Node 10.4.1
  3789. // Workaround for https://github.com/joyent/node/issues/4337
  3790. if (isWindows$1 && error.code === 'EPERM') {
  3791. try {
  3792. const fd = await open(path, 'r');
  3793. await close(fd);
  3794. broadcastErr(error);
  3795. } catch (err) {}
  3796. } else {
  3797. broadcastErr(error);
  3798. }
  3799. });
  3800. cont = {
  3801. listeners: listener,
  3802. errHandlers: errHandler,
  3803. rawEmitters: rawEmitter,
  3804. watcher
  3805. };
  3806. FsWatchInstances.set(fullPath, cont);
  3807. }
  3808. // const index = cont.listeners.indexOf(listener);
  3809. // removes this instance's listeners and closes the underlying fs_watch
  3810. // instance if there are no more listeners left
  3811. return () => {
  3812. delFromSet(cont, KEY_LISTENERS, listener);
  3813. delFromSet(cont, KEY_ERR, errHandler);
  3814. delFromSet(cont, KEY_RAW, rawEmitter);
  3815. if (isEmptySet(cont.listeners)) {
  3816. // Check to protect against issue gh-730.
  3817. // if (cont.watcherUnusable) {
  3818. cont.watcher.close();
  3819. // }
  3820. FsWatchInstances.delete(fullPath);
  3821. HANDLER_KEYS.forEach(clearItem(cont));
  3822. cont.watcher = undefined;
  3823. Object.freeze(cont);
  3824. }
  3825. };
  3826. };
  3827. // fs_watchFile helpers
  3828. // object to hold per-process fs_watchFile instances
  3829. // (may be shared across chokidar FSWatcher instances)
  3830. const FsWatchFileInstances = new Map();
  3831. /**
  3832. * Instantiates the fs_watchFile interface or binds listeners
  3833. * to an existing one covering the same file system entry
  3834. * @param {String} path to be watched
  3835. * @param {String} fullPath absolute path
  3836. * @param {Object} options options to be passed to fs_watchFile
  3837. * @param {Object} handlers container for event listener functions
  3838. * @returns {Function} closer
  3839. */
  3840. const setFsWatchFileListener = (path, fullPath, options, handlers) => {
  3841. const {listener, rawEmitter} = handlers;
  3842. let cont = FsWatchFileInstances.get(fullPath);
  3843. const copts = cont && cont.options;
  3844. if (copts && (copts.persistent < options.persistent || copts.interval > options.interval)) {
  3845. fs$2.unwatchFile(fullPath);
  3846. cont = undefined;
  3847. }
  3848. /* eslint-enable no-unused-vars, prefer-destructuring */
  3849. if (cont) {
  3850. addAndConvert(cont, KEY_LISTENERS, listener);
  3851. addAndConvert(cont, KEY_RAW, rawEmitter);
  3852. } else {
  3853. // TODO
  3854. // listeners.add(listener);
  3855. // rawEmitters.add(rawEmitter);
  3856. cont = {
  3857. listeners: listener,
  3858. rawEmitters: rawEmitter,
  3859. options,
  3860. watcher: fs$2.watchFile(fullPath, options, (curr, prev) => {
  3861. foreach(cont.rawEmitters, (rawEmitter) => {
  3862. rawEmitter(EV_CHANGE$2, fullPath, {curr, prev});
  3863. });
  3864. const currmtime = curr.mtimeMs;
  3865. if (curr.size !== prev.size || currmtime > prev.mtimeMs || currmtime === 0) {
  3866. foreach(cont.listeners, (listener) => listener(path, curr));
  3867. }
  3868. })
  3869. };
  3870. FsWatchFileInstances.set(fullPath, cont);
  3871. }
  3872. // const index = cont.listeners.indexOf(listener);
  3873. // Removes this instance's listeners and closes the underlying fs_watchFile
  3874. // instance if there are no more listeners left.
  3875. return () => {
  3876. delFromSet(cont, KEY_LISTENERS, listener);
  3877. delFromSet(cont, KEY_RAW, rawEmitter);
  3878. if (isEmptySet(cont.listeners)) {
  3879. FsWatchFileInstances.delete(fullPath);
  3880. fs$2.unwatchFile(fullPath);
  3881. cont.options = cont.watcher = undefined;
  3882. Object.freeze(cont);
  3883. }
  3884. };
  3885. };
  3886. /**
  3887. * @mixin
  3888. */
  3889. class NodeFsHandler$1 {
  3890. /**
  3891. * @param {import("../index").FSWatcher} fsW
  3892. */
  3893. constructor(fsW) {
  3894. this.fsw = fsW;
  3895. this._boundHandleError = (error) => fsW._handleError(error);
  3896. }
  3897. /**
  3898. * Watch file for changes with fs_watchFile or fs_watch.
  3899. * @param {String} path to file or dir
  3900. * @param {Function} listener on fs change
  3901. * @returns {Function} closer for the watcher instance
  3902. */
  3903. _watchWithNodeFs(path, listener) {
  3904. const opts = this.fsw.options;
  3905. const directory = sysPath$2.dirname(path);
  3906. const basename = sysPath$2.basename(path);
  3907. const parent = this.fsw._getWatchedDir(directory);
  3908. parent.add(basename);
  3909. const absolutePath = sysPath$2.resolve(path);
  3910. const options = {persistent: opts.persistent};
  3911. if (!listener) listener = EMPTY_FN$2;
  3912. let closer;
  3913. if (opts.usePolling) {
  3914. options.interval = opts.enableBinaryInterval && isBinaryPath(basename) ?
  3915. opts.binaryInterval : opts.interval;
  3916. closer = setFsWatchFileListener(path, absolutePath, options, {
  3917. listener,
  3918. rawEmitter: this.fsw._emitRaw
  3919. });
  3920. } else {
  3921. closer = setFsWatchListener(path, absolutePath, options, {
  3922. listener,
  3923. errHandler: this._boundHandleError,
  3924. rawEmitter: this.fsw._emitRaw
  3925. });
  3926. }
  3927. return closer;
  3928. }
  3929. /**
  3930. * Watch a file and emit add event if warranted.
  3931. * @param {Path} file Path
  3932. * @param {fs.Stats} stats result of fs_stat
  3933. * @param {Boolean} initialAdd was the file added at watch instantiation?
  3934. * @returns {Function} closer for the watcher instance
  3935. */
  3936. _handleFile(file, stats, initialAdd) {
  3937. if (this.fsw.closed) {
  3938. return;
  3939. }
  3940. const dirname = sysPath$2.dirname(file);
  3941. const basename = sysPath$2.basename(file);
  3942. const parent = this.fsw._getWatchedDir(dirname);
  3943. // stats is always present
  3944. let prevStats = stats;
  3945. // if the file is already being watched, do nothing
  3946. if (parent.has(basename)) return;
  3947. const listener = async (path, newStats) => {
  3948. if (!this.fsw._throttle(THROTTLE_MODE_WATCH, file, 5)) return;
  3949. if (!newStats || newStats.mtimeMs === 0) {
  3950. try {
  3951. const newStats = await stat$2(file);
  3952. if (this.fsw.closed) return;
  3953. // Check that change event was not fired because of changed only accessTime.
  3954. const at = newStats.atimeMs;
  3955. const mt = newStats.mtimeMs;
  3956. if (!at || at <= mt || mt !== prevStats.mtimeMs) {
  3957. this.fsw._emit(EV_CHANGE$2, file, newStats);
  3958. }
  3959. if (isLinux && prevStats.ino !== newStats.ino) {
  3960. this.fsw._closeFile(path);
  3961. prevStats = newStats;
  3962. this.fsw._addPathCloser(path, this._watchWithNodeFs(file, listener));
  3963. } else {
  3964. prevStats = newStats;
  3965. }
  3966. } catch (error) {
  3967. // Fix issues where mtime is null but file is still present
  3968. this.fsw._remove(dirname, basename);
  3969. }
  3970. // add is about to be emitted if file not already tracked in parent
  3971. } else if (parent.has(basename)) {
  3972. // Check that change event was not fired because of changed only accessTime.
  3973. const at = newStats.atimeMs;
  3974. const mt = newStats.mtimeMs;
  3975. if (!at || at <= mt || mt !== prevStats.mtimeMs) {
  3976. this.fsw._emit(EV_CHANGE$2, file, newStats);
  3977. }
  3978. prevStats = newStats;
  3979. }
  3980. };
  3981. // kick off the watcher
  3982. const closer = this._watchWithNodeFs(file, listener);
  3983. // emit an add event if we're supposed to
  3984. if (!(initialAdd && this.fsw.options.ignoreInitial) && this.fsw._isntIgnored(file)) {
  3985. if (!this.fsw._throttle(EV_ADD$2, file, 0)) return;
  3986. this.fsw._emit(EV_ADD$2, file, stats);
  3987. }
  3988. return closer;
  3989. }
  3990. /**
  3991. * Handle symlinks encountered while reading a dir.
  3992. * @param {Object} entry returned by readdirp
  3993. * @param {String} directory path of dir being read
  3994. * @param {String} path of this item
  3995. * @param {String} item basename of this item
  3996. * @returns {Promise<Boolean>} true if no more processing is needed for this entry.
  3997. */
  3998. async _handleSymlink(entry, directory, path, item) {
  3999. if (this.fsw.closed) {
  4000. return;
  4001. }
  4002. const full = entry.fullPath;
  4003. const dir = this.fsw._getWatchedDir(directory);
  4004. if (!this.fsw.options.followSymlinks) {
  4005. // watch symlink directly (don't follow) and detect changes
  4006. this.fsw._incrReadyCount();
  4007. const linkPath = await fsrealpath(path);
  4008. if (this.fsw.closed) return;
  4009. if (dir.has(item)) {
  4010. if (this.fsw._symlinkPaths.get(full) !== linkPath) {
  4011. this.fsw._symlinkPaths.set(full, linkPath);
  4012. this.fsw._emit(EV_CHANGE$2, path, entry.stats);
  4013. }
  4014. } else {
  4015. dir.add(item);
  4016. this.fsw._symlinkPaths.set(full, linkPath);
  4017. this.fsw._emit(EV_ADD$2, path, entry.stats);
  4018. }
  4019. this.fsw._emitReady();
  4020. return true;
  4021. }
  4022. // don't follow the same symlink more than once
  4023. if (this.fsw._symlinkPaths.has(full)) {
  4024. return true;
  4025. }
  4026. this.fsw._symlinkPaths.set(full, true);
  4027. }
  4028. _handleRead(directory, initialAdd, wh, target, dir, depth, throttler) {
  4029. // Normalize the directory name on Windows
  4030. directory = sysPath$2.join(directory, EMPTY_STR$1);
  4031. if (!wh.hasGlob) {
  4032. throttler = this.fsw._throttle('readdir', directory, 1000);
  4033. if (!throttler) return;
  4034. }
  4035. const previous = this.fsw._getWatchedDir(wh.path);
  4036. const current = new Set();
  4037. let stream = this.fsw._readdirp(directory, {
  4038. fileFilter: entry => wh.filterPath(entry),
  4039. directoryFilter: entry => wh.filterDir(entry),
  4040. depth: 0
  4041. }).on(STR_DATA$1, async (entry) => {
  4042. if (this.fsw.closed) {
  4043. stream = undefined;
  4044. return;
  4045. }
  4046. const item = entry.path;
  4047. let path = sysPath$2.join(directory, item);
  4048. current.add(item);
  4049. if (entry.stats.isSymbolicLink() && await this._handleSymlink(entry, directory, path, item)) {
  4050. return;
  4051. }
  4052. if (this.fsw.closed) {
  4053. stream = undefined;
  4054. return;
  4055. }
  4056. // Files that present in current directory snapshot
  4057. // but absent in previous are added to watch list and
  4058. // emit `add` event.
  4059. if (item === target || !target && !previous.has(item)) {
  4060. this.fsw._incrReadyCount();
  4061. // ensure relativeness of path is preserved in case of watcher reuse
  4062. path = sysPath$2.join(dir, sysPath$2.relative(dir, path));
  4063. this._addToNodeFs(path, initialAdd, wh, depth + 1);
  4064. }
  4065. }).on(EV_ERROR$2, this._boundHandleError);
  4066. return new Promise(resolve =>
  4067. stream.once(STR_END$2, () => {
  4068. if (this.fsw.closed) {
  4069. stream = undefined;
  4070. return;
  4071. }
  4072. const wasThrottled = throttler ? throttler.clear() : false;
  4073. resolve();
  4074. // Files that absent in current directory snapshot
  4075. // but present in previous emit `remove` event
  4076. // and are removed from @watched[directory].
  4077. previous.getChildren().filter((item) => {
  4078. return item !== directory &&
  4079. !current.has(item) &&
  4080. // in case of intersecting globs;
  4081. // a path may have been filtered out of this readdir, but
  4082. // shouldn't be removed because it matches a different glob
  4083. (!wh.hasGlob || wh.filterPath({
  4084. fullPath: sysPath$2.resolve(directory, item)
  4085. }));
  4086. }).forEach((item) => {
  4087. this.fsw._remove(directory, item);
  4088. });
  4089. stream = undefined;
  4090. // one more time for any missed in case changes came in extremely quickly
  4091. if (wasThrottled) this._handleRead(directory, false, wh, target, dir, depth, throttler);
  4092. })
  4093. );
  4094. }
  4095. /**
  4096. * Read directory to add / remove files from `@watched` list and re-read it on change.
  4097. * @param {String} dir fs path
  4098. * @param {fs.Stats} stats
  4099. * @param {Boolean} initialAdd
  4100. * @param {Number} depth relative to user-supplied path
  4101. * @param {String} target child path targeted for watch
  4102. * @param {Object} wh Common watch helpers for this path
  4103. * @param {String} realpath
  4104. * @returns {Promise<Function>} closer for the watcher instance.
  4105. */
  4106. async _handleDir(dir, stats, initialAdd, depth, target, wh, realpath) {
  4107. const parentDir = this.fsw._getWatchedDir(sysPath$2.dirname(dir));
  4108. const tracked = parentDir.has(sysPath$2.basename(dir));
  4109. if (!(initialAdd && this.fsw.options.ignoreInitial) && !target && !tracked) {
  4110. if (!wh.hasGlob || wh.globFilter(dir)) this.fsw._emit(EV_ADD_DIR$2, dir, stats);
  4111. }
  4112. // ensure dir is tracked (harmless if redundant)
  4113. parentDir.add(sysPath$2.basename(dir));
  4114. this.fsw._getWatchedDir(dir);
  4115. let throttler;
  4116. let closer;
  4117. const oDepth = this.fsw.options.depth;
  4118. if ((oDepth == null || depth <= oDepth) && !this.fsw._symlinkPaths.has(realpath)) {
  4119. if (!target) {
  4120. await this._handleRead(dir, initialAdd, wh, target, dir, depth, throttler);
  4121. if (this.fsw.closed) return;
  4122. }
  4123. closer = this._watchWithNodeFs(dir, (dirPath, stats) => {
  4124. // if current directory is removed, do nothing
  4125. if (stats && stats.mtimeMs === 0) return;
  4126. this._handleRead(dirPath, false, wh, target, dir, depth, throttler);
  4127. });
  4128. }
  4129. return closer;
  4130. }
  4131. /**
  4132. * Handle added file, directory, or glob pattern.
  4133. * Delegates call to _handleFile / _handleDir after checks.
  4134. * @param {String} path to file or ir
  4135. * @param {Boolean} initialAdd was the file added at watch instantiation?
  4136. * @param {Object} priorWh depth relative to user-supplied path
  4137. * @param {Number} depth Child path actually targeted for watch
  4138. * @param {String=} target Child path actually targeted for watch
  4139. * @returns {Promise}
  4140. */
  4141. async _addToNodeFs(path, initialAdd, priorWh, depth, target) {
  4142. const ready = this.fsw._emitReady;
  4143. if (this.fsw._isIgnored(path) || this.fsw.closed) {
  4144. ready();
  4145. return false;
  4146. }
  4147. const wh = this.fsw._getWatchHelpers(path, depth);
  4148. if (!wh.hasGlob && priorWh) {
  4149. wh.hasGlob = priorWh.hasGlob;
  4150. wh.globFilter = priorWh.globFilter;
  4151. wh.filterPath = entry => priorWh.filterPath(entry);
  4152. wh.filterDir = entry => priorWh.filterDir(entry);
  4153. }
  4154. // evaluate what is at the path we're being asked to watch
  4155. try {
  4156. const stats = await statMethods$1[wh.statMethod](wh.watchPath);
  4157. if (this.fsw.closed) return;
  4158. if (this.fsw._isIgnored(wh.watchPath, stats)) {
  4159. ready();
  4160. return false;
  4161. }
  4162. const follow = this.fsw.options.followSymlinks && !path.includes(STAR) && !path.includes(BRACE_START$1);
  4163. let closer;
  4164. if (stats.isDirectory()) {
  4165. const absPath = sysPath$2.resolve(path);
  4166. const targetPath = follow ? await fsrealpath(path) : path;
  4167. if (this.fsw.closed) return;
  4168. closer = await this._handleDir(wh.watchPath, stats, initialAdd, depth, target, wh, targetPath);
  4169. if (this.fsw.closed) return;
  4170. // preserve this symlink's target path
  4171. if (absPath !== targetPath && targetPath !== undefined) {
  4172. this.fsw._symlinkPaths.set(absPath, targetPath);
  4173. }
  4174. } else if (stats.isSymbolicLink()) {
  4175. const targetPath = follow ? await fsrealpath(path) : path;
  4176. if (this.fsw.closed) return;
  4177. const parent = sysPath$2.dirname(wh.watchPath);
  4178. this.fsw._getWatchedDir(parent).add(wh.watchPath);
  4179. this.fsw._emit(EV_ADD$2, wh.watchPath, stats);
  4180. closer = await this._handleDir(parent, stats, initialAdd, depth, path, wh, targetPath);
  4181. if (this.fsw.closed) return;
  4182. // preserve this symlink's target path
  4183. if (targetPath !== undefined) {
  4184. this.fsw._symlinkPaths.set(sysPath$2.resolve(path), targetPath);
  4185. }
  4186. } else {
  4187. closer = this._handleFile(wh.watchPath, stats, initialAdd);
  4188. }
  4189. ready();
  4190. this.fsw._addPathCloser(path, closer);
  4191. return false;
  4192. } catch (error) {
  4193. if (this.fsw._handleError(error)) {
  4194. ready();
  4195. return path;
  4196. }
  4197. }
  4198. }
  4199. }
  4200. var nodefsHandler = NodeFsHandler$1;
  4201. var fseventsHandler = {exports: {}};
  4202. var require$$3 = /*@__PURE__*/rollup.getAugmentedNamespace(rollup.fseventsImporter);
  4203. const fs$1 = fs$4;
  4204. const sysPath$1 = path$3;
  4205. const { promisify: promisify$1 } = require$$0$1;
  4206. let fsevents;
  4207. try {
  4208. fsevents = require$$3.getFsEvents();
  4209. } catch (error) {
  4210. if (process.env.CHOKIDAR_PRINT_FSEVENTS_REQUIRE_ERROR) console.error(error);
  4211. }
  4212. if (fsevents) {
  4213. // TODO: real check
  4214. const mtch = process.version.match(/v(\d+)\.(\d+)/);
  4215. if (mtch && mtch[1] && mtch[2]) {
  4216. const maj = Number.parseInt(mtch[1], 10);
  4217. const min = Number.parseInt(mtch[2], 10);
  4218. if (maj === 8 && min < 16) {
  4219. fsevents = undefined;
  4220. }
  4221. }
  4222. }
  4223. const {
  4224. EV_ADD: EV_ADD$1,
  4225. EV_CHANGE: EV_CHANGE$1,
  4226. EV_ADD_DIR: EV_ADD_DIR$1,
  4227. EV_UNLINK: EV_UNLINK$1,
  4228. EV_ERROR: EV_ERROR$1,
  4229. STR_DATA,
  4230. STR_END: STR_END$1,
  4231. FSEVENT_CREATED,
  4232. FSEVENT_MODIFIED,
  4233. FSEVENT_DELETED,
  4234. FSEVENT_MOVED,
  4235. // FSEVENT_CLONED,
  4236. FSEVENT_UNKNOWN,
  4237. FSEVENT_TYPE_FILE,
  4238. FSEVENT_TYPE_DIRECTORY,
  4239. FSEVENT_TYPE_SYMLINK,
  4240. ROOT_GLOBSTAR,
  4241. DIR_SUFFIX,
  4242. DOT_SLASH,
  4243. FUNCTION_TYPE: FUNCTION_TYPE$1,
  4244. EMPTY_FN: EMPTY_FN$1,
  4245. IDENTITY_FN
  4246. } = constants;
  4247. const Depth = (value) => isNaN(value) ? {} : {depth: value};
  4248. const stat$1 = promisify$1(fs$1.stat);
  4249. const lstat = promisify$1(fs$1.lstat);
  4250. const realpath = promisify$1(fs$1.realpath);
  4251. const statMethods = { stat: stat$1, lstat };
  4252. /**
  4253. * @typedef {String} Path
  4254. */
  4255. /**
  4256. * @typedef {Object} FsEventsWatchContainer
  4257. * @property {Set<Function>} listeners
  4258. * @property {Function} rawEmitter
  4259. * @property {{stop: Function}} watcher
  4260. */
  4261. // fsevents instance helper functions
  4262. /**
  4263. * Object to hold per-process fsevents instances (may be shared across chokidar FSWatcher instances)
  4264. * @type {Map<Path,FsEventsWatchContainer>}
  4265. */
  4266. const FSEventsWatchers = new Map();
  4267. // Threshold of duplicate path prefixes at which to start
  4268. // consolidating going forward
  4269. const consolidateThreshhold = 10;
  4270. const wrongEventFlags = new Set([
  4271. 69888, 70400, 71424, 72704, 73472, 131328, 131840, 262912
  4272. ]);
  4273. /**
  4274. * Instantiates the fsevents interface
  4275. * @param {Path} path path to be watched
  4276. * @param {Function} callback called when fsevents is bound and ready
  4277. * @returns {{stop: Function}} new fsevents instance
  4278. */
  4279. const createFSEventsInstance = (path, callback) => {
  4280. const stop = fsevents.watch(path, callback);
  4281. return {stop};
  4282. };
  4283. /**
  4284. * Instantiates the fsevents interface or binds listeners to an existing one covering
  4285. * the same file tree.
  4286. * @param {Path} path - to be watched
  4287. * @param {Path} realPath - real path for symlinks
  4288. * @param {Function} listener - called when fsevents emits events
  4289. * @param {Function} rawEmitter - passes data to listeners of the 'raw' event
  4290. * @returns {Function} closer
  4291. */
  4292. function setFSEventsListener(path, realPath, listener, rawEmitter) {
  4293. let watchPath = sysPath$1.extname(path) ? sysPath$1.dirname(path) : path;
  4294. const parentPath = sysPath$1.dirname(watchPath);
  4295. let cont = FSEventsWatchers.get(watchPath);
  4296. // If we've accumulated a substantial number of paths that
  4297. // could have been consolidated by watching one directory
  4298. // above the current one, create a watcher on the parent
  4299. // path instead, so that we do consolidate going forward.
  4300. if (couldConsolidate(parentPath)) {
  4301. watchPath = parentPath;
  4302. }
  4303. const resolvedPath = sysPath$1.resolve(path);
  4304. const hasSymlink = resolvedPath !== realPath;
  4305. const filteredListener = (fullPath, flags, info) => {
  4306. if (hasSymlink) fullPath = fullPath.replace(realPath, resolvedPath);
  4307. if (
  4308. fullPath === resolvedPath ||
  4309. !fullPath.indexOf(resolvedPath + sysPath$1.sep)
  4310. ) listener(fullPath, flags, info);
  4311. };
  4312. // check if there is already a watcher on a parent path
  4313. // modifies `watchPath` to the parent path when it finds a match
  4314. let watchedParent = false;
  4315. for (const watchedPath of FSEventsWatchers.keys()) {
  4316. if (realPath.indexOf(sysPath$1.resolve(watchedPath) + sysPath$1.sep) === 0) {
  4317. watchPath = watchedPath;
  4318. cont = FSEventsWatchers.get(watchPath);
  4319. watchedParent = true;
  4320. break;
  4321. }
  4322. }
  4323. if (cont || watchedParent) {
  4324. cont.listeners.add(filteredListener);
  4325. } else {
  4326. cont = {
  4327. listeners: new Set([filteredListener]),
  4328. rawEmitter,
  4329. watcher: createFSEventsInstance(watchPath, (fullPath, flags) => {
  4330. if (!cont.listeners.size) return;
  4331. const info = fsevents.getInfo(fullPath, flags);
  4332. cont.listeners.forEach(list => {
  4333. list(fullPath, flags, info);
  4334. });
  4335. cont.rawEmitter(info.event, fullPath, info);
  4336. })
  4337. };
  4338. FSEventsWatchers.set(watchPath, cont);
  4339. }
  4340. // removes this instance's listeners and closes the underlying fsevents
  4341. // instance if there are no more listeners left
  4342. return () => {
  4343. const lst = cont.listeners;
  4344. lst.delete(filteredListener);
  4345. if (!lst.size) {
  4346. FSEventsWatchers.delete(watchPath);
  4347. if (cont.watcher) return cont.watcher.stop().then(() => {
  4348. cont.rawEmitter = cont.watcher = undefined;
  4349. Object.freeze(cont);
  4350. });
  4351. }
  4352. };
  4353. }
  4354. // Decide whether or not we should start a new higher-level
  4355. // parent watcher
  4356. const couldConsolidate = (path) => {
  4357. let count = 0;
  4358. for (const watchPath of FSEventsWatchers.keys()) {
  4359. if (watchPath.indexOf(path) === 0) {
  4360. count++;
  4361. if (count >= consolidateThreshhold) {
  4362. return true;
  4363. }
  4364. }
  4365. }
  4366. return false;
  4367. };
  4368. // returns boolean indicating whether fsevents can be used
  4369. const canUse = () => fsevents && FSEventsWatchers.size < 128;
  4370. // determines subdirectory traversal levels from root to path
  4371. const calcDepth = (path, root) => {
  4372. let i = 0;
  4373. while (!path.indexOf(root) && (path = sysPath$1.dirname(path)) !== root) i++;
  4374. return i;
  4375. };
  4376. // returns boolean indicating whether the fsevents' event info has the same type
  4377. // as the one returned by fs.stat
  4378. const sameTypes = (info, stats) => (
  4379. info.type === FSEVENT_TYPE_DIRECTORY && stats.isDirectory() ||
  4380. info.type === FSEVENT_TYPE_SYMLINK && stats.isSymbolicLink() ||
  4381. info.type === FSEVENT_TYPE_FILE && stats.isFile()
  4382. );
  4383. /**
  4384. * @mixin
  4385. */
  4386. class FsEventsHandler$1 {
  4387. /**
  4388. * @param {import('../index').FSWatcher} fsw
  4389. */
  4390. constructor(fsw) {
  4391. this.fsw = fsw;
  4392. }
  4393. checkIgnored(path, stats) {
  4394. const ipaths = this.fsw._ignoredPaths;
  4395. if (this.fsw._isIgnored(path, stats)) {
  4396. ipaths.add(path);
  4397. if (stats && stats.isDirectory()) {
  4398. ipaths.add(path + ROOT_GLOBSTAR);
  4399. }
  4400. return true;
  4401. }
  4402. ipaths.delete(path);
  4403. ipaths.delete(path + ROOT_GLOBSTAR);
  4404. }
  4405. addOrChange(path, fullPath, realPath, parent, watchedDir, item, info, opts) {
  4406. const event = watchedDir.has(item) ? EV_CHANGE$1 : EV_ADD$1;
  4407. this.handleEvent(event, path, fullPath, realPath, parent, watchedDir, item, info, opts);
  4408. }
  4409. async checkExists(path, fullPath, realPath, parent, watchedDir, item, info, opts) {
  4410. try {
  4411. const stats = await stat$1(path);
  4412. if (this.fsw.closed) return;
  4413. if (sameTypes(info, stats)) {
  4414. this.addOrChange(path, fullPath, realPath, parent, watchedDir, item, info, opts);
  4415. } else {
  4416. this.handleEvent(EV_UNLINK$1, path, fullPath, realPath, parent, watchedDir, item, info, opts);
  4417. }
  4418. } catch (error) {
  4419. if (error.code === 'EACCES') {
  4420. this.addOrChange(path, fullPath, realPath, parent, watchedDir, item, info, opts);
  4421. } else {
  4422. this.handleEvent(EV_UNLINK$1, path, fullPath, realPath, parent, watchedDir, item, info, opts);
  4423. }
  4424. }
  4425. }
  4426. handleEvent(event, path, fullPath, realPath, parent, watchedDir, item, info, opts) {
  4427. if (this.fsw.closed || this.checkIgnored(path)) return;
  4428. if (event === EV_UNLINK$1) {
  4429. const isDirectory = info.type === FSEVENT_TYPE_DIRECTORY;
  4430. // suppress unlink events on never before seen files
  4431. if (isDirectory || watchedDir.has(item)) {
  4432. this.fsw._remove(parent, item, isDirectory);
  4433. }
  4434. } else {
  4435. if (event === EV_ADD$1) {
  4436. // track new directories
  4437. if (info.type === FSEVENT_TYPE_DIRECTORY) this.fsw._getWatchedDir(path);
  4438. if (info.type === FSEVENT_TYPE_SYMLINK && opts.followSymlinks) {
  4439. // push symlinks back to the top of the stack to get handled
  4440. const curDepth = opts.depth === undefined ?
  4441. undefined : calcDepth(fullPath, realPath) + 1;
  4442. return this._addToFsEvents(path, false, true, curDepth);
  4443. }
  4444. // track new paths
  4445. // (other than symlinks being followed, which will be tracked soon)
  4446. this.fsw._getWatchedDir(parent).add(item);
  4447. }
  4448. /**
  4449. * @type {'add'|'addDir'|'unlink'|'unlinkDir'}
  4450. */
  4451. const eventName = info.type === FSEVENT_TYPE_DIRECTORY ? event + DIR_SUFFIX : event;
  4452. this.fsw._emit(eventName, path);
  4453. if (eventName === EV_ADD_DIR$1) this._addToFsEvents(path, false, true);
  4454. }
  4455. }
  4456. /**
  4457. * Handle symlinks encountered during directory scan
  4458. * @param {String} watchPath - file/dir path to be watched with fsevents
  4459. * @param {String} realPath - real path (in case of symlinks)
  4460. * @param {Function} transform - path transformer
  4461. * @param {Function} globFilter - path filter in case a glob pattern was provided
  4462. * @returns {Function} closer for the watcher instance
  4463. */
  4464. _watchWithFsEvents(watchPath, realPath, transform, globFilter) {
  4465. if (this.fsw.closed || this.fsw._isIgnored(watchPath)) return;
  4466. const opts = this.fsw.options;
  4467. const watchCallback = async (fullPath, flags, info) => {
  4468. if (this.fsw.closed) return;
  4469. if (
  4470. opts.depth !== undefined &&
  4471. calcDepth(fullPath, realPath) > opts.depth
  4472. ) return;
  4473. const path = transform(sysPath$1.join(
  4474. watchPath, sysPath$1.relative(watchPath, fullPath)
  4475. ));
  4476. if (globFilter && !globFilter(path)) return;
  4477. // ensure directories are tracked
  4478. const parent = sysPath$1.dirname(path);
  4479. const item = sysPath$1.basename(path);
  4480. const watchedDir = this.fsw._getWatchedDir(
  4481. info.type === FSEVENT_TYPE_DIRECTORY ? path : parent
  4482. );
  4483. // correct for wrong events emitted
  4484. if (wrongEventFlags.has(flags) || info.event === FSEVENT_UNKNOWN) {
  4485. if (typeof opts.ignored === FUNCTION_TYPE$1) {
  4486. let stats;
  4487. try {
  4488. stats = await stat$1(path);
  4489. } catch (error) {}
  4490. if (this.fsw.closed) return;
  4491. if (this.checkIgnored(path, stats)) return;
  4492. if (sameTypes(info, stats)) {
  4493. this.addOrChange(path, fullPath, realPath, parent, watchedDir, item, info, opts);
  4494. } else {
  4495. this.handleEvent(EV_UNLINK$1, path, fullPath, realPath, parent, watchedDir, item, info, opts);
  4496. }
  4497. } else {
  4498. this.checkExists(path, fullPath, realPath, parent, watchedDir, item, info, opts);
  4499. }
  4500. } else {
  4501. switch (info.event) {
  4502. case FSEVENT_CREATED:
  4503. case FSEVENT_MODIFIED:
  4504. return this.addOrChange(path, fullPath, realPath, parent, watchedDir, item, info, opts);
  4505. case FSEVENT_DELETED:
  4506. case FSEVENT_MOVED:
  4507. return this.checkExists(path, fullPath, realPath, parent, watchedDir, item, info, opts);
  4508. }
  4509. }
  4510. };
  4511. const closer = setFSEventsListener(
  4512. watchPath,
  4513. realPath,
  4514. watchCallback,
  4515. this.fsw._emitRaw
  4516. );
  4517. this.fsw._emitReady();
  4518. return closer;
  4519. }
  4520. /**
  4521. * Handle symlinks encountered during directory scan
  4522. * @param {String} linkPath path to symlink
  4523. * @param {String} fullPath absolute path to the symlink
  4524. * @param {Function} transform pre-existing path transformer
  4525. * @param {Number} curDepth level of subdirectories traversed to where symlink is
  4526. * @returns {Promise<void>}
  4527. */
  4528. async _handleFsEventsSymlink(linkPath, fullPath, transform, curDepth) {
  4529. // don't follow the same symlink more than once
  4530. if (this.fsw.closed || this.fsw._symlinkPaths.has(fullPath)) return;
  4531. this.fsw._symlinkPaths.set(fullPath, true);
  4532. this.fsw._incrReadyCount();
  4533. try {
  4534. const linkTarget = await realpath(linkPath);
  4535. if (this.fsw.closed) return;
  4536. if (this.fsw._isIgnored(linkTarget)) {
  4537. return this.fsw._emitReady();
  4538. }
  4539. this.fsw._incrReadyCount();
  4540. // add the linkTarget for watching with a wrapper for transform
  4541. // that causes emitted paths to incorporate the link's path
  4542. this._addToFsEvents(linkTarget || linkPath, (path) => {
  4543. let aliasedPath = linkPath;
  4544. if (linkTarget && linkTarget !== DOT_SLASH) {
  4545. aliasedPath = path.replace(linkTarget, linkPath);
  4546. } else if (path !== DOT_SLASH) {
  4547. aliasedPath = sysPath$1.join(linkPath, path);
  4548. }
  4549. return transform(aliasedPath);
  4550. }, false, curDepth);
  4551. } catch(error) {
  4552. if (this.fsw._handleError(error)) {
  4553. return this.fsw._emitReady();
  4554. }
  4555. }
  4556. }
  4557. /**
  4558. *
  4559. * @param {Path} newPath
  4560. * @param {fs.Stats} stats
  4561. */
  4562. emitAdd(newPath, stats, processPath, opts, forceAdd) {
  4563. const pp = processPath(newPath);
  4564. const isDir = stats.isDirectory();
  4565. const dirObj = this.fsw._getWatchedDir(sysPath$1.dirname(pp));
  4566. const base = sysPath$1.basename(pp);
  4567. // ensure empty dirs get tracked
  4568. if (isDir) this.fsw._getWatchedDir(pp);
  4569. if (dirObj.has(base)) return;
  4570. dirObj.add(base);
  4571. if (!opts.ignoreInitial || forceAdd === true) {
  4572. this.fsw._emit(isDir ? EV_ADD_DIR$1 : EV_ADD$1, pp, stats);
  4573. }
  4574. }
  4575. initWatch(realPath, path, wh, processPath) {
  4576. if (this.fsw.closed) return;
  4577. const closer = this._watchWithFsEvents(
  4578. wh.watchPath,
  4579. sysPath$1.resolve(realPath || wh.watchPath),
  4580. processPath,
  4581. wh.globFilter
  4582. );
  4583. this.fsw._addPathCloser(path, closer);
  4584. }
  4585. /**
  4586. * Handle added path with fsevents
  4587. * @param {String} path file/dir path or glob pattern
  4588. * @param {Function|Boolean=} transform converts working path to what the user expects
  4589. * @param {Boolean=} forceAdd ensure add is emitted
  4590. * @param {Number=} priorDepth Level of subdirectories already traversed.
  4591. * @returns {Promise<void>}
  4592. */
  4593. async _addToFsEvents(path, transform, forceAdd, priorDepth) {
  4594. if (this.fsw.closed) {
  4595. return;
  4596. }
  4597. const opts = this.fsw.options;
  4598. const processPath = typeof transform === FUNCTION_TYPE$1 ? transform : IDENTITY_FN;
  4599. const wh = this.fsw._getWatchHelpers(path);
  4600. // evaluate what is at the path we're being asked to watch
  4601. try {
  4602. const stats = await statMethods[wh.statMethod](wh.watchPath);
  4603. if (this.fsw.closed) return;
  4604. if (this.fsw._isIgnored(wh.watchPath, stats)) {
  4605. throw null;
  4606. }
  4607. if (stats.isDirectory()) {
  4608. // emit addDir unless this is a glob parent
  4609. if (!wh.globFilter) this.emitAdd(processPath(path), stats, processPath, opts, forceAdd);
  4610. // don't recurse further if it would exceed depth setting
  4611. if (priorDepth && priorDepth > opts.depth) return;
  4612. // scan the contents of the dir
  4613. this.fsw._readdirp(wh.watchPath, {
  4614. fileFilter: entry => wh.filterPath(entry),
  4615. directoryFilter: entry => wh.filterDir(entry),
  4616. ...Depth(opts.depth - (priorDepth || 0))
  4617. }).on(STR_DATA, (entry) => {
  4618. // need to check filterPath on dirs b/c filterDir is less restrictive
  4619. if (this.fsw.closed) {
  4620. return;
  4621. }
  4622. if (entry.stats.isDirectory() && !wh.filterPath(entry)) return;
  4623. const joinedPath = sysPath$1.join(wh.watchPath, entry.path);
  4624. const {fullPath} = entry;
  4625. if (wh.followSymlinks && entry.stats.isSymbolicLink()) {
  4626. // preserve the current depth here since it can't be derived from
  4627. // real paths past the symlink
  4628. const curDepth = opts.depth === undefined ?
  4629. undefined : calcDepth(joinedPath, sysPath$1.resolve(wh.watchPath)) + 1;
  4630. this._handleFsEventsSymlink(joinedPath, fullPath, processPath, curDepth);
  4631. } else {
  4632. this.emitAdd(joinedPath, entry.stats, processPath, opts, forceAdd);
  4633. }
  4634. }).on(EV_ERROR$1, EMPTY_FN$1).on(STR_END$1, () => {
  4635. this.fsw._emitReady();
  4636. });
  4637. } else {
  4638. this.emitAdd(wh.watchPath, stats, processPath, opts, forceAdd);
  4639. this.fsw._emitReady();
  4640. }
  4641. } catch (error) {
  4642. if (!error || this.fsw._handleError(error)) {
  4643. // TODO: Strange thing: "should not choke on an ignored watch path" will be failed without 2 ready calls -__-
  4644. this.fsw._emitReady();
  4645. this.fsw._emitReady();
  4646. }
  4647. }
  4648. if (opts.persistent && forceAdd !== true) {
  4649. if (typeof transform === FUNCTION_TYPE$1) {
  4650. // realpath has already been resolved
  4651. this.initWatch(undefined, path, wh, processPath);
  4652. } else {
  4653. let realPath;
  4654. try {
  4655. realPath = await realpath(wh.watchPath);
  4656. } catch (e) {}
  4657. this.initWatch(realPath, path, wh, processPath);
  4658. }
  4659. }
  4660. }
  4661. }
  4662. fseventsHandler.exports = FsEventsHandler$1;
  4663. fseventsHandler.exports.canUse = canUse;
  4664. const { EventEmitter } = require$$0$2;
  4665. const fs = fs$4;
  4666. const sysPath = path$3;
  4667. const { promisify } = require$$0$1;
  4668. const readdirp = readdirp_1;
  4669. const anymatch = anymatch$2.exports.default;
  4670. const globParent = globParent$1;
  4671. const isGlob = isGlob$2;
  4672. const braces = braces_1;
  4673. const normalizePath = normalizePath$2;
  4674. const NodeFsHandler = nodefsHandler;
  4675. const FsEventsHandler = fseventsHandler.exports;
  4676. const {
  4677. EV_ALL,
  4678. EV_READY,
  4679. EV_ADD,
  4680. EV_CHANGE,
  4681. EV_UNLINK,
  4682. EV_ADD_DIR,
  4683. EV_UNLINK_DIR,
  4684. EV_RAW,
  4685. EV_ERROR,
  4686. STR_CLOSE,
  4687. STR_END,
  4688. BACK_SLASH_RE,
  4689. DOUBLE_SLASH_RE,
  4690. SLASH_OR_BACK_SLASH_RE,
  4691. DOT_RE,
  4692. REPLACER_RE,
  4693. SLASH,
  4694. SLASH_SLASH,
  4695. BRACE_START,
  4696. BANG,
  4697. ONE_DOT,
  4698. TWO_DOTS,
  4699. GLOBSTAR,
  4700. SLASH_GLOBSTAR,
  4701. ANYMATCH_OPTS,
  4702. STRING_TYPE,
  4703. FUNCTION_TYPE,
  4704. EMPTY_STR,
  4705. EMPTY_FN,
  4706. isWindows,
  4707. isMacos
  4708. } = constants;
  4709. const stat = promisify(fs.stat);
  4710. const readdir = promisify(fs.readdir);
  4711. /**
  4712. * @typedef {String} Path
  4713. * @typedef {'all'|'add'|'addDir'|'change'|'unlink'|'unlinkDir'|'raw'|'error'|'ready'} EventName
  4714. * @typedef {'readdir'|'watch'|'add'|'remove'|'change'} ThrottleType
  4715. */
  4716. /**
  4717. *
  4718. * @typedef {Object} WatchHelpers
  4719. * @property {Boolean} followSymlinks
  4720. * @property {'stat'|'lstat'} statMethod
  4721. * @property {Path} path
  4722. * @property {Path} watchPath
  4723. * @property {Function} entryPath
  4724. * @property {Boolean} hasGlob
  4725. * @property {Object} globFilter
  4726. * @property {Function} filterPath
  4727. * @property {Function} filterDir
  4728. */
  4729. const arrify = (value = []) => Array.isArray(value) ? value : [value];
  4730. const flatten = (list, result = []) => {
  4731. list.forEach(item => {
  4732. if (Array.isArray(item)) {
  4733. flatten(item, result);
  4734. } else {
  4735. result.push(item);
  4736. }
  4737. });
  4738. return result;
  4739. };
  4740. const unifyPaths = (paths_) => {
  4741. /**
  4742. * @type {Array<String>}
  4743. */
  4744. const paths = flatten(arrify(paths_));
  4745. if (!paths.every(p => typeof p === STRING_TYPE)) {
  4746. throw new TypeError(`Non-string provided as watch path: ${paths}`);
  4747. }
  4748. return paths.map(normalizePathToUnix);
  4749. };
  4750. // If SLASH_SLASH occurs at the beginning of path, it is not replaced
  4751. // because "//StoragePC/DrivePool/Movies" is a valid network path
  4752. const toUnix = (string) => {
  4753. let str = string.replace(BACK_SLASH_RE, SLASH);
  4754. let prepend = false;
  4755. if (str.startsWith(SLASH_SLASH)) {
  4756. prepend = true;
  4757. }
  4758. while (str.match(DOUBLE_SLASH_RE)) {
  4759. str = str.replace(DOUBLE_SLASH_RE, SLASH);
  4760. }
  4761. if (prepend) {
  4762. str = SLASH + str;
  4763. }
  4764. return str;
  4765. };
  4766. // Our version of upath.normalize
  4767. // TODO: this is not equal to path-normalize module - investigate why
  4768. const normalizePathToUnix = (path) => toUnix(sysPath.normalize(toUnix(path)));
  4769. const normalizeIgnored = (cwd = EMPTY_STR) => (path) => {
  4770. if (typeof path !== STRING_TYPE) return path;
  4771. return normalizePathToUnix(sysPath.isAbsolute(path) ? path : sysPath.join(cwd, path));
  4772. };
  4773. const getAbsolutePath = (path, cwd) => {
  4774. if (sysPath.isAbsolute(path)) {
  4775. return path;
  4776. }
  4777. if (path.startsWith(BANG)) {
  4778. return BANG + sysPath.join(cwd, path.slice(1));
  4779. }
  4780. return sysPath.join(cwd, path);
  4781. };
  4782. const undef = (opts, key) => opts[key] === undefined;
  4783. /**
  4784. * Directory entry.
  4785. * @property {Path} path
  4786. * @property {Set<Path>} items
  4787. */
  4788. class DirEntry {
  4789. /**
  4790. * @param {Path} dir
  4791. * @param {Function} removeWatcher
  4792. */
  4793. constructor(dir, removeWatcher) {
  4794. this.path = dir;
  4795. this._removeWatcher = removeWatcher;
  4796. /** @type {Set<Path>} */
  4797. this.items = new Set();
  4798. }
  4799. add(item) {
  4800. const {items} = this;
  4801. if (!items) return;
  4802. if (item !== ONE_DOT && item !== TWO_DOTS) items.add(item);
  4803. }
  4804. async remove(item) {
  4805. const {items} = this;
  4806. if (!items) return;
  4807. items.delete(item);
  4808. if (items.size > 0) return;
  4809. const dir = this.path;
  4810. try {
  4811. await readdir(dir);
  4812. } catch (err) {
  4813. if (this._removeWatcher) {
  4814. this._removeWatcher(sysPath.dirname(dir), sysPath.basename(dir));
  4815. }
  4816. }
  4817. }
  4818. has(item) {
  4819. const {items} = this;
  4820. if (!items) return;
  4821. return items.has(item);
  4822. }
  4823. /**
  4824. * @returns {Array<String>}
  4825. */
  4826. getChildren() {
  4827. const {items} = this;
  4828. if (!items) return;
  4829. return [...items.values()];
  4830. }
  4831. dispose() {
  4832. this.items.clear();
  4833. delete this.path;
  4834. delete this._removeWatcher;
  4835. delete this.items;
  4836. Object.freeze(this);
  4837. }
  4838. }
  4839. const STAT_METHOD_F = 'stat';
  4840. const STAT_METHOD_L = 'lstat';
  4841. class WatchHelper {
  4842. constructor(path, watchPath, follow, fsw) {
  4843. this.fsw = fsw;
  4844. this.path = path = path.replace(REPLACER_RE, EMPTY_STR);
  4845. this.watchPath = watchPath;
  4846. this.fullWatchPath = sysPath.resolve(watchPath);
  4847. this.hasGlob = watchPath !== path;
  4848. /** @type {object|boolean} */
  4849. if (path === EMPTY_STR) this.hasGlob = false;
  4850. this.globSymlink = this.hasGlob && follow ? undefined : false;
  4851. this.globFilter = this.hasGlob ? anymatch(path, undefined, ANYMATCH_OPTS) : false;
  4852. this.dirParts = this.getDirParts(path);
  4853. this.dirParts.forEach((parts) => {
  4854. if (parts.length > 1) parts.pop();
  4855. });
  4856. this.followSymlinks = follow;
  4857. this.statMethod = follow ? STAT_METHOD_F : STAT_METHOD_L;
  4858. }
  4859. checkGlobSymlink(entry) {
  4860. // only need to resolve once
  4861. // first entry should always have entry.parentDir === EMPTY_STR
  4862. if (this.globSymlink === undefined) {
  4863. this.globSymlink = entry.fullParentDir === this.fullWatchPath ?
  4864. false : {realPath: entry.fullParentDir, linkPath: this.fullWatchPath};
  4865. }
  4866. if (this.globSymlink) {
  4867. return entry.fullPath.replace(this.globSymlink.realPath, this.globSymlink.linkPath);
  4868. }
  4869. return entry.fullPath;
  4870. }
  4871. entryPath(entry) {
  4872. return sysPath.join(this.watchPath,
  4873. sysPath.relative(this.watchPath, this.checkGlobSymlink(entry))
  4874. );
  4875. }
  4876. filterPath(entry) {
  4877. const {stats} = entry;
  4878. if (stats && stats.isSymbolicLink()) return this.filterDir(entry);
  4879. const resolvedPath = this.entryPath(entry);
  4880. const matchesGlob = this.hasGlob && typeof this.globFilter === FUNCTION_TYPE ?
  4881. this.globFilter(resolvedPath) : true;
  4882. return matchesGlob &&
  4883. this.fsw._isntIgnored(resolvedPath, stats) &&
  4884. this.fsw._hasReadPermissions(stats);
  4885. }
  4886. getDirParts(path) {
  4887. if (!this.hasGlob) return [];
  4888. const parts = [];
  4889. const expandedPath = path.includes(BRACE_START) ? braces.expand(path) : [path];
  4890. expandedPath.forEach((path) => {
  4891. parts.push(sysPath.relative(this.watchPath, path).split(SLASH_OR_BACK_SLASH_RE));
  4892. });
  4893. return parts;
  4894. }
  4895. filterDir(entry) {
  4896. if (this.hasGlob) {
  4897. const entryParts = this.getDirParts(this.checkGlobSymlink(entry));
  4898. let globstar = false;
  4899. this.unmatchedGlob = !this.dirParts.some((parts) => {
  4900. return parts.every((part, i) => {
  4901. if (part === GLOBSTAR) globstar = true;
  4902. return globstar || !entryParts[0][i] || anymatch(part, entryParts[0][i], ANYMATCH_OPTS);
  4903. });
  4904. });
  4905. }
  4906. return !this.unmatchedGlob && this.fsw._isntIgnored(this.entryPath(entry), entry.stats);
  4907. }
  4908. }
  4909. /**
  4910. * Watches files & directories for changes. Emitted events:
  4911. * `add`, `addDir`, `change`, `unlink`, `unlinkDir`, `all`, `error`
  4912. *
  4913. * new FSWatcher()
  4914. * .add(directories)
  4915. * .on('add', path => log('File', path, 'was added'))
  4916. */
  4917. class FSWatcher extends EventEmitter {
  4918. // Not indenting methods for history sake; for now.
  4919. constructor(_opts) {
  4920. super();
  4921. const opts = {};
  4922. if (_opts) Object.assign(opts, _opts); // for frozen objects
  4923. /** @type {Map<String, DirEntry>} */
  4924. this._watched = new Map();
  4925. /** @type {Map<String, Array>} */
  4926. this._closers = new Map();
  4927. /** @type {Set<String>} */
  4928. this._ignoredPaths = new Set();
  4929. /** @type {Map<ThrottleType, Map>} */
  4930. this._throttled = new Map();
  4931. /** @type {Map<Path, String|Boolean>} */
  4932. this._symlinkPaths = new Map();
  4933. this._streams = new Set();
  4934. this.closed = false;
  4935. // Set up default options.
  4936. if (undef(opts, 'persistent')) opts.persistent = true;
  4937. if (undef(opts, 'ignoreInitial')) opts.ignoreInitial = false;
  4938. if (undef(opts, 'ignorePermissionErrors')) opts.ignorePermissionErrors = false;
  4939. if (undef(opts, 'interval')) opts.interval = 100;
  4940. if (undef(opts, 'binaryInterval')) opts.binaryInterval = 300;
  4941. if (undef(opts, 'disableGlobbing')) opts.disableGlobbing = false;
  4942. opts.enableBinaryInterval = opts.binaryInterval !== opts.interval;
  4943. // Enable fsevents on OS X when polling isn't explicitly enabled.
  4944. if (undef(opts, 'useFsEvents')) opts.useFsEvents = !opts.usePolling;
  4945. // If we can't use fsevents, ensure the options reflect it's disabled.
  4946. const canUseFsEvents = FsEventsHandler.canUse();
  4947. if (!canUseFsEvents) opts.useFsEvents = false;
  4948. // Use polling on Mac if not using fsevents.
  4949. // Other platforms use non-polling fs_watch.
  4950. if (undef(opts, 'usePolling') && !opts.useFsEvents) {
  4951. opts.usePolling = isMacos;
  4952. }
  4953. // Global override (useful for end-developers that need to force polling for all
  4954. // instances of chokidar, regardless of usage/dependency depth)
  4955. const envPoll = process.env.CHOKIDAR_USEPOLLING;
  4956. if (envPoll !== undefined) {
  4957. const envLower = envPoll.toLowerCase();
  4958. if (envLower === 'false' || envLower === '0') {
  4959. opts.usePolling = false;
  4960. } else if (envLower === 'true' || envLower === '1') {
  4961. opts.usePolling = true;
  4962. } else {
  4963. opts.usePolling = !!envLower;
  4964. }
  4965. }
  4966. const envInterval = process.env.CHOKIDAR_INTERVAL;
  4967. if (envInterval) {
  4968. opts.interval = Number.parseInt(envInterval, 10);
  4969. }
  4970. // Editor atomic write normalization enabled by default with fs.watch
  4971. if (undef(opts, 'atomic')) opts.atomic = !opts.usePolling && !opts.useFsEvents;
  4972. if (opts.atomic) this._pendingUnlinks = new Map();
  4973. if (undef(opts, 'followSymlinks')) opts.followSymlinks = true;
  4974. if (undef(opts, 'awaitWriteFinish')) opts.awaitWriteFinish = false;
  4975. if (opts.awaitWriteFinish === true) opts.awaitWriteFinish = {};
  4976. const awf = opts.awaitWriteFinish;
  4977. if (awf) {
  4978. if (!awf.stabilityThreshold) awf.stabilityThreshold = 2000;
  4979. if (!awf.pollInterval) awf.pollInterval = 100;
  4980. this._pendingWrites = new Map();
  4981. }
  4982. if (opts.ignored) opts.ignored = arrify(opts.ignored);
  4983. let readyCalls = 0;
  4984. this._emitReady = () => {
  4985. readyCalls++;
  4986. if (readyCalls >= this._readyCount) {
  4987. this._emitReady = EMPTY_FN;
  4988. this._readyEmitted = true;
  4989. // use process.nextTick to allow time for listener to be bound
  4990. process.nextTick(() => this.emit(EV_READY));
  4991. }
  4992. };
  4993. this._emitRaw = (...args) => this.emit(EV_RAW, ...args);
  4994. this._readyEmitted = false;
  4995. this.options = opts;
  4996. // Initialize with proper watcher.
  4997. if (opts.useFsEvents) {
  4998. this._fsEventsHandler = new FsEventsHandler(this);
  4999. } else {
  5000. this._nodeFsHandler = new NodeFsHandler(this);
  5001. }
  5002. // You’re frozen when your heart’s not open.
  5003. Object.freeze(opts);
  5004. }
  5005. // Public methods
  5006. /**
  5007. * Adds paths to be watched on an existing FSWatcher instance
  5008. * @param {Path|Array<Path>} paths_
  5009. * @param {String=} _origAdd private; for handling non-existent paths to be watched
  5010. * @param {Boolean=} _internal private; indicates a non-user add
  5011. * @returns {FSWatcher} for chaining
  5012. */
  5013. add(paths_, _origAdd, _internal) {
  5014. const {cwd, disableGlobbing} = this.options;
  5015. this.closed = false;
  5016. let paths = unifyPaths(paths_);
  5017. if (cwd) {
  5018. paths = paths.map((path) => {
  5019. const absPath = getAbsolutePath(path, cwd);
  5020. // Check `path` instead of `absPath` because the cwd portion can't be a glob
  5021. if (disableGlobbing || !isGlob(path)) {
  5022. return absPath;
  5023. }
  5024. return normalizePath(absPath);
  5025. });
  5026. }
  5027. // set aside negated glob strings
  5028. paths = paths.filter((path) => {
  5029. if (path.startsWith(BANG)) {
  5030. this._ignoredPaths.add(path.slice(1));
  5031. return false;
  5032. }
  5033. // if a path is being added that was previously ignored, stop ignoring it
  5034. this._ignoredPaths.delete(path);
  5035. this._ignoredPaths.delete(path + SLASH_GLOBSTAR);
  5036. // reset the cached userIgnored anymatch fn
  5037. // to make ignoredPaths changes effective
  5038. this._userIgnored = undefined;
  5039. return true;
  5040. });
  5041. if (this.options.useFsEvents && this._fsEventsHandler) {
  5042. if (!this._readyCount) this._readyCount = paths.length;
  5043. if (this.options.persistent) this._readyCount *= 2;
  5044. paths.forEach((path) => this._fsEventsHandler._addToFsEvents(path));
  5045. } else {
  5046. if (!this._readyCount) this._readyCount = 0;
  5047. this._readyCount += paths.length;
  5048. Promise.all(
  5049. paths.map(async path => {
  5050. const res = await this._nodeFsHandler._addToNodeFs(path, !_internal, 0, 0, _origAdd);
  5051. if (res) this._emitReady();
  5052. return res;
  5053. })
  5054. ).then(results => {
  5055. if (this.closed) return;
  5056. results.filter(item => item).forEach(item => {
  5057. this.add(sysPath.dirname(item), sysPath.basename(_origAdd || item));
  5058. });
  5059. });
  5060. }
  5061. return this;
  5062. }
  5063. /**
  5064. * Close watchers or start ignoring events from specified paths.
  5065. * @param {Path|Array<Path>} paths_ - string or array of strings, file/directory paths and/or globs
  5066. * @returns {FSWatcher} for chaining
  5067. */
  5068. unwatch(paths_) {
  5069. if (this.closed) return this;
  5070. const paths = unifyPaths(paths_);
  5071. const {cwd} = this.options;
  5072. paths.forEach((path) => {
  5073. // convert to absolute path unless relative path already matches
  5074. if (!sysPath.isAbsolute(path) && !this._closers.has(path)) {
  5075. if (cwd) path = sysPath.join(cwd, path);
  5076. path = sysPath.resolve(path);
  5077. }
  5078. this._closePath(path);
  5079. this._ignoredPaths.add(path);
  5080. if (this._watched.has(path)) {
  5081. this._ignoredPaths.add(path + SLASH_GLOBSTAR);
  5082. }
  5083. // reset the cached userIgnored anymatch fn
  5084. // to make ignoredPaths changes effective
  5085. this._userIgnored = undefined;
  5086. });
  5087. return this;
  5088. }
  5089. /**
  5090. * Close watchers and remove all listeners from watched paths.
  5091. * @returns {Promise<void>}.
  5092. */
  5093. close() {
  5094. if (this.closed) return this._closePromise;
  5095. this.closed = true;
  5096. // Memory management.
  5097. this.removeAllListeners();
  5098. const closers = [];
  5099. this._closers.forEach(closerList => closerList.forEach(closer => {
  5100. const promise = closer();
  5101. if (promise instanceof Promise) closers.push(promise);
  5102. }));
  5103. this._streams.forEach(stream => stream.destroy());
  5104. this._userIgnored = undefined;
  5105. this._readyCount = 0;
  5106. this._readyEmitted = false;
  5107. this._watched.forEach(dirent => dirent.dispose());
  5108. ['closers', 'watched', 'streams', 'symlinkPaths', 'throttled'].forEach(key => {
  5109. this[`_${key}`].clear();
  5110. });
  5111. this._closePromise = closers.length ? Promise.all(closers).then(() => undefined) : Promise.resolve();
  5112. return this._closePromise;
  5113. }
  5114. /**
  5115. * Expose list of watched paths
  5116. * @returns {Object} for chaining
  5117. */
  5118. getWatched() {
  5119. const watchList = {};
  5120. this._watched.forEach((entry, dir) => {
  5121. const key = this.options.cwd ? sysPath.relative(this.options.cwd, dir) : dir;
  5122. watchList[key || ONE_DOT] = entry.getChildren().sort();
  5123. });
  5124. return watchList;
  5125. }
  5126. emitWithAll(event, args) {
  5127. this.emit(...args);
  5128. if (event !== EV_ERROR) this.emit(EV_ALL, ...args);
  5129. }
  5130. // Common helpers
  5131. // --------------
  5132. /**
  5133. * Normalize and emit events.
  5134. * Calling _emit DOES NOT MEAN emit() would be called!
  5135. * @param {EventName} event Type of event
  5136. * @param {Path} path File or directory path
  5137. * @param {*=} val1 arguments to be passed with event
  5138. * @param {*=} val2
  5139. * @param {*=} val3
  5140. * @returns the error if defined, otherwise the value of the FSWatcher instance's `closed` flag
  5141. */
  5142. async _emit(event, path, val1, val2, val3) {
  5143. if (this.closed) return;
  5144. const opts = this.options;
  5145. if (isWindows) path = sysPath.normalize(path);
  5146. if (opts.cwd) path = sysPath.relative(opts.cwd, path);
  5147. /** @type Array<any> */
  5148. const args = [event, path];
  5149. if (val3 !== undefined) args.push(val1, val2, val3);
  5150. else if (val2 !== undefined) args.push(val1, val2);
  5151. else if (val1 !== undefined) args.push(val1);
  5152. const awf = opts.awaitWriteFinish;
  5153. let pw;
  5154. if (awf && (pw = this._pendingWrites.get(path))) {
  5155. pw.lastChange = new Date();
  5156. return this;
  5157. }
  5158. if (opts.atomic) {
  5159. if (event === EV_UNLINK) {
  5160. this._pendingUnlinks.set(path, args);
  5161. setTimeout(() => {
  5162. this._pendingUnlinks.forEach((entry, path) => {
  5163. this.emit(...entry);
  5164. this.emit(EV_ALL, ...entry);
  5165. this._pendingUnlinks.delete(path);
  5166. });
  5167. }, typeof opts.atomic === 'number' ? opts.atomic : 100);
  5168. return this;
  5169. }
  5170. if (event === EV_ADD && this._pendingUnlinks.has(path)) {
  5171. event = args[0] = EV_CHANGE;
  5172. this._pendingUnlinks.delete(path);
  5173. }
  5174. }
  5175. if (awf && (event === EV_ADD || event === EV_CHANGE) && this._readyEmitted) {
  5176. const awfEmit = (err, stats) => {
  5177. if (err) {
  5178. event = args[0] = EV_ERROR;
  5179. args[1] = err;
  5180. this.emitWithAll(event, args);
  5181. } else if (stats) {
  5182. // if stats doesn't exist the file must have been deleted
  5183. if (args.length > 2) {
  5184. args[2] = stats;
  5185. } else {
  5186. args.push(stats);
  5187. }
  5188. this.emitWithAll(event, args);
  5189. }
  5190. };
  5191. this._awaitWriteFinish(path, awf.stabilityThreshold, event, awfEmit);
  5192. return this;
  5193. }
  5194. if (event === EV_CHANGE) {
  5195. const isThrottled = !this._throttle(EV_CHANGE, path, 50);
  5196. if (isThrottled) return this;
  5197. }
  5198. if (opts.alwaysStat && val1 === undefined &&
  5199. (event === EV_ADD || event === EV_ADD_DIR || event === EV_CHANGE)
  5200. ) {
  5201. const fullPath = opts.cwd ? sysPath.join(opts.cwd, path) : path;
  5202. let stats;
  5203. try {
  5204. stats = await stat(fullPath);
  5205. } catch (err) {}
  5206. // Suppress event when fs_stat fails, to avoid sending undefined 'stat'
  5207. if (!stats || this.closed) return;
  5208. args.push(stats);
  5209. }
  5210. this.emitWithAll(event, args);
  5211. return this;
  5212. }
  5213. /**
  5214. * Common handler for errors
  5215. * @param {Error} error
  5216. * @returns {Error|Boolean} The error if defined, otherwise the value of the FSWatcher instance's `closed` flag
  5217. */
  5218. _handleError(error) {
  5219. const code = error && error.code;
  5220. if (error && code !== 'ENOENT' && code !== 'ENOTDIR' &&
  5221. (!this.options.ignorePermissionErrors || (code !== 'EPERM' && code !== 'EACCES'))
  5222. ) {
  5223. this.emit(EV_ERROR, error);
  5224. }
  5225. return error || this.closed;
  5226. }
  5227. /**
  5228. * Helper utility for throttling
  5229. * @param {ThrottleType} actionType type being throttled
  5230. * @param {Path} path being acted upon
  5231. * @param {Number} timeout duration of time to suppress duplicate actions
  5232. * @returns {Object|false} tracking object or false if action should be suppressed
  5233. */
  5234. _throttle(actionType, path, timeout) {
  5235. if (!this._throttled.has(actionType)) {
  5236. this._throttled.set(actionType, new Map());
  5237. }
  5238. /** @type {Map<Path, Object>} */
  5239. const action = this._throttled.get(actionType);
  5240. /** @type {Object} */
  5241. const actionPath = action.get(path);
  5242. if (actionPath) {
  5243. actionPath.count++;
  5244. return false;
  5245. }
  5246. let timeoutObject;
  5247. const clear = () => {
  5248. const item = action.get(path);
  5249. const count = item ? item.count : 0;
  5250. action.delete(path);
  5251. clearTimeout(timeoutObject);
  5252. if (item) clearTimeout(item.timeoutObject);
  5253. return count;
  5254. };
  5255. timeoutObject = setTimeout(clear, timeout);
  5256. const thr = {timeoutObject, clear, count: 0};
  5257. action.set(path, thr);
  5258. return thr;
  5259. }
  5260. _incrReadyCount() {
  5261. return this._readyCount++;
  5262. }
  5263. /**
  5264. * Awaits write operation to finish.
  5265. * Polls a newly created file for size variations. When files size does not change for 'threshold' milliseconds calls callback.
  5266. * @param {Path} path being acted upon
  5267. * @param {Number} threshold Time in milliseconds a file size must be fixed before acknowledging write OP is finished
  5268. * @param {EventName} event
  5269. * @param {Function} awfEmit Callback to be called when ready for event to be emitted.
  5270. */
  5271. _awaitWriteFinish(path, threshold, event, awfEmit) {
  5272. let timeoutHandler;
  5273. let fullPath = path;
  5274. if (this.options.cwd && !sysPath.isAbsolute(path)) {
  5275. fullPath = sysPath.join(this.options.cwd, path);
  5276. }
  5277. const now = new Date();
  5278. const awaitWriteFinish = (prevStat) => {
  5279. fs.stat(fullPath, (err, curStat) => {
  5280. if (err || !this._pendingWrites.has(path)) {
  5281. if (err && err.code !== 'ENOENT') awfEmit(err);
  5282. return;
  5283. }
  5284. const now = Number(new Date());
  5285. if (prevStat && curStat.size !== prevStat.size) {
  5286. this._pendingWrites.get(path).lastChange = now;
  5287. }
  5288. const pw = this._pendingWrites.get(path);
  5289. const df = now - pw.lastChange;
  5290. if (df >= threshold) {
  5291. this._pendingWrites.delete(path);
  5292. awfEmit(undefined, curStat);
  5293. } else {
  5294. timeoutHandler = setTimeout(
  5295. awaitWriteFinish,
  5296. this.options.awaitWriteFinish.pollInterval,
  5297. curStat
  5298. );
  5299. }
  5300. });
  5301. };
  5302. if (!this._pendingWrites.has(path)) {
  5303. this._pendingWrites.set(path, {
  5304. lastChange: now,
  5305. cancelWait: () => {
  5306. this._pendingWrites.delete(path);
  5307. clearTimeout(timeoutHandler);
  5308. return event;
  5309. }
  5310. });
  5311. timeoutHandler = setTimeout(
  5312. awaitWriteFinish,
  5313. this.options.awaitWriteFinish.pollInterval
  5314. );
  5315. }
  5316. }
  5317. _getGlobIgnored() {
  5318. return [...this._ignoredPaths.values()];
  5319. }
  5320. /**
  5321. * Determines whether user has asked to ignore this path.
  5322. * @param {Path} path filepath or dir
  5323. * @param {fs.Stats=} stats result of fs.stat
  5324. * @returns {Boolean}
  5325. */
  5326. _isIgnored(path, stats) {
  5327. if (this.options.atomic && DOT_RE.test(path)) return true;
  5328. if (!this._userIgnored) {
  5329. const {cwd} = this.options;
  5330. const ign = this.options.ignored;
  5331. const ignored = ign && ign.map(normalizeIgnored(cwd));
  5332. const paths = arrify(ignored)
  5333. .filter((path) => typeof path === STRING_TYPE && !isGlob(path))
  5334. .map((path) => path + SLASH_GLOBSTAR);
  5335. const list = this._getGlobIgnored().map(normalizeIgnored(cwd)).concat(ignored, paths);
  5336. this._userIgnored = anymatch(list, undefined, ANYMATCH_OPTS);
  5337. }
  5338. return this._userIgnored([path, stats]);
  5339. }
  5340. _isntIgnored(path, stat) {
  5341. return !this._isIgnored(path, stat);
  5342. }
  5343. /**
  5344. * Provides a set of common helpers and properties relating to symlink and glob handling.
  5345. * @param {Path} path file, directory, or glob pattern being watched
  5346. * @param {Number=} depth at any depth > 0, this isn't a glob
  5347. * @returns {WatchHelper} object containing helpers for this path
  5348. */
  5349. _getWatchHelpers(path, depth) {
  5350. const watchPath = depth || this.options.disableGlobbing || !isGlob(path) ? path : globParent(path);
  5351. const follow = this.options.followSymlinks;
  5352. return new WatchHelper(path, watchPath, follow, this);
  5353. }
  5354. // Directory helpers
  5355. // -----------------
  5356. /**
  5357. * Provides directory tracking objects
  5358. * @param {String} directory path of the directory
  5359. * @returns {DirEntry} the directory's tracking object
  5360. */
  5361. _getWatchedDir(directory) {
  5362. if (!this._boundRemove) this._boundRemove = this._remove.bind(this);
  5363. const dir = sysPath.resolve(directory);
  5364. if (!this._watched.has(dir)) this._watched.set(dir, new DirEntry(dir, this._boundRemove));
  5365. return this._watched.get(dir);
  5366. }
  5367. // File helpers
  5368. // ------------
  5369. /**
  5370. * Check for read permissions.
  5371. * Based on this answer on SO: https://stackoverflow.com/a/11781404/1358405
  5372. * @param {fs.Stats} stats - object, result of fs_stat
  5373. * @returns {Boolean} indicates whether the file can be read
  5374. */
  5375. _hasReadPermissions(stats) {
  5376. if (this.options.ignorePermissionErrors) return true;
  5377. // stats.mode may be bigint
  5378. const md = stats && Number.parseInt(stats.mode, 10);
  5379. const st = md & 0o777;
  5380. const it = Number.parseInt(st.toString(8)[0], 10);
  5381. return Boolean(4 & it);
  5382. }
  5383. /**
  5384. * Handles emitting unlink events for
  5385. * files and directories, and via recursion, for
  5386. * files and directories within directories that are unlinked
  5387. * @param {String} directory within which the following item is located
  5388. * @param {String} item base path of item/directory
  5389. * @returns {void}
  5390. */
  5391. _remove(directory, item, isDirectory) {
  5392. // if what is being deleted is a directory, get that directory's paths
  5393. // for recursive deleting and cleaning of watched object
  5394. // if it is not a directory, nestedDirectoryChildren will be empty array
  5395. const path = sysPath.join(directory, item);
  5396. const fullPath = sysPath.resolve(path);
  5397. isDirectory = isDirectory != null
  5398. ? isDirectory
  5399. : this._watched.has(path) || this._watched.has(fullPath);
  5400. // prevent duplicate handling in case of arriving here nearly simultaneously
  5401. // via multiple paths (such as _handleFile and _handleDir)
  5402. if (!this._throttle('remove', path, 100)) return;
  5403. // if the only watched file is removed, watch for its return
  5404. if (!isDirectory && !this.options.useFsEvents && this._watched.size === 1) {
  5405. this.add(directory, item, true);
  5406. }
  5407. // This will create a new entry in the watched object in either case
  5408. // so we got to do the directory check beforehand
  5409. const wp = this._getWatchedDir(path);
  5410. const nestedDirectoryChildren = wp.getChildren();
  5411. // Recursively remove children directories / files.
  5412. nestedDirectoryChildren.forEach(nested => this._remove(path, nested));
  5413. // Check if item was on the watched list and remove it
  5414. const parent = this._getWatchedDir(directory);
  5415. const wasTracked = parent.has(item);
  5416. parent.remove(item);
  5417. // Fixes issue #1042 -> Relative paths were detected and added as symlinks
  5418. // (https://github.com/paulmillr/chokidar/blob/e1753ddbc9571bdc33b4a4af172d52cb6e611c10/lib/nodefs-handler.js#L612),
  5419. // but never removed from the map in case the path was deleted.
  5420. // This leads to an incorrect state if the path was recreated:
  5421. // https://github.com/paulmillr/chokidar/blob/e1753ddbc9571bdc33b4a4af172d52cb6e611c10/lib/nodefs-handler.js#L553
  5422. if (this._symlinkPaths.has(fullPath)) {
  5423. this._symlinkPaths.delete(fullPath);
  5424. }
  5425. // If we wait for this file to be fully written, cancel the wait.
  5426. let relPath = path;
  5427. if (this.options.cwd) relPath = sysPath.relative(this.options.cwd, path);
  5428. if (this.options.awaitWriteFinish && this._pendingWrites.has(relPath)) {
  5429. const event = this._pendingWrites.get(relPath).cancelWait();
  5430. if (event === EV_ADD) return;
  5431. }
  5432. // The Entry will either be a directory that just got removed
  5433. // or a bogus entry to a file, in either case we have to remove it
  5434. this._watched.delete(path);
  5435. this._watched.delete(fullPath);
  5436. const eventName = isDirectory ? EV_UNLINK_DIR : EV_UNLINK;
  5437. if (wasTracked && !this._isIgnored(path)) this._emit(eventName, path);
  5438. // Avoid conflicts if we later create another file with the same name
  5439. if (!this.options.useFsEvents) {
  5440. this._closePath(path);
  5441. }
  5442. }
  5443. /**
  5444. * Closes all watchers for a path
  5445. * @param {Path} path
  5446. */
  5447. _closePath(path) {
  5448. this._closeFile(path);
  5449. const dir = sysPath.dirname(path);
  5450. this._getWatchedDir(dir).remove(sysPath.basename(path));
  5451. }
  5452. /**
  5453. * Closes only file-specific watchers
  5454. * @param {Path} path
  5455. */
  5456. _closeFile(path) {
  5457. const closers = this._closers.get(path);
  5458. if (!closers) return;
  5459. closers.forEach(closer => closer());
  5460. this._closers.delete(path);
  5461. }
  5462. /**
  5463. *
  5464. * @param {Path} path
  5465. * @param {Function} closer
  5466. */
  5467. _addPathCloser(path, closer) {
  5468. if (!closer) return;
  5469. let list = this._closers.get(path);
  5470. if (!list) {
  5471. list = [];
  5472. this._closers.set(path, list);
  5473. }
  5474. list.push(closer);
  5475. }
  5476. _readdirp(root, opts) {
  5477. if (this.closed) return;
  5478. const options = {type: EV_ALL, alwaysStat: true, lstat: true, ...opts};
  5479. let stream = readdirp(root, options);
  5480. this._streams.add(stream);
  5481. stream.once(STR_CLOSE, () => {
  5482. stream = undefined;
  5483. });
  5484. stream.once(STR_END, () => {
  5485. if (stream) {
  5486. this._streams.delete(stream);
  5487. stream = undefined;
  5488. }
  5489. });
  5490. return stream;
  5491. }
  5492. }
  5493. // Export FSWatcher class
  5494. chokidar.FSWatcher = FSWatcher;
  5495. /**
  5496. * Instantiates watcher with paths to be tracked.
  5497. * @param {String|Array<String>} paths file/directory paths and/or globs
  5498. * @param {Object=} options chokidar opts
  5499. * @returns an instance of FSWatcher for chaining.
  5500. */
  5501. const watch = (paths, options) => {
  5502. const watcher = new FSWatcher(options);
  5503. watcher.add(paths);
  5504. return watcher;
  5505. };
  5506. chokidar.watch = watch;
  5507. exports.braces_1 = braces_1;
  5508. exports.chokidar = chokidar;
  5509. exports.picomatch = picomatch$2;
  5510. exports.utils = utils$3;
  5511. //# sourceMappingURL=index.js.map