verify-export-jsdoc.ts 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573
  1. /**
  2. * Verify JSDoc completeness for EVERY module-level exported name of every
  3. * non-vendored package (each `packages/<group>/<pkg>/src/` tree). This is the
  4. * mechanical form of the AGENTS.md rule "every export has a JSDoc explaining
  5. * semantics", generalizing the cordis-surface gate (`gen-cordis-catalog.ts`,
  6. * which owns `interface Events` members and `ctx.<key>` service classes) to
  7. * the whole export surface; the parsing + check helpers are shared via
  8. * `scripts/jsdoc.ts` so "documented" means the same thing on both.
  9. *
  10. * `tsx scripts/verify-export-jsdoc.ts` → exit 1 listing every offender
  11. *
  12. * The contract, per exported declaration kind:
  13. *
  14. * - Every exported name needs JSDoc with non-empty description prose (prose
  15. * ends at the first block tag, standard JSDoc semantics).
  16. * - A function-like export (function declaration, a const with a function
  17. * initializer or an INLINE callable annotation, or a non-identifier
  18. * function default export) additionally needs a non-empty `@param` per
  19. * parameter (`this` receiver annotations exempt; a stale `@param` errors)
  20. * and a non-empty `@returns` unless the return type is `void` /
  21. * `Promise<void>`. Wrapper expressions (parentheses, `as` / `satisfies`
  22. * casts, non-null assertions) are peeled before classifying. The walk
  23. * classifies returns syntactically, so the return type must be ANNOTATED —
  24. * except a const whose declarator is annotated with a NAMED type (e.g.
  25. * `export const f: Handler = …`), where that type's own declaration owns
  26. * the signature contract and `@returns` stays optional; an inline
  27. * `(x: T) => U` annotation or single-call-signature literal is the surface
  28. * signature itself and gets the full contract, and a literal mixing
  29. * call/construct signatures with anything else is refused (extract a named
  30. * type).
  31. * - An exported class needs class-level JSDoc; its public methods (static
  32. * included — they are reachable on the exported name) follow the function
  33. * contract, and public properties and accessors need description prose (on
  34. * a get/set pair the getter's doc covers both). A member declared by an
  35. * `extends`/`implements` heritage type is EXEMPT — the seam declaration is
  36. * the doc's one home, the IDE inherits it, and re-documenting every
  37. * implementation invites drift — UNLESS the override grows surface the
  38. * base never documented: a protected-only base member does not exempt a
  39. * public override, and parameters the base never names keep their `@param`
  40. * duty. This is the one question the walk asks the TYPE CHECKER (heritage
  41. * members live across package boundaries); everything else is pure AST.
  42. * Constructors are exempt like the cordis gate's: plugin classes are
  43. * framework-constructed, and the class doc owns the story.
  44. * - Exported interfaces, type aliases, enums: description prose on the
  45. * declaration (member-level docs stay review's job; the highest-value
  46. * member surface — seam service classes — is already under the cordis
  47. * gate).
  48. * - An exported namespace recurses (its exported members are package
  49. * surface; in an ambient `declare` namespace every member exports
  50. * implicitly); the namespace itself needs prose only when it does not
  51. * merge with an already-documented same-name declaration (the
  52. * Config-namespace idiom documents the class/function once, not twice).
  53. * - The cordis plugin-protocol slots are exempt: top-level `name` / `inject`
  54. * / `reusable` / `Config` consts and the `apply` entry, plus the same
  55. * slots as statics on a plugin class. Their shape is fixed by the
  56. * framework, so a doc would restate the protocol — the module doc comment
  57. * and the `interface Config` carry the plugin's real semantics. (These
  58. * names are reserved by cordis convention; documenting one anyway is
  59. * allowed, only absence goes unchecked.)
  60. * - Overload groups: each overload signature carries its own docs; the
  61. * implementation signature is exempt (callers never see it).
  62. * - Skipped: `declare module` / `declare global` augmentation bodies (the
  63. * cordis gate's turf; an augmentation is not an export of the package) and
  64. * re-export statements with a module specifier (`export … from`) — the
  65. * defining module is walked on its own, and external definitions are not
  66. * ours to document. An `export import X = N.member` alias documents
  67. * ITSELF, and only prose-only target kinds are gate-supported: a callable,
  68. * class, or namespace target carries signature/member contracts the alias
  69. * cannot hold and is refused (export the declaration directly).
  70. * - Everything else fails CLOSED: `export =` is refused outright, and an
  71. * exported statement kind the dispatch does not recognize is itself a
  72. * violation, so no export form can pass unchecked by omission.
  73. */
  74. import { existsSync, globSync } from 'node:fs'
  75. import { resolve } from 'node:path'
  76. import ts from 'typescript'
  77. import { checkParams, checkReturns, parseJsDoc, parseTags, pointer, rawJsDoc } from './jsdoc.ts'
  78. const root = resolve(import.meta.dirname, '..')
  79. /** Plugin-protocol slot names exempt as statics on an exported class. */
  80. const PROTOCOL_STATICS = new Set(['Config', 'inject', 'name', 'reusable'])
  81. /** Plugin-protocol slot names exempt as top-level exports (const or function). */
  82. const PROTOCOL_EXPORTS = new Set(['Config', 'inject', 'name', 'reusable', 'apply'])
  83. /** Per-file walk state threaded through the scope recursion. */
  84. interface Walk {
  85. /** Repo-relative path of the file being walked. */
  86. rel: string
  87. /** The parsed source file. */
  88. sf: ts.SourceFile
  89. /** Raw file text (rawJsDoc reads comment ranges out of it). */
  90. text: string
  91. /** The program's checker, consulted only for heritage-member lookups. */
  92. checker: ts.TypeChecker
  93. /** The aggregate violation list, appended in place. */
  94. violations: string[]
  95. }
  96. /** True when a statement carries the `export` modifier. */
  97. function isExported(stmt: ts.Statement): boolean {
  98. return ts.canHaveModifiers(stmt) && (ts.getModifiers(stmt)?.some(m => m.kind === ts.SyntaxKind.ExportKeyword) ?? false)
  99. }
  100. /** True for a class member a consumer cannot reach: `private`/`protected`/`#name`. */
  101. function isNonPublic(member: ts.ClassElement): boolean {
  102. const mods = ts.canHaveModifiers(member) ? ts.getModifiers(member) : undefined
  103. return (mods?.some(m => m.kind === ts.SyntaxKind.PrivateKeyword || m.kind === ts.SyntaxKind.ProtectedKeyword) ?? false)
  104. || ('name' in member && ts.isPrivateIdentifier(member.name))
  105. }
  106. /** True when a class member carries the `static` modifier. */
  107. function isStatic(member: ts.ClassElement): boolean {
  108. const mods = ts.canHaveModifiers(member) ? ts.getModifiers(member) : undefined
  109. return mods?.some(m => m.kind === ts.SyntaxKind.StaticKeyword) ?? false
  110. }
  111. /** The `this`-receiver exemption every function-like check shares. */
  112. function thisReceiver(p: ts.ParameterDeclaration): boolean {
  113. return ts.isIdentifier(p.name) && p.name.text === 'this'
  114. }
  115. /**
  116. * Peel wrapper expressions that carry no surface of their own — parentheses,
  117. * `as` / `satisfies` / angle-bracket casts, non-null assertions — so a
  118. * wrapped function expression is still classified as function-like.
  119. * @param e - the expression to unwrap.
  120. * @returns the innermost non-wrapper expression.
  121. */
  122. function unwrapExpression(e: ts.Expression): ts.Expression {
  123. let inner = e
  124. while (
  125. ts.isParenthesizedExpression(inner) || ts.isAsExpression(inner) || ts.isSatisfiesExpression(inner)
  126. || ts.isNonNullExpression(inner) || ts.isTypeAssertionExpression(inner)
  127. ) inner = inner.expression
  128. return inner
  129. }
  130. /**
  131. * Classify a declarator's type annotation for the function contract: an
  132. * inline function type or a type literal that is EXACTLY one call signature
  133. * is the surface signature itself; a literal mixing call/construct
  134. * signatures with anything else cannot be classified syntactically and is
  135. * refused (fail closed — extract a named type); everything else is a plain
  136. * value shape.
  137. * @param type - the declarator's type annotation.
  138. * @returns the signature to check, 'refuse' for an unclassifiable callable literal, or null for a non-callable shape.
  139. */
  140. function callableAnnotation(type: ts.TypeNode): ts.SignatureDeclarationBase | 'refuse' | null {
  141. if (ts.isFunctionTypeNode(type)) return type
  142. if (!ts.isTypeLiteralNode(type)) return null
  143. const signatures = type.members.filter(m => ts.isCallSignatureDeclaration(m) || ts.isConstructSignatureDeclaration(m))
  144. if (signatures.length === 0) return null
  145. if (signatures.length === 1 && type.members.length === 1 && signatures[0] !== undefined && ts.isCallSignatureDeclaration(signatures[0])) {
  146. return signatures[0]
  147. }
  148. return 'refuse'
  149. }
  150. /**
  151. * The heritage-member exemption for one class member. When the member's name
  152. * is declared by an `extends`/`implements` heritage type, the seam declaration
  153. * is the doc's one home (the IDE inherits it on hover) and the member needs no
  154. * doc of its own — EXCEPT where the override grows public surface the base
  155. * never documented: a base member that is protected on every declaration does
  156. * not exempt a public override (consumers could not call it before), and
  157. * parameters the base never names keep their own `@param` duty (the caller
  158. * reads the seam doc, which cannot describe them; an underscore-prefixed
  159. * rename of a base parameter — the deliberately-unused marker — is the same
  160. * parameter, not new surface). Static members are looked
  161. * up on the base CONSTRUCTOR type (only an `extends` expression has one; an
  162. * unresolvable or interface expression yields no property and therefore no
  163. * exemption).
  164. * @param cls - the class whose heritage to search.
  165. * @param name - the member name to look up.
  166. * @param staticSide - whether to search the constructor side instead of the instance side.
  167. * @param checker - the program's type checker.
  168. * @returns null when no exemption applies; otherwise the parameter names the
  169. * base declarations carry (`baseParams: null` means the base's parameters are
  170. * not syntactically recoverable — a complex heritage type — and the member is
  171. * exempt in full).
  172. */
  173. function heritageExemption(
  174. cls: ts.ClassDeclaration,
  175. name: string,
  176. staticSide: boolean,
  177. checker: ts.TypeChecker,
  178. ): { baseParams: Set<string> | null } | null {
  179. const isProtected = (d: ts.Declaration): boolean =>
  180. (ts.canHaveModifiers(d) ? ts.getModifiers(d) : undefined)?.some(m => m.kind === ts.SyntaxKind.ProtectedKeyword) ?? false
  181. for (const clause of cls.heritageClauses ?? []) {
  182. for (const t of clause.types) {
  183. const type = staticSide ? checker.getTypeAtLocation(t.expression) : checker.getTypeAtLocation(t)
  184. const prop = type.getProperty(name)
  185. if (prop === undefined) continue
  186. const decls = prop.declarations ?? []
  187. if (decls.length > 0 && decls.every(isProtected)) continue // public override of a protected base: new surface
  188. let baseParams: Set<string> | null = null
  189. for (const d of decls) {
  190. let params: readonly ts.ParameterDeclaration[] | undefined
  191. if (ts.isMethodDeclaration(d) || ts.isMethodSignature(d)) params = d.parameters
  192. else if ((ts.isPropertySignature(d) || ts.isPropertyDeclaration(d)) && d.type !== undefined && ts.isFunctionTypeNode(d.type)) {
  193. params = d.type.parameters
  194. } else continue
  195. baseParams ??= new Set()
  196. // Leading underscores are the deliberately-unused marker (eslint
  197. // argsIgnorePattern), not a rename: `_cwd` overriding `cwd` is the
  198. // same parameter, so compare underscore-stripped on both sides.
  199. for (const p of params) if (ts.isIdentifier(p.name)) baseParams.add(p.name.text.replace(/^_+/, ''))
  200. }
  201. return { baseParams }
  202. }
  203. }
  204. return null
  205. }
  206. /**
  207. * Check description-prose presence for one labeled declaration: JSDoc must
  208. * exist and carry prose above its block tags.
  209. * @param where - the offender label violations open with.
  210. * @param raw - the declaration's raw JSDoc block ('' if none).
  211. * @param w - the walk state violations append to.
  212. */
  213. function checkDescribed(where: string, raw: string, w: Walk): void {
  214. if (!raw) w.violations.push(`${where} has no JSDoc.`)
  215. else if (!parseJsDoc(raw).doc) w.violations.push(`${where} has no description prose above its block tags.`)
  216. }
  217. /**
  218. * Check the full function contract for one labeled function-like declaration:
  219. * description prose, `@param` per parameter, `@returns` on a non-void result.
  220. * @param where - the offender label violations open with.
  221. * @param raw - the declaration's raw JSDoc block ('' if none).
  222. * @param parameters - the declaration's parameter list.
  223. * @param returnType - the return type annotation, or undefined when inferred.
  224. * @param returnsWaived - suppress the `@returns`/annotation requirement (a
  225. * declarator-annotated const defers its return contract to the named type).
  226. * @param w - the walk state violations append to.
  227. */
  228. function checkFunctionLike(
  229. where: string,
  230. raw: string,
  231. parameters: readonly ts.ParameterDeclaration[],
  232. returnType: ts.TypeNode | undefined,
  233. returnsWaived: boolean,
  234. w: Walk,
  235. ): void {
  236. if (!raw) { w.violations.push(`${where} has no JSDoc.`); return }
  237. if (!parseJsDoc(raw).doc) w.violations.push(`${where} has no description prose above its block tags.`)
  238. const { params, returns } = parseTags(raw)
  239. checkParams(where, 'export', parameters, params, w.sf, thisReceiver, w.violations)
  240. if (!returnsWaived) checkReturns(where, returnType, returns, w.sf, w.violations)
  241. }
  242. /**
  243. * Check one exported class: class-level prose, the function contract on every
  244. * public method (overload implementations exempt), and description prose on
  245. * public properties and accessors (a get/set pair is covered by the getter's
  246. * doc). Heritage-declared members are exempt per heritageExemption (an
  247. * override's extra parameters keep their @param duty); plugin-protocol
  248. * statics are exempt; constructors are not checked (framework-constructed
  249. * plugins, and the class doc owns the story).
  250. * @param cls - the exported class declaration.
  251. * @param name - the class's surface name (namespace-qualified).
  252. * @param w - the walk state violations append to.
  253. */
  254. function checkClass(cls: ts.ClassDeclaration, name: string, w: Walk): void {
  255. checkDescribed(`exported class '${name}' (${pointer(w.rel, w.sf, cls)})`, rawJsDoc(w.text, cls), w)
  256. const overloadSigs = new Set<string>()
  257. const documentedGetters = new Set<string>()
  258. for (const m of cls.members) {
  259. if ('name' in m && ts.isComputedPropertyName(m.name)) continue
  260. if (ts.isMethodDeclaration(m) && !m.body) overloadSigs.add(m.name.getText(w.sf))
  261. if (ts.isGetAccessorDeclaration(m)) documentedGetters.add(m.name.getText(w.sf))
  262. }
  263. for (const m of cls.members) {
  264. if (isNonPublic(m) || ts.isConstructorDeclaration(m)) continue
  265. if (!('name' in m) || ts.isComputedPropertyName(m.name)) continue // computed/symbol members
  266. const mname = m.name.getText(w.sf)
  267. if (isStatic(m) && PROTOCOL_STATICS.has(mname)) continue // cordis plugin-protocol slot
  268. const exemption = heritageExemption(cls, mname, isStatic(m), w.checker)
  269. if (ts.isMethodDeclaration(m)) {
  270. if (m.body && overloadSigs.has(mname)) continue // overload implementation: the signatures carry the docs
  271. const where = `exported class method '${name}.${mname}' (${pointer(w.rel, w.sf, m)})`
  272. if (exemption !== null) {
  273. // The heritage declaration owns prose and @returns; parameters the
  274. // base never names — including binding patterns, which no base
  275. // declaration can name — are new surface and keep their @param duty.
  276. const base = exemption.baseParams
  277. const inBase = (p: ts.ParameterDeclaration): boolean =>
  278. base !== null && ts.isIdentifier(p.name) && base.has(p.name.text.replace(/^_+/, ''))
  279. if (base !== null && m.parameters.some(p => !thisReceiver(p) && !inBase(p))) {
  280. const { params } = parseTags(rawJsDoc(w.text, m))
  281. checkParams(where, 'export', m.parameters, params, w.sf,
  282. p => thisReceiver(p) || inBase(p), w.violations)
  283. }
  284. continue
  285. }
  286. checkFunctionLike(where, rawJsDoc(w.text, m), m.parameters, m.type, false, w)
  287. } else if (exemption !== null) {
  288. continue // the heritage declaration owns the doc (properties/accessors carry no own parameters)
  289. } else if (ts.isGetAccessorDeclaration(m) || ts.isPropertyDeclaration(m)) {
  290. const kind = ts.isPropertyDeclaration(m) ? 'property' : 'accessor'
  291. checkDescribed(`exported class ${kind} '${name}.${mname}' (${pointer(w.rel, w.sf, m)})`, rawJsDoc(w.text, m), w)
  292. } else if (ts.isSetAccessorDeclaration(m) && !documentedGetters.has(mname)) {
  293. checkDescribed(`exported class accessor '${name}.${mname}' (${pointer(w.rel, w.sf, m)})`, rawJsDoc(w.text, m), w)
  294. }
  295. // index signatures / static blocks: not named surface
  296. }
  297. }
  298. /**
  299. * Check one exported declaration statement, dispatching on its kind. Any
  300. * exported statement kind the dispatch does not recognize is a violation
  301. * (fail closed), so no export form can pass unchecked by omission.
  302. * @param stmt - the exported statement (export modifier or export-list target).
  303. * @param prefix - the namespace qualification for surface names ('' at top level).
  304. * @param overloadSigs - names in this scope declared as bodyless function overload signatures.
  305. * @param byName - this scope's named declarations (for namespace/sibling-merge lookups).
  306. * @param ambient - whether the enclosing scope is ambient (`declare`), where members export implicitly.
  307. * @param w - the walk state violations append to.
  308. */
  309. function checkDecl(
  310. stmt: ts.Statement,
  311. prefix: string,
  312. overloadSigs: Set<string>,
  313. byName: Map<string, ts.Statement[]>,
  314. ambient: boolean,
  315. w: Walk,
  316. ): void {
  317. const at = (n: ts.Node): string => ` (${pointer(w.rel, w.sf, n)})`
  318. if (ts.isFunctionDeclaration(stmt)) {
  319. const name = stmt.name?.text ?? 'default'
  320. if (prefix === '' && PROTOCOL_EXPORTS.has(name)) return // cordis plugin-protocol slot
  321. if (stmt.body && overloadSigs.has(name)) return // overload implementation: the signatures carry the docs
  322. checkFunctionLike(`exported function '${prefix}${name}'${at(stmt)}`, rawJsDoc(w.text, stmt),
  323. stmt.parameters, stmt.type, false, w)
  324. return
  325. }
  326. if (ts.isClassDeclaration(stmt)) {
  327. checkClass(stmt, `${prefix}${stmt.name?.text ?? 'default'}`, w)
  328. return
  329. }
  330. if (ts.isInterfaceDeclaration(stmt)) {
  331. checkDescribed(`exported interface '${prefix}${stmt.name.text}'${at(stmt)}`, rawJsDoc(w.text, stmt), w)
  332. return
  333. }
  334. if (ts.isTypeAliasDeclaration(stmt)) {
  335. checkDescribed(`exported type '${prefix}${stmt.name.text}'${at(stmt)}`, rawJsDoc(w.text, stmt), w)
  336. return
  337. }
  338. if (ts.isEnumDeclaration(stmt)) {
  339. checkDescribed(`exported enum '${prefix}${stmt.name.text}'${at(stmt)}`, rawJsDoc(w.text, stmt), w)
  340. return
  341. }
  342. if (ts.isVariableStatement(stmt)) {
  343. const raw = rawJsDoc(w.text, stmt) // JSDoc sits on the statement, not the declarator
  344. for (const d of stmt.declarationList.declarations) {
  345. const name = ts.isIdentifier(d.name) ? d.name.text : d.name.getText(w.sf)
  346. if (prefix === '' && PROTOCOL_EXPORTS.has(name)) continue // cordis plugin-protocol slot
  347. const where = `exported const '${prefix}${name}'${at(d)}`
  348. const annotation = d.type !== undefined ? callableAnnotation(d.type) : null
  349. const init = d.initializer !== undefined ? unwrapExpression(d.initializer) : undefined
  350. if (annotation === 'refuse') {
  351. // A literal mixing call/construct signatures with other members (or
  352. // overloading them) has no single signature the walk can hold the
  353. // tags against — fail closed rather than silently narrow the check.
  354. w.violations.push(`${where}: its callable type literal is not gate-classifiable; extract a named type and document it there.`)
  355. } else if (annotation !== null) {
  356. // An INLINE callable annotation is the surface signature itself: its
  357. // parameters and result need docs right here. (A NAMED reference
  358. // type carries its docs at the type's own declaration instead.)
  359. checkFunctionLike(where, raw, annotation.parameters, annotation.type, false, w)
  360. } else if (init !== undefined && (ts.isArrowFunction(init) || ts.isFunctionExpression(init))) {
  361. // A named declarator type annotation (`const f: Handler = …`) hands
  362. // the return contract to the named type; the arrow's own annotation is
  363. // still checked when it is the only signature the reader has.
  364. checkFunctionLike(where, raw, init.parameters, init.type, init.type === undefined && d.type !== undefined, w)
  365. } else {
  366. checkDescribed(where, raw, w)
  367. }
  368. }
  369. return
  370. }
  371. if (ts.isModuleDeclaration(stmt) && ts.isIdentifier(stmt.name)) {
  372. // A namespace merging with a documented same-name sibling (the
  373. // Config-namespace idiom) needs no second doc block of its own.
  374. const siblings = (byName.get(stmt.name.text) ?? []).filter(s => s !== stmt)
  375. const merged = siblings.some(s => parseJsDoc(rawJsDoc(w.text, s)).doc !== '')
  376. if (!merged) checkDescribed(`exported namespace '${prefix}${stmt.name.text}'${at(stmt)}`, rawJsDoc(w.text, stmt), w)
  377. let body = stmt.body
  378. let nsPrefix = `${prefix}${stmt.name.text}.`
  379. while (body !== undefined && ts.isModuleDeclaration(body)) { // dotted `namespace A.B`
  380. nsPrefix += `${body.name.getText(w.sf)}.`
  381. body = body.body
  382. }
  383. // In an ambient (`declare`) namespace body, members are implicitly
  384. // exported — no `export` modifier required — so the recursion must treat
  385. // every statement as surface.
  386. const declared = ambient
  387. || ((ts.canHaveModifiers(stmt) ? ts.getModifiers(stmt) : undefined)?.some(m => m.kind === ts.SyntaxKind.DeclareKeyword) ?? false)
  388. if (body !== undefined && ts.isModuleBlock(body)) checkScope(body.statements, nsPrefix, w, declared)
  389. return
  390. }
  391. if (ts.isImportEqualsDeclaration(stmt)) {
  392. const where = `exported alias '${prefix}${stmt.name.text}'${at(stmt)}`
  393. // An alias is a distinct exported name whose target may be a non-exported
  394. // namespace member no walk ever visits, so it documents ITSELF — which
  395. // matches the gate's strength only for prose-only target kinds. A
  396. // callable, class, or namespace target carries signature or member
  397. // contracts the alias prose cannot hold: refuse those (fail closed) and
  398. // demand the declaration be exported directly. An unresolvable target is
  399. // refused for the same reason.
  400. const sym = w.checker.getSymbolAtLocation(stmt.name)
  401. const target = sym !== undefined && (sym.flags & ts.SymbolFlags.Alias) !== 0 ? w.checker.getAliasedSymbol(sym) : sym
  402. const RICH_TARGETS = ts.SymbolFlags.Function | ts.SymbolFlags.Class | ts.SymbolFlags.ValueModule | ts.SymbolFlags.NamespaceModule
  403. const rich = target === undefined
  404. || (target.flags & RICH_TARGETS) !== 0
  405. || w.checker.getTypeOfSymbol(target).getCallSignatures().length > 0
  406. if (rich) {
  407. w.violations.push(`${where} aliases a callable, class, or namespace target whose signature/member contract the alias cannot carry; export the declaration directly instead.`)
  408. return
  409. }
  410. checkDescribed(where, rawJsDoc(w.text, stmt), w)
  411. return
  412. }
  413. // Fail CLOSED: an exported statement kind this dispatch does not recognize
  414. // must never pass silently — the gate's whole promise is that unchecked
  415. // surface cannot exist. New TypeScript export forms extend the gate here.
  416. w.violations.push(`exported statement${at(stmt)} uses an export form verify-export-jsdoc does not handle; extend the gate.`)
  417. }
  418. /**
  419. * Walk one lexical scope (file top level or a namespace body): check every
  420. * exported declaration, resolving `export { … }` lists (no module specifier)
  421. * to their local declarations.
  422. * @param statements - the scope's statements.
  423. * @param prefix - the namespace qualification for surface names ('' at top level).
  424. * @param w - the walk state violations append to.
  425. * @param ambient - whether this scope is ambient (`declare` namespace or a declaration file), where members export implicitly.
  426. */
  427. function checkScope(statements: readonly ts.Statement[], prefix: string, w: Walk, ambient: boolean): void {
  428. const byName = new Map<string, ts.Statement[]>()
  429. const overloadSigs = new Set<string>()
  430. const add = (name: string, stmt: ts.Statement): void => {
  431. byName.set(name, [...(byName.get(name) ?? []), stmt])
  432. }
  433. for (const stmt of statements) {
  434. if (ts.isFunctionDeclaration(stmt)) {
  435. if (stmt.name) add(stmt.name.text, stmt)
  436. if (!stmt.body && stmt.name) overloadSigs.add(stmt.name.text)
  437. } else if (ts.isClassDeclaration(stmt) || ts.isInterfaceDeclaration(stmt)
  438. || ts.isTypeAliasDeclaration(stmt) || ts.isEnumDeclaration(stmt)) {
  439. if (stmt.name) add(stmt.name.text, stmt)
  440. } else if (ts.isModuleDeclaration(stmt) && ts.isIdentifier(stmt.name)) {
  441. add(stmt.name.text, stmt)
  442. } else if (ts.isVariableStatement(stmt)) {
  443. for (const d of stmt.declarationList.declarations) {
  444. if (ts.isIdentifier(d.name)) add(d.name.text, stmt)
  445. }
  446. }
  447. }
  448. const checked = new Set<ts.Statement>()
  449. const check = (stmt: ts.Statement): void => {
  450. if (checked.has(stmt)) return
  451. checked.add(stmt)
  452. checkDecl(stmt, prefix, overloadSigs, byName, ambient, w)
  453. }
  454. for (const stmt of statements) {
  455. if (ts.isModuleDeclaration(stmt)
  456. && (ts.isStringLiteral(stmt.name) || (stmt.flags & ts.NodeFlags.GlobalAugmentation) !== 0)) {
  457. continue // `declare module '…'` / `declare global` augmentation: not an export of this package
  458. }
  459. if (ts.isExportDeclaration(stmt)) {
  460. if (stmt.moduleSpecifier) continue // re-export: the defining module is walked on its own
  461. if (stmt.exportClause && ts.isNamedExports(stmt.exportClause)) {
  462. for (const el of stmt.exportClause.elements) {
  463. for (const decl of byName.get((el.propertyName ?? el.name).text) ?? []) check(decl)
  464. // a name with no local declaration is an imported binding re-exported
  465. // without a specifier — its defining module is walked on its own
  466. }
  467. }
  468. continue
  469. }
  470. if (ts.isExportAssignment(stmt)) {
  471. if (stmt.isExportEquals) {
  472. // `export =` has no ESM consumer surface in this repo and the walk
  473. // cannot classify its operand's shape; refuse rather than fail open.
  474. w.violations.push(`export-equals assignment (${pointer(w.rel, w.sf, stmt)}) is not a gate-supported export form; use ESM named exports.`)
  475. continue
  476. }
  477. const where = `default export (${pointer(w.rel, w.sf, stmt)})`
  478. const expr = unwrapExpression(stmt.expression)
  479. if (ts.isIdentifier(expr)) {
  480. for (const decl of byName.get(expr.text) ?? []) check(decl)
  481. } else if (ts.isArrowFunction(expr) || ts.isFunctionExpression(expr)) {
  482. checkFunctionLike(where, rawJsDoc(w.text, stmt), expr.parameters, expr.type, false, w)
  483. } else {
  484. checkDescribed(where, rawJsDoc(w.text, stmt), w)
  485. }
  486. continue
  487. }
  488. if (isExported(stmt) || (ambient && !ts.isImportDeclaration(stmt))) check(stmt)
  489. }
  490. }
  491. /**
  492. * Compiler options for the walk's program. The real repo hands over its
  493. * tsconfig.base.json (whose `paths` map resolves cross-package imports to
  494. * source, so heritage-member lookups see seam types); a fixture root without
  495. * one gets bare defaults — fixtures are single-file and self-contained.
  496. * Emit-side options are stripped: the walk never emits or asks for
  497. * diagnostics, it only binds types on demand.
  498. * @param scanRoot - the root being scanned.
  499. * @returns compiler options for ts.createProgram.
  500. */
  501. function loadCompilerOptions(scanRoot: string): ts.CompilerOptions {
  502. const cfgPath = resolve(scanRoot, 'tsconfig.base.json')
  503. if (!existsSync(cfgPath)) return { skipLibCheck: true }
  504. const cfg = ts.readConfigFile(cfgPath, ts.sys.readFile.bind(ts.sys)) as { config?: unknown }
  505. const parsed = ts.parseJsonConfigFileContent(cfg.config ?? {}, ts.sys, scanRoot)
  506. return {
  507. ...parsed.options,
  508. noEmit: true,
  509. composite: false,
  510. declaration: false,
  511. declarationMap: false,
  512. sourceMap: false,
  513. incremental: false,
  514. }
  515. }
  516. /**
  517. * Walk every non-vendored package source file and collect JSDoc-completeness
  518. * violations for its module-level exports. Returns findings instead of
  519. * throwing so tests assert on the list; the CLI entry turns a non-empty list
  520. * into exit 1.
  521. * @param scanRoot - the repo root to scan; tests pass a fixture dir.
  522. * @returns every violation, in file order, one human-readable line each.
  523. */
  524. export function collectExportJsdocViolations(scanRoot: string = root): string[] {
  525. const violations: string[] = []
  526. const rels = globSync('packages/*/*/src/**/*.ts', { cwd: scanRoot }).sort()
  527. const program = ts.createProgram(rels.map(rel => resolve(scanRoot, rel)), loadCompilerOptions(scanRoot))
  528. const checker = program.getTypeChecker()
  529. for (const rel of rels) {
  530. const sf = program.getSourceFile(resolve(scanRoot, rel))
  531. if (!sf) continue // program root files always resolve; guard for narrowing
  532. // A script-style declaration file (no imports/exports) is one big ambient
  533. // scope; a module-style .d.ts still honors explicit export modifiers.
  534. checkScope(sf.statements, '', { rel, sf, text: sf.text, checker, violations }, sf.isDeclarationFile && !ts.isExternalModule(sf))
  535. }
  536. return violations
  537. }
  538. /** CLI entry: list every violation and exit 1, or confirm a clean surface. */
  539. function main(): void {
  540. const violations = collectExportJsdocViolations()
  541. if (violations.length === 0) {
  542. console.log('verify-export-jsdoc: every exported name on the package surface is documented.')
  543. return
  544. }
  545. console.error(`verify-export-jsdoc: ${violations.length} JSDoc completeness violation(s) (see AGENTS.md):`)
  546. for (const v of violations) console.error(` ${v}`)
  547. process.exit(1)
  548. }
  549. // Run only when invoked as a script, not when imported by a test.
  550. if (process.argv[1] && import.meta.filename === resolve(process.argv[1])) {
  551. main()
  552. }