verify-export-jsdoc.ts 34 KB

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