@blogmcp/mdx-schema 0.2.2 → 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/composables/useMdxParsing.d.ts +155 -0
- package/dist/composables/useMdxParsing.js +617 -30
- package/dist/composables/useMdxParsing.js.map +1 -1
- package/dist/metadata/validate.d.ts +19 -0
- package/dist/metadata/validate.js +40 -15
- package/dist/metadata/validate.js.map +1 -1
- package/package.json +1 -1
- package/src/composables/useMdxParsing.ts +629 -30
- package/src/metadata/validate.ts +45 -15
|
@@ -17,6 +17,38 @@ export const HAS_MDX_RE = /<[A-Z][a-zA-Z]*[\s/>]/;
|
|
|
17
17
|
* - Self-closing: match[4]=name, match[5]=props
|
|
18
18
|
*
|
|
19
19
|
* NOTE: Create a new RegExp instance per call (g-flag + exec requires fresh lastIndex).
|
|
20
|
+
*
|
|
21
|
+
* @deprecated MATCHING ONLY — never build a document WALK on this. It cannot express either
|
|
22
|
+
* half of correct extraction, and both gaps caused measured production damage:
|
|
23
|
+
*
|
|
24
|
+
* - NO PROP BOUNDARY. The self-closing branch's props group `(?:[^/]|\/(?!>))*` matches '>'
|
|
25
|
+
* and newlines, so ANY `<Name>` — including a prose mention — starts a match that runs to
|
|
26
|
+
* the next '/>' anywhere in the document. Measured on `docs/public/tools/upload-media.md`:
|
|
27
|
+
* ONE match spanning lines 25→166 (142 lines, 8916 chars, 1362 whitespace-separated "prop"
|
|
28
|
+
* tokens), which SWALLOWS everything it spans — 81.7% of that page's body never reached the
|
|
29
|
+
* renderer.
|
|
30
|
+
* - NO CODE AWARENESS. A component inside a fence (all 4 flavours: bare ```, ```lang,
|
|
31
|
+
* 1-3-space-indented, and ~~~) or inside an inline `code` span is documentation ABOUT the
|
|
32
|
+
* component, and was extracted as a LIVE one. Both the inline SELF-CLOSING form
|
|
33
|
+
* (`` `<Gallery images={[1]} />` ``) and the inline PAIRED form (`` `<Callout>x</Callout>` ``)
|
|
34
|
+
* extracted. A bare `` `<Gallery>` `` mention was ignored only because it has no closer — so
|
|
35
|
+
* "inline spans are already respected" was never true.
|
|
36
|
+
* - The paired branch is not a safe reference to mirror either: `([^>]*)` stops at the first '>'
|
|
37
|
+
* even inside a quoted value (`<Callout title="a > b">Hi</Callout>` → children `b">\nHi`) and
|
|
38
|
+
* eats the trailing '/' of a self-closing tag, absorbing it as paired whenever a later
|
|
39
|
+
* `</Name>` exists (`docs/public/concepts/mdx-storage-format.md:138` swallowed 4 real
|
|
40
|
+
* components that way, across 57 lines).
|
|
41
|
+
*
|
|
42
|
+
* Neither gap is expressible as a regex (nested braces need recursion; code masking needs a
|
|
43
|
+
* block-structure pre-pass), and a post-filter over these matches cannot recover a component a
|
|
44
|
+
* runaway match already consumed — `exec` has advanced past it. The tempting "just mirror the
|
|
45
|
+
* paired branch" tighten to `([^>]*)` is WORSE THAN THE BUG: it passes the entire existing test
|
|
46
|
+
* suite while silently deleting real committed content — `upload-media.md:166-167`
|
|
47
|
+
* (`<Gallery images={[{ src: "<url>", … }]} />`, `<AudioPlayer slug="<slug>" />`) match ZERO
|
|
48
|
+
* times under it.
|
|
49
|
+
*
|
|
50
|
+
* Use {@link scanMdxNodes} (offsets) or {@link extractMdxComponents} (no offsets). Still exported
|
|
51
|
+
* only so already-published consumers keep compiling.
|
|
20
52
|
*/
|
|
21
53
|
export const MDX_COMPONENT_PATTERN = /<([A-Z][a-zA-Z]*)\s*([^>]*)>([\s\S]*?)<\/\1>|<([A-Z][a-zA-Z]*)\s*((?:[^/]|\/(?!>))*)\/>/g;
|
|
22
54
|
/**
|
|
@@ -99,11 +131,21 @@ export function parseJsxProps(propsString) {
|
|
|
99
131
|
else if (s[i] === '{') {
|
|
100
132
|
const expr = extractBraceExpression(s, i);
|
|
101
133
|
if (expr) {
|
|
134
|
+
// Try the expression AS WRITTEN first. The `'` → `"` rewrite below exists only to accept
|
|
135
|
+
// single-quoted arrays (`images={['/a.jpg']}`), but applying it first corrupts any valid JSON
|
|
136
|
+
// containing an apostrophe — `{"it's \"x\""}` became `{"it"s \"x\""}` and fell through to the
|
|
137
|
+
// raw-string fallback. That matters now that `serializeProps` emits quote-bearing strings
|
|
138
|
+
// through this brace form.
|
|
102
139
|
try {
|
|
103
|
-
result[name] = JSON.parse(expr.content
|
|
140
|
+
result[name] = JSON.parse(expr.content);
|
|
104
141
|
}
|
|
105
142
|
catch {
|
|
106
|
-
|
|
143
|
+
try {
|
|
144
|
+
result[name] = JSON.parse(expr.content.replace(/'/g, '"'));
|
|
145
|
+
}
|
|
146
|
+
catch {
|
|
147
|
+
result[name] = expr.content;
|
|
148
|
+
}
|
|
107
149
|
}
|
|
108
150
|
i = expr.endIndex;
|
|
109
151
|
}
|
|
@@ -136,7 +178,18 @@ export function serializeProps(props) {
|
|
|
136
178
|
parts.push(key);
|
|
137
179
|
}
|
|
138
180
|
else if (typeof value === 'string') {
|
|
139
|
-
|
|
181
|
+
// ⚠ A double quote cannot appear inside a double-quoted JSX attribute, so a value containing
|
|
182
|
+
// one goes out through the BRACE form instead. Emitting it raw produced content that neither
|
|
183
|
+
// this scanner nor @mdx-js/mdx can parse, and the failure was silent in three different ways:
|
|
184
|
+
// {title: 'Vyska 5" a delka'} → the component was DROPPED entirely on re-read
|
|
185
|
+
// {title: 'say "hi"'} → re-read as {title: 'say ', hi: true} — value truncated and a
|
|
186
|
+
// boolean prop invented out of the remaining text
|
|
187
|
+
// {alt: 'a " b', src: '/x'} → dropped, taking the unrelated `src` with it
|
|
188
|
+
// This writer is reachable from ordinary authoring: MdxBlockView's visual prop editor calls it
|
|
189
|
+
// on every edit, so typing a quote into a title corrupted the component on save.
|
|
190
|
+
// `{JSON.stringify(...)}` round-trips through `parseJsxProps`, which parses a brace expression
|
|
191
|
+
// as JSON.
|
|
192
|
+
parts.push(value.includes('"') ? `${key}={${JSON.stringify(value)}}` : `${key}="${value}"`);
|
|
140
193
|
}
|
|
141
194
|
else if (typeof value === 'number') {
|
|
142
195
|
parts.push(`${key}={${value}}`);
|
|
@@ -192,45 +245,579 @@ export function extractFrontmatter(source) {
|
|
|
192
245
|
return null;
|
|
193
246
|
}
|
|
194
247
|
/**
|
|
195
|
-
*
|
|
196
|
-
* Does NOT process markdown → HTML (caller handles that).
|
|
248
|
+
* Exact start offset of the `stripFrontmatter` result within `content`.
|
|
197
249
|
*
|
|
198
|
-
*
|
|
199
|
-
*
|
|
250
|
+
* Mirrors `stripFrontmatter` exactly (substring after the closing `---`, then `.trim()`), so an
|
|
251
|
+
* offset produced by scanning the STRIPPED body can be mapped back onto full-article coordinates.
|
|
252
|
+
*
|
|
253
|
+
* ⚠ Do NOT derive this as `content.length - stripped.length` — `stripFrontmatter` trims BOTH
|
|
254
|
+
* ends, so that delta is not the prefix length. That confusion is half of the line-number defect
|
|
255
|
+
* this exists to fix: the validator searched the ORIGINAL content while extraction ran on the
|
|
256
|
+
* STRIPPED copy, so the two offset bases silently differed and a component name merely MENTIONED
|
|
257
|
+
* in frontmatter hijacked every reported line.
|
|
258
|
+
*
|
|
259
|
+
* KNOWN, PRE-EXISTING: a document opening with a `---` THEMATIC BREAK is still misread as
|
|
260
|
+
* frontmatter. This function faithfully mirrors that bug so offsets stay CONSISTENT with
|
|
261
|
+
* `stripFrontmatter`; fixing it is a separate change to `stripFrontmatter` itself.
|
|
200
262
|
*/
|
|
201
|
-
export function
|
|
263
|
+
export function computeBodyOffset(content) {
|
|
264
|
+
if (!content)
|
|
265
|
+
return 0;
|
|
266
|
+
if (!content.startsWith('---'))
|
|
267
|
+
return 0; // no frontmatter → returned as-is, no trim
|
|
268
|
+
const endIndex = content.indexOf('---', 3);
|
|
269
|
+
if (endIndex === -1)
|
|
270
|
+
return 0; // unterminated frontmatter → returned as-is
|
|
271
|
+
const preBodyEnd = endIndex + 3;
|
|
272
|
+
const afterDelim = content.slice(preBodyEnd);
|
|
273
|
+
return preBodyEnd + (afterDelim.length - afterDelim.trimStart().length);
|
|
274
|
+
}
|
|
275
|
+
/** 1-based line number containing `offset` within `content`. */
|
|
276
|
+
export function lineAtOffset(content, offset) {
|
|
277
|
+
if (offset <= 0)
|
|
278
|
+
return 1;
|
|
279
|
+
const limit = Math.min(offset, content.length);
|
|
280
|
+
let line = 1;
|
|
281
|
+
for (let i = 0; i < limit; i++) {
|
|
282
|
+
if (content[i] === '\n')
|
|
283
|
+
line++;
|
|
284
|
+
}
|
|
285
|
+
return line;
|
|
286
|
+
}
|
|
287
|
+
/** `computeCodeMask` flag: this offset is ordinary markup/prose. */
|
|
288
|
+
export const CODE_NONE = 0;
|
|
289
|
+
/**
|
|
290
|
+
* `computeCodeMask` flag: this offset is inside a FENCED code block — block-level structure,
|
|
291
|
+
* therefore HIGH confidence. A tag whose own boundary lands in one is malformed and is rejected.
|
|
292
|
+
*/
|
|
293
|
+
export const CODE_FENCE = 1;
|
|
294
|
+
/**
|
|
295
|
+
* `computeCodeMask` flag: this offset is inside an INLINE code span — AMBIGUOUS, therefore lower
|
|
296
|
+
* confidence. A lone backtick inside a prop value (`title="the \` char"`) can pair with a genuine
|
|
297
|
+
* span later on the same line and mask the tag's own '>' or its closing tag. Inline masking may
|
|
298
|
+
* therefore hide a tag START, but must never invalidate a tag BOUNDARY (see `scanOpenTag`'s caller)
|
|
299
|
+
* and must never be the sole reason a paired tag loses its closer (see `findClosingTag`, which
|
|
300
|
+
* falls back to a masked closer rather than dropping the component).
|
|
301
|
+
*/
|
|
302
|
+
export const CODE_INLINE = 2;
|
|
303
|
+
/** Opening fence: up to 3 spaces of indent, then >=3 backticks or tildes, then the info string. */
|
|
304
|
+
const FENCE_OPEN_RE = /^ {0,3}(`{3,}|~{3,})(.*)$/;
|
|
305
|
+
/** Closing fence: same run, and nothing but trailing horizontal whitespace after it. */
|
|
306
|
+
const FENCE_CLOSE_RE = /^ {0,3}(`{3,}|~{3,})[ \t]*$/;
|
|
307
|
+
/**
|
|
308
|
+
* Flag every offset in `source` that sits inside a code region. `mask[i] !== CODE_NONE` means
|
|
309
|
+
* "offset i is code, not markup". Always exactly `source.length` long.
|
|
310
|
+
*
|
|
311
|
+
* ⚠ A PARALLEL FLAG ARRAY, NOT A MASKED COPY OF THE STRING. This is the one decision in this file
|
|
312
|
+
* that must never be "simplified" later. The obvious implementation — build a masked string and
|
|
313
|
+
* scan that — destroys content, because every slice the scanner emits (props, children, html
|
|
314
|
+
* chunks) would then come from the masked copy: a `<CodeBlock language="md">` wrapping a fenced
|
|
315
|
+
* sample would emit `children` of pure filler, and `title="Use \`code\` inline"` would become
|
|
316
|
+
* `title="Use ______ inline"`. With a flag array there is no second string to slice from by
|
|
317
|
+
* accident, index alignment is free, and the validator's offsets are exact by construction.
|
|
318
|
+
*
|
|
319
|
+
* WHY it exists at all (measured): the scanner had no notion of code, so 100% of the component
|
|
320
|
+
* instances in the entire shipped docs corpus — 49 fenced + 21 inline, ZERO in prose — were
|
|
321
|
+
* extracted as live components. All 4 fence flavours are affected (bare ```, ```lang,
|
|
322
|
+
* 1-3-space-indented, ~~~), and BOTH inline forms extract. It also made a component's own
|
|
323
|
+
* documentation unpublishable: `docs/public/features/editor-mcp.md` was rejected with HTTP 400
|
|
324
|
+
* `Gallery (line 194): Missing required prop "images"` purely from a fenced teaching example, and
|
|
325
|
+
* `features/article-feedback.md` — which contains ZERO fences — was blocked by an inline one.
|
|
326
|
+
*
|
|
327
|
+
* Three deliberate divergences from CommonMark, each chosen because the alternative loses
|
|
328
|
+
* legitimate content. Every one fails OPEN (toward extraction): a false negative re-renders a code
|
|
329
|
+
* sample as a live component — visible and reportable; a false positive DELETES a working
|
|
330
|
+
* component from a published page.
|
|
331
|
+
*
|
|
332
|
+
* 1. An UNTERMINATED fence masks NOTHING, and the scan RESUMES on the next line so a LATER
|
|
333
|
+
* well-formed fence in the same document is still masked. CommonMark extends an unclosed fence
|
|
334
|
+
* to end-of-document; honouring that drops every component after a stray fence, and this is not
|
|
335
|
+
* hypothetical — `docs/public/features/media-picker.md:204` opens a ```json fence it never
|
|
336
|
+
* closes. It would also break the extract → serialize → re-extract roundtrip for
|
|
337
|
+
* `<CodeBlock language="md">\n```\n</CodeBlock>`.
|
|
338
|
+
* 2. Inline spans are SINGLE-LINE and run-length matched (a run of N closes only on exactly N).
|
|
339
|
+
* CommonMark would pair a stray backtick with one on a later line and swallow a real component
|
|
340
|
+
* in between.
|
|
341
|
+
* 3. Four-space INDENTED code blocks are NOT masked. They are the only construct where masking is
|
|
342
|
+
* actively harmful: the continuation lines of a legitimate multi-line component are themselves
|
|
343
|
+
* indented >=4, so masking them would leave the tag matching with its props EMPTIED, turning
|
|
344
|
+
* valid content into a save-blocking `Missing required prop "images"`. A false negative beats a
|
|
345
|
+
* false error. (Blockquoted fences and fences indented >=4 inside list items are likewise not
|
|
346
|
+
* detected — same direction, same reason.)
|
|
347
|
+
*/
|
|
348
|
+
export function computeCodeMask(source) {
|
|
349
|
+
const mask = new Uint8Array(source.length);
|
|
350
|
+
// Fast path: no fence or span delimiter can exist without one of these.
|
|
351
|
+
if (!source || (!source.includes('`') && !source.includes('~')))
|
|
352
|
+
return mask;
|
|
353
|
+
// Line index over the ORIGINAL source; offsets stay valid in both views.
|
|
354
|
+
const lineStart = [];
|
|
355
|
+
const lineEnd = [];
|
|
356
|
+
for (let i = 0; i <= source.length;) {
|
|
357
|
+
const nl = source.indexOf('\n', i);
|
|
358
|
+
lineStart.push(i);
|
|
359
|
+
lineEnd.push(nl === -1 ? source.length : nl);
|
|
360
|
+
if (nl === -1)
|
|
361
|
+
break;
|
|
362
|
+
i = nl + 1;
|
|
363
|
+
}
|
|
364
|
+
/**
|
|
365
|
+
* The line's text WITHOUT its trailing CR.
|
|
366
|
+
*
|
|
367
|
+
* ⚠ Load-bearing for CRLF documents. `FENCE_CLOSE_RE` ends `[ \t]*$`, which a trailing '\r' does
|
|
368
|
+
* not satisfy — so on CRLF content the CLOSING fence never matched, every fenced block read as
|
|
369
|
+
* unterminated, and (because an unterminated fence deliberately masks nothing) the whole code-
|
|
370
|
+
* awareness fix silently did not apply: a fenced `<Gallery images={[1]} />` extracted as a live
|
|
371
|
+
* component again. Nothing in the write path normalises line endings, and the API already
|
|
372
|
+
* receives CRLF articles (there is a CRLF fixture in kb-api's embeddings spec), so this is
|
|
373
|
+
* reachable from ordinary Windows-authored content.
|
|
374
|
+
*
|
|
375
|
+
* Stripping it HERE rather than in the regexes keeps the fix in one place, and cannot disturb
|
|
376
|
+
* offsets: `lineText` feeds only the two fence tests, while the mask is filled from
|
|
377
|
+
* `lineStart`/`lineEnd`, which still index the original source.
|
|
378
|
+
*/
|
|
379
|
+
const lineText = (n) => {
|
|
380
|
+
const raw = source.slice(lineStart[n], lineEnd[n]);
|
|
381
|
+
return raw.endsWith('\r') ? raw.slice(0, -1) : raw;
|
|
382
|
+
};
|
|
383
|
+
const fencedLine = new Array(lineStart.length).fill(false);
|
|
384
|
+
// ── Pass 1: fenced blocks. Runs FIRST so pass 2 never reads a fence delimiter as a span. ──
|
|
385
|
+
for (let ln = 0; ln < lineStart.length;) {
|
|
386
|
+
const open = FENCE_OPEN_RE.exec(lineText(ln));
|
|
387
|
+
if (!open) {
|
|
388
|
+
ln++;
|
|
389
|
+
continue;
|
|
390
|
+
}
|
|
391
|
+
const marker = open[1];
|
|
392
|
+
const fenceChar = marker[0];
|
|
393
|
+
// CommonMark: a backtick-fence info string may not itself contain a backtick.
|
|
394
|
+
if (fenceChar === '`' && open[2].includes('`')) {
|
|
395
|
+
ln++;
|
|
396
|
+
continue;
|
|
397
|
+
}
|
|
398
|
+
let close = -1;
|
|
399
|
+
for (let k = ln + 1; k < lineStart.length; k++) {
|
|
400
|
+
const m = FENCE_CLOSE_RE.exec(lineText(k));
|
|
401
|
+
if (m && m[1][0] === fenceChar && m[1].length >= marker.length) {
|
|
402
|
+
close = k;
|
|
403
|
+
break;
|
|
404
|
+
}
|
|
405
|
+
}
|
|
406
|
+
// Unterminated → mask nothing, and resume on the NEXT line (not `break`) so a later
|
|
407
|
+
// well-formed fence is still masked.
|
|
408
|
+
if (close === -1) {
|
|
409
|
+
ln++;
|
|
410
|
+
continue;
|
|
411
|
+
}
|
|
412
|
+
mask.fill(CODE_FENCE, lineStart[ln], lineEnd[close]);
|
|
413
|
+
for (let k = ln; k <= close; k++)
|
|
414
|
+
fencedLine[k] = true;
|
|
415
|
+
ln = close + 1;
|
|
416
|
+
}
|
|
417
|
+
// ── Pass 2: inline spans, per line, run-length matched. ──
|
|
418
|
+
for (let ln = 0; ln < lineStart.length; ln++) {
|
|
419
|
+
if (fencedLine[ln])
|
|
420
|
+
continue;
|
|
421
|
+
const from = lineStart[ln];
|
|
422
|
+
const to = lineEnd[ln];
|
|
423
|
+
let i = from;
|
|
424
|
+
while (i < to) {
|
|
425
|
+
if (source[i] !== '`') {
|
|
426
|
+
i++;
|
|
427
|
+
continue;
|
|
428
|
+
}
|
|
429
|
+
let run = 0;
|
|
430
|
+
while (i + run < to && source[i + run] === '`')
|
|
431
|
+
run++;
|
|
432
|
+
// A run of >=3 at line start is a fence delimiter pass 1 already ruled on (an unterminated
|
|
433
|
+
// opener is deliberately unmasked); reading it as a span delimiter would pair it with a
|
|
434
|
+
// backtick far down the document.
|
|
435
|
+
if (run >= 3 && source.slice(from, i).trim() === '') {
|
|
436
|
+
i += run;
|
|
437
|
+
continue;
|
|
438
|
+
}
|
|
439
|
+
let j = i + run;
|
|
440
|
+
let close = -1;
|
|
441
|
+
while (j < to) {
|
|
442
|
+
if (source[j] !== '`') {
|
|
443
|
+
j++;
|
|
444
|
+
continue;
|
|
445
|
+
}
|
|
446
|
+
let r = 0;
|
|
447
|
+
while (j + r < to && source[j + r] === '`')
|
|
448
|
+
r++;
|
|
449
|
+
if (r === run) {
|
|
450
|
+
close = j;
|
|
451
|
+
break;
|
|
452
|
+
}
|
|
453
|
+
j += r;
|
|
454
|
+
}
|
|
455
|
+
if (close === -1) {
|
|
456
|
+
i += run;
|
|
457
|
+
continue;
|
|
458
|
+
} // unterminated span → mask nothing
|
|
459
|
+
mask.fill(CODE_INLINE, i, close + run);
|
|
460
|
+
i = close + run;
|
|
461
|
+
}
|
|
462
|
+
}
|
|
463
|
+
return mask;
|
|
464
|
+
}
|
|
465
|
+
/**
|
|
466
|
+
* Scan one opening tag starting at `start` (which must be '<'), returning null when this is not a
|
|
467
|
+
* well-formed MDX component tag. The state machine at depth 0 outside quotes:
|
|
468
|
+
*
|
|
469
|
+
* '<' + [A-Z] → NAME (grammar is letters-only: `Product3D` is deliberately NOT a
|
|
470
|
+
* component — pinned by customComponents.spec.ts)
|
|
471
|
+
* NAME + ws|'>'|'/'→ PROPS (any other char → not a tag; this is what keeps a TS generic
|
|
472
|
+
* like `ref<Set<number>>` out)
|
|
473
|
+
* PROPS + '"'|"'" → IN_STRING (consumes '>' and '/>' — the paired-branch fix)
|
|
474
|
+
* PROPS + '{' → extractBraceExpression() (nesting- and quote-aware; unbalanced → null)
|
|
475
|
+
* PROPS + '/>' → DONE self-closing
|
|
476
|
+
* PROPS + '>' → DONE paired opener
|
|
477
|
+
* PROPS + '<' → NOT A TAG ← load-bearing prop-boundary bound
|
|
478
|
+
* PROPS + blank ln → NOT A TAG ← independent paragraph bound
|
|
479
|
+
*
|
|
480
|
+
* WHY a scanner and not a tightened regex: the old self-closing props group had no bound at all,
|
|
481
|
+
* so a prose `<Gallery>` mention ran to the next '/>' anywhere — 142 lines / 8916 chars / 1362
|
|
482
|
+
* "prop" tokens on `docs/public/tools/upload-media.md`. It cannot be fixed with a regex:
|
|
483
|
+
* - `([^>]*)` (mirroring the paired branch) passes all existing tests while silently DROPPING
|
|
484
|
+
* real committed content — `<Gallery images={[{ src: "<url>", alt: "<title>" }]} />` and
|
|
485
|
+
* `<AudioPlayer slug="<slug>" />` (`upload-media.md:166-167`) match ZERO times under it;
|
|
486
|
+
* - balanced braces nest to arbitrary depth (`images={[{...}]}`), which a JS regex cannot
|
|
487
|
+
* express, and a bounded-depth alternation only moves the silent-drop threshold.
|
|
488
|
+
* Reusing `extractBraceExpression` is what makes this provable rather than merely better: the
|
|
489
|
+
* scanner's notion of "a brace expression" is now the SAME function `parseJsxProps` uses, so a tag
|
|
490
|
+
* this scanner accepts is exactly a tag whose props `parseJsxProps` can read.
|
|
491
|
+
*
|
|
492
|
+
* The '<' bail is what stops the runaway recurring in the new implementation: without it an
|
|
493
|
+
* unterminated `<Gallery images=` walks forward through arbitrary prose to some '/>' hundreds of
|
|
494
|
+
* lines later — the identical old failure with a nicer implementation. A well-formed tag body can
|
|
495
|
+
* never contain a bare '<' at depth 0 outside quotes, and `title="a < b"` / `fn={x < y}` are
|
|
496
|
+
* consumed by the string/brace branches, so the bail costs nothing real.
|
|
497
|
+
*
|
|
498
|
+
* The blank-line bail is a second, independent bound, but it fires ONLY while a prop value is
|
|
499
|
+
* pending (a trailing '='). That condition is not decoration: an unconditional bail dropped
|
|
500
|
+
* `<Gallery\n images={[…]}\n\n columns={2}\n/>`, which @mdx-js/mdx accepts — so the reference
|
|
501
|
+
* parser and this scanner disagreed in the direction that deletes content. It cannot affect a
|
|
502
|
+
* multi-line `images={[ … ]}` either way (that newline lives inside the brace expression, consumed
|
|
503
|
+
* by extractBraceExpression); the measured corpus maximum for a real multi-line component is 4
|
|
504
|
+
* lines.
|
|
505
|
+
*
|
|
506
|
+
* Quoted values have NO escape handling, deliberately — see the `inString` branch. That matches
|
|
507
|
+
* `parseJsxProps`, which also ends a value at the first plain quote, so a tag this scanner accepts
|
|
508
|
+
* is exactly a tag whose props it can read.
|
|
509
|
+
*/
|
|
510
|
+
function scanOpenTag(source, start) {
|
|
511
|
+
if (source[start] !== '<')
|
|
512
|
+
return null;
|
|
513
|
+
const first = source[start + 1];
|
|
514
|
+
if (first === undefined || first < 'A' || first > 'Z')
|
|
515
|
+
return null;
|
|
516
|
+
let i = start + 2;
|
|
517
|
+
while (i < source.length && /[a-zA-Z]/.test(source[i]))
|
|
518
|
+
i++;
|
|
519
|
+
const name = source.slice(start + 1, i);
|
|
520
|
+
const sep = source[i];
|
|
521
|
+
if (sep === undefined)
|
|
522
|
+
return null;
|
|
523
|
+
if (sep !== '>' && sep !== '/' && !/\s/.test(sep))
|
|
524
|
+
return null;
|
|
525
|
+
while (i < source.length && /\s/.test(source[i]))
|
|
526
|
+
i++;
|
|
527
|
+
const propsStart = i;
|
|
528
|
+
/** True when the newline at `j` is followed by a blank line (i.e. a paragraph break). */
|
|
529
|
+
const blankLineAt = (j) => {
|
|
530
|
+
let k = j + 1;
|
|
531
|
+
while (k < source.length && (source[k] === ' ' || source[k] === '\t' || source[k] === '\r'))
|
|
532
|
+
k++;
|
|
533
|
+
return k >= source.length || source[k] === '\n';
|
|
534
|
+
};
|
|
535
|
+
let inString = null;
|
|
536
|
+
while (i < source.length) {
|
|
537
|
+
const ch = source[i];
|
|
538
|
+
if (inString) {
|
|
539
|
+
// ⚠ NO backslash-escape branch. JSX attribute values have no escape sequences, and treating
|
|
540
|
+
// '\' as one made an odd trailing run swallow the CLOSING quote: `title="C:\"` left the
|
|
541
|
+
// scanner permanently inside a string, so `<Callout title="C:\">Zaloha</Callout>` extracted
|
|
542
|
+
// ZERO components while the old regex read it fine — a silent drop, with validation still
|
|
543
|
+
// reporting `{valid: true}`. Worse, neither the '<' bail nor the blank-line bail can stop the
|
|
544
|
+
// walk, because both are only evaluated OUTSIDE a string, so a second stray quote later in the
|
|
545
|
+
// document produced a runaway paired match that deleted the prose between them.
|
|
546
|
+
//
|
|
547
|
+
// This is not hypothetical: `serializeProps` emits `key="value"` with no escaping, so the
|
|
548
|
+
// system's own writer produces such a value whenever a prop is edited to contain a quote.
|
|
549
|
+
// `parseJsxProps` likewise ends a value at the first plain '"', so dropping the branch makes
|
|
550
|
+
// the boundary agree with the parser that reads these props.
|
|
551
|
+
//
|
|
552
|
+
// An unterminated quote is still bounded by the paragraph break below, so it can never run
|
|
553
|
+
// away past the tag's own block.
|
|
554
|
+
if (ch === '\n' && blankLineAt(i))
|
|
555
|
+
return null;
|
|
556
|
+
if (ch === inString)
|
|
557
|
+
inString = null;
|
|
558
|
+
i++;
|
|
559
|
+
continue;
|
|
560
|
+
}
|
|
561
|
+
if (ch === '"' || ch === "'") {
|
|
562
|
+
inString = ch;
|
|
563
|
+
i++;
|
|
564
|
+
continue;
|
|
565
|
+
}
|
|
566
|
+
if (ch === '{') {
|
|
567
|
+
const expr = extractBraceExpression(source, i);
|
|
568
|
+
if (!expr)
|
|
569
|
+
return null; // unbalanced brace → not a tag we can trust
|
|
570
|
+
i = expr.endIndex;
|
|
571
|
+
continue;
|
|
572
|
+
}
|
|
573
|
+
if (ch === '/' && source[i + 1] === '>') {
|
|
574
|
+
return { name, propsSource: source.slice(propsStart, i), tagEnd: i + 2, selfClosing: true };
|
|
575
|
+
}
|
|
576
|
+
if (ch === '>') {
|
|
577
|
+
return { name, propsSource: source.slice(propsStart, i), tagEnd: i + 1, selfClosing: false };
|
|
578
|
+
}
|
|
579
|
+
if (ch === '<')
|
|
580
|
+
return null;
|
|
581
|
+
if (ch === '\n') {
|
|
582
|
+
if (blankLineAt(i)) {
|
|
583
|
+
// Only fatal while a prop VALUE is PENDING — a trailing '=' with nothing after it is the
|
|
584
|
+
// runaway precondition (`<Gallery images=` followed by paragraphs of prose and some stray
|
|
585
|
+
// '/>' far below). A blank line between COMPLETE props is valid MDX: @mdx-js/mdx accepts
|
|
586
|
+
// <Gallery\n images={["/a.jpg"]}\n\n columns={2}\n/>
|
|
587
|
+
// and an unconditional bail dropped it silently — 0 components, `{valid: true}`, and the
|
|
588
|
+
// sanitizer then removed the unknown tag, so the gallery disappeared from the page with no
|
|
589
|
+
// error and no line number to chase. The old regex parsed it and both props.
|
|
590
|
+
let k = i - 1;
|
|
591
|
+
while (k >= start && /\s/.test(source[k]))
|
|
592
|
+
k--;
|
|
593
|
+
if (source[k] === '=')
|
|
594
|
+
return null;
|
|
595
|
+
}
|
|
596
|
+
i++;
|
|
597
|
+
continue;
|
|
598
|
+
}
|
|
599
|
+
i++;
|
|
600
|
+
}
|
|
601
|
+
return null; // ran off the end with no terminator
|
|
602
|
+
}
|
|
603
|
+
/**
|
|
604
|
+
* Find the matching `</Name>` for a paired opener.
|
|
605
|
+
*
|
|
606
|
+
* FIRST match wins (not innermost/balanced) — byte-identical to the lazy `([\s\S]*?)<\/\1>` it
|
|
607
|
+
* replaces, so two sibling `<Callout>`s stay two components (pinned by the existing suite).
|
|
608
|
+
* Same-name NESTING therefore remains unsupported; there is none in the corpus, and changing it
|
|
609
|
+
* would be a behaviour change beyond the measured defects.
|
|
610
|
+
*
|
|
611
|
+
* PREFER an UNMASKED closer; fall back to the first masked one. Two independent reasons:
|
|
612
|
+
* - preferring unmasked is what lets `<CodeBlock language="md">` wrap a fenced sample that itself
|
|
613
|
+
* contains a literal `</CodeBlock>` — the lazy regex stopped at that fake closer and leaked the
|
|
614
|
+
* fence tail into a mangled html chunk;
|
|
615
|
+
* - falling back rather than dropping is what saves the paired form of the inline-span hazard:
|
|
616
|
+
* `<Callout type="info" title="the \` char">x</Callout> and \`code\` after` has its real closer
|
|
617
|
+
* swallowed by an inline span that pairs the prop's stray backtick with the span after the tag.
|
|
618
|
+
* Returning null there would DROP a component that renders correctly today.
|
|
619
|
+
*
|
|
620
|
+
* The preference is bounded by `hasSiblingOpenerBefore`: an unmasked closer lying past another
|
|
621
|
+
* opener of the same name belongs to that sibling, so it is rejected in favour of this tag's own
|
|
622
|
+
* (masked) closer. Without that bound the two components collapse into one and the prose between
|
|
623
|
+
* them is swallowed — the very failure this rewrite exists to remove, one level up.
|
|
624
|
+
*
|
|
625
|
+
* Trailing whitespace before '>' is tolerated (`</Callout >`) — a strict superset of the old
|
|
626
|
+
* behaviour (such a tag matched nothing before and fell into the runaway self-closing branch). The
|
|
627
|
+
* next-non-space-must-be-'>' check is also what stops `</Gallery` matching inside `</GalleryFoo>`.
|
|
628
|
+
*/
|
|
629
|
+
function findClosingTag(source, name, from, mask,
|
|
630
|
+
/**
|
|
631
|
+
* Names already proven to have NO unmasked closer left. Purely a performance memo — see below.
|
|
632
|
+
* Caller-owned so it lives for one `scanMdxNodes` call.
|
|
633
|
+
*/
|
|
634
|
+
noUnmaskedClosers) {
|
|
635
|
+
const needle = `</${name}`;
|
|
636
|
+
let firstAny = null;
|
|
637
|
+
// ⚠ QUADRATIC GUARD. Without it, every opener of a name whose closers are ALL masked rescans the
|
|
638
|
+
// whole remaining document looking for an unmasked one. Measured: 11KB/22KB/45KB of that shape
|
|
639
|
+
// cost 9.1/21.6/78.5ms (exponent ~1.9) where the old regex was FLAT at 0.1-0.2ms — the one new
|
|
640
|
+
// quadratic this rewrite introduced, and the only shape where it lost to the code it replaced.
|
|
641
|
+
//
|
|
642
|
+
// Soundness: closers at/after a LATER offset are a subset of those at/after an EARLIER one, and
|
|
643
|
+
// openers are visited in ascending order. So "no unmasked closer of this name after X" implies the
|
|
644
|
+
// same for every Y > X, and the memo can never hide a closer a full scan would have found. Once a
|
|
645
|
+
// name is in the set we still need `firstAny`, but that is the FIRST valid closer, so it costs one
|
|
646
|
+
// scan that stops early instead of one that always runs to EOF.
|
|
647
|
+
const skipUnmaskedSearch = noUnmaskedClosers?.has(name) ?? false;
|
|
648
|
+
/**
|
|
649
|
+
* Is there another OPENER of this same name strictly before `limit`?
|
|
650
|
+
*
|
|
651
|
+
* ⚠ This is the sibling bound on the unmasked preference, and it is load-bearing. Without it, a
|
|
652
|
+
* component whose OWN closer is masked by a false-positive inline span walks past its own closer to
|
|
653
|
+
* the next same-name sibling's closer, absorbing that sibling and all the prose between — two
|
|
654
|
+
* components collapse into one and the text in the middle disappears. That is the same failure the
|
|
655
|
+
* whole rewrite exists to remove, reintroduced one level up. Verified with
|
|
656
|
+
* `<A title="` + backtick + `">first</A> ` + span + `\n<A title="t">second</A>`, which produced a
|
|
657
|
+
* single component whose children ran to the second closer.
|
|
658
|
+
*
|
|
659
|
+
* `</Name` never matches `<Name`, so only real openers are found; the letter check after the name
|
|
660
|
+
* stops `<GalleryFoo` counting as a `<Gallery` opener.
|
|
661
|
+
*/
|
|
662
|
+
const hasSiblingOpenerBefore = (limit) => {
|
|
663
|
+
const openNeedle = `<${name}`;
|
|
664
|
+
let k = source.indexOf(openNeedle, from);
|
|
665
|
+
while (k !== -1 && k < limit) {
|
|
666
|
+
const after = source[k + openNeedle.length];
|
|
667
|
+
if (after === undefined || !/[a-zA-Z]/.test(after))
|
|
668
|
+
return true;
|
|
669
|
+
k = source.indexOf(openNeedle, k + 1);
|
|
670
|
+
}
|
|
671
|
+
return false;
|
|
672
|
+
};
|
|
673
|
+
let i = from;
|
|
674
|
+
while (i < source.length) {
|
|
675
|
+
const at = source.indexOf(needle, i);
|
|
676
|
+
if (at === -1)
|
|
677
|
+
break;
|
|
678
|
+
let j = at + needle.length;
|
|
679
|
+
while (j < source.length && /\s/.test(source[j]))
|
|
680
|
+
j++;
|
|
681
|
+
if (source[j] === '>') {
|
|
682
|
+
const hit = { start: at, end: j + 1 };
|
|
683
|
+
// Prefer an unmasked closer, but never one that belongs to a later sibling.
|
|
684
|
+
if (mask[at] === CODE_NONE && !hasSiblingOpenerBefore(at))
|
|
685
|
+
return hit;
|
|
686
|
+
if (!firstAny) {
|
|
687
|
+
firstAny = hit;
|
|
688
|
+
if (skipUnmaskedSearch)
|
|
689
|
+
return firstAny;
|
|
690
|
+
}
|
|
691
|
+
}
|
|
692
|
+
i = at + needle.length;
|
|
693
|
+
}
|
|
694
|
+
// Ran the whole tail without an unmasked closer: record it so sibling openers skip that scan.
|
|
695
|
+
if (firstAny)
|
|
696
|
+
noUnmaskedClosers?.add(name);
|
|
697
|
+
return firstAny;
|
|
698
|
+
}
|
|
699
|
+
/**
|
|
700
|
+
* THE canonical MDX split — single-pass, code-aware, brace/quote-aware, offset-bearing.
|
|
701
|
+
* `extractMdxComponents` is a thin adapter over it; every other surface should be expressed in
|
|
702
|
+
* terms of it rather than re-walking `MDX_COMPONENT_PATTERN` (several sites did, and therefore
|
|
703
|
+
* carried both bugs independently).
|
|
704
|
+
*
|
|
705
|
+
* Structure is LOCATED on the code mask; every string is SLICED from the ORIGINAL. That split is
|
|
706
|
+
* the whole safety property: masking decides what IS a component, never what a component CONTAINS.
|
|
707
|
+
*
|
|
708
|
+
* Offsets are relative to the string PASSED IN. A caller that scanned a frontmatter-stripped body
|
|
709
|
+
* and needs file coordinates must add `computeBodyOffset(originalContent)`.
|
|
710
|
+
*
|
|
711
|
+
* Nested components are handled by consumers re-scanning `children` (see `checkPin`), so the mask
|
|
712
|
+
* is re-derived per level rather than inherited — a fence inside a component's children must still
|
|
713
|
+
* be a fence when that child text is scanned on its own.
|
|
714
|
+
*/
|
|
715
|
+
export function scanMdxNodes(content) {
|
|
716
|
+
if (!content)
|
|
717
|
+
return [];
|
|
202
718
|
if (!HAS_MDX_RE.test(content)) {
|
|
203
|
-
return [{ type: 'html', content }];
|
|
719
|
+
return [{ type: 'html', content, start: 0, end: content.length }];
|
|
204
720
|
}
|
|
205
|
-
const
|
|
206
|
-
const
|
|
721
|
+
const mask = computeCodeMask(content);
|
|
722
|
+
const nodes = [];
|
|
723
|
+
/** Performance memo for `findClosingTag`; scoped to this one walk. */
|
|
724
|
+
const noUnmaskedClosers = new Set();
|
|
207
725
|
let lastIndex = 0;
|
|
208
|
-
let
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
726
|
+
let i = 0;
|
|
727
|
+
let foundComponent = false;
|
|
728
|
+
while (i < content.length) {
|
|
729
|
+
const lt = content.indexOf('<', i);
|
|
730
|
+
if (lt === -1)
|
|
731
|
+
break;
|
|
732
|
+
// A component mentioned inside code is documentation, not markup.
|
|
733
|
+
if (mask[lt] !== CODE_NONE) {
|
|
734
|
+
i = lt + 1;
|
|
735
|
+
continue;
|
|
736
|
+
}
|
|
737
|
+
// Parsed from the ORIGINAL — the mask only decided that a tag MAY start here.
|
|
738
|
+
const tag = scanOpenTag(content, lt);
|
|
739
|
+
if (!tag) {
|
|
740
|
+
i = lt + 1;
|
|
741
|
+
continue;
|
|
742
|
+
}
|
|
743
|
+
// The tag's own terminator landed inside a FENCED block → it straddles block structure and is
|
|
744
|
+
// malformed. Fence-only on purpose: an inline span must never veto a boundary, or a stray
|
|
745
|
+
// backtick in a prop value would drop a component that renders correctly today.
|
|
746
|
+
if (mask[tag.tagEnd - 1] === CODE_FENCE) {
|
|
747
|
+
i = lt + 1;
|
|
748
|
+
continue;
|
|
749
|
+
}
|
|
750
|
+
let end;
|
|
751
|
+
let children;
|
|
752
|
+
if (tag.selfClosing) {
|
|
753
|
+
end = tag.tagEnd;
|
|
754
|
+
}
|
|
755
|
+
else {
|
|
756
|
+
const closer = findClosingTag(content, tag.name, tag.tagEnd, mask, noUnmaskedClosers);
|
|
757
|
+
if (!closer) {
|
|
758
|
+
// An opener with no closer anywhere is literal text — overwhelmingly a prose or
|
|
759
|
+
// inline-code mention like `<Gallery>`, which is exactly what must NOT anchor a match.
|
|
760
|
+
// Resume past the opener, not at lt+1: its body is known to contain no bare '<' at depth
|
|
761
|
+
// 0, and skipping it prevents a `<Gallery />` written inside a QUOTED prop value from
|
|
762
|
+
// being extracted as a component.
|
|
763
|
+
i = tag.tagEnd;
|
|
764
|
+
continue;
|
|
214
765
|
}
|
|
766
|
+
children = content.slice(tag.tagEnd, closer.start).trim();
|
|
767
|
+
end = closer.end;
|
|
215
768
|
}
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
769
|
+
if (lt > lastIndex) {
|
|
770
|
+
const raw = content.slice(lastIndex, lt);
|
|
771
|
+
if (raw.trim())
|
|
772
|
+
nodes.push({ type: 'html', content: raw, start: lastIndex, end: lt });
|
|
773
|
+
}
|
|
774
|
+
nodes.push({
|
|
220
775
|
type: 'component',
|
|
221
|
-
name,
|
|
222
|
-
|
|
223
|
-
|
|
776
|
+
name: tag.name,
|
|
777
|
+
propsSource: tag.propsSource,
|
|
778
|
+
props: parseJsxProps(tag.propsSource),
|
|
779
|
+
children,
|
|
780
|
+
start: lt,
|
|
781
|
+
end,
|
|
224
782
|
});
|
|
225
|
-
|
|
783
|
+
foundComponent = true;
|
|
784
|
+
lastIndex = end;
|
|
785
|
+
i = end;
|
|
226
786
|
}
|
|
227
787
|
if (lastIndex < content.length) {
|
|
228
|
-
const
|
|
229
|
-
if (
|
|
230
|
-
|
|
231
|
-
|
|
788
|
+
const raw = content.slice(lastIndex);
|
|
789
|
+
if (raw.trim())
|
|
790
|
+
nodes.push({ type: 'html', content: raw, start: lastIndex, end: content.length });
|
|
791
|
+
}
|
|
792
|
+
// HAS_MDX_RE matched but nothing well-formed survived (e.g. every occurrence is in code).
|
|
793
|
+
// Collapsing to one html node is what lets every renderer take its existing pure-markdown
|
|
794
|
+
// fallback instead of rendering an empty slot.
|
|
795
|
+
if (!foundComponent) {
|
|
796
|
+
return content.trim() ? [{ type: 'html', content, start: 0, end: content.length }] : [];
|
|
797
|
+
}
|
|
798
|
+
return nodes;
|
|
799
|
+
}
|
|
800
|
+
/**
|
|
801
|
+
* Extract MDX components from content, splitting into html chunks and component definitions.
|
|
802
|
+
* Does NOT process markdown → HTML (caller handles that).
|
|
803
|
+
*
|
|
804
|
+
* Thin adapter over `scanMdxNodes`; the offsets are dropped here ON PURPOSE. `ParsedContent` is a
|
|
805
|
+
* PUBLISHED type (headless tenants render off it) and existing specs pin its exact shape with a
|
|
806
|
+
* strict `toEqual`, encoding the html / `children: undefined` / `children: ''` tri-state. Adding
|
|
807
|
+
* offsets would break those specs and force every renderer to handle a field it does not use.
|
|
808
|
+
* Callers that need offsets (validation, render-embed, the review app) call `scanMdxNodes`.
|
|
809
|
+
*
|
|
810
|
+
* @param content - MDX content (frontmatter should already be stripped)
|
|
811
|
+
* @returns Array of parsed content items
|
|
812
|
+
*/
|
|
813
|
+
export function extractMdxComponents(content) {
|
|
814
|
+
if (!HAS_MDX_RE.test(content)) {
|
|
815
|
+
return [{ type: 'html', content }];
|
|
232
816
|
}
|
|
233
|
-
|
|
817
|
+
const items = scanMdxNodes(content).map(node => node.type === 'html'
|
|
818
|
+
? { type: 'html', content: node.content }
|
|
819
|
+
: { type: 'component', name: node.name, props: node.props, children: node.children });
|
|
820
|
+
// Fallback: nothing well-formed survived the scan.
|
|
234
821
|
if (items.length === 0 && content.trim()) {
|
|
235
822
|
return [{ type: 'html', content }];
|
|
236
823
|
}
|