verify-export-jsdoc.ts 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607
  1. /**
  2. * Enforce JSDoc on every non-vendored package export. Functions and public
  3. * class methods require parameter and non-void return documentation; exported
  4. * declarations require description prose. Inline callable types, overload
  5. * signatures, namespace members, and public class members are included;
  6. * framework slots, constructors, inherited contracts, augmentations, and source
  7. * re-exports keep their docs at the declaring contract. Unknown forms fail closed.
  8. */
  9. import { existsSync, globSync, readFileSync } from 'node:fs'
  10. import { relative, resolve, sep } from 'node:path'
  11. import ts from 'typescript'
  12. import { checkParams, checkReturns, parseJsDoc, parseTags, pointer, rawJsDoc } from './jsdoc.ts'
  13. const root = resolve(import.meta.dirname, '..')
  14. /** Plugin-protocol slot names exempt as statics on an exported class. */
  15. const PROTOCOL_STATICS = new Set(['Config', 'inject', 'name', 'reusable'])
  16. /** Plugin-protocol slot names exempt as top-level exports (const or function). */
  17. const PROTOCOL_EXPORTS = new Set(['Config', 'inject', 'name', 'reusable', 'apply'])
  18. /** Per-file walk state threaded through the scope recursion. */
  19. interface Walk {
  20. rel: string
  21. sf: ts.SourceFile
  22. text: string
  23. checker: ts.TypeChecker
  24. violations: string[]
  25. }
  26. function isExported(stmt: ts.Statement): boolean {
  27. return ts.canHaveModifiers(stmt) && (ts.getModifiers(stmt)?.some(m => m.kind === ts.SyntaxKind.ExportKeyword) ?? false)
  28. }
  29. function isNonPublic(member: ts.ClassElement): boolean {
  30. const mods = ts.canHaveModifiers(member) ? ts.getModifiers(member) : undefined
  31. return (mods?.some(m => m.kind === ts.SyntaxKind.PrivateKeyword || m.kind === ts.SyntaxKind.ProtectedKeyword) ?? false)
  32. || ('name' in member && ts.isPrivateIdentifier(member.name))
  33. }
  34. function isStatic(member: ts.ClassElement): boolean {
  35. const mods = ts.canHaveModifiers(member) ? ts.getModifiers(member) : undefined
  36. return mods?.some(m => m.kind === ts.SyntaxKind.StaticKeyword) ?? false
  37. }
  38. function thisReceiver(p: ts.ParameterDeclaration): boolean {
  39. return ts.isIdentifier(p.name) && p.name.text === 'this'
  40. }
  41. /**
  42. * Peel wrapper expressions that define no API of their own — parentheses,
  43. * `as` / `satisfies` / angle-bracket casts, non-null assertions — so a
  44. * wrapped function expression is still classified as function-like.
  45. * @param e - the expression to unwrap.
  46. * @returns the innermost non-wrapper expression.
  47. */
  48. function unwrapExpression(e: ts.Expression): ts.Expression {
  49. let inner = e
  50. while (
  51. ts.isParenthesizedExpression(inner) || ts.isAsExpression(inner) || ts.isSatisfiesExpression(inner)
  52. || ts.isNonNullExpression(inner) || ts.isTypeAssertionExpression(inner)
  53. ) inner = inner.expression
  54. return inner
  55. }
  56. /**
  57. * Classify inline callable annotations. Mixed callable literals fail closed;
  58. * other annotations are ordinary value types.
  59. * @param type - the declarator's type annotation.
  60. * @returns the signature to check, 'refuse' for an unclassifiable callable literal, or null for a non-callable type.
  61. */
  62. function callableAnnotation(type: ts.TypeNode): ts.SignatureDeclarationBase | 'refuse' | null {
  63. if (ts.isFunctionTypeNode(type)) return type
  64. if (!ts.isTypeLiteralNode(type)) return null
  65. const signatures = type.members.filter(m => ts.isCallSignatureDeclaration(m) || ts.isConstructSignatureDeclaration(m))
  66. if (signatures.length === 0) return null
  67. if (signatures.length === 1 && type.members.length === 1 && signatures[0] !== undefined && ts.isCallSignatureDeclaration(signatures[0])) {
  68. return signatures[0]
  69. }
  70. return 'refuse'
  71. }
  72. /**
  73. * Find inherited documentation for a class member without exempting a newly public API.
  74. * @param cls - the class whose heritage to search.
  75. * @param name - the member name to look up.
  76. * @param staticSide - whether to search the constructor side instead of the instance side.
  77. * @param checker - the program's type checker.
  78. * @returns inherited parameter and return coverage, or `null` when none applies.
  79. */
  80. function heritageExemption(
  81. cls: ts.ClassDeclaration,
  82. name: string,
  83. staticSide: boolean,
  84. checker: ts.TypeChecker,
  85. ): { baseParams: Set<string> | null; baseVoidReturn: boolean | null } | null {
  86. const isProtected = (d: ts.Declaration): boolean =>
  87. (ts.canHaveModifiers(d) ? ts.getModifiers(d) : undefined)?.some(m => m.kind === ts.SyntaxKind.ProtectedKeyword) ?? false
  88. for (const clause of cls.heritageClauses ?? []) {
  89. for (const t of clause.types) {
  90. const type = staticSide ? checker.getTypeAtLocation(t.expression) : checker.getTypeAtLocation(t)
  91. const prop = type.getProperty(name)
  92. if (prop === undefined) continue
  93. const decls = prop.declarations ?? []
  94. if (decls.length > 0 && decls.every(isProtected)) continue // public override of a protected base: new API
  95. let baseParams: Set<string> | null = null
  96. let baseVoidReturn: boolean | null = null
  97. for (const d of decls) {
  98. let params: readonly ts.ParameterDeclaration[] | undefined
  99. let returnType: ts.TypeNode | undefined
  100. if (ts.isMethodDeclaration(d) || ts.isMethodSignature(d)) {
  101. params = d.parameters
  102. returnType = d.type
  103. } else if ((ts.isPropertySignature(d) || ts.isPropertyDeclaration(d)) && d.type !== undefined && ts.isFunctionTypeNode(d.type)) {
  104. params = d.type.parameters
  105. returnType = d.type.type
  106. } else continue
  107. baseParams ??= new Set()
  108. // Leading underscores are the deliberately-unused marker (lint
  109. // argsIgnorePattern), not a rename: `_cwd` overriding `cwd` is the
  110. // same parameter, so compare underscore-stripped on both sides.
  111. for (const p of params) if (ts.isIdentifier(p.name)) baseParams.add(p.name.text.replace(/^_+/, ''))
  112. if (returnType !== undefined) {
  113. const voidish = /^(void|Promise<void>)$/.test(returnType.getText(d.getSourceFile()).replace(/\s+/g, ' '))
  114. baseVoidReturn = (baseVoidReturn ?? true) && voidish
  115. }
  116. }
  117. return { baseParams, baseVoidReturn }
  118. }
  119. }
  120. return null
  121. }
  122. /**
  123. * True when a method's INFERRED return type is void-like (void, undefined,
  124. * never, or a promise of one) — the one return the walk asks the checker to
  125. * classify: an unannotated override above a void heritage member, where
  126. * demanding an annotation just to prove faithfulness would be boilerplate.
  127. * @param m - a method declaration with no return type annotation.
  128. * @param checker - the program's type checker.
  129. * @returns true when the inferred result carries nothing to document.
  130. */
  131. function inferredReturnIsVoidish(m: ts.MethodDeclaration, checker: ts.TypeChecker): boolean {
  132. const sig = checker.getSignatureFromDeclaration(m)
  133. if (sig === undefined) return true // no callable signature: nothing classifiable to document
  134. const returned = checker.getReturnTypeOfSignature(sig)
  135. const awaited = checker.getAwaitedType(returned) ?? returned
  136. return (awaited.flags & (ts.TypeFlags.Void | ts.TypeFlags.Undefined | ts.TypeFlags.Never)) !== 0
  137. }
  138. /**
  139. * Check description-prose presence for one labeled declaration: JSDoc must
  140. * exist and carry prose above its block tags.
  141. * @param where - the offender label violations open with.
  142. * @param raw - the declaration's raw JSDoc block ('' if none).
  143. * @param w - the walk state violations append to.
  144. */
  145. function checkDescribed(where: string, raw: string, w: Walk): void {
  146. if (!raw) w.violations.push(`${where} has no JSDoc.`)
  147. else if (!parseJsDoc(raw).doc) w.violations.push(`${where} has no description prose above its block tags.`)
  148. }
  149. /**
  150. * Check the full function contract for one labeled function-like declaration:
  151. * description prose, `@param` per parameter, `@returns` on a non-void result.
  152. * @param where - the offender label violations open with.
  153. * @param raw - the declaration's raw JSDoc block ('' if none).
  154. * @param parameters - the declaration's parameter list.
  155. * @param returnType - the return type annotation, or undefined when inferred.
  156. * @param returnsWaived - suppress the `@returns`/annotation requirement (a
  157. * declarator-annotated const defers its return contract to the named type).
  158. * @param w - the walk state violations append to.
  159. */
  160. function checkFunctionLike(
  161. where: string,
  162. raw: string,
  163. parameters: readonly ts.ParameterDeclaration[],
  164. returnType: ts.TypeNode | undefined,
  165. returnsWaived: boolean,
  166. w: Walk,
  167. ): void {
  168. if (!raw) { w.violations.push(`${where} has no JSDoc.`); return }
  169. if (!parseJsDoc(raw).doc) w.violations.push(`${where} has no description prose above its block tags.`)
  170. const { params, returns } = parseTags(raw)
  171. checkParams(where, 'exported', parameters, params, w.sf, thisReceiver, w.violations)
  172. if (!returnsWaived) checkReturns(where, returnType, returns, w.sf, w.violations)
  173. }
  174. /**
  175. * Check one exported class: class-level prose, the function contract on every
  176. * public method (overload implementations exempt), and description prose on
  177. * public properties and accessors (a get/set pair is covered by the getter's
  178. * doc). Heritage-declared members are exempt per heritageExemption (an
  179. * override's extra parameters keep their @param duty); plugin-protocol
  180. * statics are exempt; constructors are not checked (framework-constructed
  181. * plugins, and the class doc owns the story).
  182. * @param cls - the exported class declaration.
  183. * @param name - the class's exported name (namespace-qualified).
  184. * @param w - the walk state violations append to.
  185. */
  186. function checkClass(cls: ts.ClassDeclaration, name: string, w: Walk): void {
  187. checkDescribed(`exported class '${name}' (${pointer(w.rel, w.sf, cls)})`, rawJsDoc(w.text, cls), w)
  188. const overloadSigs = new Set<string>()
  189. const documentedGetters = new Set<string>()
  190. for (const m of cls.members) {
  191. if ('name' in m && ts.isComputedPropertyName(m.name)) continue
  192. if (ts.isMethodDeclaration(m) && !m.body) overloadSigs.add(m.name.getText(w.sf))
  193. if (ts.isGetAccessorDeclaration(m)) documentedGetters.add(m.name.getText(w.sf))
  194. }
  195. for (const m of cls.members) {
  196. if (isNonPublic(m) || ts.isConstructorDeclaration(m)) continue
  197. if (!('name' in m) || ts.isComputedPropertyName(m.name)) continue // computed/symbol members
  198. const mname = m.name.getText(w.sf)
  199. if (isStatic(m) && PROTOCOL_STATICS.has(mname)) continue // cordis plugin-protocol slot
  200. const exemption = heritageExemption(cls, mname, isStatic(m), w.checker)
  201. if (ts.isMethodDeclaration(m)) {
  202. if (m.body && overloadSigs.has(mname)) continue // overload implementation: the signatures carry the docs
  203. const where = `exported class method '${name}.${mname}' (${pointer(w.rel, w.sf, m)})`
  204. if (exemption !== null) {
  205. const raw = rawJsDoc(w.text, m)
  206. // The heritage declaration owns the prose; parameters the base never
  207. // names — including binding patterns, which no base declaration can
  208. // name — are new API and keep their @param duty.
  209. const base = exemption.baseParams
  210. const inBase = (p: ts.ParameterDeclaration): boolean =>
  211. base !== null && ts.isIdentifier(p.name) && base.has(p.name.text.replace(/^_+/, ''))
  212. if (base !== null && m.parameters.some(p => !thisReceiver(p) && !inBase(p))) {
  213. checkParams(where, 'exported', m.parameters, parseTags(raw).params, w.sf,
  214. p => thisReceiver(p) || inBase(p), w.violations)
  215. }
  216. // A void base return carried no @returns duty, so an override growing a concrete result
  217. // documents it itself.
  218. if (exemption.baseVoidReturn === true) {
  219. if (m.type !== undefined) {
  220. checkReturns(where, m.type, parseTags(raw).returns, w.sf, w.violations)
  221. } else if (!inferredReturnIsVoidish(m, w.checker)) {
  222. w.violations.push(`${where} returns a non-void result its heritage declaration does not document; annotate the return type and add @returns.`)
  223. }
  224. }
  225. continue
  226. }
  227. checkFunctionLike(where, rawJsDoc(w.text, m), m.parameters, m.type, false, w)
  228. } else if (exemption !== null) {
  229. continue // the heritage declaration owns the doc (properties/accessors carry no own parameters)
  230. } else if (ts.isGetAccessorDeclaration(m) || ts.isPropertyDeclaration(m)) {
  231. const kind = ts.isPropertyDeclaration(m) ? 'property' : 'accessor'
  232. checkDescribed(`exported class ${kind} '${name}.${mname}' (${pointer(w.rel, w.sf, m)})`, rawJsDoc(w.text, m), w)
  233. } else if (ts.isSetAccessorDeclaration(m) && !documentedGetters.has(mname)) {
  234. checkDescribed(`exported class accessor '${name}.${mname}' (${pointer(w.rel, w.sf, m)})`, rawJsDoc(w.text, m), w)
  235. }
  236. // index signatures / static blocks: no named API
  237. }
  238. }
  239. /**
  240. * Check one exported declaration.
  241. * @param stmt - exported statement.
  242. * @param prefix - namespace qualifier.
  243. * @param overloadSigs - bodyless overload names.
  244. * @param byName - declarations keyed by name.
  245. * @param ambient - whether exports are implicit.
  246. * @param w - walk state.
  247. * @param only - selected declarators, or all.
  248. */
  249. function checkDecl(
  250. stmt: ts.Statement,
  251. prefix: string,
  252. overloadSigs: Set<string>,
  253. byName: Map<string, ts.Statement[]>,
  254. ambient: boolean,
  255. w: Walk,
  256. only: ReadonlySet<string> | null = null,
  257. ): void {
  258. const at = (n: ts.Node): string => ` (${pointer(w.rel, w.sf, n)})`
  259. if (ts.isFunctionDeclaration(stmt)) {
  260. const name = stmt.name?.text ?? 'default'
  261. if (prefix === '' && PROTOCOL_EXPORTS.has(name)) return // cordis plugin-protocol slot
  262. if (stmt.body && overloadSigs.has(name)) return // overload implementation: the signatures carry the docs
  263. checkFunctionLike(`exported function '${prefix}${name}'${at(stmt)}`, rawJsDoc(w.text, stmt),
  264. stmt.parameters, stmt.type, false, w)
  265. return
  266. }
  267. if (ts.isClassDeclaration(stmt)) {
  268. checkClass(stmt, `${prefix}${stmt.name?.text ?? 'default'}`, w)
  269. return
  270. }
  271. if (ts.isInterfaceDeclaration(stmt)) {
  272. checkDescribed(`exported interface '${prefix}${stmt.name.text}'${at(stmt)}`, rawJsDoc(w.text, stmt), w)
  273. return
  274. }
  275. if (ts.isTypeAliasDeclaration(stmt)) {
  276. checkDescribed(`exported type '${prefix}${stmt.name.text}'${at(stmt)}`, rawJsDoc(w.text, stmt), w)
  277. return
  278. }
  279. if (ts.isEnumDeclaration(stmt)) {
  280. checkDescribed(`exported enum '${prefix}${stmt.name.text}'${at(stmt)}`, rawJsDoc(w.text, stmt), w)
  281. return
  282. }
  283. if (ts.isVariableStatement(stmt)) {
  284. const raw = rawJsDoc(w.text, stmt) // JSDoc sits on the statement, not the declarator
  285. for (const d of stmt.declarationList.declarations) {
  286. const name = ts.isIdentifier(d.name) ? d.name.text : d.name.getText(w.sf)
  287. if (only !== null && !only.has(name)) continue // sibling declarator the export list never named: not exported API
  288. if (prefix === '' && PROTOCOL_EXPORTS.has(name)) continue // cordis plugin-protocol slot
  289. const where = `exported const '${prefix}${name}'${at(d)}`
  290. const annotation = d.type !== undefined ? callableAnnotation(d.type) : null
  291. const init = d.initializer !== undefined ? unwrapExpression(d.initializer) : undefined
  292. if (annotation === 'refuse') {
  293. // A literal mixing call/construct signatures with other members (or
  294. // overloading them) has no single signature the walk can hold the
  295. // tags against — fail closed rather than silently narrow the check.
  296. w.violations.push(`${where}: its callable type literal is not gate-classifiable; extract a named type and document it there.`)
  297. } else if (annotation !== null) {
  298. // An INLINE callable annotation is the exported signature itself: its
  299. // parameters and result need docs right here. (A NAMED reference
  300. // type carries its docs at the type's own declaration instead.)
  301. checkFunctionLike(where, raw, annotation.parameters, annotation.type, false, w)
  302. } else if (init !== undefined && (ts.isArrowFunction(init) || ts.isFunctionExpression(init))) {
  303. // A named declarator type annotation (`const f: Handler = …`) hands
  304. // the return contract to the named type; the arrow's own annotation is
  305. // still checked when it is the only signature the reader has.
  306. checkFunctionLike(where, raw, init.parameters, init.type, init.type === undefined && d.type !== undefined, w)
  307. } else {
  308. checkDescribed(where, raw, w)
  309. }
  310. }
  311. return
  312. }
  313. if (ts.isModuleDeclaration(stmt) && ts.isIdentifier(stmt.name)) {
  314. // A namespace merging with a documented same-name sibling (the
  315. // Config-namespace idiom) needs no second doc block of its own.
  316. const siblings = (byName.get(stmt.name.text) ?? []).filter(s => s !== stmt)
  317. const merged = siblings.some(s => parseJsDoc(rawJsDoc(w.text, s)).doc !== '')
  318. if (!merged) checkDescribed(`exported namespace '${prefix}${stmt.name.text}'${at(stmt)}`, rawJsDoc(w.text, stmt), w)
  319. let body = stmt.body
  320. let nsPrefix = `${prefix}${stmt.name.text}.`
  321. while (body !== undefined && ts.isModuleDeclaration(body)) { // dotted `namespace A.B`
  322. nsPrefix += `${body.name.getText(w.sf)}.`
  323. body = body.body
  324. }
  325. // In an ambient (`declare`) namespace body, members are implicitly
  326. // exported — no `export` modifier required — so the recursion must treat
  327. // every statement as exported API.
  328. const declared = ambient
  329. || ((ts.canHaveModifiers(stmt) ? ts.getModifiers(stmt) : undefined)?.some(m => m.kind === ts.SyntaxKind.DeclareKeyword) ?? false)
  330. if (body !== undefined && ts.isModuleBlock(body)) checkScope(body.statements, nsPrefix, w, declared)
  331. return
  332. }
  333. if (ts.isImportEqualsDeclaration(stmt)) {
  334. const where = `exported alias '${prefix}${stmt.name.text}'${at(stmt)}`
  335. // An alias is a distinct exported name whose target may be a non-exported namespace member
  336. // no walk ever visits, so it documents ITSELF — which matches the gate's strength only for
  337. // prose-only target kinds.
  338. const sym = w.checker.getSymbolAtLocation(stmt.name)
  339. const target = sym !== undefined && (sym.flags & ts.SymbolFlags.Alias) !== 0 ? w.checker.getAliasedSymbol(sym) : sym
  340. const RICH_TARGETS = ts.SymbolFlags.Function | ts.SymbolFlags.Class | ts.SymbolFlags.ValueModule | ts.SymbolFlags.NamespaceModule
  341. const rich = target === undefined
  342. || (target.flags & RICH_TARGETS) !== 0
  343. || w.checker.getTypeOfSymbol(target).getCallSignatures().length > 0
  344. if (rich) {
  345. w.violations.push(`${where} aliases a callable, class, or namespace target whose signature/member contract the alias cannot carry; export the declaration directly instead.`)
  346. return
  347. }
  348. checkDescribed(where, rawJsDoc(w.text, stmt), w)
  349. return
  350. }
  351. // Fail CLOSED: an exported statement kind this dispatch does not recognize
  352. // must never pass silently — the gate's whole promise is that unchecked
  353. // unchecked API cannot exist. New TypeScript export forms extend the gate here.
  354. w.violations.push(`exported statement${at(stmt)} uses an export form verify-export-jsdoc does not handle; extend the gate.`)
  355. }
  356. /**
  357. * Walk one lexical scope (file top level or a namespace body): check every
  358. * exported declaration, resolving `export { … }` lists (no module specifier)
  359. * to their local declarations.
  360. * @param statements - the scope's statements.
  361. * @param prefix - the namespace qualification for exported names ('' at top level).
  362. * @param w - the walk state violations append to.
  363. * @param ambient - whether this scope is ambient (`declare` namespace or a declaration file), where members export implicitly.
  364. */
  365. function checkScope(
  366. statements: readonly ts.Statement[],
  367. prefix: string,
  368. w: Walk,
  369. ambient: boolean,
  370. allowedNames?: ReadonlySet<string>,
  371. ): void {
  372. const byName = new Map<string, ts.Statement[]>()
  373. const overloadSigs = new Set<string>()
  374. const add = (name: string, stmt: ts.Statement): void => {
  375. byName.set(name, [...(byName.get(name) ?? []), stmt])
  376. }
  377. for (const stmt of statements) {
  378. if (ts.isFunctionDeclaration(stmt)) {
  379. if (stmt.name) add(stmt.name.text, stmt)
  380. if (!stmt.body && stmt.name) overloadSigs.add(stmt.name.text)
  381. } else if (ts.isClassDeclaration(stmt) || ts.isInterfaceDeclaration(stmt)
  382. || ts.isTypeAliasDeclaration(stmt) || ts.isEnumDeclaration(stmt)) {
  383. if (stmt.name) add(stmt.name.text, stmt)
  384. } else if (ts.isModuleDeclaration(stmt) && ts.isIdentifier(stmt.name)) {
  385. add(stmt.name.text, stmt)
  386. } else if (ts.isVariableStatement(stmt)) {
  387. for (const d of stmt.declarationList.declarations) {
  388. if (ts.isIdentifier(d.name)) add(d.name.text, stmt)
  389. }
  390. }
  391. }
  392. // Two-phase dispatch.
  393. const requested = new Map<ts.Statement, Set<string> | null>()
  394. const request = (stmt: ts.Statement, name: string | null): void => {
  395. const prior = requested.get(stmt)
  396. if (name === null || prior === null) {
  397. requested.set(stmt, null)
  398. return
  399. }
  400. requested.set(stmt, prior === undefined ? new Set([name]) : prior.add(name))
  401. }
  402. for (const stmt of statements) {
  403. if (ts.isModuleDeclaration(stmt)
  404. && (ts.isStringLiteral(stmt.name) || (stmt.flags & ts.NodeFlags.GlobalAugmentation) !== 0)) {
  405. continue // `declare module '…'` / `declare global` augmentation: not an export of this package
  406. }
  407. if (ts.isExportDeclaration(stmt)) {
  408. if (stmt.moduleSpecifier) continue // re-export: the defining module is walked on its own
  409. if (stmt.exportClause && ts.isNamedExports(stmt.exportClause)) {
  410. for (const el of stmt.exportClause.elements) {
  411. const local = (el.propertyName ?? el.name).text
  412. for (const decl of byName.get(local) ?? []) request(decl, local)
  413. // a name with no local declaration is an imported binding re-exported
  414. // without a specifier — its defining module is walked on its own
  415. }
  416. }
  417. continue
  418. }
  419. if (ts.isExportAssignment(stmt)) {
  420. if (stmt.isExportEquals) {
  421. // `export =` has no ESM consumer API in this repo and the walk
  422. // cannot classify its operand's type; refuse rather than fail open.
  423. w.violations.push(`export-equals assignment (${pointer(w.rel, w.sf, stmt)}) is not a gate-supported export form; use ESM named exports.`)
  424. continue
  425. }
  426. const where = `default export (${pointer(w.rel, w.sf, stmt)})`
  427. const expr = unwrapExpression(stmt.expression)
  428. if (ts.isIdentifier(expr)) {
  429. for (const decl of byName.get(expr.text) ?? []) request(decl, expr.text)
  430. } else if (ts.isArrowFunction(expr) || ts.isFunctionExpression(expr)) {
  431. checkFunctionLike(where, rawJsDoc(w.text, stmt), expr.parameters, expr.type, false, w)
  432. } else {
  433. checkDescribed(where, rawJsDoc(w.text, stmt), w)
  434. }
  435. continue
  436. }
  437. if (isExported(stmt) || (ambient && !ts.isImportDeclaration(stmt))) {
  438. if (allowedNames === undefined) {
  439. request(stmt, null)
  440. } else if (ts.isVariableStatement(stmt)) {
  441. for (const declaration of stmt.declarationList.declarations) {
  442. if (ts.isIdentifier(declaration.name) && allowedNames.has(declaration.name.text)) {
  443. request(stmt, declaration.name.text)
  444. }
  445. }
  446. } else {
  447. const name = declarationName(stmt) ?? 'default'
  448. if (allowedNames.has(name)) request(stmt, null)
  449. }
  450. }
  451. }
  452. for (const stmt of statements) {
  453. const only = requested.get(stmt)
  454. if (only !== undefined) checkDecl(stmt, prefix, overloadSigs, byName, ambient, w, only)
  455. }
  456. }
  457. function exportedTargets(value: unknown): string[] {
  458. if (typeof value === 'string') return [value]
  459. if (!value || typeof value !== 'object') return []
  460. return Object.values(value).flatMap(exportedTargets)
  461. }
  462. function sourceEntry(target: string): string | undefined {
  463. if (target.startsWith('./lib/types/') && target.endsWith('.d.ts')) {
  464. return `src/${target.slice('./lib/types/'.length, -'.d.ts'.length)}.ts`
  465. }
  466. if (target.startsWith('./lib/') && target.endsWith('.js')) {
  467. return `src/${target.slice('./lib/'.length, -'.js'.length)}.ts`
  468. }
  469. return undefined
  470. }
  471. function declarationName(declaration: ts.Node): string | undefined {
  472. const name = (declaration as ts.NamedDeclaration).name
  473. if (name && ts.isIdentifier(name)) return name.text
  474. return undefined
  475. }
  476. /** Resolve the declarations reachable through packages that do not export src/*. */
  477. function restrictedPublicNames(
  478. scanRoot: string,
  479. rels: readonly string[],
  480. program: ts.Program,
  481. checker: ts.TypeChecker,
  482. ): { restrictedPackages: Set<string>; namesByFile: Map<string, Set<string>> } {
  483. const restrictedPackages = new Set<string>()
  484. const namesByFile = new Map<string, Set<string>>()
  485. const packages = new Set(rels.map(rel => rel.split('/').slice(0, 3).join('/')))
  486. for (const packageDir of packages) {
  487. const manifestPath = resolve(scanRoot, packageDir, 'package.json')
  488. if (!existsSync(manifestPath)) continue
  489. const manifest = JSON.parse(readFileSync(manifestPath, 'utf8')) as { exports?: Record<string, unknown> }
  490. if (!manifest.exports || manifest.exports['./src/*'] !== undefined) continue
  491. restrictedPackages.add(packageDir)
  492. const entries = new Set(Object.values(manifest.exports).flatMap(exportedTargets).flatMap((target) => {
  493. const entry = sourceEntry(target)
  494. return entry ? [`${packageDir}/${entry}`] : []
  495. }))
  496. for (const entry of entries) {
  497. const source = program.getSourceFile(resolve(scanRoot, entry))
  498. const moduleSymbol = source && checker.getSymbolAtLocation(source)
  499. if (!source || !moduleSymbol) continue
  500. for (const exported of checker.getExportsOfModule(moduleSymbol)) {
  501. const target = (exported.flags & ts.SymbolFlags.Alias) !== 0 ? checker.getAliasedSymbol(exported) : exported
  502. for (const declaration of target.declarations ?? []) {
  503. const name = declarationName(declaration)
  504. const file = declaration.getSourceFile().fileName
  505. const rel = relative(scanRoot, file).split(sep).join('/')
  506. if (!name || !rel.startsWith(`${packageDir}/src/`)) continue
  507. namesByFile.set(rel, new Set([...(namesByFile.get(rel) ?? []), name]))
  508. }
  509. }
  510. }
  511. }
  512. return { restrictedPackages, namesByFile }
  513. }
  514. /**
  515. * Compiler options for the walk's program.
  516. *
  517. * @param scanRoot - the root being scanned.
  518. * @returns compiler options for ts.createProgram.
  519. */
  520. function loadCompilerOptions(scanRoot: string): ts.CompilerOptions {
  521. const cfgPath = resolve(scanRoot, 'tsconfig.base.json')
  522. if (!existsSync(cfgPath)) return { skipLibCheck: true, noLib: true, types: [] }
  523. const cfg = ts.readConfigFile(cfgPath, ts.sys.readFile.bind(ts.sys)) as { config?: unknown }
  524. const parsed = ts.parseJsonConfigFileContent(cfg.config ?? {}, ts.sys, scanRoot)
  525. return {
  526. ...parsed.options,
  527. noEmit: true,
  528. composite: false,
  529. declaration: false,
  530. declarationMap: false,
  531. sourceMap: false,
  532. incremental: false,
  533. }
  534. }
  535. /**
  536. * Walk every non-vendored package source file and collect JSDoc-completeness
  537. * violations for its module-level exports. Returns findings instead of
  538. * throwing so tests assert on the list; the CLI entry turns a non-empty list
  539. * into exit 1.
  540. * @param scanRoot - the repo root to scan; tests pass a fixture dir.
  541. * @returns every violation, in file order, one human-readable line each.
  542. */
  543. export function collectExportJsdocViolations(scanRoot: string = root): string[] {
  544. const violations: string[] = []
  545. const rels = globSync('packages/*/*/src/**/*.ts', { cwd: scanRoot })
  546. .map(path => path.split(sep).join('/'))
  547. .sort()
  548. const program = ts.createProgram(rels.map(rel => resolve(scanRoot, rel)), loadCompilerOptions(scanRoot))
  549. const checker = program.getTypeChecker()
  550. const { restrictedPackages, namesByFile } = restrictedPublicNames(scanRoot, rels, program, checker)
  551. for (const rel of rels) {
  552. const sf = program.getSourceFile(resolve(scanRoot, rel))
  553. if (!sf) continue // program root files always resolve; guard for narrowing
  554. // A script-style declaration file (no imports/exports) is one big ambient
  555. // scope; a module-style .d.ts still honors explicit export modifiers.
  556. const packageDir = rel.split('/').slice(0, 3).join('/')
  557. const allowedNames = restrictedPackages.has(packageDir) ? namesByFile.get(rel) ?? new Set<string>() : undefined
  558. checkScope(
  559. sf.statements,
  560. '',
  561. { rel, sf, text: sf.text, checker, violations },
  562. sf.isDeclarationFile && !ts.isExternalModule(sf),
  563. allowedNames,
  564. )
  565. }
  566. return violations
  567. }
  568. /** CLI entry: list every violation and exit 1, or confirm a documented API. */
  569. function main(): void {
  570. const violations = collectExportJsdocViolations()
  571. if (violations.length === 0) {
  572. console.log('verify-export-jsdoc: every exported name in each package API is documented.')
  573. return
  574. }
  575. console.error(`verify-export-jsdoc: ${violations.length} JSDoc completeness violation(s) (see AGENTS.md):`)
  576. for (const v of violations) console.error(` ${v}`)
  577. process.exit(1)
  578. }
  579. if (process.argv[1] && import.meta.filename === resolve(process.argv[1])) {
  580. main()
  581. }