cordis-core-api.ts 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433
  1. /** Generate detailed Cordis core API pages from pinned vendor declarations. */
  2. import { readFileSync } from 'node:fs'
  3. import { resolve } from 'node:path'
  4. import ts from 'typescript'
  5. import { checkParams, checkReturns, parseJsDoc, parseTags, pointer, rawJsDoc, reportViolations } from './jsdoc.ts'
  6. import { cordisModuleBody } from './cordis-walk.ts'
  7. const root = resolve(import.meta.dirname, '..')
  8. const FENCE = 'ts cordis-catalog'
  9. /** One declaration group rendered on a Cordis core API page. */
  10. type CordisCoreApiSection =
  11. | { kind: 'class'; file: string; symbol: string; prefix?: string; heading?: string }
  12. | { kind: 'context-merge'; file: string; heading?: string }
  13. | { kind: 'decl'; file: string; symbol: string }
  14. /** One generated Cordis core API page. */
  15. export interface CordisCoreApiPage {
  16. out: string
  17. title: string
  18. intro: string
  19. sections: CordisCoreApiSection[]
  20. }
  21. /** Explicit editorial grouping for the pinned Cordis core API. */
  22. export const CORDIS_CORE_API_PAGES: CordisCoreApiPage[] = [
  23. {
  24. out: 'docs/cordis-api/context.md',
  25. title: 'Context',
  26. intro: 'The context is the core Cordis object: every service, event, and lifecycle API is reached through `ctx`. Event methods are documented on [Events](events.md), effects and the current fiber on [Fiber](fiber.md), and plugin loading on [Registry](registry.md).',
  27. sections: [
  28. { kind: 'class', file: 'vendor/cordis/src/context.ts', symbol: 'Context', prefix: 'ctx.' },
  29. { kind: 'context-merge', file: 'vendor/cordis/src/reflect.ts', heading: 'Service store and mixins' },
  30. ],
  31. },
  32. {
  33. out: 'docs/cordis-api/events.md',
  34. title: 'Events',
  35. intro: 'The event-dispatch API mixed into every context. Harness event declarations and their dispatch modes are generated into each owning [subsystem page](../subsystems/core.md).',
  36. sections: [
  37. { kind: 'context-merge', file: 'vendor/cordis/src/events.ts' },
  38. { kind: 'decl', file: 'vendor/cordis/src/events.ts', symbol: 'EventOptions' },
  39. { kind: 'decl', file: 'vendor/cordis/src/events.ts', symbol: 'DispatchMode' },
  40. ],
  41. },
  42. {
  43. out: 'docs/cordis-api/fiber.md',
  44. title: 'Fiber',
  45. intro: 'A fiber is one loaded plugin instance: its lifecycle state, validated config, and registered effects. `ctx.fiber` is the current fiber, and `ctx.effect()` delegates to it.',
  46. sections: [
  47. { kind: 'context-merge', file: 'vendor/cordis/src/fiber.ts' },
  48. { kind: 'class', file: 'vendor/cordis/src/fiber.ts', symbol: 'Fiber', heading: 'The Fiber class' },
  49. { kind: 'decl', file: 'vendor/cordis/src/fiber.ts', symbol: 'Effect' },
  50. { kind: 'decl', file: 'vendor/cordis/src/fiber.ts', symbol: 'Disposable' },
  51. { kind: 'decl', file: 'vendor/cordis/src/fiber.ts', symbol: 'EffectMeta' },
  52. { kind: 'decl', file: 'vendor/cordis/src/fiber.ts', symbol: 'CordisError' },
  53. { kind: 'decl', file: 'vendor/cordis/src/fiber.ts', symbol: 'ValidationError' },
  54. ],
  55. },
  56. {
  57. out: 'docs/cordis-api/registry.md',
  58. title: 'Registry',
  59. intro: 'Plugin loading and dependency injection.',
  60. sections: [
  61. { kind: 'context-merge', file: 'vendor/cordis/src/registry.ts' },
  62. { kind: 'decl', file: 'vendor/cordis/src/registry.ts', symbol: 'Plugin' },
  63. { kind: 'decl', file: 'vendor/cordis/src/registry.ts', symbol: 'Inject' },
  64. ],
  65. },
  66. {
  67. out: 'docs/cordis-api/service.md',
  68. title: 'Service',
  69. intro: 'The base class for context services. A subclass loaded as a plugin registers itself as `ctx.<name>`.',
  70. sections: [
  71. { kind: 'class', file: 'vendor/cordis/src/service.ts', symbol: 'Service' },
  72. ],
  73. },
  74. ]
  75. interface MemberDoc {
  76. name: string
  77. heading: string
  78. signatures: string[]
  79. jsDoc: string
  80. doc: string
  81. params: { name: string; text: string }[]
  82. returns: string | null
  83. source: string
  84. }
  85. interface RenderContext {
  86. scanRoot: string
  87. cache: Map<string, { sf: ts.SourceFile; text: string }>
  88. violations: string[]
  89. }
  90. function load(ctx: RenderContext, rel: string): { sf: ts.SourceFile; text: string } {
  91. const cached = ctx.cache.get(rel)
  92. if (cached !== undefined) return cached
  93. const text = readFileSync(resolve(ctx.scanRoot, rel), 'utf8')
  94. const entry = { sf: ts.createSourceFile(rel, text, ts.ScriptTarget.Latest, true), text }
  95. ctx.cache.set(rel, entry)
  96. return entry
  97. }
  98. function sourceJsDoc(text: string, sf: ts.SourceFile, node: ts.Node): string {
  99. const raw = rawJsDoc(text, node)
  100. if (raw === '') return ''
  101. const { line } = sf.getLineAndCharacterOfPosition(node.getStart(sf))
  102. const lineStart = sf.getPositionOfLineAndCharacter(line, 0)
  103. const indent = text.slice(lineStart, node.getStart(sf))
  104. return raw.split('\n')
  105. .map((sourceLine, index) => index > 0 && sourceLine.startsWith(indent)
  106. ? sourceLine.slice(indent.length)
  107. : sourceLine)
  108. .join('\n')
  109. }
  110. function signatureOf(member: ts.Node, sf: ts.SourceFile): string {
  111. const full = member.getText(sf)
  112. const tail = (member as { body?: ts.Node; initializer?: ts.Node }).body
  113. ?? (member as { initializer?: ts.Node }).initializer
  114. const signature = tail
  115. ? full.slice(0, full.length - tail.getText(sf).length).replace(/[=\s]+$/, '')
  116. : full
  117. return signature.replace(/\s*;?\s*$/, '').replace(/\s+/g, ' ').trim()
  118. }
  119. function headingParams(parameters: readonly ts.ParameterDeclaration[], sf: ts.SourceFile): string {
  120. const names = parameters
  121. .filter(parameter => !(ts.isIdentifier(parameter.name) && parameter.name.text === 'this'))
  122. .map((parameter) => {
  123. const rest = parameter.dotDotDotToken ? '...' : ''
  124. const optional = parameter.questionToken || parameter.initializer ? '?' : ''
  125. return `${rest}${parameter.name.getText(sf)}${optional}`
  126. })
  127. return `(${names.join(', ')})`
  128. }
  129. function isPublicInstance(member: ts.ClassElement): boolean {
  130. const modifiers = ts.getCombinedModifierFlags(member)
  131. if (modifiers & (ts.ModifierFlags.Private | ts.ModifierFlags.Protected | ts.ModifierFlags.Static)) return false
  132. if (!member.name || ts.isComputedPropertyName(member.name) || ts.isPrivateIdentifier(member.name)) return false
  133. return !member.name.getText().startsWith('_')
  134. }
  135. function isPublicStatic(member: ts.ClassElement): boolean {
  136. const modifiers = ts.getCombinedModifierFlags(member)
  137. if (modifiers & (ts.ModifierFlags.Private | ts.ModifierFlags.Protected)) return false
  138. if (!(modifiers & ts.ModifierFlags.Static)) return false
  139. if (!member.name || ts.isComputedPropertyName(member.name) || ts.isPrivateIdentifier(member.name)) return false
  140. return !member.name.getText().startsWith('_')
  141. }
  142. type Member = ts.MethodDeclaration
  143. | ts.MethodSignature
  144. | ts.PropertyDeclaration
  145. | ts.PropertySignature
  146. | ts.GetAccessorDeclaration
  147. function memberDoc(ctx: RenderContext, where: string, name: string, group: Member[], rel: string): MemberDoc {
  148. const { sf, text } = load(ctx, rel)
  149. const first = group[0]
  150. if (first === undefined) throw new Error(`cordis-core-api: empty member group for ${name}.`)
  151. const rawDocs = group.map(member => sourceJsDoc(text, sf, member))
  152. const docIndex = rawDocs.findIndex(raw => parseJsDoc(raw).doc !== '')
  153. const raw = docIndex === -1 ? '' : (rawDocs[docIndex] ?? '')
  154. const doc = parseJsDoc(raw).doc
  155. if (doc === '') ctx.violations.push(`${where} has no JSDoc prose.`)
  156. const { params: tags, returns } = parseTags(raw)
  157. const functionMembers = group.filter((member): member is ts.MethodDeclaration | ts.MethodSignature =>
  158. ts.isMethodDeclaration(member) || ts.isMethodSignature(member))
  159. const docCarrier = functionMembers[docIndex === -1 ? 0 : docIndex]
  160. const params: { name: string; text: string }[] = []
  161. if (docCarrier !== undefined) {
  162. checkParams(where, 'cordis-core-api', docCarrier.parameters, tags, sf,
  163. parameter => ts.isIdentifier(parameter.name) && parameter.name.text === 'this', ctx.violations)
  164. if (docCarrier.type !== undefined) {
  165. checkReturns(where, docCarrier.type, returns, sf, ctx.violations)
  166. } else if (returns === null && ts.isMethodDeclaration(docCarrier)) {
  167. ctx.violations.push(`${where} has no return type annotation; document the result with @returns.`)
  168. }
  169. for (const parameter of docCarrier.parameters) {
  170. if (!ts.isIdentifier(parameter.name) || parameter.name.text === 'this') continue
  171. const text = tags.get(parameter.name.text)
  172. if (text !== undefined) params.push({ name: parameter.name.text, text })
  173. }
  174. }
  175. const headingSource = docCarrier ?? functionMembers[0]
  176. const signatures = ts.isMethodDeclaration(first) && functionMembers.length > 1
  177. ? functionMembers.filter(member => ts.isMethodDeclaration(member) && member.body === undefined)
  178. : group
  179. return {
  180. name,
  181. heading: headingSource === undefined ? '' : headingParams(headingSource.parameters, sf),
  182. signatures: signatures.map(member => signatureOf(member, sf)),
  183. jsDoc: raw,
  184. doc,
  185. params,
  186. returns,
  187. source: pointer(rel, sf, first),
  188. }
  189. }
  190. function heritageMembers(
  191. statement: ts.InterfaceDeclaration,
  192. sf: ts.SourceFile,
  193. groups: Map<string, (ts.MethodSignature | ts.PropertySignature | ts.MethodDeclaration)[]>,
  194. ): void {
  195. for (const clause of statement.heritageClauses ?? []) {
  196. for (const type of clause.types) {
  197. if (!ts.isIdentifier(type.expression) || type.expression.text !== 'Pick') continue
  198. const [target, keys] = type.typeArguments ?? []
  199. if (target === undefined || keys === undefined || !ts.isTypeReferenceNode(target)) continue
  200. const targetName = target.typeName.getText(sf)
  201. const cls = sf.statements.find(
  202. (entry): entry is ts.ClassDeclaration => ts.isClassDeclaration(entry) && entry.name?.text === targetName,
  203. )
  204. if (cls === undefined) continue
  205. const picked = new Set<string>()
  206. const collect = (node: ts.TypeNode): void => {
  207. if (ts.isLiteralTypeNode(node) && ts.isStringLiteral(node.literal)) picked.add(node.literal.text)
  208. if (ts.isUnionTypeNode(node)) node.types.forEach(collect)
  209. }
  210. collect(keys)
  211. for (const member of cls.members) {
  212. if (!ts.isMethodDeclaration(member)) continue
  213. const name = member.name.getText(sf)
  214. if (!picked.has(name)) continue
  215. const group = groups.get(name) ?? []
  216. group.push(member)
  217. groups.set(name, group)
  218. }
  219. }
  220. }
  221. }
  222. function contextMergeMembers(ctx: RenderContext, rel: string): MemberDoc[] {
  223. const { sf } = load(ctx, rel)
  224. const body = cordisModuleBody(sf)
  225. if (body === null) throw new Error(`cordis-core-api: ${rel} has no Context module merge.`)
  226. const groups = new Map<string, (ts.MethodSignature | ts.PropertySignature | ts.MethodDeclaration)[]>()
  227. for (const statement of body.statements) {
  228. if (!ts.isInterfaceDeclaration(statement) || statement.name.text !== 'Context') continue
  229. heritageMembers(statement, sf, groups)
  230. for (const member of statement.members) {
  231. if (!ts.isMethodSignature(member) && !ts.isPropertySignature(member)) continue
  232. if (ts.isComputedPropertyName(member.name)) continue
  233. const name = member.name.getText(sf)
  234. const group = groups.get(name) ?? []
  235. group.push(member)
  236. groups.set(name, group)
  237. }
  238. }
  239. return [...groups.entries()].map(([name, group]) =>
  240. memberDoc(ctx, `ctx.${name} (${rel})`, name, group, rel))
  241. }
  242. function classMembers(ctx: RenderContext, rel: string, className: string): {
  243. doc: string
  244. instance: MemberDoc[]
  245. statics: MemberDoc[]
  246. source: string
  247. } {
  248. const { sf, text } = load(ctx, rel)
  249. const cls = sf.statements.find(
  250. (statement): statement is ts.ClassDeclaration =>
  251. ts.isClassDeclaration(statement) && statement.name?.text === className,
  252. )
  253. if (cls === undefined) throw new Error(`cordis-core-api: class ${className} not found in ${rel}.`)
  254. const doc = parseJsDoc(rawJsDoc(text, cls)).doc
  255. if (doc === '') ctx.violations.push(`class ${className} (${pointer(rel, sf, cls)}) has no JSDoc.`)
  256. const instance = new Map<string, Member[]>()
  257. const statics = new Map<string, Member[]>()
  258. for (const member of cls.members) {
  259. if (!ts.isMethodDeclaration(member) && !ts.isPropertyDeclaration(member) && !ts.isGetAccessorDeclaration(member)) continue
  260. const name = member.name.getText(sf)
  261. if (isPublicInstance(member)) {
  262. const group = instance.get(name) ?? []
  263. group.push(member)
  264. instance.set(name, group)
  265. } else if (isPublicStatic(member) && !ts.isGetAccessorDeclaration(member)) {
  266. const group = statics.get(name) ?? []
  267. group.push(member)
  268. statics.set(name, group)
  269. }
  270. }
  271. const declaration = sf.statements.find(
  272. (statement): statement is ts.InterfaceDeclaration =>
  273. ts.isInterfaceDeclaration(statement) && statement.name.text === className,
  274. )
  275. for (const member of declaration?.members ?? []) {
  276. if (!ts.isPropertySignature(member) || ts.isComputedPropertyName(member.name)) continue
  277. const name = member.name.getText(sf)
  278. const group = instance.get(name) ?? []
  279. group.push(member)
  280. instance.set(name, group)
  281. }
  282. const render = (groups: Map<string, Member[]>, prefix: string): MemberDoc[] =>
  283. [...groups.entries()].map(([name, group]) => memberDoc(ctx, `${prefix}${name} (${rel})`, name, group, rel))
  284. return {
  285. doc,
  286. instance: render(instance, `${className}#`),
  287. statics: render(statics, `${className}.`),
  288. source: pointer(rel, sf, cls),
  289. }
  290. }
  291. function stripBodies(node: ts.Node, sf: ts.SourceFile): string {
  292. const cuts: { start: number; end: number }[] = []
  293. const visit = (entry: ts.Node): void => {
  294. const functionLike = ts.isMethodDeclaration(entry)
  295. || ts.isConstructorDeclaration(entry)
  296. || ts.isFunctionDeclaration(entry)
  297. || ts.isGetAccessorDeclaration(entry)
  298. || ts.isSetAccessorDeclaration(entry)
  299. if (functionLike && entry.body !== undefined) {
  300. const signatureEnd = (entry.type ?? entry.parameters.at(-1) ?? entry).getEnd()
  301. cuts.push({ start: signatureEnd, end: entry.body.getEnd() })
  302. return
  303. }
  304. entry.forEachChild(visit)
  305. }
  306. visit(node)
  307. const base = node.getStart(sf)
  308. let output = node.getText(sf)
  309. for (const cut of cuts.sort((left, right) => right.start - left.start)) {
  310. const head = output.slice(0, cut.start - base)
  311. const between = output.slice(cut.start - base, cut.end - base)
  312. const bodyBrace = between.indexOf('{')
  313. output = head + between.slice(0, bodyBrace).trimEnd() + output.slice(cut.end - base)
  314. }
  315. return output
  316. }
  317. function declarationPaste(ctx: RenderContext, rel: string, symbol: string): { doc: string; code: string; source: string } {
  318. const { sf, text } = load(ctx, rel)
  319. const matches = sf.statements.filter((statement) => {
  320. const named = ts.isInterfaceDeclaration(statement)
  321. || ts.isTypeAliasDeclaration(statement)
  322. || ts.isClassDeclaration(statement)
  323. || ts.isEnumDeclaration(statement)
  324. || ts.isModuleDeclaration(statement)
  325. return named && statement.name?.getText(sf) === symbol
  326. })
  327. const first = matches[0]
  328. if (first === undefined) throw new Error(`cordis-core-api: declaration ${symbol} not found in ${rel}.`)
  329. const doc = parseJsDoc(sourceJsDoc(text, sf, first)).doc
  330. const code = matches.map((statement) => {
  331. const jsDoc = sourceJsDoc(text, sf, statement)
  332. const declaration = stripBodies(statement, sf).replace(/^export\s+(default\s+)?/, '')
  333. return jsDoc === '' ? declaration : `${jsDoc}\n${declaration}`
  334. }).join('\n\n')
  335. return { doc, code, source: pointer(rel, sf, first) }
  336. }
  337. function sourceLink(source: string): string {
  338. const [file, line] = source.split(':')
  339. return `[Source](../../${file}${line === undefined ? '' : `#L${line}`})`
  340. }
  341. function unlink(text: string): string {
  342. return text.replace(/\{@link\s+([^}|\s]+)\s*(?:[|\s]\s*([^}]*))?\}/g, (_match, target: string, label?: string) => {
  343. const name = label?.trim()
  344. return name && name !== '' ? name : `\`${target}\``
  345. })
  346. }
  347. function prose(doc: string): string[] {
  348. const paragraphs = unlink(doc)
  349. .split(/\n\s*\n/)
  350. .map(paragraph => paragraph.replace(/\s*\n\s*/g, ' ').trim())
  351. .filter(paragraph => paragraph !== '')
  352. return paragraphs.flatMap((paragraph, index) => index === 0 ? [paragraph] : ['', paragraph])
  353. }
  354. function renderMember(prefix: string, member: MemberDoc): string[] {
  355. const lines = [`### ${prefix}${member.name}${member.heading}`, '', `\`\`\`${FENCE}`]
  356. if (member.jsDoc !== '') lines.push(member.jsDoc)
  357. lines.push(...member.signatures, '```', '')
  358. if (member.doc !== '') lines.push(...prose(member.doc), '')
  359. for (const parameter of member.params) lines.push(`- \`${parameter.name}\` — ${unlink(parameter.text)}`)
  360. if (member.params.length > 0) lines.push('')
  361. if (member.returns !== null && member.returns !== '') lines.push(`**Returns** ${unlink(member.returns)}`, '')
  362. lines.push(sourceLink(member.source), '')
  363. return lines
  364. }
  365. /** Render one detailed Cordis core API page and reject undocumented members. */
  366. export function renderCordisCoreApiPage(
  367. page: CordisCoreApiPage,
  368. scanRoot: string = root,
  369. ): string {
  370. const ctx: RenderContext = { scanRoot, cache: new Map(), violations: [] }
  371. const lines = [
  372. '<!-- Generated by scripts/gen-cordis-catalog.ts — do not edit by hand.',
  373. ' Run `pnpm run gen-cordis-catalog` to regenerate. -->',
  374. '',
  375. `# ${page.title}`,
  376. '',
  377. page.intro,
  378. '',
  379. ]
  380. for (const section of page.sections) {
  381. if (section.kind !== 'decl' && section.heading !== undefined) lines.push(`## ${section.heading}`, '')
  382. if (section.kind === 'context-merge') {
  383. for (const member of contextMergeMembers(ctx, section.file)) lines.push(...renderMember('ctx.', member))
  384. } else if (section.kind === 'class') {
  385. const cls = classMembers(ctx, section.file, section.symbol)
  386. if (cls.doc !== '') lines.push(...prose(cls.doc), '')
  387. lines.push(sourceLink(cls.source), '')
  388. const prefix = section.prefix ?? `${section.symbol.toLowerCase()}.`
  389. for (const member of cls.instance) lines.push(...renderMember(prefix, member))
  390. if (cls.statics.length > 0) {
  391. lines.push('## Static members', '')
  392. for (const member of cls.statics) lines.push(...renderMember(`${section.symbol}.`, member))
  393. }
  394. } else {
  395. const declaration = declarationPaste(ctx, section.file, section.symbol)
  396. lines.push(`## ${section.symbol}`, '')
  397. if (declaration.doc !== '') lines.push(...prose(declaration.doc), '')
  398. lines.push(`\`\`\`${FENCE}`, declaration.code, '```', '', sourceLink(declaration.source), '')
  399. }
  400. }
  401. reportViolations('gen-cordis-catalog', ctx.violations)
  402. return `${lines.join('\n').replace(/\n{3,}/g, '\n\n').trimEnd()}\n`
  403. }
  404. /** Render every detailed Cordis core API page. */
  405. export function renderCordisCoreApiPages(scanRoot: string = root): Map<string, string> {
  406. return new Map(CORDIS_CORE_API_PAGES.map(page => [page.out, renderCordisCoreApiPage(page, scanRoot)]))
  407. }