@redhat-cloud-services/hcc-pf-mcp
Version:
HCC PatternFly MCP package
47 lines (46 loc) • 1.78 kB
JavaScript
import { readJsonFile } from './readFile';
import { verifyLocalPackage } from './verifyLocalPackage';
const modulesCache = new Map();
function isCacheValid(cacheEntry) {
return cacheEntry.expiresAt > Date.now();
}
function setCache(packageName, modulesMap, ttlMs = 5 * 60 * 1000) {
const expiresAt = Date.now() + ttlMs;
modulesCache.set(packageName, { expiresAt, modulesMap });
}
function getCache(packageName) {
const cacheEntry = modulesCache.get(packageName);
if (cacheEntry && isCacheValid(cacheEntry)) {
return cacheEntry.modulesMap;
}
modulesCache.delete(packageName);
return null;
}
async function getModulesMap(cacheKey, packageRoot) {
const cachedEntry = getCache(cacheKey);
if (cachedEntry) {
return cachedEntry;
}
const modulesMap = await readJsonFile(`${packageRoot}/dist/dynamic-modules.json`);
setCache(cacheKey, modulesMap);
return modulesMap;
}
function createCacheKey(packageName, packageRoot) {
return packageRoot ? `${packageName}::${packageRoot}` : packageName;
}
export const getLocalModulesMap = async (packageName, nodeModulesRootPath) => {
let modulesMap = {};
const status = await verifyLocalPackage(packageName, nodeModulesRootPath);
if (!status.exists) {
throw new Error(`Package "${packageName}" not found locally. ${status.error ? status.error.message : ''}`);
}
const cacheKey = createCacheKey(packageName, status.packageRoot);
// exported map of module names to their paths
try {
modulesMap = await getModulesMap(cacheKey, status.packageRoot);
}
catch (error) {
throw new Error(`Failed to import modules map from package "${packageName}": ${error}. Does the modules map exist?`);
}
return modulesMap;
};