codebase-wiki 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (41) hide show
  1. package/CHANGELOG.md +34 -0
  2. package/LICENSE +17 -0
  3. package/README.md +130 -0
  4. package/dist/CHANGELOG.md +34 -0
  5. package/dist/LICENSE +17 -0
  6. package/dist/README.md +130 -0
  7. package/dist/chunks/build.mjs +1976 -0
  8. package/dist/chunks/config.mjs +174 -0
  9. package/dist/chunks/llm.mjs +214 -0
  10. package/dist/code-wiki-mcp.mjs +367 -0
  11. package/dist/code-wiki.mjs +11 -0
  12. package/dist/codewiki.mjs +2002 -0
  13. package/dist/grammars/c.wasm +0 -0
  14. package/dist/grammars/cpp.wasm +0 -0
  15. package/dist/grammars/go.wasm +0 -0
  16. package/dist/grammars/java.wasm +0 -0
  17. package/dist/grammars/javascript.wasm +0 -0
  18. package/dist/grammars/python.wasm +0 -0
  19. package/dist/grammars/ruby.wasm +0 -0
  20. package/dist/grammars/rust.wasm +0 -0
  21. package/dist/grammars/tsx.wasm +0 -0
  22. package/dist/grammars/typescript.wasm +0 -0
  23. package/dist/plugin/.mcp.json +11 -0
  24. package/dist/plugin/CLAUDE.md +28 -0
  25. package/dist/plugin/commands/wiki-architecture.md +10 -0
  26. package/dist/plugin/commands/wiki-build.md +23 -0
  27. package/dist/plugin/commands/wiki-enrich.md +22 -0
  28. package/dist/plugin/commands/wiki-graph.md +16 -0
  29. package/dist/plugin/commands/wiki-help.md +49 -0
  30. package/dist/plugin/commands/wiki-refresh.md +13 -0
  31. package/dist/plugin/commands/wiki-search.md +18 -0
  32. package/dist/plugin/commands/wiki-symbol.md +21 -0
  33. package/dist/plugin/hooks/hooks.json +74 -0
  34. package/dist/plugin/hooks/nudge.mjs +197 -0
  35. package/dist/plugin/hooks/post-read-reminder.mjs +56 -0
  36. package/dist/plugin/hooks/post-tool-use.mjs +60 -0
  37. package/dist/plugin/hooks/pre-compact.mjs +25 -0
  38. package/dist/plugin/hooks/session-start.mjs +38 -0
  39. package/dist/plugin/hooks/user-prompt-submit.mjs +28 -0
  40. package/dist/plugin/manifest.json +54 -0
  41. package/package.json +100 -0
@@ -0,0 +1,2002 @@
1
+ #!/usr/bin/env node
2
+ import process$1 from 'node:process';
3
+ import * as path from 'node:path';
4
+ import path__default, { resolve, join, relative, sep } from 'node:path';
5
+ import { Command } from 'commander';
6
+ import { EventEmitter } from 'node:events';
7
+ import { unwatchFile, watchFile, watch as watch$1, stat as stat$1 } from 'node:fs';
8
+ import { lstat, stat, readdir, realpath, open } from 'node:fs/promises';
9
+ import { Readable } from 'node:stream';
10
+ import { type } from 'node:os';
11
+ import { b as buildWiki } from './chunks/build.mjs';
12
+ import { r as readJson, w as writeJson, b as atomicWriteText, l as loadConfig, e as exists } from './chunks/config.mjs';
13
+ import { simpleGit } from 'simple-git';
14
+ import 'ignore';
15
+ import 'globby';
16
+ import 'node:crypto';
17
+ import 'gpt-tokenizer/encoding/cl100k_base';
18
+ import 'web-tree-sitter';
19
+ import 'pino';
20
+
21
+ const EntryTypes = {
22
+ FILE_TYPE: 'files',
23
+ DIR_TYPE: 'directories',
24
+ FILE_DIR_TYPE: 'files_directories',
25
+ EVERYTHING_TYPE: 'all',
26
+ };
27
+ const defaultOptions = {
28
+ root: '.',
29
+ fileFilter: (_entryInfo) => true,
30
+ directoryFilter: (_entryInfo) => true,
31
+ type: EntryTypes.FILE_TYPE,
32
+ lstat: false,
33
+ depth: 2147483648,
34
+ alwaysStat: false,
35
+ highWaterMark: 4096,
36
+ };
37
+ Object.freeze(defaultOptions);
38
+ const RECURSIVE_ERROR_CODE = 'READDIRP_RECURSIVE_ERROR';
39
+ const NORMAL_FLOW_ERRORS = new Set(['ENOENT', 'EPERM', 'EACCES', 'ELOOP', RECURSIVE_ERROR_CODE]);
40
+ const ALL_TYPES = [
41
+ EntryTypes.DIR_TYPE,
42
+ EntryTypes.EVERYTHING_TYPE,
43
+ EntryTypes.FILE_DIR_TYPE,
44
+ EntryTypes.FILE_TYPE,
45
+ ];
46
+ const DIR_TYPES = new Set([
47
+ EntryTypes.DIR_TYPE,
48
+ EntryTypes.EVERYTHING_TYPE,
49
+ EntryTypes.FILE_DIR_TYPE,
50
+ ]);
51
+ const FILE_TYPES = new Set([
52
+ EntryTypes.EVERYTHING_TYPE,
53
+ EntryTypes.FILE_DIR_TYPE,
54
+ EntryTypes.FILE_TYPE,
55
+ ]);
56
+ const isNormalFlowError = (error) => NORMAL_FLOW_ERRORS.has(error.code);
57
+ const wantBigintFsStats = process.platform === 'win32';
58
+ const emptyFn = (_entryInfo) => true;
59
+ const normalizeFilter = (filter) => {
60
+ if (filter === undefined)
61
+ return emptyFn;
62
+ if (typeof filter === 'function')
63
+ return filter;
64
+ if (typeof filter === 'string') {
65
+ const fl = filter.trim();
66
+ return (entry) => entry.basename === fl;
67
+ }
68
+ if (Array.isArray(filter)) {
69
+ const trItems = filter.map((item) => item.trim());
70
+ return (entry) => trItems.some((f) => entry.basename === f);
71
+ }
72
+ return emptyFn;
73
+ };
74
+ /** Readable readdir stream, emitting new files as they're being listed. */
75
+ class ReaddirpStream extends Readable {
76
+ parents;
77
+ reading;
78
+ parent;
79
+ _stat;
80
+ _maxDepth;
81
+ _wantsDir;
82
+ _wantsFile;
83
+ _wantsEverything;
84
+ _root;
85
+ _isDirent;
86
+ _statsProp;
87
+ _rdOptions;
88
+ _fileFilter;
89
+ _directoryFilter;
90
+ constructor(options = {}) {
91
+ super({
92
+ objectMode: true,
93
+ autoDestroy: true,
94
+ highWaterMark: options.highWaterMark,
95
+ });
96
+ const opts = { ...defaultOptions, ...options };
97
+ const { root, type } = opts;
98
+ this._fileFilter = normalizeFilter(opts.fileFilter);
99
+ this._directoryFilter = normalizeFilter(opts.directoryFilter);
100
+ const statMethod = opts.lstat ? lstat : stat;
101
+ // Use bigint stats if it's windows and stat() supports options (node 10+).
102
+ if (wantBigintFsStats) {
103
+ this._stat = (path) => statMethod(path, { bigint: true });
104
+ }
105
+ else {
106
+ this._stat = statMethod;
107
+ }
108
+ this._maxDepth =
109
+ opts.depth != null && Number.isSafeInteger(opts.depth) ? opts.depth : defaultOptions.depth;
110
+ this._wantsDir = type ? DIR_TYPES.has(type) : false;
111
+ this._wantsFile = type ? FILE_TYPES.has(type) : false;
112
+ this._wantsEverything = type === EntryTypes.EVERYTHING_TYPE;
113
+ this._root = resolve(root);
114
+ this._isDirent = !opts.alwaysStat;
115
+ this._statsProp = this._isDirent ? 'dirent' : 'stats';
116
+ this._rdOptions = { encoding: 'utf8', withFileTypes: this._isDirent };
117
+ // Launch stream with one parent, the root dir.
118
+ this.parents = [this._exploreDir(root, 1)];
119
+ this.reading = false;
120
+ this.parent = undefined;
121
+ }
122
+ async _read(batch) {
123
+ if (this.reading)
124
+ return;
125
+ this.reading = true;
126
+ try {
127
+ while (!this.destroyed && batch > 0) {
128
+ const par = this.parent;
129
+ const fil = par && par.files;
130
+ if (fil && fil.length > 0) {
131
+ const { path, depth } = par;
132
+ const slice = fil.splice(0, batch).map((dirent) => this._formatEntry(dirent, path));
133
+ const awaited = await Promise.all(slice);
134
+ for (const entry of awaited) {
135
+ if (!entry)
136
+ continue;
137
+ if (this.destroyed)
138
+ return;
139
+ const entryType = await this._getEntryType(entry);
140
+ if (entryType === 'directory' && this._directoryFilter(entry)) {
141
+ if (depth <= this._maxDepth) {
142
+ this.parents.push(this._exploreDir(entry.fullPath, depth + 1));
143
+ }
144
+ if (this._wantsDir) {
145
+ this.push(entry);
146
+ batch--;
147
+ }
148
+ }
149
+ else if ((entryType === 'file' || this._includeAsFile(entry)) &&
150
+ this._fileFilter(entry)) {
151
+ if (this._wantsFile) {
152
+ this.push(entry);
153
+ batch--;
154
+ }
155
+ }
156
+ }
157
+ }
158
+ else {
159
+ const parent = this.parents.pop();
160
+ if (!parent) {
161
+ this.push(null);
162
+ break;
163
+ }
164
+ this.parent = await parent;
165
+ if (this.destroyed)
166
+ return;
167
+ }
168
+ }
169
+ }
170
+ catch (error) {
171
+ this.destroy(error);
172
+ }
173
+ finally {
174
+ this.reading = false;
175
+ }
176
+ }
177
+ async _exploreDir(path, depth) {
178
+ let files;
179
+ try {
180
+ files = await readdir(path, this._rdOptions);
181
+ }
182
+ catch (error) {
183
+ this._onError(error);
184
+ }
185
+ return { files, depth, path };
186
+ }
187
+ async _formatEntry(dirent, path) {
188
+ let entry;
189
+ const basename = this._isDirent ? dirent.name : dirent;
190
+ try {
191
+ const fullPath = resolve(join(path, basename));
192
+ entry = { path: relative(this._root, fullPath), fullPath, basename };
193
+ entry[this._statsProp] = this._isDirent ? dirent : await this._stat(fullPath);
194
+ }
195
+ catch (err) {
196
+ this._onError(err);
197
+ return;
198
+ }
199
+ return entry;
200
+ }
201
+ _onError(err) {
202
+ if (isNormalFlowError(err) && !this.destroyed) {
203
+ this.emit('warn', err);
204
+ }
205
+ else {
206
+ this.destroy(err);
207
+ }
208
+ }
209
+ async _getEntryType(entry) {
210
+ // entry may be undefined, because a warning or an error were emitted
211
+ // and the statsProp is undefined
212
+ if (!entry && this._statsProp in entry) {
213
+ return '';
214
+ }
215
+ const stats = entry[this._statsProp];
216
+ if (stats.isFile())
217
+ return 'file';
218
+ if (stats.isDirectory())
219
+ return 'directory';
220
+ if (stats && stats.isSymbolicLink()) {
221
+ const full = entry.fullPath;
222
+ try {
223
+ const entryRealPath = await realpath(full);
224
+ const entryRealPathStats = await lstat(entryRealPath);
225
+ if (entryRealPathStats.isFile()) {
226
+ return 'file';
227
+ }
228
+ if (entryRealPathStats.isDirectory()) {
229
+ const len = entryRealPath.length;
230
+ if (full.startsWith(entryRealPath) && full.substr(len, 1) === sep) {
231
+ const recursiveError = new Error(`Circular symlink detected: "${full}" points to "${entryRealPath}"`);
232
+ // @ts-ignore
233
+ recursiveError.code = RECURSIVE_ERROR_CODE;
234
+ return this._onError(recursiveError);
235
+ }
236
+ return 'directory';
237
+ }
238
+ }
239
+ catch (error) {
240
+ this._onError(error);
241
+ return '';
242
+ }
243
+ }
244
+ }
245
+ _includeAsFile(entry) {
246
+ const stats = entry && entry[this._statsProp];
247
+ return stats && this._wantsEverything && !stats.isDirectory();
248
+ }
249
+ }
250
+ /**
251
+ * Streaming version: Reads all files and directories in given root recursively.
252
+ * Consumes ~constant small amount of RAM.
253
+ * @param root Root directory
254
+ * @param options Options to specify root (start directory), filters and recursion depth
255
+ */
256
+ function readdirp(root, options = {}) {
257
+ // @ts-ignore
258
+ let type = options.entryType || options.type;
259
+ if (type === 'both')
260
+ type = EntryTypes.FILE_DIR_TYPE; // backwards-compatibility
261
+ if (type)
262
+ options.type = type;
263
+ if (!root) {
264
+ throw new Error('readdirp: root argument is required. Usage: readdirp(root, options)');
265
+ }
266
+ else if (typeof root !== 'string') {
267
+ throw new TypeError('readdirp: root argument must be a string. Usage: readdirp(root, options)');
268
+ }
269
+ else if (type && !ALL_TYPES.includes(type)) {
270
+ throw new Error(`readdirp: Invalid type passed. Use one of ${ALL_TYPES.join(', ')}`);
271
+ }
272
+ options.root = root;
273
+ return new ReaddirpStream(options);
274
+ }
275
+
276
+ const STR_DATA = 'data';
277
+ const STR_END = 'end';
278
+ const STR_CLOSE = 'close';
279
+ const EMPTY_FN = () => { };
280
+ const pl = process.platform;
281
+ const isWindows = pl === 'win32';
282
+ const isMacos = pl === 'darwin';
283
+ const isLinux = pl === 'linux';
284
+ const isFreeBSD = pl === 'freebsd';
285
+ const isIBMi = type() === 'OS400';
286
+ const EVENTS = {
287
+ ALL: 'all',
288
+ READY: 'ready',
289
+ ADD: 'add',
290
+ CHANGE: 'change',
291
+ ADD_DIR: 'addDir',
292
+ UNLINK: 'unlink',
293
+ UNLINK_DIR: 'unlinkDir',
294
+ RAW: 'raw',
295
+ ERROR: 'error',
296
+ };
297
+ const EV = EVENTS;
298
+ const THROTTLE_MODE_WATCH = 'watch';
299
+ const statMethods = { lstat, stat };
300
+ const KEY_LISTENERS = 'listeners';
301
+ const KEY_ERR = 'errHandlers';
302
+ const KEY_RAW = 'rawEmitters';
303
+ const HANDLER_KEYS = [KEY_LISTENERS, KEY_ERR, KEY_RAW];
304
+ // prettier-ignore
305
+ const binaryExtensions = new Set([
306
+ '3dm', '3ds', '3g2', '3gp', '7z', 'a', 'aac', 'adp', 'afdesign', 'afphoto', 'afpub', 'ai',
307
+ 'aif', 'aiff', 'alz', 'ape', 'apk', 'appimage', 'ar', 'arj', 'asf', 'au', 'avi',
308
+ 'bak', 'baml', 'bh', 'bin', 'bk', 'bmp', 'btif', 'bz2', 'bzip2',
309
+ 'cab', 'caf', 'cgm', 'class', 'cmx', 'cpio', 'cr2', 'cur', 'dat', 'dcm', 'deb', 'dex', 'djvu',
310
+ 'dll', 'dmg', 'dng', 'doc', 'docm', 'docx', 'dot', 'dotm', 'dra', 'DS_Store', 'dsk', 'dts',
311
+ 'dtshd', 'dvb', 'dwg', 'dxf',
312
+ 'ecelp4800', 'ecelp7470', 'ecelp9600', 'egg', 'eol', 'eot', 'epub', 'exe',
313
+ 'f4v', 'fbs', 'fh', 'fla', 'flac', 'flatpak', 'fli', 'flv', 'fpx', 'fst', 'fvt',
314
+ 'g3', 'gh', 'gif', 'graffle', 'gz', 'gzip',
315
+ 'h261', 'h263', 'h264', 'icns', 'ico', 'ief', 'img', 'ipa', 'iso',
316
+ 'jar', 'jpeg', 'jpg', 'jpgv', 'jpm', 'jxr', 'key', 'ktx',
317
+ 'lha', 'lib', 'lvp', 'lz', 'lzh', 'lzma', 'lzo',
318
+ 'm3u', 'm4a', 'm4v', 'mar', 'mdi', 'mht', 'mid', 'midi', 'mj2', 'mka', 'mkv', 'mmr', 'mng',
319
+ 'mobi', 'mov', 'movie', 'mp3',
320
+ 'mp4', 'mp4a', 'mpeg', 'mpg', 'mpga', 'mxu',
321
+ 'nef', 'npx', 'numbers', 'nupkg',
322
+ 'o', 'odp', 'ods', 'odt', 'oga', 'ogg', 'ogv', 'otf', 'ott',
323
+ 'pages', 'pbm', 'pcx', 'pdb', 'pdf', 'pea', 'pgm', 'pic', 'png', 'pnm', 'pot', 'potm',
324
+ 'potx', 'ppa', 'ppam',
325
+ 'ppm', 'pps', 'ppsm', 'ppsx', 'ppt', 'pptm', 'pptx', 'psd', 'pya', 'pyc', 'pyo', 'pyv',
326
+ 'qt',
327
+ 'rar', 'ras', 'raw', 'resources', 'rgb', 'rip', 'rlc', 'rmf', 'rmvb', 'rpm', 'rtf', 'rz',
328
+ 's3m', 's7z', 'scpt', 'sgi', 'shar', 'snap', 'sil', 'sketch', 'slk', 'smv', 'snk', 'so',
329
+ 'stl', 'suo', 'sub', 'swf',
330
+ 'tar', 'tbz', 'tbz2', 'tga', 'tgz', 'thmx', 'tif', 'tiff', 'tlz', 'ttc', 'ttf', 'txz',
331
+ 'udf', 'uvh', 'uvi', 'uvm', 'uvp', 'uvs', 'uvu',
332
+ 'viv', 'vob',
333
+ 'war', 'wav', 'wax', 'wbmp', 'wdp', 'weba', 'webm', 'webp', 'whl', 'wim', 'wm', 'wma',
334
+ 'wmv', 'wmx', 'woff', 'woff2', 'wrm', 'wvx',
335
+ 'xbm', 'xif', 'xla', 'xlam', 'xls', 'xlsb', 'xlsm', 'xlsx', 'xlt', 'xltm', 'xltx', 'xm',
336
+ 'xmind', 'xpi', 'xpm', 'xwd', 'xz',
337
+ 'z', 'zip', 'zipx',
338
+ ]);
339
+ const isBinaryPath = (filePath) => binaryExtensions.has(path.extname(filePath).slice(1).toLowerCase());
340
+ // TODO: emit errors properly. Example: EMFILE on Macos.
341
+ const foreach = (val, fn) => {
342
+ if (val instanceof Set) {
343
+ val.forEach(fn);
344
+ }
345
+ else {
346
+ fn(val);
347
+ }
348
+ };
349
+ const addAndConvert = (main, prop, item) => {
350
+ let container = main[prop];
351
+ if (!(container instanceof Set)) {
352
+ main[prop] = container = new Set([container]);
353
+ }
354
+ container.add(item);
355
+ };
356
+ const clearItem = (cont) => (key) => {
357
+ const set = cont[key];
358
+ if (set instanceof Set) {
359
+ set.clear();
360
+ }
361
+ else {
362
+ delete cont[key];
363
+ }
364
+ };
365
+ const delFromSet = (main, prop, item) => {
366
+ const container = main[prop];
367
+ if (container instanceof Set) {
368
+ container.delete(item);
369
+ }
370
+ else if (container === item) {
371
+ delete main[prop];
372
+ }
373
+ };
374
+ const isEmptySet = (val) => (val instanceof Set ? val.size === 0 : !val);
375
+ const FsWatchInstances = new Map();
376
+ /**
377
+ * Instantiates the fs_watch interface
378
+ * @param path to be watched
379
+ * @param options to be passed to fs_watch
380
+ * @param listener main event handler
381
+ * @param errHandler emits info about errors
382
+ * @param emitRaw emits raw event data
383
+ * @returns {NativeFsWatcher}
384
+ */
385
+ function createFsWatchInstance(path$1, options, listener, errHandler, emitRaw) {
386
+ const handleEvent = (rawEvent, evPath) => {
387
+ listener(path$1);
388
+ emitRaw(rawEvent, evPath, { watchedPath: path$1 });
389
+ // emit based on events occurring for files from a directory's watcher in
390
+ // case the file's watcher misses it (and rely on throttling to de-dupe)
391
+ if (evPath && path$1 !== evPath) {
392
+ fsWatchBroadcast(path.resolve(path$1, evPath), KEY_LISTENERS, path.join(path$1, evPath));
393
+ }
394
+ };
395
+ try {
396
+ return watch$1(path$1, {
397
+ persistent: options.persistent,
398
+ }, handleEvent);
399
+ }
400
+ catch (error) {
401
+ errHandler(error);
402
+ return undefined;
403
+ }
404
+ }
405
+ /**
406
+ * Helper for passing fs_watch event data to a collection of listeners
407
+ * @param fullPath absolute path bound to fs_watch instance
408
+ */
409
+ const fsWatchBroadcast = (fullPath, listenerType, val1, val2, val3) => {
410
+ const cont = FsWatchInstances.get(fullPath);
411
+ if (!cont)
412
+ return;
413
+ foreach(cont[listenerType], (listener) => {
414
+ listener(val1, val2, val3);
415
+ });
416
+ };
417
+ /**
418
+ * Instantiates the fs_watch interface or binds listeners
419
+ * to an existing one covering the same file system entry
420
+ * @param path
421
+ * @param fullPath absolute path
422
+ * @param options to be passed to fs_watch
423
+ * @param handlers container for event listener functions
424
+ */
425
+ const setFsWatchListener = (path, fullPath, options, handlers) => {
426
+ const { listener, errHandler, rawEmitter } = handlers;
427
+ let cont = FsWatchInstances.get(fullPath);
428
+ let watcher;
429
+ if (!options.persistent) {
430
+ watcher = createFsWatchInstance(path, options, listener, errHandler, rawEmitter);
431
+ if (!watcher)
432
+ return;
433
+ return watcher.close.bind(watcher);
434
+ }
435
+ if (cont) {
436
+ addAndConvert(cont, KEY_LISTENERS, listener);
437
+ addAndConvert(cont, KEY_ERR, errHandler);
438
+ addAndConvert(cont, KEY_RAW, rawEmitter);
439
+ }
440
+ else {
441
+ watcher = createFsWatchInstance(path, options, fsWatchBroadcast.bind(null, fullPath, KEY_LISTENERS), errHandler, // no need to use broadcast here
442
+ fsWatchBroadcast.bind(null, fullPath, KEY_RAW));
443
+ if (!watcher)
444
+ return;
445
+ watcher.on(EV.ERROR, async (error) => {
446
+ const broadcastErr = fsWatchBroadcast.bind(null, fullPath, KEY_ERR);
447
+ if (cont)
448
+ cont.watcherUnusable = true; // documented since Node 10.4.1
449
+ // Workaround for https://github.com/joyent/node/issues/4337
450
+ if (isWindows && error.code === 'EPERM') {
451
+ try {
452
+ const fd = await open(path, 'r');
453
+ await fd.close();
454
+ broadcastErr(error);
455
+ }
456
+ catch (err) {
457
+ // do nothing
458
+ }
459
+ }
460
+ else {
461
+ broadcastErr(error);
462
+ }
463
+ });
464
+ cont = {
465
+ listeners: listener,
466
+ errHandlers: errHandler,
467
+ rawEmitters: rawEmitter,
468
+ watcher,
469
+ };
470
+ FsWatchInstances.set(fullPath, cont);
471
+ }
472
+ // const index = cont.listeners.indexOf(listener);
473
+ // removes this instance's listeners and closes the underlying fs_watch
474
+ // instance if there are no more listeners left
475
+ return () => {
476
+ delFromSet(cont, KEY_LISTENERS, listener);
477
+ delFromSet(cont, KEY_ERR, errHandler);
478
+ delFromSet(cont, KEY_RAW, rawEmitter);
479
+ if (isEmptySet(cont.listeners)) {
480
+ // Check to protect against issue gh-730.
481
+ // if (cont.watcherUnusable) {
482
+ cont.watcher.close();
483
+ // }
484
+ FsWatchInstances.delete(fullPath);
485
+ HANDLER_KEYS.forEach(clearItem(cont));
486
+ // @ts-ignore
487
+ cont.watcher = undefined;
488
+ Object.freeze(cont);
489
+ }
490
+ };
491
+ };
492
+ // fs_watchFile helpers
493
+ // object to hold per-process fs_watchFile instances
494
+ // (may be shared across chokidar FSWatcher instances)
495
+ const FsWatchFileInstances = new Map();
496
+ /**
497
+ * Instantiates the fs_watchFile interface or binds listeners
498
+ * to an existing one covering the same file system entry
499
+ * @param path to be watched
500
+ * @param fullPath absolute path
501
+ * @param options options to be passed to fs_watchFile
502
+ * @param handlers container for event listener functions
503
+ * @returns closer
504
+ */
505
+ const setFsWatchFileListener = (path, fullPath, options, handlers) => {
506
+ const { listener, rawEmitter } = handlers;
507
+ let cont = FsWatchFileInstances.get(fullPath);
508
+ // let listeners = new Set();
509
+ // let rawEmitters = new Set();
510
+ const copts = cont && cont.options;
511
+ if (copts && (copts.persistent < options.persistent || copts.interval > options.interval)) {
512
+ // "Upgrade" the watcher to persistence or a quicker interval.
513
+ // This creates some unlikely edge case issues if the user mixes
514
+ // settings in a very weird way, but solving for those cases
515
+ // doesn't seem worthwhile for the added complexity.
516
+ // listeners = cont.listeners;
517
+ // rawEmitters = cont.rawEmitters;
518
+ unwatchFile(fullPath);
519
+ cont = undefined;
520
+ }
521
+ if (cont) {
522
+ addAndConvert(cont, KEY_LISTENERS, listener);
523
+ addAndConvert(cont, KEY_RAW, rawEmitter);
524
+ }
525
+ else {
526
+ // TODO
527
+ // listeners.add(listener);
528
+ // rawEmitters.add(rawEmitter);
529
+ cont = {
530
+ listeners: listener,
531
+ rawEmitters: rawEmitter,
532
+ options,
533
+ watcher: watchFile(fullPath, options, (curr, prev) => {
534
+ foreach(cont.rawEmitters, (rawEmitter) => {
535
+ rawEmitter(EV.CHANGE, fullPath, { curr, prev });
536
+ });
537
+ const currmtime = curr.mtimeMs;
538
+ if (curr.size !== prev.size || currmtime > prev.mtimeMs || currmtime === 0) {
539
+ foreach(cont.listeners, (listener) => listener(path, curr));
540
+ }
541
+ }),
542
+ };
543
+ FsWatchFileInstances.set(fullPath, cont);
544
+ }
545
+ // const index = cont.listeners.indexOf(listener);
546
+ // Removes this instance's listeners and closes the underlying fs_watchFile
547
+ // instance if there are no more listeners left.
548
+ return () => {
549
+ delFromSet(cont, KEY_LISTENERS, listener);
550
+ delFromSet(cont, KEY_RAW, rawEmitter);
551
+ if (isEmptySet(cont.listeners)) {
552
+ FsWatchFileInstances.delete(fullPath);
553
+ unwatchFile(fullPath);
554
+ cont.options = cont.watcher = undefined;
555
+ Object.freeze(cont);
556
+ }
557
+ };
558
+ };
559
+ /**
560
+ * @mixin
561
+ */
562
+ class NodeFsHandler {
563
+ fsw;
564
+ _boundHandleError;
565
+ constructor(fsW) {
566
+ this.fsw = fsW;
567
+ this._boundHandleError = (error) => fsW._handleError(error);
568
+ }
569
+ /**
570
+ * Watch file for changes with fs_watchFile or fs_watch.
571
+ * @param path to file or dir
572
+ * @param listener on fs change
573
+ * @returns closer for the watcher instance
574
+ */
575
+ _watchWithNodeFs(path$1, listener) {
576
+ const opts = this.fsw.options;
577
+ const directory = path.dirname(path$1);
578
+ const basename = path.basename(path$1);
579
+ const parent = this.fsw._getWatchedDir(directory);
580
+ parent.add(basename);
581
+ const absolutePath = path.resolve(path$1);
582
+ const options = {
583
+ persistent: opts.persistent,
584
+ };
585
+ if (!listener)
586
+ listener = EMPTY_FN;
587
+ let closer;
588
+ if (opts.usePolling) {
589
+ const enableBin = opts.interval !== opts.binaryInterval;
590
+ options.interval = enableBin && isBinaryPath(basename) ? opts.binaryInterval : opts.interval;
591
+ closer = setFsWatchFileListener(path$1, absolutePath, options, {
592
+ listener,
593
+ rawEmitter: this.fsw._emitRaw,
594
+ });
595
+ }
596
+ else {
597
+ closer = setFsWatchListener(path$1, absolutePath, options, {
598
+ listener,
599
+ errHandler: this._boundHandleError,
600
+ rawEmitter: this.fsw._emitRaw,
601
+ });
602
+ }
603
+ return closer;
604
+ }
605
+ /**
606
+ * Watch a file and emit add event if warranted.
607
+ * @returns closer for the watcher instance
608
+ */
609
+ _handleFile(file, stats, initialAdd) {
610
+ if (this.fsw.closed) {
611
+ return;
612
+ }
613
+ const dirname = path.dirname(file);
614
+ const basename = path.basename(file);
615
+ const parent = this.fsw._getWatchedDir(dirname);
616
+ // stats is always present
617
+ let prevStats = stats;
618
+ // if the file is already being watched, do nothing
619
+ if (parent.has(basename))
620
+ return;
621
+ const listener = async (path, newStats) => {
622
+ if (!this.fsw._throttle(THROTTLE_MODE_WATCH, file, 5))
623
+ return;
624
+ if (!newStats || newStats.mtimeMs === 0) {
625
+ try {
626
+ const newStats = await stat(file);
627
+ if (this.fsw.closed)
628
+ return;
629
+ // Check that change event was not fired because of changed only accessTime.
630
+ const at = newStats.atimeMs;
631
+ const mt = newStats.mtimeMs;
632
+ if (!at || at <= mt || mt !== prevStats.mtimeMs) {
633
+ this.fsw._emit(EV.CHANGE, file, newStats);
634
+ }
635
+ if ((isMacos || isLinux || isFreeBSD) && prevStats.ino !== newStats.ino) {
636
+ this.fsw._closeFile(path);
637
+ prevStats = newStats;
638
+ const closer = this._watchWithNodeFs(file, listener);
639
+ if (closer)
640
+ this.fsw._addPathCloser(path, closer);
641
+ }
642
+ else {
643
+ prevStats = newStats;
644
+ }
645
+ }
646
+ catch (error) {
647
+ // Fix issues where mtime is null but file is still present
648
+ this.fsw._remove(dirname, basename);
649
+ }
650
+ // add is about to be emitted if file not already tracked in parent
651
+ }
652
+ else if (parent.has(basename)) {
653
+ // Check that change event was not fired because of changed only accessTime.
654
+ const at = newStats.atimeMs;
655
+ const mt = newStats.mtimeMs;
656
+ if (!at || at <= mt || mt !== prevStats.mtimeMs) {
657
+ this.fsw._emit(EV.CHANGE, file, newStats);
658
+ }
659
+ prevStats = newStats;
660
+ }
661
+ };
662
+ // kick off the watcher
663
+ const closer = this._watchWithNodeFs(file, listener);
664
+ // emit an add event if we're supposed to
665
+ if (!(initialAdd && this.fsw.options.ignoreInitial) && this.fsw._isntIgnored(file)) {
666
+ if (!this.fsw._throttle(EV.ADD, file, 0))
667
+ return;
668
+ this.fsw._emit(EV.ADD, file, stats);
669
+ }
670
+ return closer;
671
+ }
672
+ /**
673
+ * Handle symlinks encountered while reading a dir.
674
+ * @param entry returned by readdirp
675
+ * @param directory path of dir being read
676
+ * @param path of this item
677
+ * @param item basename of this item
678
+ * @returns true if no more processing is needed for this entry.
679
+ */
680
+ async _handleSymlink(entry, directory, path, item) {
681
+ if (this.fsw.closed) {
682
+ return;
683
+ }
684
+ const full = entry.fullPath;
685
+ const dir = this.fsw._getWatchedDir(directory);
686
+ if (!this.fsw.options.followSymlinks) {
687
+ // watch symlink directly (don't follow) and detect changes
688
+ this.fsw._incrReadyCount();
689
+ let linkPath;
690
+ try {
691
+ linkPath = await realpath(path);
692
+ }
693
+ catch (e) {
694
+ this.fsw._emitReady();
695
+ return true;
696
+ }
697
+ if (this.fsw.closed)
698
+ return;
699
+ if (dir.has(item)) {
700
+ if (this.fsw._symlinkPaths.get(full) !== linkPath) {
701
+ this.fsw._symlinkPaths.set(full, linkPath);
702
+ this.fsw._emit(EV.CHANGE, path, entry.stats);
703
+ }
704
+ }
705
+ else {
706
+ dir.add(item);
707
+ this.fsw._symlinkPaths.set(full, linkPath);
708
+ this.fsw._emit(EV.ADD, path, entry.stats);
709
+ }
710
+ this.fsw._emitReady();
711
+ return true;
712
+ }
713
+ // don't follow the same symlink more than once
714
+ if (this.fsw._symlinkPaths.has(full)) {
715
+ return true;
716
+ }
717
+ this.fsw._symlinkPaths.set(full, true);
718
+ }
719
+ _handleRead(directory, initialAdd, wh, target, dir, depth, throttler) {
720
+ // Normalize the directory name on Windows
721
+ directory = path.join(directory, '');
722
+ const throttleKey = target ? `${directory}:${target}` : directory;
723
+ throttler = this.fsw._throttle('readdir', throttleKey, 1000);
724
+ if (!throttler)
725
+ return;
726
+ const previous = this.fsw._getWatchedDir(wh.path);
727
+ const current = new Set();
728
+ let stream = this.fsw._readdirp(directory, {
729
+ fileFilter: (entry) => wh.filterPath(entry),
730
+ directoryFilter: (entry) => wh.filterDir(entry),
731
+ });
732
+ if (!stream)
733
+ return;
734
+ stream
735
+ .on(STR_DATA, async (entry) => {
736
+ if (this.fsw.closed) {
737
+ stream = undefined;
738
+ return;
739
+ }
740
+ const item = entry.path;
741
+ let path$1 = path.join(directory, item);
742
+ current.add(item);
743
+ if (entry.stats.isSymbolicLink() &&
744
+ (await this._handleSymlink(entry, directory, path$1, item))) {
745
+ return;
746
+ }
747
+ if (this.fsw.closed) {
748
+ stream = undefined;
749
+ return;
750
+ }
751
+ // Files that present in current directory snapshot
752
+ // but absent in previous are added to watch list and
753
+ // emit `add` event.
754
+ if (item === target || (!target && !previous.has(item))) {
755
+ this.fsw._incrReadyCount();
756
+ // ensure relativeness of path is preserved in case of watcher reuse
757
+ path$1 = path.join(dir, path.relative(dir, path$1));
758
+ this._addToNodeFs(path$1, initialAdd, wh, depth + 1);
759
+ }
760
+ })
761
+ .on(EV.ERROR, this._boundHandleError);
762
+ return new Promise((resolve, reject) => {
763
+ if (!stream)
764
+ return reject();
765
+ stream.once(STR_END, () => {
766
+ if (this.fsw.closed) {
767
+ stream = undefined;
768
+ return;
769
+ }
770
+ const wasThrottled = throttler ? throttler.clear() : false;
771
+ resolve(undefined);
772
+ // Files that absent in current directory snapshot
773
+ // but present in previous emit `remove` event
774
+ // and are removed from @watched[directory].
775
+ previous
776
+ .getChildren()
777
+ .filter((item) => {
778
+ return item !== directory && !current.has(item);
779
+ })
780
+ .forEach((item) => {
781
+ this.fsw._remove(directory, item);
782
+ });
783
+ stream = undefined;
784
+ // one more time for any missed in case changes came in extremely quickly
785
+ if (wasThrottled)
786
+ this._handleRead(directory, false, wh, target, dir, depth, throttler);
787
+ });
788
+ });
789
+ }
790
+ /**
791
+ * Read directory to add / remove files from `@watched` list and re-read it on change.
792
+ * @param dir fs path
793
+ * @param stats
794
+ * @param initialAdd
795
+ * @param depth relative to user-supplied path
796
+ * @param target child path targeted for watch
797
+ * @param wh Common watch helpers for this path
798
+ * @param realpath
799
+ * @returns closer for the watcher instance.
800
+ */
801
+ async _handleDir(dir, stats, initialAdd, depth, target, wh, realpath) {
802
+ const parentDir = this.fsw._getWatchedDir(path.dirname(dir));
803
+ const tracked = parentDir.has(path.basename(dir));
804
+ if (!(initialAdd && this.fsw.options.ignoreInitial) && !target && !tracked) {
805
+ this.fsw._emit(EV.ADD_DIR, dir, stats);
806
+ }
807
+ // ensure dir is tracked (harmless if redundant)
808
+ parentDir.add(path.basename(dir));
809
+ this.fsw._getWatchedDir(dir);
810
+ let throttler;
811
+ let closer;
812
+ const oDepth = this.fsw.options.depth;
813
+ if ((oDepth == null || depth <= oDepth) && !this.fsw._symlinkPaths.has(realpath)) {
814
+ if (!target) {
815
+ await this._handleRead(dir, initialAdd, wh, target, dir, depth, throttler);
816
+ if (this.fsw.closed)
817
+ return;
818
+ }
819
+ closer = this._watchWithNodeFs(dir, (dirPath, stats) => {
820
+ // if current directory is removed, do nothing
821
+ if (stats && stats.mtimeMs === 0)
822
+ return;
823
+ this._handleRead(dirPath, false, wh, target, dir, depth, throttler);
824
+ });
825
+ }
826
+ return closer;
827
+ }
828
+ /**
829
+ * Handle added file, directory, or glob pattern.
830
+ * Delegates call to _handleFile / _handleDir after checks.
831
+ * @param path to file or ir
832
+ * @param initialAdd was the file added at watch instantiation?
833
+ * @param priorWh depth relative to user-supplied path
834
+ * @param depth Child path actually targeted for watch
835
+ * @param target Child path actually targeted for watch
836
+ */
837
+ async _addToNodeFs(path$1, initialAdd, priorWh, depth, target) {
838
+ const ready = this.fsw._emitReady;
839
+ if (this.fsw._isIgnored(path$1) || this.fsw.closed) {
840
+ ready();
841
+ return false;
842
+ }
843
+ const wh = this.fsw._getWatchHelpers(path$1);
844
+ if (priorWh) {
845
+ wh.filterPath = (entry) => priorWh.filterPath(entry);
846
+ wh.filterDir = (entry) => priorWh.filterDir(entry);
847
+ }
848
+ // evaluate what is at the path we're being asked to watch
849
+ try {
850
+ const stats = await statMethods[wh.statMethod](wh.watchPath);
851
+ if (this.fsw.closed)
852
+ return;
853
+ if (this.fsw._isIgnored(wh.watchPath, stats)) {
854
+ ready();
855
+ return false;
856
+ }
857
+ const follow = this.fsw.options.followSymlinks;
858
+ let closer;
859
+ if (stats.isDirectory()) {
860
+ const absPath = path.resolve(path$1);
861
+ const targetPath = follow ? await realpath(path$1) : path$1;
862
+ if (this.fsw.closed)
863
+ return;
864
+ closer = await this._handleDir(wh.watchPath, stats, initialAdd, depth, target, wh, targetPath);
865
+ if (this.fsw.closed)
866
+ return;
867
+ // preserve this symlink's target path
868
+ if (absPath !== targetPath && targetPath !== undefined) {
869
+ this.fsw._symlinkPaths.set(absPath, targetPath);
870
+ }
871
+ }
872
+ else if (stats.isSymbolicLink()) {
873
+ const targetPath = follow ? await realpath(path$1) : path$1;
874
+ if (this.fsw.closed)
875
+ return;
876
+ const parent = path.dirname(wh.watchPath);
877
+ this.fsw._getWatchedDir(parent).add(wh.watchPath);
878
+ this.fsw._emit(EV.ADD, wh.watchPath, stats);
879
+ closer = await this._handleDir(parent, stats, initialAdd, depth, path$1, wh, targetPath);
880
+ if (this.fsw.closed)
881
+ return;
882
+ // preserve this symlink's target path
883
+ if (targetPath !== undefined) {
884
+ this.fsw._symlinkPaths.set(path.resolve(path$1), targetPath);
885
+ }
886
+ }
887
+ else {
888
+ closer = this._handleFile(wh.watchPath, stats, initialAdd);
889
+ }
890
+ ready();
891
+ if (closer)
892
+ this.fsw._addPathCloser(path$1, closer);
893
+ return false;
894
+ }
895
+ catch (error) {
896
+ if (this.fsw._handleError(error)) {
897
+ ready();
898
+ return path$1;
899
+ }
900
+ }
901
+ }
902
+ }
903
+
904
+ /*! chokidar - MIT License (c) 2012 Paul Miller (paulmillr.com) */
905
+ const SLASH = '/';
906
+ const SLASH_SLASH = '//';
907
+ const ONE_DOT = '.';
908
+ const TWO_DOTS = '..';
909
+ const STRING_TYPE = 'string';
910
+ const BACK_SLASH_RE = /\\/g;
911
+ const DOUBLE_SLASH_RE = /\/\//g;
912
+ const DOT_RE = /\..*\.(sw[px])$|~$|\.subl.*\.tmp/;
913
+ const REPLACER_RE = /^\.[/\\]/;
914
+ function arrify(item) {
915
+ return Array.isArray(item) ? item : [item];
916
+ }
917
+ const isMatcherObject = (matcher) => typeof matcher === 'object' && matcher !== null && !(matcher instanceof RegExp);
918
+ function createPattern(matcher) {
919
+ if (typeof matcher === 'function')
920
+ return matcher;
921
+ if (typeof matcher === 'string')
922
+ return (string) => matcher === string;
923
+ if (matcher instanceof RegExp)
924
+ return (string) => matcher.test(string);
925
+ if (typeof matcher === 'object' && matcher !== null) {
926
+ return (string) => {
927
+ if (matcher.path === string)
928
+ return true;
929
+ if (matcher.recursive) {
930
+ const relative = path.relative(matcher.path, string);
931
+ if (!relative) {
932
+ return false;
933
+ }
934
+ return !relative.startsWith('..') && !path.isAbsolute(relative);
935
+ }
936
+ return false;
937
+ };
938
+ }
939
+ return () => false;
940
+ }
941
+ function normalizePath(path$1) {
942
+ if (typeof path$1 !== 'string')
943
+ throw new Error('string expected');
944
+ path$1 = path.normalize(path$1);
945
+ path$1 = path$1.replace(/\\/g, '/');
946
+ let prepend = false;
947
+ if (path$1.startsWith('//'))
948
+ prepend = true;
949
+ path$1 = path$1.replace(DOUBLE_SLASH_RE, '/');
950
+ if (prepend)
951
+ path$1 = '/' + path$1;
952
+ return path$1;
953
+ }
954
+ function matchPatterns(patterns, testString, stats) {
955
+ const path = normalizePath(testString);
956
+ for (let index = 0; index < patterns.length; index++) {
957
+ const pattern = patterns[index];
958
+ if (pattern(path, stats)) {
959
+ return true;
960
+ }
961
+ }
962
+ return false;
963
+ }
964
+ function anymatch(matchers, testString) {
965
+ if (matchers == null) {
966
+ throw new TypeError('anymatch: specify first argument');
967
+ }
968
+ // Early cache for matchers.
969
+ const matchersArray = arrify(matchers);
970
+ const patterns = matchersArray.map((matcher) => createPattern(matcher));
971
+ {
972
+ return (testString, stats) => {
973
+ return matchPatterns(patterns, testString, stats);
974
+ };
975
+ }
976
+ }
977
+ const unifyPaths = (paths_) => {
978
+ const paths = arrify(paths_).flat();
979
+ if (!paths.every((p) => typeof p === STRING_TYPE)) {
980
+ throw new TypeError(`Non-string provided as watch path: ${paths}`);
981
+ }
982
+ return paths.map(normalizePathToUnix);
983
+ };
984
+ // If SLASH_SLASH occurs at the beginning of path, it is not replaced
985
+ // because "//StoragePC/DrivePool/Movies" is a valid network path
986
+ const toUnix = (string) => {
987
+ let str = string.replace(BACK_SLASH_RE, SLASH);
988
+ let prepend = false;
989
+ if (str.startsWith(SLASH_SLASH)) {
990
+ prepend = true;
991
+ }
992
+ str = str.replace(DOUBLE_SLASH_RE, SLASH);
993
+ if (prepend) {
994
+ str = SLASH + str;
995
+ }
996
+ return str;
997
+ };
998
+ // Our version of upath.normalize
999
+ // TODO: this is not equal to path-normalize module - investigate why
1000
+ const normalizePathToUnix = (path$1) => toUnix(path.normalize(toUnix(path$1)));
1001
+ // TODO: refactor
1002
+ const normalizeIgnored = (cwd = '') => (path$1) => {
1003
+ if (typeof path$1 === 'string') {
1004
+ return normalizePathToUnix(path.isAbsolute(path$1) ? path$1 : path.join(cwd, path$1));
1005
+ }
1006
+ else {
1007
+ return path$1;
1008
+ }
1009
+ };
1010
+ const getAbsolutePath = (path$1, cwd) => {
1011
+ if (path.isAbsolute(path$1)) {
1012
+ return path$1;
1013
+ }
1014
+ return path.join(cwd, path$1);
1015
+ };
1016
+ const EMPTY_SET = Object.freeze(new Set());
1017
+ /**
1018
+ * Directory entry.
1019
+ */
1020
+ class DirEntry {
1021
+ path;
1022
+ _removeWatcher;
1023
+ items;
1024
+ constructor(dir, removeWatcher) {
1025
+ this.path = dir;
1026
+ this._removeWatcher = removeWatcher;
1027
+ this.items = new Set();
1028
+ }
1029
+ add(item) {
1030
+ const { items } = this;
1031
+ if (!items)
1032
+ return;
1033
+ if (item !== ONE_DOT && item !== TWO_DOTS)
1034
+ items.add(item);
1035
+ }
1036
+ async remove(item) {
1037
+ const { items } = this;
1038
+ if (!items)
1039
+ return;
1040
+ items.delete(item);
1041
+ if (items.size > 0)
1042
+ return;
1043
+ const dir = this.path;
1044
+ try {
1045
+ await readdir(dir);
1046
+ }
1047
+ catch (err) {
1048
+ if (this._removeWatcher) {
1049
+ this._removeWatcher(path.dirname(dir), path.basename(dir));
1050
+ }
1051
+ }
1052
+ }
1053
+ has(item) {
1054
+ const { items } = this;
1055
+ if (!items)
1056
+ return;
1057
+ return items.has(item);
1058
+ }
1059
+ getChildren() {
1060
+ const { items } = this;
1061
+ if (!items)
1062
+ return [];
1063
+ return [...items.values()];
1064
+ }
1065
+ dispose() {
1066
+ this.items.clear();
1067
+ this.path = '';
1068
+ this._removeWatcher = EMPTY_FN;
1069
+ this.items = EMPTY_SET;
1070
+ Object.freeze(this);
1071
+ }
1072
+ }
1073
+ const STAT_METHOD_F = 'stat';
1074
+ const STAT_METHOD_L = 'lstat';
1075
+ class WatchHelper {
1076
+ fsw;
1077
+ path;
1078
+ watchPath;
1079
+ fullWatchPath;
1080
+ dirParts;
1081
+ followSymlinks;
1082
+ statMethod;
1083
+ constructor(path$1, follow, fsw) {
1084
+ this.fsw = fsw;
1085
+ const watchPath = path$1;
1086
+ this.path = path$1 = path$1.replace(REPLACER_RE, '');
1087
+ this.watchPath = watchPath;
1088
+ this.fullWatchPath = path.resolve(watchPath);
1089
+ this.dirParts = [];
1090
+ this.dirParts.forEach((parts) => {
1091
+ if (parts.length > 1)
1092
+ parts.pop();
1093
+ });
1094
+ this.followSymlinks = follow;
1095
+ this.statMethod = follow ? STAT_METHOD_F : STAT_METHOD_L;
1096
+ }
1097
+ entryPath(entry) {
1098
+ return path.join(this.watchPath, path.relative(this.watchPath, entry.fullPath));
1099
+ }
1100
+ filterPath(entry) {
1101
+ const { stats } = entry;
1102
+ if (stats && stats.isSymbolicLink())
1103
+ return this.filterDir(entry);
1104
+ const resolvedPath = this.entryPath(entry);
1105
+ // TODO: what if stats is undefined? remove !
1106
+ return this.fsw._isntIgnored(resolvedPath, stats) && this.fsw._hasReadPermissions(stats);
1107
+ }
1108
+ filterDir(entry) {
1109
+ return this.fsw._isntIgnored(this.entryPath(entry), entry.stats);
1110
+ }
1111
+ }
1112
+ /**
1113
+ * Watches files & directories for changes. Emitted events:
1114
+ * `add`, `addDir`, `change`, `unlink`, `unlinkDir`, `all`, `error`
1115
+ *
1116
+ * new FSWatcher()
1117
+ * .add(directories)
1118
+ * .on('add', path => log('File', path, 'was added'))
1119
+ */
1120
+ class FSWatcher extends EventEmitter {
1121
+ closed;
1122
+ options;
1123
+ _closers;
1124
+ _ignoredPaths;
1125
+ _throttled;
1126
+ _streams;
1127
+ _symlinkPaths;
1128
+ _watched;
1129
+ _pendingWrites;
1130
+ _pendingUnlinks;
1131
+ _readyCount;
1132
+ _emitReady;
1133
+ _closePromise;
1134
+ _userIgnored;
1135
+ _readyEmitted;
1136
+ _emitRaw;
1137
+ _boundRemove;
1138
+ _nodeFsHandler;
1139
+ // Not indenting methods for history sake; for now.
1140
+ constructor(_opts = {}) {
1141
+ super();
1142
+ this.closed = false;
1143
+ this._closers = new Map();
1144
+ this._ignoredPaths = new Set();
1145
+ this._throttled = new Map();
1146
+ this._streams = new Set();
1147
+ this._symlinkPaths = new Map();
1148
+ this._watched = new Map();
1149
+ this._pendingWrites = new Map();
1150
+ this._pendingUnlinks = new Map();
1151
+ this._readyCount = 0;
1152
+ this._readyEmitted = false;
1153
+ const awf = _opts.awaitWriteFinish;
1154
+ const DEF_AWF = { stabilityThreshold: 2000, pollInterval: 100 };
1155
+ const opts = {
1156
+ // Defaults
1157
+ persistent: true,
1158
+ ignoreInitial: false,
1159
+ ignorePermissionErrors: false,
1160
+ interval: 100,
1161
+ binaryInterval: 300,
1162
+ followSymlinks: true,
1163
+ usePolling: false,
1164
+ // useAsync: false,
1165
+ atomic: true, // NOTE: overwritten later (depends on usePolling)
1166
+ ..._opts,
1167
+ // Change format
1168
+ ignored: _opts.ignored ? arrify(_opts.ignored) : arrify([]),
1169
+ awaitWriteFinish: awf === true ? DEF_AWF : typeof awf === 'object' ? { ...DEF_AWF, ...awf } : false,
1170
+ };
1171
+ // Always default to polling on IBM i because fs.watch() is not available on IBM i.
1172
+ if (isIBMi)
1173
+ opts.usePolling = true;
1174
+ // Editor atomic write normalization enabled by default with fs.watch
1175
+ if (opts.atomic === undefined)
1176
+ opts.atomic = !opts.usePolling;
1177
+ // opts.atomic = typeof _opts.atomic === 'number' ? _opts.atomic : 100;
1178
+ // Global override. Useful for developers, who need to force polling for all
1179
+ // instances of chokidar, regardless of usage / dependency depth
1180
+ const envPoll = process.env.CHOKIDAR_USEPOLLING;
1181
+ if (envPoll !== undefined) {
1182
+ const envLower = envPoll.toLowerCase();
1183
+ if (envLower === 'false' || envLower === '0')
1184
+ opts.usePolling = false;
1185
+ else if (envLower === 'true' || envLower === '1')
1186
+ opts.usePolling = true;
1187
+ else
1188
+ opts.usePolling = !!envLower;
1189
+ }
1190
+ const envInterval = process.env.CHOKIDAR_INTERVAL;
1191
+ if (envInterval)
1192
+ opts.interval = Number.parseInt(envInterval, 10);
1193
+ // This is done to emit ready only once, but each 'add' will increase that?
1194
+ let readyCalls = 0;
1195
+ this._emitReady = () => {
1196
+ readyCalls++;
1197
+ if (readyCalls >= this._readyCount) {
1198
+ this._emitReady = EMPTY_FN;
1199
+ this._readyEmitted = true;
1200
+ // use process.nextTick to allow time for listener to be bound
1201
+ process.nextTick(() => this.emit(EVENTS.READY));
1202
+ }
1203
+ };
1204
+ this._emitRaw = (...args) => this.emit(EVENTS.RAW, ...args);
1205
+ this._boundRemove = this._remove.bind(this);
1206
+ this.options = opts;
1207
+ this._nodeFsHandler = new NodeFsHandler(this);
1208
+ // You’re frozen when your heart’s not open.
1209
+ Object.freeze(opts);
1210
+ }
1211
+ _addIgnoredPath(matcher) {
1212
+ if (isMatcherObject(matcher)) {
1213
+ // return early if we already have a deeply equal matcher object
1214
+ for (const ignored of this._ignoredPaths) {
1215
+ if (isMatcherObject(ignored) &&
1216
+ ignored.path === matcher.path &&
1217
+ ignored.recursive === matcher.recursive) {
1218
+ return;
1219
+ }
1220
+ }
1221
+ }
1222
+ this._ignoredPaths.add(matcher);
1223
+ }
1224
+ _removeIgnoredPath(matcher) {
1225
+ this._ignoredPaths.delete(matcher);
1226
+ // now find any matcher objects with the matcher as path
1227
+ if (typeof matcher === 'string') {
1228
+ for (const ignored of this._ignoredPaths) {
1229
+ // TODO (43081j): make this more efficient.
1230
+ // probably just make a `this._ignoredDirectories` or some
1231
+ // such thing.
1232
+ if (isMatcherObject(ignored) && ignored.path === matcher) {
1233
+ this._ignoredPaths.delete(ignored);
1234
+ }
1235
+ }
1236
+ }
1237
+ }
1238
+ // Public methods
1239
+ /**
1240
+ * Adds paths to be watched on an existing FSWatcher instance.
1241
+ * @param paths_ file or file list. Other arguments are unused
1242
+ */
1243
+ add(paths_, _origAdd, _internal) {
1244
+ const { cwd } = this.options;
1245
+ this.closed = false;
1246
+ this._closePromise = undefined;
1247
+ let paths = unifyPaths(paths_);
1248
+ if (cwd) {
1249
+ paths = paths.map((path) => {
1250
+ const absPath = getAbsolutePath(path, cwd);
1251
+ // Check `path` instead of `absPath` because the cwd portion can't be a glob
1252
+ return absPath;
1253
+ });
1254
+ }
1255
+ paths.forEach((path) => {
1256
+ this._removeIgnoredPath(path);
1257
+ });
1258
+ this._userIgnored = undefined;
1259
+ if (!this._readyCount)
1260
+ this._readyCount = 0;
1261
+ this._readyCount += paths.length;
1262
+ Promise.all(paths.map(async (path) => {
1263
+ const res = await this._nodeFsHandler._addToNodeFs(path, !_internal, undefined, 0, _origAdd);
1264
+ if (res)
1265
+ this._emitReady();
1266
+ return res;
1267
+ })).then((results) => {
1268
+ if (this.closed)
1269
+ return;
1270
+ results.forEach((item) => {
1271
+ if (item)
1272
+ this.add(path.dirname(item), path.basename(_origAdd || item));
1273
+ });
1274
+ });
1275
+ return this;
1276
+ }
1277
+ /**
1278
+ * Close watchers or start ignoring events from specified paths.
1279
+ */
1280
+ unwatch(paths_) {
1281
+ if (this.closed)
1282
+ return this;
1283
+ const paths = unifyPaths(paths_);
1284
+ const { cwd } = this.options;
1285
+ paths.forEach((path$1) => {
1286
+ // convert to absolute path unless relative path already matches
1287
+ if (!path.isAbsolute(path$1) && !this._closers.has(path$1)) {
1288
+ if (cwd)
1289
+ path$1 = path.join(cwd, path$1);
1290
+ path$1 = path.resolve(path$1);
1291
+ }
1292
+ this._closePath(path$1);
1293
+ this._addIgnoredPath(path$1);
1294
+ if (this._watched.has(path$1)) {
1295
+ this._addIgnoredPath({
1296
+ path: path$1,
1297
+ recursive: true,
1298
+ });
1299
+ }
1300
+ // reset the cached userIgnored anymatch fn
1301
+ // to make ignoredPaths changes effective
1302
+ this._userIgnored = undefined;
1303
+ });
1304
+ return this;
1305
+ }
1306
+ /**
1307
+ * Close watchers and remove all listeners from watched paths.
1308
+ */
1309
+ close() {
1310
+ if (this._closePromise) {
1311
+ return this._closePromise;
1312
+ }
1313
+ this.closed = true;
1314
+ // Memory management.
1315
+ this.removeAllListeners();
1316
+ const closers = [];
1317
+ this._closers.forEach((closerList) => closerList.forEach((closer) => {
1318
+ const promise = closer();
1319
+ if (promise instanceof Promise)
1320
+ closers.push(promise);
1321
+ }));
1322
+ this._streams.forEach((stream) => stream.destroy());
1323
+ this._userIgnored = undefined;
1324
+ this._readyCount = 0;
1325
+ this._readyEmitted = false;
1326
+ this._watched.forEach((dirent) => dirent.dispose());
1327
+ this._closers.clear();
1328
+ this._watched.clear();
1329
+ this._streams.clear();
1330
+ this._symlinkPaths.clear();
1331
+ this._throttled.clear();
1332
+ this._closePromise = closers.length
1333
+ ? Promise.all(closers).then(() => undefined)
1334
+ : Promise.resolve();
1335
+ return this._closePromise;
1336
+ }
1337
+ /**
1338
+ * Expose list of watched paths
1339
+ * @returns for chaining
1340
+ */
1341
+ getWatched() {
1342
+ const watchList = {};
1343
+ this._watched.forEach((entry, dir) => {
1344
+ const key = this.options.cwd ? path.relative(this.options.cwd, dir) : dir;
1345
+ const index = key || ONE_DOT;
1346
+ watchList[index] = entry.getChildren().sort();
1347
+ });
1348
+ return watchList;
1349
+ }
1350
+ emitWithAll(event, args) {
1351
+ this.emit(event, ...args);
1352
+ if (event !== EVENTS.ERROR)
1353
+ this.emit(EVENTS.ALL, event, ...args);
1354
+ }
1355
+ // Common helpers
1356
+ // --------------
1357
+ /**
1358
+ * Normalize and emit events.
1359
+ * Calling _emit DOES NOT MEAN emit() would be called!
1360
+ * @param event Type of event
1361
+ * @param path File or directory path
1362
+ * @param stats arguments to be passed with event
1363
+ * @returns the error if defined, otherwise the value of the FSWatcher instance's `closed` flag
1364
+ */
1365
+ async _emit(event, path$1, stats) {
1366
+ if (this.closed)
1367
+ return;
1368
+ const opts = this.options;
1369
+ if (isWindows)
1370
+ path$1 = path.normalize(path$1);
1371
+ if (opts.cwd)
1372
+ path$1 = path.relative(opts.cwd, path$1);
1373
+ const args = [path$1];
1374
+ if (stats != null)
1375
+ args.push(stats);
1376
+ const awf = opts.awaitWriteFinish;
1377
+ let pw;
1378
+ if (awf && (pw = this._pendingWrites.get(path$1))) {
1379
+ pw.lastChange = new Date();
1380
+ return this;
1381
+ }
1382
+ if (opts.atomic) {
1383
+ if (event === EVENTS.UNLINK) {
1384
+ this._pendingUnlinks.set(path$1, [event, ...args]);
1385
+ setTimeout(() => {
1386
+ this._pendingUnlinks.forEach((entry, path) => {
1387
+ this.emit(...entry);
1388
+ this.emit(EVENTS.ALL, ...entry);
1389
+ this._pendingUnlinks.delete(path);
1390
+ });
1391
+ }, typeof opts.atomic === 'number' ? opts.atomic : 100);
1392
+ return this;
1393
+ }
1394
+ if (event === EVENTS.ADD && this._pendingUnlinks.has(path$1)) {
1395
+ event = EVENTS.CHANGE;
1396
+ this._pendingUnlinks.delete(path$1);
1397
+ }
1398
+ }
1399
+ if (awf && (event === EVENTS.ADD || event === EVENTS.CHANGE) && this._readyEmitted) {
1400
+ const awfEmit = (err, stats) => {
1401
+ if (err) {
1402
+ event = EVENTS.ERROR;
1403
+ args[0] = err;
1404
+ this.emitWithAll(event, args);
1405
+ }
1406
+ else if (stats) {
1407
+ // if stats doesn't exist the file must have been deleted
1408
+ if (args.length > 1) {
1409
+ args[1] = stats;
1410
+ }
1411
+ else {
1412
+ args.push(stats);
1413
+ }
1414
+ this.emitWithAll(event, args);
1415
+ }
1416
+ };
1417
+ this._awaitWriteFinish(path$1, awf.stabilityThreshold, event, awfEmit);
1418
+ return this;
1419
+ }
1420
+ if (event === EVENTS.CHANGE) {
1421
+ const isThrottled = !this._throttle(EVENTS.CHANGE, path$1, 50);
1422
+ if (isThrottled)
1423
+ return this;
1424
+ }
1425
+ if (opts.alwaysStat &&
1426
+ stats === undefined &&
1427
+ (event === EVENTS.ADD || event === EVENTS.ADD_DIR || event === EVENTS.CHANGE)) {
1428
+ const fullPath = opts.cwd ? path.join(opts.cwd, path$1) : path$1;
1429
+ let stats;
1430
+ try {
1431
+ stats = await stat(fullPath);
1432
+ }
1433
+ catch (err) {
1434
+ // do nothing
1435
+ }
1436
+ // Suppress event when fs_stat fails, to avoid sending undefined 'stat'
1437
+ if (!stats || this.closed)
1438
+ return;
1439
+ args.push(stats);
1440
+ }
1441
+ this.emitWithAll(event, args);
1442
+ return this;
1443
+ }
1444
+ /**
1445
+ * Common handler for errors
1446
+ * @returns The error if defined, otherwise the value of the FSWatcher instance's `closed` flag
1447
+ */
1448
+ _handleError(error) {
1449
+ const code = error && error.code;
1450
+ if (error &&
1451
+ code !== 'ENOENT' &&
1452
+ code !== 'ENOTDIR' &&
1453
+ (!this.options.ignorePermissionErrors || (code !== 'EPERM' && code !== 'EACCES'))) {
1454
+ this.emit(EVENTS.ERROR, error);
1455
+ }
1456
+ return error || this.closed;
1457
+ }
1458
+ /**
1459
+ * Helper utility for throttling
1460
+ * @param actionType type being throttled
1461
+ * @param path being acted upon
1462
+ * @param timeout duration of time to suppress duplicate actions
1463
+ * @returns tracking object or false if action should be suppressed
1464
+ */
1465
+ _throttle(actionType, path, timeout) {
1466
+ if (!this._throttled.has(actionType)) {
1467
+ this._throttled.set(actionType, new Map());
1468
+ }
1469
+ const action = this._throttled.get(actionType);
1470
+ if (!action)
1471
+ throw new Error('invalid throttle');
1472
+ const actionPath = action.get(path);
1473
+ if (actionPath) {
1474
+ actionPath.count++;
1475
+ return false;
1476
+ }
1477
+ // eslint-disable-next-line prefer-const
1478
+ let timeoutObject;
1479
+ const clear = () => {
1480
+ const item = action.get(path);
1481
+ const count = item ? item.count : 0;
1482
+ action.delete(path);
1483
+ clearTimeout(timeoutObject);
1484
+ if (item)
1485
+ clearTimeout(item.timeoutObject);
1486
+ return count;
1487
+ };
1488
+ timeoutObject = setTimeout(clear, timeout);
1489
+ const thr = { timeoutObject, clear, count: 0 };
1490
+ action.set(path, thr);
1491
+ return thr;
1492
+ }
1493
+ _incrReadyCount() {
1494
+ return this._readyCount++;
1495
+ }
1496
+ /**
1497
+ * Awaits write operation to finish.
1498
+ * Polls a newly created file for size variations. When files size does not change for 'threshold' milliseconds calls callback.
1499
+ * @param path being acted upon
1500
+ * @param threshold Time in milliseconds a file size must be fixed before acknowledging write OP is finished
1501
+ * @param event
1502
+ * @param awfEmit Callback to be called when ready for event to be emitted.
1503
+ */
1504
+ _awaitWriteFinish(path$1, threshold, event, awfEmit) {
1505
+ const awf = this.options.awaitWriteFinish;
1506
+ if (typeof awf !== 'object')
1507
+ return;
1508
+ const pollInterval = awf.pollInterval;
1509
+ let timeoutHandler;
1510
+ let fullPath = path$1;
1511
+ if (this.options.cwd && !path.isAbsolute(path$1)) {
1512
+ fullPath = path.join(this.options.cwd, path$1);
1513
+ }
1514
+ const now = new Date();
1515
+ const writes = this._pendingWrites;
1516
+ function awaitWriteFinishFn(prevStat) {
1517
+ stat$1(fullPath, (err, curStat) => {
1518
+ if (err || !writes.has(path$1)) {
1519
+ if (err && err.code !== 'ENOENT')
1520
+ awfEmit(err);
1521
+ return;
1522
+ }
1523
+ const now = Number(new Date());
1524
+ if (prevStat && curStat.size !== prevStat.size) {
1525
+ writes.get(path$1).lastChange = now;
1526
+ }
1527
+ const pw = writes.get(path$1);
1528
+ const df = now - pw.lastChange;
1529
+ if (df >= threshold) {
1530
+ writes.delete(path$1);
1531
+ awfEmit(undefined, curStat);
1532
+ }
1533
+ else {
1534
+ timeoutHandler = setTimeout(awaitWriteFinishFn, pollInterval, curStat);
1535
+ }
1536
+ });
1537
+ }
1538
+ if (!writes.has(path$1)) {
1539
+ writes.set(path$1, {
1540
+ lastChange: now,
1541
+ cancelWait: () => {
1542
+ writes.delete(path$1);
1543
+ clearTimeout(timeoutHandler);
1544
+ return event;
1545
+ },
1546
+ });
1547
+ timeoutHandler = setTimeout(awaitWriteFinishFn, pollInterval);
1548
+ }
1549
+ }
1550
+ /**
1551
+ * Determines whether user has asked to ignore this path.
1552
+ */
1553
+ _isIgnored(path, stats) {
1554
+ if (this.options.atomic && DOT_RE.test(path))
1555
+ return true;
1556
+ if (!this._userIgnored) {
1557
+ const { cwd } = this.options;
1558
+ const ign = this.options.ignored;
1559
+ const ignored = (ign || []).map(normalizeIgnored(cwd));
1560
+ const ignoredPaths = [...this._ignoredPaths];
1561
+ const list = [...ignoredPaths.map(normalizeIgnored(cwd)), ...ignored];
1562
+ this._userIgnored = anymatch(list);
1563
+ }
1564
+ return this._userIgnored(path, stats);
1565
+ }
1566
+ _isntIgnored(path, stat) {
1567
+ return !this._isIgnored(path, stat);
1568
+ }
1569
+ /**
1570
+ * Provides a set of common helpers and properties relating to symlink handling.
1571
+ * @param path file or directory pattern being watched
1572
+ */
1573
+ _getWatchHelpers(path) {
1574
+ return new WatchHelper(path, this.options.followSymlinks, this);
1575
+ }
1576
+ // Directory helpers
1577
+ // -----------------
1578
+ /**
1579
+ * Provides directory tracking objects
1580
+ * @param directory path of the directory
1581
+ */
1582
+ _getWatchedDir(directory) {
1583
+ const dir = path.resolve(directory);
1584
+ if (!this._watched.has(dir))
1585
+ this._watched.set(dir, new DirEntry(dir, this._boundRemove));
1586
+ return this._watched.get(dir);
1587
+ }
1588
+ // File helpers
1589
+ // ------------
1590
+ /**
1591
+ * Check for read permissions: https://stackoverflow.com/a/11781404/1358405
1592
+ */
1593
+ _hasReadPermissions(stats) {
1594
+ if (this.options.ignorePermissionErrors)
1595
+ return true;
1596
+ return Boolean(Number(stats.mode) & 0o400);
1597
+ }
1598
+ /**
1599
+ * Handles emitting unlink events for
1600
+ * files and directories, and via recursion, for
1601
+ * files and directories within directories that are unlinked
1602
+ * @param directory within which the following item is located
1603
+ * @param item base path of item/directory
1604
+ */
1605
+ _remove(directory, item, isDirectory) {
1606
+ // if what is being deleted is a directory, get that directory's paths
1607
+ // for recursive deleting and cleaning of watched object
1608
+ // if it is not a directory, nestedDirectoryChildren will be empty array
1609
+ const path$1 = path.join(directory, item);
1610
+ const fullPath = path.resolve(path$1);
1611
+ isDirectory =
1612
+ isDirectory != null ? isDirectory : this._watched.has(path$1) || this._watched.has(fullPath);
1613
+ // prevent duplicate handling in case of arriving here nearly simultaneously
1614
+ // via multiple paths (such as _handleFile and _handleDir)
1615
+ if (!this._throttle('remove', path$1, 100))
1616
+ return;
1617
+ // if the only watched file is removed, watch for its return
1618
+ if (!isDirectory && this._watched.size === 1) {
1619
+ this.add(directory, item, true);
1620
+ }
1621
+ // This will create a new entry in the watched object in either case
1622
+ // so we got to do the directory check beforehand
1623
+ const wp = this._getWatchedDir(path$1);
1624
+ const nestedDirectoryChildren = wp.getChildren();
1625
+ // Recursively remove children directories / files.
1626
+ nestedDirectoryChildren.forEach((nested) => this._remove(path$1, nested));
1627
+ // Check if item was on the watched list and remove it
1628
+ const parent = this._getWatchedDir(directory);
1629
+ const wasTracked = parent.has(item);
1630
+ parent.remove(item);
1631
+ // Fixes issue #1042 -> Relative paths were detected and added as symlinks
1632
+ // (https://github.com/paulmillr/chokidar/blob/e1753ddbc9571bdc33b4a4af172d52cb6e611c10/lib/nodefs-handler.js#L612),
1633
+ // but never removed from the map in case the path was deleted.
1634
+ // This leads to an incorrect state if the path was recreated:
1635
+ // https://github.com/paulmillr/chokidar/blob/e1753ddbc9571bdc33b4a4af172d52cb6e611c10/lib/nodefs-handler.js#L553
1636
+ if (this._symlinkPaths.has(fullPath)) {
1637
+ this._symlinkPaths.delete(fullPath);
1638
+ }
1639
+ // If we wait for this file to be fully written, cancel the wait.
1640
+ let relPath = path$1;
1641
+ if (this.options.cwd)
1642
+ relPath = path.relative(this.options.cwd, path$1);
1643
+ if (this.options.awaitWriteFinish && this._pendingWrites.has(relPath)) {
1644
+ const event = this._pendingWrites.get(relPath).cancelWait();
1645
+ if (event === EVENTS.ADD)
1646
+ return;
1647
+ }
1648
+ // The Entry will either be a directory that just got removed
1649
+ // or a bogus entry to a file, in either case we have to remove it
1650
+ this._watched.delete(path$1);
1651
+ this._watched.delete(fullPath);
1652
+ const eventName = isDirectory ? EVENTS.UNLINK_DIR : EVENTS.UNLINK;
1653
+ if (wasTracked && !this._isIgnored(path$1))
1654
+ this._emit(eventName, path$1);
1655
+ // Avoid conflicts if we later create another file with the same name
1656
+ this._closePath(path$1);
1657
+ }
1658
+ /**
1659
+ * Closes all watchers for a path
1660
+ */
1661
+ _closePath(path$1) {
1662
+ this._closeFile(path$1);
1663
+ const dir = path.dirname(path$1);
1664
+ this._getWatchedDir(dir).remove(path.basename(path$1));
1665
+ }
1666
+ /**
1667
+ * Closes only file-specific watchers
1668
+ */
1669
+ _closeFile(path) {
1670
+ const closers = this._closers.get(path);
1671
+ if (!closers)
1672
+ return;
1673
+ closers.forEach((closer) => closer());
1674
+ this._closers.delete(path);
1675
+ }
1676
+ _addPathCloser(path, closer) {
1677
+ if (!closer)
1678
+ return;
1679
+ let list = this._closers.get(path);
1680
+ if (!list) {
1681
+ list = [];
1682
+ this._closers.set(path, list);
1683
+ }
1684
+ list.push(closer);
1685
+ }
1686
+ _readdirp(root, opts) {
1687
+ if (this.closed)
1688
+ return;
1689
+ const options = { type: EVENTS.ALL, alwaysStat: true, lstat: true, ...opts, depth: 0 };
1690
+ let stream = readdirp(root, options);
1691
+ this._streams.add(stream);
1692
+ stream.once(STR_CLOSE, () => {
1693
+ stream = undefined;
1694
+ });
1695
+ stream.once(STR_END, () => {
1696
+ if (stream) {
1697
+ this._streams.delete(stream);
1698
+ stream = undefined;
1699
+ }
1700
+ });
1701
+ return stream;
1702
+ }
1703
+ }
1704
+ /**
1705
+ * Instantiates watcher with paths to be tracked.
1706
+ * @param paths file / directory paths
1707
+ * @param options opts, such as `atomic`, `awaitWriteFinish`, `ignored`, and others
1708
+ * @returns an instance of FSWatcher for chaining.
1709
+ * @example
1710
+ * const watcher = watch('.').on('all', (event, path) => { console.log(event, path); });
1711
+ * watch('.', { atomic: true, awaitWriteFinish: true, ignored: (f, stats) => stats?.isFile() && !f.endsWith('.js') })
1712
+ */
1713
+ function watch(paths, options = {}) {
1714
+ const watcher = new FSWatcher(options);
1715
+ watcher.add(paths);
1716
+ return watcher;
1717
+ }
1718
+ const chokidar = { watch: watch, FSWatcher: FSWatcher };
1719
+
1720
+ function emptyState(lastHead = "uncommitted") {
1721
+ return { files: {}, lastHead, nudged: {} };
1722
+ }
1723
+ async function loadState(cwd) {
1724
+ const p = path__default.join(cwd, ".codewiki", ".state.json");
1725
+ const s = await readJson(p);
1726
+ return s ?? emptyState();
1727
+ }
1728
+ async function saveState(cwd, state) {
1729
+ const p = path__default.join(cwd, ".codewiki", ".state.json");
1730
+ await writeJson(p, state);
1731
+ }
1732
+ async function changedFilesSince(cwd, lastHead) {
1733
+ if (lastHead === "uncommitted" || !lastHead) return [];
1734
+ let hasRef = false;
1735
+ try {
1736
+ const git = simpleGit({ baseDir: cwd });
1737
+ hasRef = await git.raw(["rev-parse", "--verify", lastHead]).then(
1738
+ () => true,
1739
+ () => false
1740
+ );
1741
+ if (!hasRef) return [];
1742
+ const out = await git.raw(["diff", "--name-only", lastHead]);
1743
+ return out.trim().split("\n").filter(Boolean).map((p) => p.replace(/\\/g, "/"));
1744
+ } catch {
1745
+ return [];
1746
+ }
1747
+ }
1748
+ async function currentHead(cwd) {
1749
+ try {
1750
+ const out = await simpleGit({ baseDir: cwd }).raw(["rev-parse", "HEAD"]);
1751
+ return out.trim().slice(0, 12) || "uncommitted";
1752
+ } catch {
1753
+ return "uncommitted";
1754
+ }
1755
+ }
1756
+ async function enqueueInvalidation(cwd, repoPath) {
1757
+ const p = path__default.join(cwd, ".codewiki", ".state.json");
1758
+ const state = await loadState(cwd);
1759
+ const cur = state.files[repoPath];
1760
+ state.files[repoPath] = {
1761
+ hash: cur?.hash ?? "",
1762
+ mtimeMs: cur?.mtimeMs ?? 0,
1763
+ size: cur?.size ?? 0,
1764
+ lastIndexedAt: cur?.lastIndexedAt ?? (/* @__PURE__ */ new Date()).toISOString(),
1765
+ symbols: cur?.symbols ?? 0,
1766
+ publicSignatureChanged: true
1767
+ };
1768
+ await atomicWriteText(p, JSON.stringify(state, null, 2));
1769
+ }
1770
+
1771
+ const pkg = { version: "0.1.0" };
1772
+ async function main() {
1773
+ const program = new Command();
1774
+ program.name("codewiki").description("Token-efficient code wiki generator and Claude Code plugin entry point").version(pkg.version).option("--cwd <path>", "project root", process$1.cwd());
1775
+ program.command("build").description("Build or rebuild the .codewiki/ index for the current project").option("--full", "force a full rebuild (skip incremental cache)").option("--config <path>", "path to a config JSON file").option("--quiet", "suppress non-error output").option("--verbose", "verbose output").action(async (opts) => {
1776
+ const cwd = path__default.resolve(opts.parent?.cwd ?? process$1.cwd());
1777
+ const result = await buildWiki({
1778
+ cwd,
1779
+ configPath: opts.config,
1780
+ full: !!opts.full
1781
+ });
1782
+ process$1.stdout.write(
1783
+ `code-wiki built .codewiki/ in ${result.durationMs}ms (${result.fileCount} files, ${result.moduleCount} modules)
1784
+ `
1785
+ );
1786
+ });
1787
+ program.command("enrich").description(
1788
+ "Optional LLM enrichment (requires ANTHROPIC_API_KEY). File-level + module-level via Claude Haiku + Sonnet."
1789
+ ).option("--config <path>", "path to a config JSON file").action(async (opts) => {
1790
+ const cwd = path__default.resolve(opts.parent?.cwd ?? process$1.cwd());
1791
+ if (!process$1.env.ANTHROPIC_API_KEY) {
1792
+ process$1.stderr.write(
1793
+ "codewiki enrich: ANTHROPIC_API_KEY not set. Skipping (zero cost).\n"
1794
+ );
1795
+ process$1.exit(0);
1796
+ }
1797
+ process$1.stdout.write("codewiki enrich: starting file + module passes...\n");
1798
+ const { ensureCacheDir, runEnrichmentCli } = await import('./chunks/llm.mjs');
1799
+ await ensureCacheDir(cwd);
1800
+ const t0 = Date.now();
1801
+ await runEnrichmentCli(cwd);
1802
+ process$1.stdout.write(`codewiki enrich: done in ${Date.now() - t0}ms
1803
+ `);
1804
+ });
1805
+ program.command("refresh").description(
1806
+ "Incrementally refresh .codewiki/. Reports git diff since last index; re-runs the full build (incremental re-render lands in v0.2)."
1807
+ ).option("--config <path>", "path to a config JSON file").option("--full", "force a full rebuild").action(async (opts) => {
1808
+ const cwd = path__default.resolve(opts.parent?.cwd ?? process$1.cwd());
1809
+ const state = await loadState(cwd);
1810
+ const head = await currentHead(cwd);
1811
+ const changed = await changedFilesSince(cwd, state.lastHead);
1812
+ process$1.stdout.write(
1813
+ `code-wiki refresh: ${state.lastHead} -> ${head}, ${changed.length} files in git diff.
1814
+ `
1815
+ );
1816
+ if (changed.length > 0 && changed.length <= 20) {
1817
+ for (const f of changed) process$1.stdout.write(` - ${f}
1818
+ `);
1819
+ } else if (changed.length > 20) {
1820
+ for (const f of changed.slice(0, 20)) process$1.stdout.write(` - ${f}
1821
+ `);
1822
+ process$1.stdout.write(` ... and ${changed.length - 20} more
1823
+ `);
1824
+ }
1825
+ const t0 = Date.now();
1826
+ await buildWiki({
1827
+ cwd,
1828
+ configPath: opts.config,
1829
+ full: !!opts.full
1830
+ });
1831
+ const newState = {
1832
+ ...state,
1833
+ lastHead: head,
1834
+ files: state.files
1835
+ // populated by subsequent invalidations
1836
+ };
1837
+ await saveState(cwd, newState);
1838
+ process$1.stdout.write(
1839
+ `code-wiki refreshed .codewiki/ in ${Date.now() - t0}ms
1840
+ `
1841
+ );
1842
+ });
1843
+ program.command("watch").description(
1844
+ "Watch the working tree and run /wiki-refresh on file changes. Ctrl-C to stop."
1845
+ ).option("--config <path>", "path to a config JSON file").option("--debounce <ms>", "debounce delay in ms", "500").action(async (opts) => {
1846
+ const cwd = path__default.resolve(opts.parent?.cwd ?? process$1.cwd());
1847
+ const debounceMs = Number(opts.debounce ?? 500);
1848
+ process$1.stdout.write(`code-wiki watch: cwd=${cwd} (Ctrl-C to stop)
1849
+ `);
1850
+ const watcher = chokidar.watch(cwd, {
1851
+ ignored: (p) => p.includes(`${path__default.sep}.codewiki${path__default.sep}`) || p.includes(`${path__default.sep}node_modules${path__default.sep}`) || p.includes(`${path__default.sep}.git${path__default.sep}`) || p.includes(`${path__default.sep}dist${path__default.sep}`) || p.endsWith("package-lock.json"),
1852
+ ignoreInitial: true,
1853
+ persistent: true,
1854
+ awaitWriteFinish: { stabilityThreshold: 200, pollInterval: 50 }
1855
+ });
1856
+ let pendingTimer = null;
1857
+ const pending = /* @__PURE__ */ new Set();
1858
+ const flush = async () => {
1859
+ const files = [...pending];
1860
+ pending.clear();
1861
+ for (const f of files) {
1862
+ const rel = path__default.relative(cwd, f).split(path__default.sep).join("/");
1863
+ try {
1864
+ await enqueueInvalidation(cwd, rel);
1865
+ } catch {
1866
+ }
1867
+ }
1868
+ if (files.length > 0) {
1869
+ process$1.stdout.write(
1870
+ `code-wiki: ${files.length} change(s) detected, rebuilding...
1871
+ `
1872
+ );
1873
+ try {
1874
+ const r = await buildWiki({ cwd });
1875
+ process$1.stdout.write(` -> rebuilt ${r.fileCount} files in ${r.durationMs}ms
1876
+ `);
1877
+ } catch (err) {
1878
+ process$1.stderr.write(` ! rebuild failed: ${err.message ?? err}
1879
+ `);
1880
+ }
1881
+ }
1882
+ };
1883
+ watcher.on("change", (path2) => {
1884
+ if (pendingTimer) clearTimeout(pendingTimer);
1885
+ pending.add(path2);
1886
+ pendingTimer = setTimeout(flush, debounceMs);
1887
+ });
1888
+ watcher.on("add", (path2) => {
1889
+ if (pendingTimer) clearTimeout(pendingTimer);
1890
+ pending.add(path2);
1891
+ pendingTimer = setTimeout(flush, debounceMs);
1892
+ });
1893
+ watcher.on("unlink", (path2) => {
1894
+ if (pendingTimer) clearTimeout(pendingTimer);
1895
+ pending.add(path2);
1896
+ pendingTimer = setTimeout(flush, debounceMs);
1897
+ });
1898
+ await new Promise(() => {
1899
+ });
1900
+ });
1901
+ program.command("search <query>").description("Search the wiki for symbols, files, or modules").option("--limit <n>", "max results", "20").option("--json", "emit machine-readable JSON").action(async (query, opts) => {
1902
+ const cwd = path__default.resolve(opts.parent?.cwd ?? process$1.cwd());
1903
+ const cfg = await loadConfig(cwd);
1904
+ const indexPath = path__default.join(cwd, cfg.outDir, ".index.json");
1905
+ const tree = await readJson(indexPath);
1906
+ if (!tree) {
1907
+ process$1.stderr.write(`No .codewiki found at ${cfg.outDir}/. Run \`codewiki build\` first.
1908
+ `);
1909
+ process$1.exit(1);
1910
+ }
1911
+ const q = String(query).toLowerCase();
1912
+ const results = [];
1913
+ for (const m of tree.modules) {
1914
+ if (m.id.toLowerCase().includes(q)) results.push({ kind: "module", id: m.id, module: m.id, file: m.path });
1915
+ }
1916
+ for (const f of tree.files) {
1917
+ if (f.path.toLowerCase().includes(q)) results.push({ kind: "file", id: f.path, file: f.path, module: f.module });
1918
+ }
1919
+ for (const s of tree.symbols) {
1920
+ if (s.name.toLowerCase().includes(q)) results.push({ kind: "symbol", id: s.id, file: s.file });
1921
+ }
1922
+ const limit = Number(opts.limit) || 20;
1923
+ const trimmed = results.slice(0, limit);
1924
+ if (opts.json) {
1925
+ process$1.stdout.write(JSON.stringify(trimmed, null, 2) + "\n");
1926
+ } else {
1927
+ for (const r of trimmed) {
1928
+ process$1.stdout.write(`${r.kind.padEnd(7)} ${r.id} ${r.file ?? ""}
1929
+ `);
1930
+ }
1931
+ }
1932
+ });
1933
+ program.command("show <pathOrSymbol>").description("Print a wiki page to stdout").action(async (pathOrSymbol) => {
1934
+ const cwd = path__default.resolve(process$1.cwd());
1935
+ const cfg = await loadConfig(cwd);
1936
+ const wikiBase = path__default.join(cwd, cfg.outDir);
1937
+ const rel = String(pathOrSymbol).replace(/^\.\//, "");
1938
+ const candidates = [
1939
+ path__default.join(wikiBase, rel.endsWith(".md") ? rel : `${rel}.md`),
1940
+ path__default.join(wikiBase, "files", `${rel}.md`),
1941
+ path__default.join(wikiBase, "modules", `${rel}.md`),
1942
+ path__default.join(wikiBase, "symbols", `${rel.replace("::", "/")}.md`)
1943
+ ];
1944
+ for (const c of candidates) {
1945
+ if (await exists(c)) {
1946
+ const buf = await import('node:fs/promises').then((m) => m.readFile(c, "utf8"));
1947
+ process$1.stdout.write(buf);
1948
+ return;
1949
+ }
1950
+ }
1951
+ process$1.stderr.write(`No wiki page matches ${pathOrSymbol}
1952
+ `);
1953
+ process$1.exit(1);
1954
+ });
1955
+ program.command("invalidate <path>").description("Mark a single file for incremental re-render (used by hooks)").action(async (p) => {
1956
+ const cwd = path__default.resolve(process$1.cwd());
1957
+ await enqueueInvalidation(cwd, String(p));
1958
+ });
1959
+ program.command("validate").description("Sanity-check that .codewiki/ is well-formed").action(async () => {
1960
+ const cwd = path__default.resolve(process$1.cwd());
1961
+ const cfg = await loadConfig(cwd);
1962
+ const base = path__default.join(cwd, cfg.outDir);
1963
+ if (!await exists(base)) {
1964
+ process$1.stderr.write(`No .codewiki at ${cfg.outDir}. Run \`codewiki build\` first.
1965
+ `);
1966
+ process$1.exit(1);
1967
+ }
1968
+ const meta = await readJson(path__default.join(base, ".meta.json"));
1969
+ if (!meta || meta.schemaVersion !== 1) {
1970
+ process$1.stderr.write(`.meta.json missing or wrong schemaVersion: got ${meta?.schemaVersion}
1971
+ `);
1972
+ process$1.exit(1);
1973
+ }
1974
+ process$1.stdout.write(`${cfg.outDir} looks valid.
1975
+ `);
1976
+ });
1977
+ program.command("clean").description("Remove .codewiki/ from the current project").option("--yes", "do not prompt").action(async (opts) => {
1978
+ const cwd = path__default.resolve(process$1.cwd());
1979
+ const cfg = await loadConfig(cwd);
1980
+ const dir = path__default.join(cwd, cfg.outDir);
1981
+ if (await exists(dir)) {
1982
+ if (!opts.yes) {
1983
+ process$1.stderr.write(`Pass --yes to confirm removal of ${cfg.outDir}/
1984
+ `);
1985
+ process$1.exit(2);
1986
+ }
1987
+ const fs = await import('node:fs/promises');
1988
+ await fs.rm(dir, { recursive: true, force: true });
1989
+ process$1.stdout.write(`Removed ${cfg.outDir}/
1990
+ `);
1991
+ } else {
1992
+ process$1.stdout.write(`No ${cfg.outDir}/ to remove.
1993
+ `);
1994
+ }
1995
+ });
1996
+ await program.parseAsync(process$1.argv);
1997
+ }
1998
+ main().catch((err) => {
1999
+ process$1.stderr.write(`codewiki: ${err?.stack ?? err}
2000
+ `);
2001
+ process$1.exit(1);
2002
+ });