verify-md-links.ts 3.7 KB

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