"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.ValidateXml = void 0;
const xsd = require("@tokenscript/libxmljs2-xsd");
const path_1 = require("path");
class ValidateXml {
    constructor(context) {
        this.context = context;
    }
    async runBuildStep() {
        this.context.updateStatus("Validate TSML...");
        let doc = this.context.getXmlDoc();
        let ns = doc.documentElement.getAttribute("xmlns:ts");
        if (!ns)
            throw new Error("Could not find namespace in XML. Are you missing a namespace declaration?");
        const versionMatch = ns.match(/([0-9]{4})\/([0-9]{2})/g);
        if (!versionMatch)
            throw new Error("Invalid schema version specified");
        const schemaVersion = versionMatch[0].replace("/", "-");
        // For some reason external schemas referenced by tokenscript.xsd do not work when using path.join or path.resolve
        const schemaBasePath = __dirname + path_1.sep + ".." + path_1.sep + ".." + path_1.sep + "schema" + path_1.sep + schemaVersion + path_1.sep;
        const schema = xsd.parseFile((0, path_1.join)(schemaBasePath, "tokenscript.xsd"), {
            baseUrl: schemaBasePath
        });
        const errors = schema.validateFile(this.context.getOutputXmlPath());
        if (errors) {
            const errMsg = "XML Validation Errors: \r\n" +
                errors.map((error) => {
                    return "- " + error.message.trim() + " (line " + error.line + ", column " + error.column + ")";
                }).join("\r\n");
            throw new Error(errMsg);
        }
    }
}
exports.ValidateXml = ValidateXml;
