doc-typecheck.ts 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151
  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 file and compiled with `tsc --noEmit` against the
  7. * workspace sources (resolved through the same `paths` map vitest uses, so no
  8. * build is required first). A block that is a deliberate sketch rather than
  9. * compilable code opts out with an explicit ` ```ts ignore-check ` info string
  10. * — the opt-out is visible in the source, and this script reports the ratio so
  11. * the escape 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. /**
  57. * Read the workspace `paths` map from tsconfig.typecheck.json (JSONC). This map
  58. * resolves vendored packages to their BUILT declarations (`lib`) and harness
  59. * packages to source (`src`) — the same resolution `pnpm run lint`/`typecheck` use.
  60. * Resolving vendor to `lib` (not `src`) is essential: otherwise tsc type-checks
  61. * raw vendor source and floods the run with unrelated errors. Requires the
  62. * vendor `lib/` to exist (a fresh clone runs `pnpm run build` first; CI does too).
  63. */
  64. function workspacePaths(): Record<string, string[]> {
  65. const raw = readFileSync(join(root, 'tsconfig.typecheck.json'), 'utf8')
  66. // Strip // line comments and /* */ block comments so JSON.parse accepts it.
  67. const stripped = raw
  68. .replace(/\/\*[\s\S]*?\*\//g, '')
  69. .replace(/(^|[^:])\/\/.*$/gm, '$1')
  70. return (JSON.parse(stripped) as { compilerOptions: { paths: Record<string, string[]> } })
  71. .compilerOptions.paths
  72. }
  73. /** The standalone tsconfig for the temp project (copies base resolution, no
  74. * composite/declaration settings that would fight `--noEmit`). */
  75. function tempTsconfig(): string {
  76. return JSON.stringify({
  77. compilerOptions: {
  78. target: 'es2024',
  79. module: 'esnext',
  80. moduleResolution: 'bundler',
  81. allowImportingTsExtensions: true,
  82. strict: true,
  83. noEmit: true,
  84. skipLibCheck: true,
  85. types: ['node'],
  86. baseUrl: root,
  87. ignoreDeprecations: '6.0',
  88. paths: workspacePaths(),
  89. },
  90. })
  91. }
  92. const markdownGlobs = ['README.md', 'docs/**/*.md', 'packages/*/README.md']
  93. const files: string[] = []
  94. for (const pattern of markdownGlobs) {
  95. for await (const match of glob(pattern, { cwd: root })) files.push(resolve(root, match))
  96. }
  97. files.sort()
  98. const all = files.flatMap(extractBlocks)
  99. const checked = all.filter(b => !b.ignored)
  100. const ignored = all.filter(b => b.ignored)
  101. if (checked.length === 0) {
  102. console.log('doc-typecheck: no ts code blocks to check.')
  103. process.exit(0)
  104. }
  105. const tmp = mkdtempSync(join(root, '.doc-typecheck-'))
  106. try {
  107. writeFileSync(join(tmp, 'tsconfig.json'), tempTsconfig())
  108. const fileForBlock = new Map<string, Block>()
  109. checked.forEach((block, i) => {
  110. const name = `block-${i}.ts`
  111. writeFileSync(join(tmp, name), block.code.endsWith('\n') ? block.code : `${block.code}\n`)
  112. fileForBlock.set(name, block)
  113. })
  114. try {
  115. execFileSync('node_modules/.bin/tsc', ['-p', join(tmp, 'tsconfig.json')], { cwd: root, stdio: 'pipe' })
  116. } catch (error: unknown) {
  117. const out = (error as { stdout?: Buffer }).stdout?.toString() ?? ''
  118. // Rewrite "block-N.ts(line,col)" to the real "file:fenceLine" for triage.
  119. const remapped = out.replace(/block-(\d+)\.ts\((\d+),(\d+)\)/g, (_m, idx: string, ln: string, col: string) => {
  120. const block = fileForBlock.get(`block-${idx}.ts`)
  121. if (!block) return `block-${idx}.ts(${ln},${col})`
  122. return `${block.file} (block at line ${block.line}, +${ln}:${col})`
  123. })
  124. console.error('doc-typecheck: documentation code blocks failed to compile.\n')
  125. console.error(remapped)
  126. process.exit(1)
  127. }
  128. const ratio = ignored.length / all.length
  129. console.log(`doc-typecheck: ${checked.length} block(s) compiled, ${ignored.length} ignored (${(ratio * 100).toFixed(0)}% opt-out).`)
  130. // Guard against the escape hatch becoming the norm.
  131. if (all.length >= 4 && ratio > 0.5) {
  132. console.error(`doc-typecheck: too many blocks opt out of checking (${ignored.length}/${all.length}). Make them compile or delete them.`)
  133. process.exit(1)
  134. }
  135. } finally {
  136. rmSync(tmp, { recursive: true, force: true })
  137. }