"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;
    };
})();
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.NestiaEditorModule = void 0;
const fs = __importStar(require("fs"));
var NestiaEditorModule;
(function (NestiaEditorModule) {
    NestiaEditorModule.setup = (props) => __awaiter(this, void 0, void 0, function* () {
        const prefix = "/" +
            [getGlobalPrefix(props.application), props.path]
                .join("/")
                .split("/")
                .filter((str) => str.length !== 0)
                .join("/");
        const adaptor = props.application.getHttpAdapter();
        const staticFiles = [
            {
                path: "/index.html",
                type: "text/html",
                content: yield getIndex(props),
            },
            {
                path: "/swagger.json",
                type: "application/json",
                content: JSON.stringify(typeof props.swagger === "string"
                    ? yield getSwagger(props.swagger)
                    : props.swagger, null, 2),
            },
            yield getJavaScript(),
        ];
        for (const f of staticFiles) {
            adaptor.get(prefix + f.path, (_, res) => {
                res.type(f.type);
                return res.send(f.content);
            });
        }
        for (const p of ["", "/"])
            adaptor.get(prefix + p, (_, res) => {
                return res.redirect(prefix + "/index.html");
            });
    });
    const getGlobalPrefix = (app) => {
        var _a;
        return typeof ((_a = app.config) === null || _a === void 0 ? void 0 : _a.globalPrefix) === "string"
            ? app.config.globalPrefix
            : "";
    };
})(NestiaEditorModule || (exports.NestiaEditorModule = NestiaEditorModule = {}));
const getIndex = (props) => __awaiter(void 0, void 0, void 0, function* () {
    var _a;
    const content = yield fs.promises.readFile(`${__dirname}/../dist/index.html`, "utf8");
    return content
        .replace(`"@ORGANIZATION/PROJECT"`, JSON.stringify((_a = props.package) !== null && _a !== void 0 ? _a : "@ORGANIZATION/PROJECT"))
        .replace("window.simulate = false", `window.simulate = ${!!props.simulate}`)
        .replace("window.e2e = false", `window.e2e = ${!!props.e2e}`);
});
const getJavaScript = () => __awaiter(void 0, void 0, void 0, function* () {
    const directory = yield fs.promises.readdir(`${__dirname}/../dist/assets`);
    const path = directory[0];
    if (path === undefined)
        throw new Error("Unreachable code, no JS file exists.");
    return {
        path: `/assets/${path}`,
        type: "application/javascript",
        content: yield fs.promises.readFile(`${__dirname}/../dist/assets/${path}`, "utf8"),
    };
});
const getSwagger = (url) => __awaiter(void 0, void 0, void 0, function* () {
    const response = yield fetch(url);
    if (response.status !== 200)
        throw new Error(`Failed to fetch Swagger document from ${url}`);
    return response.json();
});
//# sourceMappingURL=NestiaEditorModule.js.map