"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.renderConfigTemplate = exports.forgeConfigIsValidFilePath = exports.fromBuildIdentifier = void 0;
const path_1 = __importDefault(require("path"));
const fs_extra_1 = __importDefault(require("fs-extra"));
const interpret = __importStar(require("interpret"));
const lodash_1 = require("lodash");
const rechoir = __importStar(require("rechoir"));
const dynamic_import_js_1 = require("../../helper/dynamic-import.js");
const hook_1 = require("./hook");
const plugin_interface_1 = __importDefault(require("./plugin-interface"));
const read_package_json_1 = require("./read-package-json");
const underscoreCase = (str) => str
    .replace(/(.)([A-Z][a-z]+)/g, '$1_$2')
    .replace(/([a-z0-9])([A-Z])/g, '$1_$2')
    .toUpperCase();
/* eslint-disable @typescript-eslint/no-explicit-any */
const proxify = (buildIdentifier, proxifiedObject, envPrefix) => {
    let newObject = {};
    if (Array.isArray(proxifiedObject)) {
        newObject = [];
    }
    for (const [key, val] of Object.entries(proxifiedObject)) {
        if (typeof val === 'object' && (val.constructor === Object || val.constructor === Array) && key !== 'pluginInterface' && !(val instanceof RegExp)) {
            newObject[key] = proxify(buildIdentifier, proxifiedObject[key], `${envPrefix}_${underscoreCase(key)}`);
        }
        else {
            newObject[key] = proxifiedObject[key];
        }
    }
    return new Proxy(newObject, {
        get(target, name, receiver) {
            // eslint-disable-next-line no-prototype-builtins
            if (!target.hasOwnProperty(name) && typeof name === 'string') {
                const envValue = process.env[`${envPrefix}_${underscoreCase(name)}`];
                if (envValue)
                    return envValue;
            }
            const value = Reflect.get(target, name, receiver);
            if (value && typeof value === 'object' && value.__isMagicBuildIdentifierMap) {
                const identifier = typeof buildIdentifier === 'function' ? buildIdentifier() : buildIdentifier;
                return value.map[identifier];
            }
            return value;
        },
        getOwnPropertyDescriptor(target, name) {
            const envValue = process.env[`${envPrefix}_${underscoreCase(name)}`];
            // eslint-disable-next-line no-prototype-builtins
            if (target.hasOwnProperty(name)) {
                return Reflect.getOwnPropertyDescriptor(target, name);
            }
            if (envValue) {
                return {
                    writable: true,
                    enumerable: true,
                    configurable: true,
                    value: envValue,
                };
            }
            return undefined;
        },
    });
};
function fromBuildIdentifier(map) {
    return {
        map,
        __isMagicBuildIdentifierMap: true,
    };
}
exports.fromBuildIdentifier = fromBuildIdentifier;
async function forgeConfigIsValidFilePath(dir, forgeConfig) {
    return typeof forgeConfig === 'string' && ((await fs_extra_1.default.pathExists(path_1.default.resolve(dir, forgeConfig))) || fs_extra_1.default.pathExists(path_1.default.resolve(dir, `${forgeConfig}.js`)));
}
exports.forgeConfigIsValidFilePath = forgeConfigIsValidFilePath;
// eslint-disable-next-line @typescript-eslint/no-explicit-any
function renderConfigTemplate(dir, templateObj, obj) {
    for (const [key, value] of Object.entries(obj)) {
        if (typeof value === 'object' && value !== null) {
            renderConfigTemplate(dir, templateObj, value);
        }
        else if (typeof value === 'string') {
            obj[key] = (0, lodash_1.template)(value)(templateObj);
            if (obj[key].startsWith('require:')) {
                obj[key] = require(path_1.default.resolve(dir, obj[key].substr(8)));
            }
        }
    }
}
exports.renderConfigTemplate = renderConfigTemplate;
exports.default = async (dir) => {
    const packageJSON = await (0, read_package_json_1.readRawPackageJson)(dir);
    let forgeConfig = packageJSON.config && packageJSON.config.forge ? packageJSON.config.forge : null;
    if (!forgeConfig || typeof forgeConfig === 'string') {
        for (const extension of ['.js', ...Object.keys(interpret.extensions)]) {
            const pathToConfig = path_1.default.resolve(dir, `forge.config${extension}`);
            if (await fs_extra_1.default.pathExists(pathToConfig)) {
                rechoir.prepare(interpret.extensions, pathToConfig, dir);
                forgeConfig = `forge.config${extension}`;
                break;
            }
        }
    }
    forgeConfig = forgeConfig || {};
    if (await forgeConfigIsValidFilePath(dir, forgeConfig)) {
        const forgeConfigPath = path_1.default.resolve(dir, forgeConfig);
        try {
            // The loaded "config" could potentially be a static forge config, ESM module or async function
            let loaded;
            try {
                loaded = (await (0, dynamic_import_js_1.dynamicImport)(forgeConfigPath));
            }
            catch (err) {
                // eslint-disable-next-line @typescript-eslint/no-var-requires
                loaded = require(forgeConfigPath);
            }
            const maybeForgeConfig = 'default' in loaded ? loaded.default : loaded;
            forgeConfig = typeof maybeForgeConfig === 'function' ? await maybeForgeConfig() : maybeForgeConfig;
        }
        catch (err) {
            console.error(`Failed to load: ${forgeConfigPath}`);
            throw err;
        }
    }
    else if (typeof forgeConfig !== 'object') {
        throw new Error('Expected packageJSON.config.forge to be an object or point to a requirable JS file');
    }
    const defaultForgeConfig = {
        rebuildConfig: {},
        packagerConfig: {},
        makers: [],
        publishers: [],
        plugins: [],
    };
    let resolvedForgeConfig = {
        ...defaultForgeConfig,
        ...forgeConfig,
        // eslint-disable-next-line @typescript-eslint/no-explicit-any
        pluginInterface: null,
    };
    const templateObj = { ...packageJSON, year: new Date().getFullYear() };
    renderConfigTemplate(dir, templateObj, resolvedForgeConfig);
    resolvedForgeConfig.pluginInterface = new plugin_interface_1.default(dir, resolvedForgeConfig);
    resolvedForgeConfig = await (0, hook_1.runMutatingHook)(resolvedForgeConfig, 'resolveForgeConfig', resolvedForgeConfig);
    return proxify(resolvedForgeConfig.buildIdentifier || '', resolvedForgeConfig, 'ELECTRON_FORGE');
};
//# sourceMappingURL=data:application/json;base64, 