"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const path_1 = __importDefault(require("path"));
const core_utils_1 = require("@electron-forge/core-utils");
const debug_1 = __importDefault(require("debug"));
const fs_extra_1 = __importDefault(require("fs-extra"));
const read_package_json_1 = require("./read-package-json");
const d = (0, debug_1.default)('electron-forge:project-resolver');
// FIXME: If we want getElectronVersion to be overridable by plugins
//        and / or forge config then we need to be able to resolve
//        the dir without calling getElectronVersion
exports.default = async (dir) => {
    let mDir = dir;
    let bestGuessDir = null;
    let lastError = null;
    let prevDir;
    while (prevDir !== mDir) {
        prevDir = mDir;
        const testPath = path_1.default.resolve(mDir, 'package.json');
        d('searching for project in:', mDir);
        if (await fs_extra_1.default.pathExists(testPath)) {
            const packageJSON = await (0, read_package_json_1.readRawPackageJson)(mDir);
            // TODO: Move this check to inside the forge config resolver and use
            //       mutatedPackageJson reader
            try {
                await (0, core_utils_1.getElectronVersion)(mDir, packageJSON);
            }
            catch (err) {
                if (err instanceof Error) {
                    lastError = err.message;
                }
            }
            if (packageJSON.config && packageJSON.config.forge) {
                d('electron-forge compatible package.json found in', testPath);
                return mDir;
            }
            if (packageJSON.devDependencies?.['@electron-forge/cli'] || packageJSON.devDependencies?.['@electron-forge/core']) {
                d('package.json with forge dependency found in', testPath);
                return mDir;
            }
            bestGuessDir = mDir;
        }
        mDir = path_1.default.dirname(mDir);
    }
    if (bestGuessDir) {
        d('guessing on the best electron-forge package.json found in', bestGuessDir);
        return bestGuessDir;
    }
    if (lastError) {
        throw new Error(lastError);
    }
    return null;
};
//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoicmVzb2x2ZS1kaXIuanMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyIuLi8uLi9zcmMvdXRpbC9yZXNvbHZlLWRpci50cyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiOzs7Ozt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