UNPKG

2.84 kBJavaScriptView Raw
1"use strict";
2var __importDefault = (this && this.__importDefault) || function (mod) {
3 return (mod && mod.__esModule) ? mod : { "default": mod };
4};
5Object.defineProperty(exports, "__esModule", { value: true });
6const path_1 = __importDefault(require("path"));
7const chokidar_1 = __importDefault(require("chokidar"));
8class Watcher {
9 constructor(options) {
10 const { onReady, onTrigger, onCollectFiles, onError } = options;
11 this.onReady = onReady;
12 this.onTrigger = onTrigger;
13 this.onCollectFiles = onCollectFiles;
14 this.onError = onError;
15 }
16 async watch() {
17 // Collect files to watch
18 const files = await this.onCollectFiles();
19 // Initialize watcher
20 this.watcher = chokidar_1.default.watch(files, {
21 persistent: true,
22 ignoreInitial: true,
23 atomic: 500,
24 });
25 // Bind variables locally
26 const watcher = this.watcher;
27 const onTrigger = this.onTrigger;
28 const onCollectFiles = this.onCollectFiles;
29 const onError = this.onError;
30 const onReady = this.onReady;
31 watcher.on('ready', async () => {
32 // Notify listeners that we're watching
33 onReady();
34 // Trigger once when ready
35 await onTrigger(undefined);
36 });
37 watcher.on('error', (error) => {
38 onError(error);
39 });
40 watcher.on('all', async (_, file) => {
41 try {
42 // Collect watch all new files to watch
43 const newFiles = await onCollectFiles();
44 // Collect watched files, if there are any
45 let watchedFiles = [];
46 const watched = watcher.getWatched();
47 watchedFiles = Object.keys(watched).reduce((files, dirname) => watched[dirname].reduce((files, filename) => {
48 files.push(path_1.default.resolve(path_1.default.join(dirname, filename)));
49 return files;
50 }, files), []);
51 const diff = (xs, ys) => ({
52 added: ys.filter((y) => !xs.includes(y)),
53 removed: xs.filter((x) => !ys.includes(x)),
54 });
55 // Diff previously watched files and new files; then remove and
56 // add files from/to the watcher accordingly
57 const filesDiff = diff(watchedFiles, newFiles);
58 watcher.unwatch(filesDiff.removed);
59 watcher.add(filesDiff.added);
60 // Run the trigger callback
61 await onTrigger(file);
62 }
63 catch (e) {
64 onError(e);
65 }
66 });
67 }
68 close() {
69 if (this.watcher !== undefined) {
70 this.watcher.close();
71 }
72 }
73}
74exports.default = Watcher;