import * as fs from "node:fs"; import * as path from "node:path"; import { shouldIncludeCompiledPath, shouldWatchDirectory, toSlash, type CompiledPathFilter, type LlmiterateConfig, } from "./core"; const DIRECTORY_REFRESH_MS = 250; type FileHandler = (absolutePath: string) => void; type ErrorHandler = () => void; export class ProjectWatcher { private readonly watchers = new Map(); private readonly fileTimers = new Map>(); private readonly dirTimers = new Map>(); public errorCount = 0; constructor( private readonly root: string, private readonly config: LlmiterateConfig, private readonly pathFilter: CompiledPathFilter, private readonly onFileReady: FileHandler, private readonly onError: ErrorHandler, ) {} start(): void { if (!shouldWatchDirectory("", this.pathFilter)) return; const root = path.resolve(this.root); this.watchTree(root); // fs.watch can miss changes made immediately after watcher creation. // One delayed reconciliation makes startup deterministic without polling. this.scheduleDirectoryRefresh(root); } stop(): void { for (const timer of this.fileTimers.values()) clearTimeout(timer); for (const timer of this.dirTimers.values()) clearTimeout(timer); for (const watcher of this.watchers.values()) watcher.close(); this.fileTimers.clear(); this.dirTimers.clear(); this.watchers.clear(); } scanAll(onFile: (absolutePath: string) => number): number { let total = 0; this.walkFiles(this.root, (file) => { total += onFile(file); }); return total; } private watchTree(dir: string): void { const abs = path.resolve(dir); if (this.watchers.has(abs)) return; try { const watcher = fs.watch(abs, { persistent: false }, (eventType, filename) => { if (!filename) { this.scheduleDirectoryRefresh(abs); return; } this.handlePathEvent(path.join(abs, filename.toString())); if (eventType === "rename") this.scheduleDirectoryRefresh(abs); }); watcher.on("error", () => { this.recordError(); this.unwatchTree(abs); }); watcher.on("close", () => this.watchers.delete(abs)); this.watchers.set(abs, watcher); } catch { this.recordError(); // fs.watch is not equally reliable across platforms/runtimes. Still scan // the directory once so startup/reconciliation catches already-written files. this.refreshDirectory(abs); return; } this.refreshDirectory(abs); } private handlePathEvent(absPath: string): void { let stat: fs.Stats | undefined; try { stat = fs.statSync(absPath); } catch { return; } if (stat.isDirectory()) { if (this.shouldWatchDir(absPath)) this.watchTree(absPath); return; } if (stat.isFile()) this.scheduleFile(absPath); } private refreshDirectory(abs: string): void { let entries: fs.Dirent[]; try { entries = fs.readdirSync(abs, { withFileTypes: true }); } catch { return; } for (const entry of entries) { const child = path.join(abs, entry.name); const rel = this.projectRel(child); if (entry.isDirectory()) { if (!shouldWatchDirectory(rel, this.pathFilter)) continue; this.watchTree(child); continue; } if (entry.isFile() && shouldIncludeCompiledPath(rel, this.pathFilter)) this.scheduleFile(child); } } private scheduleDirectoryRefresh(abs: string): void { const existing = this.dirTimers.get(abs); if (existing) clearTimeout(existing); this.dirTimers.set(abs, setTimeout(() => { this.dirTimers.delete(abs); this.reconcileWatchers(); this.refreshDirectory(abs); }, DIRECTORY_REFRESH_MS)); } private reconcileWatchers(): void { for (const dir of this.watchers.keys()) { if (!fs.existsSync(dir)) this.unwatchTree(dir); } } private unwatchTree(abs: string): void { const watcher = this.watchers.get(abs); this.watchers.delete(abs); try { watcher?.close(); } catch {} for (const dir of [...this.watchers.keys()]) { if (isDescendant(abs, dir)) this.unwatchTree(dir); } } private scheduleFile(absPath: string): void { const rel = this.projectRel(absPath); if (!isSafeProjectRel(rel) || !shouldIncludeCompiledPath(rel, this.pathFilter)) return; const existing = this.fileTimers.get(rel); if (existing) clearTimeout(existing); this.fileTimers.set(rel, setTimeout(() => { this.fileTimers.delete(rel); this.onFileReady(absPath); }, this.config.debounceMs)); } private walkFiles(dir: string, onFile: FileHandler): void { let entries: fs.Dirent[]; try { entries = fs.readdirSync(dir, { withFileTypes: true }); } catch { return; } for (const entry of entries) { const abs = path.join(dir, entry.name); const rel = this.projectRel(abs); if (entry.isDirectory()) { if (!shouldWatchDirectory(rel, this.pathFilter)) continue; this.walkFiles(abs, onFile); continue; } if (entry.isFile() && shouldIncludeCompiledPath(rel, this.pathFilter)) onFile(abs); } } private projectRel(absPath: string): string { return toSlash(path.relative(this.root, absPath)); } private shouldWatchDir(absPath: string): boolean { const rel = this.projectRel(absPath); return isSafeProjectRel(rel) && shouldWatchDirectory(rel, this.pathFilter); } private recordError(): void { this.errorCount++; this.onError(); } } function isSafeProjectRel(rel: string): boolean { return Boolean(rel) && !rel.startsWith("..") && !path.isAbsolute(rel); } function isDescendant(parent: string, child: string): boolean { const rel = path.relative(parent, child); return Boolean(rel) && !rel.startsWith("..") && !path.isAbsolute(rel); }