"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.__tsfTypeAliases = void 0;
exports.findPackageRoot = findPackageRoot;
exports.findProjectRoot = findProjectRoot;
exports.readPackageDependencyVersion = readPackageDependencyVersion;
exports.extractTsconfigArg = extractTsconfigArg;
exports.cleanDist = cleanDist;
exports.resolveFromProject = resolveFromProject;
exports.runNode = runNode;
exports.runBinary = runBinary;
const tslib_1 = require("tslib");
const _a = tslib_1.__importStar(require("@zyno-io/ts-server-foundation/type-metadata-runtime"));
const node_child_process_1 = require("node:child_process");
const node_fs_1 = require("node:fs");
const node_module_1 = require("node:module");
const node_path_1 = require("node:path");
const env_1 = require("../env");
function findPackageRoot(start = __dirname) {
    let dir = start;
    while (true) {
        if ((0, node_fs_1.existsSync)((0, node_path_1.join)(dir, 'package.json')))
            return dir;
        const parent = (0, node_path_1.dirname)(dir);
        if (parent === dir)
            throw new Error('Could not find package root');
        dir = parent;
    }
}
function findProjectRoot(start = process.cwd()) {
    let dir = start;
    while (true) {
        if ((0, node_fs_1.existsSync)((0, node_path_1.join)(dir, 'package.json')))
            return dir;
        const parent = (0, node_path_1.dirname)(dir);
        if (parent === dir)
            throw new Error('Could not find package.json in any parent directory');
        dir = parent;
    }
}
function readPackageDependencyVersion(packageRoot, name) {
    const packageJsonPath = (0, node_path_1.join)(packageRoot, 'package.json');
    const pkg = JSON.parse((0, node_fs_1.readFileSync)(packageJsonPath, 'utf8'));
    const version = pkg.devDependencies?.[name] ?? pkg.dependencies?.[name] ?? pkg.peerDependencies?.[name];
    if (!version)
        throw new Error(`${name} is not declared in ${packageJsonPath}`);
    return version;
}
function extractTsconfigArg(args) {
    for (let index = 0; index < args.length; index++) {
        const arg = args[index];
        if (arg === '-p' || arg === '--tsconfig') {
            const value = args[index + 1];
            args.splice(index, 2);
            return value;
        }
        if (arg.startsWith('-p=')) {
            args.splice(index, 1);
            return arg.slice(3);
        }
        if (arg.startsWith('--tsconfig=')) {
            args.splice(index, 1);
            return arg.slice('--tsconfig='.length);
        }
    }
}
function cleanDist(projectDir = findProjectRoot()) {
    (0, node_fs_1.rmSync)((0, node_path_1.join)(projectDir, 'dist'), { recursive: true, force: true });
}
function resolveFromProject(projectDir, specifier) {
    try {
        return (0, node_module_1.createRequire)((0, node_path_1.join)(projectDir, 'package.json')).resolve(specifier);
    }
    catch (error) {
        throw new Error(`Could not resolve ${specifier} from ${projectDir}. Install it in the project before running this command.`, {
            cause: error
        });
    }
}
function runNode(args, cwd = process.cwd(), env = env_1.Env) {
    const result = (0, node_child_process_1.spawnSync)(process.execPath, args, {
        cwd,
        env: (0, env_1.toProcessEnv)({ ...env_1.Env, ...env }),
        stdio: 'inherit'
    });
    return { status: result.status ?? 1 };
}
function runBinary(bin, args, cwd = process.cwd(), env = env_1.Env) {
    const result = (0, node_child_process_1.spawnSync)(bin, args, {
        cwd,
        env: (0, env_1.toProcessEnv)({ ...env_1.Env, ...env }),
        stdio: 'inherit'
    });
    if (result.error) {
        console.error(result.error.message);
        return { status: 1 };
    }
    return { status: result.status ?? 1 };
}
exports.__tsfTypeAliases = _a.decodeCompactMetadataV1("[1,{\"SpawnResult\":{\"kind\":18,\"typeName\":\"SpawnResult\",\"types\":[{\"kind\":20,\"name\":\"status\",\"type\":{\"kind\":7},\"optional\":false}]}}]", []);
//# sourceMappingURL=common.js.map