Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 3 additions & 5 deletions skills/explain-diff-html/references/validation.md
Original file line number Diff line number Diff line change
Expand Up @@ -64,11 +64,9 @@ mistake fails instead of reporting on a page the script never opened.

- Every code block is HTML-escaped: `&`, `<`, and `>` inside a `<pre>` or
`<code>` block appear as `&amp;`, `&lt;`, `&gt;`, with the `.del`, `.add`,
and `.hi` spans wrapping the escaped text. Raw angle brackets are parsed as
tags and silently break the document tree and every anchor below. The script
fails on any element inside a `<pre>` or `<code>` other than those spans,
which is what a raw `<` before a letter becomes. It does not see a raw end
tag such as `</div>` or a raw `<!--`, so read the blocks for those.
and `.hi` spans wrapping the escaped text. The script fails on unexpected
elements and HTML comments inside those blocks, and unmatched raw end tags
anywhere in the page source (outside comments and `script` or `style` bodies).

- Any Mermaid source in a `<pre class="mermaid">` block is HTML-escaped the same
way. An unescaped `<br/>` vanishes from the rendered label and a bare `<`
Expand Down
62 changes: 52 additions & 10 deletions skills/explain-diff-html/scripts/validate-output.js
Original file line number Diff line number Diff line change
Expand Up @@ -10307,17 +10307,54 @@ const checks = [
},
{
id: "code-escaped",
run({ document }) {
const stray = new Set(selectAll("pre, code", document).flatMap((block) => selectAll("*", block.children).filter((node) => !is(node, "span.del, span.add, span.hi"))));
return stray.size === 0 ? {
run({ document, html }) {
const blocks = selectAll("pre, code", document);
const stray = blocks.flatMap((block) => selectAll("*", block.children).filter((node) => !is(node, "span.del, span.add, span.hi")));
const comments = blocks.flatMap((block) => filter(isComment, block.children, true));
const matchedEndTags = /* @__PURE__ */ new Set();
const ignoredRanges = [];
const elements = filter(isTag, document.children, true);
for (const element of elements) {
const location = element.sourceCodeLocation;
if (location && "startTag" in location && location.startTag) ignoredRanges.push({
start: location.startTag.startOffset,
end: location.startTag.endOffset
});
if (location && "endTag" in location && location.endTag) matchedEndTags.add(location.endTag.startOffset);
if ((element.name === "script" || element.name === "style") && location && "startTag" in location && location.startTag) {
const endOffset = "endTag" in location && location.endTag ? location.endTag.startOffset : location.endOffset;
ignoredRanges.push({
start: location.startTag.endOffset,
end: endOffset
});
}
}
for (const comment of filter(isComment, document.children, true)) {
const start = comment.startIndex ?? -1;
const end = comment.endIndex ?? start;
ignoredRanges.push({
start,
end
});
}
const rawEndTags = [...html.matchAll(/<\/\s*([a-z][a-z0-9:-]*)\b[^>]*>/gi)].filter((match) => {
const offset = match.index ?? -1;
return !matchedEndTags.has(offset) && !ignoredRanges.some(({ start, end }) => start <= offset && offset < end);
}).map(([tag]) => tag);
const findings = [
...stray.map((node) => {
return `<${[node.name, ...getAttributeValue(node, "class")?.split(" ") ?? []].filter(Boolean).join(".")}> in ${getText(node.parent)}`;
}),
...comments.map((node) => `raw HTML comment in code block: <!--${isComment(node) ? node.data : ""}-->`),
...rawEndTags.map((tag) => `unmatched raw end tag in page source: ${tag}`)
];
return findings.length === 0 ? {
isFailed: false,
message: "every code block holds only text and .del, .add, .hi spans"
message: "code blocks are escaped; no stray elements, comments, or end tags"
} : {
isFailed: true,
message: "elements inside a code block other than .del, .add, and .hi spans:",
findings: [...stray].map((node) => {
return `<${[node.name, ...getAttributeValue(node, "class")?.split(" ") ?? []].filter(Boolean).join(".")}> in ${getText(node.parent)}`;
})
message: "unexpected code-block elements/comments or unmatched page end tags:",
findings
};
}
},
Expand Down Expand Up @@ -10347,7 +10384,10 @@ const checks = [
}
];
function parsePage(html) {
return parse(html, { treeAdapter: adapter });
return parse(html, {
treeAdapter: adapter,
sourceCodeLocationInfo: true
});
}
function validate(page) {
return checks.map((check) => ({
Expand All @@ -10370,14 +10410,16 @@ function main(args) {
console.error(`FAIL: ${path} is not a non-empty file`);
return 1;
}
const document = parsePage(readFileSync(path, "utf8"));
const html = readFileSync(path, "utf8");
const document = parsePage(html);
const references = getReferences(document);
const linked = selectAll("a.srcref", document).length;
const marked = references.filter(isMarkedBare).length;
console.log(`references=${references.length} linked=${linked} marked-bare=${marked}`);
let status = 0;
for (const { result } of validate({
document,
html,
sha
})) if (result.isFailed) {
console.log(`FAIL: ${result.message}`);
Expand Down
96 changes: 76 additions & 20 deletions src/validate-output.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,8 @@

import { readFileSync, statSync } from "node:fs";
import { is, selectAll, selectOne } from "css-select";
import { isTag, isText, type AnyNode, type Document, type Element } from "domhandler";
import { getAttributeValue, textContent } from "domutils";
import { isComment, isTag, isText, type AnyNode, type Document, type Element } from "domhandler";
import { filter, getAttributeValue, textContent } from "domutils";
import { parse } from "parse5";
import { adapter } from "parse5-htmlparser2-tree-adapter";

Expand All @@ -21,6 +21,7 @@ export type Result =

export interface Page {
document: Document;
html: string;
sha: string;
}

Expand Down Expand Up @@ -262,26 +263,80 @@ export const checks: Check[] = [
},
},
{
// A raw `<` that starts a tag becomes an element inside the block, so only the
// diff and highlight spans may sit in a code block.
// parse5 drops unmatched end tags from the tree, so scan the source.
// Comments stay in the tree.
id: "code-escaped",
run({ document }) {
const stray = new Set(
selectAll<AnyNode, Element>("pre, code", document).flatMap((block) =>
selectAll<AnyNode, Element>("*", block.children).filter(
(node) => !is<AnyNode, Element>(node, "span.del, span.add, span.hi"),
),
run({ document, html }) {
const blocks = selectAll<AnyNode, Element>("pre, code", document);
const stray = blocks.flatMap((block) =>
selectAll<AnyNode, Element>("*", block.children).filter(
(node) => !is<AnyNode, Element>(node, "span.del, span.add, span.hi"),
),
);
return stray.size === 0
? { isFailed: false, message: "every code block holds only text and .del, .add, .hi spans" }
const comments = blocks.flatMap((block) => filter(isComment, block.children, true));
const matchedEndTags = new Set<number>();
const ignoredRanges: { start: number; end: number }[] = [];
const elements = filter(isTag, document.children, true) as Element[];
for (const element of elements) {
const location = element.sourceCodeLocation;
if (location && "startTag" in location && location.startTag) {
ignoredRanges.push({
start: location.startTag.startOffset,
end: location.startTag.endOffset,
});
}
if (location && "endTag" in location && location.endTag) {
matchedEndTags.add(location.endTag.startOffset);
}
if (
(element.name === "script" || element.name === "style") &&
location &&
"startTag" in location &&
location.startTag
) {
const endOffset =
"endTag" in location && location.endTag
? location.endTag.startOffset
: location.endOffset;
ignoredRanges.push({
start: location.startTag.endOffset,
end: endOffset,
});
}
}
for (const comment of filter(isComment, document.children, true)) {
const start = comment.startIndex ?? -1;
const end = comment.endIndex ?? start;
ignoredRanges.push({ start, end });
}
const rawEndTags = [...html.matchAll(/<\/\s*([a-z][a-z0-9:-]*)\b[^>]*>/gi)]
.filter((match) => {
const offset = match.index ?? -1;
return (
!matchedEndTags.has(offset) &&
!ignoredRanges.some(({ start, end }) => start <= offset && offset < end)
);
})
.map(([tag]) => tag);
const findings = [
...stray.map((node) => {
const tag = [node.name, ...(getAttributeValue(node, "class")?.split(" ") ?? [])];
return `<${tag.filter(Boolean).join(".")}> in ${getText(node.parent as Element)}`;
}),
...comments.map(
(node) => `raw HTML comment in code block: <!--${isComment(node) ? node.data : ""}-->`,
),
...rawEndTags.map((tag) => `unmatched raw end tag in page source: ${tag}`),
];
return findings.length === 0
? {
isFailed: false,
message: "code blocks are escaped; no stray elements, comments, or end tags",
}
: {
isFailed: true,
message: "elements inside a code block other than .del, .add, and .hi spans:",
findings: [...stray].map((node) => {
const tag = [node.name, ...(getAttributeValue(node, "class")?.split(" ") ?? [])];
return `<${tag.filter(Boolean).join(".")}> in ${getText(node.parent as Element)}`;
}),
message: "unexpected code-block elements/comments or unmatched page end tags:",
findings,
};
},
},
Expand Down Expand Up @@ -313,7 +368,7 @@ export const checks: Check[] = [
];

export function parsePage(html: string): Document {
return parse(html, { treeAdapter: adapter });
return parse(html, { treeAdapter: adapter, sourceCodeLocationInfo: true });
}

export function validate(page: Page): { id: string; result: Result }[] {
Expand All @@ -337,14 +392,15 @@ function main(args: string[]): number {
return 1;
}

const document = parsePage(readFileSync(path, "utf8"));
const html = readFileSync(path, "utf8");
const document = parsePage(html);
const references = getReferences(document);
const linked = selectAll<AnyNode, Element>("a.srcref", document).length;
const marked = references.filter(isMarkedBare).length;
console.log(`references=${references.length} linked=${linked} marked-bare=${marked}`);

let status = 0;
for (const { result } of validate({ document, sha })) {
for (const { result } of validate({ document, html, sha })) {
if (result.isFailed) {
console.log(`FAIL: ${result.message}`);
for (const finding of result.findings) console.log(finding);
Expand Down
11 changes: 11 additions & 0 deletions tests/validate-output/fail/code-escaped/raw-code-end-tag.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
<!doctype html>
<html lang="en">
<head><meta charset="utf-8"><title>Validator regression</title></head>
<body>
<main>
<p class="provenance">0123456789ab</p>
<p>Use <code>a </code> b</code> here.</p>
<section id="quiz">A quiz is present.</section>
</main>
</body>
</html>
11 changes: 11 additions & 0 deletions tests/validate-output/fail/code-escaped/raw-comment.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
<!doctype html>
<html lang="en">
<head><meta charset="utf-8"><title>Validator regression</title></head>
<body>
<main>
<p class="provenance">0123456789ab</p>
<pre>before <!-- raw comment --> after</pre>
<section id="quiz">A quiz is present.</section>
</main>
</body>
</html>
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
<!doctype html>
<html lang="en">
<head><meta charset="utf-8"><title>Validator regression</title></head>
<body>
<main>
<p class="provenance">0123456789ab</p>
<p>Before the comment.</p><!-- note --></div>
<section id="quiz">A quiz is present.</section>
</main>
</body>
</html>
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
<!doctype html>
<html lang="en">
<head><meta charset="utf-8"><title>Validator regression</title></head>
<body>
<main>
<p class="provenance">0123456789ab</p>
<pre>before </div class="x"> after</pre>
<section id="quiz">A quiz is present.</section>
</main>
</body>
</html>
11 changes: 11 additions & 0 deletions tests/validate-output/fail/code-escaped/raw-end-tag.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
<!doctype html>
<html lang="en">
<head><meta charset="utf-8"><title>Validator regression</title></head>
<body>
<main>
<p class="provenance">0123456789ab</p>
<pre>before </div> after</pre>
<section id="quiz">A quiz is present.</section>
</main>
</body>
</html>
11 changes: 11 additions & 0 deletions tests/validate-output/fail/code-escaped/raw-pre-script.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
<!doctype html>
<html lang="en">
<head><meta charset="utf-8"><title>Validator regression</title></head>
<body>
<main>
<p class="provenance">0123456789ab</p>
<pre>before </pre><script>window.bad = true;</script> after</pre>
<section id="quiz">A quiz is present.</section>
</main>
</body>
</html>
11 changes: 11 additions & 0 deletions tests/validate-output/fail/code-escaped/raw-span-end-tag.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
<!doctype html>
<html lang="en">
<head><meta charset="utf-8"><title>Validator regression</title></head>
<body>
<main>
<p class="provenance">0123456789ab</p>
<pre>before </span> after</pre>
<section id="quiz">A quiz is present.</section>
</main>
</body>
</html>
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
<!doctype html>
<html lang="en">
<head><meta charset="utf-8"><title>Validator regression</title></head>
<body>
<main>
<p class="provenance">0123456789ab</p>
<!-- A closing tag in a comment is not markup: </div> -->
<script>const example = "</div>";</script>
<section id="quiz">A quiz is present.</section>
</main>
</body>
</html>
10 changes: 6 additions & 4 deletions tests/validate-output/validate-output.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,8 +18,9 @@ const script = fileURLToPath(
const sha = "0123456";

function getFailedCheckIds(path: string): string[] {
const document = parsePage(readFileSync(path, "utf8"));
return validate({ document, sha })
const html = readFileSync(path, "utf8");
const document = parsePage(html);
return validate({ document, html, sha })
.filter(({ result }) => result.isFailed)
.map(({ id }) => id);
}
Expand Down Expand Up @@ -71,8 +72,9 @@ for (const checkId of checkIds) {

test("an unlinked reference is listed by its text", () => {
const path = join(failFolder, "unlinked-reference", "spare-srcref.html");
const document = parsePage(readFileSync(path, "utf8"));
const unlinked = validate({ document, sha }).find(({ id }) => id === "unlinked-reference");
const html = readFileSync(path, "utf8");
const document = parsePage(html);
const unlinked = validate({ document, html, sha }).find(({ id }) => id === "unlinked-reference");
expect(unlinked?.result.isFailed ? unlinked.result.findings : []).toEqual(["b.py:9"]);
});

Expand Down