verify-md-links.ts 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157
  1. /**
  2. * Doc-sync gate: verify that every relative Markdown cross-link resolves to a
  3. * file that exists. Docs in this repo link to each other by relative path
  4. * (`[topic](../implemented/2026-…-….md)`, `[the cookbook](adding-a-tool.md)`);
  5. * a rename or a move silently breaks those links, and nothing caught it before
  6. * review. The RFC tree reorganization (one `docs/rfc/` with proposed/
  7. * implemented/ rejected/ subfolders, every file renamed to a dated slug) is the
  8. * motivating case: ~40 inter-doc links were rewritten by hand, and a single
  9. * fat-fingered path would have shipped a dead link.
  10. *
  11. * Detection is AST-based, mirroring verify-md-wrap: parse each file with
  12. * mdast-util-from-markdown + GFM, then walk every `link`, `image`, and
  13. * `definition` node. A target is checked when it is a RELATIVE path; these are
  14. * skipped because they are not ours to verify:
  15. * - absolute URLs with a scheme (`https:`, `http:`, `mailto:`, …),
  16. * - protocol-relative URLs (`//host/path`),
  17. * - root-absolute paths (`/foo` — no stable base in a repo checkout),
  18. * - pure in-page anchors (`#section`).
  19. * For a relative target the `#fragment` and `?query` are stripped, the path is
  20. * resolved against the linking file's directory, and the result must exist on
  21. * disk. This is checker, not fixer: it reports and never rewrites.
  22. *
  23. * Scope is the other doc-sync gates' set plus example Markdown, AGENTS.md
  24. * files in those checked trees, AND the repo-authored agent-skill Markdown under
  25. * `.agents/skills/` — those skill files cross-link into the docs tree (e.g. the
  26. * dsh-code-review skill cites the RFC index), so a rename must not silently
  27. * break them either: README.md, docs/** /*.md, packages/* /README.md,
  28. * examples/** /*.md, AGENTS.md, packages/AGENTS.md, .agents/skills/** /*.md.
  29. * The root, packages/, and examples/ CLAUDE.md files are symlinks to the
  30. * AGENTS.md files, so they are deduped by real path.
  31. *
  32. * Run: `tsx scripts/verify-md-links.ts`.
  33. */
  34. import { existsSync, globSync, readFileSync, realpathSync } from 'node:fs'
  35. import { dirname, relative, resolve } from 'node:path'
  36. import { fromMarkdown } from 'mdast-util-from-markdown'
  37. import { gfmFromMarkdown } from 'mdast-util-gfm'
  38. import { gfm } from 'micromark-extension-gfm'
  39. import type { Nodes } from 'mdast'
  40. const root = resolve(import.meta.dirname, '..')
  41. /**
  42. * Files to check: doc-typecheck's scope, example Markdown, the AGENTS.md pair,
  43. * and repo-authored agent-skill Markdown.
  44. */
  45. const PATTERNS = [
  46. 'README.md',
  47. 'README.zh.md',
  48. 'docs/**/*.md',
  49. 'packages/*/*.md',
  50. 'packages/*/*/*.md',
  51. 'examples/**/*.md',
  52. 'AGENTS.md',
  53. 'packages/AGENTS.md',
  54. '.agents/skills/**/*.md',
  55. ]
  56. /** A broken relative link: a target path that does not resolve to a file. */
  57. interface Violation {
  58. file: string
  59. /** 1-based line where the link/image/definition node starts. */
  60. line: number
  61. url: string
  62. }
  63. /**
  64. * True for targets this gate must NOT check: scheme-qualified URLs (`https:`,
  65. * `mailto:`, …), protocol-relative (`//host`), root-absolute (`/path`), and
  66. * pure in-page anchors (`#frag`). Everything else is a relative path we own.
  67. */
  68. function isExternalOrAnchor(url: string): boolean {
  69. if (url.startsWith('#')) return true
  70. if (url.startsWith('//')) return true
  71. if (url.startsWith('/')) return true
  72. // A scheme like `https:` / `mailto:` — a colon before any slash, dot, or hash.
  73. return /^[a-zA-Z][a-zA-Z0-9+.-]*:/.test(url)
  74. }
  75. /**
  76. * Strip the `#fragment` and `?query` from a link target, then percent-decode
  77. * the remaining path so an encoded target (`My%20File.md`, `READ%4DE.md`)
  78. * probes the real filename on disk, the way a Markdown renderer resolves it. A
  79. * malformed escape (`%zz`) makes `decodeURIComponent` throw; we keep the raw
  80. * path in that case so the link is reported as broken (a `%zz` target is not a
  81. * file anyone meant to link) rather than crashing the gate.
  82. */
  83. function pathPart(url: string): string {
  84. const raw = url.replace(/[#?].*$/, '')
  85. try {
  86. return decodeURIComponent(raw)
  87. } catch {
  88. // decodeURIComponent throws only on a malformed percent-escape; the raw
  89. // string is then a path no renderer resolves, so fall through to the
  90. // existence check, which reports it broken.
  91. return raw
  92. }
  93. }
  94. /** Find every broken relative cross-link in one Markdown file via its AST. */
  95. function findViolations(absPath: string): Violation[] {
  96. const file = relative(root, absPath)
  97. const dir = dirname(absPath)
  98. const source = readFileSync(absPath, 'utf8')
  99. const tree = fromMarkdown(source, { extensions: [gfm()], mdastExtensions: [gfmFromMarkdown()] })
  100. const out: Violation[] = []
  101. const check = (url: string, node: Nodes): void => {
  102. if (isExternalOrAnchor(url)) return
  103. const target = pathPart(url)
  104. // A bare `#anchor` reduced to empty path is a same-file anchor — skip.
  105. if (target === '') return
  106. const resolved = resolve(dir, target)
  107. if (!existsSync(resolved)) {
  108. out.push({ file, line: node.position?.start.line ?? 0, url })
  109. }
  110. }
  111. const visit = (node: Nodes): void => {
  112. if ((node.type === 'link' || node.type === 'image' || node.type === 'definition') && 'url' in node) {
  113. check(node.url, node)
  114. }
  115. if ('children' in node) {
  116. for (const child of node.children) visit(child)
  117. }
  118. }
  119. visit(tree)
  120. return out
  121. }
  122. const seen = new Set<string>()
  123. const all: Violation[] = []
  124. let checked = 0
  125. for (const pattern of PATTERNS) {
  126. for (const match of globSync(pattern, { cwd: root })) {
  127. const abs = resolve(root, match)
  128. // CLAUDE.md symlinks resolve onto AGENTS.md; dedupe by real path so a file
  129. // matched twice (or via symlink) is checked once.
  130. const real = realpathSync(abs)
  131. if (seen.has(real)) continue
  132. seen.add(real)
  133. checked++
  134. all.push(...findViolations(abs))
  135. }
  136. }
  137. if (all.length === 0) {
  138. console.log(`verify-md-links: ${checked} file(s) checked, all relative cross-links resolve.`)
  139. process.exit(0)
  140. }
  141. console.error('verify-md-links: broken relative cross-links found (target does not exist):')
  142. for (const v of all) {
  143. console.error(` ${v.file}:${v.line} ${v.url}`)
  144. }
  145. process.exit(1)