Skip to content

Commit 946eea7

Browse files
TMHSDigitalclaude
andcommitted
One Markdown link reader for validate and the renderer (#254)
markdown.mjs exports markdownLinks(): LINK_RE's balanced-paren href rule plus titles, <href> and empty labels, outside code. checkMarkdownLinks reads links through it (and decodeURIs the path as the build does), so [a](docs/a_(b).md) is checked as the file the build links. The renderer now throws on the forms it cannot draw instead of printing them as text. Closes #254 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01LpkeXQPaUhxjgqdqnk6BrJ
1 parent f413cd0 commit 946eea7

3 files changed

Lines changed: 60 additions & 8 deletions

File tree

‎site/checks.mjs‎

Lines changed: 10 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@ import path from "node:path";
1010
import { ID_RE } from "./lib/entry-files.mjs";
1111
import { evidenceSection } from "./lib/frontmatter.mjs";
1212
import { caseMismatch } from "./lib/links.mjs";
13+
import { markdownLinks } from "./lib/markdown.mjs";
1314
import { ENGINE_LOCK_NOTES, isRealDate, MAINTENANCE_NOTES, PERSPECTIVES, STATUS_NOTES } from "./lib/shared.mjs";
1415
import { headingSlug } from "./lib/guide-render.mjs";
1516
import { isAttributionLicence, isPrivateHost, PREVIEW_LICENSES, previewEligibility, safeImageUrl } from "./lib/thumbs.mjs";
@@ -1184,8 +1185,6 @@ export function checkEntryCount(count, expected) {
11841185
: [`entry count ${count} !== ${expected} (update expectedEntryCount in site/config.json when adding or removing entries)`];
11851186
}
11861187

1187-
const MD_LINK_RE = /!\[[^\]]*\]\(([^)]+)\)|\[[^\]]*\]\(([^)]+)\)/g;
1188-
11891188
/**
11901189
* Relative links in one Markdown file: each must reach a file (in the same
11911190
* case as on disk; CI is case-sensitive), and a #fragment into a Markdown
@@ -1197,11 +1196,9 @@ export function checkMarkdownLinks(file, text, { root, realRoot, target, anchors
11971196
const errors = [];
11981197
const rel = relOf(file);
11991198
const dir = path.dirname(file);
1200-
for (const m of String(text).matchAll(MD_LINK_RE)) {
1201-
let raw = (m[1] || m[2] || "").trim();
1202-
if (!raw) continue;
1203-
if (raw.startsWith("<") && raw.endsWith(">")) raw = raw.slice(1, -1);
1204-
const href = raw.split(/\s+/)[0];
1199+
// The renderer's own reading of links (#254): balanced parens, titles and
1200+
// <href> are read the same way in both places.
1201+
for (const { href } of markdownLinks(text)) {
12051202
if (!href) continue;
12061203
if (external.test(href)) continue;
12071204
const scheme = href.match(anyScheme);
@@ -1210,7 +1207,12 @@ export function checkMarkdownLinks(file, text, { root, realRoot, target, anchors
12101207
continue;
12111208
}
12121209
const hash = href.indexOf("#");
1213-
const filePart = hash === -1 ? href : href.slice(0, hash);
1210+
let filePart = hash === -1 ? href : href.slice(0, hash);
1211+
try {
1212+
filePart = decodeURI(filePart); // as the build's resolver reads it: %20 is a space
1213+
} catch {
1214+
// A malformed escape stays as written and fails the lookup below.
1215+
}
12141216
const fragment = hash === -1 ? "" : href.slice(hash + 1);
12151217
const resolved = filePart ? path.resolve(dir, filePart) : file;
12161218
const onDisk = target(resolved);

‎site/lib/lib.test.mjs‎

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2036,6 +2036,25 @@ eq("search: q from the URL is capped", readState(`?q=${"a".repeat(5000)}`, { q:
20362036
eq("lint: dist is not", listed.some((f) => f.startsWith("dist/")), false);
20372037
}
20382038

2039+
/* one link reader for validate and the renderer (#254) --------------------- */
2040+
{
2041+
const { markdownLinks, MarkdownError } = await import("./markdown.mjs");
2042+
const hrefs = (t) => [...markdownLinks(t)].map((l) => `${l.href}${l.plain ? "" : "!"}`).join();
2043+
eq("links: balanced parens read whole", hrefs("[a](docs/a_(b).md)"), "docs/a_(b).md");
2044+
eq("links: a title is not part of the href", hrefs('[a](x.md "t")'), "x.md!");
2045+
eq("links: angle brackets are stripped", hrefs("[a](<x y.md>)"), "x y.md!");
2046+
eq("links: an empty label is still a link", hrefs("[](x.md)"), "x.md!");
2047+
eq("links: images are read too", hrefs("![i](p.png)"), "p.png!");
2048+
eq("links: code spans and fences are skipped", hrefs("`[a](x.md)`\n```\n[b](y.md)\n```\n[c](z.md)"), "z.md");
2049+
const r = (t) => renderInline(t, (href) => ({ href }));
2050+
has("links: renderer and reader agree on balanced parens", r("[a](docs/a_(b).md)"), 'href="docs/a_(b).md"');
2051+
for (const bad of ['[a](x.md "t")', "[a](<x y.md>)", "[](x.md)"]) {
2052+
let threw = false;
2053+
try { r(bad); } catch (e) { threw = e instanceof MarkdownError; }
2054+
eq(`links: the renderer rejects ${bad}`, threw, true);
2055+
}
2056+
}
2057+
20392058
/* report (keep last) ------------------------------------------------------ */
20402059
if (failures.length) {
20412060
console.error(`lib.test failed (${failures.length}):`);

‎site/lib/markdown.mjs‎

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,32 @@ const count = (str, sub) => str.split(sub).length - 1;
1919
*/
2020
export const LINK_RE = /\[([^\]]+)\]\(((?:[^()\s]|\([^()\s]*\))+)\)/g;
2121

22+
/**
23+
* Any inline link or image as GitHub reads it: LINK_RE's href rule plus an
24+
* optional title, an <angle-bracketed> href and an empty label. The renderer
25+
* draws only the LINK_RE subset and rejects the rest (#254).
26+
*/
27+
const ANY_LINK_RE = /(!?)\[([^\]]*)\]\(\s*(<[^<>\n]*>|(?:[^()\s]|\([^()\s]*\))*)(?:\s+(?:"[^"\n]*"|'[^'\n]*'))?\s*\)/g;
28+
29+
/**
30+
* Every inline link and image in a Markdown text, outside fenced code blocks
31+
* and code spans: `{ href, label, image, plain }`. `plain` is true when the
32+
* site's renderer draws it as a link. validate (checkMarkdownLinks) reads
33+
* links through this, so it checks the same href the build resolves.
34+
*/
35+
export function* markdownLinks(text) {
36+
const prose = String(text)
37+
.replace(/^(`{3,}|~{3,})[^\n]*\n[\s\S]*?^\1[^\n]*$/gm, "")
38+
.replace(/`[^`\n]+`/g, "");
39+
for (const m of prose.matchAll(ANY_LINK_RE)) {
40+
const angled = m[3].startsWith("<");
41+
const href = angled ? m[3].slice(1, -1).trim() : m[3];
42+
const image = m[1] === "!";
43+
const plain = !image && m[2].length > 0 && !angled && m[0] === `[${m[2]}](${m[3]})`;
44+
yield { href, label: m[2], image, plain };
45+
}
46+
}
47+
2248
/**
2349
* Bold and italic on already-escaped text. Italic that would cross a bold
2450
* boundary (`**a *b** c*`) stays literal: wrapping it would nest the tags
@@ -70,6 +96,11 @@ export function renderInline(text, resolveLink) {
7096
const text = entryName && label.trim() === entryId ? esc(entryName) : marks(esc(label));
7197
return keep(`<a href="${esc(out)}"${rel}>${text}</a>`);
7298
});
99+
// Link syntax LINK_RE did not draw (a title, <href>, empty label) would
100+
// reach the page as literal text; fail instead (#254).
101+
for (const link of markdownLinks(s)) {
102+
if (!link.image) throw new MarkdownError(`unsupported link form for "${link.href}": write [label](path), without a title or angle brackets`);
103+
}
73104
// Autolinks in angle brackets.
74105
s = s.replace(/<(https?:\/\/[^\s<>]+)>/g, (_, url) => keep(`<a href="${esc(url)}" rel="noopener noreferrer">${esc(url)}</a>`));
75106
// Bare URLs, leaving trailing sentence punctuation outside the link. A URL

0 commit comments

Comments
 (0)