markdown-parity-check 0.1.1

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.
@@ -0,0 +1,315 @@
1
+ // HTML main-content extraction into the shared block model. Uses htmlparser2 (parsing) and css-select
2
+ // (selectors). No JavaScript is executed; dynamic pages are compared as served.
3
+ import { parseDocument } from 'htmlparser2';
4
+ import { selectAll, selectOne } from 'css-select';
5
+ import { Element, Text } from 'domhandler';
6
+ import { textContent } from 'domutils';
7
+ import { extractNumbers, looseNormalize, normalizeCode, resolveHref, strictNormalize } from './normalize.js';
8
+ export class HtmlExtractError extends Error {
9
+ }
10
+ const SKIP_TAGS = new Set(['script', 'style', 'noscript', 'template', 'nav', 'iframe', 'svg', 'canvas', 'object', 'embed', 'map', 'form', 'button', 'input', 'select', 'textarea', 'dialog']);
11
+ const SKIP_ROLES = new Set(['navigation', 'banner', 'contentinfo', 'complementary', 'search', 'menu', 'menubar', 'dialog']);
12
+ const BLOCK_TAGS = new Set(['address', 'article', 'aside', 'blockquote', 'details', 'summary', 'dd', 'dl', 'dt', 'div', 'fieldset', 'figcaption', 'figure', 'footer', 'header', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'hgroup', 'hr', 'li', 'main', 'ol', 'p', 'pre', 'section', 'table', 'ul', 'body', 'html', 'center', 'tr', 'td', 'th', 'thead', 'tbody', 'tfoot', 'caption']);
13
+ const HEADING_RE = /^h([1-6])$/;
14
+ function lineOf(ctx, node) {
15
+ const idx = node.startIndex;
16
+ if (idx === null || idx === undefined || idx < 0)
17
+ return undefined;
18
+ // Binary search over line start offsets.
19
+ let lo = 0;
20
+ let hi = ctx.lineStarts.length - 1;
21
+ while (lo < hi) {
22
+ const mid = (lo + hi + 1) >> 1;
23
+ if ((ctx.lineStarts[mid] ?? 0) <= idx)
24
+ lo = mid;
25
+ else
26
+ hi = mid - 1;
27
+ }
28
+ return lo + 1;
29
+ }
30
+ function pathOf(ctx, el) {
31
+ const parts = [];
32
+ let cur = el;
33
+ while (cur) {
34
+ let index = 1;
35
+ let sib = cur.prev;
36
+ while (sib) {
37
+ if (sib instanceof Element && sib.name === cur.name)
38
+ index++;
39
+ sib = sib.prev;
40
+ }
41
+ parts.unshift(index > 1 || hasLaterSameNamedSibling(cur) ? `${cur.name}:nth-of-type(${index})` : cur.name);
42
+ if (cur === ctx.root)
43
+ break;
44
+ cur = cur.parent instanceof Element ? cur.parent : null;
45
+ }
46
+ return parts.join(' > ');
47
+ }
48
+ function hasLaterSameNamedSibling(el) {
49
+ let sib = el.next;
50
+ while (sib) {
51
+ if (sib instanceof Element && sib.name === el.name)
52
+ return true;
53
+ sib = sib.next;
54
+ }
55
+ return false;
56
+ }
57
+ function isSkipped(el, root) {
58
+ if (SKIP_TAGS.has(el.name))
59
+ return true;
60
+ const role = (el.attribs['role'] ?? '').toLowerCase();
61
+ if (SKIP_ROLES.has(role))
62
+ return true;
63
+ if (el.attribs['hidden'] !== undefined || el.attribs['aria-hidden'] === 'true')
64
+ return true;
65
+ // header/footer are page chrome only when they sit directly under body (or the html root), not inside an
66
+ // article, where they usually carry metadata that belongs to the content.
67
+ if ((el.name === 'header' || el.name === 'footer') && el.parent instanceof Element && (el.parent.name === 'body' || el.parent.name === 'html')) {
68
+ return el !== root;
69
+ }
70
+ return false;
71
+ }
72
+ function newRun() {
73
+ return { text: '', links: [], firstNode: null };
74
+ }
75
+ /** Collects inline text of a node, recording links. Block-level descendants are treated as inline here. */
76
+ function inlineText(ctx, node, run) {
77
+ if (node instanceof Text) {
78
+ if (run.firstNode === null && node.data.trim() !== '')
79
+ run.firstNode = node;
80
+ run.text += node.data;
81
+ return;
82
+ }
83
+ if (!(node instanceof Element))
84
+ return;
85
+ if (isSkipped(node, ctx.root))
86
+ return;
87
+ if (run.firstNode === null)
88
+ run.firstNode = node;
89
+ if (node.name === 'br') {
90
+ run.text += ' ';
91
+ return;
92
+ }
93
+ if (node.name === 'img') {
94
+ const alt = node.attribs['alt'];
95
+ if (alt && alt.trim())
96
+ run.text += ` ${alt} `;
97
+ return;
98
+ }
99
+ if (node.name === 'a' && node.attribs['href'] !== undefined) {
100
+ const inner = newRun();
101
+ for (const child of node.children)
102
+ inlineText(ctx, child, inner);
103
+ const raw = node.attribs['href'] ?? '';
104
+ run.links.push({ text: strictNormalize(inner.text), rawHref: raw, resolved: resolveHref(raw, ctx.base) });
105
+ run.links.push(...inner.links);
106
+ run.text += inner.text;
107
+ return;
108
+ }
109
+ if (BLOCK_TAGS.has(node.name))
110
+ run.text += ' ';
111
+ for (const child of node.children)
112
+ inlineText(ctx, child, run);
113
+ if (BLOCK_TAGS.has(node.name))
114
+ run.text += ' ';
115
+ }
116
+ function pushBlock(ctx, partial, node, pathEl) {
117
+ const block = {
118
+ ...partial,
119
+ loose: looseNormalize(partial.text),
120
+ numbers: extractNumbers(partial.text),
121
+ location: { line: lineOf(ctx, node), path: pathOf(ctx, pathEl), blockIndex: ctx.blocks.length },
122
+ };
123
+ ctx.blocks.push(block);
124
+ }
125
+ function flushRun(ctx, run, container, type = 'paragraph') {
126
+ const text = strictNormalize(run.text);
127
+ if (text === '')
128
+ return;
129
+ const node = run.firstNode ?? container;
130
+ pushBlock(ctx, { type, text, links: run.links }, node, container);
131
+ }
132
+ function hasBlockChild(el) {
133
+ return el.children.some((c) => c instanceof Element && BLOCK_TAGS.has(c.name) && !SKIP_TAGS.has(c.name));
134
+ }
135
+ function walk(ctx, el) {
136
+ // A container: inline runs between block children become paragraphs; block children recurse.
137
+ let run = newRun();
138
+ for (const child of el.children) {
139
+ if (child instanceof Element && isSkipped(child, ctx.root))
140
+ continue;
141
+ if (child instanceof Element && BLOCK_TAGS.has(child.name)) {
142
+ flushRun(ctx, run, el);
143
+ run = newRun();
144
+ handleBlock(ctx, child);
145
+ }
146
+ else {
147
+ inlineText(ctx, child, run);
148
+ }
149
+ }
150
+ flushRun(ctx, run, el);
151
+ }
152
+ function handleBlock(ctx, el) {
153
+ const m = HEADING_RE.exec(el.name);
154
+ if (m) {
155
+ const run = newRun();
156
+ for (const c of el.children)
157
+ inlineText(ctx, c, run);
158
+ const text = strictNormalize(run.text);
159
+ if (text !== '')
160
+ pushBlock(ctx, { type: 'heading', text, depth: Number(m[1]), links: run.links }, el, el);
161
+ return;
162
+ }
163
+ if (el.name === 'p' || el.name === 'dt' || el.name === 'dd' || el.name === 'figcaption' || el.name === 'summary' || el.name === 'caption' || el.name === 'address') {
164
+ if (hasBlockChild(el)) {
165
+ walk(ctx, el);
166
+ return;
167
+ }
168
+ const run = newRun();
169
+ for (const c of el.children)
170
+ inlineText(ctx, c, run);
171
+ flushRun(ctx, run, el);
172
+ return;
173
+ }
174
+ if (el.name === 'pre') {
175
+ const code = normalizeCode(textContent(el));
176
+ if (code.trim() !== '')
177
+ pushBlock(ctx, { type: 'code', text: strictNormalize(code), code, links: [] }, el, el);
178
+ return;
179
+ }
180
+ if (el.name === 'table') {
181
+ handleTable(ctx, el);
182
+ return;
183
+ }
184
+ if (el.name === 'ul' || el.name === 'ol') {
185
+ for (const c of el.children) {
186
+ if (c instanceof Element && c.name === 'li')
187
+ handleListItem(ctx, c);
188
+ else if (c instanceof Element && (c.name === 'ul' || c.name === 'ol'))
189
+ handleBlock(ctx, c);
190
+ }
191
+ return;
192
+ }
193
+ if (el.name === 'li') {
194
+ handleListItem(ctx, el);
195
+ return;
196
+ }
197
+ if (el.name === 'hr')
198
+ return;
199
+ // Generic container (div, section, article, blockquote, figure, details, header, footer, ...).
200
+ walk(ctx, el);
201
+ }
202
+ function handleListItem(ctx, li) {
203
+ // The item's own inline text (and inline text of a leading <p>) becomes one listItem block; nested lists
204
+ // and other block children recurse.
205
+ let run = newRun();
206
+ let ownFlushed = false;
207
+ for (const child of li.children) {
208
+ if (child instanceof Element && isSkipped(child, ctx.root))
209
+ continue;
210
+ if (child instanceof Element && BLOCK_TAGS.has(child.name)) {
211
+ if (!ownFlushed && child.name === 'p' && !hasBlockChild(child) && strictNormalize(run.text) === '') {
212
+ for (const c of child.children)
213
+ inlineText(ctx, c, run);
214
+ if (run.firstNode === null)
215
+ run.firstNode = child;
216
+ continue;
217
+ }
218
+ if (!ownFlushed) {
219
+ flushRun(ctx, run, li, 'listItem');
220
+ ownFlushed = true;
221
+ run = newRun();
222
+ }
223
+ else {
224
+ flushRun(ctx, run, li, 'paragraph');
225
+ run = newRun();
226
+ }
227
+ handleBlock(ctx, child);
228
+ }
229
+ else {
230
+ inlineText(ctx, child, run);
231
+ }
232
+ }
233
+ flushRun(ctx, run, li, ownFlushed ? 'paragraph' : 'listItem');
234
+ }
235
+ function handleTable(ctx, table) {
236
+ const rows = selectAll('tr', table).filter((tr) => closestTable(tr) === table);
237
+ const cells = [];
238
+ const links = [];
239
+ for (const tr of rows) {
240
+ const row = [];
241
+ for (const cell of tr.children) {
242
+ if (cell instanceof Element && (cell.name === 'td' || cell.name === 'th')) {
243
+ const run = newRun();
244
+ for (const c of cell.children)
245
+ inlineText(ctx, c, run);
246
+ row.push(strictNormalize(run.text));
247
+ links.push(...run.links);
248
+ }
249
+ }
250
+ if (row.length > 0)
251
+ cells.push(row);
252
+ }
253
+ if (cells.length === 0)
254
+ return;
255
+ const text = cells.map((r) => r.join(' | ')).join(' \n ');
256
+ pushBlock(ctx, { type: 'table', text: strictNormalize(text), cells, links }, table, table);
257
+ }
258
+ function closestTable(el) {
259
+ let cur = el.parent;
260
+ while (cur) {
261
+ if (cur instanceof Element && cur.name === 'table')
262
+ return cur;
263
+ cur = cur.parent;
264
+ }
265
+ return null;
266
+ }
267
+ function pickRoot(doc, selector, notes) {
268
+ if (selector) {
269
+ let matches;
270
+ try {
271
+ matches = selectAll(selector, doc.children).filter((n) => n instanceof Element);
272
+ }
273
+ catch (err) {
274
+ throw new HtmlExtractError(`Invalid selector "${selector}": ${err.message}`);
275
+ }
276
+ if (matches.length === 0)
277
+ throw new HtmlExtractError(`Selector "${selector}" matched no element.`);
278
+ if (matches.length > 1)
279
+ notes.push(`Selector "${selector}" matched ${matches.length} elements; the first in document order was used.`);
280
+ return { root: matches[0], strategy: `selector:${selector}`, confidence: 'high' };
281
+ }
282
+ for (const tag of ['main', 'article', '[role=main]']) {
283
+ const matches = selectAll(tag, doc.children).filter((n) => n instanceof Element);
284
+ if (matches.length >= 1) {
285
+ if (matches.length > 1)
286
+ notes.push(`${matches.length} <${tag}> elements found; the first in document order was used.`);
287
+ return { root: matches[0], strategy: tag, confidence: 'high' };
288
+ }
289
+ }
290
+ const body = selectOne('body', doc.children);
291
+ if (body instanceof Element) {
292
+ notes.push('No <main>, <article> or [role=main] element; fell back to <body> with lower extraction confidence.');
293
+ return { root: body, strategy: 'body-fallback', confidence: 'low' };
294
+ }
295
+ throw new HtmlExtractError('Document has no <body> element.');
296
+ }
297
+ export function extractHtml(source, options = {}) {
298
+ const doc = parseDocument(source, { withStartIndices: true, withEndIndices: true, decodeEntities: true });
299
+ const notes = [];
300
+ const baseEl = selectOne('base[href]', doc.children);
301
+ let base = options.baseUrl ?? null;
302
+ if (baseEl instanceof Element && baseEl.attribs['href']) {
303
+ const resolved = resolveHref(baseEl.attribs['href'], base);
304
+ if (resolved)
305
+ base = resolved;
306
+ }
307
+ const { root, strategy, confidence } = pickRoot(doc, options.selector, notes);
308
+ const lineStarts = [0];
309
+ for (let i = 0; i < source.length; i++)
310
+ if (source.charCodeAt(i) === 10)
311
+ lineStarts.push(i + 1);
312
+ const ctx = { base, source, lineStarts, blocks: [], notes, root };
313
+ walk(ctx, root);
314
+ return { blocks: ctx.blocks, strategy, confidence, notes, issues: [] };
315
+ }
@@ -0,0 +1,320 @@
1
+ // Markdown extraction into the shared block model, using mdast-util-from-markdown with GFM extensions.
2
+ import { fromMarkdown } from 'mdast-util-from-markdown';
3
+ import { gfm } from 'micromark-extension-gfm';
4
+ import { gfmFromMarkdown } from 'mdast-util-gfm';
5
+ import { extractHtml } from './html.js';
6
+ import { parseDocument } from 'htmlparser2';
7
+ import { Element } from 'domhandler';
8
+ import { excerpt, extractNumbers, looseNormalize, normalizeCode, resolveHref, strictNormalize } from './normalize.js';
9
+ /** Parses one inline HTML node (a single tag, per micromark) with htmlparser2. Returns null for comments,
10
+ * processing instructions or anything that is not exactly one tag. */
11
+ function parseInlineTag(value) {
12
+ const v = value.trim();
13
+ const closing = /^<\/[A-Za-z]/.test(v);
14
+ if (closing) {
15
+ const m = /^<\/([A-Za-z][A-Za-z0-9-]*)\s*>$/.exec(v);
16
+ return m ? { name: m[1].toLowerCase(), closing: true, attribs: {} } : null;
17
+ }
18
+ if (!/^<[A-Za-z][^>]*>$/.test(v))
19
+ return null;
20
+ const doc = parseDocument(v, { decodeEntities: true });
21
+ const el = doc.children.find((c) => c instanceof Element);
22
+ if (!el)
23
+ return null;
24
+ return { name: el.name.toLowerCase(), closing: false, attribs: el.attribs };
25
+ }
26
+ /**
27
+ * Walks phrasing children in order so that inline HTML anchors (<a href="..">text</a>) become links with
28
+ * their Markdown child text. Other inline tags are structure, not content: <img> contributes its alt
29
+ * text, <br> a space, everything else is dropped while the text between tags stays.
30
+ */
31
+ function inlineChildren(ctx, children, run, line) {
32
+ for (let i = 0; i < children.length; i++) {
33
+ const node = children[i];
34
+ if (node.type !== 'html') {
35
+ inline(ctx, node, run);
36
+ continue;
37
+ }
38
+ const tag = parseInlineTag(node.value);
39
+ if (!tag)
40
+ continue; // comment or unparsable fragment: no visible content
41
+ if (tag.closing) {
42
+ if (tag.name === 'a')
43
+ ctx.issues.push({ code: 'MARKDOWN_INLINE_HTML_UNSUPPORTED', severity: 'warning', message: 'A closing </a> without an opening <a> in the same paragraph; the inline HTML structure could not be resolved reliably.', line: node.position?.start.line ?? line, excerpt: excerpt(node.value) });
44
+ continue;
45
+ }
46
+ if (tag.name === 'img') {
47
+ const alt = tag.attribs['alt'];
48
+ if (alt && alt.trim())
49
+ run.text += ` ${alt} `;
50
+ continue;
51
+ }
52
+ if (tag.name === 'br') {
53
+ run.text += ' ';
54
+ continue;
55
+ }
56
+ if (tag.name !== 'a')
57
+ continue; // span, em, strong, sup, ...: the text is in sibling nodes
58
+ // Find the matching </a> among the following siblings.
59
+ let end = -1;
60
+ for (let j = i + 1; j < children.length; j++) {
61
+ const c = children[j];
62
+ if (c.type === 'html') {
63
+ const t = parseInlineTag(c.value);
64
+ if (t && t.name === 'a') {
65
+ if (t.closing) {
66
+ end = j;
67
+ break;
68
+ }
69
+ break; // nested <a>: unsupported
70
+ }
71
+ }
72
+ }
73
+ if (end < 0) {
74
+ ctx.issues.push({ code: 'MARKDOWN_INLINE_HTML_UNSUPPORTED', severity: 'warning', message: 'An inline <a> tag has no matching </a> in the same paragraph (or anchors are nested); its link was not compared.', line: node.position?.start.line ?? line, excerpt: excerpt(node.value) });
75
+ continue;
76
+ }
77
+ const inner = { text: '', links: [] };
78
+ inlineChildren(ctx, children.slice(i + 1, end), inner, line);
79
+ const href = tag.attribs['href'];
80
+ if (href !== undefined)
81
+ run.links.push({ text: strictNormalize(inner.text), rawHref: href, resolved: resolveHref(href, ctx.base) });
82
+ run.links.push(...inner.links);
83
+ run.text += inner.text;
84
+ i = end;
85
+ }
86
+ }
87
+ function inline(ctx, node, run) {
88
+ switch (node.type) {
89
+ case 'text':
90
+ run.text += node.value;
91
+ return;
92
+ case 'inlineCode':
93
+ run.text += node.value;
94
+ return;
95
+ case 'break':
96
+ run.text += ' ';
97
+ return;
98
+ case 'image':
99
+ if (node.alt && node.alt.trim())
100
+ run.text += ` ${node.alt} `;
101
+ return;
102
+ case 'imageReference':
103
+ if (node.alt && node.alt.trim())
104
+ run.text += ` ${node.alt} `;
105
+ return;
106
+ case 'html':
107
+ // Inline raw HTML is a tag, not content: the text around it is in sibling text nodes.
108
+ return;
109
+ case 'linkReference': {
110
+ const inner = { text: '', links: [] };
111
+ inlineChildren(ctx, node.children, inner, node.position?.start.line);
112
+ const def = ctx.definitions.get(node.identifier);
113
+ if (def) {
114
+ run.links.push({ text: strictNormalize(inner.text), rawHref: def.url, resolved: resolveHref(def.url, ctx.base) });
115
+ run.links.push(...inner.links);
116
+ run.text += inner.text;
117
+ }
118
+ else {
119
+ // Unreachable with micromark, which only emits a reference that has a definition; kept as a safe
120
+ // fallback that treats an unresolved reference as literal text.
121
+ run.text += `[${inner.text}]`;
122
+ run.links.push(...inner.links);
123
+ }
124
+ return;
125
+ }
126
+ case 'link': {
127
+ const inner = { text: '', links: [] };
128
+ inlineChildren(ctx, node.children, inner, node.position?.start.line);
129
+ run.links.push({ text: strictNormalize(inner.text), rawHref: node.url, resolved: resolveHref(node.url, ctx.base) });
130
+ run.links.push(...inner.links);
131
+ run.text += inner.text;
132
+ return;
133
+ }
134
+ case 'footnoteReference':
135
+ return;
136
+ default:
137
+ if ('children' in node) {
138
+ inlineChildren(ctx, node.children, run, node.position?.start.line);
139
+ }
140
+ else if ('value' in node && typeof node.value === 'string') {
141
+ run.text += node.value;
142
+ }
143
+ }
144
+ }
145
+ function push(ctx, partial, node) {
146
+ const line = node.position?.start.line;
147
+ const block = {
148
+ ...partial,
149
+ loose: looseNormalize(partial.text),
150
+ numbers: extractNumbers(partial.text),
151
+ location: { line, blockIndex: ctx.blocks.length },
152
+ };
153
+ ctx.blocks.push(block);
154
+ }
155
+ function handleTable(ctx, table) {
156
+ const cells = [];
157
+ const links = [];
158
+ for (const row of table.children) {
159
+ const r = [];
160
+ for (const cell of row.children) {
161
+ const run = { text: '', links: [] };
162
+ inlineChildren(ctx, cell.children, run, cell.position?.start.line);
163
+ r.push(strictNormalize(run.text));
164
+ links.push(...run.links);
165
+ }
166
+ cells.push(r);
167
+ }
168
+ if (cells.length === 0)
169
+ return;
170
+ const text = cells.map((r) => r.join(' | ')).join(' \n ');
171
+ push(ctx, { type: 'table', text: strictNormalize(text), cells, links }, table);
172
+ }
173
+ function handle(ctx, node, listItem = false) {
174
+ switch (node.type) {
175
+ case 'heading': {
176
+ const run = { text: '', links: [] };
177
+ inlineChildren(ctx, node.children, run, node.position?.start.line);
178
+ const text = strictNormalize(run.text);
179
+ if (text !== '')
180
+ push(ctx, { type: 'heading', text, depth: node.depth, links: run.links }, node);
181
+ return;
182
+ }
183
+ case 'paragraph': {
184
+ const run = { text: '', links: [] };
185
+ inlineChildren(ctx, node.children, run, node.position?.start.line);
186
+ const text = strictNormalize(run.text);
187
+ if (text !== '')
188
+ push(ctx, { type: listItem ? 'listItem' : 'paragraph', text, links: run.links }, node);
189
+ return;
190
+ }
191
+ case 'code': {
192
+ const code = normalizeCode(node.value);
193
+ if (code.trim() !== '')
194
+ push(ctx, { type: 'code', text: strictNormalize(code), code, links: [] }, node);
195
+ return;
196
+ }
197
+ case 'table':
198
+ handleTable(ctx, node);
199
+ return;
200
+ case 'list':
201
+ for (const item of node.children) {
202
+ let first = true;
203
+ for (const child of item.children) {
204
+ handle(ctx, child, first && child.type === 'paragraph');
205
+ first = false;
206
+ }
207
+ if (item.children.length === 0)
208
+ continue;
209
+ }
210
+ return;
211
+ case 'blockquote':
212
+ for (const c of node.children)
213
+ handle(ctx, c);
214
+ return;
215
+ case 'html':
216
+ handleRawHtml(ctx, node.value, node.position?.start.line);
217
+ return;
218
+ case 'thematicBreak':
219
+ case 'definition':
220
+ case 'footnoteDefinition':
221
+ case 'yaml':
222
+ return;
223
+ default:
224
+ if ('children' in node)
225
+ for (const c of node.children)
226
+ handle(ctx, c);
227
+ }
228
+ }
229
+ /** A raw HTML block in Markdown is parsed with the HTML extractor so its content takes part in the
230
+ * comparison; the report shows that this happened. Comments and bare tags without text yield nothing. */
231
+ function handleRawHtml(ctx, value, line) {
232
+ const withoutComments = value.replace(/<!--[\s\S]*?-->/g, '');
233
+ // Text check for the fallback warning: script, style, template and noscript are page machinery on both
234
+ // sides, so their content does not count as skipped text.
235
+ const visibleSource = withoutComments.replace(/<(script|style|template|noscript)\b[\s\S]*?<\/\1\s*>/gi, ' ');
236
+ const textOnly = strictNormalize(visibleSource.replace(/<[^>]*>/g, ' '));
237
+ let parsed = null;
238
+ try {
239
+ parsed = extractHtml(`<body>${withoutComments}</body>`, { selector: 'body', baseUrl: ctx.base });
240
+ }
241
+ catch {
242
+ parsed = null;
243
+ }
244
+ const blocks = parsed?.blocks ?? [];
245
+ if (blocks.length > 0) {
246
+ for (const b of blocks) {
247
+ // The wrapper <body> sits on the fragment's first line, so the extractor's line is 1-based within
248
+ // the fragment and maps onto the html node's start line.
249
+ const inner = b.location.line;
250
+ const absolute = line !== undefined && inner !== undefined ? line + inner - 1 : line;
251
+ ctx.blocks.push({ ...b, location: { line: absolute, blockIndex: ctx.blocks.length } });
252
+ }
253
+ ctx.issues.push({ code: 'MARKDOWN_RAW_HTML_PARSED', severity: 'info', message: `A raw HTML block in the Markdown was parsed as HTML (${blocks.length} block(s)); Markdown readers that do not render HTML will not see it.`, line, excerpt: excerpt(textOnly) });
254
+ }
255
+ else if (textOnly !== '') {
256
+ ctx.issues.push({ code: 'MARKDOWN_RAW_HTML_SKIPPED', severity: 'warning', message: 'A raw HTML block in the Markdown carries text that could not be parsed into blocks; it was not compared.', line, excerpt: excerpt(textOnly) });
257
+ }
258
+ }
259
+ const YAML_LINE = /^(?:[A-Za-z0-9_.-]+\s*:(?:\s|$)|\s+\S|-\s|#)/;
260
+ const FENCE_RE = /^(?:\ufeff)?---[ \t]*\r?\n([\s\S]*?)\r?\n(?:---|\.\.\.)[ \t]*(?:\r?\n|$)/;
261
+ /**
262
+ * Front matter is never removed on guesswork. With 'keep' the source is parsed as written and a leading
263
+ * fenced block that looks like YAML only raises a warning (strict fails). With 'strip' the user has
264
+ * declared that the document carries front matter, so the leading fenced block is removed and reported.
265
+ */
266
+ function scanFrontMatter(source, mode) {
267
+ const m = FENCE_RE.exec(source);
268
+ if (!m)
269
+ return { text: source, skippedLines: 0, looksLikeYaml: false, body: '' };
270
+ const body = m[1] ?? '';
271
+ const nonEmpty = body.split(/\r?\n/).filter((l) => l.trim() !== '');
272
+ const looksLikeYaml = nonEmpty.length > 0 && nonEmpty.every((l) => YAML_LINE.test(l));
273
+ if (mode === 'keep')
274
+ return { text: source, skippedLines: 0, looksLikeYaml, body };
275
+ const skippedLines = m[0].split(/\r?\n/).length - (m[0].endsWith('\n') ? 1 : 0);
276
+ return { text: source.slice(m[0].length), skippedLines, looksLikeYaml, body };
277
+ }
278
+ function collectDefinitions(tree) {
279
+ const defs = new Map();
280
+ const visit = (node) => {
281
+ if (node.type === 'definition') {
282
+ if (!defs.has(node.identifier))
283
+ defs.set(node.identifier, { url: node.url, title: node.title ?? null });
284
+ return;
285
+ }
286
+ if ('children' in node)
287
+ for (const c of node.children)
288
+ visit(c);
289
+ };
290
+ visit(tree);
291
+ return defs;
292
+ }
293
+ export function extractMarkdown(source, options = {}) {
294
+ const mode = options.frontMatter ?? 'keep';
295
+ const fm = scanFrontMatter(source, mode);
296
+ const tree = fromMarkdown(fm.text, { extensions: [gfm()], mdastExtensions: [gfmFromMarkdown()] });
297
+ const ctx = { base: options.baseUrl ?? null, blocks: [], notes: [], issues: [], definitions: collectDefinitions(tree) };
298
+ const fmExcerpt = () => excerpt(fm.body.replace(/\s+/g, ' '));
299
+ if (mode === 'strip' && fm.skippedLines > 0) {
300
+ ctx.notes.push(`Front matter (${fm.skippedLines} lines) was stripped as requested (--front-matter strip).`);
301
+ ctx.issues.push({ code: 'MARKDOWN_FRONT_MATTER_STRIPPED', severity: 'info', message: `Lines 1-${fm.skippedLines} were stripped as front matter (--front-matter strip) and not compared.`, line: 1, excerpt: fmExcerpt() });
302
+ }
303
+ else if (mode === 'strip') {
304
+ ctx.notes.push('--front-matter strip was given but the document does not start with a fenced block; nothing was stripped.');
305
+ }
306
+ else if (fm.looksLikeYaml) {
307
+ ctx.issues.push({ code: 'MARKDOWN_POSSIBLE_FRONT_MATTER', severity: 'warning', message: 'The document starts with a fenced block that looks like YAML front matter. It was compared as written (nothing is removed by default); pass --front-matter strip if it is metadata.', line: 1, excerpt: fmExcerpt() });
308
+ }
309
+ for (const child of tree.children)
310
+ handle(ctx, child);
311
+ if (fm.skippedLines > 0) {
312
+ for (const b of ctx.blocks)
313
+ if (b.location.line !== undefined)
314
+ b.location.line += fm.skippedLines;
315
+ for (const i of ctx.issues)
316
+ if (i.code !== 'MARKDOWN_FRONT_MATTER_STRIPPED' && i.line !== undefined)
317
+ i.line += fm.skippedLines;
318
+ }
319
+ return { blocks: ctx.blocks, strategy: 'markdown', confidence: 'high', notes: ctx.notes, issues: ctx.issues };
320
+ }
@@ -0,0 +1,2 @@
1
+ // Shared block model used by both the HTML and Markdown extractors and by the comparison core.
2
+ export {};