// engine/stack-auditor/build-tool-auditor.ts — SPEC-050 S6
// Detects build-tool anti-patterns in audit_stack.
// C14: Webpack 4 EOL → high severity finding
// C15: require() CJS in ESM-first project → high severity finding
import { readFile } from 'node:fs/promises';
import { join } from 'node:path';
import { glob } from 'glob';
// ---------------------------------------------------------------------------
// Helpers
// ---------------------------------------------------------------------------
async function readFileSafe(filePath) {
    try {
        return await readFile(filePath, 'utf-8');
    }
    catch {
        return '';
    }
}
function parseVersionMajor(version) {
    if (!version) {
        return null;
    }
    const cleaned = version.replace(/^[^0-9]*/, '');
    const match = /^(\d+)/.exec(cleaned);
    return match !== null ? parseInt(match[1] ?? '0', 10) : null;
}
// ---------------------------------------------------------------------------
// C14: Webpack 4 EOL detection
// ---------------------------------------------------------------------------
async function detectWebpack4Eol(projectPath) {
    const pkgContent = await readFileSafe(join(projectPath, 'package.json'));
    if (!pkgContent) {
        return [];
    }
    let pkg;
    try {
        pkg = JSON.parse(pkgContent);
    }
    catch {
        return [];
    }
    const allDeps = { ...pkg.dependencies, ...pkg.devDependencies };
    const webpackVersion = allDeps.webpack;
    if (!webpackVersion) {
        return [];
    }
    const major = parseVersionMajor(webpackVersion);
    if (major === null || major >= 5) {
        return [];
    }
    return [
        {
            id: 'webpack4-eol',
            severity: 'high',
            category: 'build-tool',
            title: 'Webpack 4 EOL — no security patches since 2024',
            description: 'Webpack 4 is end-of-life. Security vulnerabilities will not be patched by the Webpack team.',
            fix: 'Upgrade to Webpack 5 or migrate to Vite 7. Migration guide: https://webpack.js.org/migrate/5/',
        },
    ];
}
// ---------------------------------------------------------------------------
// C15: require() CJS in ESM-first project
// ---------------------------------------------------------------------------
async function detectCjsRequireInEsm(projectPath) {
    const pkgContent = await readFileSafe(join(projectPath, 'package.json'));
    if (!pkgContent) {
        return [];
    }
    let pkg;
    try {
        pkg = JSON.parse(pkgContent);
    }
    catch {
        return [];
    }
    // Only relevant for ESM-first projects
    if (pkg.type !== 'module') {
        return [];
    }
    // Search for require() usage in JS/TS source files (excluding node_modules, dist)
    let sourceFiles;
    try {
        sourceFiles = await glob('**/*.{js,ts,jsx,tsx,mjs,cjs}', {
            cwd: projectPath,
            nodir: true,
            ignore: ['node_modules/**', 'dist/**', 'build/**', '.next/**'],
        });
    }
    catch {
        return [];
    }
    for (const file of sourceFiles) {
        const content = await readFileSafe(join(projectPath, file));
        // Match require() calls (not inside comments)
        if (/(?:^|[^/])\brequire\s*\(/.test(content)) {
            return [
                {
                    id: 'cjs-require-in-esm',
                    severity: 'high',
                    category: 'build-tool',
                    title: 'require() CJS syntax in ESM-first project',
                    description: "Using require() in a project with 'type': 'module' in package.json will throw ERR_REQUIRE_ESM at runtime. Vite handles this in dev but the production build may expose the issue.",
                    fix: 'Replace require() with import statements. For dynamic imports use import() with await.',
                },
            ];
        }
    }
    return [];
}
// ---------------------------------------------------------------------------
// Main export
// ---------------------------------------------------------------------------
/**
 * Detect build-tool anti-patterns for audit_stack.
 * Returns a flat list of findings (C14 + C15).
 */
export async function detectBuildToolAntiPatterns(projectPath) {
    const [webpack4Findings, cjsFindings] = await Promise.all([
        detectWebpack4Eol(projectPath),
        detectCjsRequireInEsm(projectPath),
    ]);
    return [...webpack4Findings, ...cjsFindings];
}
//# sourceMappingURL=build-tool-auditor.js.map