import { normalizeSourcePath } from './source-path.js'; import { readdirSync, statSync, watch as watchDirectory, type FSWatcher, } from 'node:fs'; import { basename, extname, isAbsolute, relative, resolve, sep } from 'node:path'; import { pathToFileURL } from 'node:url'; import type { Dispose } from '@zhin.js/plugin-runtime'; // Type-only: the index (and es-module-lexer's WebAssembly memory) loads on first use (#1250). import type { ModuleDependencyIndex, ModuleDependencyAnalysis, } from './module-dependency-index.js'; import type { ModuleRuntime, ModuleWatchRoot } from './module-runtime.js'; import { withToolPackageInstallHint } from './missing-tool-package.js'; import { isEditorTempFile } from './editor-temp-file.js'; import { ensureTypeScriptSpecifierRemap, publishPackageFileRevisions, publishRevisionablePackageRoots, } from './typescript-specifier-remap.js'; import { randomUUID } from 'node:crypto'; import { getEsmCacheEvictor, type EsmCacheEvictor } from './esm-cache-evictor.js'; export interface NativeDevelopmentModuleRuntimeOptions { readonly projectRoot: string; readonly watch?: boolean; /** * When the import graph of loaded entries is analyzed (#1250 `prod-runs-dependency-index`). * `eager` analyzes every entry as it loads, so file watching can map a changed helper back to its * entries at once. `lazy` loads entries without analysis and without loading `es-module-lexer`; * the graph is built from the loaded entries the first time `prepareInvalidation()` runs (an * explicit reload under `--no-watch`) and kept up to date from then on; each later call also * analyzes any committed entry the graph does not know yet. An entry whose analysis fails is * reported as a `ZhinModuleRuntimeWarning` process warning (code `ZHIN_DEPENDENCY_ANALYSIS_FAILED`) * and makes `requiresProcessRestart()` answer true for every other importable source (not * Markdown or YAML) while it stays loaded. * Defaults to `eager` with `watch` and `lazy` without it. */ readonly dependencyTracking?: 'eager' | 'lazy'; /** Optional scoped loader used only when the active Node loader rejects TSX. */ readonly tsxLoader?: TsxModuleLoader; /** * Evicts retired `zhin-generation` URLs from Node's ESM load cache after a * generation commits, so their module instances can be garbage collected. * Best effort: silently disabled when the runtime cannot reach the cache. * Defaults to on; `ZHIN_HMR_EVICT=0` turns it off. Pass an evictor to test. */ readonly evictRetiredModules?: boolean | EsmCacheEvictor; } /** Counters describing retired module eviction, for diagnostics and tests. */ export interface ModuleEvictionStats { readonly enabled: boolean; readonly evicted: number; } export interface TsxModuleLoader { load(source: string, parentURL: string): Promise; close?(): Promise; } const ignoredDirectories = new Set([ '.git', '.zhin', 'coverage', 'data', 'dist', 'lib', 'node_modules', ]); const watchedExtensions = new Set([ '.cjs', '.cts', '.js', '.json', '.jsx', '.md', '.mjs', '.mts', '.ts', '.tsx', '.yaml', '.yml', ]); const capabilityRoots = new Set([ 'adapters', 'agents', 'commands', 'components', 'handlers', 'hooks', 'mcps', 'middlewares', 'pages', 'prompt-sections', 'schedules', 'skills', 'tools', ]); /** * Uses Node's native ESM/TypeScript loader with dependency-aware cache busting * and portable filesystem watch support. */ export class NativeDevelopmentModuleRuntime implements ModuleRuntime { readonly #projectRoot: string; readonly #watchEnabled: boolean; readonly #tsxLoader: TsxModuleLoader | undefined; /** Created on first use: by every load when tracking is eager, else by `prepareInvalidation()`. */ #dependencies?: ModuleDependencyIndex; #dependenciesReady?: Promise; /** Lazy tracking: the in-flight `prepareInvalidation()` pass that brings the graph up to date. */ #graphReady?: Promise; /** * Lazy tracking: committed entries whose import analysis failed. Their imports are unknown, so * a reload of any other source cannot be planned safely while one of them is loaded. */ readonly #unanalyzedEntries = new Set(); readonly #eagerDependencies: boolean; readonly #watchers = new Set(); #pendingDependencies?: Map; #watchRoots: readonly string[]; #revision = 0; readonly #entryRevisions = new Map(); #closed = false; readonly #evictionOption: boolean | EsmCacheEvictor; #evictor?: EsmCacheEvictor | null; #evicted = 0; /** Revision each entry was actually loaded at, by the committed generation. */ readonly #committedRevisions = new Map(); #pendingRevisions?: Map; /** Mounted local Plugin package roots whose package-name imports reload with the importer (#1250). */ #revisionableRoots: readonly string[] = []; #rootsPublished?: Promise; /** * Files of revisionable packages imported by package name, with the revision of their latest * change (#1250): the loader hook loads them at it, so unchanged packages keep one instance. */ readonly #packageFileRevisions = new Map(); readonly #hookOwner = randomUUID(); readonly #isRevisionable = (source: string): boolean => this.#revisionableRoots.some((root) => isWithinRoot(root, source)); constructor(options: NativeDevelopmentModuleRuntimeOptions) { ensureTypeScriptSpecifierRemap(); this.#projectRoot = normalizeSourcePath(options.projectRoot); this.#watchEnabled = options.watch ?? true; this.#eagerDependencies = (options.dependencyTracking ?? (this.#watchEnabled ? 'eager' : 'lazy')) === 'eager'; this.#tsxLoader = options.tsxLoader; this.#watchRoots = normalizeWatchRoots([this.#projectRoot]); this.#evictionOption = options.evictRetiredModules ?? process.env.ZHIN_HMR_EVICT !== '0'; } async load(source: string): Promise { this.#assertOpen(); const normalized = normalizeSourcePath(source); if (isNativeTypeScriptSource(normalized)) assertNativeTypeScriptSupport(); // Lazy tracking skips the analysis until an explicit reload first needs the graph. const dependencies = this.#eagerDependencies ? await this.#dependencyIndex() : this.#dependencies; const analysis = this.#pendingDependencies?.get(normalized) ?? await dependencies?.analyze(normalized); const url = pathToFileURL(normalized); if (!this.#entryRevisions.has(normalized)) this.#entryRevisions.set(normalized, this.#revision); url.searchParams.set('zhin-generation', String(this.#entryRevisions.get(normalized))); let loaded: T; try { loaded = await import(url.href) as T; } catch (error) { if (!normalized.endsWith('.tsx') || !isUnsupportedTsxError(error) || !this.#tsxLoader) { throw withToolPackageInstallHint(error); } try { loaded = await this.#tsxLoader.load( url.href, pathToFileURL(`${this.#projectRoot}${sep}`).href, ); } catch (tsxError) { throw withToolPackageInstallHint(tsxError); } } const revision = this.#entryRevisions.get(normalized) ?? this.#revision; if (this.#pendingDependencies) { if (analysis) this.#pendingDependencies.set(normalized, analysis); this.#pendingRevisions?.set(normalized, revision); } else { if (analysis) dependencies?.commit(normalized, analysis); this.#committedRevisions.set(normalized, revision); } return loaded; } /** * Makes the dependency queries (`affectedSources`, `staleDependents`, `requiresProcessRestart`, * `invalidate`) complete before a reload. With lazy tracking the first call loads the index and * analyzes the committed entries as they are on disk now; later loads keep it current, and every * later call analyzes the committed entries still missing from the graph (an entry whose load began * before the index existed commits without analysis) and retries those whose analysis failed. A * failed call (the index could not load) is not cached. */ prepareInvalidation(): Promise { this.#assertOpen(); if (this.#eagerDependencies) return Promise.resolve(); // Every call reconciles, so an entry committed after an earlier pass took its snapshot (a load // that started before the index existed) still joins the graph; concurrent calls share a pass. this.#graphReady ??= this.#reconcileGraph().finally(() => { this.#graphReady = undefined; }); return this.#graphReady; } /** Analyzes every committed entry the graph does not know yet, including earlier failures. */ async #reconcileGraph(): Promise { const index = await this.#dependencyIndex(); const attempted = new Set(); for (;;) { const missing = [...this.#committedRevisions.keys()] .filter((entry) => !attempted.has(entry) && !index.hasEntry(entry)); if (missing.length === 0) break; for (const entry of missing) { attempted.add(entry); let analysis: ModuleDependencyAnalysis; try { analysis = await index.analyze(entry); } catch (error) { // Kept as unknown: `requiresProcessRestart` falls back to a restart while it is loaded. if (this.#committedRevisions.has(entry) && !this.#unanalyzedEntries.has(entry)) { this.#unanalyzedEntries.add(entry); emitDependencyAnalysisWarning(entry, error); } continue; } this.#unanalyzedEntries.delete(entry); // The entry may have been retired, or reloaded with a fresher analysis, meanwhile. if (this.#committedRevisions.has(entry) && !index.hasEntry(entry)) index.commit(entry, analysis); } } } /** True while a loaded entry other than `source` has imports the graph could not analyze. */ #hasUnanalyzedEntryBesides(source: string): boolean { for (const entry of this.#unanalyzedEntries) { if (entry === source) continue; if (this.#committedRevisions.has(entry) && !this.#dependencies?.hasEntry(entry)) return true; } return false; } #dependencyIndex(): Promise { if (this.#dependencies) return Promise.resolve(this.#dependencies); this.#dependenciesReady ??= import('./module-dependency-index.js').then(({ ModuleDependencyIndex: Index }) => { // Package-name imports are followed only into watched roots: nothing else reports a change. this.#dependencies ??= new Index({ followPackageImport: (source) => this.#watchRoots.some((root) => isWithin(root, source)), }); return this.#dependencies; }).catch((error: unknown) => { // A failed load is not cached: the next reload tries again (as `scaffold-wizard-loader`). this.#dependenciesReady = undefined; throw error; }); return this.#dependenciesReady; } invalidate(source: string): void | Promise { const impacted = this.#dependencies?.affectedSources(source, this.#isRevisionable) ?? []; const packageTargets = this.#dependencies?.changedPackageImportTargets( source, (file) => this.#revisionableRoots.find((root) => isWithinRoot(root, file)), ) ?? []; this.#dependencies?.invalidate(source); this.#revision += 1; for (const entry of new Set([normalizeSourcePath(source), ...impacted])) { this.#entryRevisions.set(entry, this.#revision); } for (const target of packageTargets) this.#packageFileRevisions.set(target, this.#revision); const revisionsPublished = packageTargets.length > 0 ? publishPackageFileRevisions(this.#hookOwner, packageTargets.map((target) => [target, String(this.#revision)] as const)) : undefined; // The loader hook must know the revisionable roots and changed package files before the // importers load again. if (!revisionsPublished) return this.#rootsPublished; return Promise.all([this.#rootsPublished, revisionsPublished]).then(() => undefined); } /** Without a dependency graph yet (lazy tracking before `prepareInvalidation()`), only the source itself. */ affectedSources(source: string): readonly string[] { return this.#dependencies?.affectedSources(source, this.#isRevisionable) ?? Object.freeze([normalizeSourcePath(source)]); } /** Loaded entries that keep their old instance of the source after a reload (#1250). */ staleDependents(source: string): readonly string[] { return this.#dependencies?.staleDependents(source, this.#isRevisionable) ?? []; } updateRevisionableRoots(roots: readonly string[]): void { this.#assertOpen(); const next = [...new Set(roots.map((root) => normalizeSourcePath(root)))].sort(); if (next.length === this.#revisionableRoots.length && next.every((root, index) => root === this.#revisionableRoots[index])) return; this.#revisionableRoots = Object.freeze(next); for (const file of this.#packageFileRevisions.keys()) { if (!next.some((root) => isWithinRoot(root, file))) this.#packageFileRevisions.delete(file); } this.#rootsPublished = publishRevisionablePackageRoots(this.#hookOwner, next); } requiresProcessRestart(source: string): boolean { const normalized = normalizeSourcePath(source); const packageRoot = nearestWatchRoot(this.#watchRoots, normalized); // Installed packages and external paths are intentionally not watched. // The HMR coordinator turns this into a visible process restart reason. if (!packageRoot || isNodeModulesSource(packageRoot, normalized)) return true; if (packageRoot === this.#projectRoot && basename(normalized).startsWith('.env')) return true; // Lazy tracking: an entry whose analysis failed may import this source; only a restart is safe. // Sources no JS import can reach (Markdown, YAML) keep their normal reload decision below. if (isModuleImportableSource(normalized) && this.#hasUnanalyzedEntryBesides(normalized)) return true; // Native ESM query revisions do not invalidate CommonJS require.cache. // Keep .cjs/.cts entries and their statically discovered closure on the // process boundary until the module runtime owns a CJS cache transaction. if (['.cjs', '.cts'].includes(extname(normalized)) || this.#dependencies?.hasCommonJsImpact(normalized)) return true; // A helper with one or more loaded entry importers is safe: the planner // invalidates those owned entries and the generation query refreshes their // complete project-local import closure. if (this.affectedSources(normalized).length > 1) return false; // An already loaded ESM entry has the same revisioned import closure as a // capability entry. Its manifest may name plugin.ts or any other filename; // Runtime ownership, rather than directory spelling, chooses its reload. if (this.#entryRevisions.has(normalized) && isExecutableSource(normalized)) return false; const parts = relative(packageRoot, normalized).split(sep); const capability = parts.findIndex((part) => capabilityRoots.has(part)); if (capability < 0) return isExecutableSource(normalized); const root = parts[capability]; if (root === 'agents' || root === 'skills') { const local = parts.slice(capability + 1); if (isNestedDirectoryEntry(local)) return false; return extname(normalized) !== '.md'; } if (root === 'commands') { const local = parts.slice(capability + 1); if (!isExecutableSource(normalized)) return extname(normalized) === '.json'; return local.length < 2 || !local.slice(0, -1).every(isCommandDirectorySegment); } if (root === 'adapters' || root === 'components' || root === 'handlers' || root === 'hooks' || root === 'mcps' || root === 'middlewares' || root === 'pages' || root === 'prompt-sections' || root === 'schedules' || root === 'tools') { const local = parts.slice(capability + 1); if (!isExecutableSource(normalized)) return extname(normalized) === '.json'; return local.length < 2 || !isNamedCapabilityDirectory(local[0] ?? '', root === 'tools'); } // Support files inside capability directories (e.g. commands/_utils.ts) // are not discovery entries: reloading the entry URL only bumps that // entry's zhin-generation, so the importer closure keeps the old code. return ['.cjs', '.cts', '.js', '.json', '.mjs', '.mts', '.ts', '.tsx'] .includes(extname(normalized)); } beginGeneration(): void { this.#assertOpen(); if (this.#pendingDependencies) { throw new Error('A module generation transaction is already active'); } this.#pendingDependencies = new Map(); this.#pendingRevisions = new Map(); } commitGeneration(sources: readonly string[]): void { this.#assertOpen(); for (const [entry, analysis] of this.#pendingDependencies ?? []) { this.#dependencies?.commit(entry, analysis); } this.#pendingDependencies = undefined; for (const [entry, revision] of this.#pendingRevisions ?? []) this.#committedRevisions.set(entry, revision); this.#pendingRevisions = undefined; this.#dependencies?.retain(sources); const retained = new Set(sources.map(normalizeSourcePath)); for (const entry of this.#entryRevisions.keys()) { if (!retained.has(entry)) this.#entryRevisions.delete(entry); } for (const entry of this.#committedRevisions.keys()) { if (!retained.has(entry)) this.#committedRevisions.delete(entry); } for (const entry of this.#unanalyzedEntries) { if (!retained.has(entry)) this.#unanalyzedEntries.delete(entry); } this.#evictRetiredRevisions(); } get evictionStats(): ModuleEvictionStats { return { enabled: Boolean(this.#resolveEvictor()), evicted: this.#evicted }; } #resolveEvictor(): EsmCacheEvictor | undefined { if (this.#evictor === undefined) { const option = this.#evictionOption; this.#evictor = option === false ? null : option === true ? getEsmCacheEvictor() ?? null : option; } return this.#evictor ?? undefined; } /** * A revision is live while the committed generation loaded some entry at it; * helpers inherit their importer's revision, so a URL whose revision no * committed entry was loaded at belongs only to retired generations (or to a * rolled-back attempt). Running code keeps its linked instances, so eviction * affects memory and never the identity of modules already in use. */ #evictRetiredRevisions(): void { if (this.#revision === 0) return; const evictor = this.#resolveEvictor(); if (!evictor) return; // Package files keep the revision of their latest change for every later importer. const live = new Set([...this.#committedRevisions.values(), ...this.#packageFileRevisions.values()].map(String)); for (const href of evictor.urls()) { if (!href.startsWith('file:') || !href.includes('zhin-generation=')) continue; let revision: string | null; try { revision = new URL(href).searchParams.get('zhin-generation'); } catch { continue; } if (revision !== null && !live.has(revision) && evictor.evict(href)) this.#evicted += 1; } } rollbackGeneration(): void { this.#pendingDependencies = undefined; this.#pendingRevisions = undefined; } updateWatchRoots(roots: readonly ModuleWatchRoot[]): void { this.#assertOpen(); const next = normalizeWatchRoots([ this.#projectRoot, ...roots.map((root) => root.root), ]); if (sameRoots(this.#watchRoots, next)) return; this.#watchRoots = next; // Cached closures followed package imports by the previous roots. this.#dependencies?.invalidateAll(); for (const watcher of this.#watchers) watcher.replaceRoots(next); } watch(listener: (source: string) => void): Dispose { this.#assertOpen(); if (!this.#watchEnabled) return () => undefined; const watcher = new PortableSourceWatcher(this.#watchRoots, listener); this.#watchers.add(watcher); return () => { watcher.close(); this.#watchers.delete(watcher); }; } async close(): Promise { if (this.#closed) return; this.#closed = true; for (const watcher of this.#watchers) watcher.close(); this.#watchers.clear(); this.#pendingDependencies = undefined; this.#dependencies?.clear(); this.#entryRevisions.clear(); this.#committedRevisions.clear(); this.#unanalyzedEntries.clear(); this.#pendingRevisions = undefined; this.#packageFileRevisions.clear(); if (this.#revisionableRoots.length > 0) { this.#revisionableRoots = []; await publishRevisionablePackageRoots(this.#hookOwner, []); } await this.#tsxLoader?.close?.(); } #assertOpen(): void { if (this.#closed) throw new Error('NativeDevelopmentModuleRuntime is closed'); } } function isCommandDirectorySegment(value: string): boolean { return /^[a-z0-9][a-z0-9-]*$/u.test(value) || (!/[A-Z]/u.test(value) && /[^\x00-\x7F]/u.test(value) && !/[\s/\\]/u.test(value)) || /^\[(?:\[)?(?:\.\.\.)?[a-zA-Z][a-zA-Z0-9]*\](?:\])?$/u.test(value); } function isNamedCapabilityDirectory(value: string, allowSnake: boolean): boolean { return allowSnake ? /^[a-z0-9][a-z0-9_-]*$/u.test(value) : /^[a-z0-9][a-z0-9-]*$/u.test(value); } function isDirectoryCapabilityEntry(parts: readonly string[]): boolean { return parts.length === 2 && parts[1] === `index${extname(parts[1] ?? '')}` && ['.cjs', '.cts', '.js', '.mjs', '.mts', '.ts', '.tsx'].includes(extname(parts[1] ?? '')); } function isNestedDirectoryEntry(parts: readonly string[]): boolean { const index = parts.indexOf('tools'); const hookIndex = parts.indexOf('hooks'); const capability = index >= 0 ? index : hookIndex; return capability >= 1 && isDirectoryCapabilityEntry(parts.slice(capability + 1)); } export function supportsNativeTypeScript( version = process.versions.node, execArguments: readonly string[] = process.execArgv, nodeOptions = process.env.NODE_OPTIONS ?? '', ): boolean { if ( execArguments.includes('--experimental-strip-types') || /(?:^|\s)--experimental-strip-types(?:\s|$)/u.test(nodeOptions) ) return true; const [major = 0, minor = 0] = version.split('.').map(Number); return major > 23 || (major === 23 && minor >= 6) || (major === 22 && minor >= 18); } export function assertNativeTypeScriptSupport(): void { if (supportsNativeTypeScript()) return; throw new Error([ `Node ${process.versions.node} does not enable native TypeScript by default.`, 'Use Node >=22.18.0 or start Node with --experimental-strip-types.', ].join(' ')); } function isUnsupportedTsxError(error: unknown): boolean { return error instanceof Error && 'code' in error && error.code === 'ERR_UNKNOWN_FILE_EXTENSION'; } /** The polling fallback walks every watch root synchronously, so it must stay infrequent. */ const pollIntervalMs = 1000; const nativeRetryInitialDelayMs = 5_000; const nativeRetryMaxDelayMs = 60_000; class PortableSourceWatcher { #watchers = new Set(); #pollTimer?: NodeJS.Timeout; #retryTimer?: NodeJS.Timeout; #retryDelayMs = nativeRetryInitialDelayMs; #nativeSince = 0; #snapshot: ReadonlyMap; #closed = false; #roots: readonly string[]; constructor( roots: readonly string[], private readonly listener: (source: string) => void, ) { this.#roots = normalizeWatchRoots(roots); this.#snapshot = sourceSnapshot(this.#roots); if (!this.#attachNativeWatchers()) this.#startPolling(); } replaceRoots(roots: readonly string[]): void { if (this.#closed) return; const next = normalizeWatchRoots(roots); if (sameRoots(this.#roots, next)) return; // The root set and polling snapshot change together. Native handles are // replaced afterwards; stale handles are filtered by the committed set. this.#roots = next; this.#snapshot = sourceSnapshot(next); // While polling, the scheduled native retry picks the new roots up. if (!this.#pollTimer && !this.#attachNativeWatchers()) this.#startPolling(); } close(): void { if (this.#closed) return; this.#closed = true; this.#closeNativeWatchers(); if (this.#pollTimer) clearInterval(this.#pollTimer); if (this.#retryTimer) clearTimeout(this.#retryTimer); this.#pollTimer = undefined; this.#retryTimer = undefined; } /** Replaces the native handles for the current roots; false when the platform refuses. */ #attachNativeWatchers(): boolean { if (this.#closed) return false; const next = new Set(); try { for (const root of this.#roots) { const watcher = watchDirectory(root, { recursive: true }, (_event, name) => { if (!name || !this.#roots.includes(root)) return; const source = resolve(root, name.toString()); if (isWatchedSource(source) && !isIgnoredSource(root, source)) this.listener(source); }); // A handle that was already replaced or closed must not degrade the live ones. watcher.on('error', () => { if (this.#watchers.has(watcher)) this.#startPolling(); }); next.add(watcher); } } catch { for (const watcher of next) watcher.close(); return false; } const previous = this.#watchers; this.#watchers = next; this.#nativeSince = Date.now(); for (const watcher of previous) watcher.close(); return true; } #startPolling(): void { if (this.#closed) return; // Watchers that stayed healthy for a while earn a fresh backoff; a flapping platform does not. if (this.#watchers.size > 0 && Date.now() - this.#nativeSince >= nativeRetryMaxDelayMs) { this.#retryDelayMs = nativeRetryInitialDelayMs; } this.#closeNativeWatchers(); this.#pollTimer ??= setInterval(() => this.#poll(), pollIntervalMs); this.#scheduleNativeRetry(); } #poll(): void { const next = sourceSnapshot(this.#roots); const sources = new Set([...this.#snapshot.keys(), ...next.keys()]); for (const source of sources) { if (this.#snapshot.get(source) !== next.get(source)) this.listener(source); } this.#snapshot = next; } /** Polling is a degraded mode: keep trying to get native watching back, with backoff. */ #scheduleNativeRetry(): void { if (this.#closed || this.#retryTimer) return; const delay = this.#retryDelayMs; this.#retryDelayMs = Math.min(delay * 2, nativeRetryMaxDelayMs); this.#retryTimer = setTimeout(() => { this.#retryTimer = undefined; if (this.#closed || !this.#pollTimer) return; if (!this.#attachNativeWatchers()) { this.#scheduleNativeRetry(); return; } clearInterval(this.#pollTimer); this.#pollTimer = undefined; // Report what changed between the last poll and the native handles attaching. this.#poll(); }, delay); } #closeNativeWatchers(): void { for (const watcher of this.#watchers) watcher.close(); this.#watchers.clear(); } } function sourceSnapshot(roots: readonly string[]): ReadonlyMap { const result = new Map(); const visit = (directory: string): void => { let entries; try { entries = readdirSync(directory, { withFileTypes: true }); } catch { return; } for (const entry of entries) { if (entry.isDirectory() && !ignoredDirectories.has(entry.name)) { visit(resolve(directory, entry.name)); } else if (entry.isFile()) { const source = resolve(directory, entry.name); if (!isWatchedSource(source)) continue; try { result.set(source, statSync(source).mtimeMs); } catch { /* The next poll reports a concurrent unlink. */ } } } }; for (const root of roots) visit(root); return result; } /** Shared by the native watcher and the polling fallback, so both skip the same files. */ function isWatchedSource(source: string): boolean { const name = source.slice(source.lastIndexOf(sep) + 1); // Editor temp/backup files (e.g. `.!97910!index.ts`, `.env.swp`) never reload (#857). if (isEditorTempFile(name)) return false; return watchedExtensions.has(extname(source)) || name.startsWith('.env'); } /** Mirrors sourceSnapshot: any path segment matching an ignored directory opts out. */ function isIgnoredSource(root: string, source: string): boolean { return relative(root, source).split(sep).some((segment) => ignoredDirectories.has(segment)); } function isExecutableSource(source: string): boolean { return ['.cjs', '.cts', '.js', '.mjs', '.mts', '.ts', '.tsx'].includes(extname(source)); } /** * Watched source types that no `import` can load: Node has no loader for them and the module * runtime registers none. JSON stays importable (`with { type: 'json' }`), as does any unknown type. */ const nonImportableExtensions = new Set(['.md', '.yaml', '.yml']); function isModuleImportableSource(source: string): boolean { return !nonImportableExtensions.has(extname(source)); } /** * Lazy tracking: reports an entry whose import analysis failed, once per failure (#1250). While it * stays loaded, every reload of another importable source falls back to a process restart. */ function emitDependencyAnalysisWarning(entry: string, error: unknown): void { const reason = error instanceof Error ? error.message : String(error); process.emitWarning( `Cannot analyze the imports of ${entry}: ${reason}. Until it is analyzed, reloading any other ` + 'module source restarts the process instead of reloading in place.', { type: 'ZhinModuleRuntimeWarning', code: 'ZHIN_DEPENDENCY_ANALYSIS_FAILED', detail: JSON.stringify({ entry }) }, ); } function isNativeTypeScriptSource(source: string): boolean { return ['.cts', '.mts', '.ts'].includes(extname(source)); } function isWithin(root: string, source: string): boolean { const child = relative(root, source); return child === '' || (!child.startsWith('..') && !isAbsolute(child)); } function nearestWatchRoot(roots: readonly string[], source: string): string | undefined { return roots.find((root) => isWithin(root, source)); } function isNodeModulesSource(root: string, source: string): boolean { return relative(root, source).split(sep).some((part) => part === 'node_modules'); } function normalizeWatchRoots(roots: readonly string[]): readonly string[] { const sorted = [...new Set(roots.map((root) => normalizeSourcePath(root)))].sort( (left, right) => left.length - right.length, ); return Object.freeze(sorted.filter((root, index) => !sorted.slice(0, index).some((parent) => isWithin(parent, root)), )); } function sameRoots(left: readonly string[], right: readonly string[]): boolean { return left.length === right.length && left.every((root, index) => root === right[index]); } function isWithinRoot(root: string, source: string): boolean { const child = relative(root, normalizeSourcePath(source)); return child === '' || (!child.startsWith('..') && !isAbsolute(child)); }