verify-md-links.ts 3.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111
  1. /**
  2. * Verify that relative Markdown links, images, and definitions resolve. URL,
  3. * root-absolute, and in-page targets are excluded; query strings and fragments
  4. * do not affect resolution against the source file. The checker never rewrites,
  5. * and symlinked instruction files are deduped.
  6. */
  7. import { existsSync, readFileSync } from 'node:fs'
  8. import { dirname, relative, resolve } from 'node:path'
  9. import type { Nodes } from 'mdast'
  10. import { parseMarkdown, visitMarkdown } from './markdown.ts'
  11. import { uniqueRepoFiles } from './repo-files.ts'
  12. const root = resolve(import.meta.dirname, '..')
  13. /** Repo-authored Markdown checked for relative links. */
  14. const PATTERNS = [
  15. 'README.md',
  16. 'README.zh.md',
  17. '.agents/notes/**/*.md',
  18. 'docs/**/*.md',
  19. 'packages/*/*.md',
  20. 'packages/*/*/*.md',
  21. 'examples/**/*.md',
  22. 'AGENTS.md',
  23. 'packages/AGENTS.md',
  24. '.agents/skills/**/*.md',
  25. ]
  26. /** A broken relative link: a target path that does not resolve to a file. */
  27. interface Violation {
  28. file: string
  29. /** 1-based line where the link/image/definition node starts. */
  30. line: number
  31. url: string
  32. }
  33. /**
  34. * True for targets this gate must NOT check: scheme-qualified URLs (`https:`,
  35. * `mailto:`, …), protocol-relative (`//host`), root-absolute (`/path`), and
  36. * pure in-page anchors (`#frag`). Everything else is a relative path we own.
  37. */
  38. function isExternalOrAnchor(url: string): boolean {
  39. if (url.startsWith('#')) return true
  40. if (url.startsWith('//')) return true
  41. if (url.startsWith('/')) return true
  42. // A scheme like `https:` / `mailto:` — a colon before any slash, dot, or hash.
  43. return /^[a-zA-Z][a-zA-Z0-9+.-]*:/.test(url)
  44. }
  45. /**
  46. * Strip the `#fragment` and `?query` from a link target, then percent-decode
  47. * the remaining path so an encoded target (`My%20File.md`, `READ%4DE.md`)
  48. * probes the real filename on disk, the way a Markdown renderer resolves it. A
  49. * malformed escape (`%zz`) makes `decodeURIComponent` throw; we keep the raw
  50. * path in that case so the link is reported as broken (a `%zz` target is not a
  51. * file anyone meant to link) rather than crashing the gate.
  52. */
  53. function pathPart(url: string): string {
  54. const raw = url.replace(/[#?].*$/, '')
  55. try {
  56. return decodeURIComponent(raw)
  57. } catch {
  58. // decodeURIComponent throws only on a malformed percent-escape; the raw
  59. // string is then a path no renderer resolves, so fall through to the
  60. // existence check, which reports it broken.
  61. return raw
  62. }
  63. }
  64. /** Find every broken relative cross-link in one Markdown file via its AST. */
  65. function findViolations(absPath: string): Violation[] {
  66. const file = relative(root, absPath)
  67. const dir = dirname(absPath)
  68. const source = readFileSync(absPath, 'utf8')
  69. const tree = parseMarkdown(source)
  70. const out: Violation[] = []
  71. const check = (url: string, node: Nodes): void => {
  72. if (isExternalOrAnchor(url)) return
  73. const target = pathPart(url)
  74. // A bare `#anchor` reduced to empty path is a same-file anchor — skip.
  75. if (target === '') return
  76. const resolved = resolve(dir, target)
  77. if (!existsSync(resolved)) {
  78. out.push({ file, line: node.position?.start.line ?? 0, url })
  79. }
  80. }
  81. visitMarkdown(tree, (node: Nodes): void => {
  82. if ((node.type === 'link' || node.type === 'image' || node.type === 'definition') && 'url' in node) {
  83. check(node.url, node)
  84. }
  85. })
  86. return out
  87. }
  88. const files = uniqueRepoFiles(root, PATTERNS)
  89. const all = files.flatMap(file => findViolations(file.abs))
  90. const checked = files.length
  91. if (all.length === 0) {
  92. console.log(`verify-md-links: ${checked} file(s) checked, all relative cross-links resolve.`)
  93. process.exit(0)
  94. }
  95. console.error('verify-md-links: broken relative cross-links found (target does not exist):')
  96. for (const v of all) {
  97. console.error(` ${v.file}:${v.line} ${v.url}`)
  98. }
  99. process.exit(1)