/**
 * Minimal YAML front-matter parser. Splits a `---`-delimited header from the
 * markdown body and validates the YAML payload against
 * {@link DocFrontmatterSchema}.
 *
 * Implemented in-house (rather than via `gray-matter`) to avoid an extra
 * runtime dependency: `js-yaml` is already in the install bundle.
 */
import yaml from "js-yaml";
import { DocFrontmatterSchema } from "./types.js";
const FRONTMATTER_RE = /^---\r?\n([\s\S]*?)\r?\n---\r?\n?([\s\S]*)$/;
export class FrontmatterError extends Error {
    sourcePath;
    cause;
    constructor(message, sourcePath, cause) {
        super(`[${sourcePath}] ${message}`);
        this.sourcePath = sourcePath;
        this.cause = cause;
        this.name = "FrontmatterError";
    }
}
/**
 * Parse and validate front-matter from a raw markdown source.
 *
 * @param raw The full file contents.
 * @param sourcePath Used purely for error messages.
 */
export function parseFrontmatter(raw, sourcePath) {
    const match = FRONTMATTER_RE.exec(raw);
    if (!match) {
        throw new FrontmatterError("missing or malformed front-matter block (expected --- ... --- at file start)", sourcePath);
    }
    const [, yamlSrc, bodySrc] = match;
    let parsed;
    try {
        parsed = yaml.load(yamlSrc) ?? {};
    }
    catch (error) {
        throw new FrontmatterError("front-matter YAML failed to parse", sourcePath, error);
    }
    const result = DocFrontmatterSchema.safeParse(parsed);
    if (!result.success) {
        const detail = result.error.issues
            .map((issue) => `${issue.path.join(".") || "(root)"}: ${issue.message}`)
            .join("; ");
        throw new FrontmatterError(`front-matter validation failed (${detail})`, sourcePath);
    }
    return { frontmatter: result.data, body: bodySrc.trimStart() };
}
//# sourceMappingURL=frontmatter.js.map