"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.buildPackageByPath = buildPackageByPath;
const chalk_1 = __importDefault(require("chalk"));
const fs_1 = __importDefault(require("fs"));
const path_1 = __importDefault(require("path"));
const utils_js_1 = require("../utils.js");
/**
 * Given any file or directory path, walk up to find the nearest package.json
 * and run `linked build` in that package's directory. This is the editor-hook
 * variant of build: the caller knows a file path, we figure out the package.
 *
 * Only rebuilds packages flagged `linkedPackage: true` (or legacy `lincd: true`).
 */
async function buildPackageByPath(filePath) {
    let currentPath = path_1.default.isAbsolute(filePath)
        ? filePath
        : path_1.default.resolve(process.cwd(), filePath);
    if (fs_1.default.existsSync(currentPath) && fs_1.default.statSync(currentPath).isFile()) {
        currentPath = path_1.default.dirname(currentPath);
    }
    while (currentPath !== path_1.default.dirname(currentPath)) {
        const pkgJsonPath = path_1.default.join(currentPath, 'package.json');
        if (fs_1.default.existsSync(pkgJsonPath)) {
            const pkgJson = JSON.parse(fs_1.default.readFileSync(pkgJsonPath, 'utf8'));
            const isLinked = pkgJson.linkedPackage === true || pkgJson.lincd === true;
            if (!isLinked) {
                console.log(chalk_1.default.yellow(`Package ${pkgJson.name} is not a linked package (no linkedPackage flag). Skipping.`));
                return;
            }
            console.log(chalk_1.default.cyan(`Rebuilding ${pkgJson.name}`));
            // Prefer workspace-local yarn if available, else fall back to PATH `yarn`
            let yarnBin = 'yarn';
            const yarnReleasesDir = path_1.default.join(process.cwd(), '.yarn', 'releases');
            if (fs_1.default.existsSync(yarnReleasesDir)) {
                const releases = fs_1.default.readdirSync(yarnReleasesDir);
                if (releases.length > 0) {
                    yarnBin = path_1.default.join(yarnReleasesDir, releases[0]);
                }
            }
            // Use `yarn exec` so we invoke the `linked` binary rather than a script.
            // Inner packages don't have a "linked" script in package.json.
            const command = `cd ${currentPath} && ${yarnBin} exec linked build`;
            await (0, utils_js_1.execp)(command, true, false);
            return;
        }
        currentPath = path_1.default.dirname(currentPath);
    }
    console.error(chalk_1.default.red(`No package.json found walking up from ${filePath}`));
    process.exit(1);
}
//# sourceMappingURL=build-package.js.map