"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.withFHR = void 0;
const find_up_1 = require("find-up");
const promises_1 = __importDefault(require("node:fs/promises"));
const log_1 = __importDefault(require("./helpers/log"));
const logError_1 = __importDefault(require("./helpers/logError"));
const FirebaseConfigFileName = 'firebase.json';
const withFHR = (sites) => (nextConfig = {}) => {
    if (!sites || sites.length < 1) {
        throw new Error(`In order for this to work provide a list of sites to check for rewrites in the firebase.json hosting section.`);
    }
    return Object.assign({}, nextConfig, {
        exportPathMap: async (defaultPathMap, { dir }) => {
            (0, log_1.default)('Validating Firebase Hosting Rules (FHR)...');
            const firebaseConfigPath = await (0, find_up_1.findUp)(FirebaseConfigFileName, {
                cwd: dir,
            });
            if (!firebaseConfigPath) {
                throw new Error(`${FirebaseConfigFileName} not found looking through directories from ${dir} to the root.`);
            }
            (0, log_1.default)(`Found Firebase config at ${firebaseConfigPath}.`);
            const firebaseConfig = JSON.parse(await promises_1.default.readFile(firebaseConfigPath, 'utf8'));
            const firebaseConfigHosting = firebaseConfig.hosting;
            if (!firebaseConfigHosting) {
                throw new Error(`The config ${firebaseConfigPath} does not contain a "hosting" section. Add it and run this again.`);
            }
            const firebaseConfigHostingItems = firebaseConfigHosting.filter((hostingConfig) => hostingConfig.site && sites.includes(hostingConfig.site));
            if (firebaseConfigHostingItems.length === 0) {
                throw new Error(`The following sites were provided as parameter (${sites.join(', ')}), but no hosting entries with matching site were found.`);
            }
            if (firebaseConfigHostingItems.length !== sites.length) {
                const foundSites = firebaseConfigHostingItems.map((item) => item.site);
                throw new Error(`The following sites were provided as parameter (${sites.join(', ')}), but only (${foundSites.join(', ')}).`);
            }
            let errorFound = false;
            for (const sitePath in defaultPathMap) {
                if (sitePath.includes('[')) {
                    // Replace slugs (i.e. [...varname])
                    let source = sitePath.replace(/\[\.{3}.+?\]$/gm, '**');
                    // Check for mistake in remaining params (param starting with .)
                    if (/\[\.+.+?\]/gm.test(source)) {
                        throw new Error(`Dynamic path '${sitePath}' section should not start with . (e.g. [.name]) except for slugs at the end (i.e. [...name]). Check https://nextjs.org/docs/routing/dynamic-routes for more details.`);
                    }
                    // Replace other params with glob
                    source = source.replace(/\[[^.].+?\]/gm, '*');
                    // Destination just add html (generated by Next.js)
                    let destination = sitePath + '.html';
                    let rewriteRule;
                    for (const hostingEntry of firebaseConfigHostingItems) {
                        rewriteRule = hostingEntry.rewrites?.find((val) => val.source === source);
                        if (!rewriteRule) {
                            errorFound = true;
                            (0, logError_1.default)();
                            (0, logError_1.default)(`REWRITE RULE ERROR @ firebase.json/hosting/[site="${hostingEntry.site}"]`);
                            (0, logError_1.default)(`Missing rewrite rule for site path '${sitePath}'.`);
                            (0, logError_1.default)('Include the following rewrite rule in firebase.json:');
                            (0, logError_1.default)();
                            (0, logError_1.default)(JSON.stringify({ source, destination }));
                            (0, logError_1.default)();
                        }
                        else if (rewriteRule.destination !== destination) {
                            errorFound = true;
                            (0, logError_1.default)();
                            (0, logError_1.default)(`REWRITE RULE ERROR @ firebase.json/hosting/[site=${hostingEntry.site}]`);
                            (0, logError_1.default)(`Incorrect rewrite rule for site path '${sitePath}'.`);
                            (0, logError_1.default)('In firebase.json replace:');
                            (0, logError_1.default)();
                            (0, logError_1.default)(JSON.stringify(rewriteRule));
                            (0, logError_1.default)();
                            (0, logError_1.default)('with');
                            (0, logError_1.default)();
                            (0, logError_1.default)(JSON.stringify({ source, destination }));
                            (0, logError_1.default)();
                        }
                    }
                }
            }
            if (errorFound) {
                throw new Error(`One or more rewrites rules missing or erroneous in '${firebaseConfigPath}'.`);
            }
            else {
                (0, log_1.default)('[PASS] Firebase Hosting Rules are OK!');
            }
            return defaultPathMap;
        },
    });
};
exports.withFHR = withFHR;
//# sourceMappingURL=index.js.map