index.js 119 KB

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