doc-typecheck.ts 9.9 KB

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