"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.parseYaml = parseYaml;
exports.parseSingleYaml = parseSingleYaml;
exports.dump = dump;
const js_yaml_1 = require("js-yaml");
const logger_1 = require("../logger");
const regex_1 = require("./regex");
function parseYaml(content, options) {
    const massagedContent = massageContent(content, options);
    const rawDocuments = (0, js_yaml_1.loadAll)(massagedContent, null, options);
    const schema = options?.customSchema;
    if (!schema) {
        return rawDocuments;
    }
    const parsed = [];
    for (const element of rawDocuments) {
        const result = schema.safeParse(element);
        if (result.success) {
            parsed.push(result.data);
            continue;
        }
        if (options?.failureBehaviour !== 'filter') {
            throw new Error('Failed to parse YAML file', { cause: result.error });
        }
        logger_1.logger.trace({ error: result.error, document: element }, 'Failed to parse schema for YAML');
    }
    return parsed;
}
function parseSingleYaml(content, options) {
    const massagedContent = massageContent(content, options);
    const rawDocument = (0, js_yaml_1.load)(massagedContent, options);
    const schema = options?.customSchema;
    if (!schema) {
        return rawDocument;
    }
    return schema.parse(rawDocument);
}
function dump(obj, opts) {
    return (0, js_yaml_1.dump)(obj, opts);
}
function massageContent(content, options) {
    if (options?.removeTemplates) {
        return content
            .replace((0, regex_1.regEx)(/\s+{{.+?}}:.+/gs), '')
            .replace((0, regex_1.regEx)(/{{`.+?`}}/gs), '')
            .replace((0, regex_1.regEx)(/{{.+?}}/gs), '')
            .replace((0, regex_1.regEx)(/{%`.+?`%}/gs), '')
            .replace((0, regex_1.regEx)(/{%.+?%}/g), '');
    }
    return content;
}
//# sourceMappingURL=yaml.js.map