repositories / pi-ext

pi-ext

bugabingas pi extensions

owned by bugabinga

extensions/llmiterate/watcher.ts

Raw
File outline
import * as fs from "node:fs";
import * as path from "node:path";
import type { LlmiterateConfig } from "./config";
import { GitIgnoreMatcher } from "./gitignore";
import {
	type CompiledPathFilter,
	shouldIncludeCompiledPath,
	shouldWatchDirectory,
} from "./path-filter";
import { toSlash } from "./util";

const DIRECTORY_REFRESH_MS = 50;
const IGNORE_FILE_NAMES = new Set([".gitignore", ".ignore"]);

type FileHandler = (absolutePath: string) => void;
type ErrorHandler = () => void;

interface RefreshOptions {
	scheduleFiles: boolean;
	fileMtimeSinceMs?: number;
}

interface IgnoreContext {
	matcher: GitIgnoreMatcher;
	stamp: string;
}

export class ProjectWatcher {
	private readonly watchers = new Map<string, fs.FSWatcher>();
	private readonly fileTimers = new Map<
		string,
		ReturnType<typeof setTimeout>
	>();
	private readonly dirTimers = new Map<string, ReturnType<typeof setTimeout>>();
	private readonly ignoreContexts = new Map<string, IgnoreContext>();
	private readonly scheduledFileMtimes = new Map<string, number>();
	private watchLimitHit = false;
	private eventMtimeSinceMs: number | undefined;

	public errorCount = 0;

	get watcherCount(): number {
		return this.watchers.size;
	}

	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);
		const startedAt = performance.timeOrigin + performance.now();
		this.watchTree(root, { scheduleFiles: false });
		// fs.watch can miss changes made immediately after watcher creation.
		// Reconcile watched dirs once, but only queue files modified after start.
		this.scheduleWatchedTreeRefresh(root, {
			scheduleFiles: true,
			fileMtimeSinceMs: startedAt,
		});
	}

	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();
		this.ignoreContexts.clear();
		this.scheduledFileMtimes.clear();
		this.eventMtimeSinceMs = undefined;
	}

	scanAll(onFile: (absolutePath: string) => number): number {
		let total = 0;
		this.walkFiles(this.root, (file) => {
			total += onFile(file);
		});
		return total;
	}

	private watchTree(dir: string, options: RefreshOptions): void {
		const abs = path.resolve(dir);
		if (this.watchers.has(abs)) return;

		if (!this.reserveWatchSlot()) return;

		try {
			const watcher = fs.watch(
				abs,
				{ persistent: false },
				(eventType, filename) => {
					if (!filename) {
						this.scheduleWatchedTreeRefresh(abs, { scheduleFiles: true }, true);
						return;
					}

					const child = path.join(abs, filename.toString());
					if (IGNORE_FILE_NAMES.has(path.basename(child))) {
						this.scheduleWatchedTreeRefresh(
							abs,
							{ scheduleFiles: false },
							true,
						);
						return;
					}

					this.handlePathEvent(child);
					if (eventType === "rename")
						this.scheduleDirectoryRefresh(abs, { scheduleFiles: true }, true);
				},
			);
			watcher.on("error", () => {
				this.recordError();
				this.unwatchTree(abs);
			});
			watcher.on("close", () => this.watchers.delete(abs));
			this.watchers.set(abs, watcher);
		} catch {
			this.recordError();
			this.refreshDirectory(abs, options);
			return;
		}

		this.refreshDirectory(abs, options);
	}

	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, { scheduleFiles: true });
			return;
		}

		if (
			stat.isFile() &&
			this.isFreshEnough(absPath, {
				scheduleFiles: true,
				fileMtimeSinceMs: this.eventMtimeSinceMs,
			})
		)
			this.scheduleFile(absPath);
	}

	private refreshDirectory(abs: string, options: RefreshOptions): void {
		this.loadIgnoreContext(abs);

		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 (
					this.isIgnored(rel, true) ||
					!shouldWatchDirectory(rel, this.pathFilter)
				)
					continue;
				this.watchTree(child, options);
				continue;
			}
			if (entry.isFile()) {
				if (
					this.isIgnored(rel, false) ||
					!shouldIncludeCompiledPath(rel, this.pathFilter)
				)
					continue;

				if (!options.scheduleFiles) {
					this.recordFileMtime(rel, child);
					continue;
				}

				if (this.isFreshEnough(child, options)) this.scheduleFile(child);
			}
		}
	}

	private scheduleDirectoryRefresh(
		abs: string,
		options: RefreshOptions,
		reloadIgnores = false,
	): void {
		const existing = this.dirTimers.get(abs);
		if (existing) clearTimeout(existing);
		this.dirTimers.set(
			abs,
			setTimeout(() => {
				this.dirTimers.delete(abs);
				if (reloadIgnores) this.invalidateIgnoreContextsUnder(abs);
				this.reconcileWatchersUnder(abs);
				this.refreshDirectory(abs, options);
			}, DIRECTORY_REFRESH_MS),
		);
	}

	private scheduleWatchedTreeRefresh(
		abs: string,
		options: RefreshOptions,
		reloadIgnores = false,
	): void {
		const existing = this.dirTimers.get(abs);
		if (existing) clearTimeout(existing);
		this.dirTimers.set(
			abs,
			setTimeout(() => {
				this.dirTimers.delete(abs);
				if (reloadIgnores) this.invalidateIgnoreContextsUnder(abs);
				this.reconcileWatchersUnder(abs);
				for (const dir of [...this.watchers.keys()]) {
					if (dir === abs || isDescendant(abs, dir))
						this.refreshDirectory(dir, options);
				}
			}, DIRECTORY_REFRESH_MS),
		);
	}

	private reconcileWatchersUnder(abs: string): void {
		for (const dir of [...this.watchers.keys()]) {
			if (dir !== abs && !isDescendant(abs, dir)) continue;
			const rel = this.projectRel(dir);
			if (!fs.existsSync(dir) || (rel && this.isIgnored(rel, true)))
				this.unwatchTree(dir);
		}
	}

	private unwatchTree(abs: string): void {
		const dirs = [
			abs,
			...[...this.watchers.keys()].filter((dir) => isDescendant(abs, dir)),
		].sort((a, b) => b.length - a.length);
		for (const dir of dirs) {
			const watcher = this.watchers.get(dir);
			this.watchers.delete(dir);
			this.ignoreContexts.delete(this.projectRel(dir));
			try {
				watcher?.close();
			} catch {}
		}
	}

	private reserveWatchSlot(): boolean {
		if (this.watchers.size < this.config.maxWatchDirs) return true;
		if (!this.watchLimitHit) {
			this.watchLimitHit = true;
			this.recordError();
		}
		return false;
	}

	private isFreshEnough(absPath: string, options: RefreshOptions): boolean {
		if (options.fileMtimeSinceMs === undefined) return true;
		try {
			return fs.statSync(absPath).mtimeMs > options.fileMtimeSinceMs;
		} catch {
			return false;
		}
	}

	private scheduleFile(absPath: string): void {
		const rel = this.projectRel(absPath);
		if (
			!isSafeProjectRel(rel) ||
			this.isIgnored(rel, false) ||
			!shouldIncludeCompiledPath(rel, this.pathFilter)
		)
			return;

		const mtimeMs = fileMtimeMs(absPath);
		const previousMtimeMs = this.scheduledFileMtimes.get(rel);
		if (
			mtimeMs !== undefined &&
			previousMtimeMs !== undefined &&
			mtimeMs <= previousMtimeMs
		)
			return;
		if (mtimeMs !== undefined) this.scheduledFileMtimes.set(rel, mtimeMs);

		const existing = this.fileTimers.get(rel);
		if (existing) clearTimeout(existing);
		this.fileTimers.set(
			rel,
			setTimeout(() => {
				this.fileTimers.delete(rel);
				// Refresh may run after debounce; pin emitted mtime to avoid duplicate queues.
				const readyMtimeMs = fileMtimeMs(absPath);
				if (readyMtimeMs !== undefined)
					this.scheduledFileMtimes.set(rel, readyMtimeMs);
				this.onFileReady(absPath);
			}, this.config.debounceMs),
		);
	}

	private recordFileMtime(rel: string, absPath: string): void {
		const mtimeMs = fileMtimeMs(absPath);
		if (mtimeMs !== undefined) this.scheduledFileMtimes.set(rel, mtimeMs);
	}

	private walkFiles(dir: string, onFile: FileHandler): void {
		this.loadIgnoreContext(dir);

		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 (
					this.isIgnored(rel, true) ||
					!shouldWatchDirectory(rel, this.pathFilter)
				)
					continue;
				this.walkFiles(abs, onFile);
				continue;
			}
			if (
				entry.isFile() &&
				!this.isIgnored(rel, false) &&
				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) &&
			!this.isIgnored(rel, true) &&
			shouldWatchDirectory(rel, this.pathFilter)
		);
	}

	private loadIgnoreContext(absDir: string): void {
		const rel = this.projectRel(absDir);
		const stamp = this.ignoreStamp(absDir);
		const cached = this.ignoreContexts.get(rel);
		if (cached?.stamp === stamp) return;

		const parent = path.dirname(absDir);
		if (parent !== absDir && isDescendant(this.root, absDir))
			this.loadIgnoreContext(parent);

		const matcher = new GitIgnoreMatcher();
		for (const name of IGNORE_FILE_NAMES) {
			try {
				matcher.add(fs.readFileSync(path.join(absDir, name), "utf-8"));
			} catch {}
		}
		this.ignoreContexts.set(rel, { matcher, stamp });
	}

	private isIgnored(relPath: string, directory: boolean): boolean {
		const rel = toSlash(relPath);
		this.loadIgnoreContext(path.dirname(path.join(this.root, rel)));
		for (const [base, context] of this.ignoreContexts) {
			if (base && rel !== base && !rel.startsWith(`${base}/`)) continue;
			const local = base ? rel.slice(base.length + 1) : rel;
			if (!local) continue;
			if (
				context.matcher.ignores(local) ||
				(directory && context.matcher.ignores(`${local}/`))
			)
				return true;
		}
		return false;
	}

	private ignoreStamp(absDir: string): string {
		return [...IGNORE_FILE_NAMES]
			.map((name) => {
				try {
					const stat = fs.statSync(path.join(absDir, name));
					return `${name}:${stat.mtimeMs}:${stat.size}`;
				} catch {
					return `${name}:missing`;
				}
			})
			.join("|");
	}

	private invalidateIgnoreContextsUnder(abs: string): void {
		const rel = this.projectRel(abs);
		for (const base of [...this.ignoreContexts.keys()]) {
			if (base === rel || !rel || base.startsWith(`${rel}/`))
				this.ignoreContexts.delete(base);
		}
	}

	private recordError(): void {
		this.errorCount++;
		this.onError();
	}
}

function fileMtimeMs(absPath: string): number | undefined {
	try {
		return fs.statSync(absPath).mtimeMs;
	} catch {
		return undefined;
	}
}

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);
}