index.js 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798
  1. import { stat as statcb } from 'fs';
  2. import { stat, readdir } from 'fs/promises';
  3. import { EventEmitter } from 'events';
  4. import * as sysPath from 'path';
  5. import { readdirp } from 'readdirp';
  6. import { NodeFsHandler, EVENTS as EV, isWindows, isIBMi, EMPTY_FN, STR_CLOSE, STR_END, } from './handler.js';
  7. const SLASH = '/';
  8. const SLASH_SLASH = '//';
  9. const ONE_DOT = '.';
  10. const TWO_DOTS = '..';
  11. const STRING_TYPE = 'string';
  12. const BACK_SLASH_RE = /\\/g;
  13. const DOUBLE_SLASH_RE = /\/\//;
  14. const DOT_RE = /\..*\.(sw[px])$|~$|\.subl.*\.tmp/;
  15. const REPLACER_RE = /^\.[/\\]/;
  16. function arrify(item) {
  17. return Array.isArray(item) ? item : [item];
  18. }
  19. const isMatcherObject = (matcher) => typeof matcher === 'object' && matcher !== null && !(matcher instanceof RegExp);
  20. function createPattern(matcher) {
  21. if (typeof matcher === 'function')
  22. return matcher;
  23. if (typeof matcher === 'string')
  24. return (string) => matcher === string;
  25. if (matcher instanceof RegExp)
  26. return (string) => matcher.test(string);
  27. if (typeof matcher === 'object' && matcher !== null) {
  28. return (string) => {
  29. if (matcher.path === string)
  30. return true;
  31. if (matcher.recursive) {
  32. const relative = sysPath.relative(matcher.path, string);
  33. if (!relative) {
  34. return false;
  35. }
  36. return !relative.startsWith('..') && !sysPath.isAbsolute(relative);
  37. }
  38. return false;
  39. };
  40. }
  41. return () => false;
  42. }
  43. function normalizePath(path) {
  44. if (typeof path !== 'string')
  45. throw new Error('string expected');
  46. path = sysPath.normalize(path);
  47. path = path.replace(/\\/g, '/');
  48. let prepend = false;
  49. if (path.startsWith('//'))
  50. prepend = true;
  51. const DOUBLE_SLASH_RE = /\/\//;
  52. while (path.match(DOUBLE_SLASH_RE))
  53. path = path.replace(DOUBLE_SLASH_RE, '/');
  54. if (prepend)
  55. path = '/' + path;
  56. return path;
  57. }
  58. function matchPatterns(patterns, testString, stats) {
  59. const path = normalizePath(testString);
  60. for (let index = 0; index < patterns.length; index++) {
  61. const pattern = patterns[index];
  62. if (pattern(path, stats)) {
  63. return true;
  64. }
  65. }
  66. return false;
  67. }
  68. function anymatch(matchers, testString) {
  69. if (matchers == null) {
  70. throw new TypeError('anymatch: specify first argument');
  71. }
  72. // Early cache for matchers.
  73. const matchersArray = arrify(matchers);
  74. const patterns = matchersArray.map((matcher) => createPattern(matcher));
  75. if (testString == null) {
  76. return (testString, stats) => {
  77. return matchPatterns(patterns, testString, stats);
  78. };
  79. }
  80. return matchPatterns(patterns, testString);
  81. }
  82. const unifyPaths = (paths_) => {
  83. const paths = arrify(paths_).flat();
  84. if (!paths.every((p) => typeof p === STRING_TYPE)) {
  85. throw new TypeError(`Non-string provided as watch path: ${paths}`);
  86. }
  87. return paths.map(normalizePathToUnix);
  88. };
  89. // If SLASH_SLASH occurs at the beginning of path, it is not replaced
  90. // because "//StoragePC/DrivePool/Movies" is a valid network path
  91. const toUnix = (string) => {
  92. let str = string.replace(BACK_SLASH_RE, SLASH);
  93. let prepend = false;
  94. if (str.startsWith(SLASH_SLASH)) {
  95. prepend = true;
  96. }
  97. while (str.match(DOUBLE_SLASH_RE)) {
  98. str = str.replace(DOUBLE_SLASH_RE, SLASH);
  99. }
  100. if (prepend) {
  101. str = SLASH + str;
  102. }
  103. return str;
  104. };
  105. // Our version of upath.normalize
  106. // TODO: this is not equal to path-normalize module - investigate why
  107. const normalizePathToUnix = (path) => toUnix(sysPath.normalize(toUnix(path)));
  108. // TODO: refactor
  109. const normalizeIgnored = (cwd = '') => (path) => {
  110. if (typeof path === 'string') {
  111. return normalizePathToUnix(sysPath.isAbsolute(path) ? path : sysPath.join(cwd, path));
  112. }
  113. else {
  114. return path;
  115. }
  116. };
  117. const getAbsolutePath = (path, cwd) => {
  118. if (sysPath.isAbsolute(path)) {
  119. return path;
  120. }
  121. return sysPath.join(cwd, path);
  122. };
  123. const EMPTY_SET = Object.freeze(new Set());
  124. /**
  125. * Directory entry.
  126. */
  127. class DirEntry {
  128. constructor(dir, removeWatcher) {
  129. this.path = dir;
  130. this._removeWatcher = removeWatcher;
  131. this.items = new Set();
  132. }
  133. add(item) {
  134. const { items } = this;
  135. if (!items)
  136. return;
  137. if (item !== ONE_DOT && item !== TWO_DOTS)
  138. items.add(item);
  139. }
  140. async remove(item) {
  141. const { items } = this;
  142. if (!items)
  143. return;
  144. items.delete(item);
  145. if (items.size > 0)
  146. return;
  147. const dir = this.path;
  148. try {
  149. await readdir(dir);
  150. }
  151. catch (err) {
  152. if (this._removeWatcher) {
  153. this._removeWatcher(sysPath.dirname(dir), sysPath.basename(dir));
  154. }
  155. }
  156. }
  157. has(item) {
  158. const { items } = this;
  159. if (!items)
  160. return;
  161. return items.has(item);
  162. }
  163. getChildren() {
  164. const { items } = this;
  165. if (!items)
  166. return [];
  167. return [...items.values()];
  168. }
  169. dispose() {
  170. this.items.clear();
  171. this.path = '';
  172. this._removeWatcher = EMPTY_FN;
  173. this.items = EMPTY_SET;
  174. Object.freeze(this);
  175. }
  176. }
  177. const STAT_METHOD_F = 'stat';
  178. const STAT_METHOD_L = 'lstat';
  179. export class WatchHelper {
  180. constructor(path, follow, fsw) {
  181. this.fsw = fsw;
  182. const watchPath = path;
  183. this.path = path = path.replace(REPLACER_RE, '');
  184. this.watchPath = watchPath;
  185. this.fullWatchPath = sysPath.resolve(watchPath);
  186. this.dirParts = [];
  187. this.dirParts.forEach((parts) => {
  188. if (parts.length > 1)
  189. parts.pop();
  190. });
  191. this.followSymlinks = follow;
  192. this.statMethod = follow ? STAT_METHOD_F : STAT_METHOD_L;
  193. }
  194. entryPath(entry) {
  195. return sysPath.join(this.watchPath, sysPath.relative(this.watchPath, entry.fullPath));
  196. }
  197. filterPath(entry) {
  198. const { stats } = entry;
  199. if (stats && stats.isSymbolicLink())
  200. return this.filterDir(entry);
  201. const resolvedPath = this.entryPath(entry);
  202. // TODO: what if stats is undefined? remove !
  203. return this.fsw._isntIgnored(resolvedPath, stats) && this.fsw._hasReadPermissions(stats);
  204. }
  205. filterDir(entry) {
  206. return this.fsw._isntIgnored(this.entryPath(entry), entry.stats);
  207. }
  208. }
  209. /**
  210. * Watches files & directories for changes. Emitted events:
  211. * `add`, `addDir`, `change`, `unlink`, `unlinkDir`, `all`, `error`
  212. *
  213. * new FSWatcher()
  214. * .add(directories)
  215. * .on('add', path => log('File', path, 'was added'))
  216. */
  217. export class FSWatcher extends EventEmitter {
  218. // Not indenting methods for history sake; for now.
  219. constructor(_opts = {}) {
  220. super();
  221. this.closed = false;
  222. this._closers = new Map();
  223. this._ignoredPaths = new Set();
  224. this._throttled = new Map();
  225. this._streams = new Set();
  226. this._symlinkPaths = new Map();
  227. this._watched = new Map();
  228. this._pendingWrites = new Map();
  229. this._pendingUnlinks = new Map();
  230. this._readyCount = 0;
  231. this._readyEmitted = false;
  232. const awf = _opts.awaitWriteFinish;
  233. const DEF_AWF = { stabilityThreshold: 2000, pollInterval: 100 };
  234. const opts = {
  235. // Defaults
  236. persistent: true,
  237. ignoreInitial: false,
  238. ignorePermissionErrors: false,
  239. interval: 100,
  240. binaryInterval: 300,
  241. followSymlinks: true,
  242. usePolling: false,
  243. // useAsync: false,
  244. atomic: true, // NOTE: overwritten later (depends on usePolling)
  245. ..._opts,
  246. // Change format
  247. ignored: _opts.ignored ? arrify(_opts.ignored) : arrify([]),
  248. awaitWriteFinish: awf === true ? DEF_AWF : typeof awf === 'object' ? { ...DEF_AWF, ...awf } : false,
  249. };
  250. // Always default to polling on IBM i because fs.watch() is not available on IBM i.
  251. if (isIBMi)
  252. opts.usePolling = true;
  253. // Editor atomic write normalization enabled by default with fs.watch
  254. if (opts.atomic === undefined)
  255. opts.atomic = !opts.usePolling;
  256. // opts.atomic = typeof _opts.atomic === 'number' ? _opts.atomic : 100;
  257. // Global override. Useful for developers, who need to force polling for all
  258. // instances of chokidar, regardless of usage / dependency depth
  259. const envPoll = process.env.CHOKIDAR_USEPOLLING;
  260. if (envPoll !== undefined) {
  261. const envLower = envPoll.toLowerCase();
  262. if (envLower === 'false' || envLower === '0')
  263. opts.usePolling = false;
  264. else if (envLower === 'true' || envLower === '1')
  265. opts.usePolling = true;
  266. else
  267. opts.usePolling = !!envLower;
  268. }
  269. const envInterval = process.env.CHOKIDAR_INTERVAL;
  270. if (envInterval)
  271. opts.interval = Number.parseInt(envInterval, 10);
  272. // This is done to emit ready only once, but each 'add' will increase that?
  273. let readyCalls = 0;
  274. this._emitReady = () => {
  275. readyCalls++;
  276. if (readyCalls >= this._readyCount) {
  277. this._emitReady = EMPTY_FN;
  278. this._readyEmitted = true;
  279. // use process.nextTick to allow time for listener to be bound
  280. process.nextTick(() => this.emit(EV.READY));
  281. }
  282. };
  283. this._emitRaw = (...args) => this.emit(EV.RAW, ...args);
  284. this._boundRemove = this._remove.bind(this);
  285. this.options = opts;
  286. this._nodeFsHandler = new NodeFsHandler(this);
  287. // You’re frozen when your heart’s not open.
  288. Object.freeze(opts);
  289. }
  290. _addIgnoredPath(matcher) {
  291. if (isMatcherObject(matcher)) {
  292. // return early if we already have a deeply equal matcher object
  293. for (const ignored of this._ignoredPaths) {
  294. if (isMatcherObject(ignored) &&
  295. ignored.path === matcher.path &&
  296. ignored.recursive === matcher.recursive) {
  297. return;
  298. }
  299. }
  300. }
  301. this._ignoredPaths.add(matcher);
  302. }
  303. _removeIgnoredPath(matcher) {
  304. this._ignoredPaths.delete(matcher);
  305. // now find any matcher objects with the matcher as path
  306. if (typeof matcher === 'string') {
  307. for (const ignored of this._ignoredPaths) {
  308. // TODO (43081j): make this more efficient.
  309. // probably just make a `this._ignoredDirectories` or some
  310. // such thing.
  311. if (isMatcherObject(ignored) && ignored.path === matcher) {
  312. this._ignoredPaths.delete(ignored);
  313. }
  314. }
  315. }
  316. }
  317. // Public methods
  318. /**
  319. * Adds paths to be watched on an existing FSWatcher instance.
  320. * @param paths_ file or file list. Other arguments are unused
  321. */
  322. add(paths_, _origAdd, _internal) {
  323. const { cwd } = this.options;
  324. this.closed = false;
  325. this._closePromise = undefined;
  326. let paths = unifyPaths(paths_);
  327. if (cwd) {
  328. paths = paths.map((path) => {
  329. const absPath = getAbsolutePath(path, cwd);
  330. // Check `path` instead of `absPath` because the cwd portion can't be a glob
  331. return absPath;
  332. });
  333. }
  334. paths.forEach((path) => {
  335. this._removeIgnoredPath(path);
  336. });
  337. this._userIgnored = undefined;
  338. if (!this._readyCount)
  339. this._readyCount = 0;
  340. this._readyCount += paths.length;
  341. Promise.all(paths.map(async (path) => {
  342. const res = await this._nodeFsHandler._addToNodeFs(path, !_internal, undefined, 0, _origAdd);
  343. if (res)
  344. this._emitReady();
  345. return res;
  346. })).then((results) => {
  347. if (this.closed)
  348. return;
  349. results.forEach((item) => {
  350. if (item)
  351. this.add(sysPath.dirname(item), sysPath.basename(_origAdd || item));
  352. });
  353. });
  354. return this;
  355. }
  356. /**
  357. * Close watchers or start ignoring events from specified paths.
  358. */
  359. unwatch(paths_) {
  360. if (this.closed)
  361. return this;
  362. const paths = unifyPaths(paths_);
  363. const { cwd } = this.options;
  364. paths.forEach((path) => {
  365. // convert to absolute path unless relative path already matches
  366. if (!sysPath.isAbsolute(path) && !this._closers.has(path)) {
  367. if (cwd)
  368. path = sysPath.join(cwd, path);
  369. path = sysPath.resolve(path);
  370. }
  371. this._closePath(path);
  372. this._addIgnoredPath(path);
  373. if (this._watched.has(path)) {
  374. this._addIgnoredPath({
  375. path,
  376. recursive: true,
  377. });
  378. }
  379. // reset the cached userIgnored anymatch fn
  380. // to make ignoredPaths changes effective
  381. this._userIgnored = undefined;
  382. });
  383. return this;
  384. }
  385. /**
  386. * Close watchers and remove all listeners from watched paths.
  387. */
  388. close() {
  389. if (this._closePromise) {
  390. return this._closePromise;
  391. }
  392. this.closed = true;
  393. // Memory management.
  394. this.removeAllListeners();
  395. const closers = [];
  396. this._closers.forEach((closerList) => closerList.forEach((closer) => {
  397. const promise = closer();
  398. if (promise instanceof Promise)
  399. closers.push(promise);
  400. }));
  401. this._streams.forEach((stream) => stream.destroy());
  402. this._userIgnored = undefined;
  403. this._readyCount = 0;
  404. this._readyEmitted = false;
  405. this._watched.forEach((dirent) => dirent.dispose());
  406. this._closers.clear();
  407. this._watched.clear();
  408. this._streams.clear();
  409. this._symlinkPaths.clear();
  410. this._throttled.clear();
  411. this._closePromise = closers.length
  412. ? Promise.all(closers).then(() => undefined)
  413. : Promise.resolve();
  414. return this._closePromise;
  415. }
  416. /**
  417. * Expose list of watched paths
  418. * @returns for chaining
  419. */
  420. getWatched() {
  421. const watchList = {};
  422. this._watched.forEach((entry, dir) => {
  423. const key = this.options.cwd ? sysPath.relative(this.options.cwd, dir) : dir;
  424. const index = key || ONE_DOT;
  425. watchList[index] = entry.getChildren().sort();
  426. });
  427. return watchList;
  428. }
  429. emitWithAll(event, args) {
  430. this.emit(...args);
  431. if (event !== EV.ERROR)
  432. this.emit(EV.ALL, ...args);
  433. }
  434. // Common helpers
  435. // --------------
  436. /**
  437. * Normalize and emit events.
  438. * Calling _emit DOES NOT MEAN emit() would be called!
  439. * @param event Type of event
  440. * @param path File or directory path
  441. * @param stats arguments to be passed with event
  442. * @returns the error if defined, otherwise the value of the FSWatcher instance's `closed` flag
  443. */
  444. async _emit(event, path, stats) {
  445. if (this.closed)
  446. return;
  447. const opts = this.options;
  448. if (isWindows)
  449. path = sysPath.normalize(path);
  450. if (opts.cwd)
  451. path = sysPath.relative(opts.cwd, path);
  452. const args = [event, path];
  453. if (stats != null)
  454. args.push(stats);
  455. const awf = opts.awaitWriteFinish;
  456. let pw;
  457. if (awf && (pw = this._pendingWrites.get(path))) {
  458. pw.lastChange = new Date();
  459. return this;
  460. }
  461. if (opts.atomic) {
  462. if (event === EV.UNLINK) {
  463. this._pendingUnlinks.set(path, args);
  464. setTimeout(() => {
  465. this._pendingUnlinks.forEach((entry, path) => {
  466. this.emit(...entry);
  467. this.emit(EV.ALL, ...entry);
  468. this._pendingUnlinks.delete(path);
  469. });
  470. }, typeof opts.atomic === 'number' ? opts.atomic : 100);
  471. return this;
  472. }
  473. if (event === EV.ADD && this._pendingUnlinks.has(path)) {
  474. event = args[0] = EV.CHANGE;
  475. this._pendingUnlinks.delete(path);
  476. }
  477. }
  478. if (awf && (event === EV.ADD || event === EV.CHANGE) && this._readyEmitted) {
  479. const awfEmit = (err, stats) => {
  480. if (err) {
  481. event = args[0] = EV.ERROR;
  482. args[1] = err;
  483. this.emitWithAll(event, args);
  484. }
  485. else if (stats) {
  486. // if stats doesn't exist the file must have been deleted
  487. if (args.length > 2) {
  488. args[2] = stats;
  489. }
  490. else {
  491. args.push(stats);
  492. }
  493. this.emitWithAll(event, args);
  494. }
  495. };
  496. this._awaitWriteFinish(path, awf.stabilityThreshold, event, awfEmit);
  497. return this;
  498. }
  499. if (event === EV.CHANGE) {
  500. const isThrottled = !this._throttle(EV.CHANGE, path, 50);
  501. if (isThrottled)
  502. return this;
  503. }
  504. if (opts.alwaysStat &&
  505. stats === undefined &&
  506. (event === EV.ADD || event === EV.ADD_DIR || event === EV.CHANGE)) {
  507. const fullPath = opts.cwd ? sysPath.join(opts.cwd, path) : path;
  508. let stats;
  509. try {
  510. stats = await stat(fullPath);
  511. }
  512. catch (err) {
  513. // do nothing
  514. }
  515. // Suppress event when fs_stat fails, to avoid sending undefined 'stat'
  516. if (!stats || this.closed)
  517. return;
  518. args.push(stats);
  519. }
  520. this.emitWithAll(event, args);
  521. return this;
  522. }
  523. /**
  524. * Common handler for errors
  525. * @returns The error if defined, otherwise the value of the FSWatcher instance's `closed` flag
  526. */
  527. _handleError(error) {
  528. const code = error && error.code;
  529. if (error &&
  530. code !== 'ENOENT' &&
  531. code !== 'ENOTDIR' &&
  532. (!this.options.ignorePermissionErrors || (code !== 'EPERM' && code !== 'EACCES'))) {
  533. this.emit(EV.ERROR, error);
  534. }
  535. return error || this.closed;
  536. }
  537. /**
  538. * Helper utility for throttling
  539. * @param actionType type being throttled
  540. * @param path being acted upon
  541. * @param timeout duration of time to suppress duplicate actions
  542. * @returns tracking object or false if action should be suppressed
  543. */
  544. _throttle(actionType, path, timeout) {
  545. if (!this._throttled.has(actionType)) {
  546. this._throttled.set(actionType, new Map());
  547. }
  548. const action = this._throttled.get(actionType);
  549. if (!action)
  550. throw new Error('invalid throttle');
  551. const actionPath = action.get(path);
  552. if (actionPath) {
  553. actionPath.count++;
  554. return false;
  555. }
  556. // eslint-disable-next-line prefer-const
  557. let timeoutObject;
  558. const clear = () => {
  559. const item = action.get(path);
  560. const count = item ? item.count : 0;
  561. action.delete(path);
  562. clearTimeout(timeoutObject);
  563. if (item)
  564. clearTimeout(item.timeoutObject);
  565. return count;
  566. };
  567. timeoutObject = setTimeout(clear, timeout);
  568. const thr = { timeoutObject, clear, count: 0 };
  569. action.set(path, thr);
  570. return thr;
  571. }
  572. _incrReadyCount() {
  573. return this._readyCount++;
  574. }
  575. /**
  576. * Awaits write operation to finish.
  577. * Polls a newly created file for size variations. When files size does not change for 'threshold' milliseconds calls callback.
  578. * @param path being acted upon
  579. * @param threshold Time in milliseconds a file size must be fixed before acknowledging write OP is finished
  580. * @param event
  581. * @param awfEmit Callback to be called when ready for event to be emitted.
  582. */
  583. _awaitWriteFinish(path, threshold, event, awfEmit) {
  584. const awf = this.options.awaitWriteFinish;
  585. if (typeof awf !== 'object')
  586. return;
  587. const pollInterval = awf.pollInterval;
  588. let timeoutHandler;
  589. let fullPath = path;
  590. if (this.options.cwd && !sysPath.isAbsolute(path)) {
  591. fullPath = sysPath.join(this.options.cwd, path);
  592. }
  593. const now = new Date();
  594. const writes = this._pendingWrites;
  595. function awaitWriteFinishFn(prevStat) {
  596. statcb(fullPath, (err, curStat) => {
  597. if (err || !writes.has(path)) {
  598. if (err && err.code !== 'ENOENT')
  599. awfEmit(err);
  600. return;
  601. }
  602. const now = Number(new Date());
  603. if (prevStat && curStat.size !== prevStat.size) {
  604. writes.get(path).lastChange = now;
  605. }
  606. const pw = writes.get(path);
  607. const df = now - pw.lastChange;
  608. if (df >= threshold) {
  609. writes.delete(path);
  610. awfEmit(undefined, curStat);
  611. }
  612. else {
  613. timeoutHandler = setTimeout(awaitWriteFinishFn, pollInterval, curStat);
  614. }
  615. });
  616. }
  617. if (!writes.has(path)) {
  618. writes.set(path, {
  619. lastChange: now,
  620. cancelWait: () => {
  621. writes.delete(path);
  622. clearTimeout(timeoutHandler);
  623. return event;
  624. },
  625. });
  626. timeoutHandler = setTimeout(awaitWriteFinishFn, pollInterval);
  627. }
  628. }
  629. /**
  630. * Determines whether user has asked to ignore this path.
  631. */
  632. _isIgnored(path, stats) {
  633. if (this.options.atomic && DOT_RE.test(path))
  634. return true;
  635. if (!this._userIgnored) {
  636. const { cwd } = this.options;
  637. const ign = this.options.ignored;
  638. const ignored = (ign || []).map(normalizeIgnored(cwd));
  639. const ignoredPaths = [...this._ignoredPaths];
  640. const list = [...ignoredPaths.map(normalizeIgnored(cwd)), ...ignored];
  641. this._userIgnored = anymatch(list, undefined);
  642. }
  643. return this._userIgnored(path, stats);
  644. }
  645. _isntIgnored(path, stat) {
  646. return !this._isIgnored(path, stat);
  647. }
  648. /**
  649. * Provides a set of common helpers and properties relating to symlink handling.
  650. * @param path file or directory pattern being watched
  651. */
  652. _getWatchHelpers(path) {
  653. return new WatchHelper(path, this.options.followSymlinks, this);
  654. }
  655. // Directory helpers
  656. // -----------------
  657. /**
  658. * Provides directory tracking objects
  659. * @param directory path of the directory
  660. */
  661. _getWatchedDir(directory) {
  662. const dir = sysPath.resolve(directory);
  663. if (!this._watched.has(dir))
  664. this._watched.set(dir, new DirEntry(dir, this._boundRemove));
  665. return this._watched.get(dir);
  666. }
  667. // File helpers
  668. // ------------
  669. /**
  670. * Check for read permissions: https://stackoverflow.com/a/11781404/1358405
  671. */
  672. _hasReadPermissions(stats) {
  673. if (this.options.ignorePermissionErrors)
  674. return true;
  675. return Boolean(Number(stats.mode) & 0o400);
  676. }
  677. /**
  678. * Handles emitting unlink events for
  679. * files and directories, and via recursion, for
  680. * files and directories within directories that are unlinked
  681. * @param directory within which the following item is located
  682. * @param item base path of item/directory
  683. */
  684. _remove(directory, item, isDirectory) {
  685. // if what is being deleted is a directory, get that directory's paths
  686. // for recursive deleting and cleaning of watched object
  687. // if it is not a directory, nestedDirectoryChildren will be empty array
  688. const path = sysPath.join(directory, item);
  689. const fullPath = sysPath.resolve(path);
  690. isDirectory =
  691. isDirectory != null ? isDirectory : this._watched.has(path) || this._watched.has(fullPath);
  692. // prevent duplicate handling in case of arriving here nearly simultaneously
  693. // via multiple paths (such as _handleFile and _handleDir)
  694. if (!this._throttle('remove', path, 100))
  695. return;
  696. // if the only watched file is removed, watch for its return
  697. if (!isDirectory && this._watched.size === 1) {
  698. this.add(directory, item, true);
  699. }
  700. // This will create a new entry in the watched object in either case
  701. // so we got to do the directory check beforehand
  702. const wp = this._getWatchedDir(path);
  703. const nestedDirectoryChildren = wp.getChildren();
  704. // Recursively remove children directories / files.
  705. nestedDirectoryChildren.forEach((nested) => this._remove(path, nested));
  706. // Check if item was on the watched list and remove it
  707. const parent = this._getWatchedDir(directory);
  708. const wasTracked = parent.has(item);
  709. parent.remove(item);
  710. // Fixes issue #1042 -> Relative paths were detected and added as symlinks
  711. // (https://github.com/paulmillr/chokidar/blob/e1753ddbc9571bdc33b4a4af172d52cb6e611c10/lib/nodefs-handler.js#L612),
  712. // but never removed from the map in case the path was deleted.
  713. // This leads to an incorrect state if the path was recreated:
  714. // https://github.com/paulmillr/chokidar/blob/e1753ddbc9571bdc33b4a4af172d52cb6e611c10/lib/nodefs-handler.js#L553
  715. if (this._symlinkPaths.has(fullPath)) {
  716. this._symlinkPaths.delete(fullPath);
  717. }
  718. // If we wait for this file to be fully written, cancel the wait.
  719. let relPath = path;
  720. if (this.options.cwd)
  721. relPath = sysPath.relative(this.options.cwd, path);
  722. if (this.options.awaitWriteFinish && this._pendingWrites.has(relPath)) {
  723. const event = this._pendingWrites.get(relPath).cancelWait();
  724. if (event === EV.ADD)
  725. return;
  726. }
  727. // The Entry will either be a directory that just got removed
  728. // or a bogus entry to a file, in either case we have to remove it
  729. this._watched.delete(path);
  730. this._watched.delete(fullPath);
  731. const eventName = isDirectory ? EV.UNLINK_DIR : EV.UNLINK;
  732. if (wasTracked && !this._isIgnored(path))
  733. this._emit(eventName, path);
  734. // Avoid conflicts if we later create another file with the same name
  735. this._closePath(path);
  736. }
  737. /**
  738. * Closes all watchers for a path
  739. */
  740. _closePath(path) {
  741. this._closeFile(path);
  742. const dir = sysPath.dirname(path);
  743. this._getWatchedDir(dir).remove(sysPath.basename(path));
  744. }
  745. /**
  746. * Closes only file-specific watchers
  747. */
  748. _closeFile(path) {
  749. const closers = this._closers.get(path);
  750. if (!closers)
  751. return;
  752. closers.forEach((closer) => closer());
  753. this._closers.delete(path);
  754. }
  755. _addPathCloser(path, closer) {
  756. if (!closer)
  757. return;
  758. let list = this._closers.get(path);
  759. if (!list) {
  760. list = [];
  761. this._closers.set(path, list);
  762. }
  763. list.push(closer);
  764. }
  765. _readdirp(root, opts) {
  766. if (this.closed)
  767. return;
  768. const options = { type: EV.ALL, alwaysStat: true, lstat: true, ...opts, depth: 0 };
  769. let stream = readdirp(root, options);
  770. this._streams.add(stream);
  771. stream.once(STR_CLOSE, () => {
  772. stream = undefined;
  773. });
  774. stream.once(STR_END, () => {
  775. if (stream) {
  776. this._streams.delete(stream);
  777. stream = undefined;
  778. }
  779. });
  780. return stream;
  781. }
  782. }
  783. /**
  784. * Instantiates watcher with paths to be tracked.
  785. * @param paths file / directory paths
  786. * @param options opts, such as `atomic`, `awaitWriteFinish`, `ignored`, and others
  787. * @returns an instance of FSWatcher for chaining.
  788. * @example
  789. * const watcher = watch('.').on('all', (event, path) => { console.log(event, path); });
  790. * watch('.', { atomic: true, awaitWriteFinish: true, ignored: (f, stats) => stats?.isFile() && !f.endsWith('.js') })
  791. */
  792. export function watch(paths, options = {}) {
  793. const watcher = new FSWatcher(options);
  794. watcher.add(paths);
  795. return watcher;
  796. }
  797. export default { watch, FSWatcher };
  798. //# sourceMappingURL=index.js.map