verify-md-links.ts 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217
  1. /**
  2. * Verify that relative Markdown links, images, and definitions resolve — the
  3. * target file must exist AND a `#fragment` onto a Markdown target (including
  4. * a same-file `#anchor`) must name a real heading slug or explicit `<a id>`.
  5. * URL and root-absolute targets are excluded; query strings do not affect
  6. * resolution against the source file. The checker never rewrites, and
  7. * symlinked instruction files are deduped.
  8. */
  9. import { existsSync, readFileSync } from 'node:fs'
  10. import { dirname, relative, resolve } from 'node:path'
  11. import type { Nodes } from 'mdast'
  12. import { markdownHeadingLines, parseMarkdown, visitMarkdown } from './markdown.ts'
  13. import { isArchivedAgentNotePath, uniqueRepoFiles } from './repo-files.ts'
  14. const root = resolve(import.meta.dirname, '..')
  15. /** Repo-authored Markdown checked for relative links. */
  16. const PATTERNS = [
  17. 'README.md',
  18. 'README.zh.md',
  19. '.agents/notes/**/*.md',
  20. 'docs/**/*.md',
  21. 'packages/*/*.md',
  22. 'packages/*/*/*.md',
  23. 'examples/**/*.md',
  24. 'AGENTS.md',
  25. 'packages/AGENTS.md',
  26. '.agents/skills/**/*.md',
  27. 'skills/**/*.md',
  28. ]
  29. /** A broken relative link: a missing target path or a missing anchor on it. */
  30. interface Violation {
  31. file: string
  32. /** 1-based line where the link/image/definition node starts. */
  33. line: number
  34. url: string
  35. /** What failed: the target file or the fragment onto it. */
  36. reason: 'target' | 'anchor'
  37. }
  38. /**
  39. * True for targets this gate must NOT check: scheme-qualified URLs (`https:`,
  40. * `mailto:`, …), protocol-relative (`//host`), and root-absolute (`/path`).
  41. * Pure in-page anchors (`#frag`) ARE checked, against the source file itself.
  42. */
  43. function isExternal(url: string): boolean {
  44. if (url.startsWith('//')) return true
  45. if (url.startsWith('/')) return true
  46. // A scheme like `https:` / `mailto:` — a colon before any slash, dot, or hash.
  47. return /^[a-zA-Z][a-zA-Z0-9+.-]*:/.test(url)
  48. }
  49. /**
  50. * Strip the `#fragment` and `?query` from a link target, then percent-decode
  51. * the remaining path so an encoded target (`My%20File.md`, `READ%4DE.md`)
  52. * probes the real filename on disk, the way a Markdown renderer resolves it. A
  53. * malformed escape (`%zz`) makes `decodeURIComponent` throw; we keep the raw
  54. * path in that case so the link is reported as broken (a `%zz` target is not a
  55. * file anyone meant to link) rather than crashing the gate.
  56. */
  57. function pathPart(url: string): string {
  58. const raw = url.replace(/[#?].*$/, '')
  59. try {
  60. return decodeURIComponent(raw)
  61. } catch {
  62. // decodeURIComponent throws only on a malformed percent-escape; the raw
  63. // string is then a path no renderer resolves, so fall through to the
  64. // existence check, which reports it broken.
  65. return raw
  66. }
  67. }
  68. /** The percent-decoded `#fragment` of a link target, or null when it has none. */
  69. function fragmentPart(url: string): string | null {
  70. const hash = url.indexOf('#')
  71. if (hash === -1) return null
  72. const raw = url.slice(hash + 1).replace(/\?.*$/, '')
  73. try {
  74. return decodeURIComponent(raw)
  75. } catch {
  76. // Same stance as pathPart: a malformed escape names no anchor anyone
  77. // meant, so the raw text flows into the lookup and is reported missing.
  78. return raw
  79. }
  80. }
  81. /**
  82. * GitHub's heading-slug algorithm (lowercase; drop everything but letters,
  83. * numbers, underscores, spaces, hyphens; spaces become hyphens). Underscores
  84. * survive (`## Showcase: web_fetch` → `#showcase-web_fetch`), unlike
  85. * `gen-cordis-catalog`'s region-anchor slugs — the generator's headings are
  86. * always reachable through its explicit `<a id>` anchors, so the two need not
  87. * share one rule.
  88. * @param heading - the RENDERED heading text (Markdown syntax already gone).
  89. * @returns the anchor GitHub assigns the first occurrence of the heading.
  90. */
  91. export function githubSlug(heading: string): string {
  92. return heading.toLowerCase().replace(/[^\p{L}\p{N}_ -]/gu, '').replaceAll(' ', '-')
  93. }
  94. /**
  95. * Every anchor one Markdown document exposes: each heading's GitHub slug —
  96. * computed from the RENDERED heading text, so links, images, inline code, and
  97. * emphasis inside a heading slug the way GitHub renders them — plus every
  98. * explicit `<a id="…">` that appears in real HTML flow (a fenced or inline
  99. * code sample and a commented-out anchor register nothing). Repeated slugs
  100. * get GitHub's occupied-set `-1`, `-2`, … suffixes: each collision bumps the
  101. * ORIGINAL slug's counter until a free name is found, so `Repeat`, `Repeat-1`,
  102. * `Repeat` yields `repeat`, `repeat-1`, `repeat-2`. Matching is exact —
  103. * element ids are case-sensitive.
  104. * @param source - the document's full Markdown text.
  105. * @returns the set of valid fragments for links into this document.
  106. */
  107. export function documentAnchors(source: string): Set<string> {
  108. const anchors = new Set<string>()
  109. const occurrences = new Map<string, number>()
  110. for (const heading of markdownHeadingLines(source)) {
  111. const base = githubSlug(heading.text)
  112. let result = base
  113. let bump = occurrences.get(base) ?? 0
  114. while (anchors.has(result)) {
  115. bump += 1
  116. result = `${base}-${bump}`
  117. }
  118. occurrences.set(base, bump)
  119. anchors.add(result)
  120. }
  121. visitMarkdown(parseMarkdown(source), (node: Nodes): void => {
  122. if (node.type !== 'html') return
  123. const html = node.value.replace(/<!--[\s\S]*?-->/g, '')
  124. for (const match of html.matchAll(/<a id="([^"]+)"/g)) anchors.add(match[1] ?? '')
  125. })
  126. return anchors
  127. }
  128. /**
  129. * Lazily collect and cache the anchor set of any existing Markdown file —
  130. * shared across all scanned sources so a target parses once.
  131. * @returns the memoized absolute-path → anchor-set lookup.
  132. */
  133. export function anchorCache(): (absPath: string) => Set<string> {
  134. const cache = new Map<string, Set<string>>()
  135. return (absPath) => {
  136. const hit = cache.get(absPath)
  137. if (hit) return hit
  138. const anchors = documentAnchors(readFileSync(absPath, 'utf8'))
  139. cache.set(absPath, anchors)
  140. return anchors
  141. }
  142. }
  143. /**
  144. * Find every broken relative cross-link in one Markdown file via its AST: a
  145. * relative target that does not exist, or a fragment onto a Markdown file
  146. * (same-file `#anchor` links included) that names no heading slug or explicit
  147. * `<a id>` there. Fragments onto non-Markdown targets (`file.ts#L10`) carry
  148. * renderer-owned semantics and are not judged.
  149. * @param absPath - absolute path of the Markdown source to scan.
  150. * @param anchorsOf - anchor lookup shared across files for cross-link checks.
  151. * @param scanRoot - repository root violations are reported relative to.
  152. * @returns one entry per broken link, in document order.
  153. */
  154. export function findViolations(
  155. absPath: string,
  156. anchorsOf: (abs: string) => Set<string>,
  157. scanRoot: string = root,
  158. ): Violation[] {
  159. const file = relative(scanRoot, absPath)
  160. const dir = dirname(absPath)
  161. const source = readFileSync(absPath, 'utf8')
  162. const tree = parseMarkdown(source)
  163. const out: Violation[] = []
  164. const check = (url: string, node: Nodes): void => {
  165. if (isExternal(url)) return
  166. const target = pathPart(url)
  167. const resolved = target === '' ? absPath : resolve(dir, target)
  168. if (!existsSync(resolved)) {
  169. out.push({ file, line: node.position?.start.line ?? 0, url, reason: 'target' })
  170. return
  171. }
  172. const fragment = fragmentPart(url)
  173. if (fragment === null || !resolved.endsWith('.md')) return
  174. if (!anchorsOf(resolved).has(fragment)) {
  175. out.push({ file, line: node.position?.start.line ?? 0, url, reason: 'anchor' })
  176. }
  177. }
  178. visitMarkdown(tree, (node: Nodes): void => {
  179. if ((node.type === 'link' || node.type === 'image' || node.type === 'definition') && 'url' in node) {
  180. check(node.url, node)
  181. }
  182. })
  183. return out
  184. }
  185. // Run only when invoked as a script, not when imported by the spec.
  186. if (process.argv[1] && import.meta.filename === resolve(process.argv[1])) {
  187. // Archived notes remain valid link targets, but their historical outbound links are frozen.
  188. const files = uniqueRepoFiles(root, PATTERNS, isArchivedAgentNotePath)
  189. const anchorsOf = anchorCache()
  190. const all = files.flatMap(file => findViolations(file.abs, anchorsOf))
  191. const checked = files.length
  192. if (all.length === 0) {
  193. console.log(`verify-md-links: ${checked} file(s) checked, all relative cross-links and fragments resolve.`)
  194. process.exit(0)
  195. }
  196. console.error('verify-md-links: broken relative cross-links found:')
  197. for (const v of all) {
  198. console.error(` ${v.file}:${v.line} ${v.url} (${v.reason === 'target' ? 'target does not exist' : 'no such anchor in target'})`)
  199. }
  200. process.exit(1)
  201. }