verify-type-equiv.ts 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227
  1. /**
  2. * Doc-sync gate: verify every ` ```ts type-equiv ` block in the docs is a
  3. * VERBATIM copy of the source type definition it documents.
  4. *
  5. * The core-data-structures docs paste real type definitions so a reader sees
  6. * the exact shape. A paste drifts the moment source changes — this script is
  7. * the drift guard. For each block it extracts the documented symbol's
  8. * declaration from source via the TypeScript compiler API, whitespace-
  9. * normalizes both the source text and the block, and asserts they are equal.
  10. *
  11. * Provenance lives in a central manifest (`scripts/type-equiv.manifest.json`),
  12. * NOT in the doc prose: each entry names `{ doc, symbol, source }`. The script
  13. * enforces a 1:1 correspondence — every type-equiv block in the docs has
  14. * exactly one manifest entry (keyed by doc + declared symbol), and every
  15. * manifest entry resolves to exactly one block. An orphan on either side fails,
  16. * so a block can never be silently unchecked and an entry can never rot.
  17. *
  18. * doc-typecheck.ts recognizes the same ` ```ts type-equiv ` fence and skips it
  19. * (it is not standalone-compilable and is not counted in the opt-out ratio);
  20. * the two scripts share the fence, this one owns the verification.
  21. *
  22. * Run: `tsx scripts/verify-type-equiv.ts`.
  23. */
  24. import { readFileSync, existsSync } from 'node:fs'
  25. import { resolve } from 'node:path'
  26. import { glob } from 'node:fs/promises'
  27. import ts from 'typescript'
  28. const root = resolve(import.meta.dirname, '..')
  29. /**
  30. * Markdown globs scanned for ` ```ts type-equiv ` blocks — the SAME scope
  31. * doc-typecheck uses. Scanning every doc (not only the docs the manifest names)
  32. * is what makes the 1:1 guarantee real in both directions: a type-equiv block
  33. * added to a doc with NO manifest entry is still discovered here and reported as
  34. * an orphan, instead of being silently skipped.
  35. */
  36. const MARKDOWN_GLOBS = ['README.md', 'docs/**/*.md', 'packages/*/*.md', 'packages/*/*/*.md']
  37. /** One manifest entry: a documented type-equiv block and its source symbol. */
  38. interface ManifestEntry {
  39. /** Doc file (repo-relative) containing the ` ```ts type-equiv ` block. */
  40. doc: string
  41. /** The declared symbol the block must match (e.g. `SessionEvent`). */
  42. symbol: string
  43. /** Source file (repo-relative) that exports the symbol. */
  44. source: string
  45. }
  46. /** One extracted ` ```ts type-equiv ` block. */
  47. interface EquivBlock {
  48. doc: string
  49. /** 1-based line of the opening fence (for diagnostics). */
  50. line: number
  51. /** Symbol name parsed from the block's declaration. */
  52. symbol: string
  53. /** Block body (the pasted declaration). */
  54. code: string
  55. }
  56. /** Collapse a declaration to its structural form for comparison: drop comments
  57. * (block + line), then collapse all whitespace runs to single spaces. This lets
  58. * a doc block show a CLEAN definition (without source's verbose inline JSDoc)
  59. * while still guaranteeing the field shapes match — drift in a field name or
  60. * type fails; a reworded inline comment does not. Adequate for our own type
  61. * source (no string literal contains `//` or `/* *​/`); not a general tokenizer. */
  62. function normalize(code: string): string {
  63. return code
  64. .replace(/\/\*[\s\S]*?\*\//g, '')
  65. .replace(/(^|[^:])\/\/.*$/gm, '$1')
  66. .replace(/\s+/g, ' ')
  67. .trim()
  68. }
  69. /** Strip a leading `export ` / `export default ` modifier — the doc block shows
  70. * the bare declaration, the source carries the export modifier. */
  71. function stripExport(code: string): string {
  72. return code.replace(/^export\s+(default\s+)?/, '')
  73. }
  74. /** Parse the declared symbol name from a type-equiv block body. */
  75. function blockSymbol(code: string): string | null {
  76. const m = /(?:export\s+(?:default\s+)?)?(?:abstract\s+)?(?:interface|type|class|enum)\s+([A-Za-z0-9_]+)/.exec(code)
  77. return m?.[1] ?? null
  78. }
  79. /** Extract every ` ```ts type-equiv ` block from one Markdown file. */
  80. function extractEquivBlocks(docRel: string): EquivBlock[] {
  81. const text = readFileSync(resolve(root, docRel), 'utf8')
  82. const lines = text.split('\n')
  83. const blocks: EquivBlock[] = []
  84. let open: { line: number; body: string[] } | null = null
  85. for (let i = 0; i < lines.length; i++) {
  86. const raw = lines[i] ?? ''
  87. const fence = /^```(\s*)(\S.*)?$/.exec(raw)
  88. if (!fence) {
  89. if (open) open.body.push(raw)
  90. continue
  91. }
  92. if (open) {
  93. const code = open.body.join('\n')
  94. const symbol = blockSymbol(code)
  95. if (!symbol) {
  96. throw new Error(`verify-type-equiv: ${docRel}:${open.line} — type-equiv block has no parseable interface/type/class declaration`)
  97. }
  98. blocks.push({ doc: docRel, line: open.line, symbol, code })
  99. open = null
  100. continue
  101. }
  102. if ((fence[2] ?? '').trim() === 'ts type-equiv') open = { line: i + 1, body: [] }
  103. }
  104. if (open) throw new Error(`verify-type-equiv: ${docRel}:${open.line} — unterminated type-equiv block`)
  105. return blocks
  106. }
  107. /** The declaration text of `symbol` in `sourceRel`, with `export` stripped, or
  108. * null when the symbol is not declared there. Uses the TS parser so it spans
  109. * interfaces, type aliases (including mapped/generic ones), classes, and enums
  110. * uniformly, and excludes the leading JSDoc (getStart skips leading trivia)
  111. * while keeping inline member comments. */
  112. function sourceDeclaration(sourceRel: string, symbol: string): string | null {
  113. const abs = resolve(root, sourceRel)
  114. const text = readFileSync(abs, 'utf8')
  115. const sf = ts.createSourceFile(abs, text, ts.ScriptTarget.Latest, /* setParentNodes */ true)
  116. for (const stmt of sf.statements) {
  117. const named =
  118. ts.isInterfaceDeclaration(stmt) || ts.isTypeAliasDeclaration(stmt)
  119. || ts.isClassDeclaration(stmt) || ts.isEnumDeclaration(stmt)
  120. if (named && stmt.name?.text === symbol) {
  121. return stripExport(stmt.getText(sf))
  122. }
  123. }
  124. return null
  125. }
  126. const manifestRaw = readFileSync(resolve(root, 'scripts/type-equiv.manifest.json'), 'utf8')
  127. const manifest = JSON.parse(manifestRaw) as { entries: ManifestEntry[] }
  128. const entries = manifest.entries
  129. // Key a block/entry by doc + symbol (a symbol may be documented in more than one
  130. // doc, but at most once per doc).
  131. const keyOf = (x: { doc: string; symbol: string }): string => `${x.doc}::${x.symbol}`
  132. // Collect every type-equiv block across ALL docs in scope — not only the docs
  133. // the manifest names — so a block in an unmanifested doc is found and reported
  134. // as an orphan rather than silently skipped.
  135. const docSet = new Set<string>()
  136. for (const pattern of MARKDOWN_GLOBS) {
  137. for await (const match of glob(pattern, { cwd: root })) docSet.add(match)
  138. }
  139. const blocks: EquivBlock[] = [...docSet].sort().flatMap(extractEquivBlocks)
  140. const errors: string[] = []
  141. // A manifest entry naming a doc that does not exist (or is outside the scanned
  142. // scope, so no block could ever match it) is an error in its own right.
  143. for (const d of [...new Set(entries.map(e => e.doc))]) {
  144. if (!existsSync(resolve(root, d))) errors.push(`manifest references ${d}, which does not exist`)
  145. else if (!docSet.has(d)) errors.push(`manifest references ${d}, which is outside the scanned markdown scope (${MARKDOWN_GLOBS.join(', ')})`)
  146. }
  147. // Duplicate-block guard: the same symbol twice in one doc is ambiguous.
  148. const blockByKey = new Map<string, EquivBlock>()
  149. for (const b of blocks) {
  150. const k = keyOf(b)
  151. const prior = blockByKey.get(k)
  152. if (prior) {
  153. errors.push(`duplicate type-equiv block for ${b.symbol} in ${b.doc} (lines ${prior.line} and ${b.line})`)
  154. continue
  155. }
  156. blockByKey.set(k, b)
  157. }
  158. // Duplicate-entry guard in the manifest.
  159. const entryByKey = new Map<string, ManifestEntry>()
  160. for (const e of entries) {
  161. const k = keyOf(e)
  162. if (entryByKey.has(k)) {
  163. errors.push(`duplicate manifest entry for ${e.symbol} in ${e.doc}`)
  164. continue
  165. }
  166. entryByKey.set(k, e)
  167. }
  168. // 1:1 correspondence: orphan blocks (no entry) and orphan entries (no block).
  169. for (const b of blocks) {
  170. if (!entryByKey.has(keyOf(b))) {
  171. errors.push(`type-equiv block ${b.symbol} (${b.doc}:${b.line}) has no manifest entry — add one to scripts/type-equiv.manifest.json`)
  172. }
  173. }
  174. for (const e of entries) {
  175. if (!blockByKey.has(keyOf(e))) {
  176. errors.push(`manifest entry ${e.symbol} (${e.doc}) has no matching type-equiv block — remove it or add the block`)
  177. }
  178. }
  179. // Verbatim check: each matched block must equal its source declaration.
  180. let verified = 0
  181. for (const e of entries) {
  182. const b = blockByKey.get(keyOf(e))
  183. if (!b) continue // already reported as an orphan entry
  184. const decl = sourceDeclaration(e.source, e.symbol)
  185. if (decl === null) {
  186. errors.push(`symbol ${e.symbol} not found in ${e.source} (manifest entry for ${e.doc})`)
  187. continue
  188. }
  189. if (normalize(decl) !== normalize(stripExport(b.code))) {
  190. errors.push(
  191. `DRIFT: ${e.doc}:${b.line} — type-equiv block for ${e.symbol} does not match ${e.source}.\n`
  192. + ` source: ${normalize(decl)}\n`
  193. + ` doc: ${normalize(stripExport(b.code))}`,
  194. )
  195. continue
  196. }
  197. verified++
  198. }
  199. if (errors.length === 0) {
  200. console.log(`verify-type-equiv: ${verified} type-equiv block(s) match source (1:1 with manifest).`)
  201. process.exit(0)
  202. }
  203. console.error('verify-type-equiv: type-equiv verification failed:')
  204. for (const e of errors) console.error(` ${e}`)
  205. console.error(`\n(checked ${blocks.length} block(s) across ${new Set(blocks.map(b => b.doc)).size} doc(s); manifest at scripts/type-equiv.manifest.json)`)
  206. process.exit(1)