import { readFileSync, statSync } from 'node:fs'; import { UNFOUND_INDEX } from '../constants'; import { normalizePath } from '../utils/normalizePath'; /* Bun.hash (Wyhash) returns a number — comparing numbers is faster than comparing strings and avoids the .toString() allocation. We use -1 as the "file unreadable" sentinel (impossible hash value). */ export const computeFileHash = (filePath: string) => { try { const fileContent = readFileSync(filePath); return Number(Bun.hash(fileContent)); } catch { return UNFOUND_INDEX; } }; /* This function checks if the file has changed by comparing its current hash to the previous hash this handles the detection of actual changes */ export const hasFileChanged = ( filePath: string, currentHash: number, previousHashes: Map ) => { // Normalize path for consistent Map key lookup across platforms const normalizedPath = normalizePath(filePath); const previousHash = previousHashes.get(normalizedPath); if (previousHash === undefined) { // First time seeing this file, definitely changed return true; } return previousHash !== currentHash; }; /* Whether a file the watcher has not hashed yet is just what this process loaded: last written before the process started. Watch-event bursts and the atomic-save recovery scan (every file touched in the last minute, e.g. by a checkout) report such files although nobody edited them. */ export const predatesProcess = ( filePath: string, previousHashes: Map, processStart = performance.timeOrigin ) => { if (previousHashes.has(normalizePath(filePath))) return false; try { return statSync(filePath).mtimeMs < processStart; } catch { return false; } };