fix(sdk): anchor extractFrontmatter at file start (#3240) (#3247)

* test: reproduce extractFrontmatter LAST-block bug (#3240)

* fix(sdk): anchor extractFrontmatter at file start (#3240)

* changeset: pr=3247 for #3240
This commit is contained in:
Tom Boucher
2026-05-08 08:40:30 -04:00
committed by GitHub
parent 447763411a
commit b2f0fdf250
5 changed files with 122 additions and 12 deletions

View File

@@ -25,13 +25,17 @@ import type {
* Uses a stack-based parser that handles nested objects, inline arrays,
* multi-line arrays, and boolean/numeric coercion. Ported from the CJS
* reference implementation with the same edge-case coverage.
*
* Anchored at the start of the file — only the leading `---...---` block is
* considered canonical frontmatter. Body `---` separators and embedded YAML
* inside fenced code blocks are never picked up.
*/
export function extractFrontmatter(content: string): Record<string, unknown> {
const frontmatter: Record<string, unknown> = {};
// Find ALL frontmatter blocks — if multiple exist (corruption), use the last one
const allBlocks = [...content.matchAll(/(?:^|\n)\s*---\r?\n([\s\S]+?)\r?\n---/g)];
const match = allBlocks.length > 0 ? allBlocks[allBlocks.length - 1] : null;
// Anchored at file start — only the leading ---...--- block is canonical frontmatter.
// Body `---` separators and embedded YAML inside fenced code blocks are not matched.
const match = content.match(/^---\r?\n([\s\S]+?)\r?\n---/);
if (!match) return frontmatter;
const yaml = match[1];