UNPKG

code-complexity

Version:

Measure the churn/complexity score. Higher values mean hotspots where refactorings should happen.

45 lines (44 loc) 1.67 kB
"use strict"; exports.__esModule = true; exports.calculate = void 0; var node_path_1 = require("node:path"); var node_fs_1 = require("node:fs"); var utils_1 = require("../../utils"); var core_1 = require("@babel/core"); // eslint-disable-next-line @typescript-eslint/no-var-requires var escomplex = require("escomplex"); var internal = { debug: (0, utils_1.buildDebugger)("cyclomatic") }; function calculate(path) { switch ((0, node_path_1.extname)(path)) { case ".ts": return fromTypeScript(path); case ".mjs": case ".js": return fromJavaScript(path); default: internal.debug("Unsupported file extension. Falling back on default complexity (1)"); return new utils_1.UnsupportedExtension(); } } exports.calculate = calculate; function fromJavaScript(path) { var content = (0, node_fs_1.readFileSync)(path, { encoding: "utf8" }); var babelResult = (0, core_1.transformSync)(content, { presets: ["@babel/preset-env"] }); if (!babelResult) throw new Error("Error while parsing file ".concat(path)); var result = escomplex.analyse(babelResult.code, {}); return result.aggregate.cyclomatic; } function fromTypeScript(path) { var content = (0, node_fs_1.readFileSync)(path, { encoding: "utf8" }); var babelResult = (0, core_1.transformSync)(content, { plugins: ["@babel/plugin-transform-typescript"], presets: ["@babel/preset-env"] }); if (!babelResult) throw new Error("Error while parsing file ".concat(path)); var result = escomplex.analyse(babelResult.code); return result.aggregate.cyclomatic; }