persistence-catalog-source.ts 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307
  1. /** Source discovery and declaration validation shared by persistence documentation and schemas. */
  2. import { globSync, readFileSync } from 'node:fs'
  3. import { resolve, sep } from 'node:path'
  4. import ts from 'typescript'
  5. import { parseJsDoc, pointer, rawJsDoc, reportViolations } from './jsdoc.ts'
  6. const root = resolve(import.meta.dirname, '..')
  7. /** The package that owns the durable event vocabulary. */
  8. const SESSION_PACKAGE = '@deepseek-ai/dsh-session'
  9. /** The type-only module that plugin declaration merges augment. */
  10. const SESSION_TYPES_MODULE = '@deepseek-ai/dsh-session/types'
  11. /** Event-envelope declarations rendered before the per-event vocabulary. */
  12. const EVENT_ENVELOPE_TYPE_NAMES = [
  13. 'SessionEventType',
  14. 'SurfaceEventType',
  15. 'SurfaceOp',
  16. 'SessionEvent',
  17. ] as const
  18. type EventEnvelopeTypeName = typeof EVENT_ENVELOPE_TYPE_NAMES[number]
  19. /** One log event, extracted from a `SessionEventMap` declaration. */
  20. export interface LogEventEntry {
  21. /** Scoped name, e.g. `turn/start`. */
  22. name: string
  23. /** The scope prefix, e.g. `turn` (everything before the first `/`). */
  24. scope: string
  25. /** Payload type text (the member's type annotation, whitespace-collapsed). */
  26. payload: string
  27. /** Source member declaration and complete JSDoc, dedented from its container. */
  28. declaration: string
  29. /** Description prose (the member's JSDoc), one line per paragraph. */
  30. doc: string
  31. /** Source pointer `packages/…/file.ts:line` of the declaration. */
  32. source: string
  33. /** Whether interpretation requires a plugin-owned message projection. */
  34. messageProjection?: true
  35. }
  36. /** A {@link LogEventEntry} plus its surface-eligibility badge. */
  37. export interface AnnotatedLogEventEntry extends LogEventEntry {
  38. /** Whether the type is a `SurfaceEventType` member (may carry `surfaceOp`). */
  39. surface: boolean
  40. }
  41. /** One owning event-envelope declaration pasted into the generated catalog. */
  42. export interface EventEnvelopeTypeEntry {
  43. /** Exported declaration name. */
  44. name: EventEnvelopeTypeName
  45. /** Verbatim type declaration, including its complete leading JSDoc. */
  46. declaration: string
  47. /** Source pointer `packages/…/file.ts:line` of the declaration. */
  48. source: string
  49. }
  50. const printer = ts.createPrinter({ removeComments: true })
  51. /**
  52. * Render a member type on one line through the TypeScript printer, which adds
  53. * semicolon separators. Drop its trailing semicolon before `}` to match the
  54. * repository's inline-literal style.
  55. */
  56. function payloadText(type: ts.TypeNode, sf: ts.SourceFile): string {
  57. return printer.printNode(ts.EmitHint.Unspecified, type, sf)
  58. .replace(/\s+/g, ' ')
  59. .replace(/;\s*\}/g, ' }')
  60. .trim()
  61. }
  62. /**
  63. * Copy a declaration from its leading JSDoc through its closing token while
  64. * removing only the indentation imposed by its containing interface/module.
  65. */
  66. function declarationText(text: string, sf: ts.SourceFile, node: ts.Node): string {
  67. const raw = rawJsDoc(text, node)
  68. const nodeStart = node.getStart(sf)
  69. const start = raw ? text.lastIndexOf(raw, nodeStart) : nodeStart
  70. const { line } = sf.getLineAndCharacterOfPosition(start)
  71. const lineStart = sf.getPositionOfLineAndCharacter(line, 0)
  72. const indent = text.slice(lineStart, start)
  73. return text.slice(lineStart, node.end)
  74. .split('\n')
  75. .map(lineText => lineText.startsWith(indent) ? lineText.slice(indent.length) : lineText)
  76. .join('\n')
  77. .trimEnd()
  78. }
  79. /**
  80. * Every `interface SessionEventMap` declaration in a source file: the owning
  81. * top-level declaration (in `@deepseek-ai/dsh-session`) and any declaration
  82. * merge inside a `declare module '@deepseek-ai/dsh-session/types'` block. Both forms
  83. * declare members of the SAME merged interface, so both are catalogued
  84. * uniformly. `topLevel` distinguishes the owning form so the caller can verify
  85. * it actually lives in the owning package — an unrelated local interface that
  86. * happens to share the name must not be catalogued as the on-disk vocabulary.
  87. */
  88. function sessionEventMapDecls(sf: ts.SourceFile): { decl: ts.InterfaceDeclaration; topLevel: boolean }[] {
  89. const decls: { decl: ts.InterfaceDeclaration; topLevel: boolean }[] = []
  90. for (const stmt of sf.statements) {
  91. if (ts.isInterfaceDeclaration(stmt) && stmt.name.text === 'SessionEventMap') decls.push({ decl: stmt, topLevel: true })
  92. if (ts.isModuleDeclaration(stmt) && ts.isStringLiteral(stmt.name) && stmt.name.text === SESSION_TYPES_MODULE
  93. && stmt.body && ts.isModuleBlock(stmt.body)) {
  94. for (const inner of stmt.body.statements) {
  95. if (ts.isInterfaceDeclaration(inner) && inner.name.text === 'SessionEventMap') decls.push({ decl: inner, topLevel: false })
  96. }
  97. }
  98. }
  99. return decls
  100. }
  101. /**
  102. * The npm package name owning a `packages/<group>/<pkg>/…` source file, read
  103. * from that package's manifest — or null when the manifest is missing or
  104. * unparseable (the caller treats null as "ownership unverifiable").
  105. */
  106. function packageNameFor(rel: string, scanRoot: string): string | null {
  107. const dir = rel.split('/').slice(0, 3).join('/')
  108. try {
  109. const manifest = JSON.parse(readFileSync(resolve(scanRoot, dir, 'package.json'), 'utf8')) as { name?: string }
  110. return typeof manifest.name === 'string' ? manifest.name : null
  111. } catch {
  112. // Missing or malformed package.json — every real workspace package has one,
  113. // so this only arises in stripped-down fixture trees; either way ownership
  114. // cannot be verified and the caller reports the declaration.
  115. return null
  116. }
  117. }
  118. /**
  119. * Collect every `SessionEventMap` merge, rejecting inherited, non-literal,
  120. * untyped, undocumented, duplicate, or incorrectly owned members in one report.
  121. */
  122. export function collectLogEvents(scanRoot: string = root): LogEventEntry[] {
  123. const entries: LogEventEntry[] = []
  124. const violations: string[] = []
  125. const seen = new Map<string, string>()
  126. let owningDecl: string | null = null
  127. for (const rel of globSync('packages/*/*/src/**/*.{ts,tsx}', { cwd: scanRoot }).map(s => s.split(sep).join('/')).sort()) {
  128. const abs = resolve(scanRoot, rel)
  129. const text = readFileSync(abs, 'utf8')
  130. if (!text.includes('SessionEventMap')) continue
  131. const sf = ts.createSourceFile(abs, text, ts.ScriptTarget.Latest, true)
  132. for (const { decl, topLevel } of sessionEventMapDecls(sf)) {
  133. const declSrc = pointer(rel, sf, decl)
  134. if (topLevel) {
  135. // The top-level form has one home: the single exported declaration in
  136. // the owning package. Same-named interfaces elsewhere are different
  137. // types and must not enter the on-disk catalog.
  138. const pkg = packageNameFor(rel, scanRoot)
  139. if (pkg !== SESSION_PACKAGE) {
  140. violations.push(`top-level interface SessionEventMap (${declSrc}) is outside ${SESSION_PACKAGE} (package ${pkg ?? 'unknown'}). Rename the interface, or contribute events via declare module '${SESSION_TYPES_MODULE}'.`)
  141. continue
  142. }
  143. const exported = decl.modifiers?.some(m => m.kind === ts.SyntaxKind.ExportKeyword) ?? false
  144. if (!exported) {
  145. violations.push(`top-level interface SessionEventMap (${declSrc}) is not exported; the owning vocabulary is the single exported declaration — rename a local helper interface.`)
  146. continue
  147. }
  148. if (owningDecl) {
  149. violations.push(`top-level interface SessionEventMap (${declSrc}) is already declared at ${owningDecl}; the owning vocabulary has exactly one home.`)
  150. continue
  151. }
  152. owningDecl = declSrc
  153. }
  154. if (decl.heritageClauses?.length) {
  155. violations.push(`SessionEventMap declaration (${declSrc}) uses extends; inherited keys would join keyof SessionEventMap without a catalog row — declare event members directly.`)
  156. }
  157. for (const member of decl.members) {
  158. const src = pointer(rel, sf, member)
  159. if (!ts.isPropertySignature(member) || !member.type) {
  160. // A method-form or type-less member still joins `keyof SessionEventMap`,
  161. // so skipping it silently would be exactly the undocumented-event hole
  162. // this catalog exists to close.
  163. const label = (member as { name?: ts.Node }).name?.getText(sf) ?? member.getText(sf).replace(/\s+/g, ' ')
  164. violations.push(`SessionEventMap member ${label} (${src}) is not a property signature with an explicit payload type; declare every log event as 'scope/name': <payload>.`)
  165. continue
  166. }
  167. if (!ts.isStringLiteral(member.name)) {
  168. violations.push(`log event at ${src} has a non-literal name; the catalog needs string-literal event names.`)
  169. continue
  170. }
  171. const name = member.name.text
  172. const where = `log event '${name}' (${src})`
  173. const prior = seen.get(name)
  174. if (prior) {
  175. violations.push(`${where} is already declared at ${prior}; an event type has exactly one declaration.`)
  176. continue
  177. }
  178. seen.set(name, src)
  179. const payload = payloadText(member.type, sf)
  180. const { doc, hasMode } = parseJsDoc(rawJsDoc(text, member))
  181. if (hasMode) {
  182. violations.push(`${where} carries an @mode tag, but a log event has no dispatch mode (it is not a cordis bus event — it rides the 'session/event' emit). Remove the tag.`)
  183. }
  184. if (!doc) {
  185. violations.push(`${where} has no description prose. Say what the event records and what its payload means — the JSDoc becomes the catalog entry.`)
  186. }
  187. const declaration = declarationText(text, sf, member)
  188. const messageProjection = ts.getJSDocTags(member).some(tag => tag.tagName.text === 'messageProjection')
  189. entries.push({ name, scope: name.split('/')[0] ?? name, payload, declaration, doc, source: src, ...messageProjection ? { messageProjection: true as const } : {} })
  190. }
  191. }
  192. }
  193. reportViolations('gen-persistence-catalog', violations)
  194. return entries
  195. }
  196. /**
  197. * Collect the exported declarations that compose the persisted event envelope,
  198. * preserving their source JSDoc and declaration text.
  199. */
  200. export function collectEventEnvelopeTypes(scanRoot: string = root): EventEnvelopeTypeEntry[] {
  201. const found = new Map<EventEnvelopeTypeName, EventEnvelopeTypeEntry>()
  202. const violations: string[] = []
  203. const wanted = new Set<string>(EVENT_ENVELOPE_TYPE_NAMES)
  204. for (const rel of globSync('packages/*/*/src/**/*.{ts,tsx}', { cwd: scanRoot }).map(s => s.split(sep).join('/')).sort()) {
  205. const abs = resolve(scanRoot, rel)
  206. const text = readFileSync(abs, 'utf8')
  207. if (!EVENT_ENVELOPE_TYPE_NAMES.some(name => text.includes(name))) continue
  208. if (packageNameFor(rel, scanRoot) !== SESSION_PACKAGE) continue
  209. const sf = ts.createSourceFile(abs, text, ts.ScriptTarget.Latest, true)
  210. for (const stmt of sf.statements) {
  211. if (!ts.isTypeAliasDeclaration(stmt) || !wanted.has(stmt.name.text)) continue
  212. const name = stmt.name.text as EventEnvelopeTypeName
  213. const src = pointer(rel, sf, stmt)
  214. const where = `event-envelope type '${name}' (${src})`
  215. const prior = found.get(name)
  216. if (prior) {
  217. violations.push(`${where} is already declared at ${prior.source}; the persisted envelope type has exactly one owner.`)
  218. continue
  219. }
  220. if (!(stmt.modifiers?.some(m => m.kind === ts.SyntaxKind.ExportKeyword) ?? false)) {
  221. violations.push(`${where} is not exported.`)
  222. }
  223. const { doc, hasMode } = parseJsDoc(rawJsDoc(text, stmt))
  224. if (hasMode) violations.push(`${where} carries an @mode tag, but a persisted type has no dispatch mode.`)
  225. if (!doc) violations.push(`${where} has no description prose. The full JSDoc is part of the generated catalog.`)
  226. found.set(name, { name, declaration: declarationText(text, sf, stmt), source: src })
  227. }
  228. }
  229. const missing = EVENT_ENVELOPE_TYPE_NAMES.filter(name => !found.has(name))
  230. if (missing.length > 0) {
  231. violations.push(`missing event-envelope declaration(s): ${missing.join(', ')}.`)
  232. }
  233. reportViolations('gen-persistence-catalog', violations)
  234. return EVENT_ENVELOPE_TYPE_NAMES.map((name) => {
  235. const entry = found.get(name)
  236. if (!entry) throw new Error(`gen-persistence-catalog: missing checked event-envelope declaration '${name}'.`)
  237. return entry
  238. })
  239. }
  240. /**
  241. * Parse the `SurfaceEventType` union — the surface-eligible subset of event
  242. * types — from source. Hard-errors when the alias is missing, declared more
  243. * than once, or contains a non-string-literal member: the badge derivation
  244. * relies on the union being a closed set of literal event names.
  245. * `scanRoot` defaults to the repo root; tests pass a fixture dir.
  246. */
  247. export function collectSurfaceEventTypes(scanRoot: string = root): string[] {
  248. const found: { names: string[]; source: string }[] = []
  249. for (const rel of globSync('packages/*/*/src/**/*.{ts,tsx}', { cwd: scanRoot }).map(s => s.split(sep).join('/')).sort()) {
  250. const abs = resolve(scanRoot, rel)
  251. const text = readFileSync(abs, 'utf8')
  252. if (!text.includes('SurfaceEventType')) continue
  253. const sf = ts.createSourceFile(abs, text, ts.ScriptTarget.Latest, true)
  254. for (const stmt of sf.statements) {
  255. if (!ts.isTypeAliasDeclaration(stmt) || stmt.name.text !== 'SurfaceEventType') continue
  256. const src = pointer(rel, sf, stmt)
  257. const members = ts.isUnionTypeNode(stmt.type) ? [...stmt.type.types] : [stmt.type]
  258. const names: string[] = []
  259. for (const m of members) {
  260. if (ts.isLiteralTypeNode(m) && ts.isStringLiteral(m.literal)) names.push(m.literal.text)
  261. else throw new Error(`gen-persistence-catalog: SurfaceEventType (${src}) has a non-string-literal member; the badge derivation needs a closed literal union.`)
  262. }
  263. found.push({ names, source: src })
  264. }
  265. }
  266. const only = found[0]
  267. if (!only) throw new Error('gen-persistence-catalog: no SurfaceEventType union found under packages/*/*/src.')
  268. if (found.length > 1) throw new Error(`gen-persistence-catalog: SurfaceEventType is declared more than once (${found.map(f => f.source).join(', ')}); the surface subset has exactly one owner.`)
  269. return only.names
  270. }
  271. /**
  272. * Attach the surface/log-only badge to each event. Hard-errors when a
  273. * `SurfaceEventType` union member names no collected event — a stale union
  274. * member would otherwise silently badge nothing.
  275. */
  276. export function annotateSurface(events: LogEventEntry[], surfaceTypes: string[]): AnnotatedLogEventEntry[] {
  277. const names = new Set(events.map(e => e.name))
  278. const stale = surfaceTypes.filter(t => !names.has(t))
  279. if (stale.length > 0) {
  280. throw new Error(`gen-persistence-catalog: SurfaceEventType member(s) ${stale.map(t => `'${t}'`).join(', ')} name no declared log event (stale union member?).`)
  281. }
  282. const surface = new Set(surfaceTypes)
  283. for (const event of events) {
  284. if (event.messageProjection && surface.has(event.name)) {
  285. throw new Error(`gen-persistence-catalog: '${event.name}' cannot declare both a message projection and surface operations.`)
  286. }
  287. }
  288. return events.map(e => ({ ...e, surface: surface.has(e.name) }))
  289. }