verify-type-equiv.ts 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316
  1. /**
  2. * Verify every `ts type-equiv` and `ts public-api` block against the source
  3. * symbol named by the manifest. Ordinary entries preserve the complete
  4. * declaration; `public-api` entries preserve a class's body-stripped public
  5. * declaration. Blocks and entries have a one-to-one relationship; comparison
  6. * ignores whitespace and non-JSDoc comments but preserves declaration
  7. * structure and every original JSDoc comment. Byte-identical `.zh.md` blocks
  8. * reuse the manifest-backed check of their unsuffixed sibling.
  9. */
  10. import { globSync, readFileSync, existsSync } from 'node:fs'
  11. import { resolve, sep } from 'node:path'
  12. import ts from 'typescript'
  13. import { partitionPairedMarkdownDerivatives } from './paired-markdown-derivatives.ts'
  14. const root = resolve(import.meta.dirname, '..')
  15. /** Scan doc-typecheck's full Markdown scope so unmanifested blocks also fail. */
  16. const MARKDOWN_GLOBS = ['README.md', '.agents/notes/**/*.md', 'docs/**/*.md', 'packages/*/*.md', 'packages/*/*/*.md']
  17. /** One manifest entry: a source-equivalence block and its source symbol. */
  18. interface ManifestEntry {
  19. /** Doc file (repo-relative) containing the source-equivalence block. */
  20. doc: string
  21. /** The declared symbol the block must match (e.g. `SessionEvent`). */
  22. symbol: string
  23. /** Source file (repo-relative) that exports the symbol. */
  24. source: string
  25. /** Complete declaration (default), or a body-stripped public class API. */
  26. projection?: 'public-api'
  27. }
  28. /** One extracted ` ```ts type-equiv ` or ` ```ts public-api ` block. */
  29. interface EquivBlock {
  30. doc: string
  31. /** 1-based line of the opening fence (for diagnostics). */
  32. line: number
  33. /** Symbol name parsed from the block's declaration. */
  34. symbol: string
  35. /** Complete declaration (default), or a body-stripped public class API. */
  36. projection?: 'public-api'
  37. /** Block body (the pasted declaration). */
  38. code: string
  39. }
  40. /** Normalize declaration structure independently of comments and whitespace. */
  41. function normalizeStructure(code: string): string {
  42. return code
  43. .replace(/\/\*[\s\S]*?\*\//g, '')
  44. .replace(/(^|[^:])\/\/.*$/gm, '$1')
  45. .replace(/\s+/g, ' ')
  46. .trim()
  47. }
  48. /**
  49. * Extract normalized JSDoc comments in source order. Type declarations in this
  50. * repository do not contain comment delimiters inside string literals.
  51. */
  52. function normalizeJSDoc(code: string): string[] {
  53. return [...code.matchAll(/\/\*\*[\s\S]*?\*\//g)]
  54. .map(match => match[0].replace(/\s+/g, ' ').trim())
  55. }
  56. /** Strip source-only export modifiers. */
  57. function stripExport(code: string): string {
  58. return code.replace(/^export\s+(default\s+)?/, '')
  59. }
  60. /** Parse the declared symbol name from a source-equivalence block body. */
  61. function blockSymbol(code: string): string | null {
  62. const sf = ts.createSourceFile('type-equiv.ts', code, ts.ScriptTarget.Latest, /* setParentNodes */ false, ts.ScriptKind.TS)
  63. for (const stmt of sf.statements) {
  64. const named =
  65. ts.isInterfaceDeclaration(stmt) || ts.isTypeAliasDeclaration(stmt)
  66. || ts.isClassDeclaration(stmt) || ts.isEnumDeclaration(stmt)
  67. if (named && stmt.name) return stmt.name.text
  68. }
  69. return null
  70. }
  71. /** Extract every source-equivalence block from one Markdown file. */
  72. function extractEquivBlocks(docRel: string): EquivBlock[] {
  73. const text = readFileSync(resolve(root, docRel), 'utf8')
  74. const lines = text.split('\n')
  75. const blocks: EquivBlock[] = []
  76. let open: { line: number; body: string[]; projection?: 'public-api' } | null = null
  77. for (let i = 0; i < lines.length; i++) {
  78. const raw = lines[i] ?? ''
  79. const fence = /^```(\s*)(\S.*)?$/.exec(raw)
  80. if (!fence) {
  81. if (open) open.body.push(raw)
  82. continue
  83. }
  84. if (open) {
  85. const code = open.body.join('\n')
  86. const symbol = blockSymbol(code)
  87. if (!symbol) {
  88. throw new Error(`verify-type-equiv: ${docRel}:${open.line} — type-equiv block has no parseable interface/type/class declaration`)
  89. }
  90. blocks.push({
  91. doc: docRel,
  92. line: open.line,
  93. symbol,
  94. code,
  95. ...(open.projection === undefined ? {} : { projection: open.projection }),
  96. })
  97. open = null
  98. continue
  99. }
  100. const info = (fence[2] ?? '').trim()
  101. if (info === 'ts type-equiv public-api') {
  102. throw new Error(`verify-type-equiv: ${docRel}:${i + 1} — use the concise \`ts public-api\` fence`)
  103. }
  104. if (info === 'ts type-equiv') open = { line: i + 1, body: [] }
  105. if (info === 'ts public-api') open = { line: i + 1, body: [], projection: 'public-api' }
  106. }
  107. if (open) throw new Error(`verify-type-equiv: ${docRel}:${open.line} — unterminated type-equiv block`)
  108. return blocks
  109. }
  110. /**
  111. * The declaration text of `symbol` in `sourceRel`, with `export` stripped, or
  112. * null when the symbol is not declared there. Uses the TS parser so it spans
  113. * interfaces, type aliases (including mapped/generic ones), classes, and enums
  114. * uniformly while including declaration and member JSDoc.
  115. */
  116. function sourceDeclaration(sourceRel: string, symbol: string): string | null {
  117. const abs = resolve(root, sourceRel)
  118. const text = readFileSync(abs, 'utf8')
  119. const sf = ts.createSourceFile(abs, text, ts.ScriptTarget.Latest, /* setParentNodes */ true)
  120. for (const stmt of sf.statements) {
  121. const named =
  122. ts.isInterfaceDeclaration(stmt) || ts.isTypeAliasDeclaration(stmt)
  123. || ts.isClassDeclaration(stmt) || ts.isEnumDeclaration(stmt)
  124. if (named && stmt.name?.text === symbol) {
  125. const declarationStart = stmt.getStart(sf)
  126. const jsDoc = ts.getJSDocCommentsAndTags(stmt)
  127. .filter(ts.isJSDoc)
  128. .map(doc => text.slice(doc.pos, doc.end))
  129. .join('\n')
  130. const declaration = stripExport(text.slice(declarationStart, stmt.getEnd()))
  131. return jsDoc === '' ? declaration : `${jsDoc}\n${declaration}`
  132. }
  133. }
  134. return null
  135. }
  136. /** Leading source JSDoc attached to one declaration or member. */
  137. function sourceJSDoc(text: string, node: ts.Node): string {
  138. return ts.getJSDocCommentsAndTags(node)
  139. .filter(ts.isJSDoc)
  140. .map(doc => text.slice(doc.pos, doc.end))
  141. .join('\n')
  142. }
  143. /** Whether a class member is part of its public declaration. */
  144. function isPublicMember(member: ts.ClassElement): boolean {
  145. if (ts.isClassStaticBlockDeclaration(member)) return false
  146. const name = ts.getNameOfDeclaration(member)
  147. if (name && ts.isPrivateIdentifier(name)) return false
  148. const modifiers = ts.canHaveModifiers(member) ? ts.getModifiers(member) : undefined
  149. return !(modifiers?.some(modifier =>
  150. modifier.kind === ts.SyntaxKind.PrivateKeyword
  151. || modifier.kind === ts.SyntaxKind.ProtectedKeyword,
  152. ) ?? false)
  153. }
  154. /** Remove an implementation body while retaining the source signature. */
  155. function bodylessMember(text: string, sf: ts.SourceFile, member: ts.ClassElement): string {
  156. const start = member.getStart(sf)
  157. let end = member.end
  158. if (ts.isConstructorDeclaration(member) || ts.isMethodDeclaration(member)
  159. || ts.isGetAccessorDeclaration(member) || ts.isSetAccessorDeclaration(member)) {
  160. if (member.body) end = member.body.getStart(sf)
  161. }
  162. if (ts.isPropertyDeclaration(member) && member.initializer) end = member.initializer.getStart(sf)
  163. const signature = text.slice(start, end).trimEnd().replace(/;$/, '').replace(/=\s*$/, '').trimEnd()
  164. return `${signature};`
  165. }
  166. /**
  167. * Render a class as an ambient declaration containing only its public fields,
  168. * constructor, accessors, and methods. Implementation bodies and private or
  169. * protected members are deliberately absent; original class/member JSDoc is
  170. * retained so the projection is the source-owned public contract.
  171. */
  172. function sourcePublicApi(sourceRel: string, symbol: string): string | null {
  173. const abs = resolve(root, sourceRel)
  174. const text = readFileSync(abs, 'utf8')
  175. const sf = ts.createSourceFile(abs, text, ts.ScriptTarget.Latest, /* setParentNodes */ true)
  176. for (const stmt of sf.statements) {
  177. if (!ts.isClassDeclaration(stmt) || stmt.name?.text !== symbol) continue
  178. const classDoc = sourceJSDoc(text, stmt)
  179. const abstract = stmt.modifiers?.some(modifier => modifier.kind === ts.SyntaxKind.AbstractKeyword) ? 'abstract ' : ''
  180. const typeParameters = stmt.typeParameters?.map(parameter => parameter.getText(sf)).join(', ')
  181. const heritage = stmt.heritageClauses?.map(clause => clause.getText(sf)).join(' ')
  182. const header = `declare ${abstract}class ${symbol}${typeParameters ? `<${typeParameters}>` : ''}${heritage ? ` ${heritage}` : ''} {`
  183. const members = stmt.members
  184. .filter(isPublicMember)
  185. .map((member) => {
  186. const jsDoc = sourceJSDoc(text, member)
  187. const declaration = bodylessMember(text, sf, member)
  188. return jsDoc === '' ? declaration : `${jsDoc}\n${declaration}`
  189. })
  190. const declaration = [header, ...members.map(member => member.split('\n').map(line => ` ${line}`).join('\n')), '}'].join('\n')
  191. return classDoc === '' ? declaration : `${classDoc}\n${declaration}`
  192. }
  193. return null
  194. }
  195. const manifestRaw = readFileSync(resolve(root, 'scripts/type-equiv.manifest.json'), 'utf8')
  196. const manifest = JSON.parse(manifestRaw) as { entries: ManifestEntry[] }
  197. const entries = manifest.entries
  198. // Key a block/entry by doc + symbol + projection. A symbol may be documented in
  199. // more than one doc, and a doc may carry both complete and projected forms.
  200. const keyOf = (x: { doc: string; symbol: string; projection?: 'public-api' }): string =>
  201. `${x.doc}::${x.symbol}::${x.projection ?? 'declaration'}`
  202. // Collect every type-equiv block across ALL docs in scope — not only the docs
  203. // the manifest names — so a block in an unmanifested doc is found and reported
  204. // as an orphan rather than silently skipped.
  205. const docSet = new Set<string>()
  206. for (const pattern of MARKDOWN_GLOBS) {
  207. for (const match of globSync(pattern, { cwd: root })) docSet.add(match.split(sep).join('/'))
  208. }
  209. const extractedBlocks: EquivBlock[] = [...docSet].sort().flatMap(extractEquivBlocks)
  210. const { primary: blocks, derivatives } = partitionPairedMarkdownDerivatives(
  211. extractedBlocks,
  212. block => block.doc,
  213. block => `${block.projection ?? 'declaration'}\0${block.code}`,
  214. )
  215. const errors: string[] = []
  216. // A manifest entry naming a doc that does not exist (or is outside the scanned
  217. // scope, so no block could ever match it) is an error in its own right.
  218. for (const d of [...new Set(entries.map(e => e.doc))]) {
  219. if (!existsSync(resolve(root, d))) errors.push(`manifest references ${d}, which does not exist`)
  220. else if (!docSet.has(d)) errors.push(`manifest references ${d}, which is outside the scanned markdown scope (${MARKDOWN_GLOBS.join(', ')})`)
  221. }
  222. // Duplicate-block guard: the same projected symbol twice in one doc is ambiguous.
  223. const blockByKey = new Map<string, EquivBlock>()
  224. for (const b of blocks) {
  225. const k = keyOf(b)
  226. const prior = blockByKey.get(k)
  227. if (prior) {
  228. errors.push(`duplicate type-equiv block for ${b.symbol} in ${b.doc} (lines ${prior.line} and ${b.line})`)
  229. continue
  230. }
  231. blockByKey.set(k, b)
  232. }
  233. // Duplicate-entry guard in the manifest.
  234. const entryByKey = new Map<string, ManifestEntry>()
  235. for (const e of entries) {
  236. const k = keyOf(e)
  237. if (entryByKey.has(k)) {
  238. errors.push(`duplicate manifest entry for ${e.symbol} in ${e.doc}`)
  239. continue
  240. }
  241. entryByKey.set(k, e)
  242. }
  243. // 1:1 correspondence: orphan blocks (no entry) and orphan entries (no block).
  244. for (const b of blocks) {
  245. if (!entryByKey.has(keyOf(b))) {
  246. errors.push(`type-equiv block ${b.symbol} (${b.doc}:${b.line}) has no manifest entry — add one to scripts/type-equiv.manifest.json`)
  247. }
  248. }
  249. for (const e of entries) {
  250. if (!blockByKey.has(keyOf(e))) {
  251. errors.push(`manifest entry ${e.symbol} (${e.doc}) has no matching type-equiv block — remove it or add the block`)
  252. }
  253. }
  254. // Verbatim check: each matched block must equal its source declaration.
  255. let verified = 0
  256. for (const e of entries) {
  257. const b = blockByKey.get(keyOf(e))
  258. if (!b) continue // already reported as an orphan entry
  259. const decl = e.projection === 'public-api'
  260. ? sourcePublicApi(e.source, e.symbol)
  261. : sourceDeclaration(e.source, e.symbol)
  262. if (decl === null) {
  263. errors.push(`symbol ${e.symbol} not found in ${e.source} (manifest entry for ${e.doc})`)
  264. continue
  265. }
  266. const doc = stripExport(b.code)
  267. const sourceStructure = normalizeStructure(decl)
  268. const docStructure = normalizeStructure(doc)
  269. const sourceJSDoc = normalizeJSDoc(decl)
  270. const docJSDoc = normalizeJSDoc(doc)
  271. if (sourceStructure !== docStructure || JSON.stringify(sourceJSDoc) !== JSON.stringify(docJSDoc)) {
  272. errors.push(
  273. `DRIFT: ${e.doc}:${b.line} — type-equiv block for ${e.symbol} does not match ${e.source}.\n`
  274. + ` source structure: ${sourceStructure}\n`
  275. + ` doc structure: ${docStructure}\n`
  276. + ` source JSDoc: ${JSON.stringify(sourceJSDoc)}\n`
  277. + ` doc JSDoc: ${JSON.stringify(docJSDoc)}`,
  278. )
  279. continue
  280. }
  281. verified++
  282. }
  283. if (errors.length === 0) {
  284. console.log(`verify-type-equiv: ${verified} type-equiv block(s) match source structure and JSDoc (1:1 with manifest); ${derivatives.length} paired derivative(s).`)
  285. process.exit(0)
  286. }
  287. console.error('verify-type-equiv: type-equiv verification failed:')
  288. for (const e of errors) console.error(` ${e}`)
  289. console.error(`\n(checked ${blocks.length} primary block(s) across ${new Set(blocks.map(b => b.doc)).size} doc(s), ${derivatives.length} paired derivative(s); manifest at scripts/type-equiv.manifest.json)`)
  290. process.exit(1)