refactor(utils): rename and refactor clearModuleCache to recursively clear dependencies

The function has been renamed to clearRequireCache and updated to recursively
clear the require cache for a module and all its dependencies, preventing
cycles with a visited set. This improves reliability after rebuilding native
modules by ensuring complete cache invalidation. Removed unused createRequire
import as it's no longer needed.
This commit is contained in:
jgor20
2026-01-05 01:13:45 +00:00
parent 02ceeb2ff5
commit 2d4693b4c6

View File

@@ -7,7 +7,6 @@
import { execSync } from 'child_process';
import { dirname, join } from 'path';
import { existsSync } from 'fs';
import { createRequire } from 'module';
import { logger } from './logger.js';
/**
@@ -121,30 +120,36 @@ export function attemptAutoRebuild(error) {
}
/**
* Clear the require cache for a module to force re-import
* This is needed after rebuilding a native module
* @param {string} moduleName - The module name (e.g., 'better-sqlite3')
* Recursively clear a module and its dependencies from the require cache
* This is needed after rebuilding a native module to force re-import
* @param {string} modulePath - Resolved path to the module
* @param {object} cache - The require.cache object
* @param {Set} [visited] - Set of already-visited paths to prevent cycles
*/
export function clearModuleCache(moduleName) {
const require = createRequire(import.meta.url);
try {
const resolved = require.resolve(moduleName);
// Clear the main module and its dependencies
const mod = require.cache[resolved];
if (mod) {
export function clearRequireCache(modulePath, cache, visited = new Set()) {
if (visited.has(modulePath)) return;
visited.add(modulePath);
const mod = cache[modulePath];
if (!mod) return;
// Recursively clear children first
if (mod.children) {
for (const child of mod.children) {
clearRequireCache(child.id, cache, visited);
}
}
// Remove from parent's children array
if (mod.parent) {
if (mod.parent && mod.parent.children) {
const idx = mod.parent.children.indexOf(mod);
if (idx !== -1) {
mod.parent.children.splice(idx, 1);
}
}
// Delete from cache
delete require.cache[resolved];
}
} catch {
// Module might not be in cache, that's okay
}
delete cache[modulePath];
}
export default {
@@ -153,5 +158,5 @@ export default {
findPackageRoot,
rebuildModule,
attemptAutoRebuild,
clearModuleCache
clearRequireCache
};