"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.defaultUiDev = defaultUiDev;
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 node_module_1 = require("node:module");
const AIUX_ENTRY_POINT = 'aiux.json';
const contextualRequire = (project, dep) => (0, node_module_1.createRequire)(sdk_build_core_1.path.join(project.getRootDir(), 'package.json')).resolve(dep);
const resolveRollup = async (project) => {
    try {
        const resolved = contextualRequire(project, '@servicenow/isomorphic-rollup');
        return (await import(resolved));
    }
    catch {
        return localRollup;
    }
};
async function defaultUiDev({ project, credential, args, }) {
    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 hasHtml = config.clientDir && sdk_build_core_1.FileSystem.existsSync(fs, clientDir);
    const hasAiux = sdk_build_core_1.FileSystem.existsSync(fs, aiuxJsonPath);
    if (!hasHtml && !hasAiux) {
        logger.debug(`No client directory at ${clientDir} and no ${AIUX_ENTRY_POINT} in ${rootDir}, skipping UI dev.`);
        return;
    }
    if (hasAiux) {
        await runAiuxDev({ project, credential, args });
    }
    else if (hasHtml) {
        await runRollupDev({ project, credential });
    }
}
async function runRollupDev({ project, credential, }) {
    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 registerExplicitId = (0, register_explicit_id_1.createSandboxedRegisterExplicitId)(project);
    const { servicenowFrontEndPlugins, watch } = await resolveRollup(project);
    const staticContentDir = sdk_build_core_1.path.join(rootDir, config.staticContent.buildDir);
    fs.rmSync(staticContentDir, { recursive: true, force: true });
    const htmlFilePattern = sdk_build_core_1.path.join(clientDir, '**', '*.html');
    const frontEndPlugins = await servicenowFrontEndPlugins({
        dev: true,
        scope: config.scope,
        rootDir: clientDir,
        registerExplicitId: registerExplicitId,
        watchPaths: [staticContentDir],
        ...(credential ? { credential } : {}),
    });
    const watcher = watch({
        fs,
        input: htmlFilePattern,
        plugins: frontEndPlugins,
        output: {
            dir: staticContentDir,
            sourcemap: true,
        },
    });
    return new Promise((_resolve, reject) => {
        watcher.on('event', (event) => {
            if (event.code === 'ERROR') {
                reject(event.error);
            }
            else if (event.code === 'BUNDLE_END') {
                logger.info(`Finished watch build in ${event.duration}ms`);
                event.result.close();
            }
        });
    });
}
async function runAiuxDev({ project, credential, args, }) {
    const fs = project.getFileSystem();
    const rootDir = project.getRootDir();
    const { rollup } = await resolveRollup(project);
    const aiuxSdk = await (0, sdk_build_core_1.resolveAiuxSdkServe)(rootDir);
    if (!credential) {
        throw new Error("Cannot start dev server: no credentials found. Run 'now-sdk auth' to authenticate with your ServiceNow instance.");
    }
    const glideOrigin = credential.getUrl().origin;
    const headers = await credential.getHeaders();
    await aiuxSdk.serve({
        args,
        rollup: (options) => rollup({ ...options, fs: options?.fs ?? fs }),
        devCookie: headers?.['Cookie'],
        xUserToken: headers?.['X-UserToken'],
        glideOrigin,
        nowConfig: project.getConfig(),
    });
}
//# sourceMappingURL=default-ui-dev.js.map