| 10 | } |
| 11 | |
| 12 | export class FileWatcher { |
| 13 | private watchers: fs.FSWatcher[] = []; |
| 14 | private callbacks: Set<() => void> = new Set(); |
| 15 | private debounceTimer: NodeJS.Timeout | null = null; |
| 16 | private options: Required<FileWatcherOptions>; |
| 17 | private watchedDirs: Set<string> = new Set(); |
| 18 | private isInitializing: boolean = false; |
| 19 | private lastErrorCode: string | null = null; |
| 20 | |
| 21 | constructor(options: FileWatcherOptions = {}) { |
| 22 | this.options = { |
| 23 | ignore: [...FILE_IGNORE_PATTERNS, ...(options.ignore || [])], |
| 24 | debounceMs: options.debounceMs || 1000, |
| 25 | maxDepth: options.maxDepth || 10, |
| 26 | }; |
| 27 | } |
| 28 | |
| 29 | private shouldIgnorePath(filePath: string): boolean { |
| 30 | const normalizedPath = path.normalize(filePath).replace(/\\/g, "/"); |
| 31 | |
| 32 | return this.options.ignore.some((pattern) => { |
| 33 | if (pattern.startsWith("**/")) { |
| 34 | const suffix = pattern.slice(3); |
| 35 | if (suffix.endsWith("/**")) { |
| 36 | // Directory pattern like **/node_modules/** |
| 37 | const dirName = suffix.slice(0, -3); |
| 38 | return ( |
| 39 | normalizedPath.includes(`/${dirName}/`) || |
| 40 | normalizedPath.endsWith(`/${dirName}`) || |
| 41 | normalizedPath === dirName |
| 42 | ); |
| 43 | } else if (suffix.startsWith("*")) { |
| 44 | // File pattern like **/*.tmp |
| 45 | const extension = suffix.slice(1); // Remove the '*' to get the extension |
| 46 | return normalizedPath.endsWith(extension); |
| 47 | } else { |
| 48 | // File pattern like **/package.json |
| 49 | return ( |
| 50 | normalizedPath.endsWith(`/${suffix}`) || |
| 51 | normalizedPath.endsWith(suffix) |
| 52 | ); |
| 53 | } |
| 54 | } |
| 55 | return normalizedPath.includes(pattern); |
| 56 | }); |
| 57 | } |
| 58 | |
| 59 | private triggerCallbacks(): void { |
| 60 | // Don't trigger callbacks during initialization |
| 61 | if (this.isInitializing) { |
| 62 | return; |
| 63 | } |
| 64 | |
| 65 | if (this.debounceTimer) { |
| 66 | clearTimeout(this.debounceTimer); |
| 67 | } |
| 68 | |
| 69 | this.debounceTimer = setTimeout(() => { |
nothing calls this directly
no test coverage detected