doc-typecheck.ts 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234
  1. /**
  2. * Typecheck Markdown `ts` fences against the workspace API. `ignore-check` fences are reported as
  3. * opt-outs; generated catalog fragments and `type-equiv` blocks are skipped here because their
  4. * owning gates verify them. A build-coordinated mode consumes existing declarations without emit.
  5. */
  6. import { execFileSync } from 'node:child_process'
  7. import { globSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
  8. import { join, relative, resolve } from 'node:path'
  9. import ts from 'typescript'
  10. import { extractFences } from './md-fences.ts'
  11. const root = resolve(import.meta.dirname, '..')
  12. /**
  13. * TypeScript-fence ownership. `check` compiles; `ignore` is an unchecked sketch
  14. * counted in the opt-out ratio; the catalog and type-equivalence variants are
  15. * excluded from that ratio because their owning gates verify them.
  16. */
  17. type BlockKind = 'check' | 'ignore' | 'type-equiv' | 'cordis-catalog' | 'persistence-catalog' | 'config-catalog'
  18. /** One extracted code block. */
  19. interface Block {
  20. file: string
  21. /** 1-based line of the opening fence. */
  22. line: number
  23. kind: BlockKind
  24. code: string
  25. }
  26. /** The info-string → kind table this gate tracks. */
  27. const KIND_BY_INFO: Record<string, BlockKind> = {
  28. 'ts': 'check',
  29. 'ts ignore-check': 'ignore',
  30. 'ts type-equiv': 'type-equiv',
  31. 'ts cordis-catalog': 'cordis-catalog',
  32. 'ts persistence-catalog': 'persistence-catalog',
  33. 'ts config-catalog': 'config-catalog',
  34. }
  35. /** Extract every recognized TypeScript fence from one Markdown file. */
  36. function extractBlocks(absPath: string): Block[] {
  37. const file = relative(root, absPath)
  38. return extractFences(absPath, info => KIND_BY_INFO[info] ?? null)
  39. .map(f => ({ file, line: f.line, kind: f.kind, code: f.code }))
  40. }
  41. const configHost: ts.ParseConfigFileHost = {
  42. ...ts.sys,
  43. getCurrentDirectory: () => root,
  44. onUnRecoverableConfigFileDiagnostic(diagnostic) {
  45. throw new Error(ts.flattenDiagnosticMessageText(diagnostic.messageText, '\n'))
  46. },
  47. }
  48. /** Load root settings and redirect workspace aliases to declarations from the coordinated build. */
  49. function builtTypeCompilerOptions(): ts.CompilerOptions {
  50. const configPath = join(root, 'tsconfig.json')
  51. const parsed = ts.getParsedCommandLineOfConfigFile(configPath, {}, configHost)
  52. if (!parsed) throw new Error(`doc-typecheck: cannot parse ${configPath}`)
  53. if (parsed.errors.length > 0) {
  54. throw new Error(parsed.errors.map(error => ts.flattenDiagnosticMessageText(error.messageText, '\n')).join('\n'))
  55. }
  56. if (parsed.options.paths === undefined) throw new Error('doc-typecheck: root tsconfig has no workspace paths')
  57. const paths = Object.fromEntries(Object.entries(parsed.options.paths).map(([specifier, candidates]) => [
  58. specifier,
  59. candidates.map((candidate) => {
  60. if (!candidate.endsWith('/src')) {
  61. throw new Error(`doc-typecheck: cannot map workspace source path to built declarations: ${candidate}`)
  62. }
  63. return `${candidate.slice(0, -'/src'.length)}/lib/types`
  64. }),
  65. ]))
  66. const options: ts.CompilerOptions = {
  67. ...parsed.options,
  68. paths,
  69. noEmit: true,
  70. composite: false,
  71. incremental: false,
  72. declaration: false,
  73. declarationMap: false,
  74. sourceMap: false,
  75. noUnusedLocals: false,
  76. noUnusedParameters: false,
  77. }
  78. delete options.tsBuildInfoFile
  79. return options
  80. }
  81. /** Compile Markdown blocks as virtual files against declarations from the coordinated build. */
  82. function compileBlocksAgainstBuiltTypes(blocks: Block[]): readonly ts.Diagnostic[] {
  83. const options = builtTypeCompilerOptions()
  84. const sources = new Map<string, string>()
  85. for (const [index, block] of blocks.entries()) {
  86. const fileName = resolve(root, '.doc-typecheck', `block-${index}.ts`)
  87. sources.set(fileName, block.code.endsWith('\n') ? block.code : `${block.code}\n`)
  88. }
  89. const baseHost = ts.createCompilerHost(options, true)
  90. const host: ts.CompilerHost = {
  91. ...baseHost,
  92. fileExists(fileName) {
  93. return sources.has(resolve(fileName)) || baseHost.fileExists(fileName)
  94. },
  95. readFile(fileName) {
  96. return sources.get(resolve(fileName)) ?? baseHost.readFile(fileName)
  97. },
  98. getSourceFile(fileName, languageVersion, onError, shouldCreateNewSourceFile) {
  99. const source = sources.get(resolve(fileName))
  100. if (source !== undefined) return ts.createSourceFile(fileName, source, languageVersion, true)
  101. return baseHost.getSourceFile(fileName, languageVersion, onError, shouldCreateNewSourceFile)
  102. },
  103. writeFile() {
  104. throw new Error('doc-typecheck: noEmit compilation attempted to write output')
  105. },
  106. }
  107. const program = ts.createProgram([...sources.keys()], options, host)
  108. return ts.getPreEmitDiagnostics(program)
  109. }
  110. /** Render compiler diagnostics with virtual block paths mapped back to Markdown. */
  111. function formatDiagnostics(diagnostics: readonly ts.Diagnostic[], blocks: Block[]): string {
  112. const formatted = ts.formatDiagnostics(diagnostics, {
  113. getCanonicalFileName: fileName => fileName,
  114. getCurrentDirectory: () => root,
  115. getNewLine: () => ts.sys.newLine,
  116. })
  117. return remapBlockPaths(formatted, blocks)
  118. }
  119. /** Reuse the repo typecheck graph references from a temp project one directory below root. */
  120. function workspaceReferences(): { path: string }[] {
  121. const file = join(root, 'tsconfig.json')
  122. // Parse with TypeScript's own JSONC reader: a regex comment stripper corrupts the `/*/` path
  123. // candidate in the workspace wildcard.
  124. const result = ts.readConfigFile(file, path => readFileSync(path, 'utf8'))
  125. if (result.error) {
  126. throw new Error(`doc-typecheck: cannot read ${file}: ${ts.flattenDiagnosticMessageText(result.error.messageText, '\n')}`)
  127. }
  128. // `config` is typed `any` by the TS API; narrow it to the one field read here.
  129. const { references } = result.config as { references: { path: string }[] }
  130. return references.map(({ path }) => ({
  131. path: path.startsWith('./') ? `../${path.slice(2)}` : `../${path}`,
  132. }))
  133. }
  134. /** The standalone temp project used when no coordinated build owns declaration freshness. */
  135. function tempTsconfig(): string {
  136. return JSON.stringify({
  137. extends: '../tsconfig.json',
  138. compilerOptions: {
  139. noUnusedLocals: false,
  140. noUnusedParameters: false,
  141. tsBuildInfoFile: './tsconfig.tsbuildinfo',
  142. },
  143. include: ['block-*.ts'],
  144. references: workspaceReferences(),
  145. })
  146. }
  147. /** Compile blocks through project references for the standalone command. */
  148. function compileBlocksStandalone(blocks: Block[]): string | undefined {
  149. const tmp = mkdtempSync(join(root, '.doc-typecheck-'))
  150. try {
  151. writeFileSync(join(tmp, 'tsconfig.json'), tempTsconfig())
  152. for (const [index, block] of blocks.entries()) {
  153. writeFileSync(join(tmp, `block-${index}.ts`), block.code.endsWith('\n') ? block.code : `${block.code}\n`)
  154. }
  155. try {
  156. // Invoke tsc's JS entry through Node instead of a platform-specific shell shim.
  157. execFileSync(process.execPath, ['node_modules/typescript/bin/tsc', '-b', join(tmp, 'tsconfig.json')], {
  158. cwd: root,
  159. stdio: 'pipe',
  160. })
  161. return undefined
  162. } catch (error: unknown) {
  163. const failed = error as { stdout?: Buffer; stderr?: Buffer }
  164. return remapBlockPaths(`${failed.stdout?.toString() ?? ''}${failed.stderr?.toString() ?? ''}`, blocks)
  165. }
  166. } finally {
  167. rmSync(tmp, { recursive: true, force: true })
  168. }
  169. }
  170. /** Map virtual or temporary block paths back to their owning Markdown fences. */
  171. function remapBlockPaths(output: string, blocks: Block[]): string {
  172. return output.replace(/(?:[^\s:()]*[/\\])?block-(\d+)\.ts\((\d+),(\d+)\)/g, (_match, index: string, line: string, column: string) => {
  173. const block = blocks[Number(index)]
  174. if (!block) return `block-${index}.ts(${line},${column})`
  175. return `${block.file} (block at line ${block.line}, +${line}:${column})`
  176. })
  177. }
  178. const markdownGlobs = ['README.md', 'docs/**/*.md', 'packages/*/*.md', 'packages/*/*/*.md', 'website/zh-CN/**/*.md']
  179. const files: string[] = []
  180. for (const pattern of markdownGlobs) {
  181. for (const match of globSync(pattern, { cwd: root })) files.push(resolve(root, match))
  182. }
  183. files.sort()
  184. const all = files.flatMap(extractBlocks)
  185. const checked = all.filter(b => b.kind === 'check')
  186. const ignored = all.filter(b => b.kind === 'ignore')
  187. // Only compile-eligible fences belong in the opt-out ratio; every other skipped
  188. // kind has an independent verifier named in BlockKind's contract above.
  189. const ratioDenominator = checked.length + ignored.length
  190. if (checked.length === 0) {
  191. console.log('doc-typecheck: no ts code blocks to check.')
  192. process.exit(0)
  193. }
  194. const useBuiltTypes = process.env.DSH_DOC_TYPECHECK_USE_BUILD_OUTPUT === '1'
  195. const compilationError = useBuiltTypes
  196. ? (() => {
  197. const diagnostics = compileBlocksAgainstBuiltTypes(checked)
  198. return diagnostics.length === 0 ? undefined : formatDiagnostics(diagnostics, checked)
  199. })()
  200. : compileBlocksStandalone(checked)
  201. if (compilationError !== undefined) {
  202. console.error('doc-typecheck: documentation code blocks failed to compile.\n')
  203. console.error(compilationError)
  204. process.exit(1)
  205. }
  206. const ratio = ignored.length / ratioDenominator
  207. const skipped = all.length - ratioDenominator
  208. console.log(`doc-typecheck: ${checked.length} block(s) compiled, ${ignored.length} ignored (${(ratio * 100).toFixed(0)}% opt-out), ${skipped} type-equiv/catalog (checked elsewhere).`)
  209. // Guard against the escape hatch becoming the norm.
  210. if (ratioDenominator >= 4 && ratio > 0.5) {
  211. console.error(`doc-typecheck: too many blocks opt out of checking (${ignored.length}/${ratioDenominator}). Make them compile or delete them.`)
  212. process.exit(1)
  213. }