/** * Shared frontmatter utilities — used by read-frontmatter, write-frontmatter, * card-crud, preview-deck, and generate-card-deck. */ import yaml from "js-yaml"; import type { DeckFrontmatter } from "./read-frontmatter.js"; /** * Parse YAML frontmatter from a CSV file's raw content. * Expects `---\n...\n---\n` delimited frontmatter at the top of the file. */ export function parseFrontMatter(content: string): { frontmatter?: DeckFrontmatter; csvContent: string; } { const parts = content.trim().split(/(?:^|\n)---\s*\n/g); if (parts.length !== 3 || parts[0] !== "") { return { csvContent: content }; } try { const frontmatterStr = parts[1].trim(); const frontmatter = yaml.load(frontmatterStr) as | DeckFrontmatter | undefined; const csvContent = parts.slice(2).join("---\n").trimStart(); return { frontmatter, csvContent }; } catch (error) { console.warn("Failed to parse front matter:", error); return { csvContent: content }; } } /** * Serialize a DeckFrontmatter object to YAML frontmatter string. */ export function serializeFrontMatter(frontmatter: DeckFrontmatter): string { const yamlStr = yaml.dump(frontmatter, { indent: 2, lineWidth: -1, noRefs: true, quotingType: '"', forceQuotes: false, }); return `---\n${yamlStr}---\n`; }