Dieses Repository beinhaltet HTML- und Javascript Code zur einer NotizenWebApp auf Basis von Web Storage. Zudem sind Mocha/Chai Tests im Browser enthalten. https://meinenotizen.netlify.app/
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

index.js 27KB

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