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