"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.projectHasScript = projectHasScript;
exports.runScriptInProject = runScriptInProject;
const sdk_build_core_1 = require("@servicenow/sdk-build-core");
const environment_1 = require("./environment");
const register_explicit_id_1 = require("./register-explicit-id");
function projectHasScript(project, scriptName) {
    const fs = project.getFileSystem();
    const config = project.getConfig();
    const scriptPath = config.scripts?.[scriptName];
    if (scriptPath) {
        const absoluteScriptPath = project.resolvePath(scriptPath);
        if (sdk_build_core_1.FileSystem.existsSync(fs, absoluteScriptPath)) {
            return true;
        }
    }
    // Fallback: check for now.scriptName.mjs
    const fallbackPath = project.resolvePath(`now.${scriptName}.mjs`);
    if (sdk_build_core_1.FileSystem.existsSync(fs, fallbackPath)) {
        return true;
    }
    return false;
}
const SCRIPT_DEFAULTS = {
    dev: './default-ui-dev.js',
};
async function runScriptInProject({ scriptName, project, credential, throwIfNotFound = false, args, }) {
    const rootDir = project.getRootDir();
    const fs = project.getFileSystem();
    const config = project.getConfig();
    const logger = project.getLogger();
    const registerExplicitId = (0, register_explicit_id_1.createSandboxedRegisterExplicitId)(project);
    let absoluteScriptPath = null;
    const scriptPath = config.scripts?.[scriptName];
    // If script is explicitly defined in config, use that path (takes precedence)
    if (scriptPath) {
        const configPath = project.resolvePath(scriptPath);
        if (!sdk_build_core_1.FileSystem.existsSync(fs, configPath)) {
            if (throwIfNotFound) {
                throw Error(`Script "${scriptName}" defined in config at "${scriptPath}" not found at ${configPath}.`);
            }
            return;
        }
        absoluteScriptPath = configPath;
    }
    else {
        // Only check fallback if script NOT defined in config
        const fallbackPath = project.resolvePath(`now.${scriptName}.mjs`);
        if (sdk_build_core_1.FileSystem.existsSync(fs, fallbackPath)) {
            absoluteScriptPath = fallbackPath;
        }
    }
    // No user script found — try built-in default
    if (!absoluteScriptPath) {
        const defaultModule = SCRIPT_DEFAULTS[scriptName];
        if (defaultModule) {
            logger.info(`No user script for "${scriptName}", using built-in default`);
            const mod = await import(defaultModule);
            const defaultFn = mod.defaultUiDev ?? mod.default;
            await defaultFn({ project, credential, args });
            return;
        }
        if (throwIfNotFound) {
            throw Error(`No script defined for "${scriptName}". Please add it to scripts in now.config.json or create now.${scriptName}.mjs.`);
        }
        return;
    }
    logger.info(`Running script "${scriptName}" from ${absoluteScriptPath}`);
    let scriptResults = null;
    if (environment_1.isWebWorker && (0, environment_1.hasModuleLoader)()) {
        scriptResults = await require(absoluteScriptPath);
    }
    else {
        const webpackWillIgnoreThisIhateYouWebpack = (p) => `file://${p}`;
        scriptResults = await import(webpackWillIgnoreThisIhateYouWebpack(absoluteScriptPath));
    }
    const taskFns = Array.isArray(scriptResults.default) ? scriptResults.default : [scriptResults.default];
    for (const taskFn of taskFns) {
        if (typeof taskFn === 'function') {
            await taskFn({ rootDir, config, fs, path: sdk_build_core_1.path, logger, registerExplicitId, credential, args });
        }
        else {
            logger.warn(`Skipping non-function task in script "${scriptName}": ${taskFn?.toString()} . Please export a function or an array of functions.`);
        }
    }
    logger.info(`Script "${scriptName}" completed successfully`);
}
//# sourceMappingURL=script-runner.js.map