"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.SpaHtmlService = void 0;
const node_path_1 = require("node:path");
const node_process_1 = __importDefault(require("node:process"));
const fs_extra_1 = require("fs-extra");
class SpaHtmlService {
    static async updateIndexHtml(webroot) {
        const indexPath = (0, node_path_1.resolve)(node_process_1.default.env.UIX_BASE_PATH, 'public/index.html');
        if (!(await (0, fs_extra_1.exists)(indexPath))) {
            return;
        }
        const originalHtml = await (0, fs_extra_1.readFile)(indexPath, 'utf-8');
        const normalizedWebroot = this.normalizeWebroot(webroot);
        const modifiedHtml = this.transformHtmlForWebroot(originalHtml, normalizedWebroot);
        await (0, fs_extra_1.writeFile)(indexPath, modifiedHtml);
    }
    static normalizeWebroot(webroot) {
        if (!webroot || webroot === '/') {
            return '';
        }
        return webroot.replace(/\/+/g, '/').replace(/^\/+|\/+$/g, '');
    }
    static transformHtmlForWebroot(html, webroot) {
        const baseHref = webroot ? `/${webroot}/` : '/';
        return html
            .replace(/<base href="[^"]*"(\s*)\/?>/g, `<base href="${baseHref}"$1/>`)
            .replace(/href="\/(?:.*?\/)?assets\//g, 'href="assets/')
            .replace(/href="\/(?:.*?\/)?favicon\.ico"/g, 'href="favicon.ico"')
            .replace(/href="\/(?:.*?\/)?([^"/]+\.(png|svg|webmanifest))"/g, 'href="$1"')
            .replace(/src="\/(?:.*?\/)?assets\//g, 'src="assets/');
    }
}
exports.SpaHtmlService = SpaHtmlService;
//# sourceMappingURL=spa-html.service.js.map