watching.js 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", {
  3. value: true
  4. });
  5. Object.defineProperty(exports, "createWatcher", {
  6. enumerable: true,
  7. get: ()=>createWatcher
  8. });
  9. const _chokidar = /*#__PURE__*/ _interopRequireDefault(require("chokidar"));
  10. const _fs = /*#__PURE__*/ _interopRequireDefault(require("fs"));
  11. const _micromatch = /*#__PURE__*/ _interopRequireDefault(require("micromatch"));
  12. const _normalizePath = /*#__PURE__*/ _interopRequireDefault(require("normalize-path"));
  13. const _path = /*#__PURE__*/ _interopRequireDefault(require("path"));
  14. const _utils = require("./utils");
  15. function _interopRequireDefault(obj) {
  16. return obj && obj.__esModule ? obj : {
  17. default: obj
  18. };
  19. }
  20. function createWatcher(args, { state , rebuild }) {
  21. let shouldPoll = args["--poll"];
  22. let shouldCoalesceWriteEvents = shouldPoll || process.platform === "win32";
  23. // Polling interval in milliseconds
  24. // Used only when polling or coalescing add/change events on Windows
  25. let pollInterval = 10;
  26. let watcher = _chokidar.default.watch([], {
  27. // Force checking for atomic writes in all situations
  28. // This causes chokidar to wait up to 100ms for a file to re-added after it's been unlinked
  29. // This only works when watching directories though
  30. atomic: true,
  31. usePolling: shouldPoll,
  32. interval: shouldPoll ? pollInterval : undefined,
  33. ignoreInitial: true,
  34. awaitWriteFinish: shouldCoalesceWriteEvents ? {
  35. stabilityThreshold: 50,
  36. pollInterval: pollInterval
  37. } : false
  38. });
  39. // A queue of rebuilds, file reads, etc… to run
  40. let chain = Promise.resolve();
  41. /**
  42. * A list of files that have been changed since the last rebuild
  43. *
  44. * @type {{file: string, content: () => Promise<string>, extension: string}[]}
  45. */ let changedContent = [];
  46. /**
  47. * A list of files for which a rebuild has already been queued.
  48. * This is used to prevent duplicate rebuilds when multiple events are fired for the same file.
  49. * The rebuilt file is cleared from this list when it's associated rebuild has _started_
  50. * This is because if the file is changed during a rebuild it won't trigger a new rebuild which it should
  51. **/ let pendingRebuilds = new Set();
  52. let _timer;
  53. let _reject;
  54. /**
  55. * Rebuilds the changed files and resolves when the rebuild is
  56. * complete regardless of whether it was successful or not
  57. */ async function rebuildAndContinue() {
  58. let changes = changedContent.splice(0);
  59. // There are no changes to rebuild so we can just do nothing
  60. if (changes.length === 0) {
  61. return Promise.resolve();
  62. }
  63. // Clear all pending rebuilds for the about-to-be-built files
  64. changes.forEach((change)=>pendingRebuilds.delete(change.file));
  65. // Resolve the promise even when the rebuild fails
  66. return rebuild(changes).then(()=>{}, ()=>{});
  67. }
  68. /**
  69. *
  70. * @param {*} file
  71. * @param {(() => Promise<string>) | null} content
  72. * @param {boolean} skipPendingCheck
  73. * @returns {Promise<void>}
  74. */ function recordChangedFile(file, content = null, skipPendingCheck = false) {
  75. file = _path.default.resolve(file);
  76. // Applications like Vim/Neovim fire both rename and change events in succession for atomic writes
  77. // In that case rebuild has already been queued by rename, so can be skipped in change
  78. if (pendingRebuilds.has(file) && !skipPendingCheck) {
  79. return Promise.resolve();
  80. }
  81. // Mark that a rebuild of this file is going to happen
  82. // It MUST happen synchronously before the rebuild is queued for this to be effective
  83. pendingRebuilds.add(file);
  84. changedContent.push({
  85. file,
  86. content: content !== null && content !== void 0 ? content : ()=>_fs.default.promises.readFile(file, "utf8"),
  87. extension: _path.default.extname(file).slice(1)
  88. });
  89. if (_timer) {
  90. clearTimeout(_timer);
  91. _reject();
  92. }
  93. // If a rebuild is already in progress we don't want to start another one until the 10ms timer has expired
  94. chain = chain.then(()=>new Promise((resolve, reject)=>{
  95. _timer = setTimeout(resolve, 10);
  96. _reject = reject;
  97. }));
  98. // Resolves once this file has been rebuilt (or the rebuild for this file has failed)
  99. // This queues as many rebuilds as there are changed files
  100. // But those rebuilds happen after some delay
  101. // And will immediately resolve if there are no changes
  102. chain = chain.then(rebuildAndContinue, rebuildAndContinue);
  103. return chain;
  104. }
  105. watcher.on("change", (file)=>recordChangedFile(file));
  106. watcher.on("add", (file)=>recordChangedFile(file));
  107. // Restore watching any files that are "removed"
  108. // This can happen when a file is pseudo-atomically replaced (a copy is created, overwritten, the old one is unlinked, and the new one is renamed)
  109. // TODO: An an optimization we should allow removal when the config changes
  110. watcher.on("unlink", (file)=>{
  111. file = (0, _normalizePath.default)(file);
  112. // Only re-add the file if it's not covered by a dynamic pattern
  113. if (!_micromatch.default.some([
  114. file
  115. ], state.contentPatterns.dynamic)) {
  116. watcher.add(file);
  117. }
  118. });
  119. // Some applications such as Visual Studio (but not VS Code)
  120. // will only fire a rename event for atomic writes and not a change event
  121. // This is very likely a chokidar bug but it's one we need to work around
  122. // We treat this as a change event and rebuild the CSS
  123. watcher.on("raw", (evt, filePath, meta)=>{
  124. if (evt !== "rename") {
  125. return;
  126. }
  127. let watchedPath = meta.watchedPath;
  128. // Watched path might be the file itself
  129. // Or the directory it is in
  130. filePath = watchedPath.endsWith(filePath) ? watchedPath : _path.default.join(watchedPath, filePath);
  131. // Skip this event since the files it is for does not match any of the registered content globs
  132. if (!_micromatch.default.some([
  133. filePath
  134. ], state.contentPatterns.all)) {
  135. return;
  136. }
  137. // Skip since we've already queued a rebuild for this file that hasn't happened yet
  138. if (pendingRebuilds.has(filePath)) {
  139. return;
  140. }
  141. // We'll go ahead and add the file to the pending rebuilds list here
  142. // It'll be removed when the rebuild starts unless the read fails
  143. // which will be taken care of as well
  144. pendingRebuilds.add(filePath);
  145. async function enqueue() {
  146. try {
  147. // We need to read the file as early as possible outside of the chain
  148. // because it may be gone by the time we get to it. doing the read
  149. // immediately increases the chance that the file is still there
  150. let content = await (0, _utils.readFileWithRetries)(_path.default.resolve(filePath));
  151. if (content === undefined) {
  152. return;
  153. }
  154. // This will push the rebuild onto the chain
  155. // We MUST skip the rebuild check here otherwise the rebuild will never happen on Linux
  156. // This is because the order of events and timing is different on Linux
  157. // @ts-ignore: TypeScript isn't picking up that content is a string here
  158. await recordChangedFile(filePath, ()=>content, true);
  159. } catch {
  160. // If reading the file fails, it's was probably a deleted temporary file
  161. // So we can ignore it and no rebuild is needed
  162. }
  163. }
  164. enqueue().then(()=>{
  165. // If the file read fails we still need to make sure the file isn't stuck in the pending rebuilds list
  166. pendingRebuilds.delete(filePath);
  167. });
  168. });
  169. return {
  170. fswatcher: watcher,
  171. refreshWatchedFiles () {
  172. watcher.add(Array.from(state.contextDependencies));
  173. watcher.add(Array.from(state.configBag.dependencies));
  174. watcher.add(state.contentPatterns.all);
  175. }
  176. };
  177. }