"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const path_1 = __importDefault(require("path"));
const debug_1 = __importDefault(require("debug"));
const compiler_1 = require("@webruntime/compiler");
const api_1 = require("@webruntime/api");
const strip_ansi_1 = __importDefault(require("strip-ansi"));
const SFDX_LWC_DIRECTORY = 'lwc';
const debug = debug_1.default('localdevserver:customcomponents');
function getCustomComponentService(customModulesNamespace, modulesDirectory) {
    const uriPrefix = `/custom-component/:uid/:mode/:locale/${customModulesNamespace}/`;
    const uri = `${uriPrefix}:name`;
    return class CustomComponentService extends api_1.AddressableService {
        constructor(config) {
            super(uri);
            this.mappings = {};
            this.mappings = {
                [`${customModulesNamespace}/`]: uriPrefix
            };
        }
        async initialize() { }
        async request(specifier, params, { compilerConfig }) {
            const name = this.extractNameFromSpecifier(specifier);
            if (!name) {
                throw new Error(`Invalid specifier for custom component: ${specifier}`);
            }
            compilerConfig.baseDir = modulesDirectory;
            let { result, metadata, success, diagnostics } = await compiler_1.compile({
                ...compilerConfig,
                namespace: SFDX_LWC_DIRECTORY,
                name
            });
            if (diagnostics && diagnostics.length > 0) {
                let partialCompileError = false;
                for (let i = 0; i < diagnostics.length; i++) {
                    if (diagnostics[i].code === 1002) {
                        partialCompileError = true;
                        break;
                    }
                }
                if (!partialCompileError) {
                    return {
                        type: api_1.RequestOutputTypes.JSON,
                        resource: { json: this.formatDiagnostics(diagnostics) },
                        specifier,
                        diagnostics,
                        success
                    };
                }
            }
            return {
                type: api_1.RequestOutputTypes.COMPONENT,
                specifier,
                resource: result,
                metadata,
                success,
                diagnostics
            };
        }
        toSpecifier(url) {
            const namespace = path_1.default.basename(path_1.default.dirname(url));
            const name = path_1.default.basename(url);
            return `${namespace}/${name}`;
        }
        extractNameFromSpecifier(specifier) {
            const split = specifier.split('/');
            if (!split || split.length !== 2) {
                return null;
            }
            return split[1];
        }
        formatDiagnostics(diagnostics) {
            let resultJSON = { errors: [] };
            diagnostics.forEach(diagnostic => {
                let msgTitle = diagnostic.message.split('\n')[0];
                const msgBody = strip_ansi_1.default(diagnostic.message.replace(msgTitle, ''));
                if (diagnostic.filename) {
                    msgTitle = msgTitle.replace(`${diagnostic.filename}:`, '');
                }
                const err = {
                    filename: diagnostic.filename,
                    location: diagnostic.location,
                    code: msgBody,
                    message: msgTitle
                };
                resultJSON.errors.push(err);
            });
            return resultJSON;
        }
    };
}
exports.getCustomComponentService = getCustomComponentService;
//# sourceMappingURL=CustomComponentService.js.map