verify-type-equiv.ts 16 KB

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