doc-typecheck.ts 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138
  1. /**
  2. * Doc-sync gate (doc-sync-enforcement RFC, part 1): typecheck the fenced `ts` code blocks in our
  3. * Markdown so documentation can't drift from the API it documents.
  4. *
  5. * Every ```ts block in README.md, docs/** and packages/* /README.md is
  6. * extracted to a temp typecheck project and compiled against the workspace
  7. * sources through the same project-reference boundaries used by repo
  8. * typecheck. A block that is a deliberate sketch rather than compilable code
  9. * opts out with an explicit ` ```ts ignore-check ` info string — the opt-out
  10. * is visible in the source, and this script reports the ratio so the escape
  11. * hatch can't quietly become the norm.
  12. *
  13. * Run: `tsx scripts/doc-typecheck.ts`.
  14. */
  15. import { execFileSync } from 'node:child_process'
  16. import { mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
  17. import { join, relative, resolve } from 'node:path'
  18. import { glob } from 'node:fs/promises'
  19. const root = resolve(import.meta.dirname, '..')
  20. /** One extracted code block. */
  21. interface Block {
  22. file: string
  23. /** 1-based line of the opening fence. */
  24. line: number
  25. /** `true` when the fence is ` ```ts ignore-check ` (skip compilation). */
  26. ignored: boolean
  27. code: string
  28. }
  29. /** Extract every ```ts / ```ts ignore-check block from one Markdown file. */
  30. function extractBlocks(absPath: string): Block[] {
  31. const text = readFileSync(absPath, 'utf8')
  32. const lines = text.split('\n')
  33. const file = relative(root, absPath)
  34. const blocks: Block[] = []
  35. let open: { line: number; ignored: boolean; body: string[] } | null = null
  36. lines.forEach((raw, i) => {
  37. const fence = /^```(\s*)(\S.*)?$/.exec(raw)
  38. if (!fence) {
  39. if (open) open.body.push(raw)
  40. return
  41. }
  42. if (open) {
  43. // closing fence
  44. blocks.push({ file, line: open.line, ignored: open.ignored, code: open.body.join('\n') })
  45. open = null
  46. return
  47. }
  48. // opening fence — only care about ts blocks
  49. const info = (fence[2] ?? '').trim()
  50. if (info === 'ts' || info === 'ts ignore-check') {
  51. open = { line: i + 1, ignored: info === 'ts ignore-check', body: [] }
  52. }
  53. })
  54. return blocks
  55. }
  56. /** Reuse the repo typecheck graph references from a temp project one directory below root. */
  57. function workspaceReferences(): { path: string }[] {
  58. const raw = readFileSync(join(root, 'tsconfig.json'), 'utf8')
  59. const { references } = JSON.parse(raw) as { references: { path: string }[] }
  60. return references.map(({ path }) => {
  61. const relativeToTemp = path.startsWith('./') ? `../${path.slice(2)}` : `../${path}`
  62. return { path: relativeToTemp }
  63. })
  64. }
  65. /** The standalone tsconfig for the temp typecheck project. */
  66. function tempTsconfig(): string {
  67. return JSON.stringify({
  68. extends: '../tsconfig.json',
  69. compilerOptions: {
  70. noUnusedLocals: false,
  71. noUnusedParameters: false,
  72. tsBuildInfoFile: './tsconfig.tsbuildinfo',
  73. },
  74. include: ['block-*.ts'],
  75. references: workspaceReferences(),
  76. })
  77. }
  78. const markdownGlobs = ['README.md', 'docs/**/*.md', 'packages/*/README.md']
  79. const files: string[] = []
  80. for (const pattern of markdownGlobs) {
  81. for await (const match of glob(pattern, { cwd: root })) files.push(resolve(root, match))
  82. }
  83. files.sort()
  84. const all = files.flatMap(extractBlocks)
  85. const checked = all.filter(b => !b.ignored)
  86. const ignored = all.filter(b => b.ignored)
  87. if (checked.length === 0) {
  88. console.log('doc-typecheck: no ts code blocks to check.')
  89. process.exit(0)
  90. }
  91. const tmp = mkdtempSync(join(root, '.doc-typecheck-'))
  92. try {
  93. writeFileSync(join(tmp, 'tsconfig.json'), tempTsconfig())
  94. const fileForBlock = new Map<string, Block>()
  95. checked.forEach((block, i) => {
  96. const name = `block-${i}.ts`
  97. writeFileSync(join(tmp, name), block.code.endsWith('\n') ? block.code : `${block.code}\n`)
  98. fileForBlock.set(name, block)
  99. })
  100. try {
  101. execFileSync('node_modules/.bin/tsc', ['-b', join(tmp, 'tsconfig.json')], { cwd: root, stdio: 'pipe' })
  102. } catch (error: unknown) {
  103. const failed = error as { stdout?: Buffer; stderr?: Buffer }
  104. const out = `${failed.stdout?.toString() ?? ''}${failed.stderr?.toString() ?? ''}`
  105. // Rewrite "block-N.ts(line,col)" to the real "file:fenceLine" for triage.
  106. const remapped = out.replace(/(?:[^\s:()]*[/\\])?block-(\d+)\.ts\((\d+),(\d+)\)/g, (_m, idx: string, ln: string, col: string) => {
  107. const block = fileForBlock.get(`block-${idx}.ts`)
  108. if (!block) return `block-${idx}.ts(${ln},${col})`
  109. return `${block.file} (block at line ${block.line}, +${ln}:${col})`
  110. })
  111. console.error('doc-typecheck: documentation code blocks failed to compile.\n')
  112. console.error(remapped)
  113. process.exit(1)
  114. }
  115. const ratio = ignored.length / all.length
  116. console.log(`doc-typecheck: ${checked.length} block(s) compiled, ${ignored.length} ignored (${(ratio * 100).toFixed(0)}% opt-out).`)
  117. // Guard against the escape hatch becoming the norm.
  118. if (all.length >= 4 && ratio > 0.5) {
  119. console.error(`doc-typecheck: too many blocks opt out of checking (${ignored.length}/${all.length}). Make them compile or delete them.`)
  120. process.exit(1)
  121. }
  122. } finally {
  123. rmSync(tmp, { recursive: true, force: true })
  124. }