es-guard
Version:
A tool to check JavaScript compatibility with target environments
77 lines • 2.18 kB
JavaScript
import * as fs from "fs";
import * as path from "path";
/**
* Helper to read and parse JSON file safely
*/
export const readJsonFile = (filePath) => {
const content = fs.readFileSync(filePath, "utf-8");
return JSON.parse(content);
};
/**
* Helper to read text file safely
*/
export const readTextFile = (filePath) => {
return fs.readFileSync(filePath, "utf-8");
};
/**
* Helper to safely evaluate JavaScript files (for config files)
*/
export const evaluateJsFile = (filePath) => {
const content = readTextFile(filePath);
// Create a safe evaluation context
const module = { exports: {} };
const require = (id) => {
if (id === "path")
return path;
if (id === "fs")
return fs;
throw new Error(`Cannot require '${id}' in config evaluation`);
};
try {
// Use Function constructor to create a safe evaluation environment
const fn = new Function("module", "exports", "require", "path", "fs", "__dirname", content);
fn(module, module.exports, require, path, fs, path.dirname(filePath));
return module.exports;
}
catch (error) {
console.warn(`Error evaluating ${filePath}:`, error);
return null;
}
};
/**
* Type guard for package.json structure
*/
export const isPackageJson = (obj) => {
return typeof obj === "object" && obj !== null;
};
/**
* Type guard for tsconfig.json structure
*/
export const isTsConfig = (obj) => {
return typeof obj === "object" && obj !== null && "compilerOptions" in obj;
};
/**
* Type guard for .babelrc structure
*/
export const isBabelRc = (obj) => {
return typeof obj === "object" && obj !== null && "presets" in obj;
};
/**
* Type guard for vite config structure
*/
export const isViteConfig = (obj) => {
return typeof obj === "object" && obj !== null;
};
/**
* Type guard for webpack config structure
*/
export const isWebpackConfig = (obj) => {
return typeof obj === "object" && obj !== null;
};
/**
* Type guard for next.js config structure
*/
export const isNextConfig = (obj) => {
return typeof obj === "object" && obj !== null;
};
//# sourceMappingURL=utils.js.map