"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const fs = require("fs");
const path = require("path");
const child_process_1 = require("child_process");
const TARGET_REGEX = /\/\*\s*webpackIgnore\s*:\s*true\s*\*\//g;
const REPLACEMENT = '/* @vite-ignore */';
function isTextFile(filePath) {
    return /\.(js|ts|mjs|cjs|jsx|tsx|json|txt|html|htm|css|scss|vue|svelte)$/.test(filePath);
}
function replaceInFile(filePath, options) {
    try {
        let content = fs.readFileSync(filePath, 'utf8');
        if (TARGET_REGEX.test(content)) {
            content = content.replace(TARGET_REGEX, REPLACEMENT);
            fs.writeFileSync(filePath, content, 'utf8');
            if (options.verbose)
                console.log(`✅ Patched: ${filePath}`);
        }
    }
    catch {
        if (options.verbose)
            console.warn(`⚠️ Skipped unreadable file: ${filePath}`);
    }
}
function walkDir(dir, options) {
    for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
        const fullPath = path.join(dir, entry.name);
        if (entry.isDirectory()) {
            walkDir(fullPath, options);
        }
        else if (entry.isFile() && isTextFile(fullPath)) {
            replaceInFile(fullPath, options);
        }
    }
}
function getTargetPath(pkg) {
    const base = path.resolve('node_modules');
    return pkg ? path.join(base, pkg) : base;
}
function runPatchPackage(pkg) {
    try {
        (0, child_process_1.execSync)(`npx patch-package ${pkg}`, { stdio: 'inherit' });
        console.log(`📦 patch-package created patch for: ${pkg}`);
    }
    catch (err) {
        console.error(`❌ patch-package failed for ${pkg}`, err);
    }
}
exports.default = (options) => (_tree, _context) => {
    const targetPath = getTargetPath(options.package);
    if (!fs.existsSync(targetPath)) {
        console.warn(`⚠️ Path not found: ${targetPath}`);
        return _tree;
    }
    if (options.verbose) {
        console.log(`🔍 Scanning: ${targetPath}`);
    }
    walkDir(targetPath, options);
    if (options.patchPackage && options.package) {
        runPatchPackage(options.package);
    }
    else if (options.patchPackage) {
        console.warn('⚠️ --patchPackage requires --package to be set.');
    }
    return _tree;
};
//# sourceMappingURL=index.js.map