watch.js 135 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003
  1. /*
  2. @license
  3. Rollup.js v2.79.1
  4. Thu, 22 Sep 2022 04:55:29 GMT - commit 69ff4181e701a0fe0026d0ba147f31bc86beffa8
  5. https://github.com/rollup/rollup
  6. Released under the MIT License.
  7. */
  8. import require$$0$2, { resolve } from 'path';
  9. import process$1 from 'process';
  10. import { ensureArray, warnUnknownOptions, defaultOnWarn, objectifyOptionWithPresets, treeshakePresets, objectifyOption, generatedCodePresets, picomatch as picomatch$2, getAugmentedNamespace, fseventsImporter, createFilter, rollupInternal } from './rollup.js';
  11. import require$$2$1, { platform } from 'os';
  12. import require$$0$1 from 'fs';
  13. import require$$2 from 'util';
  14. import require$$1 from 'stream';
  15. import require$$0$3 from 'events';
  16. import 'perf_hooks';
  17. import 'crypto';
  18. const commandAliases = {
  19. c: 'config',
  20. d: 'dir',
  21. e: 'external',
  22. f: 'format',
  23. g: 'globals',
  24. h: 'help',
  25. i: 'input',
  26. m: 'sourcemap',
  27. n: 'name',
  28. o: 'file',
  29. p: 'plugin',
  30. v: 'version',
  31. w: 'watch'
  32. };
  33. function mergeOptions(config, rawCommandOptions = { external: [], globals: undefined }, defaultOnWarnHandler = defaultOnWarn) {
  34. const command = getCommandOptions(rawCommandOptions);
  35. const inputOptions = mergeInputOptions(config, command, defaultOnWarnHandler);
  36. const warn = inputOptions.onwarn;
  37. if (command.output) {
  38. Object.assign(command, command.output);
  39. }
  40. const outputOptionsArray = ensureArray(config.output);
  41. if (outputOptionsArray.length === 0)
  42. outputOptionsArray.push({});
  43. const outputOptions = outputOptionsArray.map(singleOutputOptions => mergeOutputOptions(singleOutputOptions, command, warn));
  44. warnUnknownOptions(command, Object.keys(inputOptions).concat(Object.keys(outputOptions[0]).filter(option => option !== 'sourcemapPathTransform'), Object.keys(commandAliases), 'config', 'environment', 'plugin', 'silent', 'failAfterWarnings', 'stdin', 'waitForBundleInput', 'configPlugin'), 'CLI flags', warn, /^_$|output$|config/);
  45. inputOptions.output = outputOptions;
  46. return inputOptions;
  47. }
  48. function getCommandOptions(rawCommandOptions) {
  49. const external = rawCommandOptions.external && typeof rawCommandOptions.external === 'string'
  50. ? rawCommandOptions.external.split(',')
  51. : [];
  52. return {
  53. ...rawCommandOptions,
  54. external,
  55. globals: typeof rawCommandOptions.globals === 'string'
  56. ? rawCommandOptions.globals.split(',').reduce((globals, globalDefinition) => {
  57. const [id, variableName] = globalDefinition.split(':');
  58. globals[id] = variableName;
  59. if (!external.includes(id)) {
  60. external.push(id);
  61. }
  62. return globals;
  63. }, Object.create(null))
  64. : undefined
  65. };
  66. }
  67. function mergeInputOptions(config, overrides, defaultOnWarnHandler) {
  68. const getOption = (name) => { var _a; return (_a = overrides[name]) !== null && _a !== void 0 ? _a : config[name]; };
  69. const inputOptions = {
  70. acorn: getOption('acorn'),
  71. acornInjectPlugins: config.acornInjectPlugins,
  72. cache: config.cache,
  73. context: getOption('context'),
  74. experimentalCacheExpiry: getOption('experimentalCacheExpiry'),
  75. external: getExternal(config, overrides),
  76. inlineDynamicImports: getOption('inlineDynamicImports'),
  77. input: getOption('input') || [],
  78. makeAbsoluteExternalsRelative: getOption('makeAbsoluteExternalsRelative'),
  79. manualChunks: getOption('manualChunks'),
  80. maxParallelFileOps: getOption('maxParallelFileOps'),
  81. maxParallelFileReads: getOption('maxParallelFileReads'),
  82. moduleContext: getOption('moduleContext'),
  83. onwarn: getOnWarn(config, defaultOnWarnHandler),
  84. perf: getOption('perf'),
  85. plugins: ensureArray(config.plugins),
  86. preserveEntrySignatures: getOption('preserveEntrySignatures'),
  87. preserveModules: getOption('preserveModules'),
  88. preserveSymlinks: getOption('preserveSymlinks'),
  89. shimMissingExports: getOption('shimMissingExports'),
  90. strictDeprecations: getOption('strictDeprecations'),
  91. treeshake: getObjectOption(config, overrides, 'treeshake', objectifyOptionWithPresets(treeshakePresets, 'treeshake', 'false, true, ')),
  92. watch: getWatch(config, overrides)
  93. };
  94. warnUnknownOptions(config, Object.keys(inputOptions), 'input options', inputOptions.onwarn, /^output$/);
  95. return inputOptions;
  96. }
  97. const getExternal = (config, overrides) => {
  98. const configExternal = config.external;
  99. return typeof configExternal === 'function'
  100. ? (source, importer, isResolved) => configExternal(source, importer, isResolved) || overrides.external.includes(source)
  101. : ensureArray(configExternal).concat(overrides.external);
  102. };
  103. const getOnWarn = (config, defaultOnWarnHandler) => config.onwarn
  104. ? warning => config.onwarn(warning, defaultOnWarnHandler)
  105. : defaultOnWarnHandler;
  106. const getObjectOption = (config, overrides, name, objectifyValue = objectifyOption) => {
  107. const commandOption = normalizeObjectOptionValue(overrides[name], objectifyValue);
  108. const configOption = normalizeObjectOptionValue(config[name], objectifyValue);
  109. if (commandOption !== undefined) {
  110. return commandOption && { ...configOption, ...commandOption };
  111. }
  112. return configOption;
  113. };
  114. const getWatch = (config, overrides) => config.watch !== false && getObjectOption(config, overrides, 'watch');
  115. const normalizeObjectOptionValue = (optionValue, objectifyValue) => {
  116. if (!optionValue) {
  117. return optionValue;
  118. }
  119. if (Array.isArray(optionValue)) {
  120. return optionValue.reduce((result, value) => value && result && { ...result, ...objectifyValue(value) }, {});
  121. }
  122. return objectifyValue(optionValue);
  123. };
  124. function mergeOutputOptions(config, overrides, warn) {
  125. const getOption = (name) => { var _a; return (_a = overrides[name]) !== null && _a !== void 0 ? _a : config[name]; };
  126. const outputOptions = {
  127. amd: getObjectOption(config, overrides, 'amd'),
  128. assetFileNames: getOption('assetFileNames'),
  129. banner: getOption('banner'),
  130. chunkFileNames: getOption('chunkFileNames'),
  131. compact: getOption('compact'),
  132. dir: getOption('dir'),
  133. dynamicImportFunction: getOption('dynamicImportFunction'),
  134. entryFileNames: getOption('entryFileNames'),
  135. esModule: getOption('esModule'),
  136. exports: getOption('exports'),
  137. extend: getOption('extend'),
  138. externalLiveBindings: getOption('externalLiveBindings'),
  139. file: getOption('file'),
  140. footer: getOption('footer'),
  141. format: getOption('format'),
  142. freeze: getOption('freeze'),
  143. generatedCode: getObjectOption(config, overrides, 'generatedCode', objectifyOptionWithPresets(generatedCodePresets, 'output.generatedCode', '')),
  144. globals: getOption('globals'),
  145. hoistTransitiveImports: getOption('hoistTransitiveImports'),
  146. indent: getOption('indent'),
  147. inlineDynamicImports: getOption('inlineDynamicImports'),
  148. interop: getOption('interop'),
  149. intro: getOption('intro'),
  150. manualChunks: getOption('manualChunks'),
  151. minifyInternalExports: getOption('minifyInternalExports'),
  152. name: getOption('name'),
  153. namespaceToStringTag: getOption('namespaceToStringTag'),
  154. noConflict: getOption('noConflict'),
  155. outro: getOption('outro'),
  156. paths: getOption('paths'),
  157. plugins: ensureArray(config.plugins),
  158. preferConst: getOption('preferConst'),
  159. preserveModules: getOption('preserveModules'),
  160. preserveModulesRoot: getOption('preserveModulesRoot'),
  161. sanitizeFileName: getOption('sanitizeFileName'),
  162. sourcemap: getOption('sourcemap'),
  163. sourcemapBaseUrl: getOption('sourcemapBaseUrl'),
  164. sourcemapExcludeSources: getOption('sourcemapExcludeSources'),
  165. sourcemapFile: getOption('sourcemapFile'),
  166. sourcemapPathTransform: getOption('sourcemapPathTransform'),
  167. strict: getOption('strict'),
  168. systemNullSetters: getOption('systemNullSetters'),
  169. validate: getOption('validate')
  170. };
  171. warnUnknownOptions(config, Object.keys(outputOptions), 'output options', warn);
  172. return outputOptions;
  173. }
  174. var chokidar = {};
  175. const fs$3 = require$$0$1;
  176. const { Readable } = require$$1;
  177. const sysPath$3 = require$$0$2;
  178. const { promisify: promisify$3 } = require$$2;
  179. const picomatch$1 = picomatch$2.exports;
  180. const readdir$1 = promisify$3(fs$3.readdir);
  181. const stat$3 = promisify$3(fs$3.stat);
  182. const lstat$2 = promisify$3(fs$3.lstat);
  183. const realpath$1 = promisify$3(fs$3.realpath);
  184. /**
  185. * @typedef {Object} EntryInfo
  186. * @property {String} path
  187. * @property {String} fullPath
  188. * @property {fs.Stats=} stats
  189. * @property {fs.Dirent=} dirent
  190. * @property {String} basename
  191. */
  192. const BANG$2 = '!';
  193. const RECURSIVE_ERROR_CODE = 'READDIRP_RECURSIVE_ERROR';
  194. const NORMAL_FLOW_ERRORS = new Set(['ENOENT', 'EPERM', 'EACCES', 'ELOOP', RECURSIVE_ERROR_CODE]);
  195. const FILE_TYPE = 'files';
  196. const DIR_TYPE = 'directories';
  197. const FILE_DIR_TYPE = 'files_directories';
  198. const EVERYTHING_TYPE = 'all';
  199. const ALL_TYPES = [FILE_TYPE, DIR_TYPE, FILE_DIR_TYPE, EVERYTHING_TYPE];
  200. const isNormalFlowError = error => NORMAL_FLOW_ERRORS.has(error.code);
  201. const [maj, min] = process.versions.node.split('.').slice(0, 2).map(n => Number.parseInt(n, 10));
  202. const wantBigintFsStats = process.platform === 'win32' && (maj > 10 || (maj === 10 && min >= 5));
  203. const normalizeFilter = filter => {
  204. if (filter === undefined) return;
  205. if (typeof filter === 'function') return filter;
  206. if (typeof filter === 'string') {
  207. const glob = picomatch$1(filter.trim());
  208. return entry => glob(entry.basename);
  209. }
  210. if (Array.isArray(filter)) {
  211. const positive = [];
  212. const negative = [];
  213. for (const item of filter) {
  214. const trimmed = item.trim();
  215. if (trimmed.charAt(0) === BANG$2) {
  216. negative.push(picomatch$1(trimmed.slice(1)));
  217. } else {
  218. positive.push(picomatch$1(trimmed));
  219. }
  220. }
  221. if (negative.length > 0) {
  222. if (positive.length > 0) {
  223. return entry =>
  224. positive.some(f => f(entry.basename)) && !negative.some(f => f(entry.basename));
  225. }
  226. return entry => !negative.some(f => f(entry.basename));
  227. }
  228. return entry => positive.some(f => f(entry.basename));
  229. }
  230. };
  231. class ReaddirpStream extends Readable {
  232. static get defaultOptions() {
  233. return {
  234. root: '.',
  235. /* eslint-disable no-unused-vars */
  236. fileFilter: (path) => true,
  237. directoryFilter: (path) => true,
  238. /* eslint-enable no-unused-vars */
  239. type: FILE_TYPE,
  240. lstat: false,
  241. depth: 2147483648,
  242. alwaysStat: false
  243. };
  244. }
  245. constructor(options = {}) {
  246. super({
  247. objectMode: true,
  248. autoDestroy: true,
  249. highWaterMark: options.highWaterMark || 4096
  250. });
  251. const opts = { ...ReaddirpStream.defaultOptions, ...options };
  252. const { root, type } = opts;
  253. this._fileFilter = normalizeFilter(opts.fileFilter);
  254. this._directoryFilter = normalizeFilter(opts.directoryFilter);
  255. const statMethod = opts.lstat ? lstat$2 : stat$3;
  256. // Use bigint stats if it's windows and stat() supports options (node 10+).
  257. if (wantBigintFsStats) {
  258. this._stat = path => statMethod(path, { bigint: true });
  259. } else {
  260. this._stat = statMethod;
  261. }
  262. this._maxDepth = opts.depth;
  263. this._wantsDir = [DIR_TYPE, FILE_DIR_TYPE, EVERYTHING_TYPE].includes(type);
  264. this._wantsFile = [FILE_TYPE, FILE_DIR_TYPE, EVERYTHING_TYPE].includes(type);
  265. this._wantsEverything = type === EVERYTHING_TYPE;
  266. this._root = sysPath$3.resolve(root);
  267. this._isDirent = ('Dirent' in fs$3) && !opts.alwaysStat;
  268. this._statsProp = this._isDirent ? 'dirent' : 'stats';
  269. this._rdOptions = { encoding: 'utf8', withFileTypes: this._isDirent };
  270. // Launch stream with one parent, the root dir.
  271. this.parents = [this._exploreDir(root, 1)];
  272. this.reading = false;
  273. this.parent = undefined;
  274. }
  275. async _read(batch) {
  276. if (this.reading) return;
  277. this.reading = true;
  278. try {
  279. while (!this.destroyed && batch > 0) {
  280. const { path, depth, files = [] } = this.parent || {};
  281. if (files.length > 0) {
  282. const slice = files.splice(0, batch).map(dirent => this._formatEntry(dirent, path));
  283. for (const entry of await Promise.all(slice)) {
  284. if (this.destroyed) return;
  285. const entryType = await this._getEntryType(entry);
  286. if (entryType === 'directory' && this._directoryFilter(entry)) {
  287. if (depth <= this._maxDepth) {
  288. this.parents.push(this._exploreDir(entry.fullPath, depth + 1));
  289. }
  290. if (this._wantsDir) {
  291. this.push(entry);
  292. batch--;
  293. }
  294. } else if ((entryType === 'file' || this._includeAsFile(entry)) && this._fileFilter(entry)) {
  295. if (this._wantsFile) {
  296. this.push(entry);
  297. batch--;
  298. }
  299. }
  300. }
  301. } else {
  302. const parent = this.parents.pop();
  303. if (!parent) {
  304. this.push(null);
  305. break;
  306. }
  307. this.parent = await parent;
  308. if (this.destroyed) return;
  309. }
  310. }
  311. } catch (error) {
  312. this.destroy(error);
  313. } finally {
  314. this.reading = false;
  315. }
  316. }
  317. async _exploreDir(path, depth) {
  318. let files;
  319. try {
  320. files = await readdir$1(path, this._rdOptions);
  321. } catch (error) {
  322. this._onError(error);
  323. }
  324. return { files, depth, path };
  325. }
  326. async _formatEntry(dirent, path) {
  327. let entry;
  328. try {
  329. const basename = this._isDirent ? dirent.name : dirent;
  330. const fullPath = sysPath$3.resolve(sysPath$3.join(path, basename));
  331. entry = { path: sysPath$3.relative(this._root, fullPath), fullPath, basename };
  332. entry[this._statsProp] = this._isDirent ? dirent : await this._stat(fullPath);
  333. } catch (err) {
  334. this._onError(err);
  335. }
  336. return entry;
  337. }
  338. _onError(err) {
  339. if (isNormalFlowError(err) && !this.destroyed) {
  340. this.emit('warn', err);
  341. } else {
  342. this.destroy(err);
  343. }
  344. }
  345. async _getEntryType(entry) {
  346. // entry may be undefined, because a warning or an error were emitted
  347. // and the statsProp is undefined
  348. const stats = entry && entry[this._statsProp];
  349. if (!stats) {
  350. return;
  351. }
  352. if (stats.isFile()) {
  353. return 'file';
  354. }
  355. if (stats.isDirectory()) {
  356. return 'directory';
  357. }
  358. if (stats && stats.isSymbolicLink()) {
  359. const full = entry.fullPath;
  360. try {
  361. const entryRealPath = await realpath$1(full);
  362. const entryRealPathStats = await lstat$2(entryRealPath);
  363. if (entryRealPathStats.isFile()) {
  364. return 'file';
  365. }
  366. if (entryRealPathStats.isDirectory()) {
  367. const len = entryRealPath.length;
  368. if (full.startsWith(entryRealPath) && full.substr(len, 1) === sysPath$3.sep) {
  369. const recursiveError = new Error(
  370. `Circular symlink detected: "${full}" points to "${entryRealPath}"`
  371. );
  372. recursiveError.code = RECURSIVE_ERROR_CODE;
  373. return this._onError(recursiveError);
  374. }
  375. return 'directory';
  376. }
  377. } catch (error) {
  378. this._onError(error);
  379. }
  380. }
  381. }
  382. _includeAsFile(entry) {
  383. const stats = entry && entry[this._statsProp];
  384. return stats && this._wantsEverything && !stats.isDirectory();
  385. }
  386. }
  387. /**
  388. * @typedef {Object} ReaddirpArguments
  389. * @property {Function=} fileFilter
  390. * @property {Function=} directoryFilter
  391. * @property {String=} type
  392. * @property {Number=} depth
  393. * @property {String=} root
  394. * @property {Boolean=} lstat
  395. * @property {Boolean=} bigint
  396. */
  397. /**
  398. * Main function which ends up calling readdirRec and reads all files and directories in given root recursively.
  399. * @param {String} root Root directory
  400. * @param {ReaddirpArguments=} options Options to specify root (start directory), filters and recursion depth
  401. */
  402. const readdirp$1 = (root, options = {}) => {
  403. let type = options.entryType || options.type;
  404. if (type === 'both') type = FILE_DIR_TYPE; // backwards-compatibility
  405. if (type) options.type = type;
  406. if (!root) {
  407. throw new Error('readdirp: root argument is required. Usage: readdirp(root, options)');
  408. } else if (typeof root !== 'string') {
  409. throw new TypeError('readdirp: root argument must be a string. Usage: readdirp(root, options)');
  410. } else if (type && !ALL_TYPES.includes(type)) {
  411. throw new Error(`readdirp: Invalid type passed. Use one of ${ALL_TYPES.join(', ')}`);
  412. }
  413. options.root = root;
  414. return new ReaddirpStream(options);
  415. };
  416. const readdirpPromise = (root, options = {}) => {
  417. return new Promise((resolve, reject) => {
  418. const files = [];
  419. readdirp$1(root, options)
  420. .on('data', entry => files.push(entry))
  421. .on('end', () => resolve(files))
  422. .on('error', error => reject(error));
  423. });
  424. };
  425. readdirp$1.promise = readdirpPromise;
  426. readdirp$1.ReaddirpStream = ReaddirpStream;
  427. readdirp$1.default = readdirp$1;
  428. var readdirp_1 = readdirp$1;
  429. var anymatch$2 = {exports: {}};
  430. /*!
  431. * normalize-path <https://github.com/jonschlinkert/normalize-path>
  432. *
  433. * Copyright (c) 2014-2018, Jon Schlinkert.
  434. * Released under the MIT License.
  435. */
  436. var normalizePath$2 = function(path, stripTrailing) {
  437. if (typeof path !== 'string') {
  438. throw new TypeError('expected path to be a string');
  439. }
  440. if (path === '\\' || path === '/') return '/';
  441. var len = path.length;
  442. if (len <= 1) return path;
  443. // ensure that win32 namespaces has two leading slashes, so that the path is
  444. // handled properly by the win32 version of path.parse() after being normalized
  445. // https://msdn.microsoft.com/library/windows/desktop/aa365247(v=vs.85).aspx#namespaces
  446. var prefix = '';
  447. if (len > 4 && path[3] === '\\') {
  448. var ch = path[2];
  449. if ((ch === '?' || ch === '.') && path.slice(0, 2) === '\\\\') {
  450. path = path.slice(2);
  451. prefix = '//';
  452. }
  453. }
  454. var segs = path.split(/[/\\]+/);
  455. if (stripTrailing !== false && segs[segs.length - 1] === '') {
  456. segs.pop();
  457. }
  458. return prefix + segs.join('/');
  459. };
  460. Object.defineProperty(anymatch$2.exports, "__esModule", { value: true });
  461. const picomatch = picomatch$2.exports;
  462. const normalizePath$1 = normalizePath$2;
  463. /**
  464. * @typedef {(testString: string) => boolean} AnymatchFn
  465. * @typedef {string|RegExp|AnymatchFn} AnymatchPattern
  466. * @typedef {AnymatchPattern|AnymatchPattern[]} AnymatchMatcher
  467. */
  468. const BANG$1 = '!';
  469. const DEFAULT_OPTIONS = {returnIndex: false};
  470. const arrify$1 = (item) => Array.isArray(item) ? item : [item];
  471. /**
  472. * @param {AnymatchPattern} matcher
  473. * @param {object} options
  474. * @returns {AnymatchFn}
  475. */
  476. const createPattern = (matcher, options) => {
  477. if (typeof matcher === 'function') {
  478. return matcher;
  479. }
  480. if (typeof matcher === 'string') {
  481. const glob = picomatch(matcher, options);
  482. return (string) => matcher === string || glob(string);
  483. }
  484. if (matcher instanceof RegExp) {
  485. return (string) => matcher.test(string);
  486. }
  487. return (string) => false;
  488. };
  489. /**
  490. * @param {Array<Function>} patterns
  491. * @param {Array<Function>} negPatterns
  492. * @param {String|Array} args
  493. * @param {Boolean} returnIndex
  494. * @returns {boolean|number}
  495. */
  496. const matchPatterns = (patterns, negPatterns, args, returnIndex) => {
  497. const isList = Array.isArray(args);
  498. const _path = isList ? args[0] : args;
  499. if (!isList && typeof _path !== 'string') {
  500. throw new TypeError('anymatch: second argument must be a string: got ' +
  501. Object.prototype.toString.call(_path))
  502. }
  503. const path = normalizePath$1(_path);
  504. for (let index = 0; index < negPatterns.length; index++) {
  505. const nglob = negPatterns[index];
  506. if (nglob(path)) {
  507. return returnIndex ? -1 : false;
  508. }
  509. }
  510. const applied = isList && [path].concat(args.slice(1));
  511. for (let index = 0; index < patterns.length; index++) {
  512. const pattern = patterns[index];
  513. if (isList ? pattern(...applied) : pattern(path)) {
  514. return returnIndex ? index : true;
  515. }
  516. }
  517. return returnIndex ? -1 : false;
  518. };
  519. /**
  520. * @param {AnymatchMatcher} matchers
  521. * @param {Array|string} testString
  522. * @param {object} options
  523. * @returns {boolean|number|Function}
  524. */
  525. const anymatch$1 = (matchers, testString, options = DEFAULT_OPTIONS) => {
  526. if (matchers == null) {
  527. throw new TypeError('anymatch: specify first argument');
  528. }
  529. const opts = typeof options === 'boolean' ? {returnIndex: options} : options;
  530. const returnIndex = opts.returnIndex || false;
  531. // Early cache for matchers.
  532. const mtchers = arrify$1(matchers);
  533. const negatedGlobs = mtchers
  534. .filter(item => typeof item === 'string' && item.charAt(0) === BANG$1)
  535. .map(item => item.slice(1))
  536. .map(item => picomatch(item, opts));
  537. const patterns = mtchers
  538. .filter(item => typeof item !== 'string' || (typeof item === 'string' && item.charAt(0) !== BANG$1))
  539. .map(matcher => createPattern(matcher, opts));
  540. if (testString == null) {
  541. return (testString, ri = false) => {
  542. const returnIndex = typeof ri === 'boolean' ? ri : false;
  543. return matchPatterns(patterns, negatedGlobs, testString, returnIndex);
  544. }
  545. }
  546. return matchPatterns(patterns, negatedGlobs, testString, returnIndex);
  547. };
  548. anymatch$1.default = anymatch$1;
  549. anymatch$2.exports = anymatch$1;
  550. /*!
  551. * is-extglob <https://github.com/jonschlinkert/is-extglob>
  552. *
  553. * Copyright (c) 2014-2016, Jon Schlinkert.
  554. * Licensed under the MIT License.
  555. */
  556. var isExtglob$1 = function isExtglob(str) {
  557. if (typeof str !== 'string' || str === '') {
  558. return false;
  559. }
  560. var match;
  561. while ((match = /(\\).|([@?!+*]\(.*\))/g.exec(str))) {
  562. if (match[2]) return true;
  563. str = str.slice(match.index + match[0].length);
  564. }
  565. return false;
  566. };
  567. /*!
  568. * is-glob <https://github.com/jonschlinkert/is-glob>
  569. *
  570. * Copyright (c) 2014-2017, Jon Schlinkert.
  571. * Released under the MIT License.
  572. */
  573. var isExtglob = isExtglob$1;
  574. var chars = { '{': '}', '(': ')', '[': ']'};
  575. var strictCheck = function(str) {
  576. if (str[0] === '!') {
  577. return true;
  578. }
  579. var index = 0;
  580. var pipeIndex = -2;
  581. var closeSquareIndex = -2;
  582. var closeCurlyIndex = -2;
  583. var closeParenIndex = -2;
  584. var backSlashIndex = -2;
  585. while (index < str.length) {
  586. if (str[index] === '*') {
  587. return true;
  588. }
  589. if (str[index + 1] === '?' && /[\].+)]/.test(str[index])) {
  590. return true;
  591. }
  592. if (closeSquareIndex !== -1 && str[index] === '[' && str[index + 1] !== ']') {
  593. if (closeSquareIndex < index) {
  594. closeSquareIndex = str.indexOf(']', index);
  595. }
  596. if (closeSquareIndex > index) {
  597. if (backSlashIndex === -1 || backSlashIndex > closeSquareIndex) {
  598. return true;
  599. }
  600. backSlashIndex = str.indexOf('\\', index);
  601. if (backSlashIndex === -1 || backSlashIndex > closeSquareIndex) {
  602. return true;
  603. }
  604. }
  605. }
  606. if (closeCurlyIndex !== -1 && str[index] === '{' && str[index + 1] !== '}') {
  607. closeCurlyIndex = str.indexOf('}', index);
  608. if (closeCurlyIndex > index) {
  609. backSlashIndex = str.indexOf('\\', index);
  610. if (backSlashIndex === -1 || backSlashIndex > closeCurlyIndex) {
  611. return true;
  612. }
  613. }
  614. }
  615. if (closeParenIndex !== -1 && str[index] === '(' && str[index + 1] === '?' && /[:!=]/.test(str[index + 2]) && str[index + 3] !== ')') {
  616. closeParenIndex = str.indexOf(')', index);
  617. if (closeParenIndex > index) {
  618. backSlashIndex = str.indexOf('\\', index);
  619. if (backSlashIndex === -1 || backSlashIndex > closeParenIndex) {
  620. return true;
  621. }
  622. }
  623. }
  624. if (pipeIndex !== -1 && str[index] === '(' && str[index + 1] !== '|') {
  625. if (pipeIndex < index) {
  626. pipeIndex = str.indexOf('|', index);
  627. }
  628. if (pipeIndex !== -1 && str[pipeIndex + 1] !== ')') {
  629. closeParenIndex = str.indexOf(')', pipeIndex);
  630. if (closeParenIndex > pipeIndex) {
  631. backSlashIndex = str.indexOf('\\', pipeIndex);
  632. if (backSlashIndex === -1 || backSlashIndex > closeParenIndex) {
  633. return true;
  634. }
  635. }
  636. }
  637. }
  638. if (str[index] === '\\') {
  639. var open = str[index + 1];
  640. index += 2;
  641. var close = chars[open];
  642. if (close) {
  643. var n = str.indexOf(close, index);
  644. if (n !== -1) {
  645. index = n + 1;
  646. }
  647. }
  648. if (str[index] === '!') {
  649. return true;
  650. }
  651. } else {
  652. index++;
  653. }
  654. }
  655. return false;
  656. };
  657. var relaxedCheck = function(str) {
  658. if (str[0] === '!') {
  659. return true;
  660. }
  661. var index = 0;
  662. while (index < str.length) {
  663. if (/[*?{}()[\]]/.test(str[index])) {
  664. return true;
  665. }
  666. if (str[index] === '\\') {
  667. var open = str[index + 1];
  668. index += 2;
  669. var close = chars[open];
  670. if (close) {
  671. var n = str.indexOf(close, index);
  672. if (n !== -1) {
  673. index = n + 1;
  674. }
  675. }
  676. if (str[index] === '!') {
  677. return true;
  678. }
  679. } else {
  680. index++;
  681. }
  682. }
  683. return false;
  684. };
  685. var isGlob$2 = function isGlob(str, options) {
  686. if (typeof str !== 'string' || str === '') {
  687. return false;
  688. }
  689. if (isExtglob(str)) {
  690. return true;
  691. }
  692. var check = strictCheck;
  693. // optionally relax check
  694. if (options && options.strict === false) {
  695. check = relaxedCheck;
  696. }
  697. return check(str);
  698. };
  699. var isGlob$1 = isGlob$2;
  700. var pathPosixDirname = require$$0$2.posix.dirname;
  701. var isWin32 = require$$2$1.platform() === 'win32';
  702. var slash = '/';
  703. var backslash = /\\/g;
  704. var enclosure = /[\{\[].*[\}\]]$/;
  705. var globby = /(^|[^\\])([\{\[]|\([^\)]+$)/;
  706. var escaped = /\\([\!\*\?\|\[\]\(\)\{\}])/g;
  707. /**
  708. * @param {string} str
  709. * @param {Object} opts
  710. * @param {boolean} [opts.flipBackslashes=true]
  711. * @returns {string}
  712. */
  713. var globParent$1 = function globParent(str, opts) {
  714. var options = Object.assign({ flipBackslashes: true }, opts);
  715. // flip windows path separators
  716. if (options.flipBackslashes && isWin32 && str.indexOf(slash) < 0) {
  717. str = str.replace(backslash, slash);
  718. }
  719. // special case for strings ending in enclosure containing path separator
  720. if (enclosure.test(str)) {
  721. str += slash;
  722. }
  723. // preserves full path in case of trailing path separator
  724. str += 'a';
  725. // remove path parts that are globby
  726. do {
  727. str = pathPosixDirname(str);
  728. } while (isGlob$1(str) || globby.test(str));
  729. // remove escape chars and return result
  730. return str.replace(escaped, '$1');
  731. };
  732. var utils$3 = {};
  733. (function (exports) {
  734. exports.isInteger = num => {
  735. if (typeof num === 'number') {
  736. return Number.isInteger(num);
  737. }
  738. if (typeof num === 'string' && num.trim() !== '') {
  739. return Number.isInteger(Number(num));
  740. }
  741. return false;
  742. };
  743. /**
  744. * Find a node of the given type
  745. */
  746. exports.find = (node, type) => node.nodes.find(node => node.type === type);
  747. /**
  748. * Find a node of the given type
  749. */
  750. exports.exceedsLimit = (min, max, step = 1, limit) => {
  751. if (limit === false) return false;
  752. if (!exports.isInteger(min) || !exports.isInteger(max)) return false;
  753. return ((Number(max) - Number(min)) / Number(step)) >= limit;
  754. };
  755. /**
  756. * Escape the given node with '\\' before node.value
  757. */
  758. exports.escapeNode = (block, n = 0, type) => {
  759. let node = block.nodes[n];
  760. if (!node) return;
  761. if ((type && node.type === type) || node.type === 'open' || node.type === 'close') {
  762. if (node.escaped !== true) {
  763. node.value = '\\' + node.value;
  764. node.escaped = true;
  765. }
  766. }
  767. };
  768. /**
  769. * Returns true if the given brace node should be enclosed in literal braces
  770. */
  771. exports.encloseBrace = node => {
  772. if (node.type !== 'brace') return false;
  773. if ((node.commas >> 0 + node.ranges >> 0) === 0) {
  774. node.invalid = true;
  775. return true;
  776. }
  777. return false;
  778. };
  779. /**
  780. * Returns true if a brace node is invalid.
  781. */
  782. exports.isInvalidBrace = block => {
  783. if (block.type !== 'brace') return false;
  784. if (block.invalid === true || block.dollar) return true;
  785. if ((block.commas >> 0 + block.ranges >> 0) === 0) {
  786. block.invalid = true;
  787. return true;
  788. }
  789. if (block.open !== true || block.close !== true) {
  790. block.invalid = true;
  791. return true;
  792. }
  793. return false;
  794. };
  795. /**
  796. * Returns true if a node is an open or close node
  797. */
  798. exports.isOpenOrClose = node => {
  799. if (node.type === 'open' || node.type === 'close') {
  800. return true;
  801. }
  802. return node.open === true || node.close === true;
  803. };
  804. /**
  805. * Reduce an array of text nodes.
  806. */
  807. exports.reduce = nodes => nodes.reduce((acc, node) => {
  808. if (node.type === 'text') acc.push(node.value);
  809. if (node.type === 'range') node.type = 'text';
  810. return acc;
  811. }, []);
  812. /**
  813. * Flatten an array
  814. */
  815. exports.flatten = (...args) => {
  816. const result = [];
  817. const flat = arr => {
  818. for (let i = 0; i < arr.length; i++) {
  819. let ele = arr[i];
  820. Array.isArray(ele) ? flat(ele) : ele !== void 0 && result.push(ele);
  821. }
  822. return result;
  823. };
  824. flat(args);
  825. return result;
  826. };
  827. } (utils$3));
  828. const utils$2 = utils$3;
  829. var stringify$4 = (ast, options = {}) => {
  830. let stringify = (node, parent = {}) => {
  831. let invalidBlock = options.escapeInvalid && utils$2.isInvalidBrace(parent);
  832. let invalidNode = node.invalid === true && options.escapeInvalid === true;
  833. let output = '';
  834. if (node.value) {
  835. if ((invalidBlock || invalidNode) && utils$2.isOpenOrClose(node)) {
  836. return '\\' + node.value;
  837. }
  838. return node.value;
  839. }
  840. if (node.value) {
  841. return node.value;
  842. }
  843. if (node.nodes) {
  844. for (let child of node.nodes) {
  845. output += stringify(child);
  846. }
  847. }
  848. return output;
  849. };
  850. return stringify(ast);
  851. };
  852. /*!
  853. * is-number <https://github.com/jonschlinkert/is-number>
  854. *
  855. * Copyright (c) 2014-present, Jon Schlinkert.
  856. * Released under the MIT License.
  857. */
  858. var isNumber$2 = function(num) {
  859. if (typeof num === 'number') {
  860. return num - num === 0;
  861. }
  862. if (typeof num === 'string' && num.trim() !== '') {
  863. return Number.isFinite ? Number.isFinite(+num) : isFinite(+num);
  864. }
  865. return false;
  866. };
  867. /*!
  868. * to-regex-range <https://github.com/micromatch/to-regex-range>
  869. *
  870. * Copyright (c) 2015-present, Jon Schlinkert.
  871. * Released under the MIT License.
  872. */
  873. const isNumber$1 = isNumber$2;
  874. const toRegexRange$1 = (min, max, options) => {
  875. if (isNumber$1(min) === false) {
  876. throw new TypeError('toRegexRange: expected the first argument to be a number');
  877. }
  878. if (max === void 0 || min === max) {
  879. return String(min);
  880. }
  881. if (isNumber$1(max) === false) {
  882. throw new TypeError('toRegexRange: expected the second argument to be a number.');
  883. }
  884. let opts = { relaxZeros: true, ...options };
  885. if (typeof opts.strictZeros === 'boolean') {
  886. opts.relaxZeros = opts.strictZeros === false;
  887. }
  888. let relax = String(opts.relaxZeros);
  889. let shorthand = String(opts.shorthand);
  890. let capture = String(opts.capture);
  891. let wrap = String(opts.wrap);
  892. let cacheKey = min + ':' + max + '=' + relax + shorthand + capture + wrap;
  893. if (toRegexRange$1.cache.hasOwnProperty(cacheKey)) {
  894. return toRegexRange$1.cache[cacheKey].result;
  895. }
  896. let a = Math.min(min, max);
  897. let b = Math.max(min, max);
  898. if (Math.abs(a - b) === 1) {
  899. let result = min + '|' + max;
  900. if (opts.capture) {
  901. return `(${result})`;
  902. }
  903. if (opts.wrap === false) {
  904. return result;
  905. }
  906. return `(?:${result})`;
  907. }
  908. let isPadded = hasPadding(min) || hasPadding(max);
  909. let state = { min, max, a, b };
  910. let positives = [];
  911. let negatives = [];
  912. if (isPadded) {
  913. state.isPadded = isPadded;
  914. state.maxLen = String(state.max).length;
  915. }
  916. if (a < 0) {
  917. let newMin = b < 0 ? Math.abs(b) : 1;
  918. negatives = splitToPatterns(newMin, Math.abs(a), state, opts);
  919. a = state.a = 0;
  920. }
  921. if (b >= 0) {
  922. positives = splitToPatterns(a, b, state, opts);
  923. }
  924. state.negatives = negatives;
  925. state.positives = positives;
  926. state.result = collatePatterns(negatives, positives);
  927. if (opts.capture === true) {
  928. state.result = `(${state.result})`;
  929. } else if (opts.wrap !== false && (positives.length + negatives.length) > 1) {
  930. state.result = `(?:${state.result})`;
  931. }
  932. toRegexRange$1.cache[cacheKey] = state;
  933. return state.result;
  934. };
  935. function collatePatterns(neg, pos, options) {
  936. let onlyNegative = filterPatterns(neg, pos, '-', false) || [];
  937. let onlyPositive = filterPatterns(pos, neg, '', false) || [];
  938. let intersected = filterPatterns(neg, pos, '-?', true) || [];
  939. let subpatterns = onlyNegative.concat(intersected).concat(onlyPositive);
  940. return subpatterns.join('|');
  941. }
  942. function splitToRanges(min, max) {
  943. let nines = 1;
  944. let zeros = 1;
  945. let stop = countNines(min, nines);
  946. let stops = new Set([max]);
  947. while (min <= stop && stop <= max) {
  948. stops.add(stop);
  949. nines += 1;
  950. stop = countNines(min, nines);
  951. }
  952. stop = countZeros(max + 1, zeros) - 1;
  953. while (min < stop && stop <= max) {
  954. stops.add(stop);
  955. zeros += 1;
  956. stop = countZeros(max + 1, zeros) - 1;
  957. }
  958. stops = [...stops];
  959. stops.sort(compare);
  960. return stops;
  961. }
  962. /**
  963. * Convert a range to a regex pattern
  964. * @param {Number} `start`
  965. * @param {Number} `stop`
  966. * @return {String}
  967. */
  968. function rangeToPattern(start, stop, options) {
  969. if (start === stop) {
  970. return { pattern: start, count: [], digits: 0 };
  971. }
  972. let zipped = zip(start, stop);
  973. let digits = zipped.length;
  974. let pattern = '';
  975. let count = 0;
  976. for (let i = 0; i < digits; i++) {
  977. let [startDigit, stopDigit] = zipped[i];
  978. if (startDigit === stopDigit) {
  979. pattern += startDigit;
  980. } else if (startDigit !== '0' || stopDigit !== '9') {
  981. pattern += toCharacterClass(startDigit, stopDigit);
  982. } else {
  983. count++;
  984. }
  985. }
  986. if (count) {
  987. pattern += options.shorthand === true ? '\\d' : '[0-9]';
  988. }
  989. return { pattern, count: [count], digits };
  990. }
  991. function splitToPatterns(min, max, tok, options) {
  992. let ranges = splitToRanges(min, max);
  993. let tokens = [];
  994. let start = min;
  995. let prev;
  996. for (let i = 0; i < ranges.length; i++) {
  997. let max = ranges[i];
  998. let obj = rangeToPattern(String(start), String(max), options);
  999. let zeros = '';
  1000. if (!tok.isPadded && prev && prev.pattern === obj.pattern) {
  1001. if (prev.count.length > 1) {
  1002. prev.count.pop();
  1003. }
  1004. prev.count.push(obj.count[0]);
  1005. prev.string = prev.pattern + toQuantifier(prev.count);
  1006. start = max + 1;
  1007. continue;
  1008. }
  1009. if (tok.isPadded) {
  1010. zeros = padZeros(max, tok, options);
  1011. }
  1012. obj.string = zeros + obj.pattern + toQuantifier(obj.count);
  1013. tokens.push(obj);
  1014. start = max + 1;
  1015. prev = obj;
  1016. }
  1017. return tokens;
  1018. }
  1019. function filterPatterns(arr, comparison, prefix, intersection, options) {
  1020. let result = [];
  1021. for (let ele of arr) {
  1022. let { string } = ele;
  1023. // only push if _both_ are negative...
  1024. if (!intersection && !contains(comparison, 'string', string)) {
  1025. result.push(prefix + string);
  1026. }
  1027. // or _both_ are positive
  1028. if (intersection && contains(comparison, 'string', string)) {
  1029. result.push(prefix + string);
  1030. }
  1031. }
  1032. return result;
  1033. }
  1034. /**
  1035. * Zip strings
  1036. */
  1037. function zip(a, b) {
  1038. let arr = [];
  1039. for (let i = 0; i < a.length; i++) arr.push([a[i], b[i]]);
  1040. return arr;
  1041. }
  1042. function compare(a, b) {
  1043. return a > b ? 1 : b > a ? -1 : 0;
  1044. }
  1045. function contains(arr, key, val) {
  1046. return arr.some(ele => ele[key] === val);
  1047. }
  1048. function countNines(min, len) {
  1049. return Number(String(min).slice(0, -len) + '9'.repeat(len));
  1050. }
  1051. function countZeros(integer, zeros) {
  1052. return integer - (integer % Math.pow(10, zeros));
  1053. }
  1054. function toQuantifier(digits) {
  1055. let [start = 0, stop = ''] = digits;
  1056. if (stop || start > 1) {
  1057. return `{${start + (stop ? ',' + stop : '')}}`;
  1058. }
  1059. return '';
  1060. }
  1061. function toCharacterClass(a, b, options) {
  1062. return `[${a}${(b - a === 1) ? '' : '-'}${b}]`;
  1063. }
  1064. function hasPadding(str) {
  1065. return /^-?(0+)\d/.test(str);
  1066. }
  1067. function padZeros(value, tok, options) {
  1068. if (!tok.isPadded) {
  1069. return value;
  1070. }
  1071. let diff = Math.abs(tok.maxLen - String(value).length);
  1072. let relax = options.relaxZeros !== false;
  1073. switch (diff) {
  1074. case 0:
  1075. return '';
  1076. case 1:
  1077. return relax ? '0?' : '0';
  1078. case 2:
  1079. return relax ? '0{0,2}' : '00';
  1080. default: {
  1081. return relax ? `0{0,${diff}}` : `0{${diff}}`;
  1082. }
  1083. }
  1084. }
  1085. /**
  1086. * Cache
  1087. */
  1088. toRegexRange$1.cache = {};
  1089. toRegexRange$1.clearCache = () => (toRegexRange$1.cache = {});
  1090. /**
  1091. * Expose `toRegexRange`
  1092. */
  1093. var toRegexRange_1 = toRegexRange$1;
  1094. /*!
  1095. * fill-range <https://github.com/jonschlinkert/fill-range>
  1096. *
  1097. * Copyright (c) 2014-present, Jon Schlinkert.
  1098. * Licensed under the MIT License.
  1099. */
  1100. const util = require$$2;
  1101. const toRegexRange = toRegexRange_1;
  1102. const isObject = val => val !== null && typeof val === 'object' && !Array.isArray(val);
  1103. const transform = toNumber => {
  1104. return value => toNumber === true ? Number(value) : String(value);
  1105. };
  1106. const isValidValue = value => {
  1107. return typeof value === 'number' || (typeof value === 'string' && value !== '');
  1108. };
  1109. const isNumber = num => Number.isInteger(+num);
  1110. const zeros = input => {
  1111. let value = `${input}`;
  1112. let index = -1;
  1113. if (value[0] === '-') value = value.slice(1);
  1114. if (value === '0') return false;
  1115. while (value[++index] === '0');
  1116. return index > 0;
  1117. };
  1118. const stringify$3 = (start, end, options) => {
  1119. if (typeof start === 'string' || typeof end === 'string') {
  1120. return true;
  1121. }
  1122. return options.stringify === true;
  1123. };
  1124. const pad = (input, maxLength, toNumber) => {
  1125. if (maxLength > 0) {
  1126. let dash = input[0] === '-' ? '-' : '';
  1127. if (dash) input = input.slice(1);
  1128. input = (dash + input.padStart(dash ? maxLength - 1 : maxLength, '0'));
  1129. }
  1130. if (toNumber === false) {
  1131. return String(input);
  1132. }
  1133. return input;
  1134. };
  1135. const toMaxLen = (input, maxLength) => {
  1136. let negative = input[0] === '-' ? '-' : '';
  1137. if (negative) {
  1138. input = input.slice(1);
  1139. maxLength--;
  1140. }
  1141. while (input.length < maxLength) input = '0' + input;
  1142. return negative ? ('-' + input) : input;
  1143. };
  1144. const toSequence = (parts, options) => {
  1145. parts.negatives.sort((a, b) => a < b ? -1 : a > b ? 1 : 0);
  1146. parts.positives.sort((a, b) => a < b ? -1 : a > b ? 1 : 0);
  1147. let prefix = options.capture ? '' : '?:';
  1148. let positives = '';
  1149. let negatives = '';
  1150. let result;
  1151. if (parts.positives.length) {
  1152. positives = parts.positives.join('|');
  1153. }
  1154. if (parts.negatives.length) {
  1155. negatives = `-(${prefix}${parts.negatives.join('|')})`;
  1156. }
  1157. if (positives && negatives) {
  1158. result = `${positives}|${negatives}`;
  1159. } else {
  1160. result = positives || negatives;
  1161. }
  1162. if (options.wrap) {
  1163. return `(${prefix}${result})`;
  1164. }
  1165. return result;
  1166. };
  1167. const toRange = (a, b, isNumbers, options) => {
  1168. if (isNumbers) {
  1169. return toRegexRange(a, b, { wrap: false, ...options });
  1170. }
  1171. let start = String.fromCharCode(a);
  1172. if (a === b) return start;
  1173. let stop = String.fromCharCode(b);
  1174. return `[${start}-${stop}]`;
  1175. };
  1176. const toRegex = (start, end, options) => {
  1177. if (Array.isArray(start)) {
  1178. let wrap = options.wrap === true;
  1179. let prefix = options.capture ? '' : '?:';
  1180. return wrap ? `(${prefix}${start.join('|')})` : start.join('|');
  1181. }
  1182. return toRegexRange(start, end, options);
  1183. };
  1184. const rangeError = (...args) => {
  1185. return new RangeError('Invalid range arguments: ' + util.inspect(...args));
  1186. };
  1187. const invalidRange = (start, end, options) => {
  1188. if (options.strictRanges === true) throw rangeError([start, end]);
  1189. return [];
  1190. };
  1191. const invalidStep = (step, options) => {
  1192. if (options.strictRanges === true) {
  1193. throw new TypeError(`Expected step "${step}" to be a number`);
  1194. }
  1195. return [];
  1196. };
  1197. const fillNumbers = (start, end, step = 1, options = {}) => {
  1198. let a = Number(start);
  1199. let b = Number(end);
  1200. if (!Number.isInteger(a) || !Number.isInteger(b)) {
  1201. if (options.strictRanges === true) throw rangeError([start, end]);
  1202. return [];
  1203. }
  1204. // fix negative zero
  1205. if (a === 0) a = 0;
  1206. if (b === 0) b = 0;
  1207. let descending = a > b;
  1208. let startString = String(start);
  1209. let endString = String(end);
  1210. let stepString = String(step);
  1211. step = Math.max(Math.abs(step), 1);
  1212. let padded = zeros(startString) || zeros(endString) || zeros(stepString);
  1213. let maxLen = padded ? Math.max(startString.length, endString.length, stepString.length) : 0;
  1214. let toNumber = padded === false && stringify$3(start, end, options) === false;
  1215. let format = options.transform || transform(toNumber);
  1216. if (options.toRegex && step === 1) {
  1217. return toRange(toMaxLen(start, maxLen), toMaxLen(end, maxLen), true, options);
  1218. }
  1219. let parts = { negatives: [], positives: [] };
  1220. let push = num => parts[num < 0 ? 'negatives' : 'positives'].push(Math.abs(num));
  1221. let range = [];
  1222. let index = 0;
  1223. while (descending ? a >= b : a <= b) {
  1224. if (options.toRegex === true && step > 1) {
  1225. push(a);
  1226. } else {
  1227. range.push(pad(format(a, index), maxLen, toNumber));
  1228. }
  1229. a = descending ? a - step : a + step;
  1230. index++;
  1231. }
  1232. if (options.toRegex === true) {
  1233. return step > 1
  1234. ? toSequence(parts, options)
  1235. : toRegex(range, null, { wrap: false, ...options });
  1236. }
  1237. return range;
  1238. };
  1239. const fillLetters = (start, end, step = 1, options = {}) => {
  1240. if ((!isNumber(start) && start.length > 1) || (!isNumber(end) && end.length > 1)) {
  1241. return invalidRange(start, end, options);
  1242. }
  1243. let format = options.transform || (val => String.fromCharCode(val));
  1244. let a = `${start}`.charCodeAt(0);
  1245. let b = `${end}`.charCodeAt(0);
  1246. let descending = a > b;
  1247. let min = Math.min(a, b);
  1248. let max = Math.max(a, b);
  1249. if (options.toRegex && step === 1) {
  1250. return toRange(min, max, false, options);
  1251. }
  1252. let range = [];
  1253. let index = 0;
  1254. while (descending ? a >= b : a <= b) {
  1255. range.push(format(a, index));
  1256. a = descending ? a - step : a + step;
  1257. index++;
  1258. }
  1259. if (options.toRegex === true) {
  1260. return toRegex(range, null, { wrap: false, options });
  1261. }
  1262. return range;
  1263. };
  1264. const fill$2 = (start, end, step, options = {}) => {
  1265. if (end == null && isValidValue(start)) {
  1266. return [start];
  1267. }
  1268. if (!isValidValue(start) || !isValidValue(end)) {
  1269. return invalidRange(start, end, options);
  1270. }
  1271. if (typeof step === 'function') {
  1272. return fill$2(start, end, 1, { transform: step });
  1273. }
  1274. if (isObject(step)) {
  1275. return fill$2(start, end, 0, step);
  1276. }
  1277. let opts = { ...options };
  1278. if (opts.capture === true) opts.wrap = true;
  1279. step = step || opts.step || 1;
  1280. if (!isNumber(step)) {
  1281. if (step != null && !isObject(step)) return invalidStep(step, opts);
  1282. return fill$2(start, end, 1, step);
  1283. }
  1284. if (isNumber(start) && isNumber(end)) {
  1285. return fillNumbers(start, end, step, opts);
  1286. }
  1287. return fillLetters(start, end, Math.max(Math.abs(step), 1), opts);
  1288. };
  1289. var fillRange = fill$2;
  1290. const fill$1 = fillRange;
  1291. const utils$1 = utils$3;
  1292. const compile$1 = (ast, options = {}) => {
  1293. let walk = (node, parent = {}) => {
  1294. let invalidBlock = utils$1.isInvalidBrace(parent);
  1295. let invalidNode = node.invalid === true && options.escapeInvalid === true;
  1296. let invalid = invalidBlock === true || invalidNode === true;
  1297. let prefix = options.escapeInvalid === true ? '\\' : '';
  1298. let output = '';
  1299. if (node.isOpen === true) {
  1300. return prefix + node.value;
  1301. }
  1302. if (node.isClose === true) {
  1303. return prefix + node.value;
  1304. }
  1305. if (node.type === 'open') {
  1306. return invalid ? (prefix + node.value) : '(';
  1307. }
  1308. if (node.type === 'close') {
  1309. return invalid ? (prefix + node.value) : ')';
  1310. }
  1311. if (node.type === 'comma') {
  1312. return node.prev.type === 'comma' ? '' : (invalid ? node.value : '|');
  1313. }
  1314. if (node.value) {
  1315. return node.value;
  1316. }
  1317. if (node.nodes && node.ranges > 0) {
  1318. let args = utils$1.reduce(node.nodes);
  1319. let range = fill$1(...args, { ...options, wrap: false, toRegex: true });
  1320. if (range.length !== 0) {
  1321. return args.length > 1 && range.length > 1 ? `(${range})` : range;
  1322. }
  1323. }
  1324. if (node.nodes) {
  1325. for (let child of node.nodes) {
  1326. output += walk(child, node);
  1327. }
  1328. }
  1329. return output;
  1330. };
  1331. return walk(ast);
  1332. };
  1333. var compile_1 = compile$1;
  1334. const fill = fillRange;
  1335. const stringify$2 = stringify$4;
  1336. const utils = utils$3;
  1337. const append = (queue = '', stash = '', enclose = false) => {
  1338. let result = [];
  1339. queue = [].concat(queue);
  1340. stash = [].concat(stash);
  1341. if (!stash.length) return queue;
  1342. if (!queue.length) {
  1343. return enclose ? utils.flatten(stash).map(ele => `{${ele}}`) : stash;
  1344. }
  1345. for (let item of queue) {
  1346. if (Array.isArray(item)) {
  1347. for (let value of item) {
  1348. result.push(append(value, stash, enclose));
  1349. }
  1350. } else {
  1351. for (let ele of stash) {
  1352. if (enclose === true && typeof ele === 'string') ele = `{${ele}}`;
  1353. result.push(Array.isArray(ele) ? append(item, ele, enclose) : (item + ele));
  1354. }
  1355. }
  1356. }
  1357. return utils.flatten(result);
  1358. };
  1359. const expand$1 = (ast, options = {}) => {
  1360. let rangeLimit = options.rangeLimit === void 0 ? 1000 : options.rangeLimit;
  1361. let walk = (node, parent = {}) => {
  1362. node.queue = [];
  1363. let p = parent;
  1364. let q = parent.queue;
  1365. while (p.type !== 'brace' && p.type !== 'root' && p.parent) {
  1366. p = p.parent;
  1367. q = p.queue;
  1368. }
  1369. if (node.invalid || node.dollar) {
  1370. q.push(append(q.pop(), stringify$2(node, options)));
  1371. return;
  1372. }
  1373. if (node.type === 'brace' && node.invalid !== true && node.nodes.length === 2) {
  1374. q.push(append(q.pop(), ['{}']));
  1375. return;
  1376. }
  1377. if (node.nodes && node.ranges > 0) {
  1378. let args = utils.reduce(node.nodes);
  1379. if (utils.exceedsLimit(...args, options.step, rangeLimit)) {
  1380. throw new RangeError('expanded array length exceeds range limit. Use options.rangeLimit to increase or disable the limit.');
  1381. }
  1382. let range = fill(...args, options);
  1383. if (range.length === 0) {
  1384. range = stringify$2(node, options);
  1385. }
  1386. q.push(append(q.pop(), range));
  1387. node.nodes = [];
  1388. return;
  1389. }
  1390. let enclose = utils.encloseBrace(node);
  1391. let queue = node.queue;
  1392. let block = node;
  1393. while (block.type !== 'brace' && block.type !== 'root' && block.parent) {
  1394. block = block.parent;
  1395. queue = block.queue;
  1396. }
  1397. for (let i = 0; i < node.nodes.length; i++) {
  1398. let child = node.nodes[i];
  1399. if (child.type === 'comma' && node.type === 'brace') {
  1400. if (i === 1) queue.push('');
  1401. queue.push('');
  1402. continue;
  1403. }
  1404. if (child.type === 'close') {
  1405. q.push(append(q.pop(), queue, enclose));
  1406. continue;
  1407. }
  1408. if (child.value && child.type !== 'open') {
  1409. queue.push(append(queue.pop(), child.value));
  1410. continue;
  1411. }
  1412. if (child.nodes) {
  1413. walk(child, node);
  1414. }
  1415. }
  1416. return queue;
  1417. };
  1418. return utils.flatten(walk(ast));
  1419. };
  1420. var expand_1 = expand$1;
  1421. var constants$1 = {
  1422. MAX_LENGTH: 1024 * 64,
  1423. // Digits
  1424. CHAR_0: '0', /* 0 */
  1425. CHAR_9: '9', /* 9 */
  1426. // Alphabet chars.
  1427. CHAR_UPPERCASE_A: 'A', /* A */
  1428. CHAR_LOWERCASE_A: 'a', /* a */
  1429. CHAR_UPPERCASE_Z: 'Z', /* Z */
  1430. CHAR_LOWERCASE_Z: 'z', /* z */
  1431. CHAR_LEFT_PARENTHESES: '(', /* ( */
  1432. CHAR_RIGHT_PARENTHESES: ')', /* ) */
  1433. CHAR_ASTERISK: '*', /* * */
  1434. // Non-alphabetic chars.
  1435. CHAR_AMPERSAND: '&', /* & */
  1436. CHAR_AT: '@', /* @ */
  1437. CHAR_BACKSLASH: '\\', /* \ */
  1438. CHAR_BACKTICK: '`', /* ` */
  1439. CHAR_CARRIAGE_RETURN: '\r', /* \r */
  1440. CHAR_CIRCUMFLEX_ACCENT: '^', /* ^ */
  1441. CHAR_COLON: ':', /* : */
  1442. CHAR_COMMA: ',', /* , */
  1443. CHAR_DOLLAR: '$', /* . */
  1444. CHAR_DOT: '.', /* . */
  1445. CHAR_DOUBLE_QUOTE: '"', /* " */
  1446. CHAR_EQUAL: '=', /* = */
  1447. CHAR_EXCLAMATION_MARK: '!', /* ! */
  1448. CHAR_FORM_FEED: '\f', /* \f */
  1449. CHAR_FORWARD_SLASH: '/', /* / */
  1450. CHAR_HASH: '#', /* # */
  1451. CHAR_HYPHEN_MINUS: '-', /* - */
  1452. CHAR_LEFT_ANGLE_BRACKET: '<', /* < */
  1453. CHAR_LEFT_CURLY_BRACE: '{', /* { */
  1454. CHAR_LEFT_SQUARE_BRACKET: '[', /* [ */
  1455. CHAR_LINE_FEED: '\n', /* \n */
  1456. CHAR_NO_BREAK_SPACE: '\u00A0', /* \u00A0 */
  1457. CHAR_PERCENT: '%', /* % */
  1458. CHAR_PLUS: '+', /* + */
  1459. CHAR_QUESTION_MARK: '?', /* ? */
  1460. CHAR_RIGHT_ANGLE_BRACKET: '>', /* > */
  1461. CHAR_RIGHT_CURLY_BRACE: '}', /* } */
  1462. CHAR_RIGHT_SQUARE_BRACKET: ']', /* ] */
  1463. CHAR_SEMICOLON: ';', /* ; */
  1464. CHAR_SINGLE_QUOTE: '\'', /* ' */
  1465. CHAR_SPACE: ' ', /* */
  1466. CHAR_TAB: '\t', /* \t */
  1467. CHAR_UNDERSCORE: '_', /* _ */
  1468. CHAR_VERTICAL_LINE: '|', /* | */
  1469. CHAR_ZERO_WIDTH_NOBREAK_SPACE: '\uFEFF' /* \uFEFF */
  1470. };
  1471. const stringify$1 = stringify$4;
  1472. /**
  1473. * Constants
  1474. */
  1475. const {
  1476. MAX_LENGTH,
  1477. CHAR_BACKSLASH, /* \ */
  1478. CHAR_BACKTICK, /* ` */
  1479. CHAR_COMMA, /* , */
  1480. CHAR_DOT, /* . */
  1481. CHAR_LEFT_PARENTHESES, /* ( */
  1482. CHAR_RIGHT_PARENTHESES, /* ) */
  1483. CHAR_LEFT_CURLY_BRACE, /* { */
  1484. CHAR_RIGHT_CURLY_BRACE, /* } */
  1485. CHAR_LEFT_SQUARE_BRACKET, /* [ */
  1486. CHAR_RIGHT_SQUARE_BRACKET, /* ] */
  1487. CHAR_DOUBLE_QUOTE, /* " */
  1488. CHAR_SINGLE_QUOTE, /* ' */
  1489. CHAR_NO_BREAK_SPACE,
  1490. CHAR_ZERO_WIDTH_NOBREAK_SPACE
  1491. } = constants$1;
  1492. /**
  1493. * parse
  1494. */
  1495. const parse$1 = (input, options = {}) => {
  1496. if (typeof input !== 'string') {
  1497. throw new TypeError('Expected a string');
  1498. }
  1499. let opts = options || {};
  1500. let max = typeof opts.maxLength === 'number' ? Math.min(MAX_LENGTH, opts.maxLength) : MAX_LENGTH;
  1501. if (input.length > max) {
  1502. throw new SyntaxError(`Input length (${input.length}), exceeds max characters (${max})`);
  1503. }
  1504. let ast = { type: 'root', input, nodes: [] };
  1505. let stack = [ast];
  1506. let block = ast;
  1507. let prev = ast;
  1508. let brackets = 0;
  1509. let length = input.length;
  1510. let index = 0;
  1511. let depth = 0;
  1512. let value;
  1513. /**
  1514. * Helpers
  1515. */
  1516. const advance = () => input[index++];
  1517. const push = node => {
  1518. if (node.type === 'text' && prev.type === 'dot') {
  1519. prev.type = 'text';
  1520. }
  1521. if (prev && prev.type === 'text' && node.type === 'text') {
  1522. prev.value += node.value;
  1523. return;
  1524. }
  1525. block.nodes.push(node);
  1526. node.parent = block;
  1527. node.prev = prev;
  1528. prev = node;
  1529. return node;
  1530. };
  1531. push({ type: 'bos' });
  1532. while (index < length) {
  1533. block = stack[stack.length - 1];
  1534. value = advance();
  1535. /**
  1536. * Invalid chars
  1537. */
  1538. if (value === CHAR_ZERO_WIDTH_NOBREAK_SPACE || value === CHAR_NO_BREAK_SPACE) {
  1539. continue;
  1540. }
  1541. /**
  1542. * Escaped chars
  1543. */
  1544. if (value === CHAR_BACKSLASH) {
  1545. push({ type: 'text', value: (options.keepEscaping ? value : '') + advance() });
  1546. continue;
  1547. }
  1548. /**
  1549. * Right square bracket (literal): ']'
  1550. */
  1551. if (value === CHAR_RIGHT_SQUARE_BRACKET) {
  1552. push({ type: 'text', value: '\\' + value });
  1553. continue;
  1554. }
  1555. /**
  1556. * Left square bracket: '['
  1557. */
  1558. if (value === CHAR_LEFT_SQUARE_BRACKET) {
  1559. brackets++;
  1560. let next;
  1561. while (index < length && (next = advance())) {
  1562. value += next;
  1563. if (next === CHAR_LEFT_SQUARE_BRACKET) {
  1564. brackets++;
  1565. continue;
  1566. }
  1567. if (next === CHAR_BACKSLASH) {
  1568. value += advance();
  1569. continue;
  1570. }
  1571. if (next === CHAR_RIGHT_SQUARE_BRACKET) {
  1572. brackets--;
  1573. if (brackets === 0) {
  1574. break;
  1575. }
  1576. }
  1577. }
  1578. push({ type: 'text', value });
  1579. continue;
  1580. }
  1581. /**
  1582. * Parentheses
  1583. */
  1584. if (value === CHAR_LEFT_PARENTHESES) {
  1585. block = push({ type: 'paren', nodes: [] });
  1586. stack.push(block);
  1587. push({ type: 'text', value });
  1588. continue;
  1589. }
  1590. if (value === CHAR_RIGHT_PARENTHESES) {
  1591. if (block.type !== 'paren') {
  1592. push({ type: 'text', value });
  1593. continue;
  1594. }
  1595. block = stack.pop();
  1596. push({ type: 'text', value });
  1597. block = stack[stack.length - 1];
  1598. continue;
  1599. }
  1600. /**
  1601. * Quotes: '|"|`
  1602. */
  1603. if (value === CHAR_DOUBLE_QUOTE || value === CHAR_SINGLE_QUOTE || value === CHAR_BACKTICK) {
  1604. let open = value;
  1605. let next;
  1606. if (options.keepQuotes !== true) {
  1607. value = '';
  1608. }
  1609. while (index < length && (next = advance())) {
  1610. if (next === CHAR_BACKSLASH) {
  1611. value += next + advance();
  1612. continue;
  1613. }
  1614. if (next === open) {
  1615. if (options.keepQuotes === true) value += next;
  1616. break;
  1617. }
  1618. value += next;
  1619. }
  1620. push({ type: 'text', value });
  1621. continue;
  1622. }
  1623. /**
  1624. * Left curly brace: '{'
  1625. */
  1626. if (value === CHAR_LEFT_CURLY_BRACE) {
  1627. depth++;
  1628. let dollar = prev.value && prev.value.slice(-1) === '$' || block.dollar === true;
  1629. let brace = {
  1630. type: 'brace',
  1631. open: true,
  1632. close: false,
  1633. dollar,
  1634. depth,
  1635. commas: 0,
  1636. ranges: 0,
  1637. nodes: []
  1638. };
  1639. block = push(brace);
  1640. stack.push(block);
  1641. push({ type: 'open', value });
  1642. continue;
  1643. }
  1644. /**
  1645. * Right curly brace: '}'
  1646. */
  1647. if (value === CHAR_RIGHT_CURLY_BRACE) {
  1648. if (block.type !== 'brace') {
  1649. push({ type: 'text', value });
  1650. continue;
  1651. }
  1652. let type = 'close';
  1653. block = stack.pop();
  1654. block.close = true;
  1655. push({ type, value });
  1656. depth--;
  1657. block = stack[stack.length - 1];
  1658. continue;
  1659. }
  1660. /**
  1661. * Comma: ','
  1662. */
  1663. if (value === CHAR_COMMA && depth > 0) {
  1664. if (block.ranges > 0) {
  1665. block.ranges = 0;
  1666. let open = block.nodes.shift();
  1667. block.nodes = [open, { type: 'text', value: stringify$1(block) }];
  1668. }
  1669. push({ type: 'comma', value });
  1670. block.commas++;
  1671. continue;
  1672. }
  1673. /**
  1674. * Dot: '.'
  1675. */
  1676. if (value === CHAR_DOT && depth > 0 && block.commas === 0) {
  1677. let siblings = block.nodes;
  1678. if (depth === 0 || siblings.length === 0) {
  1679. push({ type: 'text', value });
  1680. continue;
  1681. }
  1682. if (prev.type === 'dot') {
  1683. block.range = [];
  1684. prev.value += value;
  1685. prev.type = 'range';
  1686. if (block.nodes.length !== 3 && block.nodes.length !== 5) {
  1687. block.invalid = true;
  1688. block.ranges = 0;
  1689. prev.type = 'text';
  1690. continue;
  1691. }
  1692. block.ranges++;
  1693. block.args = [];
  1694. continue;
  1695. }
  1696. if (prev.type === 'range') {
  1697. siblings.pop();
  1698. let before = siblings[siblings.length - 1];
  1699. before.value += prev.value + value;
  1700. prev = before;
  1701. block.ranges--;
  1702. continue;
  1703. }
  1704. push({ type: 'dot', value });
  1705. continue;
  1706. }
  1707. /**
  1708. * Text
  1709. */
  1710. push({ type: 'text', value });
  1711. }
  1712. // Mark imbalanced braces and brackets as invalid
  1713. do {
  1714. block = stack.pop();
  1715. if (block.type !== 'root') {
  1716. block.nodes.forEach(node => {
  1717. if (!node.nodes) {
  1718. if (node.type === 'open') node.isOpen = true;
  1719. if (node.type === 'close') node.isClose = true;
  1720. if (!node.nodes) node.type = 'text';
  1721. node.invalid = true;
  1722. }
  1723. });
  1724. // get the location of the block on parent.nodes (block's siblings)
  1725. let parent = stack[stack.length - 1];
  1726. let index = parent.nodes.indexOf(block);
  1727. // replace the (invalid) block with it's nodes
  1728. parent.nodes.splice(index, 1, ...block.nodes);
  1729. }
  1730. } while (stack.length > 0);
  1731. push({ type: 'eos' });
  1732. return ast;
  1733. };
  1734. var parse_1 = parse$1;
  1735. const stringify = stringify$4;
  1736. const compile = compile_1;
  1737. const expand = expand_1;
  1738. const parse = parse_1;
  1739. /**
  1740. * Expand the given pattern or create a regex-compatible string.
  1741. *
  1742. * ```js
  1743. * const braces = require('braces');
  1744. * console.log(braces('{a,b,c}', { compile: true })); //=> ['(a|b|c)']
  1745. * console.log(braces('{a,b,c}')); //=> ['a', 'b', 'c']
  1746. * ```
  1747. * @param {String} `str`
  1748. * @param {Object} `options`
  1749. * @return {String}
  1750. * @api public
  1751. */
  1752. const braces$1 = (input, options = {}) => {
  1753. let output = [];
  1754. if (Array.isArray(input)) {
  1755. for (let pattern of input) {
  1756. let result = braces$1.create(pattern, options);
  1757. if (Array.isArray(result)) {
  1758. output.push(...result);
  1759. } else {
  1760. output.push(result);
  1761. }
  1762. }
  1763. } else {
  1764. output = [].concat(braces$1.create(input, options));
  1765. }
  1766. if (options && options.expand === true && options.nodupes === true) {
  1767. output = [...new Set(output)];
  1768. }
  1769. return output;
  1770. };
  1771. /**
  1772. * Parse the given `str` with the given `options`.
  1773. *
  1774. * ```js
  1775. * // braces.parse(pattern, [, options]);
  1776. * const ast = braces.parse('a/{b,c}/d');
  1777. * console.log(ast);
  1778. * ```
  1779. * @param {String} pattern Brace pattern to parse
  1780. * @param {Object} options
  1781. * @return {Object} Returns an AST
  1782. * @api public
  1783. */
  1784. braces$1.parse = (input, options = {}) => parse(input, options);
  1785. /**
  1786. * Creates a braces string from an AST, or an AST node.
  1787. *
  1788. * ```js
  1789. * const braces = require('braces');
  1790. * let ast = braces.parse('foo/{a,b}/bar');
  1791. * console.log(stringify(ast.nodes[2])); //=> '{a,b}'
  1792. * ```
  1793. * @param {String} `input` Brace pattern or AST.
  1794. * @param {Object} `options`
  1795. * @return {Array} Returns an array of expanded values.
  1796. * @api public
  1797. */
  1798. braces$1.stringify = (input, options = {}) => {
  1799. if (typeof input === 'string') {
  1800. return stringify(braces$1.parse(input, options), options);
  1801. }
  1802. return stringify(input, options);
  1803. };
  1804. /**
  1805. * Compiles a brace pattern into a regex-compatible, optimized string.
  1806. * This method is called by the main [braces](#braces) function by default.
  1807. *
  1808. * ```js
  1809. * const braces = require('braces');
  1810. * console.log(braces.compile('a/{b,c}/d'));
  1811. * //=> ['a/(b|c)/d']
  1812. * ```
  1813. * @param {String} `input` Brace pattern or AST.
  1814. * @param {Object} `options`
  1815. * @return {Array} Returns an array of expanded values.
  1816. * @api public
  1817. */
  1818. braces$1.compile = (input, options = {}) => {
  1819. if (typeof input === 'string') {
  1820. input = braces$1.parse(input, options);
  1821. }
  1822. return compile(input, options);
  1823. };
  1824. /**
  1825. * Expands a brace pattern into an array. This method is called by the
  1826. * main [braces](#braces) function when `options.expand` is true. Before
  1827. * using this method it's recommended that you read the [performance notes](#performance))
  1828. * and advantages of using [.compile](#compile) instead.
  1829. *
  1830. * ```js
  1831. * const braces = require('braces');
  1832. * console.log(braces.expand('a/{b,c}/d'));
  1833. * //=> ['a/b/d', 'a/c/d'];
  1834. * ```
  1835. * @param {String} `pattern` Brace pattern
  1836. * @param {Object} `options`
  1837. * @return {Array} Returns an array of expanded values.
  1838. * @api public
  1839. */
  1840. braces$1.expand = (input, options = {}) => {
  1841. if (typeof input === 'string') {
  1842. input = braces$1.parse(input, options);
  1843. }
  1844. let result = expand(input, options);
  1845. // filter out empty strings if specified
  1846. if (options.noempty === true) {
  1847. result = result.filter(Boolean);
  1848. }
  1849. // filter out duplicates if specified
  1850. if (options.nodupes === true) {
  1851. result = [...new Set(result)];
  1852. }
  1853. return result;
  1854. };
  1855. /**
  1856. * Processes a brace pattern and returns either an expanded array
  1857. * (if `options.expand` is true), a highly optimized regex-compatible string.
  1858. * This method is called by the main [braces](#braces) function.
  1859. *
  1860. * ```js
  1861. * const braces = require('braces');
  1862. * console.log(braces.create('user-{200..300}/project-{a,b,c}-{1..10}'))
  1863. * //=> 'user-(20[0-9]|2[1-9][0-9]|300)/project-(a|b|c)-([1-9]|10)'
  1864. * ```
  1865. * @param {String} `pattern` Brace pattern
  1866. * @param {Object} `options`
  1867. * @return {Array} Returns an array of expanded values.
  1868. * @api public
  1869. */
  1870. braces$1.create = (input, options = {}) => {
  1871. if (input === '' || input.length < 3) {
  1872. return [input];
  1873. }
  1874. return options.expand !== true
  1875. ? braces$1.compile(input, options)
  1876. : braces$1.expand(input, options);
  1877. };
  1878. /**
  1879. * Expose "braces"
  1880. */
  1881. var braces_1 = braces$1;
  1882. var binaryExtensions$1 = {exports: {}};
  1883. const require$$0 = [
  1884. "3dm",
  1885. "3ds",
  1886. "3g2",
  1887. "3gp",
  1888. "7z",
  1889. "a",
  1890. "aac",
  1891. "adp",
  1892. "ai",
  1893. "aif",
  1894. "aiff",
  1895. "alz",
  1896. "ape",
  1897. "apk",
  1898. "appimage",
  1899. "ar",
  1900. "arj",
  1901. "asf",
  1902. "au",
  1903. "avi",
  1904. "bak",
  1905. "baml",
  1906. "bh",
  1907. "bin",
  1908. "bk",
  1909. "bmp",
  1910. "btif",
  1911. "bz2",
  1912. "bzip2",
  1913. "cab",
  1914. "caf",
  1915. "cgm",
  1916. "class",
  1917. "cmx",
  1918. "cpio",
  1919. "cr2",
  1920. "cur",
  1921. "dat",
  1922. "dcm",
  1923. "deb",
  1924. "dex",
  1925. "djvu",
  1926. "dll",
  1927. "dmg",
  1928. "dng",
  1929. "doc",
  1930. "docm",
  1931. "docx",
  1932. "dot",
  1933. "dotm",
  1934. "dra",
  1935. "DS_Store",
  1936. "dsk",
  1937. "dts",
  1938. "dtshd",
  1939. "dvb",
  1940. "dwg",
  1941. "dxf",
  1942. "ecelp4800",
  1943. "ecelp7470",
  1944. "ecelp9600",
  1945. "egg",
  1946. "eol",
  1947. "eot",
  1948. "epub",
  1949. "exe",
  1950. "f4v",
  1951. "fbs",
  1952. "fh",
  1953. "fla",
  1954. "flac",
  1955. "flatpak",
  1956. "fli",
  1957. "flv",
  1958. "fpx",
  1959. "fst",
  1960. "fvt",
  1961. "g3",
  1962. "gh",
  1963. "gif",
  1964. "graffle",
  1965. "gz",
  1966. "gzip",
  1967. "h261",
  1968. "h263",
  1969. "h264",
  1970. "icns",
  1971. "ico",
  1972. "ief",
  1973. "img",
  1974. "ipa",
  1975. "iso",
  1976. "jar",
  1977. "jpeg",
  1978. "jpg",
  1979. "jpgv",
  1980. "jpm",
  1981. "jxr",
  1982. "key",
  1983. "ktx",
  1984. "lha",
  1985. "lib",
  1986. "lvp",
  1987. "lz",
  1988. "lzh",
  1989. "lzma",
  1990. "lzo",
  1991. "m3u",
  1992. "m4a",
  1993. "m4v",
  1994. "mar",
  1995. "mdi",
  1996. "mht",
  1997. "mid",
  1998. "midi",
  1999. "mj2",
  2000. "mka",
  2001. "mkv",
  2002. "mmr",
  2003. "mng",
  2004. "mobi",
  2005. "mov",
  2006. "movie",
  2007. "mp3",
  2008. "mp4",
  2009. "mp4a",
  2010. "mpeg",
  2011. "mpg",
  2012. "mpga",
  2013. "mxu",
  2014. "nef",
  2015. "npx",
  2016. "numbers",
  2017. "nupkg",
  2018. "o",
  2019. "odp",
  2020. "ods",
  2021. "odt",
  2022. "oga",
  2023. "ogg",
  2024. "ogv",
  2025. "otf",
  2026. "ott",
  2027. "pages",
  2028. "pbm",
  2029. "pcx",
  2030. "pdb",
  2031. "pdf",
  2032. "pea",
  2033. "pgm",
  2034. "pic",
  2035. "png",
  2036. "pnm",
  2037. "pot",
  2038. "potm",
  2039. "potx",
  2040. "ppa",
  2041. "ppam",
  2042. "ppm",
  2043. "pps",
  2044. "ppsm",
  2045. "ppsx",
  2046. "ppt",
  2047. "pptm",
  2048. "pptx",
  2049. "psd",
  2050. "pya",
  2051. "pyc",
  2052. "pyo",
  2053. "pyv",
  2054. "qt",
  2055. "rar",
  2056. "ras",
  2057. "raw",
  2058. "resources",
  2059. "rgb",
  2060. "rip",
  2061. "rlc",
  2062. "rmf",
  2063. "rmvb",
  2064. "rpm",
  2065. "rtf",
  2066. "rz",
  2067. "s3m",
  2068. "s7z",
  2069. "scpt",
  2070. "sgi",
  2071. "shar",
  2072. "snap",
  2073. "sil",
  2074. "sketch",
  2075. "slk",
  2076. "smv",
  2077. "snk",
  2078. "so",
  2079. "stl",
  2080. "suo",
  2081. "sub",
  2082. "swf",
  2083. "tar",
  2084. "tbz",
  2085. "tbz2",
  2086. "tga",
  2087. "tgz",
  2088. "thmx",
  2089. "tif",
  2090. "tiff",
  2091. "tlz",
  2092. "ttc",
  2093. "ttf",
  2094. "txz",
  2095. "udf",
  2096. "uvh",
  2097. "uvi",
  2098. "uvm",
  2099. "uvp",
  2100. "uvs",
  2101. "uvu",
  2102. "viv",
  2103. "vob",
  2104. "war",
  2105. "wav",
  2106. "wax",
  2107. "wbmp",
  2108. "wdp",
  2109. "weba",
  2110. "webm",
  2111. "webp",
  2112. "whl",
  2113. "wim",
  2114. "wm",
  2115. "wma",
  2116. "wmv",
  2117. "wmx",
  2118. "woff",
  2119. "woff2",
  2120. "wrm",
  2121. "wvx",
  2122. "xbm",
  2123. "xif",
  2124. "xla",
  2125. "xlam",
  2126. "xls",
  2127. "xlsb",
  2128. "xlsm",
  2129. "xlsx",
  2130. "xlt",
  2131. "xltm",
  2132. "xltx",
  2133. "xm",
  2134. "xmind",
  2135. "xpi",
  2136. "xpm",
  2137. "xwd",
  2138. "xz",
  2139. "z",
  2140. "zip",
  2141. "zipx"
  2142. ];
  2143. (function (module) {
  2144. module.exports = require$$0;
  2145. } (binaryExtensions$1));
  2146. const path = require$$0$2;
  2147. const binaryExtensions = binaryExtensions$1.exports;
  2148. const extensions = new Set(binaryExtensions);
  2149. var isBinaryPath$1 = filePath => extensions.has(path.extname(filePath).slice(1).toLowerCase());
  2150. var constants = {};
  2151. (function (exports) {
  2152. const {sep} = require$$0$2;
  2153. const {platform} = process;
  2154. const os = require$$2$1;
  2155. exports.EV_ALL = 'all';
  2156. exports.EV_READY = 'ready';
  2157. exports.EV_ADD = 'add';
  2158. exports.EV_CHANGE = 'change';
  2159. exports.EV_ADD_DIR = 'addDir';
  2160. exports.EV_UNLINK = 'unlink';
  2161. exports.EV_UNLINK_DIR = 'unlinkDir';
  2162. exports.EV_RAW = 'raw';
  2163. exports.EV_ERROR = 'error';
  2164. exports.STR_DATA = 'data';
  2165. exports.STR_END = 'end';
  2166. exports.STR_CLOSE = 'close';
  2167. exports.FSEVENT_CREATED = 'created';
  2168. exports.FSEVENT_MODIFIED = 'modified';
  2169. exports.FSEVENT_DELETED = 'deleted';
  2170. exports.FSEVENT_MOVED = 'moved';
  2171. exports.FSEVENT_CLONED = 'cloned';
  2172. exports.FSEVENT_UNKNOWN = 'unknown';
  2173. exports.FSEVENT_TYPE_FILE = 'file';
  2174. exports.FSEVENT_TYPE_DIRECTORY = 'directory';
  2175. exports.FSEVENT_TYPE_SYMLINK = 'symlink';
  2176. exports.KEY_LISTENERS = 'listeners';
  2177. exports.KEY_ERR = 'errHandlers';
  2178. exports.KEY_RAW = 'rawEmitters';
  2179. exports.HANDLER_KEYS = [exports.KEY_LISTENERS, exports.KEY_ERR, exports.KEY_RAW];
  2180. exports.DOT_SLASH = `.${sep}`;
  2181. exports.BACK_SLASH_RE = /\\/g;
  2182. exports.DOUBLE_SLASH_RE = /\/\//;
  2183. exports.SLASH_OR_BACK_SLASH_RE = /[/\\]/;
  2184. exports.DOT_RE = /\..*\.(sw[px])$|~$|\.subl.*\.tmp/;
  2185. exports.REPLACER_RE = /^\.[/\\]/;
  2186. exports.SLASH = '/';
  2187. exports.SLASH_SLASH = '//';
  2188. exports.BRACE_START = '{';
  2189. exports.BANG = '!';
  2190. exports.ONE_DOT = '.';
  2191. exports.TWO_DOTS = '..';
  2192. exports.STAR = '*';
  2193. exports.GLOBSTAR = '**';
  2194. exports.ROOT_GLOBSTAR = '/**/*';
  2195. exports.SLASH_GLOBSTAR = '/**';
  2196. exports.DIR_SUFFIX = 'Dir';
  2197. exports.ANYMATCH_OPTS = {dot: true};
  2198. exports.STRING_TYPE = 'string';
  2199. exports.FUNCTION_TYPE = 'function';
  2200. exports.EMPTY_STR = '';
  2201. exports.EMPTY_FN = () => {};
  2202. exports.IDENTITY_FN = val => val;
  2203. exports.isWindows = platform === 'win32';
  2204. exports.isMacos = platform === 'darwin';
  2205. exports.isLinux = platform === 'linux';
  2206. exports.isIBMi = os.type() === 'OS400';
  2207. } (constants));
  2208. const fs$2 = require$$0$1;
  2209. const sysPath$2 = require$$0$2;
  2210. const { promisify: promisify$2 } = require$$2;
  2211. const isBinaryPath = isBinaryPath$1;
  2212. const {
  2213. isWindows: isWindows$1,
  2214. isLinux,
  2215. EMPTY_FN: EMPTY_FN$2,
  2216. EMPTY_STR: EMPTY_STR$1,
  2217. KEY_LISTENERS,
  2218. KEY_ERR,
  2219. KEY_RAW,
  2220. HANDLER_KEYS,
  2221. EV_CHANGE: EV_CHANGE$2,
  2222. EV_ADD: EV_ADD$2,
  2223. EV_ADD_DIR: EV_ADD_DIR$2,
  2224. EV_ERROR: EV_ERROR$2,
  2225. STR_DATA: STR_DATA$1,
  2226. STR_END: STR_END$2,
  2227. BRACE_START: BRACE_START$1,
  2228. STAR
  2229. } = constants;
  2230. const THROTTLE_MODE_WATCH = 'watch';
  2231. const open = promisify$2(fs$2.open);
  2232. const stat$2 = promisify$2(fs$2.stat);
  2233. const lstat$1 = promisify$2(fs$2.lstat);
  2234. const close = promisify$2(fs$2.close);
  2235. const fsrealpath = promisify$2(fs$2.realpath);
  2236. const statMethods$1 = { lstat: lstat$1, stat: stat$2 };
  2237. // TODO: emit errors properly. Example: EMFILE on Macos.
  2238. const foreach = (val, fn) => {
  2239. if (val instanceof Set) {
  2240. val.forEach(fn);
  2241. } else {
  2242. fn(val);
  2243. }
  2244. };
  2245. const addAndConvert = (main, prop, item) => {
  2246. let container = main[prop];
  2247. if (!(container instanceof Set)) {
  2248. main[prop] = container = new Set([container]);
  2249. }
  2250. container.add(item);
  2251. };
  2252. const clearItem = cont => key => {
  2253. const set = cont[key];
  2254. if (set instanceof Set) {
  2255. set.clear();
  2256. } else {
  2257. delete cont[key];
  2258. }
  2259. };
  2260. const delFromSet = (main, prop, item) => {
  2261. const container = main[prop];
  2262. if (container instanceof Set) {
  2263. container.delete(item);
  2264. } else if (container === item) {
  2265. delete main[prop];
  2266. }
  2267. };
  2268. const isEmptySet = (val) => val instanceof Set ? val.size === 0 : !val;
  2269. /**
  2270. * @typedef {String} Path
  2271. */
  2272. // fs_watch helpers
  2273. // object to hold per-process fs_watch instances
  2274. // (may be shared across chokidar FSWatcher instances)
  2275. /**
  2276. * @typedef {Object} FsWatchContainer
  2277. * @property {Set} listeners
  2278. * @property {Set} errHandlers
  2279. * @property {Set} rawEmitters
  2280. * @property {fs.FSWatcher=} watcher
  2281. * @property {Boolean=} watcherUnusable
  2282. */
  2283. /**
  2284. * @type {Map<String,FsWatchContainer>}
  2285. */
  2286. const FsWatchInstances = new Map();
  2287. /**
  2288. * Instantiates the fs_watch interface
  2289. * @param {String} path to be watched
  2290. * @param {Object} options to be passed to fs_watch
  2291. * @param {Function} listener main event handler
  2292. * @param {Function} errHandler emits info about errors
  2293. * @param {Function} emitRaw emits raw event data
  2294. * @returns {fs.FSWatcher} new fsevents instance
  2295. */
  2296. function createFsWatchInstance(path, options, listener, errHandler, emitRaw) {
  2297. const handleEvent = (rawEvent, evPath) => {
  2298. listener(path);
  2299. emitRaw(rawEvent, evPath, {watchedPath: path});
  2300. // emit based on events occurring for files from a directory's watcher in
  2301. // case the file's watcher misses it (and rely on throttling to de-dupe)
  2302. if (evPath && path !== evPath) {
  2303. fsWatchBroadcast(
  2304. sysPath$2.resolve(path, evPath), KEY_LISTENERS, sysPath$2.join(path, evPath)
  2305. );
  2306. }
  2307. };
  2308. try {
  2309. return fs$2.watch(path, options, handleEvent);
  2310. } catch (error) {
  2311. errHandler(error);
  2312. }
  2313. }
  2314. /**
  2315. * Helper for passing fs_watch event data to a collection of listeners
  2316. * @param {Path} fullPath absolute path bound to fs_watch instance
  2317. * @param {String} type listener type
  2318. * @param {*=} val1 arguments to be passed to listeners
  2319. * @param {*=} val2
  2320. * @param {*=} val3
  2321. */
  2322. const fsWatchBroadcast = (fullPath, type, val1, val2, val3) => {
  2323. const cont = FsWatchInstances.get(fullPath);
  2324. if (!cont) return;
  2325. foreach(cont[type], (listener) => {
  2326. listener(val1, val2, val3);
  2327. });
  2328. };
  2329. /**
  2330. * Instantiates the fs_watch interface or binds listeners
  2331. * to an existing one covering the same file system entry
  2332. * @param {String} path
  2333. * @param {String} fullPath absolute path
  2334. * @param {Object} options to be passed to fs_watch
  2335. * @param {Object} handlers container for event listener functions
  2336. */
  2337. const setFsWatchListener = (path, fullPath, options, handlers) => {
  2338. const {listener, errHandler, rawEmitter} = handlers;
  2339. let cont = FsWatchInstances.get(fullPath);
  2340. /** @type {fs.FSWatcher=} */
  2341. let watcher;
  2342. if (!options.persistent) {
  2343. watcher = createFsWatchInstance(
  2344. path, options, listener, errHandler, rawEmitter
  2345. );
  2346. return watcher.close.bind(watcher);
  2347. }
  2348. if (cont) {
  2349. addAndConvert(cont, KEY_LISTENERS, listener);
  2350. addAndConvert(cont, KEY_ERR, errHandler);
  2351. addAndConvert(cont, KEY_RAW, rawEmitter);
  2352. } else {
  2353. watcher = createFsWatchInstance(
  2354. path,
  2355. options,
  2356. fsWatchBroadcast.bind(null, fullPath, KEY_LISTENERS),
  2357. errHandler, // no need to use broadcast here
  2358. fsWatchBroadcast.bind(null, fullPath, KEY_RAW)
  2359. );
  2360. if (!watcher) return;
  2361. watcher.on(EV_ERROR$2, async (error) => {
  2362. const broadcastErr = fsWatchBroadcast.bind(null, fullPath, KEY_ERR);
  2363. cont.watcherUnusable = true; // documented since Node 10.4.1
  2364. // Workaround for https://github.com/joyent/node/issues/4337
  2365. if (isWindows$1 && error.code === 'EPERM') {
  2366. try {
  2367. const fd = await open(path, 'r');
  2368. await close(fd);
  2369. broadcastErr(error);
  2370. } catch (err) {}
  2371. } else {
  2372. broadcastErr(error);
  2373. }
  2374. });
  2375. cont = {
  2376. listeners: listener,
  2377. errHandlers: errHandler,
  2378. rawEmitters: rawEmitter,
  2379. watcher
  2380. };
  2381. FsWatchInstances.set(fullPath, cont);
  2382. }
  2383. // const index = cont.listeners.indexOf(listener);
  2384. // removes this instance's listeners and closes the underlying fs_watch
  2385. // instance if there are no more listeners left
  2386. return () => {
  2387. delFromSet(cont, KEY_LISTENERS, listener);
  2388. delFromSet(cont, KEY_ERR, errHandler);
  2389. delFromSet(cont, KEY_RAW, rawEmitter);
  2390. if (isEmptySet(cont.listeners)) {
  2391. // Check to protect against issue gh-730.
  2392. // if (cont.watcherUnusable) {
  2393. cont.watcher.close();
  2394. // }
  2395. FsWatchInstances.delete(fullPath);
  2396. HANDLER_KEYS.forEach(clearItem(cont));
  2397. cont.watcher = undefined;
  2398. Object.freeze(cont);
  2399. }
  2400. };
  2401. };
  2402. // fs_watchFile helpers
  2403. // object to hold per-process fs_watchFile instances
  2404. // (may be shared across chokidar FSWatcher instances)
  2405. const FsWatchFileInstances = new Map();
  2406. /**
  2407. * Instantiates the fs_watchFile interface or binds listeners
  2408. * to an existing one covering the same file system entry
  2409. * @param {String} path to be watched
  2410. * @param {String} fullPath absolute path
  2411. * @param {Object} options options to be passed to fs_watchFile
  2412. * @param {Object} handlers container for event listener functions
  2413. * @returns {Function} closer
  2414. */
  2415. const setFsWatchFileListener = (path, fullPath, options, handlers) => {
  2416. const {listener, rawEmitter} = handlers;
  2417. let cont = FsWatchFileInstances.get(fullPath);
  2418. const copts = cont && cont.options;
  2419. if (copts && (copts.persistent < options.persistent || copts.interval > options.interval)) {
  2420. fs$2.unwatchFile(fullPath);
  2421. cont = undefined;
  2422. }
  2423. /* eslint-enable no-unused-vars, prefer-destructuring */
  2424. if (cont) {
  2425. addAndConvert(cont, KEY_LISTENERS, listener);
  2426. addAndConvert(cont, KEY_RAW, rawEmitter);
  2427. } else {
  2428. // TODO
  2429. // listeners.add(listener);
  2430. // rawEmitters.add(rawEmitter);
  2431. cont = {
  2432. listeners: listener,
  2433. rawEmitters: rawEmitter,
  2434. options,
  2435. watcher: fs$2.watchFile(fullPath, options, (curr, prev) => {
  2436. foreach(cont.rawEmitters, (rawEmitter) => {
  2437. rawEmitter(EV_CHANGE$2, fullPath, {curr, prev});
  2438. });
  2439. const currmtime = curr.mtimeMs;
  2440. if (curr.size !== prev.size || currmtime > prev.mtimeMs || currmtime === 0) {
  2441. foreach(cont.listeners, (listener) => listener(path, curr));
  2442. }
  2443. })
  2444. };
  2445. FsWatchFileInstances.set(fullPath, cont);
  2446. }
  2447. // const index = cont.listeners.indexOf(listener);
  2448. // Removes this instance's listeners and closes the underlying fs_watchFile
  2449. // instance if there are no more listeners left.
  2450. return () => {
  2451. delFromSet(cont, KEY_LISTENERS, listener);
  2452. delFromSet(cont, KEY_RAW, rawEmitter);
  2453. if (isEmptySet(cont.listeners)) {
  2454. FsWatchFileInstances.delete(fullPath);
  2455. fs$2.unwatchFile(fullPath);
  2456. cont.options = cont.watcher = undefined;
  2457. Object.freeze(cont);
  2458. }
  2459. };
  2460. };
  2461. /**
  2462. * @mixin
  2463. */
  2464. class NodeFsHandler$1 {
  2465. /**
  2466. * @param {import("../index").FSWatcher} fsW
  2467. */
  2468. constructor(fsW) {
  2469. this.fsw = fsW;
  2470. this._boundHandleError = (error) => fsW._handleError(error);
  2471. }
  2472. /**
  2473. * Watch file for changes with fs_watchFile or fs_watch.
  2474. * @param {String} path to file or dir
  2475. * @param {Function} listener on fs change
  2476. * @returns {Function} closer for the watcher instance
  2477. */
  2478. _watchWithNodeFs(path, listener) {
  2479. const opts = this.fsw.options;
  2480. const directory = sysPath$2.dirname(path);
  2481. const basename = sysPath$2.basename(path);
  2482. const parent = this.fsw._getWatchedDir(directory);
  2483. parent.add(basename);
  2484. const absolutePath = sysPath$2.resolve(path);
  2485. const options = {persistent: opts.persistent};
  2486. if (!listener) listener = EMPTY_FN$2;
  2487. let closer;
  2488. if (opts.usePolling) {
  2489. options.interval = opts.enableBinaryInterval && isBinaryPath(basename) ?
  2490. opts.binaryInterval : opts.interval;
  2491. closer = setFsWatchFileListener(path, absolutePath, options, {
  2492. listener,
  2493. rawEmitter: this.fsw._emitRaw
  2494. });
  2495. } else {
  2496. closer = setFsWatchListener(path, absolutePath, options, {
  2497. listener,
  2498. errHandler: this._boundHandleError,
  2499. rawEmitter: this.fsw._emitRaw
  2500. });
  2501. }
  2502. return closer;
  2503. }
  2504. /**
  2505. * Watch a file and emit add event if warranted.
  2506. * @param {Path} file Path
  2507. * @param {fs.Stats} stats result of fs_stat
  2508. * @param {Boolean} initialAdd was the file added at watch instantiation?
  2509. * @returns {Function} closer for the watcher instance
  2510. */
  2511. _handleFile(file, stats, initialAdd) {
  2512. if (this.fsw.closed) {
  2513. return;
  2514. }
  2515. const dirname = sysPath$2.dirname(file);
  2516. const basename = sysPath$2.basename(file);
  2517. const parent = this.fsw._getWatchedDir(dirname);
  2518. // stats is always present
  2519. let prevStats = stats;
  2520. // if the file is already being watched, do nothing
  2521. if (parent.has(basename)) return;
  2522. const listener = async (path, newStats) => {
  2523. if (!this.fsw._throttle(THROTTLE_MODE_WATCH, file, 5)) return;
  2524. if (!newStats || newStats.mtimeMs === 0) {
  2525. try {
  2526. const newStats = await stat$2(file);
  2527. if (this.fsw.closed) return;
  2528. // Check that change event was not fired because of changed only accessTime.
  2529. const at = newStats.atimeMs;
  2530. const mt = newStats.mtimeMs;
  2531. if (!at || at <= mt || mt !== prevStats.mtimeMs) {
  2532. this.fsw._emit(EV_CHANGE$2, file, newStats);
  2533. }
  2534. if (isLinux && prevStats.ino !== newStats.ino) {
  2535. this.fsw._closeFile(path);
  2536. prevStats = newStats;
  2537. this.fsw._addPathCloser(path, this._watchWithNodeFs(file, listener));
  2538. } else {
  2539. prevStats = newStats;
  2540. }
  2541. } catch (error) {
  2542. // Fix issues where mtime is null but file is still present
  2543. this.fsw._remove(dirname, basename);
  2544. }
  2545. // add is about to be emitted if file not already tracked in parent
  2546. } else if (parent.has(basename)) {
  2547. // Check that change event was not fired because of changed only accessTime.
  2548. const at = newStats.atimeMs;
  2549. const mt = newStats.mtimeMs;
  2550. if (!at || at <= mt || mt !== prevStats.mtimeMs) {
  2551. this.fsw._emit(EV_CHANGE$2, file, newStats);
  2552. }
  2553. prevStats = newStats;
  2554. }
  2555. };
  2556. // kick off the watcher
  2557. const closer = this._watchWithNodeFs(file, listener);
  2558. // emit an add event if we're supposed to
  2559. if (!(initialAdd && this.fsw.options.ignoreInitial) && this.fsw._isntIgnored(file)) {
  2560. if (!this.fsw._throttle(EV_ADD$2, file, 0)) return;
  2561. this.fsw._emit(EV_ADD$2, file, stats);
  2562. }
  2563. return closer;
  2564. }
  2565. /**
  2566. * Handle symlinks encountered while reading a dir.
  2567. * @param {Object} entry returned by readdirp
  2568. * @param {String} directory path of dir being read
  2569. * @param {String} path of this item
  2570. * @param {String} item basename of this item
  2571. * @returns {Promise<Boolean>} true if no more processing is needed for this entry.
  2572. */
  2573. async _handleSymlink(entry, directory, path, item) {
  2574. if (this.fsw.closed) {
  2575. return;
  2576. }
  2577. const full = entry.fullPath;
  2578. const dir = this.fsw._getWatchedDir(directory);
  2579. if (!this.fsw.options.followSymlinks) {
  2580. // watch symlink directly (don't follow) and detect changes
  2581. this.fsw._incrReadyCount();
  2582. let linkPath;
  2583. try {
  2584. linkPath = await fsrealpath(path);
  2585. } catch (e) {
  2586. this.fsw._emitReady();
  2587. return true;
  2588. }
  2589. if (this.fsw.closed) return;
  2590. if (dir.has(item)) {
  2591. if (this.fsw._symlinkPaths.get(full) !== linkPath) {
  2592. this.fsw._symlinkPaths.set(full, linkPath);
  2593. this.fsw._emit(EV_CHANGE$2, path, entry.stats);
  2594. }
  2595. } else {
  2596. dir.add(item);
  2597. this.fsw._symlinkPaths.set(full, linkPath);
  2598. this.fsw._emit(EV_ADD$2, path, entry.stats);
  2599. }
  2600. this.fsw._emitReady();
  2601. return true;
  2602. }
  2603. // don't follow the same symlink more than once
  2604. if (this.fsw._symlinkPaths.has(full)) {
  2605. return true;
  2606. }
  2607. this.fsw._symlinkPaths.set(full, true);
  2608. }
  2609. _handleRead(directory, initialAdd, wh, target, dir, depth, throttler) {
  2610. // Normalize the directory name on Windows
  2611. directory = sysPath$2.join(directory, EMPTY_STR$1);
  2612. if (!wh.hasGlob) {
  2613. throttler = this.fsw._throttle('readdir', directory, 1000);
  2614. if (!throttler) return;
  2615. }
  2616. const previous = this.fsw._getWatchedDir(wh.path);
  2617. const current = new Set();
  2618. let stream = this.fsw._readdirp(directory, {
  2619. fileFilter: entry => wh.filterPath(entry),
  2620. directoryFilter: entry => wh.filterDir(entry),
  2621. depth: 0
  2622. }).on(STR_DATA$1, async (entry) => {
  2623. if (this.fsw.closed) {
  2624. stream = undefined;
  2625. return;
  2626. }
  2627. const item = entry.path;
  2628. let path = sysPath$2.join(directory, item);
  2629. current.add(item);
  2630. if (entry.stats.isSymbolicLink() && await this._handleSymlink(entry, directory, path, item)) {
  2631. return;
  2632. }
  2633. if (this.fsw.closed) {
  2634. stream = undefined;
  2635. return;
  2636. }
  2637. // Files that present in current directory snapshot
  2638. // but absent in previous are added to watch list and
  2639. // emit `add` event.
  2640. if (item === target || !target && !previous.has(item)) {
  2641. this.fsw._incrReadyCount();
  2642. // ensure relativeness of path is preserved in case of watcher reuse
  2643. path = sysPath$2.join(dir, sysPath$2.relative(dir, path));
  2644. this._addToNodeFs(path, initialAdd, wh, depth + 1);
  2645. }
  2646. }).on(EV_ERROR$2, this._boundHandleError);
  2647. return new Promise(resolve =>
  2648. stream.once(STR_END$2, () => {
  2649. if (this.fsw.closed) {
  2650. stream = undefined;
  2651. return;
  2652. }
  2653. const wasThrottled = throttler ? throttler.clear() : false;
  2654. resolve();
  2655. // Files that absent in current directory snapshot
  2656. // but present in previous emit `remove` event
  2657. // and are removed from @watched[directory].
  2658. previous.getChildren().filter((item) => {
  2659. return item !== directory &&
  2660. !current.has(item) &&
  2661. // in case of intersecting globs;
  2662. // a path may have been filtered out of this readdir, but
  2663. // shouldn't be removed because it matches a different glob
  2664. (!wh.hasGlob || wh.filterPath({
  2665. fullPath: sysPath$2.resolve(directory, item)
  2666. }));
  2667. }).forEach((item) => {
  2668. this.fsw._remove(directory, item);
  2669. });
  2670. stream = undefined;
  2671. // one more time for any missed in case changes came in extremely quickly
  2672. if (wasThrottled) this._handleRead(directory, false, wh, target, dir, depth, throttler);
  2673. })
  2674. );
  2675. }
  2676. /**
  2677. * Read directory to add / remove files from `@watched` list and re-read it on change.
  2678. * @param {String} dir fs path
  2679. * @param {fs.Stats} stats
  2680. * @param {Boolean} initialAdd
  2681. * @param {Number} depth relative to user-supplied path
  2682. * @param {String} target child path targeted for watch
  2683. * @param {Object} wh Common watch helpers for this path
  2684. * @param {String} realpath
  2685. * @returns {Promise<Function>} closer for the watcher instance.
  2686. */
  2687. async _handleDir(dir, stats, initialAdd, depth, target, wh, realpath) {
  2688. const parentDir = this.fsw._getWatchedDir(sysPath$2.dirname(dir));
  2689. const tracked = parentDir.has(sysPath$2.basename(dir));
  2690. if (!(initialAdd && this.fsw.options.ignoreInitial) && !target && !tracked) {
  2691. if (!wh.hasGlob || wh.globFilter(dir)) this.fsw._emit(EV_ADD_DIR$2, dir, stats);
  2692. }
  2693. // ensure dir is tracked (harmless if redundant)
  2694. parentDir.add(sysPath$2.basename(dir));
  2695. this.fsw._getWatchedDir(dir);
  2696. let throttler;
  2697. let closer;
  2698. const oDepth = this.fsw.options.depth;
  2699. if ((oDepth == null || depth <= oDepth) && !this.fsw._symlinkPaths.has(realpath)) {
  2700. if (!target) {
  2701. await this._handleRead(dir, initialAdd, wh, target, dir, depth, throttler);
  2702. if (this.fsw.closed) return;
  2703. }
  2704. closer = this._watchWithNodeFs(dir, (dirPath, stats) => {
  2705. // if current directory is removed, do nothing
  2706. if (stats && stats.mtimeMs === 0) return;
  2707. this._handleRead(dirPath, false, wh, target, dir, depth, throttler);
  2708. });
  2709. }
  2710. return closer;
  2711. }
  2712. /**
  2713. * Handle added file, directory, or glob pattern.
  2714. * Delegates call to _handleFile / _handleDir after checks.
  2715. * @param {String} path to file or ir
  2716. * @param {Boolean} initialAdd was the file added at watch instantiation?
  2717. * @param {Object} priorWh depth relative to user-supplied path
  2718. * @param {Number} depth Child path actually targeted for watch
  2719. * @param {String=} target Child path actually targeted for watch
  2720. * @returns {Promise}
  2721. */
  2722. async _addToNodeFs(path, initialAdd, priorWh, depth, target) {
  2723. const ready = this.fsw._emitReady;
  2724. if (this.fsw._isIgnored(path) || this.fsw.closed) {
  2725. ready();
  2726. return false;
  2727. }
  2728. const wh = this.fsw._getWatchHelpers(path, depth);
  2729. if (!wh.hasGlob && priorWh) {
  2730. wh.hasGlob = priorWh.hasGlob;
  2731. wh.globFilter = priorWh.globFilter;
  2732. wh.filterPath = entry => priorWh.filterPath(entry);
  2733. wh.filterDir = entry => priorWh.filterDir(entry);
  2734. }
  2735. // evaluate what is at the path we're being asked to watch
  2736. try {
  2737. const stats = await statMethods$1[wh.statMethod](wh.watchPath);
  2738. if (this.fsw.closed) return;
  2739. if (this.fsw._isIgnored(wh.watchPath, stats)) {
  2740. ready();
  2741. return false;
  2742. }
  2743. const follow = this.fsw.options.followSymlinks && !path.includes(STAR) && !path.includes(BRACE_START$1);
  2744. let closer;
  2745. if (stats.isDirectory()) {
  2746. const absPath = sysPath$2.resolve(path);
  2747. const targetPath = follow ? await fsrealpath(path) : path;
  2748. if (this.fsw.closed) return;
  2749. closer = await this._handleDir(wh.watchPath, stats, initialAdd, depth, target, wh, targetPath);
  2750. if (this.fsw.closed) return;
  2751. // preserve this symlink's target path
  2752. if (absPath !== targetPath && targetPath !== undefined) {
  2753. this.fsw._symlinkPaths.set(absPath, targetPath);
  2754. }
  2755. } else if (stats.isSymbolicLink()) {
  2756. const targetPath = follow ? await fsrealpath(path) : path;
  2757. if (this.fsw.closed) return;
  2758. const parent = sysPath$2.dirname(wh.watchPath);
  2759. this.fsw._getWatchedDir(parent).add(wh.watchPath);
  2760. this.fsw._emit(EV_ADD$2, wh.watchPath, stats);
  2761. closer = await this._handleDir(parent, stats, initialAdd, depth, path, wh, targetPath);
  2762. if (this.fsw.closed) return;
  2763. // preserve this symlink's target path
  2764. if (targetPath !== undefined) {
  2765. this.fsw._symlinkPaths.set(sysPath$2.resolve(path), targetPath);
  2766. }
  2767. } else {
  2768. closer = this._handleFile(wh.watchPath, stats, initialAdd);
  2769. }
  2770. ready();
  2771. this.fsw._addPathCloser(path, closer);
  2772. return false;
  2773. } catch (error) {
  2774. if (this.fsw._handleError(error)) {
  2775. ready();
  2776. return path;
  2777. }
  2778. }
  2779. }
  2780. }
  2781. var nodefsHandler = NodeFsHandler$1;
  2782. var fseventsHandler = {exports: {}};
  2783. const require$$3 = /*@__PURE__*/getAugmentedNamespace(fseventsImporter);
  2784. const fs$1 = require$$0$1;
  2785. const sysPath$1 = require$$0$2;
  2786. const { promisify: promisify$1 } = require$$2;
  2787. let fsevents;
  2788. try {
  2789. fsevents = require$$3.getFsEvents();
  2790. } catch (error) {
  2791. if (process.env.CHOKIDAR_PRINT_FSEVENTS_REQUIRE_ERROR) console.error(error);
  2792. }
  2793. if (fsevents) {
  2794. // TODO: real check
  2795. const mtch = process.version.match(/v(\d+)\.(\d+)/);
  2796. if (mtch && mtch[1] && mtch[2]) {
  2797. const maj = Number.parseInt(mtch[1], 10);
  2798. const min = Number.parseInt(mtch[2], 10);
  2799. if (maj === 8 && min < 16) {
  2800. fsevents = undefined;
  2801. }
  2802. }
  2803. }
  2804. const {
  2805. EV_ADD: EV_ADD$1,
  2806. EV_CHANGE: EV_CHANGE$1,
  2807. EV_ADD_DIR: EV_ADD_DIR$1,
  2808. EV_UNLINK: EV_UNLINK$1,
  2809. EV_ERROR: EV_ERROR$1,
  2810. STR_DATA,
  2811. STR_END: STR_END$1,
  2812. FSEVENT_CREATED,
  2813. FSEVENT_MODIFIED,
  2814. FSEVENT_DELETED,
  2815. FSEVENT_MOVED,
  2816. // FSEVENT_CLONED,
  2817. FSEVENT_UNKNOWN,
  2818. FSEVENT_TYPE_FILE,
  2819. FSEVENT_TYPE_DIRECTORY,
  2820. FSEVENT_TYPE_SYMLINK,
  2821. ROOT_GLOBSTAR,
  2822. DIR_SUFFIX,
  2823. DOT_SLASH,
  2824. FUNCTION_TYPE: FUNCTION_TYPE$1,
  2825. EMPTY_FN: EMPTY_FN$1,
  2826. IDENTITY_FN
  2827. } = constants;
  2828. const Depth = (value) => isNaN(value) ? {} : {depth: value};
  2829. const stat$1 = promisify$1(fs$1.stat);
  2830. const lstat = promisify$1(fs$1.lstat);
  2831. const realpath = promisify$1(fs$1.realpath);
  2832. const statMethods = { stat: stat$1, lstat };
  2833. /**
  2834. * @typedef {String} Path
  2835. */
  2836. /**
  2837. * @typedef {Object} FsEventsWatchContainer
  2838. * @property {Set<Function>} listeners
  2839. * @property {Function} rawEmitter
  2840. * @property {{stop: Function}} watcher
  2841. */
  2842. // fsevents instance helper functions
  2843. /**
  2844. * Object to hold per-process fsevents instances (may be shared across chokidar FSWatcher instances)
  2845. * @type {Map<Path,FsEventsWatchContainer>}
  2846. */
  2847. const FSEventsWatchers = new Map();
  2848. // Threshold of duplicate path prefixes at which to start
  2849. // consolidating going forward
  2850. const consolidateThreshhold = 10;
  2851. const wrongEventFlags = new Set([
  2852. 69888, 70400, 71424, 72704, 73472, 131328, 131840, 262912
  2853. ]);
  2854. /**
  2855. * Instantiates the fsevents interface
  2856. * @param {Path} path path to be watched
  2857. * @param {Function} callback called when fsevents is bound and ready
  2858. * @returns {{stop: Function}} new fsevents instance
  2859. */
  2860. const createFSEventsInstance = (path, callback) => {
  2861. const stop = fsevents.watch(path, callback);
  2862. return {stop};
  2863. };
  2864. /**
  2865. * Instantiates the fsevents interface or binds listeners to an existing one covering
  2866. * the same file tree.
  2867. * @param {Path} path - to be watched
  2868. * @param {Path} realPath - real path for symlinks
  2869. * @param {Function} listener - called when fsevents emits events
  2870. * @param {Function} rawEmitter - passes data to listeners of the 'raw' event
  2871. * @returns {Function} closer
  2872. */
  2873. function setFSEventsListener(path, realPath, listener, rawEmitter) {
  2874. let watchPath = sysPath$1.extname(realPath) ? sysPath$1.dirname(realPath) : realPath;
  2875. const parentPath = sysPath$1.dirname(watchPath);
  2876. let cont = FSEventsWatchers.get(watchPath);
  2877. // If we've accumulated a substantial number of paths that
  2878. // could have been consolidated by watching one directory
  2879. // above the current one, create a watcher on the parent
  2880. // path instead, so that we do consolidate going forward.
  2881. if (couldConsolidate(parentPath)) {
  2882. watchPath = parentPath;
  2883. }
  2884. const resolvedPath = sysPath$1.resolve(path);
  2885. const hasSymlink = resolvedPath !== realPath;
  2886. const filteredListener = (fullPath, flags, info) => {
  2887. if (hasSymlink) fullPath = fullPath.replace(realPath, resolvedPath);
  2888. if (
  2889. fullPath === resolvedPath ||
  2890. !fullPath.indexOf(resolvedPath + sysPath$1.sep)
  2891. ) listener(fullPath, flags, info);
  2892. };
  2893. // check if there is already a watcher on a parent path
  2894. // modifies `watchPath` to the parent path when it finds a match
  2895. let watchedParent = false;
  2896. for (const watchedPath of FSEventsWatchers.keys()) {
  2897. if (realPath.indexOf(sysPath$1.resolve(watchedPath) + sysPath$1.sep) === 0) {
  2898. watchPath = watchedPath;
  2899. cont = FSEventsWatchers.get(watchPath);
  2900. watchedParent = true;
  2901. break;
  2902. }
  2903. }
  2904. if (cont || watchedParent) {
  2905. cont.listeners.add(filteredListener);
  2906. } else {
  2907. cont = {
  2908. listeners: new Set([filteredListener]),
  2909. rawEmitter,
  2910. watcher: createFSEventsInstance(watchPath, (fullPath, flags) => {
  2911. if (!cont.listeners.size) return;
  2912. const info = fsevents.getInfo(fullPath, flags);
  2913. cont.listeners.forEach(list => {
  2914. list(fullPath, flags, info);
  2915. });
  2916. cont.rawEmitter(info.event, fullPath, info);
  2917. })
  2918. };
  2919. FSEventsWatchers.set(watchPath, cont);
  2920. }
  2921. // removes this instance's listeners and closes the underlying fsevents
  2922. // instance if there are no more listeners left
  2923. return () => {
  2924. const lst = cont.listeners;
  2925. lst.delete(filteredListener);
  2926. if (!lst.size) {
  2927. FSEventsWatchers.delete(watchPath);
  2928. if (cont.watcher) return cont.watcher.stop().then(() => {
  2929. cont.rawEmitter = cont.watcher = undefined;
  2930. Object.freeze(cont);
  2931. });
  2932. }
  2933. };
  2934. }
  2935. // Decide whether or not we should start a new higher-level
  2936. // parent watcher
  2937. const couldConsolidate = (path) => {
  2938. let count = 0;
  2939. for (const watchPath of FSEventsWatchers.keys()) {
  2940. if (watchPath.indexOf(path) === 0) {
  2941. count++;
  2942. if (count >= consolidateThreshhold) {
  2943. return true;
  2944. }
  2945. }
  2946. }
  2947. return false;
  2948. };
  2949. // returns boolean indicating whether fsevents can be used
  2950. const canUse = () => fsevents && FSEventsWatchers.size < 128;
  2951. // determines subdirectory traversal levels from root to path
  2952. const calcDepth = (path, root) => {
  2953. let i = 0;
  2954. while (!path.indexOf(root) && (path = sysPath$1.dirname(path)) !== root) i++;
  2955. return i;
  2956. };
  2957. // returns boolean indicating whether the fsevents' event info has the same type
  2958. // as the one returned by fs.stat
  2959. const sameTypes = (info, stats) => (
  2960. info.type === FSEVENT_TYPE_DIRECTORY && stats.isDirectory() ||
  2961. info.type === FSEVENT_TYPE_SYMLINK && stats.isSymbolicLink() ||
  2962. info.type === FSEVENT_TYPE_FILE && stats.isFile()
  2963. );
  2964. /**
  2965. * @mixin
  2966. */
  2967. class FsEventsHandler$1 {
  2968. /**
  2969. * @param {import('../index').FSWatcher} fsw
  2970. */
  2971. constructor(fsw) {
  2972. this.fsw = fsw;
  2973. }
  2974. checkIgnored(path, stats) {
  2975. const ipaths = this.fsw._ignoredPaths;
  2976. if (this.fsw._isIgnored(path, stats)) {
  2977. ipaths.add(path);
  2978. if (stats && stats.isDirectory()) {
  2979. ipaths.add(path + ROOT_GLOBSTAR);
  2980. }
  2981. return true;
  2982. }
  2983. ipaths.delete(path);
  2984. ipaths.delete(path + ROOT_GLOBSTAR);
  2985. }
  2986. addOrChange(path, fullPath, realPath, parent, watchedDir, item, info, opts) {
  2987. const event = watchedDir.has(item) ? EV_CHANGE$1 : EV_ADD$1;
  2988. this.handleEvent(event, path, fullPath, realPath, parent, watchedDir, item, info, opts);
  2989. }
  2990. async checkExists(path, fullPath, realPath, parent, watchedDir, item, info, opts) {
  2991. try {
  2992. const stats = await stat$1(path);
  2993. if (this.fsw.closed) return;
  2994. if (sameTypes(info, stats)) {
  2995. this.addOrChange(path, fullPath, realPath, parent, watchedDir, item, info, opts);
  2996. } else {
  2997. this.handleEvent(EV_UNLINK$1, path, fullPath, realPath, parent, watchedDir, item, info, opts);
  2998. }
  2999. } catch (error) {
  3000. if (error.code === 'EACCES') {
  3001. this.addOrChange(path, fullPath, realPath, parent, watchedDir, item, info, opts);
  3002. } else {
  3003. this.handleEvent(EV_UNLINK$1, path, fullPath, realPath, parent, watchedDir, item, info, opts);
  3004. }
  3005. }
  3006. }
  3007. handleEvent(event, path, fullPath, realPath, parent, watchedDir, item, info, opts) {
  3008. if (this.fsw.closed || this.checkIgnored(path)) return;
  3009. if (event === EV_UNLINK$1) {
  3010. const isDirectory = info.type === FSEVENT_TYPE_DIRECTORY;
  3011. // suppress unlink events on never before seen files
  3012. if (isDirectory || watchedDir.has(item)) {
  3013. this.fsw._remove(parent, item, isDirectory);
  3014. }
  3015. } else {
  3016. if (event === EV_ADD$1) {
  3017. // track new directories
  3018. if (info.type === FSEVENT_TYPE_DIRECTORY) this.fsw._getWatchedDir(path);
  3019. if (info.type === FSEVENT_TYPE_SYMLINK && opts.followSymlinks) {
  3020. // push symlinks back to the top of the stack to get handled
  3021. const curDepth = opts.depth === undefined ?
  3022. undefined : calcDepth(fullPath, realPath) + 1;
  3023. return this._addToFsEvents(path, false, true, curDepth);
  3024. }
  3025. // track new paths
  3026. // (other than symlinks being followed, which will be tracked soon)
  3027. this.fsw._getWatchedDir(parent).add(item);
  3028. }
  3029. /**
  3030. * @type {'add'|'addDir'|'unlink'|'unlinkDir'}
  3031. */
  3032. const eventName = info.type === FSEVENT_TYPE_DIRECTORY ? event + DIR_SUFFIX : event;
  3033. this.fsw._emit(eventName, path);
  3034. if (eventName === EV_ADD_DIR$1) this._addToFsEvents(path, false, true);
  3035. }
  3036. }
  3037. /**
  3038. * Handle symlinks encountered during directory scan
  3039. * @param {String} watchPath - file/dir path to be watched with fsevents
  3040. * @param {String} realPath - real path (in case of symlinks)
  3041. * @param {Function} transform - path transformer
  3042. * @param {Function} globFilter - path filter in case a glob pattern was provided
  3043. * @returns {Function} closer for the watcher instance
  3044. */
  3045. _watchWithFsEvents(watchPath, realPath, transform, globFilter) {
  3046. if (this.fsw.closed || this.fsw._isIgnored(watchPath)) return;
  3047. const opts = this.fsw.options;
  3048. const watchCallback = async (fullPath, flags, info) => {
  3049. if (this.fsw.closed) return;
  3050. if (
  3051. opts.depth !== undefined &&
  3052. calcDepth(fullPath, realPath) > opts.depth
  3053. ) return;
  3054. const path = transform(sysPath$1.join(
  3055. watchPath, sysPath$1.relative(watchPath, fullPath)
  3056. ));
  3057. if (globFilter && !globFilter(path)) return;
  3058. // ensure directories are tracked
  3059. const parent = sysPath$1.dirname(path);
  3060. const item = sysPath$1.basename(path);
  3061. const watchedDir = this.fsw._getWatchedDir(
  3062. info.type === FSEVENT_TYPE_DIRECTORY ? path : parent
  3063. );
  3064. // correct for wrong events emitted
  3065. if (wrongEventFlags.has(flags) || info.event === FSEVENT_UNKNOWN) {
  3066. if (typeof opts.ignored === FUNCTION_TYPE$1) {
  3067. let stats;
  3068. try {
  3069. stats = await stat$1(path);
  3070. } catch (error) {}
  3071. if (this.fsw.closed) return;
  3072. if (this.checkIgnored(path, stats)) return;
  3073. if (sameTypes(info, stats)) {
  3074. this.addOrChange(path, fullPath, realPath, parent, watchedDir, item, info, opts);
  3075. } else {
  3076. this.handleEvent(EV_UNLINK$1, path, fullPath, realPath, parent, watchedDir, item, info, opts);
  3077. }
  3078. } else {
  3079. this.checkExists(path, fullPath, realPath, parent, watchedDir, item, info, opts);
  3080. }
  3081. } else {
  3082. switch (info.event) {
  3083. case FSEVENT_CREATED:
  3084. case FSEVENT_MODIFIED:
  3085. return this.addOrChange(path, fullPath, realPath, parent, watchedDir, item, info, opts);
  3086. case FSEVENT_DELETED:
  3087. case FSEVENT_MOVED:
  3088. return this.checkExists(path, fullPath, realPath, parent, watchedDir, item, info, opts);
  3089. }
  3090. }
  3091. };
  3092. const closer = setFSEventsListener(
  3093. watchPath,
  3094. realPath,
  3095. watchCallback,
  3096. this.fsw._emitRaw
  3097. );
  3098. this.fsw._emitReady();
  3099. return closer;
  3100. }
  3101. /**
  3102. * Handle symlinks encountered during directory scan
  3103. * @param {String} linkPath path to symlink
  3104. * @param {String} fullPath absolute path to the symlink
  3105. * @param {Function} transform pre-existing path transformer
  3106. * @param {Number} curDepth level of subdirectories traversed to where symlink is
  3107. * @returns {Promise<void>}
  3108. */
  3109. async _handleFsEventsSymlink(linkPath, fullPath, transform, curDepth) {
  3110. // don't follow the same symlink more than once
  3111. if (this.fsw.closed || this.fsw._symlinkPaths.has(fullPath)) return;
  3112. this.fsw._symlinkPaths.set(fullPath, true);
  3113. this.fsw._incrReadyCount();
  3114. try {
  3115. const linkTarget = await realpath(linkPath);
  3116. if (this.fsw.closed) return;
  3117. if (this.fsw._isIgnored(linkTarget)) {
  3118. return this.fsw._emitReady();
  3119. }
  3120. this.fsw._incrReadyCount();
  3121. // add the linkTarget for watching with a wrapper for transform
  3122. // that causes emitted paths to incorporate the link's path
  3123. this._addToFsEvents(linkTarget || linkPath, (path) => {
  3124. let aliasedPath = linkPath;
  3125. if (linkTarget && linkTarget !== DOT_SLASH) {
  3126. aliasedPath = path.replace(linkTarget, linkPath);
  3127. } else if (path !== DOT_SLASH) {
  3128. aliasedPath = sysPath$1.join(linkPath, path);
  3129. }
  3130. return transform(aliasedPath);
  3131. }, false, curDepth);
  3132. } catch(error) {
  3133. if (this.fsw._handleError(error)) {
  3134. return this.fsw._emitReady();
  3135. }
  3136. }
  3137. }
  3138. /**
  3139. *
  3140. * @param {Path} newPath
  3141. * @param {fs.Stats} stats
  3142. */
  3143. emitAdd(newPath, stats, processPath, opts, forceAdd) {
  3144. const pp = processPath(newPath);
  3145. const isDir = stats.isDirectory();
  3146. const dirObj = this.fsw._getWatchedDir(sysPath$1.dirname(pp));
  3147. const base = sysPath$1.basename(pp);
  3148. // ensure empty dirs get tracked
  3149. if (isDir) this.fsw._getWatchedDir(pp);
  3150. if (dirObj.has(base)) return;
  3151. dirObj.add(base);
  3152. if (!opts.ignoreInitial || forceAdd === true) {
  3153. this.fsw._emit(isDir ? EV_ADD_DIR$1 : EV_ADD$1, pp, stats);
  3154. }
  3155. }
  3156. initWatch(realPath, path, wh, processPath) {
  3157. if (this.fsw.closed) return;
  3158. const closer = this._watchWithFsEvents(
  3159. wh.watchPath,
  3160. sysPath$1.resolve(realPath || wh.watchPath),
  3161. processPath,
  3162. wh.globFilter
  3163. );
  3164. this.fsw._addPathCloser(path, closer);
  3165. }
  3166. /**
  3167. * Handle added path with fsevents
  3168. * @param {String} path file/dir path or glob pattern
  3169. * @param {Function|Boolean=} transform converts working path to what the user expects
  3170. * @param {Boolean=} forceAdd ensure add is emitted
  3171. * @param {Number=} priorDepth Level of subdirectories already traversed.
  3172. * @returns {Promise<void>}
  3173. */
  3174. async _addToFsEvents(path, transform, forceAdd, priorDepth) {
  3175. if (this.fsw.closed) {
  3176. return;
  3177. }
  3178. const opts = this.fsw.options;
  3179. const processPath = typeof transform === FUNCTION_TYPE$1 ? transform : IDENTITY_FN;
  3180. const wh = this.fsw._getWatchHelpers(path);
  3181. // evaluate what is at the path we're being asked to watch
  3182. try {
  3183. const stats = await statMethods[wh.statMethod](wh.watchPath);
  3184. if (this.fsw.closed) return;
  3185. if (this.fsw._isIgnored(wh.watchPath, stats)) {
  3186. throw null;
  3187. }
  3188. if (stats.isDirectory()) {
  3189. // emit addDir unless this is a glob parent
  3190. if (!wh.globFilter) this.emitAdd(processPath(path), stats, processPath, opts, forceAdd);
  3191. // don't recurse further if it would exceed depth setting
  3192. if (priorDepth && priorDepth > opts.depth) return;
  3193. // scan the contents of the dir
  3194. this.fsw._readdirp(wh.watchPath, {
  3195. fileFilter: entry => wh.filterPath(entry),
  3196. directoryFilter: entry => wh.filterDir(entry),
  3197. ...Depth(opts.depth - (priorDepth || 0))
  3198. }).on(STR_DATA, (entry) => {
  3199. // need to check filterPath on dirs b/c filterDir is less restrictive
  3200. if (this.fsw.closed) {
  3201. return;
  3202. }
  3203. if (entry.stats.isDirectory() && !wh.filterPath(entry)) return;
  3204. const joinedPath = sysPath$1.join(wh.watchPath, entry.path);
  3205. const {fullPath} = entry;
  3206. if (wh.followSymlinks && entry.stats.isSymbolicLink()) {
  3207. // preserve the current depth here since it can't be derived from
  3208. // real paths past the symlink
  3209. const curDepth = opts.depth === undefined ?
  3210. undefined : calcDepth(joinedPath, sysPath$1.resolve(wh.watchPath)) + 1;
  3211. this._handleFsEventsSymlink(joinedPath, fullPath, processPath, curDepth);
  3212. } else {
  3213. this.emitAdd(joinedPath, entry.stats, processPath, opts, forceAdd);
  3214. }
  3215. }).on(EV_ERROR$1, EMPTY_FN$1).on(STR_END$1, () => {
  3216. this.fsw._emitReady();
  3217. });
  3218. } else {
  3219. this.emitAdd(wh.watchPath, stats, processPath, opts, forceAdd);
  3220. this.fsw._emitReady();
  3221. }
  3222. } catch (error) {
  3223. if (!error || this.fsw._handleError(error)) {
  3224. // TODO: Strange thing: "should not choke on an ignored watch path" will be failed without 2 ready calls -__-
  3225. this.fsw._emitReady();
  3226. this.fsw._emitReady();
  3227. }
  3228. }
  3229. if (opts.persistent && forceAdd !== true) {
  3230. if (typeof transform === FUNCTION_TYPE$1) {
  3231. // realpath has already been resolved
  3232. this.initWatch(undefined, path, wh, processPath);
  3233. } else {
  3234. let realPath;
  3235. try {
  3236. realPath = await realpath(wh.watchPath);
  3237. } catch (e) {}
  3238. this.initWatch(realPath, path, wh, processPath);
  3239. }
  3240. }
  3241. }
  3242. }
  3243. fseventsHandler.exports = FsEventsHandler$1;
  3244. fseventsHandler.exports.canUse = canUse;
  3245. const { EventEmitter } = require$$0$3;
  3246. const fs = require$$0$1;
  3247. const sysPath = require$$0$2;
  3248. const { promisify } = require$$2;
  3249. const readdirp = readdirp_1;
  3250. const anymatch = anymatch$2.exports.default;
  3251. const globParent = globParent$1;
  3252. const isGlob = isGlob$2;
  3253. const braces = braces_1;
  3254. const normalizePath = normalizePath$2;
  3255. const NodeFsHandler = nodefsHandler;
  3256. const FsEventsHandler = fseventsHandler.exports;
  3257. const {
  3258. EV_ALL,
  3259. EV_READY,
  3260. EV_ADD,
  3261. EV_CHANGE,
  3262. EV_UNLINK,
  3263. EV_ADD_DIR,
  3264. EV_UNLINK_DIR,
  3265. EV_RAW,
  3266. EV_ERROR,
  3267. STR_CLOSE,
  3268. STR_END,
  3269. BACK_SLASH_RE,
  3270. DOUBLE_SLASH_RE,
  3271. SLASH_OR_BACK_SLASH_RE,
  3272. DOT_RE,
  3273. REPLACER_RE,
  3274. SLASH,
  3275. SLASH_SLASH,
  3276. BRACE_START,
  3277. BANG,
  3278. ONE_DOT,
  3279. TWO_DOTS,
  3280. GLOBSTAR,
  3281. SLASH_GLOBSTAR,
  3282. ANYMATCH_OPTS,
  3283. STRING_TYPE,
  3284. FUNCTION_TYPE,
  3285. EMPTY_STR,
  3286. EMPTY_FN,
  3287. isWindows,
  3288. isMacos,
  3289. isIBMi
  3290. } = constants;
  3291. const stat = promisify(fs.stat);
  3292. const readdir = promisify(fs.readdir);
  3293. /**
  3294. * @typedef {String} Path
  3295. * @typedef {'all'|'add'|'addDir'|'change'|'unlink'|'unlinkDir'|'raw'|'error'|'ready'} EventName
  3296. * @typedef {'readdir'|'watch'|'add'|'remove'|'change'} ThrottleType
  3297. */
  3298. /**
  3299. *
  3300. * @typedef {Object} WatchHelpers
  3301. * @property {Boolean} followSymlinks
  3302. * @property {'stat'|'lstat'} statMethod
  3303. * @property {Path} path
  3304. * @property {Path} watchPath
  3305. * @property {Function} entryPath
  3306. * @property {Boolean} hasGlob
  3307. * @property {Object} globFilter
  3308. * @property {Function} filterPath
  3309. * @property {Function} filterDir
  3310. */
  3311. const arrify = (value = []) => Array.isArray(value) ? value : [value];
  3312. const flatten = (list, result = []) => {
  3313. list.forEach(item => {
  3314. if (Array.isArray(item)) {
  3315. flatten(item, result);
  3316. } else {
  3317. result.push(item);
  3318. }
  3319. });
  3320. return result;
  3321. };
  3322. const unifyPaths = (paths_) => {
  3323. /**
  3324. * @type {Array<String>}
  3325. */
  3326. const paths = flatten(arrify(paths_));
  3327. if (!paths.every(p => typeof p === STRING_TYPE)) {
  3328. throw new TypeError(`Non-string provided as watch path: ${paths}`);
  3329. }
  3330. return paths.map(normalizePathToUnix);
  3331. };
  3332. // If SLASH_SLASH occurs at the beginning of path, it is not replaced
  3333. // because "//StoragePC/DrivePool/Movies" is a valid network path
  3334. const toUnix = (string) => {
  3335. let str = string.replace(BACK_SLASH_RE, SLASH);
  3336. let prepend = false;
  3337. if (str.startsWith(SLASH_SLASH)) {
  3338. prepend = true;
  3339. }
  3340. while (str.match(DOUBLE_SLASH_RE)) {
  3341. str = str.replace(DOUBLE_SLASH_RE, SLASH);
  3342. }
  3343. if (prepend) {
  3344. str = SLASH + str;
  3345. }
  3346. return str;
  3347. };
  3348. // Our version of upath.normalize
  3349. // TODO: this is not equal to path-normalize module - investigate why
  3350. const normalizePathToUnix = (path) => toUnix(sysPath.normalize(toUnix(path)));
  3351. const normalizeIgnored = (cwd = EMPTY_STR) => (path) => {
  3352. if (typeof path !== STRING_TYPE) return path;
  3353. return normalizePathToUnix(sysPath.isAbsolute(path) ? path : sysPath.join(cwd, path));
  3354. };
  3355. const getAbsolutePath = (path, cwd) => {
  3356. if (sysPath.isAbsolute(path)) {
  3357. return path;
  3358. }
  3359. if (path.startsWith(BANG)) {
  3360. return BANG + sysPath.join(cwd, path.slice(1));
  3361. }
  3362. return sysPath.join(cwd, path);
  3363. };
  3364. const undef = (opts, key) => opts[key] === undefined;
  3365. /**
  3366. * Directory entry.
  3367. * @property {Path} path
  3368. * @property {Set<Path>} items
  3369. */
  3370. class DirEntry {
  3371. /**
  3372. * @param {Path} dir
  3373. * @param {Function} removeWatcher
  3374. */
  3375. constructor(dir, removeWatcher) {
  3376. this.path = dir;
  3377. this._removeWatcher = removeWatcher;
  3378. /** @type {Set<Path>} */
  3379. this.items = new Set();
  3380. }
  3381. add(item) {
  3382. const {items} = this;
  3383. if (!items) return;
  3384. if (item !== ONE_DOT && item !== TWO_DOTS) items.add(item);
  3385. }
  3386. async remove(item) {
  3387. const {items} = this;
  3388. if (!items) return;
  3389. items.delete(item);
  3390. if (items.size > 0) return;
  3391. const dir = this.path;
  3392. try {
  3393. await readdir(dir);
  3394. } catch (err) {
  3395. if (this._removeWatcher) {
  3396. this._removeWatcher(sysPath.dirname(dir), sysPath.basename(dir));
  3397. }
  3398. }
  3399. }
  3400. has(item) {
  3401. const {items} = this;
  3402. if (!items) return;
  3403. return items.has(item);
  3404. }
  3405. /**
  3406. * @returns {Array<String>}
  3407. */
  3408. getChildren() {
  3409. const {items} = this;
  3410. if (!items) return;
  3411. return [...items.values()];
  3412. }
  3413. dispose() {
  3414. this.items.clear();
  3415. delete this.path;
  3416. delete this._removeWatcher;
  3417. delete this.items;
  3418. Object.freeze(this);
  3419. }
  3420. }
  3421. const STAT_METHOD_F = 'stat';
  3422. const STAT_METHOD_L = 'lstat';
  3423. class WatchHelper {
  3424. constructor(path, watchPath, follow, fsw) {
  3425. this.fsw = fsw;
  3426. this.path = path = path.replace(REPLACER_RE, EMPTY_STR);
  3427. this.watchPath = watchPath;
  3428. this.fullWatchPath = sysPath.resolve(watchPath);
  3429. this.hasGlob = watchPath !== path;
  3430. /** @type {object|boolean} */
  3431. if (path === EMPTY_STR) this.hasGlob = false;
  3432. this.globSymlink = this.hasGlob && follow ? undefined : false;
  3433. this.globFilter = this.hasGlob ? anymatch(path, undefined, ANYMATCH_OPTS) : false;
  3434. this.dirParts = this.getDirParts(path);
  3435. this.dirParts.forEach((parts) => {
  3436. if (parts.length > 1) parts.pop();
  3437. });
  3438. this.followSymlinks = follow;
  3439. this.statMethod = follow ? STAT_METHOD_F : STAT_METHOD_L;
  3440. }
  3441. checkGlobSymlink(entry) {
  3442. // only need to resolve once
  3443. // first entry should always have entry.parentDir === EMPTY_STR
  3444. if (this.globSymlink === undefined) {
  3445. this.globSymlink = entry.fullParentDir === this.fullWatchPath ?
  3446. false : {realPath: entry.fullParentDir, linkPath: this.fullWatchPath};
  3447. }
  3448. if (this.globSymlink) {
  3449. return entry.fullPath.replace(this.globSymlink.realPath, this.globSymlink.linkPath);
  3450. }
  3451. return entry.fullPath;
  3452. }
  3453. entryPath(entry) {
  3454. return sysPath.join(this.watchPath,
  3455. sysPath.relative(this.watchPath, this.checkGlobSymlink(entry))
  3456. );
  3457. }
  3458. filterPath(entry) {
  3459. const {stats} = entry;
  3460. if (stats && stats.isSymbolicLink()) return this.filterDir(entry);
  3461. const resolvedPath = this.entryPath(entry);
  3462. const matchesGlob = this.hasGlob && typeof this.globFilter === FUNCTION_TYPE ?
  3463. this.globFilter(resolvedPath) : true;
  3464. return matchesGlob &&
  3465. this.fsw._isntIgnored(resolvedPath, stats) &&
  3466. this.fsw._hasReadPermissions(stats);
  3467. }
  3468. getDirParts(path) {
  3469. if (!this.hasGlob) return [];
  3470. const parts = [];
  3471. const expandedPath = path.includes(BRACE_START) ? braces.expand(path) : [path];
  3472. expandedPath.forEach((path) => {
  3473. parts.push(sysPath.relative(this.watchPath, path).split(SLASH_OR_BACK_SLASH_RE));
  3474. });
  3475. return parts;
  3476. }
  3477. filterDir(entry) {
  3478. if (this.hasGlob) {
  3479. const entryParts = this.getDirParts(this.checkGlobSymlink(entry));
  3480. let globstar = false;
  3481. this.unmatchedGlob = !this.dirParts.some((parts) => {
  3482. return parts.every((part, i) => {
  3483. if (part === GLOBSTAR) globstar = true;
  3484. return globstar || !entryParts[0][i] || anymatch(part, entryParts[0][i], ANYMATCH_OPTS);
  3485. });
  3486. });
  3487. }
  3488. return !this.unmatchedGlob && this.fsw._isntIgnored(this.entryPath(entry), entry.stats);
  3489. }
  3490. }
  3491. /**
  3492. * Watches files & directories for changes. Emitted events:
  3493. * `add`, `addDir`, `change`, `unlink`, `unlinkDir`, `all`, `error`
  3494. *
  3495. * new FSWatcher()
  3496. * .add(directories)
  3497. * .on('add', path => log('File', path, 'was added'))
  3498. */
  3499. class FSWatcher extends EventEmitter {
  3500. // Not indenting methods for history sake; for now.
  3501. constructor(_opts) {
  3502. super();
  3503. const opts = {};
  3504. if (_opts) Object.assign(opts, _opts); // for frozen objects
  3505. /** @type {Map<String, DirEntry>} */
  3506. this._watched = new Map();
  3507. /** @type {Map<String, Array>} */
  3508. this._closers = new Map();
  3509. /** @type {Set<String>} */
  3510. this._ignoredPaths = new Set();
  3511. /** @type {Map<ThrottleType, Map>} */
  3512. this._throttled = new Map();
  3513. /** @type {Map<Path, String|Boolean>} */
  3514. this._symlinkPaths = new Map();
  3515. this._streams = new Set();
  3516. this.closed = false;
  3517. // Set up default options.
  3518. if (undef(opts, 'persistent')) opts.persistent = true;
  3519. if (undef(opts, 'ignoreInitial')) opts.ignoreInitial = false;
  3520. if (undef(opts, 'ignorePermissionErrors')) opts.ignorePermissionErrors = false;
  3521. if (undef(opts, 'interval')) opts.interval = 100;
  3522. if (undef(opts, 'binaryInterval')) opts.binaryInterval = 300;
  3523. if (undef(opts, 'disableGlobbing')) opts.disableGlobbing = false;
  3524. opts.enableBinaryInterval = opts.binaryInterval !== opts.interval;
  3525. // Enable fsevents on OS X when polling isn't explicitly enabled.
  3526. if (undef(opts, 'useFsEvents')) opts.useFsEvents = !opts.usePolling;
  3527. // If we can't use fsevents, ensure the options reflect it's disabled.
  3528. const canUseFsEvents = FsEventsHandler.canUse();
  3529. if (!canUseFsEvents) opts.useFsEvents = false;
  3530. // Use polling on Mac if not using fsevents.
  3531. // Other platforms use non-polling fs_watch.
  3532. if (undef(opts, 'usePolling') && !opts.useFsEvents) {
  3533. opts.usePolling = isMacos;
  3534. }
  3535. // Always default to polling on IBM i because fs.watch() is not available on IBM i.
  3536. if(isIBMi) {
  3537. opts.usePolling = true;
  3538. }
  3539. // Global override (useful for end-developers that need to force polling for all
  3540. // instances of chokidar, regardless of usage/dependency depth)
  3541. const envPoll = process.env.CHOKIDAR_USEPOLLING;
  3542. if (envPoll !== undefined) {
  3543. const envLower = envPoll.toLowerCase();
  3544. if (envLower === 'false' || envLower === '0') {
  3545. opts.usePolling = false;
  3546. } else if (envLower === 'true' || envLower === '1') {
  3547. opts.usePolling = true;
  3548. } else {
  3549. opts.usePolling = !!envLower;
  3550. }
  3551. }
  3552. const envInterval = process.env.CHOKIDAR_INTERVAL;
  3553. if (envInterval) {
  3554. opts.interval = Number.parseInt(envInterval, 10);
  3555. }
  3556. // Editor atomic write normalization enabled by default with fs.watch
  3557. if (undef(opts, 'atomic')) opts.atomic = !opts.usePolling && !opts.useFsEvents;
  3558. if (opts.atomic) this._pendingUnlinks = new Map();
  3559. if (undef(opts, 'followSymlinks')) opts.followSymlinks = true;
  3560. if (undef(opts, 'awaitWriteFinish')) opts.awaitWriteFinish = false;
  3561. if (opts.awaitWriteFinish === true) opts.awaitWriteFinish = {};
  3562. const awf = opts.awaitWriteFinish;
  3563. if (awf) {
  3564. if (!awf.stabilityThreshold) awf.stabilityThreshold = 2000;
  3565. if (!awf.pollInterval) awf.pollInterval = 100;
  3566. this._pendingWrites = new Map();
  3567. }
  3568. if (opts.ignored) opts.ignored = arrify(opts.ignored);
  3569. let readyCalls = 0;
  3570. this._emitReady = () => {
  3571. readyCalls++;
  3572. if (readyCalls >= this._readyCount) {
  3573. this._emitReady = EMPTY_FN;
  3574. this._readyEmitted = true;
  3575. // use process.nextTick to allow time for listener to be bound
  3576. process.nextTick(() => this.emit(EV_READY));
  3577. }
  3578. };
  3579. this._emitRaw = (...args) => this.emit(EV_RAW, ...args);
  3580. this._readyEmitted = false;
  3581. this.options = opts;
  3582. // Initialize with proper watcher.
  3583. if (opts.useFsEvents) {
  3584. this._fsEventsHandler = new FsEventsHandler(this);
  3585. } else {
  3586. this._nodeFsHandler = new NodeFsHandler(this);
  3587. }
  3588. // You’re frozen when your heart’s not open.
  3589. Object.freeze(opts);
  3590. }
  3591. // Public methods
  3592. /**
  3593. * Adds paths to be watched on an existing FSWatcher instance
  3594. * @param {Path|Array<Path>} paths_
  3595. * @param {String=} _origAdd private; for handling non-existent paths to be watched
  3596. * @param {Boolean=} _internal private; indicates a non-user add
  3597. * @returns {FSWatcher} for chaining
  3598. */
  3599. add(paths_, _origAdd, _internal) {
  3600. const {cwd, disableGlobbing} = this.options;
  3601. this.closed = false;
  3602. let paths = unifyPaths(paths_);
  3603. if (cwd) {
  3604. paths = paths.map((path) => {
  3605. const absPath = getAbsolutePath(path, cwd);
  3606. // Check `path` instead of `absPath` because the cwd portion can't be a glob
  3607. if (disableGlobbing || !isGlob(path)) {
  3608. return absPath;
  3609. }
  3610. return normalizePath(absPath);
  3611. });
  3612. }
  3613. // set aside negated glob strings
  3614. paths = paths.filter((path) => {
  3615. if (path.startsWith(BANG)) {
  3616. this._ignoredPaths.add(path.slice(1));
  3617. return false;
  3618. }
  3619. // if a path is being added that was previously ignored, stop ignoring it
  3620. this._ignoredPaths.delete(path);
  3621. this._ignoredPaths.delete(path + SLASH_GLOBSTAR);
  3622. // reset the cached userIgnored anymatch fn
  3623. // to make ignoredPaths changes effective
  3624. this._userIgnored = undefined;
  3625. return true;
  3626. });
  3627. if (this.options.useFsEvents && this._fsEventsHandler) {
  3628. if (!this._readyCount) this._readyCount = paths.length;
  3629. if (this.options.persistent) this._readyCount *= 2;
  3630. paths.forEach((path) => this._fsEventsHandler._addToFsEvents(path));
  3631. } else {
  3632. if (!this._readyCount) this._readyCount = 0;
  3633. this._readyCount += paths.length;
  3634. Promise.all(
  3635. paths.map(async path => {
  3636. const res = await this._nodeFsHandler._addToNodeFs(path, !_internal, 0, 0, _origAdd);
  3637. if (res) this._emitReady();
  3638. return res;
  3639. })
  3640. ).then(results => {
  3641. if (this.closed) return;
  3642. results.filter(item => item).forEach(item => {
  3643. this.add(sysPath.dirname(item), sysPath.basename(_origAdd || item));
  3644. });
  3645. });
  3646. }
  3647. return this;
  3648. }
  3649. /**
  3650. * Close watchers or start ignoring events from specified paths.
  3651. * @param {Path|Array<Path>} paths_ - string or array of strings, file/directory paths and/or globs
  3652. * @returns {FSWatcher} for chaining
  3653. */
  3654. unwatch(paths_) {
  3655. if (this.closed) return this;
  3656. const paths = unifyPaths(paths_);
  3657. const {cwd} = this.options;
  3658. paths.forEach((path) => {
  3659. // convert to absolute path unless relative path already matches
  3660. if (!sysPath.isAbsolute(path) && !this._closers.has(path)) {
  3661. if (cwd) path = sysPath.join(cwd, path);
  3662. path = sysPath.resolve(path);
  3663. }
  3664. this._closePath(path);
  3665. this._ignoredPaths.add(path);
  3666. if (this._watched.has(path)) {
  3667. this._ignoredPaths.add(path + SLASH_GLOBSTAR);
  3668. }
  3669. // reset the cached userIgnored anymatch fn
  3670. // to make ignoredPaths changes effective
  3671. this._userIgnored = undefined;
  3672. });
  3673. return this;
  3674. }
  3675. /**
  3676. * Close watchers and remove all listeners from watched paths.
  3677. * @returns {Promise<void>}.
  3678. */
  3679. close() {
  3680. if (this.closed) return this._closePromise;
  3681. this.closed = true;
  3682. // Memory management.
  3683. this.removeAllListeners();
  3684. const closers = [];
  3685. this._closers.forEach(closerList => closerList.forEach(closer => {
  3686. const promise = closer();
  3687. if (promise instanceof Promise) closers.push(promise);
  3688. }));
  3689. this._streams.forEach(stream => stream.destroy());
  3690. this._userIgnored = undefined;
  3691. this._readyCount = 0;
  3692. this._readyEmitted = false;
  3693. this._watched.forEach(dirent => dirent.dispose());
  3694. ['closers', 'watched', 'streams', 'symlinkPaths', 'throttled'].forEach(key => {
  3695. this[`_${key}`].clear();
  3696. });
  3697. this._closePromise = closers.length ? Promise.all(closers).then(() => undefined) : Promise.resolve();
  3698. return this._closePromise;
  3699. }
  3700. /**
  3701. * Expose list of watched paths
  3702. * @returns {Object} for chaining
  3703. */
  3704. getWatched() {
  3705. const watchList = {};
  3706. this._watched.forEach((entry, dir) => {
  3707. const key = this.options.cwd ? sysPath.relative(this.options.cwd, dir) : dir;
  3708. watchList[key || ONE_DOT] = entry.getChildren().sort();
  3709. });
  3710. return watchList;
  3711. }
  3712. emitWithAll(event, args) {
  3713. this.emit(...args);
  3714. if (event !== EV_ERROR) this.emit(EV_ALL, ...args);
  3715. }
  3716. // Common helpers
  3717. // --------------
  3718. /**
  3719. * Normalize and emit events.
  3720. * Calling _emit DOES NOT MEAN emit() would be called!
  3721. * @param {EventName} event Type of event
  3722. * @param {Path} path File or directory path
  3723. * @param {*=} val1 arguments to be passed with event
  3724. * @param {*=} val2
  3725. * @param {*=} val3
  3726. * @returns the error if defined, otherwise the value of the FSWatcher instance's `closed` flag
  3727. */
  3728. async _emit(event, path, val1, val2, val3) {
  3729. if (this.closed) return;
  3730. const opts = this.options;
  3731. if (isWindows) path = sysPath.normalize(path);
  3732. if (opts.cwd) path = sysPath.relative(opts.cwd, path);
  3733. /** @type Array<any> */
  3734. const args = [event, path];
  3735. if (val3 !== undefined) args.push(val1, val2, val3);
  3736. else if (val2 !== undefined) args.push(val1, val2);
  3737. else if (val1 !== undefined) args.push(val1);
  3738. const awf = opts.awaitWriteFinish;
  3739. let pw;
  3740. if (awf && (pw = this._pendingWrites.get(path))) {
  3741. pw.lastChange = new Date();
  3742. return this;
  3743. }
  3744. if (opts.atomic) {
  3745. if (event === EV_UNLINK) {
  3746. this._pendingUnlinks.set(path, args);
  3747. setTimeout(() => {
  3748. this._pendingUnlinks.forEach((entry, path) => {
  3749. this.emit(...entry);
  3750. this.emit(EV_ALL, ...entry);
  3751. this._pendingUnlinks.delete(path);
  3752. });
  3753. }, typeof opts.atomic === 'number' ? opts.atomic : 100);
  3754. return this;
  3755. }
  3756. if (event === EV_ADD && this._pendingUnlinks.has(path)) {
  3757. event = args[0] = EV_CHANGE;
  3758. this._pendingUnlinks.delete(path);
  3759. }
  3760. }
  3761. if (awf && (event === EV_ADD || event === EV_CHANGE) && this._readyEmitted) {
  3762. const awfEmit = (err, stats) => {
  3763. if (err) {
  3764. event = args[0] = EV_ERROR;
  3765. args[1] = err;
  3766. this.emitWithAll(event, args);
  3767. } else if (stats) {
  3768. // if stats doesn't exist the file must have been deleted
  3769. if (args.length > 2) {
  3770. args[2] = stats;
  3771. } else {
  3772. args.push(stats);
  3773. }
  3774. this.emitWithAll(event, args);
  3775. }
  3776. };
  3777. this._awaitWriteFinish(path, awf.stabilityThreshold, event, awfEmit);
  3778. return this;
  3779. }
  3780. if (event === EV_CHANGE) {
  3781. const isThrottled = !this._throttle(EV_CHANGE, path, 50);
  3782. if (isThrottled) return this;
  3783. }
  3784. if (opts.alwaysStat && val1 === undefined &&
  3785. (event === EV_ADD || event === EV_ADD_DIR || event === EV_CHANGE)
  3786. ) {
  3787. const fullPath = opts.cwd ? sysPath.join(opts.cwd, path) : path;
  3788. let stats;
  3789. try {
  3790. stats = await stat(fullPath);
  3791. } catch (err) {}
  3792. // Suppress event when fs_stat fails, to avoid sending undefined 'stat'
  3793. if (!stats || this.closed) return;
  3794. args.push(stats);
  3795. }
  3796. this.emitWithAll(event, args);
  3797. return this;
  3798. }
  3799. /**
  3800. * Common handler for errors
  3801. * @param {Error} error
  3802. * @returns {Error|Boolean} The error if defined, otherwise the value of the FSWatcher instance's `closed` flag
  3803. */
  3804. _handleError(error) {
  3805. const code = error && error.code;
  3806. if (error && code !== 'ENOENT' && code !== 'ENOTDIR' &&
  3807. (!this.options.ignorePermissionErrors || (code !== 'EPERM' && code !== 'EACCES'))
  3808. ) {
  3809. this.emit(EV_ERROR, error);
  3810. }
  3811. return error || this.closed;
  3812. }
  3813. /**
  3814. * Helper utility for throttling
  3815. * @param {ThrottleType} actionType type being throttled
  3816. * @param {Path} path being acted upon
  3817. * @param {Number} timeout duration of time to suppress duplicate actions
  3818. * @returns {Object|false} tracking object or false if action should be suppressed
  3819. */
  3820. _throttle(actionType, path, timeout) {
  3821. if (!this._throttled.has(actionType)) {
  3822. this._throttled.set(actionType, new Map());
  3823. }
  3824. /** @type {Map<Path, Object>} */
  3825. const action = this._throttled.get(actionType);
  3826. /** @type {Object} */
  3827. const actionPath = action.get(path);
  3828. if (actionPath) {
  3829. actionPath.count++;
  3830. return false;
  3831. }
  3832. let timeoutObject;
  3833. const clear = () => {
  3834. const item = action.get(path);
  3835. const count = item ? item.count : 0;
  3836. action.delete(path);
  3837. clearTimeout(timeoutObject);
  3838. if (item) clearTimeout(item.timeoutObject);
  3839. return count;
  3840. };
  3841. timeoutObject = setTimeout(clear, timeout);
  3842. const thr = {timeoutObject, clear, count: 0};
  3843. action.set(path, thr);
  3844. return thr;
  3845. }
  3846. _incrReadyCount() {
  3847. return this._readyCount++;
  3848. }
  3849. /**
  3850. * Awaits write operation to finish.
  3851. * Polls a newly created file for size variations. When files size does not change for 'threshold' milliseconds calls callback.
  3852. * @param {Path} path being acted upon
  3853. * @param {Number} threshold Time in milliseconds a file size must be fixed before acknowledging write OP is finished
  3854. * @param {EventName} event
  3855. * @param {Function} awfEmit Callback to be called when ready for event to be emitted.
  3856. */
  3857. _awaitWriteFinish(path, threshold, event, awfEmit) {
  3858. let timeoutHandler;
  3859. let fullPath = path;
  3860. if (this.options.cwd && !sysPath.isAbsolute(path)) {
  3861. fullPath = sysPath.join(this.options.cwd, path);
  3862. }
  3863. const now = new Date();
  3864. const awaitWriteFinish = (prevStat) => {
  3865. fs.stat(fullPath, (err, curStat) => {
  3866. if (err || !this._pendingWrites.has(path)) {
  3867. if (err && err.code !== 'ENOENT') awfEmit(err);
  3868. return;
  3869. }
  3870. const now = Number(new Date());
  3871. if (prevStat && curStat.size !== prevStat.size) {
  3872. this._pendingWrites.get(path).lastChange = now;
  3873. }
  3874. const pw = this._pendingWrites.get(path);
  3875. const df = now - pw.lastChange;
  3876. if (df >= threshold) {
  3877. this._pendingWrites.delete(path);
  3878. awfEmit(undefined, curStat);
  3879. } else {
  3880. timeoutHandler = setTimeout(
  3881. awaitWriteFinish,
  3882. this.options.awaitWriteFinish.pollInterval,
  3883. curStat
  3884. );
  3885. }
  3886. });
  3887. };
  3888. if (!this._pendingWrites.has(path)) {
  3889. this._pendingWrites.set(path, {
  3890. lastChange: now,
  3891. cancelWait: () => {
  3892. this._pendingWrites.delete(path);
  3893. clearTimeout(timeoutHandler);
  3894. return event;
  3895. }
  3896. });
  3897. timeoutHandler = setTimeout(
  3898. awaitWriteFinish,
  3899. this.options.awaitWriteFinish.pollInterval
  3900. );
  3901. }
  3902. }
  3903. _getGlobIgnored() {
  3904. return [...this._ignoredPaths.values()];
  3905. }
  3906. /**
  3907. * Determines whether user has asked to ignore this path.
  3908. * @param {Path} path filepath or dir
  3909. * @param {fs.Stats=} stats result of fs.stat
  3910. * @returns {Boolean}
  3911. */
  3912. _isIgnored(path, stats) {
  3913. if (this.options.atomic && DOT_RE.test(path)) return true;
  3914. if (!this._userIgnored) {
  3915. const {cwd} = this.options;
  3916. const ign = this.options.ignored;
  3917. const ignored = ign && ign.map(normalizeIgnored(cwd));
  3918. const paths = arrify(ignored)
  3919. .filter((path) => typeof path === STRING_TYPE && !isGlob(path))
  3920. .map((path) => path + SLASH_GLOBSTAR);
  3921. const list = this._getGlobIgnored().map(normalizeIgnored(cwd)).concat(ignored, paths);
  3922. this._userIgnored = anymatch(list, undefined, ANYMATCH_OPTS);
  3923. }
  3924. return this._userIgnored([path, stats]);
  3925. }
  3926. _isntIgnored(path, stat) {
  3927. return !this._isIgnored(path, stat);
  3928. }
  3929. /**
  3930. * Provides a set of common helpers and properties relating to symlink and glob handling.
  3931. * @param {Path} path file, directory, or glob pattern being watched
  3932. * @param {Number=} depth at any depth > 0, this isn't a glob
  3933. * @returns {WatchHelper} object containing helpers for this path
  3934. */
  3935. _getWatchHelpers(path, depth) {
  3936. const watchPath = depth || this.options.disableGlobbing || !isGlob(path) ? path : globParent(path);
  3937. const follow = this.options.followSymlinks;
  3938. return new WatchHelper(path, watchPath, follow, this);
  3939. }
  3940. // Directory helpers
  3941. // -----------------
  3942. /**
  3943. * Provides directory tracking objects
  3944. * @param {String} directory path of the directory
  3945. * @returns {DirEntry} the directory's tracking object
  3946. */
  3947. _getWatchedDir(directory) {
  3948. if (!this._boundRemove) this._boundRemove = this._remove.bind(this);
  3949. const dir = sysPath.resolve(directory);
  3950. if (!this._watched.has(dir)) this._watched.set(dir, new DirEntry(dir, this._boundRemove));
  3951. return this._watched.get(dir);
  3952. }
  3953. // File helpers
  3954. // ------------
  3955. /**
  3956. * Check for read permissions.
  3957. * Based on this answer on SO: https://stackoverflow.com/a/11781404/1358405
  3958. * @param {fs.Stats} stats - object, result of fs_stat
  3959. * @returns {Boolean} indicates whether the file can be read
  3960. */
  3961. _hasReadPermissions(stats) {
  3962. if (this.options.ignorePermissionErrors) return true;
  3963. // stats.mode may be bigint
  3964. const md = stats && Number.parseInt(stats.mode, 10);
  3965. const st = md & 0o777;
  3966. const it = Number.parseInt(st.toString(8)[0], 10);
  3967. return Boolean(4 & it);
  3968. }
  3969. /**
  3970. * Handles emitting unlink events for
  3971. * files and directories, and via recursion, for
  3972. * files and directories within directories that are unlinked
  3973. * @param {String} directory within which the following item is located
  3974. * @param {String} item base path of item/directory
  3975. * @returns {void}
  3976. */
  3977. _remove(directory, item, isDirectory) {
  3978. // if what is being deleted is a directory, get that directory's paths
  3979. // for recursive deleting and cleaning of watched object
  3980. // if it is not a directory, nestedDirectoryChildren will be empty array
  3981. const path = sysPath.join(directory, item);
  3982. const fullPath = sysPath.resolve(path);
  3983. isDirectory = isDirectory != null
  3984. ? isDirectory
  3985. : this._watched.has(path) || this._watched.has(fullPath);
  3986. // prevent duplicate handling in case of arriving here nearly simultaneously
  3987. // via multiple paths (such as _handleFile and _handleDir)
  3988. if (!this._throttle('remove', path, 100)) return;
  3989. // if the only watched file is removed, watch for its return
  3990. if (!isDirectory && !this.options.useFsEvents && this._watched.size === 1) {
  3991. this.add(directory, item, true);
  3992. }
  3993. // This will create a new entry in the watched object in either case
  3994. // so we got to do the directory check beforehand
  3995. const wp = this._getWatchedDir(path);
  3996. const nestedDirectoryChildren = wp.getChildren();
  3997. // Recursively remove children directories / files.
  3998. nestedDirectoryChildren.forEach(nested => this._remove(path, nested));
  3999. // Check if item was on the watched list and remove it
  4000. const parent = this._getWatchedDir(directory);
  4001. const wasTracked = parent.has(item);
  4002. parent.remove(item);
  4003. // Fixes issue #1042 -> Relative paths were detected and added as symlinks
  4004. // (https://github.com/paulmillr/chokidar/blob/e1753ddbc9571bdc33b4a4af172d52cb6e611c10/lib/nodefs-handler.js#L612),
  4005. // but never removed from the map in case the path was deleted.
  4006. // This leads to an incorrect state if the path was recreated:
  4007. // https://github.com/paulmillr/chokidar/blob/e1753ddbc9571bdc33b4a4af172d52cb6e611c10/lib/nodefs-handler.js#L553
  4008. if (this._symlinkPaths.has(fullPath)) {
  4009. this._symlinkPaths.delete(fullPath);
  4010. }
  4011. // If we wait for this file to be fully written, cancel the wait.
  4012. let relPath = path;
  4013. if (this.options.cwd) relPath = sysPath.relative(this.options.cwd, path);
  4014. if (this.options.awaitWriteFinish && this._pendingWrites.has(relPath)) {
  4015. const event = this._pendingWrites.get(relPath).cancelWait();
  4016. if (event === EV_ADD) return;
  4017. }
  4018. // The Entry will either be a directory that just got removed
  4019. // or a bogus entry to a file, in either case we have to remove it
  4020. this._watched.delete(path);
  4021. this._watched.delete(fullPath);
  4022. const eventName = isDirectory ? EV_UNLINK_DIR : EV_UNLINK;
  4023. if (wasTracked && !this._isIgnored(path)) this._emit(eventName, path);
  4024. // Avoid conflicts if we later create another file with the same name
  4025. if (!this.options.useFsEvents) {
  4026. this._closePath(path);
  4027. }
  4028. }
  4029. /**
  4030. * Closes all watchers for a path
  4031. * @param {Path} path
  4032. */
  4033. _closePath(path) {
  4034. this._closeFile(path);
  4035. const dir = sysPath.dirname(path);
  4036. this._getWatchedDir(dir).remove(sysPath.basename(path));
  4037. }
  4038. /**
  4039. * Closes only file-specific watchers
  4040. * @param {Path} path
  4041. */
  4042. _closeFile(path) {
  4043. const closers = this._closers.get(path);
  4044. if (!closers) return;
  4045. closers.forEach(closer => closer());
  4046. this._closers.delete(path);
  4047. }
  4048. /**
  4049. *
  4050. * @param {Path} path
  4051. * @param {Function} closer
  4052. */
  4053. _addPathCloser(path, closer) {
  4054. if (!closer) return;
  4055. let list = this._closers.get(path);
  4056. if (!list) {
  4057. list = [];
  4058. this._closers.set(path, list);
  4059. }
  4060. list.push(closer);
  4061. }
  4062. _readdirp(root, opts) {
  4063. if (this.closed) return;
  4064. const options = {type: EV_ALL, alwaysStat: true, lstat: true, ...opts};
  4065. let stream = readdirp(root, options);
  4066. this._streams.add(stream);
  4067. stream.once(STR_CLOSE, () => {
  4068. stream = undefined;
  4069. });
  4070. stream.once(STR_END, () => {
  4071. if (stream) {
  4072. this._streams.delete(stream);
  4073. stream = undefined;
  4074. }
  4075. });
  4076. return stream;
  4077. }
  4078. }
  4079. // Export FSWatcher class
  4080. chokidar.FSWatcher = FSWatcher;
  4081. /**
  4082. * Instantiates watcher with paths to be tracked.
  4083. * @param {String|Array<String>} paths file/directory paths and/or globs
  4084. * @param {Object=} options chokidar opts
  4085. * @returns an instance of FSWatcher for chaining.
  4086. */
  4087. const watch = (paths, options) => {
  4088. const watcher = new FSWatcher(options);
  4089. watcher.add(paths);
  4090. return watcher;
  4091. };
  4092. chokidar.watch = watch;
  4093. class FileWatcher {
  4094. constructor(task, chokidarOptions) {
  4095. this.transformWatchers = new Map();
  4096. this.chokidarOptions = chokidarOptions;
  4097. this.task = task;
  4098. this.watcher = this.createWatcher(null);
  4099. }
  4100. close() {
  4101. this.watcher.close();
  4102. for (const watcher of this.transformWatchers.values()) {
  4103. watcher.close();
  4104. }
  4105. }
  4106. unwatch(id) {
  4107. this.watcher.unwatch(id);
  4108. const transformWatcher = this.transformWatchers.get(id);
  4109. if (transformWatcher) {
  4110. this.transformWatchers.delete(id);
  4111. transformWatcher.close();
  4112. }
  4113. }
  4114. watch(id, isTransformDependency) {
  4115. var _a;
  4116. if (isTransformDependency) {
  4117. const watcher = (_a = this.transformWatchers.get(id)) !== null && _a !== void 0 ? _a : this.createWatcher(id);
  4118. watcher.add(id);
  4119. this.transformWatchers.set(id, watcher);
  4120. }
  4121. else {
  4122. this.watcher.add(id);
  4123. }
  4124. }
  4125. createWatcher(transformWatcherId) {
  4126. const task = this.task;
  4127. const isLinux = platform() === 'linux';
  4128. const isTransformDependency = transformWatcherId !== null;
  4129. const handleChange = (id, event) => {
  4130. const changedId = transformWatcherId || id;
  4131. if (isLinux) {
  4132. // unwatching and watching fixes an issue with chokidar where on certain systems,
  4133. // a file that was unlinked and immediately recreated would create a change event
  4134. // but then no longer any further events
  4135. watcher.unwatch(changedId);
  4136. watcher.add(changedId);
  4137. }
  4138. task.invalidate(changedId, { event, isTransformDependency });
  4139. };
  4140. const watcher = chokidar
  4141. .watch([], this.chokidarOptions)
  4142. .on('add', id => handleChange(id, 'create'))
  4143. .on('change', id => handleChange(id, 'update'))
  4144. .on('unlink', id => handleChange(id, 'delete'));
  4145. return watcher;
  4146. }
  4147. }
  4148. const eventsRewrites = {
  4149. create: {
  4150. create: 'buggy',
  4151. delete: null,
  4152. update: 'create'
  4153. },
  4154. delete: {
  4155. create: 'update',
  4156. delete: 'buggy',
  4157. update: 'buggy'
  4158. },
  4159. update: {
  4160. create: 'buggy',
  4161. delete: 'delete',
  4162. update: 'update'
  4163. }
  4164. };
  4165. class Watcher {
  4166. constructor(configs, emitter) {
  4167. this.buildDelay = 0;
  4168. this.buildTimeout = null;
  4169. this.invalidatedIds = new Map();
  4170. this.rerun = false;
  4171. this.running = true;
  4172. this.emitter = emitter;
  4173. emitter.close = this.close.bind(this);
  4174. this.tasks = configs.map(config => new Task(this, config));
  4175. this.buildDelay = configs.reduce((buildDelay, { watch }) => watch && typeof watch.buildDelay === 'number'
  4176. ? Math.max(buildDelay, watch.buildDelay)
  4177. : buildDelay, this.buildDelay);
  4178. process$1.nextTick(() => this.run());
  4179. }
  4180. async close() {
  4181. if (this.buildTimeout)
  4182. clearTimeout(this.buildTimeout);
  4183. for (const task of this.tasks) {
  4184. task.close();
  4185. }
  4186. await this.emitter.emitAndAwait('close');
  4187. this.emitter.removeAllListeners();
  4188. }
  4189. invalidate(file) {
  4190. if (file) {
  4191. const prevEvent = this.invalidatedIds.get(file.id);
  4192. const event = prevEvent ? eventsRewrites[prevEvent][file.event] : file.event;
  4193. if (event === 'buggy') {
  4194. //TODO: throws or warn? Currently just ignore, uses new event
  4195. this.invalidatedIds.set(file.id, file.event);
  4196. }
  4197. else if (event === null) {
  4198. this.invalidatedIds.delete(file.id);
  4199. }
  4200. else {
  4201. this.invalidatedIds.set(file.id, event);
  4202. }
  4203. }
  4204. if (this.running) {
  4205. this.rerun = true;
  4206. return;
  4207. }
  4208. if (this.buildTimeout)
  4209. clearTimeout(this.buildTimeout);
  4210. this.buildTimeout = setTimeout(async () => {
  4211. this.buildTimeout = null;
  4212. try {
  4213. await Promise.all([...this.invalidatedIds].map(([id, event]) => this.emitter.emitAndAwait('change', id, { event })));
  4214. this.invalidatedIds.clear();
  4215. this.emitter.emit('restart');
  4216. this.emitter.removeAwaited();
  4217. this.run();
  4218. }
  4219. catch (error) {
  4220. this.invalidatedIds.clear();
  4221. this.emitter.emit('event', {
  4222. code: 'ERROR',
  4223. error,
  4224. result: null
  4225. });
  4226. this.emitter.emit('event', {
  4227. code: 'END'
  4228. });
  4229. }
  4230. }, this.buildDelay);
  4231. }
  4232. async run() {
  4233. this.running = true;
  4234. this.emitter.emit('event', {
  4235. code: 'START'
  4236. });
  4237. for (const task of this.tasks) {
  4238. await task.run();
  4239. }
  4240. this.running = false;
  4241. this.emitter.emit('event', {
  4242. code: 'END'
  4243. });
  4244. if (this.rerun) {
  4245. this.rerun = false;
  4246. this.invalidate();
  4247. }
  4248. }
  4249. }
  4250. class Task {
  4251. constructor(watcher, config) {
  4252. this.cache = { modules: [] };
  4253. this.watchFiles = [];
  4254. this.closed = false;
  4255. this.invalidated = true;
  4256. this.watched = new Set();
  4257. this.watcher = watcher;
  4258. this.skipWrite = Boolean(config.watch && config.watch.skipWrite);
  4259. this.options = mergeOptions(config);
  4260. this.outputs = this.options.output;
  4261. this.outputFiles = this.outputs.map(output => {
  4262. if (output.file || output.dir)
  4263. return resolve(output.file || output.dir);
  4264. return undefined;
  4265. });
  4266. const watchOptions = this.options.watch || {};
  4267. this.filter = createFilter(watchOptions.include, watchOptions.exclude);
  4268. this.fileWatcher = new FileWatcher(this, {
  4269. ...watchOptions.chokidar,
  4270. disableGlobbing: true,
  4271. ignoreInitial: true
  4272. });
  4273. }
  4274. close() {
  4275. this.closed = true;
  4276. this.fileWatcher.close();
  4277. }
  4278. invalidate(id, details) {
  4279. this.invalidated = true;
  4280. if (details.isTransformDependency) {
  4281. for (const module of this.cache.modules) {
  4282. if (!module.transformDependencies.includes(id))
  4283. continue;
  4284. // effective invalidation
  4285. module.originalCode = null;
  4286. }
  4287. }
  4288. this.watcher.invalidate({ event: details.event, id });
  4289. }
  4290. async run() {
  4291. if (!this.invalidated)
  4292. return;
  4293. this.invalidated = false;
  4294. const options = {
  4295. ...this.options,
  4296. cache: this.cache
  4297. };
  4298. const start = Date.now();
  4299. this.watcher.emitter.emit('event', {
  4300. code: 'BUNDLE_START',
  4301. input: this.options.input,
  4302. output: this.outputFiles
  4303. });
  4304. let result = null;
  4305. try {
  4306. result = await rollupInternal(options, this.watcher.emitter);
  4307. if (this.closed) {
  4308. return;
  4309. }
  4310. this.updateWatchedFiles(result);
  4311. this.skipWrite || (await Promise.all(this.outputs.map(output => result.write(output))));
  4312. this.watcher.emitter.emit('event', {
  4313. code: 'BUNDLE_END',
  4314. duration: Date.now() - start,
  4315. input: this.options.input,
  4316. output: this.outputFiles,
  4317. result
  4318. });
  4319. }
  4320. catch (error) {
  4321. if (!this.closed) {
  4322. if (Array.isArray(error.watchFiles)) {
  4323. for (const id of error.watchFiles) {
  4324. this.watchFile(id);
  4325. }
  4326. }
  4327. if (error.id) {
  4328. this.cache.modules = this.cache.modules.filter(module => module.id !== error.id);
  4329. }
  4330. }
  4331. this.watcher.emitter.emit('event', {
  4332. code: 'ERROR',
  4333. error,
  4334. result
  4335. });
  4336. }
  4337. }
  4338. updateWatchedFiles(result) {
  4339. const previouslyWatched = this.watched;
  4340. this.watched = new Set();
  4341. this.watchFiles = result.watchFiles;
  4342. this.cache = result.cache;
  4343. for (const id of this.watchFiles) {
  4344. this.watchFile(id);
  4345. }
  4346. for (const module of this.cache.modules) {
  4347. for (const depId of module.transformDependencies) {
  4348. this.watchFile(depId, true);
  4349. }
  4350. }
  4351. for (const id of previouslyWatched) {
  4352. if (!this.watched.has(id)) {
  4353. this.fileWatcher.unwatch(id);
  4354. }
  4355. }
  4356. }
  4357. watchFile(id, isTransformDependency = false) {
  4358. if (!this.filter(id))
  4359. return;
  4360. this.watched.add(id);
  4361. if (this.outputFiles.some(file => file === id)) {
  4362. throw new Error('Cannot import the generated bundle');
  4363. }
  4364. // this is necessary to ensure that any 'renamed' files
  4365. // continue to be watched following an error
  4366. this.fileWatcher.watch(id, isTransformDependency);
  4367. }
  4368. }
  4369. export { Task, Watcher };