"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 () {
    var ownKeys = function(o) {
        ownKeys = Object.getOwnPropertyNames || function (o) {
            var ar = [];
            for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
            return ar;
        };
        return ownKeys(o);
    };
    return function (mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
        __setModuleDefault(result, mod);
        return result;
    };
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.defaultUiBuild = defaultUiBuild;
const localRollup = __importStar(require("@servicenow/isomorphic-rollup"));
const sdk_build_core_1 = require("@servicenow/sdk-build-core");
const register_explicit_id_1 = require("./register-explicit-id");
const AIUX_ENTRY_POINT = 'aiux.json';
const contextualRequire = (project, dep) => (0, sdk_build_core_1.isomorphicRequireResolve)(dep, sdk_build_core_1.path.join(project.getRootDir(), 'package.json'));
const resolveRollup = async (project) => {
    try {
        const resolved = await contextualRequire(project, '@servicenow/isomorphic-rollup');
        return (await require(resolved));
    }
    catch {
        return localRollup;
    }
};
async function defaultUiBuild({ project }) {
    const fs = project.getFileSystem();
    const config = project.getConfig();
    const logger = project.getLogger();
    const rootDir = project.getRootDir();
    const clientDir = sdk_build_core_1.path.join(rootDir, config.clientDir);
    const aiuxJsonPath = sdk_build_core_1.path.join(rootDir, AIUX_ENTRY_POINT);
    const { glob } = await resolveRollup(project);
    const htmlFilePattern = sdk_build_core_1.path.join(clientDir, '**', '*.html');
    const htmlFiles = sdk_build_core_1.FileSystem.existsSync(fs, clientDir) ? await glob(htmlFilePattern, { fs }) : [];
    const hasHtml = htmlFiles.length > 0;
    const hasAiux = sdk_build_core_1.FileSystem.existsSync(fs, aiuxJsonPath);
    if (!hasHtml && !hasAiux) {
        logger.debug(`No HTML files in ${clientDir} and no ${AIUX_ENTRY_POINT} in ${rootDir}, skipping UI build.`);
        return;
    }
    if (hasHtml) {
        await runRollupBuild({ project, clientDir, htmlFilePattern });
    }
    if (hasAiux) {
        await runAiuxBuild({ project });
    }
}
async function runRollupBuild({ project, clientDir, htmlFilePattern, }) {
    const fs = project.getFileSystem();
    const config = project.getConfig();
    const logger = project.getLogger();
    const rootDir = project.getRootDir();
    const registerExplicitId = (0, register_explicit_id_1.createSandboxedRegisterExplicitId)(project);
    const { servicenowFrontEndPlugins, rollup } = await resolveRollup(project);
    const staticContentDir = sdk_build_core_1.path.join(rootDir, config.staticContent.buildDir);
    fs.rmSync(staticContentDir, { recursive: true, force: true });
    const frontEndPlugins = await servicenowFrontEndPlugins({
        scope: config.scope,
        rootDir: clientDir,
        projectRootDir: rootDir,
        registerExplicitId: registerExplicitId,
        editableSourceCodeOnInstance: true,
    });
    const rollupBundle = await rollup({
        fs,
        input: htmlFilePattern,
        plugins: [...frontEndPlugins],
    });
    const rollupOutput = await rollupBundle.write({
        dir: staticContentDir,
        sourcemap: true,
    });
    rollupOutput.output.forEach((file) => {
        if (file.type === 'asset') {
            logger.info(`Bundled asset: ${file.fileName} (${file.source.length} bytes)`);
        }
        else if (file.type === 'chunk') {
            logger.info(`Bundled chunk: ${file.fileName} (${file.code.length} bytes)`);
        }
    });
}
async function runAiuxBuild({ project }) {
    const fs = project.getFileSystem();
    const logger = project.getLogger();
    const rootDir = project.getRootDir();
    const { rollup } = await resolveRollup(project);
    const { buildManifestAndMetadata } = await (0, sdk_build_core_1.resolveAiuxSdkBuild)(rootDir);
    const buildOpts = {
        projectRoot: rootDir,
        fs,
        rollup: (options) => rollup({ ...options, fs }),
        nowConfig: project.getConfig(),
    };
    const result = await buildManifestAndMetadata(buildOpts);
    logger.info(`AIUX build produced ${result.metadata.length} record(s)`);
}
//# sourceMappingURL=default-ui-build.js.map