UNPKG

read-conf

Version:
120 lines (117 loc) 3.27 kB
var chokidar, uncache; chokidar = uncache = null; module.exports = ({read, run, cleanUp, position}) => { var uncacheAll; read.hookIn(position.before, (noop, o) => { var arr, k, ref, results, v; if (o.watch) { chokidar = require("chokidar"); uncache = require("recursive-uncache"); if (o.unwatchedModules == null) { arr = o.unwatchedModules = []; ref = require.cache; results = []; for (k in ref) { v = ref[k]; results.push(arr.push(k)); } return results; } } }); run.hookIn(position.during + 1, (base, o) => { var arr, arr2, k, ref, results, v; if (o.watch) { arr = o.filesToWatch != null ? o.filesToWatch : o.filesToWatch = []; arr2 = o.unwatchedModules; ref = require.cache; results = []; for (k in ref) { v = ref[k]; if ((!~arr.indexOf(k)) && (!~arr2.indexOf(k))) { results.push(arr.push(k)); } else { results.push(void 0); } } return results; } }); uncacheAll = (o) => { var filepath, i, len, ref, results; ref = o.filesToWatch; results = []; for (i = 0, len = ref.length; i < len; i++) { filepath = ref[i]; results.push(uncache(filepath)); } return results; }; run.hookIn(position.after, (base, o) => { var watcher; if (o.watch) { if ((watcher = o.watcher) != null) { return watcher.add(o.filesToWatch); } else { o.watcher = chokidar.watch(o.filesToWatch, { ignoreInitial: true, awaitWriteFinish: { stabilityThreshold: 100, pollInterval: 100 } }); o.invalidate = (filename) => { var changed, conf; if (o.state.invalidating) { if (o.state.closing) { if (filename) { uncache(filename); } else { uncacheAll(o); } return o.state.invalidating; } } if (filename != null) { changed = (o.plugins != null) || o.filesToWatch.length > 1; if (!changed && o.filename) { uncache(filename); try { conf = require(o.filename); changed = o.hash !== o.util.hash(conf); } catch (error) {} } } else { uncacheAll(o); changed = true; } if (changed) { return o.state.invalidating = o.state.cleaning || o.cleanUp().catch((e) => { return console.log(e); }).then(() => { return o.read(); }).catch((e) => { return console.log(e); }).then(() => { o.state.invalidating = false; return o; }); } else { return Promise.resolve(o); } }; return o.watcher.on("all", (e, file) => { return o.invalidate(file); }); } } }); return cleanUp.hookIn((noop, o) => { var watcher; if ((watcher = o.watcher) != null) { uncacheAll(o); watcher.close(); return o.watcher = null; } }); };