"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.parseFrontmatterBlock = parseFrontmatterBlock;
exports.parseFrontmatterKeyValue = parseFrontmatterKeyValue;
exports.decodeFrontmatterScalar = decodeFrontmatterScalar;
function parseFrontmatterBlock(source, options = {}) {
    if (!source.startsWith("---\n") && !source.startsWith("---\r\n")) {
        return { kind: "not-frontmatter" };
    }
    const lines = source.split(/\r?\n/u);
    if (lines[0] !== "---") {
        return { kind: "not-frontmatter" };
    }
    const closingDelimiter = options.closingDelimiter ?? "exact";
    let closingIndex = -1;
    for (let index = 1; index < lines.length; index += 1) {
        const line = lines[index] ?? "";
        const isClosingDelimiter = closingDelimiter === "trimmed" ? line.trim() === "---" : line === "---";
        if (isClosingDelimiter) {
            closingIndex = index;
            break;
        }
    }
    if (closingIndex < 0) {
        return { kind: "missing-closing-delimiter" };
    }
    return {
        kind: "frontmatter",
        lines: lines.slice(1, closingIndex),
        body: lines.slice(closingIndex + 1).join("\n"),
        bodyStartLineNumber: closingIndex + 2,
    };
}
function parseFrontmatterKeyValue(line) {
    const trimmed = line.trim();
    const separatorIndex = trimmed.indexOf(":");
    if (separatorIndex <= 0) {
        return null;
    }
    return {
        key: trimmed.slice(0, separatorIndex).trim(),
        value: trimmed.slice(separatorIndex + 1).trim(),
    };
}
function decodeFrontmatterScalar(value, options = {}) {
    if (value.length < 2) {
        if (options.parseJsonString === true && (value === '"' || value === "'")) {
            return "";
        }
        return value;
    }
    const firstCharacter = value[0];
    const lastCharacter = value[value.length - 1];
    if ((firstCharacter !== '"' && firstCharacter !== "'") ||
        firstCharacter !== lastCharacter) {
        return value;
    }
    if (options.parseJsonString === true) {
        try {
            return JSON.parse(value);
        }
        catch {
            return value.slice(1, -1);
        }
    }
    return value.slice(1, -1);
}
