"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.validateAutomationEnvelope = validateAutomationEnvelope;
const _2020_1 = __importDefault(require("ajv/dist/2020"));
const schemas_1 = require("../../generated/automation-protocol/v1/schemas");
const schemas_2 = require("../../generated/automation-protocol/v2/schemas");
const _1 = require(".");
const ajv = new _2020_1.default({
    allErrors: true,
    allowUnionTypes: true,
    strict: true
});
for (const schema of [...schemas_1.AUTOMATION_PROTOCOL_SCHEMAS, ...schemas_2.AUTOMATION_PROTOCOL_SCHEMAS]) {
    ajv.addSchema(schema);
}
function requireEnvelopeValidator(version) {
    const schemaId = `https://tnsds.tech/schemas/automation/v${version}/envelope.schema.json`;
    const validator = ajv.getSchema(schemaId);
    if (validator === undefined) {
        throw new Error(`Generated automation protocol bundle is missing '${schemaId}'.`);
    }
    return validator;
}
function validateAutomationEnvelope(value) {
    const serialized = JSON.stringify(value);
    if (serialized === undefined) {
        throw new TypeError("Automation envelope must be JSON serializable.");
    }
    const wireValue = JSON.parse(serialized);
    const version = (0, _1.resolveAutomationProtocolVersion)(typeof wireValue === "object" && wireValue !== null ? wireValue.protocolVersion : undefined);
    if (version === null)
        throw new TypeError("Automation envelope has an unsupported protocol version.");
    const validateEnvelope = requireEnvelopeValidator(version);
    if (!validateEnvelope(wireValue)) {
        throw new TypeError(`Automation envelope failed protocol-v${version} validation: ${JSON.stringify(validateEnvelope.errors ?? [])}`);
    }
    return wireValue;
}
