The best way to control Claude Code, Codex and more from any computer or phone

main
ts 3,598 lines 124 KB
Raw
1 /*
2 AI prompt for writing Effect public API JSDoc:
3
4 This package owns Effect public API JSDoc parsing, extraction, and model generation.
5 */
6
7 import * as Effect from "effect/Effect"
8 import { globSync } from "glob"
9 import * as crypto from "node:crypto"
10 import * as fs from "node:fs"
11 import * as path from "node:path"
12 import * as ts from "typescript"
13
14 type ExportBucket = "value" | "type"
15 type DocScope = "module" | "declaration" | "namespace" | "namespace-declaration" | "member"
16
17 type Result<A, E> =
18 | { readonly _tag: "Success"; readonly value: A }
19 | { readonly _tag: "Failure"; readonly error: E }
20
21 interface SourceFileWithParseDiagnostics extends ts.SourceFile {
22 readonly parseDiagnostics: ReadonlyArray<ts.Diagnostic>
23 }
24
25 /**
26 * Result type returned by the JSDoc parser helpers.
27 *
28 * @category utility types
29 * @since 4.0.0
30 */
31 export type JSDocResult<A, E> = Result<A, E>
32
33 /**
34 * Diagnostic emitted when a JSDoc block does not follow the standard shape.
35 *
36 * @category models
37 * @since 4.0.0
38 */
39 export interface JSDocDiagnostic {
40 readonly code: string
41 readonly message: string
42 }
43
44 /**
45 * Parse error containing all diagnostics collected for a JSDoc block or file.
46 *
47 * @category models
48 * @since 4.0.0
49 */
50 export interface JSDocParseError {
51 readonly diagnostics: ReadonlyArray<JSDocDiagnostic>
52 }
53
54 /**
55 * Parsed `@see` tag text and any inline links it contains.
56 *
57 * @category models
58 * @since 4.0.0
59 */
60 export interface ParsedSeeTag {
61 readonly text: string
62 readonly links: ReadonlyArray<ParsedInlineLink>
63 }
64
65 /**
66 * TypeScript symbol target resolved for a parsed inline JSDoc link.
67 *
68 * @category models
69 * @since 4.0.0
70 */
71 export interface ParsedInlineLinkSymbol {
72 readonly file: string
73 readonly range: readonly [number, number]
74 }
75
76 /**
77 * Parsed inline JSDoc link target and optional display text.
78 *
79 * @category models
80 * @since 4.0.0
81 */
82 export interface ParsedInlineLink {
83 readonly raw: string
84 readonly target: string
85 readonly text: string | null
86 readonly range?: readonly [number, number]
87 readonly symbol?: ParsedInlineLinkSymbol
88 }
89
90 /**
91 * Parsed JSDoc description sections.
92 *
93 * @category models
94 * @since 4.0.0
95 */
96 export interface ParsedDescription {
97 readonly short: string
98 readonly whenToUse: string | null
99 readonly details: string | null
100 readonly gotchas: string | null
101 }
102
103 /**
104 * Parsed example section from a JSDoc block.
105 *
106 * @category models
107 * @since 4.0.0
108 */
109 export interface ParsedExample {
110 readonly title: string
111 readonly body: string | null
112 readonly code: string
113 }
114
115 /**
116 * Raw module-level JSDoc block collected from the top of a checked file.
117 *
118 * @category models
119 * @since 4.0.0
120 */
121 export interface ParsedModuleJSDoc {
122 readonly raw: string
123 readonly range: readonly [number, number]
124 }
125
126 /**
127 * Stability of a documented public API. Untagged APIs are stable.
128 *
129 * @category models
130 * @since 4.0.0
131 */
132 export type JSDocStability = "stable" | "unstable" | "experimental"
133
134 interface ParsedModuleTags {
135 readonly since: string
136 readonly stability: JSDocStability
137 readonly deprecated: string | null
138 readonly see: ReadonlyArray<ParsedSeeTag>
139 }
140
141 /**
142 * Parsed tags required for a root public declaration.
143 *
144 * @category models
145 * @since 4.0.0
146 */
147 export interface ParsedDeclarationTags {
148 readonly category: string
149 readonly since: string
150 readonly stability: JSDocStability
151 readonly deprecated: string | null
152 readonly see: ReadonlyArray<ParsedSeeTag>
153 }
154
155 /**
156 * Parsed tags allowed for namespace JSDoc.
157 *
158 * @category models
159 * @since 4.0.0
160 */
161 export interface ParsedNamespaceTags {
162 readonly category: string | null
163 readonly since: string
164 readonly stability: JSDocStability
165 readonly deprecated: string | null
166 readonly see: ReadonlyArray<ParsedSeeTag>
167 }
168
169 /**
170 * Parsed tags allowed for documented members.
171 *
172 * @category models
173 * @since 4.0.0
174 */
175 export interface ParsedMemberTags {
176 readonly since: string | null
177 readonly stability: JSDocStability
178 readonly default: string | null
179 readonly deprecated: string | null
180 readonly see: ReadonlyArray<ParsedSeeTag>
181 }
182
183 /**
184 * Parsed documented member within a declaration or another member.
185 *
186 * @category models
187 * @since 4.0.0
188 */
189 export interface ParsedMember {
190 readonly name: string
191 readonly signature: string | null
192 readonly range: readonly [number, number]
193 readonly description: ParsedDescription
194 readonly examples: ReadonlyArray<ParsedExample>
195 readonly tags: ParsedMemberTags
196 readonly members: ReadonlyArray<ParsedMember>
197 }
198
199 /**
200 * Parsed root declaration exported from a checked file.
201 *
202 * @category models
203 * @since 4.0.0
204 */
205 export interface ParsedRootDeclaration {
206 readonly name: string
207 readonly bucket: ExportBucket
208 readonly signature: string | null
209 readonly range: readonly [number, number]
210 readonly description: ParsedDescription
211 readonly examples: ReadonlyArray<ParsedExample>
212 readonly tags: ParsedDeclarationTags
213 readonly members: ReadonlyArray<ParsedMember>
214 }
215
216 /**
217 * Parsed type declaration exported from inside a namespace.
218 *
219 * @category models
220 * @since 4.0.0
221 */
222 export interface ParsedNamespaceDeclaration {
223 readonly name: string
224 readonly signature: string | null
225 readonly range: readonly [number, number]
226 readonly description: ParsedDescription
227 readonly examples: ReadonlyArray<ParsedExample>
228 readonly tags: ParsedNamespaceTags
229 readonly members: ReadonlyArray<ParsedMember>
230 }
231
232 /**
233 * Parsed namespace and its documented exported type declarations.
234 *
235 * @category models
236 * @since 4.0.0
237 */
238 export interface ParsedNamespace {
239 readonly name: string
240 readonly signature: string | null
241 readonly range: readonly [number, number]
242 readonly description: ParsedDescription
243 readonly examples: ReadonlyArray<ParsedExample>
244 readonly tags: ParsedNamespaceTags
245 readonly declarations: ReadonlyArray<ParsedNamespaceDeclaration>
246 readonly namespaces: ReadonlyArray<ParsedNamespace>
247 }
248
249 /**
250 * Parsed public JSDoc data collected from one checked file.
251 *
252 * @category models
253 * @since 4.0.0
254 */
255 export interface ParsedJSDocFile {
256 readonly moduleJSDoc?: ParsedModuleJSDoc
257 readonly declarations: ReadonlyArray<ParsedRootDeclaration>
258 readonly namespaces: ReadonlyArray<ParsedNamespace>
259 }
260
261 /**
262 * Barrel import metadata for a public module included in the JSDoc dump.
263 *
264 * @category models
265 * @since 4.0.0
266 */
267 export type ParsedJSDocBarrelImport =
268 | {
269 readonly type: "namespace"
270 readonly module: string
271 readonly name: string
272 }
273 | {
274 readonly type: "flat"
275 readonly module: string
276 }
277
278 /**
279 * Import specifiers for a public module included in the JSDoc dump.
280 *
281 * @category models
282 * @since 4.0.0
283 */
284 export interface ParsedJSDocImports {
285 readonly module: string
286 readonly barrel: ParsedJSDocBarrelImport | null
287 readonly flatNames: ReadonlyArray<string>
288 }
289
290 /**
291 * Kinds of public API records represented in a JSDoc model.
292 *
293 * @category models
294 * @since 4.0.0
295 */
296 export type JSDocApiKind = "root-declaration" | "namespace" | "namespace-declaration" | "member"
297
298 /**
299 * Recommended import declaration and usage for an importable API.
300 *
301 * @category models
302 * @since 4.0.0
303 */
304 export type JSDocApiImportGuidance =
305 | {
306 readonly style: "namespace-barrel"
307 readonly importDeclaration: string
308 readonly usage: string
309 }
310 | {
311 readonly style: "named-barrel"
312 readonly importDeclaration: string
313 readonly usage: string
314 }
315 | {
316 readonly style: "named-module"
317 readonly importDeclaration: string
318 readonly usage: string
319 }
320
321 /**
322 * Resolution result for a link in an API's `@see` tags.
323 *
324 * @category models
325 * @since 4.0.0
326 */
327 export type JSDocApiSeeLinkResolution =
328 | {
329 readonly _tag: "Resolved"
330 readonly apiId: string
331 readonly apiFqn: string
332 }
333 | {
334 readonly _tag: "Unresolved"
335 readonly reason: "not-found" | "ambiguous"
336 readonly candidates: ReadonlyArray<string>
337 }
338
339 /**
340 * Parsed `@see` link paired with its public API resolution.
341 *
342 * @category models
343 * @since 4.0.0
344 */
345 export interface JSDocApiSeeLink extends ParsedInlineLink {
346 readonly resolution: JSDocApiSeeLinkResolution
347 }
348
349 /**
350 * Parsed `@see` tag and its resolved links.
351 *
352 * @category models
353 * @since 4.0.0
354 */
355 export interface JSDocApiSeeTag {
356 readonly text: string
357 readonly links: ReadonlyArray<JSDocApiSeeLink>
358 }
359
360 /**
361 * Standard tags attached to a public API record.
362 *
363 * @category models
364 * @since 4.0.0
365 */
366 export interface JSDocApiTags {
367 readonly category: string | null
368 readonly since: string | null
369 readonly stability: JSDocStability
370 readonly deprecated: string | null
371 readonly default: string | null
372 }
373
374 /**
375 * One public API record in an extracted JSDoc model.
376 *
377 * @category models
378 * @since 4.0.0
379 */
380 export interface JSDocApi {
381 readonly id: string
382 readonly kind: JSDocApiKind
383 readonly moduleName: string
384 readonly apiName: string
385 readonly localName: string
386 readonly signature: string | null
387 readonly parentApiName: string | null
388 readonly apiFqn: string
389 readonly hasFqnCollision: boolean
390 readonly bucket: ExportBucket | null
391 readonly importable: boolean
392 readonly namespacePath: ReadonlyArray<string>
393 readonly memberPath: ReadonlyArray<string>
394 readonly source: {
395 readonly file: string
396 readonly path: ReadonlyArray<string | number>
397 readonly range: readonly [number, number]
398 }
399 readonly description: ParsedDescription
400 readonly examples: ReadonlyArray<ParsedExample>
401 readonly tags: JSDocApiTags
402 readonly see: ReadonlyArray<JSDocApiSeeTag>
403 readonly importGuidance: JSDocApiImportGuidance | null
404 }
405
406 interface ParsedBarrelExports {
407 readonly namespace: ReadonlyMap<string, string>
408 readonly flat: ReadonlySet<string>
409 readonly named: ReadonlyMap<string, ReadonlySet<string>>
410 }
411
412 /**
413 * Parsed public JSDoc data paired with the normalized source file path.
414 *
415 * @category models
416 * @since 4.0.0
417 */
418 export interface ParsedJSDocFileDumpEntry extends ParsedJSDocFile {
419 readonly file: string
420 readonly imports: ParsedJSDocImports
421 }
422
423 interface AstNode {
424 readonly type: string
425 readonly range: [number, number]
426 readonly [key: string]: any
427 }
428
429 interface JSDocTag {
430 readonly name: string
431 value: string
432 readonly line: number
433 }
434
435 interface JSDocBlock {
436 readonly range: [number, number]
437 readonly raw: string
438 readonly lines: Array<string>
439 readonly tags: Array<JSDocTag>
440 readonly parsed?: ParsedCoreJSDoc
441 readonly diagnostics: Array<JSDocDiagnostic>
442 readonly internal: boolean
443 }
444
445 interface ParsedCoreJSDoc {
446 readonly description: ParsedDescription
447 readonly examples: ReadonlyArray<ParsedExample>
448 readonly tags: ReadonlyArray<JSDocTag>
449 }
450
451 interface ProgramCacheEntry {
452 readonly program?: ts.Program
453 readonly error?: string
454 reported: boolean
455 }
456
457 interface PackageMetadata {
458 readonly root: string
459 readonly sourceRoot: string
460 readonly name: string
461 readonly exports: unknown
462 }
463
464 interface PackageExportMatch {
465 readonly key: string
466 readonly value: unknown
467 readonly star: string | null
468 readonly specificity: number
469 readonly prefixLength: number
470 }
471
472 interface ParsedConfigResult {
473 readonly parsed?: ts.ParsedCommandLine
474 readonly error?: string
475 }
476
477 const programCache = new Map<string, ProgramCacheEntry>()
478 const packageMetadataCache = new Map<string, Result<PackageMetadata, string>>()
479 const barrelExportCache = new Map<string, Result<ParsedBarrelExports, string>>()
480 const tagOrder = new Map([
481 ["deprecated", 0],
482 ["default", 1],
483 ["see", 2],
484 ["stability", 3],
485 ["category", 4],
486 ["since", 5]
487 ])
488 const signatureTypeFormatFlags = ts.TypeFormatFlags.NoTruncation |
489 ts.TypeFormatFlags.UseSingleQuotesForStringLiteralType
490
491 const stableSemverRegex = /^\d+\.\d+\.\d+$/
492 const urlRegex = /^https?:\/\//
493
494 function diagnostic(code: string, message: string): JSDocDiagnostic {
495 return { code, message }
496 }
497
498 function normalizePathName(filePath: string): string {
499 return filePath.replaceAll(path.sep, "/")
500 }
501
502 function normalizePackagePath(filePath: string): string {
503 return normalizePathName(filePath).replace(/^\.\//, "./")
504 }
505
506 function escapeRegExp(value: string): string {
507 return value.replace(/[|\\{}()[\]^$+?.]/g, "\\$&")
508 }
509
510 function globToRegExp(glob: string): RegExp {
511 let source = "^"
512 for (let index = 0; index < glob.length; index++) {
513 const char = glob[index]
514 const next = glob[index + 1]
515 if (char === "*") {
516 if (next === "*") {
517 source += ".*"
518 index++
519 } else {
520 source += "[^/]*"
521 }
522 } else if (char === "?") {
523 source += "[^/]"
524 } else {
525 source += escapeRegExp(char)
526 }
527 }
528 return new RegExp(`${source}$`)
529 }
530
531 /**
532 * Creates a predicate that checks whether a filename is included by the configured JSDoc globs.
533 *
534 * @category constructors
535 * @since 4.0.0
536 */
537 export function createJSDocFileMatcher(options: {
538 readonly cwd: string
539 readonly include?: ReadonlyArray<string>
540 readonly exclude?: ReadonlyArray<string>
541 }): (filename: string) => boolean {
542 const include = options.include?.map(globToRegExp)
543 const exclude = options.exclude?.map(globToRegExp)
544 return (filename) => {
545 const normalizedFilename = normalizePathName(filename)
546 const relativeFilename = normalizePathName(path.relative(options.cwd, filename))
547 const matches = (regexp: RegExp) => regexp.test(normalizedFilename) || regexp.test(relativeFilename)
548 if (include !== undefined && !include.some(matches)) {
549 return false
550 }
551 if (exclude !== undefined && exclude.some(matches)) {
552 return false
553 }
554 return true
555 }
556 }
557
558 function isRecord(value: unknown): value is Record<string, unknown> {
559 return typeof value === "object" && value !== null && !Array.isArray(value)
560 }
561
562 function findPackageRoot(filename: string): string | undefined {
563 let directory = path.dirname(path.resolve(filename))
564 while (true) {
565 const packageJsonPath = path.join(directory, "package.json")
566 if (fs.existsSync(packageJsonPath)) {
567 return directory
568 }
569 const parent = path.dirname(directory)
570 if (parent === directory) {
571 return undefined
572 }
573 directory = parent
574 }
575 }
576
577 function readPackageMetadata(root: string): Result<PackageMetadata, string> {
578 const normalizedRoot = path.resolve(root)
579 const cached = packageMetadataCache.get(normalizedRoot)
580 if (cached !== undefined) {
581 return cached
582 }
583 const packageJsonPath = path.join(normalizedRoot, "package.json")
584 let parsed: unknown
585 try {
586 parsed = JSON.parse(fs.readFileSync(packageJsonPath, "utf8"))
587 } catch (error) {
588 const result = {
589 _tag: "Failure",
590 error: `unable to read package.json at ${packageJsonPath}: ${String(error)}`
591 } as const
592 packageMetadataCache.set(normalizedRoot, result)
593 return result
594 }
595 if (!isRecord(parsed)) {
596 const result = { _tag: "Failure", error: `package.json at ${packageJsonPath} must be an object` } as const
597 packageMetadataCache.set(normalizedRoot, result)
598 return result
599 }
600 if (typeof parsed.name !== "string" || parsed.name.length === 0) {
601 const result = {
602 _tag: "Failure",
603 error: `package.json at ${packageJsonPath} must include a non-empty name`
604 } as const
605 packageMetadataCache.set(normalizedRoot, result)
606 return result
607 }
608 if (parsed.exports === undefined) {
609 const result = { _tag: "Failure", error: `package.json at ${packageJsonPath} must include exports` } as const
610 packageMetadataCache.set(normalizedRoot, result)
611 return result
612 }
613 const result = {
614 _tag: "Success",
615 value: {
616 root: normalizedRoot,
617 sourceRoot: path.join(normalizedRoot, "src"),
618 name: parsed.name,
619 exports: parsed.exports
620 }
621 } as const
622 packageMetadataCache.set(normalizedRoot, result)
623 return result
624 }
625
626 function parseBarrelExports(indexPath: string): Result<ParsedBarrelExports, string> {
627 const normalizedIndexPath = path.resolve(indexPath)
628 const cached = barrelExportCache.get(normalizedIndexPath)
629 if (cached !== undefined) {
630 return cached
631 }
632 let source: string
633 try {
634 source = fs.readFileSync(normalizedIndexPath, "utf8")
635 } catch (error) {
636 const result = {
637 _tag: "Failure",
638 error: `unable to read barrel file ${normalizedIndexPath}: ${String(error)}`
639 } as const
640 barrelExportCache.set(normalizedIndexPath, result)
641 return result
642 }
643 const sourceFile = ts.createSourceFile(normalizedIndexPath, source, ts.ScriptTarget.Latest, true, ts.ScriptKind.TS)
644 const namespace = new Map<string, string>()
645 const flat = new Set<string>()
646 const named = new Map<string, Set<string>>()
647 for (const statement of sourceFile.statements) {
648 if (
649 ts.isExportDeclaration(statement) &&
650 statement.moduleSpecifier !== undefined &&
651 ts.isStringLiteralLike(statement.moduleSpecifier)
652 ) {
653 const moduleSpecifier = normalizePathName(statement.moduleSpecifier.text)
654 if (statement.exportClause === undefined) {
655 flat.add(moduleSpecifier)
656 } else if (ts.isNamespaceExport(statement.exportClause)) {
657 namespace.set(moduleSpecifier, statement.exportClause.name.text)
658 } else if (ts.isNamedExports(statement.exportClause)) {
659 const names = named.get(moduleSpecifier) ?? new Set<string>()
660 for (const specifier of statement.exportClause.elements) {
661 names.add(specifier.name.text)
662 }
663 named.set(moduleSpecifier, names)
664 }
665 }
666 }
667 const result = { _tag: "Success", value: { namespace, flat, named } } as const
668 barrelExportCache.set(normalizedIndexPath, result)
669 return result
670 }
671
672 function getPackageExportMatch(exports: unknown, subpath: string): PackageExportMatch | undefined {
673 if (!isRecord(exports)) {
674 return subpath === "." ? { key: ".", value: exports, star: null, specificity: 1, prefixLength: 1 } : undefined
675 }
676 if (Object.hasOwn(exports, subpath)) {
677 return {
678 key: subpath,
679 value: exports[subpath],
680 star: null,
681 specificity: Number.MAX_SAFE_INTEGER,
682 prefixLength: subpath.length
683 }
684 }
685 const matches: Array<PackageExportMatch> = []
686 for (const [key, value] of Object.entries(exports)) {
687 const starIndex = key.indexOf("*")
688 if (!key.startsWith(".") || starIndex === -1) {
689 continue
690 }
691 const prefix = key.slice(0, starIndex)
692 const suffix = key.slice(starIndex + 1)
693 if (!subpath.startsWith(prefix) || !subpath.endsWith(suffix)) {
694 continue
695 }
696 matches.push({
697 key,
698 value,
699 star: subpath.slice(prefix.length, subpath.length - suffix.length),
700 specificity: prefix.length + suffix.length,
701 prefixLength: prefix.length
702 })
703 }
704 return matches.sort((a, b) =>
705 b.specificity - a.specificity || b.prefixLength - a.prefixLength || b.key.length - a.key.length
706 )[0]
707 }
708
709 function packageExportTargetMatches(value: unknown, star: string | null, expectedTarget: string): boolean {
710 if (typeof value === "string") {
711 const target = normalizePackagePath(star === null ? value : value.replaceAll("*", star))
712 return target === expectedTarget
713 }
714 if (value === null || value === undefined) {
715 return false
716 }
717 if (Array.isArray(value)) {
718 return value.some((item) => packageExportTargetMatches(item, star, expectedTarget))
719 }
720 if (isRecord(value)) {
721 return Object.values(value).some((item) => packageExportTargetMatches(item, star, expectedTarget))
722 }
723 return false
724 }
725
726 function isPackageSubpathExported(
727 packageExports: unknown,
728 subpath: string,
729 expectedTarget: string
730 ): boolean {
731 const match = getPackageExportMatch(packageExports, subpath)
732 return match !== undefined && packageExportTargetMatches(match.value, match.star, expectedTarget)
733 }
734
735 function isPathInside(parent: string, child: string): boolean {
736 const relative = path.relative(parent, child)
737 return relative === "" || (!relative.startsWith("..") && !path.isAbsolute(relative))
738 }
739
740 function packageSpecifier(packageName: string, subpath: string): string {
741 return subpath === "" ? packageName : `${packageName}/${subpath}`
742 }
743
744 function resolveBarrelImport(
745 metadata: PackageMetadata,
746 filename: string
747 ): Result<{ readonly barrel: ParsedJSDocBarrelImport | null; readonly flatNames: ReadonlyArray<string> }, string> {
748 let directory = path.dirname(filename)
749 while (isPathInside(metadata.sourceRoot, directory)) {
750 const indexPath = path.join(directory, "index.ts")
751 if (indexPath !== filename && fs.existsSync(indexPath)) {
752 const expectedExport = `./${normalizePathName(path.relative(directory, filename))}`
753 const parsed = parseBarrelExports(indexPath)
754 if (parsed._tag === "Failure") {
755 return parsed
756 }
757 const barrelSubpath = normalizePathName(path.relative(metadata.sourceRoot, directory))
758 const exportSubpath = barrelSubpath === "" ? "." : `./${barrelSubpath}`
759 const exportTarget = barrelSubpath === "" ? "./src/index.ts" : `./src/${barrelSubpath}/index.ts`
760 if (isPackageSubpathExported(metadata.exports, exportSubpath, exportTarget)) {
761 const moduleSpecifier = packageSpecifier(metadata.name, barrelSubpath)
762 const flatNames = Array.from(parsed.value.named.get(expectedExport) ?? [])
763 const namespace = parsed.value.namespace.get(expectedExport)
764 if (namespace !== undefined) {
765 return {
766 _tag: "Success",
767 value: { barrel: { type: "namespace", module: moduleSpecifier, name: namespace }, flatNames }
768 }
769 }
770 if (parsed.value.flat.has(expectedExport)) {
771 return {
772 _tag: "Success",
773 value: { barrel: { type: "flat", module: moduleSpecifier }, flatNames }
774 }
775 }
776 if (flatNames.length > 0) {
777 return {
778 _tag: "Success",
779 value: { barrel: { type: "flat", module: moduleSpecifier }, flatNames }
780 }
781 }
782 }
783 }
784 if (directory === metadata.sourceRoot) {
785 break
786 }
787 directory = path.dirname(directory)
788 }
789 return { _tag: "Success", value: { barrel: null, flatNames: [] } }
790 }
791
792 function resolveJSDocImports(
793 cwd: string,
794 filename: string,
795 sourceFile: ts.SourceFile,
796 checker: ts.TypeChecker
797 ): Result<ParsedJSDocImports, string> {
798 const absoluteFilename = path.resolve(filename)
799 const packageRoot = findPackageRoot(absoluteFilename)
800 const relativeFilename = normalizePathName(path.relative(cwd, absoluteFilename))
801 if (packageRoot === undefined) {
802 return { _tag: "Failure", error: `no package.json found for ${relativeFilename}` }
803 }
804 const metadata = readPackageMetadata(packageRoot)
805 if (metadata._tag === "Failure") {
806 return metadata
807 }
808 const relativeToSourceRoot = normalizePathName(path.relative(metadata.value.sourceRoot, absoluteFilename))
809 if (!isPathInside(metadata.value.sourceRoot, absoluteFilename)) {
810 return {
811 _tag: "Failure",
812 error: `${relativeFilename} is not under ${normalizePathName(path.relative(cwd, metadata.value.sourceRoot))}`
813 }
814 }
815 if (path.extname(absoluteFilename) !== ".ts" || absoluteFilename.endsWith(".d.ts")) {
816 return {
817 _tag: "Failure",
818 error: `${relativeFilename} is not a TypeScript source module`
819 }
820 }
821 const isIndex = path.basename(absoluteFilename) === "index.ts"
822 const moduleSubpath = isIndex
823 ? relativeToSourceRoot.slice(0, -"index.ts".length).replace(/\/$/, "")
824 : relativeToSourceRoot.slice(0, -".ts".length)
825 const moduleExportSubpath = moduleSubpath === "" ? "." : `./${moduleSubpath}`
826 const moduleExportTarget = `./src/${relativeToSourceRoot}`
827 if (!isPackageSubpathExported(metadata.value.exports, moduleExportSubpath, moduleExportTarget)) {
828 return {
829 _tag: "Failure",
830 error: `package.json exports do not expose ${
831 packageSpecifier(metadata.value.name, moduleSubpath)
832 } for ${relativeFilename}`
833 }
834 }
835 const symbol = checker.getSymbolAtLocation(sourceFile)
836 const barrel = isIndex
837 ? {
838 _tag: "Success",
839 value: {
840 barrel: null,
841 flatNames: symbol === undefined ? [] : checker.getExportsOfModule(symbol).map((item) => item.name)
842 }
843 } as const
844 : resolveBarrelImport(metadata.value, absoluteFilename)
845 if (barrel._tag === "Failure") {
846 return barrel
847 }
848 return {
849 _tag: "Success",
850 value: {
851 module: packageSpecifier(metadata.value.name, moduleSubpath),
852 barrel: barrel.value.barrel,
853 flatNames: barrel.value.flatNames
854 }
855 }
856 }
857
858 /**
859 * Reads source text from an Oxlint-compatible rule context.
860 *
861 * @category getters
862 * @since 4.0.0
863 */
864 export function getSourceText(context: {
865 readonly sourceCode: { readonly text?: string; getText(node?: unknown): string }
866 }): string {
867 return context.sourceCode.text ?? context.sourceCode.getText()
868 }
869
870 /**
871 * Resolves the working directory from an Oxlint-compatible rule context.
872 *
873 * @category getters
874 * @since 4.0.0
875 */
876 export function getCwd(context: { readonly cwd?: string; getCwd?: () => string }): string {
877 return context.cwd ?? context.getCwd?.() ?? process.cwd()
878 }
879
880 function skipWhitespace(source: string, end: number): number {
881 while (end > 0 && /\s/.test(source[end - 1])) {
882 end--
883 }
884 return end
885 }
886
887 function isSkippableDirectiveComment(line: string): boolean {
888 const trimmed = line.trim()
889 return trimmed.startsWith("// @ts-expect-error") ||
890 trimmed.startsWith("// @ts-ignore") ||
891 trimmed.startsWith("// @effect-diagnostics") ||
892 trimmed.startsWith("// eslint-disable-next-line") ||
893 trimmed.startsWith("// oxlint-disable-next-line")
894 }
895
896 function skipDirectiveComments(source: string, end: number): number {
897 while (end > 0) {
898 const lineStart = source.lastIndexOf("\n", end - 1) + 1
899 if (!isSkippableDirectiveComment(source.slice(lineStart, end))) {
900 return end
901 }
902 end = skipWhitespace(source, lineStart)
903 }
904 return end
905 }
906
907 /**
908 * Finds the JSDoc block immediately preceding an AST node.
909 *
910 * @category parsing
911 * @since 4.0.0
912 */
913 export function findLeadingJSDoc(
914 source: string,
915 node: AstNode,
916 ignoredRange?: [number, number]
917 ): JSDocBlock | undefined {
918 const end = skipDirectiveComments(source, skipWhitespace(source, node.range[0]))
919 if (!source.slice(0, end).endsWith("*/")) {
920 return undefined
921 }
922
923 const start = source.lastIndexOf("/*", end)
924 if (start === -1 || source[start + 2] !== "*") {
925 return undefined
926 }
927 const range: [number, number] = [start, end]
928 if (ignoredRange !== undefined && range[0] === ignoredRange[0] && range[1] === ignoredRange[1]) {
929 return undefined
930 }
931 return parseJSDocBlock(source.slice(start, end), range)
932 }
933
934 /**
935 * Parses one raw JSDoc block into the standard description, example, and tag structure.
936 *
937 * **Details**
938 *
939 * The block must have one short description paragraph, optional `When to use`, `Details`, and `Gotchas` sections in that order, then any example sections before tags. Example titles must be unique after trimming and lowercasing, each example must contain exactly one non-empty TypeScript code fence, and boundaries between sections, examples, and tags must use exactly one blank line.
940 *
941 * **Example** (Parsing a block)
942 *
943 * ```ts import.meta.vitest
944 * import { parseJSDoc } from "@effect/jsdocs"
945 *
946 * const rawBlock = [
947 * "/" + "**",
948 * " * A value.",
949 * " *",
950 * " * @category models",
951 * " * @since 4.0.0",
952 * " *" + "/"
953 * ].join("\n")
954 * const result = parseJSDoc(rawBlock)
955 *
956 * result._tag // => "Success"
957 * ```
958 *
959 * @category parsing
960 * @since 4.0.0
961 */
962 export function parseJSDoc(raw: string): Result<ParsedCoreJSDoc, JSDocParseError> {
963 const block = parseJSDocBlock(raw, [0, raw.length])
964 if (block.internal) {
965 return { _tag: "Failure", error: { diagnostics: [diagnostic("internal", "Internal JSDoc blocks are ignored")] } }
966 }
967 if (block.diagnostics.length > 0 || block.parsed === undefined) {
968 return { _tag: "Failure", error: { diagnostics: block.diagnostics } }
969 }
970 return { _tag: "Success", value: block.parsed }
971 }
972
973 function parseLooseJSDocBlock(raw: string, range: [number, number]): JSDocBlock {
974 const body = raw.replace(/^\/\*\*/, "").replace(/\*\/$/, "")
975 const rawLines = body.split(/\r\n|\r|\n/)
976 const lines = rawLines.map((line) => line.replace(/^\s*\* ?/, "").trimEnd())
977 const normalized = trimStructuralBlankLines(lines)
978 const tags = parseTags(normalized)
979 const internal = tags.some((tag) => tag.name === "internal")
980 return { range, raw, lines: normalized, tags, diagnostics: [], internal }
981 }
982
983 function parseJSDocBlock(raw: string, range: [number, number]): JSDocBlock {
984 const base = parseLooseJSDocBlock(raw, range)
985 const { lines: normalized, tags, internal } = base
986 if (internal) {
987 return base
988 }
989 const result = parseCoreJSDoc(normalized, tags)
990 const block: JSDocBlock = {
991 ...base,
992 range,
993 raw,
994 lines: normalized,
995 tags,
996 diagnostics: result._tag === "Failure" ? Array.from(result.error.diagnostics) : [],
997 internal
998 }
999 return result._tag === "Success" ? { ...block, parsed: result.value } : block
1000 }
1001
1002 function trimStructuralBlankLines(lines: Array<string>): Array<string> {
1003 let start = 0
1004 let end = lines.length
1005 if (lines[start]?.trim() === "") {
1006 start++
1007 }
1008 if (end > start && lines[end - 1]?.trim() === "") {
1009 end--
1010 }
1011 return lines.slice(start, end)
1012 }
1013
1014 function parseTags(lines: Array<string>): Array<JSDocTag> {
1015 const tags: Array<JSDocTag> = []
1016 let current: JSDocTag | undefined
1017 let inFence = false
1018
1019 for (let index = 0; index < lines.length; index++) {
1020 const trimmed = lines[index].trim()
1021 if (trimmed.startsWith("```")) {
1022 inFence = !inFence
1023 current = undefined
1024 continue
1025 }
1026 if (inFence) {
1027 continue
1028 }
1029
1030 const match = /^@([A-Za-z][\w-]*)(?:\s+(.*))?$/.exec(trimmed)
1031 if (match) {
1032 current = { name: match[1], value: match[2]?.trim() ?? "", line: index }
1033 tags.push(current)
1034 continue
1035 }
1036
1037 if (current !== undefined && trimmed !== "") {
1038 current.value = current.value === "" ? trimmed : `${current.value}\n${trimmed}`
1039 } else if (trimmed === "") {
1040 current = undefined
1041 }
1042 }
1043
1044 return tags
1045 }
1046
1047 function parseCoreJSDoc(lines: Array<string>, tags: Array<JSDocTag>): Result<ParsedCoreJSDoc, JSDocParseError> {
1048 const diagnostics: Array<JSDocDiagnostic> = []
1049 const firstTagLine = tags[0]?.line ?? lines.length
1050 const content = lines.slice(0, firstTagLine)
1051
1052 if (lines.length === 0) {
1053 diagnostics.push(diagnostic("missing-description", "JSDoc must include a short description"))
1054 }
1055 if (content.at(-1)?.trim() === "" && tags.length > 0) {
1056 // exactly one blank before tags is validated by ensuring the last content line is blank and the previous is not blank
1057 if (content.length < 2 || content[content.length - 2]?.trim() === "") {
1058 diagnostics.push(
1059 diagnostic("invalid-spacing", "JSDoc tags must be separated from description content by exactly one blank line")
1060 )
1061 }
1062 } else if (tags.length > 0 && content.length > 0) {
1063 diagnostics.push(
1064 diagnostic("invalid-spacing", "JSDoc tags must be separated from description content by exactly one blank line")
1065 )
1066 }
1067
1068 if (content[0]?.trim() === "") {
1069 diagnostics.push(diagnostic("leading-blank", "JSDoc must not start with a blank line"))
1070 }
1071 const contentWithoutTagBlank = tags.length > 0 && content.at(-1)?.trim() === "" ? content.slice(0, -1) : content
1072 if (contentWithoutTagBlank.at(-1)?.trim() === "") {
1073 diagnostics.push(diagnostic("trailing-blank", "JSDoc description must not end with a blank line"))
1074 }
1075
1076 const parsedContent = parseDescriptionContent(contentWithoutTagBlank)
1077 diagnostics.push(...parsedContent.diagnostics)
1078
1079 if (diagnostics.length > 0 || parsedContent.value === undefined) {
1080 return { _tag: "Failure", error: { diagnostics: uniqueDiagnostics(diagnostics) } }
1081 }
1082 return {
1083 _tag: "Success",
1084 value: {
1085 description: parsedContent.value.description,
1086 examples: parsedContent.value.examples,
1087 tags
1088 }
1089 }
1090 }
1091
1092 function uniqueDiagnostics(
1093 diagnostics: ReadonlyArray<JSDocDiagnostic>
1094 ): ReadonlyArray<JSDocDiagnostic> {
1095 const seen = new Set<string>()
1096 return diagnostics.filter((item) => {
1097 const key = `${item.code}:${item.message}`
1098 if (seen.has(key)) {
1099 return false
1100 }
1101 seen.add(key)
1102 return true
1103 })
1104 }
1105
1106 const standardHeadings = ["**When to use**", "**Details**", "**Gotchas**"] as const
1107
1108 type StandardHeading = typeof standardHeadings[number]
1109
1110 const whenToUsePrefixes = ["Use to", "Use when", "Use as", "Use with"] as const
1111
1112 interface ParsedContentResult {
1113 readonly value?: {
1114 readonly description: ParsedDescription
1115 readonly examples: ReadonlyArray<ParsedExample>
1116 }
1117 readonly diagnostics: ReadonlyArray<JSDocDiagnostic>
1118 }
1119
1120 function parseDescriptionContent(lines: Array<string>): ParsedContentResult {
1121 const diagnostics: Array<JSDocDiagnostic> = []
1122 const sections: Record<StandardHeading, string | null> = {
1123 "**When to use**": null,
1124 "**Details**": null,
1125 "**Gotchas**": null
1126 }
1127 const examples: Array<ParsedExample> = []
1128 const exampleTitles = new Set<string>()
1129 let index = 0
1130 let currentSectionOrder = -1
1131 let examplesStarted = false
1132
1133 while (index < lines.length && lines[index].trim() !== "" && !isHeadingLine(lines[index])) {
1134 if (isForbiddenMarkdownHeading(lines[index], false)) {
1135 diagnostics.push(diagnostic("invalid-heading", "Markdown headings are not allowed in JSDoc descriptions"))
1136 }
1137 index++
1138 }
1139
1140 const shortLines = lines.slice(0, index)
1141 if (shortLines.length === 0 || joinBody(shortLines).trim() === "") {
1142 diagnostics.push(diagnostic("missing-description", "JSDoc must include a short description"))
1143 }
1144 if (index < lines.length && lines[index].trim() === "") {
1145 const next = lines[index + 1]
1146 if (next !== undefined && !isHeadingLine(next)) {
1147 diagnostics.push(diagnostic("multiple-description-paragraphs", "JSDoc short description must be one paragraph"))
1148 }
1149 }
1150
1151 while (index < lines.length) {
1152 if (lines[index].trim() !== "") {
1153 diagnostics.push(diagnostic("invalid-spacing", "JSDoc sections must be separated by exactly one blank line"))
1154 break
1155 }
1156 if (lines[index + 1]?.trim() === "") {
1157 diagnostics.push(diagnostic("invalid-spacing", "JSDoc sections must be separated by exactly one blank line"))
1158 while (lines[index + 1]?.trim() === "") index++
1159 }
1160 index++
1161 if (index >= lines.length) {
1162 break
1163 }
1164
1165 const line = lines[index].trim()
1166 if (line.startsWith("**Example**")) {
1167 examplesStarted = true
1168 const parsed = parseExample(lines, index)
1169 diagnostics.push(...parsed.diagnostics)
1170 if (parsed.example !== undefined) {
1171 const key = parsed.example.title.trim().toLowerCase()
1172 if (exampleTitles.has(key)) {
1173 diagnostics.push(diagnostic("duplicate-example", `Duplicate example title: ${parsed.example.title.trim()}`))
1174 }
1175 exampleTitles.add(key)
1176 examples.push(parsed.example)
1177 }
1178 index = parsed.nextIndex
1179 continue
1180 }
1181
1182 const heading = standardHeadings.find((candidate) => candidate === line)
1183 if (heading !== undefined) {
1184 if (examplesStarted) {
1185 diagnostics.push(diagnostic("section-after-example", `${heading} must appear before examples`))
1186 }
1187 const order = standardHeadings.indexOf(heading)
1188 if (order <= currentSectionOrder) {
1189 diagnostics.push(diagnostic("section-out-of-order", `${heading} is out of order or duplicated`))
1190 }
1191 currentSectionOrder = Math.max(currentSectionOrder, order)
1192 if (sections[heading] !== null) {
1193 diagnostics.push(diagnostic("duplicate-section", `${heading} may appear at most once`))
1194 }
1195 const parsed = parseSection(lines, index)
1196 diagnostics.push(...parsed.diagnostics)
1197 sections[heading] = parsed.body
1198 index = parsed.nextIndex
1199 continue
1200 }
1201
1202 if (isNearMissHeading(line)) {
1203 diagnostics.push(diagnostic("invalid-heading", `Invalid JSDoc section heading: ${line}`))
1204 index++
1205 continue
1206 }
1207 if (isBoldOnlyLine(line)) {
1208 diagnostics.push(diagnostic("unknown-heading", `Unknown JSDoc section heading: ${line}`))
1209 index++
1210 continue
1211 }
1212 if (isForbiddenMarkdownHeading(line, false)) {
1213 diagnostics.push(diagnostic("invalid-heading", "Markdown headings are not allowed in JSDoc descriptions"))
1214 index++
1215 continue
1216 }
1217 diagnostics.push(
1218 diagnostic("invalid-description", "JSDoc description content must appear under a standard section heading")
1219 )
1220 index++
1221 }
1222
1223 const whenToUse = sections["**When to use**"]
1224 if (whenToUse !== null && !hasWhenToUsePrefix(whenToUse)) {
1225 diagnostics.push(
1226 diagnostic(
1227 "when-to-use-format",
1228 `**When to use** must start with one of: ${whenToUsePrefixes.map((prefix) => `\`${prefix}\``).join(", ")}`
1229 )
1230 )
1231 }
1232
1233 if (diagnostics.length > 0) {
1234 return { diagnostics }
1235 }
1236 return {
1237 value: {
1238 description: {
1239 short: joinBody(shortLines),
1240 whenToUse: sections["**When to use**"],
1241 details: sections["**Details**"],
1242 gotchas: sections["**Gotchas**"]
1243 },
1244 examples
1245 },
1246 diagnostics
1247 }
1248 }
1249
1250 function hasWhenToUsePrefix(text: string): boolean {
1251 const trimmed = text.trimStart()
1252 return whenToUsePrefixes.some((prefix) => trimmed === prefix || trimmed.startsWith(`${prefix} `))
1253 }
1254
1255 function parseSection(lines: Array<string>, headingIndex: number): {
1256 readonly body: string | null
1257 readonly nextIndex: number
1258 readonly diagnostics: ReadonlyArray<JSDocDiagnostic>
1259 } {
1260 const diagnostics: Array<JSDocDiagnostic> = []
1261 if (lines[headingIndex + 1]?.trim() !== "") {
1262 diagnostics.push(
1263 diagnostic("invalid-spacing", `${lines[headingIndex].trim()} must be followed by exactly one blank line`)
1264 )
1265 }
1266 let index = headingIndex + 2
1267 const bodyStart = index
1268 let inFence = false
1269 while (index < lines.length) {
1270 const trimmed = lines[index].trim()
1271 if (trimmed.startsWith("```")) {
1272 if (isTypeScriptFence(trimmed)) {
1273 diagnostics.push(diagnostic("loose-ts-fence", "TypeScript examples must use **Example** (Title) sections"))
1274 }
1275 inFence = !inFence
1276 }
1277 if (!inFence && trimmed === "" && isHeadingLine(lines[index + 1])) {
1278 break
1279 }
1280 if (!inFence && trimmed !== "" && isForbiddenMarkdownHeading(trimmed, false)) {
1281 diagnostics.push(diagnostic("invalid-heading", "Markdown headings are not allowed in JSDoc descriptions"))
1282 }
1283 if (
1284 !inFence && isBoldOnlyLine(trimmed) && !standardHeadings.includes(trimmed as StandardHeading) &&
1285 !trimmed.startsWith("**Example**")
1286 ) {
1287 diagnostics.push(diagnostic("unknown-heading", `Unknown JSDoc section heading: ${trimmed}`))
1288 }
1289 index++
1290 }
1291 const bodyLines = lines.slice(bodyStart, index)
1292 if (joinBody(bodyLines).trim() === "") {
1293 diagnostics.push(diagnostic("empty-section", `${lines[headingIndex].trim()} must have a non-empty body`))
1294 }
1295 if (bodyLines.at(-1)?.trim() === "") {
1296 diagnostics.push(diagnostic("invalid-spacing", "Section bodies must not end with extra blank lines"))
1297 }
1298 return { body: joinBody(bodyLines), nextIndex: index, diagnostics }
1299 }
1300
1301 const isTypeScriptFence = (line: string): boolean => /^```ts(?:\s.*)?$/.test(line)
1302
1303 function parseExample(lines: Array<string>, headingIndex: number): {
1304 readonly example?: ParsedExample
1305 readonly nextIndex: number
1306 readonly diagnostics: ReadonlyArray<JSDocDiagnostic>
1307 } {
1308 const diagnostics: Array<JSDocDiagnostic> = []
1309 const heading = lines[headingIndex].trim()
1310 const match = /^\*\*Example\*\* \((.+)\)$/.exec(heading)
1311 if (!match || match[1].trim() === "") {
1312 diagnostics.push(diagnostic("malformed-example", "TypeScript examples must use **Example** (Title)"))
1313 }
1314 if (lines[headingIndex + 1]?.trim() !== "") {
1315 diagnostics.push(diagnostic("invalid-spacing", "Example headings must be followed by exactly one blank line"))
1316 }
1317
1318 let index = headingIndex + 2
1319 const bodyStart = index
1320 let fenceIndex = -1
1321 while (index < lines.length) {
1322 const trimmed = lines[index].trim()
1323 if (isTypeScriptFence(trimmed)) {
1324 fenceIndex = index
1325 break
1326 }
1327 if (trimmed.startsWith("```")) {
1328 diagnostics.push(diagnostic("malformed-example", "Examples may only contain one TypeScript code fence"))
1329 }
1330 if (trimmed === "" && isHeadingLine(lines[index + 1])) {
1331 break
1332 }
1333 if (trimmed.startsWith("@")) {
1334 break
1335 }
1336 index++
1337 }
1338
1339 if (fenceIndex === -1) {
1340 diagnostics.push(diagnostic("malformed-example", "Examples must include a non-empty ```ts fence"))
1341 return { nextIndex: index, diagnostics }
1342 }
1343
1344 const bodyLines = lines.slice(bodyStart, fenceIndex)
1345 const nonEmptyBody = joinBody(bodyLines).trim() !== ""
1346 if (nonEmptyBody && bodyLines.at(-1)?.trim() !== "") {
1347 diagnostics.push(
1348 diagnostic("invalid-spacing", "Example prose must be separated from code by exactly one blank line")
1349 )
1350 }
1351 const prose = nonEmptyBody ? joinBody(bodyLines.slice(0, bodyLines.at(-1)?.trim() === "" ? -1 : undefined)) : null
1352
1353 index = fenceIndex + 1
1354 const codeStart = index
1355 while (index < lines.length && lines[index].trim() !== "```") {
1356 if (isTypeScriptFence(lines[index].trim())) {
1357 diagnostics.push(diagnostic("malformed-example", "Examples must contain exactly one TypeScript code fence"))
1358 }
1359 index++
1360 }
1361 const codeLines = lines.slice(codeStart, index)
1362 if (index >= lines.length) {
1363 diagnostics.push(diagnostic("malformed-example", "Examples must close the TypeScript code fence"))
1364 }
1365 if (joinBody(codeLines).trim() === "") {
1366 diagnostics.push(diagnostic("malformed-example", "Examples must include non-empty TypeScript code"))
1367 }
1368 index++
1369 if (index < lines.length && lines[index].trim() !== "" && !lines[index].trim().startsWith("@")) {
1370 diagnostics.push(
1371 diagnostic("invalid-spacing", "Examples must be separated from following content by exactly one blank line")
1372 )
1373 }
1374
1375 const result = { nextIndex: index, diagnostics }
1376 return match
1377 ? { ...result, example: { title: match[1].trim(), body: prose, code: joinBody(codeLines) } }
1378 : result
1379 }
1380
1381 function parseModuleExamples(block: JSDocBlock): {
1382 readonly examples: ReadonlyArray<ParsedExample>
1383 readonly diagnostics: ReadonlyArray<JSDocDiagnostic>
1384 } {
1385 const diagnostics: Array<JSDocDiagnostic> = []
1386 const examples: Array<ParsedExample> = []
1387 const exampleTitles = new Set<string>()
1388 const firstTagLine = block.tags[0]?.line ?? block.lines.length
1389 const lines = block.lines.slice(0, firstTagLine)
1390 let index = 0
1391 while (index < lines.length) {
1392 const trimmed = lines[index].trim()
1393 if (trimmed.startsWith("**Example**")) {
1394 const parsed = parseExample(lines, index)
1395 diagnostics.push(...parsed.diagnostics)
1396 if (parsed.example !== undefined) {
1397 const key = parsed.example.title.trim().toLowerCase()
1398 if (exampleTitles.has(key)) {
1399 diagnostics.push(diagnostic("duplicate-example", `Duplicate example title: ${parsed.example.title.trim()}`))
1400 }
1401 exampleTitles.add(key)
1402 examples.push(parsed.example)
1403 }
1404 index = Math.max(parsed.nextIndex, index + 1)
1405 continue
1406 }
1407 if (trimmed.startsWith("```")) {
1408 diagnostics.push(
1409 diagnostic("loose-ts-fence", "Code fences in module JSDoc must use **Example** (Title) sections")
1410 )
1411 index++
1412 while (index < lines.length && !lines[index].trim().startsWith("```")) index++
1413 if (index < lines.length) index++
1414 continue
1415 }
1416 index++
1417 }
1418 return { examples, diagnostics }
1419 }
1420
1421 function joinBody(lines: ReadonlyArray<string>): string {
1422 let start = 0
1423 let end = lines.length
1424 while (start < end && lines[start]?.trim() === "") start++
1425 while (end > start && lines[end - 1]?.trim() === "") end--
1426 return lines.slice(start, end).join("\n")
1427 }
1428
1429 function isHeadingLine(line: string | undefined): boolean {
1430 if (line === undefined) return false
1431 const trimmed = line.trim()
1432 return standardHeadings.includes(trimmed as StandardHeading) || trimmed.startsWith("**Example**") ||
1433 isNearMissHeading(trimmed) || isBoldOnlyLine(trimmed) || isForbiddenMarkdownHeading(trimmed, false)
1434 }
1435
1436 function isNearMissHeading(line: string): boolean {
1437 return /^\*\*(When to use|When To Use|Details|Gotchas).*\*\*/.test(line) &&
1438 !standardHeadings.includes(line as StandardHeading)
1439 }
1440
1441 function isBoldOnlyLine(line: string): boolean {
1442 return /^\*\*[^*]+\*\*(?:\s*)$/.test(line)
1443 }
1444
1445 function isForbiddenMarkdownHeading(line: string, inFence: boolean): boolean {
1446 return !inFence && /^#{1,6}\s+/.test(line.trim())
1447 }
1448
1449 function parseSeeTag(value: string): ParsedSeeTag {
1450 return { text: value, links: extractParsedInlineLinks(value) }
1451 }
1452
1453 function extractParsedInlineLinks(source: string): ReadonlyArray<ParsedInlineLink> {
1454 const links: Array<ParsedInlineLink> = []
1455 let index = source.indexOf("{@link")
1456 while (index !== -1) {
1457 if (!isInlineLinkStart(source, index)) {
1458 index = source.indexOf("{@link", index + 1)
1459 continue
1460 }
1461 const end = source.indexOf("}", index + "{@link".length)
1462 if (end === -1) {
1463 break
1464 }
1465 const raw = source.slice(index, end + 1)
1466 const content = raw.slice("{@link".length, -1).trim()
1467 const pipeIndex = content.indexOf("|")
1468 const beforeLabel = pipeIndex === -1 ? content : content.slice(0, pipeIndex).trim()
1469 const target = beforeLabel.split(/\s+/)[0] ?? ""
1470 const text = pipeIndex === -1
1471 ? beforeLabel.slice(target.length).trim() || null
1472 : content.slice(pipeIndex + 1).trim() || null
1473 links.push({ raw, target, text })
1474 index = source.indexOf("{@link", end + 1)
1475 }
1476 return links
1477 }
1478
1479 function buildTags(
1480 scope: DocScope,
1481 tags: ReadonlyArray<JSDocTag>,
1482 requireStability = false
1483 ): Result<ParsedModuleTags | ParsedDeclarationTags | ParsedNamespaceTags | ParsedMemberTags, JSDocParseError> {
1484 const diagnostics: Array<JSDocDiagnostic> = []
1485 const allowed = scope === "declaration"
1486 ? new Set(["deprecated", "see", "stability", "category", "since"])
1487 : scope === "member"
1488 ? new Set(["deprecated", "default", "see", "stability", "since"])
1489 : scope === "module"
1490 ? new Set(["deprecated", "see", "stability", "since"])
1491 : new Set(["deprecated", "see", "stability", "category", "since"])
1492 let previousOrder = -1
1493 const values = new Map<string, Array<string>>()
1494
1495 for (const tag of tags) {
1496 if (tag.name === "internal") {
1497 continue
1498 }
1499 if (tag.name === "example") {
1500 diagnostics.push(
1501 diagnostic("forbidden-tag", "@example is not allowed; use a canonical **Example** (Title) section")
1502 )
1503 continue
1504 }
1505 if (!allowed.has(tag.name)) {
1506 diagnostics.push(
1507 diagnostic(
1508 "forbidden-tag",
1509 `@${tag.name} is not allowed in ${scope === "namespace-declaration" ? "namespace" : scope} JSDoc`
1510 )
1511 )
1512 continue
1513 }
1514 const order = tagOrder.get(tag.name) ?? previousOrder
1515 if (order < previousOrder) {
1516 diagnostics.push(diagnostic("tag-out-of-order", `@${tag.name} is out of order in JSDoc`))
1517 }
1518 previousOrder = Math.max(previousOrder, order)
1519 values.set(tag.name, [...values.get(tag.name) ?? [], tag.value.trim()])
1520 }
1521
1522 const singletonTags = scope === "member"
1523 ? ["deprecated", "default", "stability", "since"]
1524 : ["deprecated", "stability", "category", "since"]
1525 for (const tag of singletonTags) {
1526 if ((values.get(tag)?.length ?? 0) > 1) {
1527 diagnostics.push(diagnostic("duplicate-tag", `JSDoc blocks may contain at most one @${tag} tag`))
1528 }
1529 }
1530
1531 const see = values.get("see") ?? []
1532 for (const value of see) {
1533 if (value === "") {
1534 diagnostics.push(diagnostic("empty-tag", "@see must include a value"))
1535 }
1536 }
1537 const deprecated = values.get("deprecated")?.[0] ?? null
1538 const stability = values.get("stability")?.[0]
1539 if (stability !== undefined && stability !== "stable" && stability !== "unstable" && stability !== "experimental") {
1540 diagnostics.push(
1541 diagnostic("invalid-stability", "@stability must have the value stable, unstable, or experimental")
1542 )
1543 }
1544 if (requireStability && stability === undefined) {
1545 diagnostics.push(
1546 diagnostic(
1547 "missing-tag",
1548 scope === "module" ? "Module JSDoc must include @stability" : "Public JSDoc must include @stability"
1549 )
1550 )
1551 }
1552 const resolvedStability: JSDocStability = stability === "unstable" || stability === "experimental"
1553 ? stability
1554 : "stable"
1555 if (deprecated === "") diagnostics.push(diagnostic("empty-tag", "@deprecated must include a message"))
1556 const since = values.get("since")?.[0] ?? null
1557 if ((scope === "declaration" || scope === "namespace" || scope === "namespace-declaration") && since === null) {
1558 diagnostics.push(
1559 diagnostic(
1560 "missing-tag",
1561 scope === "declaration" ? "Public JSDoc must include @since" : "Namespace JSDoc must include @since"
1562 )
1563 )
1564 }
1565 if (scope === "module" && since === null) {
1566 diagnostics.push(diagnostic("missing-tag", "Module JSDoc must include @since"))
1567 }
1568 if (since !== null && !stableSemverRegex.test(since)) {
1569 diagnostics.push(diagnostic("invalid-since", "@since must be a stable semver version like 1.2.3"))
1570 }
1571
1572 if (scope === "declaration") {
1573 const category = values.get("category")?.[0] ?? null
1574 if (category === null) diagnostics.push(diagnostic("missing-tag", "Public JSDoc must include @category"))
1575 if (category === "") diagnostics.push(diagnostic("empty-tag", "@category must include a value"))
1576 if (diagnostics.length > 0 || category === null || since === null) {
1577 return { _tag: "Failure", error: { diagnostics } }
1578 }
1579 return {
1580 _tag: "Success",
1581 value: { category, since, stability: resolvedStability, deprecated, see: see.map(parseSeeTag) }
1582 }
1583 }
1584
1585 if (scope === "member") {
1586 const defaultValue = values.get("default")?.[0] ?? null
1587 if (defaultValue === "") diagnostics.push(diagnostic("empty-tag", "@default must include a value"))
1588 if (diagnostics.length > 0) return { _tag: "Failure", error: { diagnostics } }
1589 return {
1590 _tag: "Success",
1591 value: { since, stability: resolvedStability, default: defaultValue, deprecated, see: see.map(parseSeeTag) }
1592 }
1593 }
1594
1595 if (scope === "module") {
1596 if (diagnostics.length > 0 || since === null) return { _tag: "Failure", error: { diagnostics } }
1597 return { _tag: "Success", value: { since, stability: resolvedStability, deprecated, see: see.map(parseSeeTag) } }
1598 }
1599
1600 const category = values.get("category")?.[0] ?? null
1601 if (category === "") diagnostics.push(diagnostic("empty-tag", "@category must include a value"))
1602 if (diagnostics.length > 0 || since === null) return { _tag: "Failure", error: { diagnostics } }
1603 return {
1604 _tag: "Success",
1605 value: { category, since, stability: resolvedStability, deprecated, see: see.map(parseSeeTag) }
1606 }
1607 }
1608
1609 function formatDiagnostic(diagnostic: ts.Diagnostic): string {
1610 return ts.flattenDiagnosticMessageText(diagnostic.messageText, "\n")
1611 }
1612
1613 function parseTsConfig(tsconfigPath: string): ParsedConfigResult {
1614 const config = ts.readConfigFile(tsconfigPath, ts.sys.readFile)
1615 if (config.error !== undefined) {
1616 return { error: `Unable to read TypeScript config ${tsconfigPath}: ${formatDiagnostic(config.error)}` }
1617 }
1618
1619 const parsed = ts.parseJsonConfigFileContent(config.config, ts.sys, path.dirname(tsconfigPath))
1620 if (parsed.errors.length > 0) {
1621 return {
1622 error: `Unable to parse TypeScript config ${tsconfigPath}: ${parsed.errors.map(formatDiagnostic).join("; ")}`
1623 }
1624 }
1625 return { parsed }
1626 }
1627
1628 function collectTsConfigFiles(tsconfigPath: string, seen: Set<string>, fileNames: Set<string>): ParsedConfigResult {
1629 if (seen.has(tsconfigPath)) return {}
1630 seen.add(tsconfigPath)
1631 const result = parseTsConfig(tsconfigPath)
1632 if (result.error !== undefined || result.parsed === undefined) return result
1633 for (const fileName of result.parsed.fileNames) fileNames.add(fileName)
1634 for (const reference of result.parsed.projectReferences ?? []) {
1635 const referenceResult = collectTsConfigFiles(ts.resolveProjectReferencePath(reference), seen, fileNames)
1636 if (referenceResult.error !== undefined) return referenceResult
1637 }
1638 return result
1639 }
1640
1641 /**
1642 * Loads and caches the TypeScript program for a project configuration.
1643 *
1644 * @category constructors
1645 * @since 4.0.0
1646 */
1647 export function getProgram(tsconfigPath: string): ProgramCacheEntry {
1648 const cached = programCache.get(tsconfigPath)
1649 if (cached !== undefined) return cached
1650 const fileNames = new Set<string>()
1651 const result = collectTsConfigFiles(tsconfigPath, new Set(), fileNames)
1652 if (result.error !== undefined || result.parsed === undefined) {
1653 const entry = { error: result.error ?? `Unable to parse TypeScript config ${tsconfigPath}`, reported: false }
1654 programCache.set(tsconfigPath, entry)
1655 return entry
1656 }
1657 const program = ts.createProgram(Array.from(fileNames), result.parsed.options)
1658 const entry = { program, reported: false }
1659 programCache.set(tsconfigPath, entry)
1660 return entry
1661 }
1662
1663 function resolveJSDocLinkSymbol(
1664 link: ts.JSDocLink,
1665 checker: ts.TypeChecker
1666 ): ts.Symbol | undefined {
1667 return link.name === undefined ? undefined : checker.getSymbolAtLocation(link.name)
1668 }
1669
1670 function isInlineLinkStart(source: string, index: number): boolean {
1671 if (!source.startsWith("{@link", index)) return false
1672 const next = source[index + "{@link".length]
1673 return next === undefined || /\s|}/.test(next)
1674 }
1675
1676 function hasInlineLink(block: JSDocBlock): boolean {
1677 return block.lines.some((line) => {
1678 let index = line.indexOf("{@link")
1679 while (index !== -1) {
1680 if (isInlineLinkStart(line, index)) return true
1681 index = line.indexOf("{@link", index + 1)
1682 }
1683 return false
1684 })
1685 }
1686
1687 function extractInlineLinkTarget(linkText: string): string {
1688 const content = linkText.slice("{@link".length, linkText.endsWith("}") ? -1 : undefined).trim()
1689 const pipeIndex = content.indexOf("|")
1690 const beforeLabel = pipeIndex === -1 ? content : content.slice(0, pipeIndex).trim()
1691 return beforeLabel.split(/\s+/)[0] ?? ""
1692 }
1693
1694 function malformedInlineLinks(block: JSDocBlock): Array<string> {
1695 const source = block.lines.join("\n")
1696 const malformed: Array<string> = []
1697 let index = source.indexOf("{@link")
1698 while (index !== -1) {
1699 if (!isInlineLinkStart(source, index)) {
1700 index = source.indexOf("{@link", index + 1)
1701 continue
1702 }
1703 const end = source.indexOf("}", index + "{@link".length)
1704 const text = end === -1 ? source.slice(index).split(/\r?\n/, 1)[0] : source.slice(index, end + 1)
1705 if (end === -1 || extractInlineLinkTarget(text) === "") malformed.push(text)
1706 index = source.indexOf("{@link", end === -1 ? index + 1 : end + 1)
1707 }
1708 return malformed
1709 }
1710
1711 function collectJSDocLinks(sourceFile: ts.SourceFile, block: JSDocBlock): Array<ts.JSDocLink> {
1712 const links: Array<ts.JSDocLink> = []
1713 function inspectJSDoc(node: ts.Node) {
1714 for (const jsdoc of (node as { readonly jsDoc?: ReadonlyArray<ts.JSDoc> }).jsDoc ?? []) {
1715 if (jsdoc.pos !== block.range[0] || jsdoc.end !== block.range[1]) continue
1716 ts.forEachChild(jsdoc, function visit(child) {
1717 if (ts.isJSDocLink(child)) links.push(child)
1718 ts.forEachChild(child, visit)
1719 })
1720 }
1721 }
1722 function visit(node: ts.Node) {
1723 inspectJSDoc(node)
1724 ts.forEachChild(node, visit)
1725 }
1726 visit(sourceFile)
1727 return links
1728 }
1729
1730 function collectJSDocSeeLinks(sourceFile: ts.SourceFile, block: JSDocBlock): Array<ts.JSDocLink> {
1731 const links: Array<ts.JSDocLink> = []
1732 function inspectJSDoc(node: ts.Node) {
1733 for (const jsdoc of (node as { readonly jsDoc?: ReadonlyArray<ts.JSDoc> }).jsDoc ?? []) {
1734 if (jsdoc.pos !== block.range[0] || jsdoc.end !== block.range[1]) continue
1735 ts.forEachChild(jsdoc, function visit(child) {
1736 if (ts.isJSDocSeeTag(child)) {
1737 ts.forEachChild(child, function visitSeeTag(seeTagChild) {
1738 if (ts.isJSDocLink(seeTagChild)) links.push(seeTagChild)
1739 ts.forEachChild(seeTagChild, visitSeeTag)
1740 })
1741 return
1742 }
1743 ts.forEachChild(child, visit)
1744 })
1745 }
1746 }
1747 function visit(node: ts.Node) {
1748 inspectJSDoc(node)
1749 ts.forEachChild(node, visit)
1750 }
1751 visit(sourceFile)
1752 return links
1753 }
1754
1755 function resolvedSymbolTarget(symbol: ts.Symbol, checker: ts.TypeChecker): ts.Symbol {
1756 return (symbol.flags & ts.SymbolFlags.Alias) === 0 ? symbol : checker.getAliasedSymbol(symbol)
1757 }
1758
1759 function isLocalSourceFile(cwd: string, sourceFile: ts.SourceFile): boolean {
1760 if (sourceFile.isDeclarationFile) return false
1761 const relative = path.relative(cwd, sourceFile.fileName)
1762 return relative === "" || (!relative.startsWith("..") && !path.isAbsolute(relative))
1763 }
1764
1765 function symbolDeclarations(symbol: ts.Symbol, checker: ts.TypeChecker): ReadonlyArray<ts.Declaration> {
1766 const target = resolvedSymbolTarget(symbol, checker)
1767 const declarations = new Set<ts.Declaration>()
1768 if (target.valueDeclaration !== undefined) declarations.add(target.valueDeclaration)
1769 for (const declaration of target.declarations ?? []) declarations.add(declaration)
1770 return Array.from(declarations)
1771 }
1772
1773 function symbolHasPublicJSDoc(symbol: ts.Symbol, checker: ts.TypeChecker): boolean {
1774 return symbolDeclarations(symbol, checker).some((declaration) => {
1775 const block = getNodeJSDoc(declaration)
1776 return block !== undefined && !block.internal && block.parsed !== undefined
1777 })
1778 }
1779
1780 function isMemberDeclaration(declaration: ts.Declaration): boolean {
1781 return ts.isPropertySignature(declaration) || ts.isMethodSignature(declaration) ||
1782 ts.isPropertyDeclaration(declaration) || ts.isMethodDeclaration(declaration) ||
1783 ts.isGetAccessorDeclaration(declaration) || ts.isSetAccessorDeclaration(declaration)
1784 }
1785
1786 function undocumentedSeeLinkTarget(
1787 symbol: ts.Symbol,
1788 checker: ts.TypeChecker,
1789 cwd: string
1790 ): ts.Declaration | undefined {
1791 const localDeclarations = symbolDeclarations(symbol, checker).filter((declaration) =>
1792 isMemberDeclaration(declaration) && isLocalSourceFile(cwd, declaration.getSourceFile())
1793 )
1794 if (localDeclarations.length === 0 || symbolHasPublicJSDoc(symbol, checker)) return undefined
1795 return localDeclarations[0]
1796 }
1797
1798 function inlineLinkSymbol(
1799 symbol: ts.Symbol,
1800 cwd: string,
1801 checker: ts.TypeChecker
1802 ): ParsedInlineLinkSymbol | undefined {
1803 const target = resolvedSymbolTarget(symbol, checker)
1804 const declaration = target.valueDeclaration ?? target.declarations?.[0]
1805 if (declaration === undefined) return undefined
1806 return {
1807 file: normalizeFile(cwd, declaration.getSourceFile().fileName),
1808 range: nodeRange(declaration)
1809 }
1810 }
1811
1812 function attachSeeLinkSymbolsFromSourceFile<
1813 T extends ParsedModuleTags | ParsedDeclarationTags | ParsedNamespaceTags | ParsedMemberTags
1814 >(
1815 tags: T,
1816 sourceFile: ts.SourceFile,
1817 block: JSDocBlock,
1818 linkContext: { readonly checker: ts.TypeChecker; readonly entry: ProgramCacheEntry; readonly cwd: string }
1819 ): T {
1820 const resolved = new Map<
1821 string,
1822 Array<{ readonly range: readonly [number, number]; readonly symbol?: ParsedInlineLinkSymbol }>
1823 >()
1824 for (const link of collectJSDocLinks(sourceFile, block)) {
1825 const text = link.getText(sourceFile)
1826 const target = extractInlineLinkTarget(text)
1827 if (target === "" || urlRegex.test(target)) continue
1828 const symbol = resolveJSDocLinkSymbol(link, linkContext.checker)
1829 const info = symbol === undefined ? undefined : inlineLinkSymbol(symbol, linkContext.cwd, linkContext.checker)
1830 const items = resolved.get(text) ?? []
1831 items.push(info === undefined ? { range: [link.pos, link.end] } : { range: [link.pos, link.end], symbol: info })
1832 resolved.set(text, items)
1833 }
1834 return {
1835 ...tags,
1836 see: tags.see.map((tag) => ({
1837 ...tag,
1838 links: tag.links.map((link) => {
1839 const items = resolved.get(link.raw)
1840 const info = items?.shift()
1841 if (info === undefined) return link
1842 return info.symbol === undefined
1843 ? { ...link, range: info.range }
1844 : { ...link, range: info.range, symbol: info.symbol }
1845 })
1846 }))
1847 }
1848 }
1849
1850 function attachSeeLinkSymbols<T extends ParsedDeclarationTags | ParsedNamespaceTags | ParsedMemberTags>(
1851 tags: T,
1852 node: ts.Node,
1853 block: JSDocBlock,
1854 linkContext: { readonly checker: ts.TypeChecker; readonly entry: ProgramCacheEntry; readonly cwd: string }
1855 ): T {
1856 return attachSeeLinkSymbolsFromSourceFile(tags, node.getSourceFile(), block, linkContext)
1857 }
1858
1859 /**
1860 * JSDoc diagnostic paired with its source range.
1861 *
1862 * @category models
1863 * @since 4.0.0
1864 */
1865 export interface JSDocModelDiagnostic extends JSDocDiagnostic {
1866 readonly range: readonly [number, number]
1867 }
1868
1869 /**
1870 * Parsed JSDoc and diagnostics for one source file in a model.
1871 *
1872 * @category models
1873 * @since 4.0.0
1874 */
1875 export interface JSDocModelFile extends ParsedJSDocFile {
1876 readonly file: string
1877 readonly hash: string
1878 readonly diagnostics: ReadonlyArray<JSDocModelDiagnostic>
1879 readonly imports?: ParsedJSDocImports
1880 }
1881
1882 /**
1883 * Versioned output of a repository JSDoc extraction.
1884 *
1885 * @category models
1886 * @since 4.0.0
1887 */
1888 export interface JSDocModel {
1889 readonly version: 3
1890 readonly generatedBy: "@effect/jsdocs"
1891 readonly generatedAt: string
1892 readonly inputHash?: string
1893 readonly files: ReadonlyArray<JSDocModelFile>
1894 readonly apis: ReadonlyArray<JSDocApi>
1895 }
1896
1897 /**
1898 * File selection and output configuration for JSDoc extraction.
1899 *
1900 * @category configuration
1901 * @since 4.0.0
1902 */
1903 export interface JSDocConfig {
1904 readonly tsconfig: string
1905 readonly include: ReadonlyArray<string>
1906 readonly exclude?: ReadonlyArray<string>
1907 readonly output: string
1908 }
1909
1910 /**
1911 * JSDoc extraction configuration with an optional working directory.
1912 *
1913 * @category configuration
1914 * @since 4.0.0
1915 */
1916 export interface ExtractJSDocsOptions extends JSDocConfig {
1917 readonly cwd?: string
1918 }
1919
1920 function addInputFile(files: Set<string>, filename: string) {
1921 const normalized = path.resolve(filename)
1922 if (fs.existsSync(normalized) && fs.statSync(normalized).isFile()) {
1923 files.add(normalized)
1924 }
1925 }
1926
1927 /**
1928 * Computes the cache key for the configured JSDoc extraction inputs.
1929 *
1930 * @category hashing
1931 * @since 4.0.0
1932 */
1933 export function computeJSDocInputHash(options: ExtractJSDocsOptions): string {
1934 const cwd = path.resolve(options.cwd ?? process.cwd())
1935 const hash = crypto.createHash("sha256")
1936 const files = new Set<string>()
1937
1938 hash.update(JSON.stringify({
1939 tsconfig: options.tsconfig,
1940 include: options.include,
1941 exclude: options.exclude ?? [],
1942 output: options.output
1943 }))
1944
1945 addInputFile(files, path.join(cwd, "jsdocs.config.json"))
1946 addInputFile(files, path.resolve(cwd, options.tsconfig))
1947
1948 for (
1949 const filename of globSync([...options.include], {
1950 cwd,
1951 absolute: true,
1952 nodir: true,
1953 ignore: ["**/node_modules/**"]
1954 })
1955 ) {
1956 addInputFile(files, filename)
1957 }
1958
1959 for (
1960 const filename of globSync([
1961 "package.json",
1962 "packages/**/package.json",
1963 "tsconfig*.json",
1964 "packages/**/tsconfig*.json"
1965 ], {
1966 cwd,
1967 absolute: true,
1968 nodir: true,
1969 ignore: ["**/node_modules/**"]
1970 })
1971 ) {
1972 addInputFile(files, filename)
1973 }
1974
1975 for (const filename of Array.from(files).sort()) {
1976 hash.update("\0")
1977 hash.update(normalizeFile(cwd, filename))
1978 hash.update("\0")
1979 hash.update(hashSource(fs.readFileSync(filename, "utf8")))
1980 }
1981
1982 return hash.digest("hex")
1983 }
1984
1985 function isIdentifierName(value: string): boolean {
1986 return /^[$A-Z_a-z][$\w]*$/.test(value)
1987 }
1988
1989 function renderInlineLinks(text: string): string {
1990 return text.replace(/\{@link\s+([^}]+)\}/g, (_match, content: string) => {
1991 const pipeIndex = content.indexOf("|")
1992 const beforeLabel = pipeIndex === -1 ? content.trim() : content.slice(0, pipeIndex).trim()
1993 const target = beforeLabel.split(/\s+/)[0] ?? ""
1994 const label = pipeIndex === -1
1995 ? beforeLabel.slice(target.length).trim() || target
1996 : content.slice(pipeIndex + 1).trim() || target
1997 return `\`${label.replace(/:var$/, "")}\``
1998 })
1999 }
2000
2001 function renderDescription(description: ParsedDescription): ParsedDescription {
2002 return {
2003 short: renderInlineLinks(description.short),
2004 whenToUse: description.whenToUse === null ? null : renderInlineLinks(description.whenToUse),
2005 details: description.details === null ? null : renderInlineLinks(description.details),
2006 gotchas: description.gotchas === null ? null : renderInlineLinks(description.gotchas)
2007 }
2008 }
2009
2010 function renderExamples(examples: ReadonlyArray<ParsedExample>): ReadonlyArray<ParsedExample> {
2011 return examples.map((example) => ({
2012 ...example,
2013 body: example.body === null ? null : renderInlineLinks(example.body)
2014 }))
2015 }
2016
2017 function apiTags(
2018 tags: ParsedDeclarationTags | ParsedNamespaceTags | ParsedMemberTags
2019 ): JSDocApiTags {
2020 return {
2021 category: "category" in tags ? tags.category : null,
2022 since: tags.since,
2023 stability: tags.stability,
2024 deprecated: tags.deprecated,
2025 default: "default" in tags ? tags.default : null
2026 }
2027 }
2028
2029 function unresolvedSeeTag(tag: ParsedSeeTag): JSDocApiSeeTag {
2030 return {
2031 text: renderInlineLinks(tag.text),
2032 links: tag.links.map((link) => ({
2033 ...link,
2034 resolution: { _tag: "Unresolved", reason: "not-found", candidates: [] }
2035 }))
2036 }
2037 }
2038
2039 function unresolvedSee(tags: ReadonlyArray<ParsedSeeTag>): ReadonlyArray<JSDocApiSeeTag> {
2040 return tags.map(unresolvedSeeTag)
2041 }
2042
2043 function apiId(kind: JSDocApiKind, bucket: ExportBucket | null, apiFqn: string): string {
2044 return `${kind}:${bucket ?? "none"}:${apiFqn}`
2045 }
2046
2047 function importGuidance(
2048 imports: ParsedJSDocImports,
2049 kind: JSDocApiKind,
2050 bucket: ExportBucket | null,
2051 apiName: string
2052 ): JSDocApiImportGuidance | null {
2053 if (kind !== "root-declaration" || bucket !== "value" || !isIdentifierName(apiName)) {
2054 return null
2055 }
2056 if (imports.flatNames.includes(apiName) && imports.barrel !== null) {
2057 return {
2058 style: "named-barrel",
2059 importDeclaration: `import { ${apiName} } from "${imports.barrel.module}"`,
2060 usage: apiName
2061 }
2062 }
2063 if (imports.barrel?.type === "namespace") {
2064 if (!isIdentifierName(imports.barrel.name)) return null
2065 return {
2066 style: "namespace-barrel",
2067 importDeclaration: `import { ${imports.barrel.name} } from "${imports.barrel.module}"`,
2068 usage: `${imports.barrel.name}.${apiName}`
2069 }
2070 }
2071 if (imports.barrel?.type === "flat") {
2072 return {
2073 style: "named-barrel",
2074 importDeclaration: `import { ${apiName} } from "${imports.barrel.module}"`,
2075 usage: apiName
2076 }
2077 }
2078 return {
2079 style: "named-module",
2080 importDeclaration: `import { ${apiName} } from "${imports.module}"`,
2081 usage: apiName
2082 }
2083 }
2084
2085 function makeApi(input: {
2086 readonly file: JSDocModelFile
2087 readonly imports: ParsedJSDocImports
2088 readonly kind: JSDocApiKind
2089 readonly bucket: ExportBucket | null
2090 readonly apiName: string
2091 readonly localName: string
2092 readonly signature: string | null
2093 readonly parentApiName: string | null
2094 readonly namespacePath: ReadonlyArray<string>
2095 readonly memberPath: ReadonlyArray<string>
2096 readonly sourcePath: ReadonlyArray<string | number>
2097 readonly sourceRange: readonly [number, number]
2098 readonly description: ParsedDescription
2099 readonly examples: ReadonlyArray<ParsedExample>
2100 readonly tags: ParsedDeclarationTags | ParsedNamespaceTags | ParsedMemberTags
2101 }): JSDocApi {
2102 const apiFqn = `${input.imports.module}.${input.apiName}`
2103 return {
2104 id: apiId(input.kind, input.bucket, apiFqn),
2105 kind: input.kind,
2106 moduleName: input.imports.module,
2107 apiName: input.apiName,
2108 localName: input.localName,
2109 signature: input.signature,
2110 parentApiName: input.parentApiName,
2111 apiFqn,
2112 hasFqnCollision: false,
2113 bucket: input.bucket,
2114 importable: input.kind === "root-declaration",
2115 namespacePath: input.namespacePath,
2116 memberPath: input.memberPath,
2117 source: {
2118 file: input.file.file,
2119 path: input.sourcePath,
2120 range: input.sourceRange
2121 },
2122 description: renderDescription(input.description),
2123 examples: renderExamples(input.examples),
2124 tags: apiTags(input.tags),
2125 see: unresolvedSee(input.tags.see),
2126 importGuidance: importGuidance(input.imports, input.kind, input.bucket, input.apiName)
2127 }
2128 }
2129
2130 function buildJSDocApis(files: ReadonlyArray<JSDocModelFile>): ReadonlyArray<JSDocApi> {
2131 const apis: Array<JSDocApi> = []
2132 const addMembers = (
2133 file: JSDocModelFile,
2134 imports: ParsedJSDocImports,
2135 members: ReadonlyArray<ParsedMember>,
2136 parentApiName: string,
2137 namespacePath: ReadonlyArray<string>,
2138 memberPath: ReadonlyArray<string>,
2139 sourcePath: ReadonlyArray<string | number>
2140 ) => {
2141 members.forEach((member, index) => {
2142 const nextMemberPath = [...memberPath, member.name]
2143 const apiName = `${parentApiName}.${nextMemberPath.join(".")}`
2144 apis.push(makeApi({
2145 file,
2146 imports,
2147 kind: "member",
2148 bucket: null,
2149 apiName,
2150 localName: member.name,
2151 signature: member.signature,
2152 parentApiName,
2153 namespacePath,
2154 memberPath: nextMemberPath,
2155 sourcePath: [...sourcePath, "members", index],
2156 sourceRange: member.range,
2157 description: member.description,
2158 examples: member.examples,
2159 tags: member.tags
2160 }))
2161 addMembers(file, imports, member.members, parentApiName, namespacePath, nextMemberPath, [
2162 ...sourcePath,
2163 "members",
2164 index
2165 ])
2166 })
2167 }
2168 const addNamespaces = (
2169 file: JSDocModelFile,
2170 imports: ParsedJSDocImports,
2171 namespaces: ReadonlyArray<ParsedNamespace>,
2172 namespacePath: ReadonlyArray<string>,
2173 sourcePath: ReadonlyArray<string | number>
2174 ) => {
2175 namespaces.forEach((namespace, index) => {
2176 const nextNamespacePath = [...namespacePath, namespace.name]
2177 const namespaceApiName = nextNamespacePath.join(".")
2178 apis.push(makeApi({
2179 file,
2180 imports,
2181 kind: "namespace",
2182 bucket: null,
2183 apiName: namespaceApiName,
2184 localName: namespace.name,
2185 signature: namespace.signature,
2186 parentApiName: namespacePath.length === 0 ? null : namespacePath.join("."),
2187 namespacePath: nextNamespacePath,
2188 memberPath: [],
2189 sourcePath: [...sourcePath, index],
2190 sourceRange: namespace.range,
2191 description: namespace.description,
2192 examples: namespace.examples,
2193 tags: namespace.tags
2194 }))
2195 namespace.declarations.forEach((declaration, declarationIndex) => {
2196 const apiName = `${namespaceApiName}.${declaration.name}`
2197 apis.push(makeApi({
2198 file,
2199 imports,
2200 kind: "namespace-declaration",
2201 bucket: "type",
2202 apiName,
2203 localName: declaration.name,
2204 signature: declaration.signature,
2205 parentApiName: namespaceApiName,
2206 namespacePath: nextNamespacePath,
2207 memberPath: [],
2208 sourcePath: [...sourcePath, index, "declarations", declarationIndex],
2209 sourceRange: declaration.range,
2210 description: declaration.description,
2211 examples: declaration.examples,
2212 tags: declaration.tags
2213 }))
2214 addMembers(file, imports, declaration.members, apiName, nextNamespacePath, [], [
2215 ...sourcePath,
2216 index,
2217 "declarations",
2218 declarationIndex
2219 ])
2220 })
2221 addNamespaces(file, imports, namespace.namespaces, nextNamespacePath, [...sourcePath, index, "namespaces"])
2222 })
2223 }
2224 for (const file of files) {
2225 if (file.imports === undefined) continue
2226 const imports = file.imports
2227 file.declarations.forEach((declaration, index) => {
2228 apis.push(makeApi({
2229 file,
2230 imports,
2231 kind: "root-declaration",
2232 bucket: declaration.bucket,
2233 apiName: declaration.name,
2234 localName: declaration.name,
2235 signature: declaration.signature,
2236 parentApiName: null,
2237 namespacePath: [],
2238 memberPath: [],
2239 sourcePath: ["declarations", index],
2240 sourceRange: declaration.range,
2241 description: declaration.description,
2242 examples: declaration.examples,
2243 tags: declaration.tags
2244 }))
2245 addMembers(file, imports, declaration.members, declaration.name, [], [], ["declarations", index])
2246 })
2247 addNamespaces(file, imports, file.namespaces, [], ["namespaces"])
2248 }
2249 return resolveJSDocApiSeeLinks(markFqnCollisions(apis))
2250 }
2251
2252 function markFqnCollisions(apis: ReadonlyArray<JSDocApi>): ReadonlyArray<JSDocApi> {
2253 const counts = new Map<string, number>()
2254 for (const api of apis) counts.set(api.apiFqn, (counts.get(api.apiFqn) ?? 0) + 1)
2255 return apis.map((api) => ({ ...api, hasFqnCollision: (counts.get(api.apiFqn) ?? 0) > 1 }))
2256 }
2257
2258 function normalizeSeeTarget(target: string): ReadonlyArray<string> {
2259 const withoutKind = target.replace(/:[A-Za-z]+$/, "")
2260 const out = [withoutKind]
2261 if (withoutKind.endsWith("_")) out.push(withoutKind.slice(0, -1))
2262 return Array.from(new Set(out.filter((item) => item.length > 0)))
2263 }
2264
2265 function sourceRangeKey(file: string, range: readonly [number, number]): string {
2266 return `${file}:${range[0]}:${range[1]}`
2267 }
2268
2269 function rangeContains(outer: readonly [number, number], inner: readonly [number, number]): boolean {
2270 return outer[0] <= inner[0] && inner[1] <= outer[1]
2271 }
2272
2273 function rangeOverlaps(self: readonly [number, number], that: readonly [number, number]): boolean {
2274 return self[0] <= that[1] && that[0] <= self[1]
2275 }
2276
2277 function rangeWidth(range: readonly [number, number]): number {
2278 return range[1] - range[0]
2279 }
2280
2281 function seeTargetNames(link: ParsedInlineLink): ReadonlySet<string> {
2282 const names = new Set<string>()
2283 const add = (target: string) => {
2284 for (const normalized of normalizeSeeTarget(target)) {
2285 const parts = normalized.split(".").filter((part) => part.length > 0)
2286 for (const part of parts) names.add(part)
2287 if (parts.length > 0) names.add(parts.join("."))
2288 }
2289 }
2290 add(link.target)
2291 if (link.text !== null) add(link.text)
2292 return names
2293 }
2294
2295 function apiMatchesSeeTarget(api: JSDocApi, names: ReadonlySet<string>): boolean {
2296 if (names.size === 0) return true
2297 if (names.has(api.localName) || names.has(api.apiName)) return true
2298 for (const name of names) {
2299 if (api.apiName.endsWith(`.${name}`)) return true
2300 }
2301 return false
2302 }
2303
2304 function createJSDocApiSeeLinkResolver(apis: ReadonlyArray<JSDocApi>) {
2305 const byModuleAndName = new Map<string, JSDocApi>()
2306 const byLocalName = new Map<string, Array<JSDocApi>>()
2307 const bySourceRange = new Map<string, JSDocApi>()
2308 const bySourceFile = new Map<string, Array<JSDocApi>>()
2309 for (const api of apis) {
2310 byModuleAndName.set(`${api.moduleName}:${api.apiName}`, api)
2311 bySourceRange.set(sourceRangeKey(api.source.file, api.source.range), api)
2312 const sourceApis = bySourceFile.get(api.source.file) ?? []
2313 sourceApis.push(api)
2314 bySourceFile.set(api.source.file, sourceApis)
2315 for (const name of new Set([api.apiName, api.localName])) {
2316 const existing = byLocalName.get(name) ?? []
2317 existing.push(api)
2318 byLocalName.set(name, existing)
2319 }
2320 }
2321 const resolveSymbol = (link: ParsedInlineLink): JSDocApiSeeLinkResolution | undefined => {
2322 if (link.symbol === undefined) return undefined
2323 const symbol = link.symbol
2324 const exact = bySourceRange.get(sourceRangeKey(symbol.file, symbol.range))
2325 if (exact !== undefined) return { _tag: "Resolved", apiId: exact.id, apiFqn: exact.apiFqn }
2326 const names = seeTargetNames(link)
2327 const candidates = (bySourceFile.get(symbol.file) ?? []).filter((api) =>
2328 apiMatchesSeeTarget(api, names) &&
2329 (rangeContains(symbol.range, api.source.range) ||
2330 rangeContains(api.source.range, symbol.range) ||
2331 rangeOverlaps(symbol.range, api.source.range))
2332 ).sort((self, that) => rangeWidth(self.source.range) - rangeWidth(that.source.range))
2333 const unique = Array.from(new Map(candidates.map((candidate) => [candidate.id, candidate])).values())
2334 if (unique.length === 1) return { _tag: "Resolved", apiId: unique[0].id, apiFqn: unique[0].apiFqn }
2335 if (unique.length > 1) {
2336 return { _tag: "Unresolved", reason: "ambiguous", candidates: unique.map((candidate) => candidate.id) }
2337 }
2338 const sameFileByName = (bySourceFile.get(symbol.file) ?? []).filter((api) => apiMatchesSeeTarget(api, names))
2339 const uniqueByName = Array.from(new Map(sameFileByName.map((candidate) => [candidate.id, candidate])).values())
2340 if (uniqueByName.length === 1) {
2341 return { _tag: "Resolved", apiId: uniqueByName[0].id, apiFqn: uniqueByName[0].apiFqn }
2342 }
2343 if (uniqueByName.length > 1) {
2344 return { _tag: "Unresolved", reason: "ambiguous", candidates: uniqueByName.map((candidate) => candidate.id) }
2345 }
2346 return undefined
2347 }
2348 return (
2349 context: { readonly moduleName: string; readonly namespacePath: ReadonlyArray<string> },
2350 link: ParsedInlineLink
2351 ): JSDocApiSeeLinkResolution => {
2352 const symbolResolution = resolveSymbol(link)
2353 if (symbolResolution !== undefined) return symbolResolution
2354 const targets = new Set<string>()
2355 for (const target of normalizeSeeTarget(link.target)) targets.add(target)
2356 if (link.text !== null) {
2357 for (const target of normalizeSeeTarget(link.text)) targets.add(target)
2358 }
2359 for (const target of targets) {
2360 const sameModule = byModuleAndName.get(`${context.moduleName}:${target}`)
2361 if (sameModule !== undefined) return { _tag: "Resolved", apiId: sameModule.id, apiFqn: sameModule.apiFqn }
2362 if (!target.includes(".") && context.namespacePath.length > 0) {
2363 const sameNamespace = byModuleAndName.get(
2364 `${context.moduleName}:${[...context.namespacePath, target].join(".")}`
2365 )
2366 if (sameNamespace !== undefined) {
2367 return { _tag: "Resolved", apiId: sameNamespace.id, apiFqn: sameNamespace.apiFqn }
2368 }
2369 }
2370 }
2371 const candidates = Array.from(targets).flatMap((target) => byLocalName.get(target) ?? [])
2372 const unique = Array.from(new Map(candidates.map((candidate) => [candidate.id, candidate])).values())
2373 if (unique.length === 1) return { _tag: "Resolved", apiId: unique[0].id, apiFqn: unique[0].apiFqn }
2374 if (unique.length > 1) {
2375 return { _tag: "Unresolved", reason: "ambiguous", candidates: unique.map((candidate) => candidate.id) }
2376 }
2377 return { _tag: "Unresolved", reason: "not-found", candidates: [] }
2378 }
2379 }
2380
2381 function resolveJSDocApiSeeLinks(apis: ReadonlyArray<JSDocApi>): ReadonlyArray<JSDocApi> {
2382 const resolve = createJSDocApiSeeLinkResolver(apis)
2383 return apis.map((api) => ({
2384 ...api,
2385 see: api.see.map((tag) => ({
2386 ...tag,
2387 links: tag.links.map((link) => ({ ...link, resolution: resolve(api, link) }))
2388 }))
2389 }))
2390 }
2391
2392 function sameDiagnostic(self: JSDocModelDiagnostic, that: JSDocModelDiagnostic): boolean {
2393 return self.code === that.code && self.message === that.message &&
2394 self.range[0] === that.range[0] && self.range[1] === that.range[1]
2395 }
2396
2397 function unresolvedPublicSeeDiagnostic(link: JSDocApiSeeLink): JSDocModelDiagnostic | undefined {
2398 if (link.resolution._tag === "Resolved" || link.range === undefined) return undefined
2399 const message = link.resolution.reason === "ambiguous"
2400 ? `@see link ${link.raw} is ambiguous; it must resolve to exactly one public JSDoc API. Candidates: ${
2401 link.resolution.candidates.join(", ")
2402 }`
2403 : `@see link ${link.raw} does not resolve to a public JSDoc API. Check that the target is exported and has valid public JSDoc.`
2404 return { ...diagnostic("public-see-target", message), range: link.range }
2405 }
2406
2407 function appendPublicSeeDiagnostics(
2408 files: ReadonlyArray<JSDocModelFile>,
2409 apis: ReadonlyArray<JSDocApi>
2410 ): { readonly files: ReadonlyArray<JSDocModelFile>; readonly added: boolean } {
2411 const diagnosticsByFile = new Map(files.map((file) => [file.file, [...file.diagnostics]]))
2412 let added = false
2413 for (const api of apis) {
2414 const diagnostics = diagnosticsByFile.get(api.source.file)
2415 if (diagnostics === undefined) continue
2416 for (const tag of api.see) {
2417 for (const link of tag.links) {
2418 const item = unresolvedPublicSeeDiagnostic(link)
2419 if (item === undefined || diagnostics.some((diagnostic) => sameDiagnostic(diagnostic, item))) continue
2420 diagnostics.push(item)
2421 added = true
2422 }
2423 }
2424 }
2425 if (!added) return { files, added }
2426 return {
2427 added,
2428 files: files.map((file) => ({
2429 ...file,
2430 diagnostics: diagnosticsByFile.get(file.file) ?? file.diagnostics
2431 }))
2432 }
2433 }
2434
2435 function moduleSeeTags(
2436 file: JSDocModelFile,
2437 sourceFile: ts.SourceFile,
2438 linkContext: { readonly checker: ts.TypeChecker; readonly entry: ProgramCacheEntry; readonly cwd: string }
2439 ): ReadonlyArray<JSDocApiSeeTag> {
2440 if (file.moduleJSDoc === undefined) return []
2441 const block = parseLooseJSDocBlock(file.moduleJSDoc.raw, [file.moduleJSDoc.range[0], file.moduleJSDoc.range[1]])
2442 if (block.internal) return []
2443 const tags = buildTags("module", block.tags)
2444 const moduleTags: ParsedModuleTags = tags._tag === "Success"
2445 ? tags.value as ParsedModuleTags
2446 : {
2447 since: "0.0.0",
2448 stability: "stable",
2449 deprecated: null,
2450 see: block.tags.filter((tag) => tag.name === "see" && tag.value.trim() !== "").map((tag) =>
2451 parseSeeTag(tag.value.trim())
2452 )
2453 }
2454 const withSymbols = attachSeeLinkSymbolsFromSourceFile(moduleTags, sourceFile, block, linkContext)
2455 return unresolvedSee(withSymbols.see)
2456 }
2457
2458 function appendModulePublicSeeDiagnostics(
2459 files: ReadonlyArray<JSDocModelFile>,
2460 apis: ReadonlyArray<JSDocApi>,
2461 context: {
2462 readonly sourceFilesByFile: ReadonlyMap<string, ts.SourceFile>
2463 readonly checker: ts.TypeChecker
2464 readonly entry: ProgramCacheEntry
2465 readonly cwd: string
2466 }
2467 ): { readonly files: ReadonlyArray<JSDocModelFile>; readonly added: boolean } {
2468 const diagnosticsByFile = new Map(files.map((file) => [file.file, [...file.diagnostics]]))
2469 const resolve = createJSDocApiSeeLinkResolver(apis)
2470 let added = false
2471 for (const file of files) {
2472 if (file.imports === undefined || file.moduleJSDoc === undefined) continue
2473 const sourceFile = context.sourceFilesByFile.get(file.file)
2474 const diagnostics = diagnosticsByFile.get(file.file)
2475 if (sourceFile === undefined || diagnostics === undefined) continue
2476 for (const tag of moduleSeeTags(file, sourceFile, context)) {
2477 for (const link of tag.links) {
2478 const item = unresolvedPublicSeeDiagnostic({
2479 ...link,
2480 resolution: resolve({ moduleName: file.imports.module, namespacePath: [] }, link)
2481 })
2482 if (item === undefined || diagnostics.some((diagnostic) => sameDiagnostic(diagnostic, item))) continue
2483 diagnostics.push(item)
2484 added = true
2485 }
2486 }
2487 }
2488 if (!added) return { files, added }
2489 return {
2490 added,
2491 files: files.map((file) => ({
2492 ...file,
2493 diagnostics: diagnosticsByFile.get(file.file) ?? file.diagnostics
2494 }))
2495 }
2496 }
2497
2498 function buildJSDocApisWithPublicSeeDiagnostics(
2499 files: ReadonlyArray<JSDocModelFile>,
2500 context?: {
2501 readonly sourceFilesByFile: ReadonlyMap<string, ts.SourceFile>
2502 readonly checker: ts.TypeChecker
2503 readonly entry: ProgramCacheEntry
2504 readonly cwd: string
2505 }
2506 ): {
2507 readonly files: ReadonlyArray<JSDocModelFile>
2508 readonly apis: ReadonlyArray<JSDocApi>
2509 } {
2510 let current = files
2511 for (let index = 0; index < 5; index++) {
2512 const apis = buildJSDocApis(current)
2513 const publicSee = appendPublicSeeDiagnostics(current, apis)
2514 const moduleSee = context === undefined
2515 ? { files: publicSee.files, added: false }
2516 : appendModulePublicSeeDiagnostics(publicSee.files, apis, context)
2517 const next = { files: moduleSee.files, added: publicSee.added || moduleSee.added }
2518 if (!next.added) return { files: current, apis }
2519 current = next.files
2520 }
2521 return { files: current, apis: buildJSDocApis(current) }
2522 }
2523
2524 interface ExampleImportPolicy {
2525 readonly allowedNamedBySource: ReadonlyMap<string, ReadonlySet<string>>
2526 readonly namespaceModuleBySource: ReadonlyMap<string, { readonly barrelModule: string; readonly name: string }>
2527 readonly flatModuleBySource: ReadonlyMap<
2528 string,
2529 { readonly barrelModule: string; readonly names: ReadonlySet<string> }
2530 >
2531 readonly namedModuleBySource: ReadonlyMap<string, ReadonlySet<string>>
2532 }
2533
2534 function createExampleImportPolicy(files: ReadonlyArray<JSDocModelFile>): ExampleImportPolicy {
2535 const allowedNamed = new Map<string, Set<string>>()
2536 const namespaceModuleBySource = new Map<string, { readonly barrelModule: string; readonly name: string }>()
2537 const flatModuleBySource = new Map<string, { readonly barrelModule: string; readonly names: ReadonlySet<string> }>()
2538 const namedModuleBySource = new Map<string, ReadonlySet<string>>()
2539 const addAllowed = (source: string, name: string) => {
2540 const names = allowedNamed.get(source) ?? new Set<string>()
2541 names.add(name)
2542 allowedNamed.set(source, names)
2543 }
2544 for (const file of files) {
2545 if (file.imports === undefined) continue
2546 const rootValues = file.declarations.filter((declaration) =>
2547 declaration.bucket === "value" && isIdentifierName(declaration.name)
2548 ).map((declaration) => declaration.name)
2549 if (file.imports.barrel?.type === "namespace") {
2550 addAllowed(file.imports.barrel.module, file.imports.barrel.name)
2551 for (const name of file.imports.flatNames) addAllowed(file.imports.barrel.module, name)
2552 namespaceModuleBySource.set(file.imports.module, {
2553 barrelModule: file.imports.barrel.module,
2554 name: file.imports.barrel.name
2555 })
2556 continue
2557 }
2558 if (file.imports.barrel?.type === "flat") {
2559 for (const name of new Set([...rootValues, ...file.imports.flatNames])) {
2560 addAllowed(file.imports.barrel.module, name)
2561 }
2562 flatModuleBySource.set(file.imports.module, {
2563 barrelModule: file.imports.barrel.module,
2564 names: new Set([...rootValues, ...file.imports.flatNames])
2565 })
2566 continue
2567 }
2568 const names = new Set([...rootValues, ...file.imports.flatNames])
2569 for (const name of names) addAllowed(file.imports.module, name)
2570 namedModuleBySource.set(file.imports.module, names)
2571 }
2572 return { allowedNamedBySource: allowedNamed, namespaceModuleBySource, flatModuleBySource, namedModuleBySource }
2573 }
2574
2575 function importSpecifierName(specifier: ts.ImportSpecifier): string {
2576 return specifier.propertyName?.text ?? specifier.name.text
2577 }
2578
2579 function validateExampleImports(
2580 code: string,
2581 policy: ExampleImportPolicy
2582 ): ReadonlyArray<JSDocDiagnostic> {
2583 const diagnostics: Array<JSDocDiagnostic> = []
2584 const sourceFile = ts.createSourceFile("example.ts", code, ts.ScriptTarget.Latest, true, ts.ScriptKind.TS)
2585 for (const statement of sourceFile.statements) {
2586 if (!ts.isImportDeclaration(statement) || !ts.isStringLiteralLike(statement.moduleSpecifier)) continue
2587 if (statement.importClause?.isTypeOnly) continue
2588 const source = statement.moduleSpecifier.text
2589 const namedAllowed = policy.allowedNamedBySource.get(source)
2590 const namespaceModule = policy.namespaceModuleBySource.get(source)
2591 const flatModule = policy.flatModuleBySource.get(source)
2592 const namedModule = policy.namedModuleBySource.get(source)
2593 const clause = statement.importClause
2594 if (clause === undefined) continue
2595 if (namespaceModule !== undefined) {
2596 diagnostics.push(diagnostic(
2597 "example-import-style",
2598 `JSDoc examples should use \`import { ${namespaceModule.name} } from "${namespaceModule.barrelModule}"\` instead of importing from "${source}"`
2599 ))
2600 continue
2601 }
2602 if (flatModule !== undefined) {
2603 diagnostics.push(diagnostic(
2604 "example-import-style",
2605 `JSDoc examples should import ${
2606 Array.from(flatModule.names).map((name) => `\`${name}\``).join(", ")
2607 } from "${flatModule.barrelModule}" instead of "${source}"`
2608 ))
2609 continue
2610 }
2611 if (clause.namedBindings !== undefined && ts.isNamespaceImport(clause.namedBindings)) {
2612 if (namedAllowed !== undefined || namedModule !== undefined) {
2613 diagnostics.push(diagnostic("example-import-style", `JSDoc examples should use named imports from "${source}"`))
2614 }
2615 continue
2616 }
2617 if (clause.name !== undefined && (namedAllowed !== undefined || namedModule !== undefined)) {
2618 diagnostics.push(
2619 diagnostic("example-import-style", `JSDoc examples should not use default imports from "${source}"`)
2620 )
2621 }
2622 if (clause.namedBindings !== undefined && ts.isNamedImports(clause.namedBindings) && namedAllowed !== undefined) {
2623 for (const specifier of clause.namedBindings.elements) {
2624 if (specifier.isTypeOnly) continue
2625 const imported = importSpecifierName(specifier)
2626 if (!namedAllowed.has(imported)) {
2627 diagnostics.push(diagnostic(
2628 "example-import-style",
2629 `JSDoc example import \`${imported}\` from "${source}" is not a canonical public API import`
2630 ))
2631 }
2632 }
2633 }
2634 }
2635 return diagnostics
2636 }
2637
2638 function appendExampleImportDiagnostics(files: ReadonlyArray<JSDocModelFile>): ReadonlyArray<JSDocModelFile> {
2639 const policy = createExampleImportPolicy(files)
2640 const checkExamples = (
2641 examples: ReadonlyArray<ParsedExample>,
2642 range: readonly [number, number] = [0, 0] as const
2643 ): ReadonlyArray<JSDocModelDiagnostic> =>
2644 examples.flatMap((example) => validateExampleImports(example.code, policy).map((item) => ({ ...item, range })))
2645 const checkModuleExamples = (moduleJSDoc: ParsedModuleJSDoc | undefined): ReadonlyArray<JSDocModelDiagnostic> => {
2646 if (moduleJSDoc === undefined) return []
2647 const block = parseLooseJSDocBlock(moduleJSDoc.raw, [moduleJSDoc.range[0], moduleJSDoc.range[1]])
2648 if (block.internal) return []
2649 return checkExamples(parseModuleExamples(block).examples, moduleJSDoc.range)
2650 }
2651 const checkMembers = (members: ReadonlyArray<ParsedMember>): ReadonlyArray<JSDocModelDiagnostic> =>
2652 members.flatMap((member) => [
2653 ...checkExamples(member.examples),
2654 ...checkMembers(member.members)
2655 ])
2656 const checkNamespaces = (namespaces: ReadonlyArray<ParsedNamespace>): ReadonlyArray<JSDocModelDiagnostic> =>
2657 namespaces.flatMap((namespace) => [
2658 ...checkExamples(namespace.examples),
2659 ...namespace.declarations.flatMap((declaration) => [
2660 ...checkExamples(declaration.examples),
2661 ...checkMembers(declaration.members)
2662 ]),
2663 ...checkNamespaces(namespace.namespaces)
2664 ])
2665 return files.map((file) => {
2666 const diagnostics = [
2667 ...file.diagnostics,
2668 ...checkModuleExamples(file.moduleJSDoc),
2669 ...file.declarations.flatMap((declaration) => [
2670 ...checkExamples(declaration.examples),
2671 ...checkMembers(declaration.members)
2672 ]),
2673 ...checkNamespaces(file.namespaces)
2674 ]
2675 return diagnostics.length === file.diagnostics.length
2676 ? file
2677 : { ...file, diagnostics: uniqueModelDiagnostics(diagnostics) }
2678 })
2679 }
2680
2681 function uniqueModelDiagnostics(
2682 diagnostics: ReadonlyArray<JSDocModelDiagnostic>
2683 ): ReadonlyArray<JSDocModelDiagnostic> {
2684 const seen = new Set<string>()
2685 return diagnostics.filter((item) => {
2686 const key = `${item.code}:${item.message}:${item.range[0]}:${item.range[1]}`
2687 if (seen.has(key)) return false
2688 seen.add(key)
2689 return true
2690 })
2691 }
2692
2693 function nodeRange(node: ts.Node): [number, number] {
2694 return [node.getStart(), node.getEnd()]
2695 }
2696
2697 function normalizeFile(cwd: string, filename: string): string {
2698 return normalizePathName(path.relative(cwd, filename))
2699 }
2700
2701 function hashSource(source: string): string {
2702 return crypto.createHash("sha256").update(source).digest("hex")
2703 }
2704
2705 function getNodeJSDoc(node: ts.Node): JSDocBlock | undefined {
2706 const jsDocs = (node as { readonly jsDoc?: ReadonlyArray<ts.JSDoc> }).jsDoc
2707 const jsDoc = jsDocs?.[jsDocs.length - 1]
2708 if (jsDoc === undefined) return undefined
2709 const source = node.getSourceFile().text
2710 return parseJSDocBlock(source.slice(jsDoc.pos, jsDoc.end), [jsDoc.pos, jsDoc.end])
2711 }
2712
2713 function addModelDiagnostics(
2714 out: Array<JSDocModelDiagnostic>,
2715 range: [number, number],
2716 diagnostics: ReadonlyArray<JSDocDiagnostic>
2717 ) {
2718 for (const item of diagnostics) out.push({ ...item, range })
2719 }
2720
2721 function addJSDocLinkDiagnostics(
2722 sourceFile: ts.SourceFile,
2723 block: JSDocBlock,
2724 diagnostics: Array<JSDocModelDiagnostic>,
2725 linkContext: { readonly checker: ts.TypeChecker; readonly entry: ProgramCacheEntry; readonly cwd: string }
2726 ) {
2727 if (!hasInlineLink(block)) return
2728 for (const link of malformedInlineLinks(block)) {
2729 diagnostics.push({ ...diagnostic("malformed-link", `Malformed JSDoc inline link: ${link}`), range: block.range })
2730 }
2731 for (const link of collectJSDocLinks(sourceFile, block)) {
2732 const text = link.getText(sourceFile)
2733 const target = extractInlineLinkTarget(text)
2734 if (target === "") continue
2735 if (urlRegex.test(target)) {
2736 diagnostics.push({
2737 ...diagnostic("url-link", `JSDoc inline link must target a TypeScript symbol: ${text}`),
2738 range: [link.pos, link.end]
2739 })
2740 } else if (resolveJSDocLinkSymbol(link, linkContext.checker) === undefined) {
2741 diagnostics.push({
2742 ...diagnostic("unresolved-link", `Unresolved JSDoc inline link: ${text}`),
2743 range: [link.pos, link.end]
2744 })
2745 }
2746 }
2747 for (const link of collectJSDocSeeLinks(sourceFile, block)) {
2748 const text = link.getText(sourceFile)
2749 const target = extractInlineLinkTarget(text)
2750 if (target === "" || urlRegex.test(target)) continue
2751 const symbol = resolveJSDocLinkSymbol(link, linkContext.checker)
2752 if (symbol === undefined) continue
2753 if (undocumentedSeeLinkTarget(symbol, linkContext.checker, linkContext.cwd) !== undefined) {
2754 diagnostics.push({
2755 ...diagnostic("undocumented-see-target", `@see link target must have public JSDoc: ${text}`),
2756 range: [link.pos, link.end]
2757 })
2758 }
2759 }
2760 }
2761
2762 function parseDocumentedTs(
2763 node: ts.Node,
2764 scope: DocScope,
2765 diagnostics: Array<JSDocModelDiagnostic>,
2766 required = true,
2767 linkContext?: { readonly checker: ts.TypeChecker; readonly entry: ProgramCacheEntry; readonly cwd: string }
2768 ) {
2769 let block = getNodeJSDoc(node)
2770 // Barrel re-exports intentionally use minimal, tag-only JSDoc.
2771 if (block !== undefined && (ts.isExportDeclaration(node) || ts.isExportSpecifier(node))) {
2772 const loose = parseLooseJSDocBlock(block.raw, block.range)
2773 if (loose.tags[0]?.line === 0) {
2774 block = {
2775 ...loose,
2776 parsed: {
2777 description: { short: "", whenToUse: null, details: null, gotchas: null },
2778 examples: [],
2779 tags: loose.tags
2780 }
2781 }
2782 }
2783 }
2784 if (block?.internal) return undefined
2785 if (block === undefined) {
2786 if (required) {
2787 diagnostics.push({
2788 ...diagnostic("missing-jsdoc", scope === "member" ? "Member JSDoc is required" : "Public JSDoc is required"),
2789 range: nodeRange(node)
2790 })
2791 }
2792 return undefined
2793 }
2794 addModelDiagnostics(diagnostics, block.range, block.diagnostics)
2795 if (block.parsed === undefined) return undefined
2796 // Only names that can be imported directly require @stability.
2797 const requireStability = scope === "declaration" || (scope === "namespace" && ts.isSourceFile(node.parent))
2798 const tags = buildTags(scope, block.parsed.tags, requireStability)
2799 if (tags._tag === "Failure") {
2800 addModelDiagnostics(diagnostics, block.range, tags.error.diagnostics)
2801 return undefined
2802 }
2803 const parsedTags = tags.value as ParsedDeclarationTags | ParsedNamespaceTags | ParsedMemberTags
2804 if (linkContext !== undefined) addJSDocLinkDiagnostics(node.getSourceFile(), block, diagnostics, linkContext)
2805 return {
2806 core: block.parsed,
2807 tags: linkContext === undefined ? parsedTags : attachSeeLinkSymbols(parsedTags, node, block, linkContext)
2808 }
2809 }
2810
2811 function hasExportModifier(node: ts.Node): boolean {
2812 return ts.canHaveModifiers(node) &&
2813 (ts.getModifiers(node)?.some((modifier) => modifier.kind === ts.SyntaxKind.ExportKeyword) ?? false)
2814 }
2815
2816 function hasDefaultModifier(node: ts.Node): boolean {
2817 return ts.canHaveModifiers(node) &&
2818 (ts.getModifiers(node)?.some((modifier) => modifier.kind === ts.SyntaxKind.DefaultKeyword) ?? false)
2819 }
2820
2821 function declarationName(node: ts.Node): string | undefined {
2822 if (
2823 (ts.isInterfaceDeclaration(node) || ts.isTypeAliasDeclaration(node) || ts.isClassDeclaration(node) ||
2824 ts.isFunctionDeclaration(node) || ts.isModuleDeclaration(node)) && node.name !== undefined
2825 ) return node.name.text
2826 if (ts.isVariableStatement(node)) {
2827 return node.declarationList.declarations.map((declaration) => {
2828 if (ts.isIdentifier(declaration.name)) return declaration.name.text
2829 if (ts.isObjectBindingPattern(declaration.name)) {
2830 return declaration.name.elements.map((element) =>
2831 element.propertyName?.getText(element.getSourceFile()) ?? element.name.getText(element.getSourceFile())
2832 ).join(", ")
2833 }
2834 return ""
2835 }).filter(Boolean).join(", ")
2836 }
2837 return undefined
2838 }
2839
2840 function publicDeclarationRange(node: ts.Node, name: string): readonly [number, number] {
2841 if (ts.isVariableStatement(node)) {
2842 const declaration = node.declarationList.declarations.find((item) =>
2843 ts.isIdentifier(item.name) && item.name.text === name
2844 )
2845 if (declaration !== undefined) return nodeRange(declaration)
2846 }
2847 return nodeRange(node)
2848 }
2849
2850 function bucketOfTs(node: ts.Node): ExportBucket | undefined {
2851 if (ts.isVariableStatement(node) || ts.isFunctionDeclaration(node) || ts.isClassDeclaration(node)) return "value"
2852 if (ts.isTypeAliasDeclaration(node) || ts.isInterfaceDeclaration(node)) return "type"
2853 return undefined
2854 }
2855
2856 function normalizeSignature(cwd: string, text: string): string | null {
2857 const normalizedCwd = normalizePathName(cwd)
2858 const signature = text.replaceAll(normalizedCwd, ".").replaceAll(cwd, ".").replace(/\r\n?/g, "\n").replace(
2859 /[ \t]+$/gm,
2860 ""
2861 ).trim()
2862 return signature === "" ? null : signature
2863 }
2864
2865 function displaySignature(text: string): string {
2866 return text.replace(/import\((?:"[^"]+"|'[^']+')\)\.([A-Za-z_$][A-Za-z0-9_$]*(?:\.[A-Za-z_$][A-Za-z0-9_$]*)*)/g, "$1")
2867 }
2868
2869 function parseableSignature(cwd: string, text: string): string | null {
2870 const signature = normalizeSignature(cwd, displaySignature(text))
2871 if (signature === null) return null
2872 const source = ts.createSourceFile(
2873 "signature.ts",
2874 signature,
2875 ts.ScriptTarget.Latest,
2876 true,
2877 ts.ScriptKind.TS
2878 ) as SourceFileWithParseDiagnostics
2879 return source.parseDiagnostics.length === 0 ? signature : null
2880 }
2881
2882 function signatureLocalName(name: string): string {
2883 const sanitized = name.replace(/[^A-Za-z0-9_$]/g, "_")
2884 return `_${sanitized === "" ? "api" : sanitized}`
2885 }
2886
2887 function signatureExportName(name: string): string {
2888 return /^[A-Za-z_$][A-Za-z0-9_$]*$/.test(name) ? name : JSON.stringify(name)
2889 }
2890
2891 function signatureAlias(name: string, text: string): string {
2892 const localName = signatureLocalName(name)
2893 return `declare const ${localName}: ${text}
2894 export { ${localName} as ${signatureExportName(name)} }`
2895 }
2896
2897 function signatureParameterDeclaration(parameter: ts.Symbol): ts.ParameterDeclaration | undefined {
2898 const declaration = parameter.valueDeclaration ?? parameter.declarations?.[0]
2899 return declaration !== undefined && ts.isParameter(declaration) ? declaration : undefined
2900 }
2901
2902 function signatureParameterName(parameter: ts.Symbol): string {
2903 const declaration = signatureParameterDeclaration(parameter)
2904 if (declaration !== undefined && ts.isIdentifier(declaration.name)) return declaration.name.text
2905 return parameter.getName()
2906 }
2907
2908 function signatureFunctionThisKind(type: ts.Type, checker: ts.TypeChecker, location: ts.Node): string {
2909 const thisParameter = checker.getSignaturesOfType(type, ts.SignatureKind.Call)[0]?.thisParameter
2910 if (thisParameter === undefined) return "none"
2911 const thisType = checker.typeToString(
2912 checker.getTypeOfSymbolAtLocation(thisParameter, location),
2913 location,
2914 signatureTypeFormatFlags
2915 )
2916 return thisType === "unassigned" ? "unassigned" : "self"
2917 }
2918
2919 function isSignatureFunctionKind(kind: string): boolean {
2920 return kind.startsWith("body:") || kind.startsWith("function:")
2921 }
2922
2923 function signatureTransformCountKind(count: number): string {
2924 if (count <= 3) return String(count)
2925 if (count <= 7) return "4"
2926 if (count <= 15) return "8"
2927 return "16"
2928 }
2929
2930 function signatureParameterKind(
2931 parameter: ts.Symbol | undefined,
2932 checker: ts.TypeChecker,
2933 location: ts.Node
2934 ): string {
2935 if (parameter === undefined) return "none"
2936 const declaration = signatureParameterDeclaration(parameter)
2937 if (declaration?.dotDotDotToken !== undefined) return "rest"
2938 const name = signatureParameterName(parameter).replace(/_$/, "").toLowerCase()
2939 const type = checker.getTypeOfSymbolAtLocation(parameter, declaration ?? location)
2940 if (name === "self" || name === "that") return "self"
2941 if (name === "body") return `body:${signatureFunctionThisKind(type, checker, location)}`
2942 if (name === "name" || name === "spanname") return "name"
2943 if (name.includes("refinement")) return "refinement"
2944 if (name.includes("predicate")) return "predicate"
2945 if (name === "options" || name === "option" || name === "opts" || name === "config" || name === "args") {
2946 return "options"
2947 }
2948 if (name === "f" || name === "fn" || name === "callback") {
2949 return `function:${signatureFunctionThisKind(type, checker, location)}`
2950 }
2951 if (checker.getSignaturesOfType(type, ts.SignatureKind.Call).length > 0) {
2952 return `function:${signatureFunctionThisKind(type, checker, location)}`
2953 }
2954 if ((type.flags & ts.TypeFlags.StringLike) !== 0) return "primitive:string"
2955 if ((type.flags & ts.TypeFlags.NumberLike) !== 0) return "primitive:number"
2956 if ((type.flags & ts.TypeFlags.BooleanLike) !== 0) return "primitive:boolean"
2957 if ((type.flags & ts.TypeFlags.BigIntLike) !== 0) return "primitive:bigint"
2958 if ((type.flags & ts.TypeFlags.ESSymbolLike) !== 0) return "primitive:symbol"
2959 if ((type.flags & ts.TypeFlags.Object) !== 0 || checker.getPropertiesOfType(type).length > 0) return "object"
2960 return "other"
2961 }
2962
2963 function signatureTailKind(signature: ts.Signature, checker: ts.TypeChecker, location: ts.Node): string {
2964 if (signature.parameters.length <= 1) return "none"
2965 const firstKind = signatureParameterKind(signature.parameters[0], checker, location)
2966 const tailKinds = signature.parameters.slice(1).map((parameter) =>
2967 signatureParameterKind(parameter, checker, location)
2968 )
2969 if (firstKind === "options") {
2970 const hasTransformTail = tailKinds.length > 1 && tailKinds.slice(1).every(isSignatureFunctionKind)
2971 return `${tailKinds[0]}:${hasTransformTail ? "transform" : "none"}`
2972 }
2973 if (tailKinds.every(isSignatureFunctionKind)) {
2974 return firstKind.startsWith("body:")
2975 ? "transform"
2976 : `transform:${signatureTransformCountKind(tailKinds.length)}`
2977 }
2978 return tailKinds[0]
2979 }
2980
2981 function signatureShapeKey(signature: ts.Signature, checker: ts.TypeChecker, location: ts.Node): string {
2982 const hasRest = signature.parameters.some((parameter) =>
2983 signatureParameterDeclaration(parameter)?.dotDotDotToken !== undefined
2984 )
2985 const returnType = checker.getReturnTypeOfSignature(signature)
2986 const returnMode = checker.getSignaturesOfType(returnType, ts.SignatureKind.Call).length > 0 ? "curried" : "direct"
2987 return [
2988 hasRest ? "rest" : "fixed",
2989 signatureParameterKind(signature.parameters[0], checker, location),
2990 signatureTailKind(signature, checker, location),
2991 returnMode
2992 ].join(":")
2993 }
2994
2995 function representativeSignatures(
2996 signatures: ReadonlyArray<ts.Signature>,
2997 checker: ts.TypeChecker,
2998 location: ts.Node
2999 ): ReadonlyArray<ts.Signature> {
3000 const seen = new Set<string>()
3001 const out: Array<ts.Signature> = []
3002 for (const signature of signatures) {
3003 const key = signatureShapeKey(signature, checker, location)
3004 if (seen.has(key)) continue
3005 seen.add(key)
3006 out.push(signature)
3007 }
3008 return out
3009 }
3010
3011 function functionSignature(
3012 name: string,
3013 symbol: ts.Symbol,
3014 location: ts.Node,
3015 checker: ts.TypeChecker,
3016 cwd: string
3017 ): string | null {
3018 const target = resolvedSymbolTarget(symbol, checker)
3019 const type = checker.getTypeOfSymbolAtLocation(target, location)
3020 const signatures = checker.getSignaturesOfType(type, ts.SignatureKind.Call)
3021 if (signatures.length === 0) return null
3022 const callSignatures: Array<string> = []
3023 for (const signature of representativeSignatures(signatures, checker, location)) {
3024 const text = normalizeSignature(
3025 cwd,
3026 checker.signatureToString(signature, location, signatureTypeFormatFlags, ts.SignatureKind.Call)
3027 )
3028 if (text === null) return null
3029 callSignatures.push(text)
3030 }
3031 const declaration = parseableSignature(
3032 cwd,
3033 callSignatures.map((text) => `declare function ${name}${text}`).join("\n")
3034 )
3035 if (declaration !== null) return declaration
3036 const callSignatureAlias = parseableSignature(
3037 cwd,
3038 signatureAlias(
3039 name,
3040 `{
3041 ${callSignatures.map((text) => ` ${text};`).join("\n")}
3042 }`
3043 )
3044 )
3045 if (callSignatureAlias !== null) return callSignatureAlias
3046 const typeText = normalizeSignature(cwd, checker.typeToString(type, location, signatureTypeFormatFlags))
3047 if (typeText === null) return null
3048 return parseableSignature(cwd, `declare const ${name}: ${typeText}`) ??
3049 parseableSignature(cwd, signatureAlias(name, typeText))
3050 }
3051
3052 function symbolSignature(
3053 name: string,
3054 bucket: ExportBucket,
3055 symbol: ts.Symbol,
3056 location: ts.Node,
3057 checker: ts.TypeChecker,
3058 cwd: string
3059 ): string | null {
3060 if (bucket !== "value") return null
3061 const target = resolvedSymbolTarget(symbol, checker)
3062 const type = checker.getTypeOfSymbolAtLocation(target, location)
3063 if (checker.getSignaturesOfType(type, ts.SignatureKind.Call).length === 0) return null
3064 return functionSignature(name, symbol, location, checker, cwd)
3065 }
3066
3067 function declarationSignature(
3068 name: string,
3069 bucket: ExportBucket,
3070 node: ts.Node,
3071 checker: ts.TypeChecker,
3072 cwd: string
3073 ): string | null {
3074 if (ts.isVariableStatement(node)) {
3075 const declaration = node.declarationList.declarations.find((item) =>
3076 ts.isIdentifier(item.name) && item.name.text === name
3077 )
3078 if (declaration === undefined) return null
3079 const symbol = checker.getSymbolAtLocation(declaration.name)
3080 return symbol === undefined ? null : symbolSignature(name, bucket, symbol, declaration.name, checker, cwd)
3081 }
3082 const nameNode = ts.isFunctionDeclaration(node) || ts.isClassDeclaration(node) || ts.isInterfaceDeclaration(node) ||
3083 ts.isTypeAliasDeclaration(node)
3084 ? node.name
3085 : undefined
3086 if (nameNode === undefined) return null
3087 const symbol = checker.getSymbolAtLocation(nameNode)
3088 return symbol === undefined ? null : symbolSignature(name, bucket, symbol, nameNode, checker, cwd)
3089 }
3090
3091 function exportSpecifierSignature(
3092 name: string,
3093 bucket: ExportBucket,
3094 specifier: ts.ExportSpecifier,
3095 checker: ts.TypeChecker,
3096 cwd: string
3097 ): string | null {
3098 const symbol = checker.getSymbolAtLocation(specifier.name) ??
3099 (specifier.propertyName === undefined ? undefined : checker.getSymbolAtLocation(specifier.propertyName))
3100 return symbol === undefined ? null : symbolSignature(name, bucket, symbol, specifier.name, checker, cwd)
3101 }
3102
3103 function parseMembersFromTsType(
3104 type: ts.TypeNode | undefined,
3105 diagnostics: Array<JSDocModelDiagnostic>,
3106 linkContext: { readonly checker: ts.TypeChecker; readonly entry: ProgramCacheEntry; readonly cwd: string }
3107 ): Array<ParsedMember> {
3108 if (!type) return []
3109 if (ts.isTypeLiteralNode(type)) return parseTsMembers(type.members, diagnostics, linkContext)
3110 if (ts.isUnionTypeNode(type) || ts.isIntersectionTypeNode(type)) {
3111 return type.types.flatMap((item) => parseMembersFromTsType(item, diagnostics, linkContext))
3112 }
3113 if (ts.isParenthesizedTypeNode(type) || ts.isTypeOperatorNode(type)) {
3114 return parseMembersFromTsType(type.type, diagnostics, linkContext)
3115 }
3116 if (ts.isArrayTypeNode(type)) return parseMembersFromTsType(type.elementType, diagnostics, linkContext)
3117 if (ts.isConditionalTypeNode(type)) {
3118 return [
3119 ...parseMembersFromTsType(type.checkType, diagnostics, linkContext),
3120 ...parseMembersFromTsType(type.extendsType, diagnostics, linkContext),
3121 ...parseMembersFromTsType(type.trueType, diagnostics, linkContext),
3122 ...parseMembersFromTsType(type.falseType, diagnostics, linkContext)
3123 ]
3124 }
3125 if (ts.isTypeReferenceNode(type)) {
3126 return type.typeArguments?.flatMap((item) => parseMembersFromTsType(item, diagnostics, linkContext)) ?? []
3127 }
3128 if (ts.isMappedTypeNode(type)) return parseMembersFromTsType(type.type, diagnostics, linkContext)
3129 if (ts.isIndexedAccessTypeNode(type)) {
3130 return [
3131 ...parseMembersFromTsType(type.objectType, diagnostics, linkContext),
3132 ...parseMembersFromTsType(type.indexType, diagnostics, linkContext)
3133 ]
3134 }
3135 if (ts.isFunctionTypeNode(type) || ts.isConstructorTypeNode(type)) {
3136 return parseMembersFromTsType(type.type, diagnostics, linkContext)
3137 }
3138 return []
3139 }
3140
3141 function memberName(member: ts.TypeElement | ts.ClassElement): string {
3142 if (
3143 ts.isPropertySignature(member) || ts.isMethodSignature(member) || ts.isPropertyDeclaration(member) ||
3144 ts.isMethodDeclaration(member) || ts.isGetAccessorDeclaration(member) || ts.isSetAccessorDeclaration(member)
3145 ) {
3146 const name = member.name
3147 if (ts.isComputedPropertyName(name)) return name.expression.getText(member.getSourceFile())
3148 return name.getText(member.getSourceFile()).replace(/^[']|[']$/g, "")
3149 }
3150 return ""
3151 }
3152
3153 function memberType(member: ts.TypeElement | ts.ClassElement): ts.TypeNode | undefined {
3154 if (
3155 ts.isPropertySignature(member) || ts.isMethodSignature(member) || ts.isPropertyDeclaration(member) ||
3156 ts.isMethodDeclaration(member) || ts.isGetAccessorDeclaration(member) || ts.isSetAccessorDeclaration(member)
3157 ) return member.type
3158 return undefined
3159 }
3160
3161 function parseTsMembers(
3162 members: ts.NodeArray<ts.TypeElement | ts.ClassElement>,
3163 diagnostics: Array<JSDocModelDiagnostic>,
3164 linkContext: { readonly checker: ts.TypeChecker; readonly entry: ProgramCacheEntry; readonly cwd: string }
3165 ): Array<ParsedMember> {
3166 const out: Array<ParsedMember> = []
3167 for (const member of members) {
3168 if (
3169 ts.isCallSignatureDeclaration(member) || ts.isConstructSignatureDeclaration(member) ||
3170 ts.isIndexSignatureDeclaration(member) || member.kind === ts.SyntaxKind.Constructor
3171 ) continue
3172 const documented = parseDocumentedTs(member, "member", diagnostics, false, linkContext)
3173 if (documented === undefined) continue
3174 const name = memberName(member)
3175 if (name === "") continue
3176 const nested = parseMembersFromTsType(memberType(member), diagnostics, linkContext)
3177 out.push({
3178 name,
3179 signature: null,
3180 range: nodeRange(member),
3181 description: documented.core.description,
3182 examples: documented.core.examples,
3183 tags: documented.tags as ParsedMemberTags,
3184 members: nested
3185 })
3186 }
3187 return out
3188 }
3189
3190 function parseDeclarationMembersTs(
3191 node: ts.Node,
3192 diagnostics: Array<JSDocModelDiagnostic>,
3193 linkContext: { readonly checker: ts.TypeChecker; readonly entry: ProgramCacheEntry; readonly cwd: string }
3194 ): Array<ParsedMember> {
3195 if (ts.isInterfaceDeclaration(node)) return parseTsMembers(node.members, diagnostics, linkContext)
3196 if (ts.isClassDeclaration(node)) return parseTsMembers(node.members, diagnostics, linkContext)
3197 if (ts.isTypeAliasDeclaration(node)) return parseMembersFromTsType(node.type, diagnostics, linkContext)
3198 if (ts.isVariableStatement(node)) {
3199 return node.declarationList.declarations.flatMap((d) => parseMembersFromTsType(d.type, diagnostics, linkContext))
3200 }
3201 if (ts.isFunctionDeclaration(node)) return parseMembersFromTsType(node.type, diagnostics, linkContext)
3202 return []
3203 }
3204
3205 function hasDeclareModifier(node: ts.Node): boolean {
3206 return ts.canHaveModifiers(node) &&
3207 (ts.getModifiers(node)?.some((modifier) => modifier.kind === ts.SyntaxKind.DeclareKeyword) ?? false)
3208 }
3209
3210 function parseNamespaceTs(
3211 node: ts.ModuleDeclaration,
3212 diagnostics: Array<JSDocModelDiagnostic>,
3213 linkContext: { readonly checker: ts.TypeChecker; readonly entry: ProgramCacheEntry; readonly cwd: string },
3214 isInsideDeclare = false
3215 ): ParsedNamespace | undefined {
3216 if (!ts.isIdentifier(node.name)) return undefined
3217 if (!isInsideDeclare && !hasDeclareModifier(node)) {
3218 diagnostics.push({
3219 ...diagnostic("namespace-declare", "Namespaces must be declared with declare namespace"),
3220 range: nodeRange(node)
3221 })
3222 return undefined
3223 }
3224 const documented = parseDocumentedTs(node, "namespace", diagnostics, true, linkContext)
3225 if (documented === undefined) return undefined
3226 const declarations: Array<ParsedNamespaceDeclaration> = []
3227 const namespaces: Array<ParsedNamespace> = []
3228 if (node.body !== undefined && ts.isModuleBlock(node.body)) {
3229 for (const statement of node.body.statements) {
3230 if (!hasExportModifier(statement)) continue
3231 if (ts.isModuleDeclaration(statement)) {
3232 const nested = parseNamespaceTs(statement, diagnostics, linkContext, true)
3233 if (nested !== undefined) namespaces.push(nested)
3234 continue
3235 }
3236 if (ts.isEnumDeclaration(statement)) {
3237 diagnostics.push({ ...diagnostic("enum", "Enums are not allowed"), range: nodeRange(statement) })
3238 continue
3239 }
3240 const bucket = bucketOfTs(statement)
3241 if (bucket !== "type") {
3242 diagnostics.push({
3243 ...diagnostic("namespace-value", "Namespace exports must be type declarations"),
3244 range: nodeRange(statement)
3245 })
3246 continue
3247 }
3248 const nestedDocumented = parseDocumentedTs(statement, "namespace-declaration", diagnostics, true, linkContext)
3249 if (nestedDocumented === undefined) continue
3250 const name = declarationName(statement)
3251 if (name === undefined || name.length === 0) {
3252 diagnostics.push({
3253 ...diagnostic("missing-name", "Namespace declaration name could not be determined"),
3254 range: nodeRange(statement)
3255 })
3256 continue
3257 }
3258 declarations.push({
3259 name,
3260 signature: null,
3261 range: publicDeclarationRange(statement, name),
3262 description: nestedDocumented.core.description,
3263 examples: nestedDocumented.core.examples,
3264 tags: nestedDocumented.tags as ParsedNamespaceTags,
3265 members: parseDeclarationMembersTs(statement, diagnostics, linkContext)
3266 })
3267 }
3268 }
3269 return {
3270 name: node.name.text,
3271 signature: null,
3272 range: nodeRange(node),
3273 description: documented.core.description,
3274 examples: documented.core.examples,
3275 tags: documented.tags as ParsedNamespaceTags,
3276 declarations,
3277 namespaces
3278 }
3279 }
3280
3281 function skipLeadingIgnoredTrivia(source: string): number {
3282 let index = source.charCodeAt(0) === 0xfeff ? 1 : 0
3283 while (index < source.length) {
3284 while (index < source.length && /\s/.test(source[index])) index++
3285 if (!source.startsWith("//", index)) return index
3286 const lineEnd = source.indexOf("\n", index)
3287 const end = lineEnd === -1 ? source.length : lineEnd + 1
3288 if (!isSkippableDirectiveComment(source.slice(index, end))) return index
3289 index = end
3290 }
3291 return index
3292 }
3293
3294 function sourceFileTopLevelJSDoc(sourceFile: ts.SourceFile): ParsedModuleJSDoc | undefined {
3295 const source = sourceFile.text
3296 const start = skipLeadingIgnoredTrivia(source)
3297 if (!source.startsWith("/**", start)) return undefined
3298 const end = source.indexOf("*/", start + 3)
3299 if (end === -1) return undefined
3300 const range = [start, end + 2] as const
3301 const firstStatement = sourceFile.statements[0]
3302 if (firstStatement !== undefined) {
3303 const jsDocs = (firstStatement as { readonly jsDoc?: ReadonlyArray<ts.JSDoc> }).jsDoc ?? []
3304 if (
3305 jsDocs.some((jsDoc) => jsDoc.pos === range[0] && jsDoc.end === range[1]) &&
3306 !ts.isImportDeclaration(firstStatement) &&
3307 !ts.isImportEqualsDeclaration(firstStatement)
3308 ) return undefined
3309 }
3310 return { raw: source.slice(range[0], range[1]), range }
3311 }
3312
3313 function parseModuleJSDocTs(
3314 sourceFile: ts.SourceFile,
3315 moduleJSDoc: ParsedModuleJSDoc,
3316 diagnostics: Array<JSDocModelDiagnostic>,
3317 linkContext: { readonly checker: ts.TypeChecker; readonly entry: ProgramCacheEntry; readonly cwd: string }
3318 ): ParsedModuleJSDoc | undefined {
3319 const block = parseLooseJSDocBlock(moduleJSDoc.raw, [moduleJSDoc.range[0], moduleJSDoc.range[1]])
3320 if (block.internal) return undefined
3321 const tags = buildTags("module", block.tags, true)
3322 if (tags._tag === "Failure") addModelDiagnostics(diagnostics, block.range, tags.error.diagnostics)
3323 const examples = parseModuleExamples(block)
3324 addModelDiagnostics(diagnostics, block.range, examples.diagnostics)
3325 addJSDocLinkDiagnostics(sourceFile, block, diagnostics, linkContext)
3326 return moduleJSDoc
3327 }
3328
3329 function parseSourceFileDocs(
3330 cwd: string,
3331 sourceFile: ts.SourceFile,
3332 checker: ts.TypeChecker,
3333 entry: ProgramCacheEntry
3334 ): { readonly parsed: ParsedJSDocFile; readonly diagnostics: ReadonlyArray<JSDocModelDiagnostic> } {
3335 const diagnostics: Array<JSDocModelDiagnostic> = []
3336 const declarations: Array<ParsedRootDeclaration> = []
3337 const namespaces: Array<ParsedNamespace> = []
3338 const linkContext = { checker, entry, cwd }
3339 const checkedFunctionOverloads = new Set<string>()
3340 const moduleJSDoc = sourceFileTopLevelJSDoc(sourceFile)
3341 const parsedModuleJSDoc = moduleJSDoc === undefined
3342 ? undefined
3343 : parseModuleJSDocTs(sourceFile, moduleJSDoc, diagnostics, linkContext)
3344
3345 for (const statement of sourceFile.statements) {
3346 if (ts.isExportAssignment(statement)) continue
3347 if (ts.isExportDeclaration(statement)) {
3348 if (statement.exportClause === undefined) continue
3349 if (ts.isNamespaceExport(statement.exportClause)) {
3350 const documented = parseDocumentedTs(statement, "namespace", diagnostics, true, linkContext)
3351 if (documented !== undefined) {
3352 namespaces.push({
3353 name: statement.exportClause.name.text,
3354 signature: statement.getText(sourceFile),
3355 range: nodeRange(statement),
3356 description: documented.core.description,
3357 examples: documented.core.examples,
3358 tags: documented.tags as ParsedNamespaceTags,
3359 declarations: [],
3360 namespaces: []
3361 })
3362 }
3363 continue
3364 }
3365 if (ts.isNamedExports(statement.exportClause) && statement.exportClause.elements.length === 0) {
3366 diagnostics.push({
3367 ...diagnostic("empty-export", "Empty export declarations are not allowed"),
3368 range: nodeRange(statement)
3369 })
3370 }
3371 if (ts.isNamedExports(statement.exportClause)) {
3372 for (const specifier of statement.exportClause.elements) {
3373 const documented = parseDocumentedTs(specifier, "declaration", diagnostics, true, linkContext)
3374 if (documented === undefined) continue
3375 declarations.push({
3376 name: specifier.name.text,
3377 bucket: statement.isTypeOnly || specifier.isTypeOnly ? "type" : "value",
3378 signature: exportSpecifierSignature(
3379 specifier.name.text,
3380 statement.isTypeOnly || specifier.isTypeOnly ? "type" : "value",
3381 specifier,
3382 checker,
3383 cwd
3384 ),
3385 range: nodeRange(specifier),
3386 description: documented.core.description,
3387 examples: documented.core.examples,
3388 tags: documented.tags as ParsedDeclarationTags,
3389 members: []
3390 })
3391 }
3392 }
3393 continue
3394 }
3395 if (!hasExportModifier(statement) || hasDefaultModifier(statement)) continue
3396 if (ts.isModuleDeclaration(statement)) {
3397 const namespace = parseNamespaceTs(statement, diagnostics, linkContext)
3398 if (namespace !== undefined) namespaces.push(namespace)
3399 continue
3400 }
3401 if (ts.isEnumDeclaration(statement)) {
3402 diagnostics.push({ ...diagnostic("enum", "Enums are not allowed"), range: nodeRange(statement) })
3403 continue
3404 }
3405 const bucket = bucketOfTs(statement)
3406 if (bucket === undefined) continue
3407 if (ts.isFunctionDeclaration(statement) && statement.name !== undefined) {
3408 const name = statement.name.text
3409 if (statement.body === undefined) {
3410 if (checkedFunctionOverloads.has(name)) continue
3411 checkedFunctionOverloads.add(name)
3412 } else if (checkedFunctionOverloads.has(name)) {
3413 continue
3414 }
3415 }
3416 const documented = parseDocumentedTs(statement, "declaration", diagnostics, true, linkContext)
3417 if (documented === undefined) continue
3418 const name = declarationName(statement)
3419 if (name === undefined || name.length === 0) {
3420 diagnostics.push({
3421 ...diagnostic("missing-name", "Root declaration name could not be determined"),
3422 range: nodeRange(statement)
3423 })
3424 continue
3425 }
3426 declarations.push({
3427 name,
3428 bucket,
3429 signature: declarationSignature(name, bucket, statement, checker, cwd),
3430 range: publicDeclarationRange(statement, name),
3431 description: documented.core.description,
3432 examples: documented.core.examples,
3433 tags: documented.tags as ParsedDeclarationTags,
3434 members: parseDeclarationMembersTs(statement, diagnostics, linkContext)
3435 })
3436 }
3437 return {
3438 parsed: {
3439 ...(parsedModuleJSDoc === undefined ? {} : { moduleJSDoc: parsedModuleJSDoc }),
3440 declarations,
3441 namespaces
3442 },
3443 diagnostics: uniqueDiagnostics(diagnostics) as Array<JSDocModelDiagnostic>
3444 }
3445 }
3446
3447 /**
3448 * Loads a JSDoc extraction configuration from JSON.
3449 *
3450 * @category configuration
3451 * @since 4.0.0
3452 */
3453 export function loadJSDocConfig(cwd = process.cwd(), configPath = "jsdocs.config.json"): JSDocConfig {
3454 const absolute = path.resolve(cwd, configPath)
3455 const parsed = JSON.parse(fs.readFileSync(absolute, "utf8")) as JSDocConfig
3456 return parsed
3457 }
3458
3459 /**
3460 * Extracts a complete JSDoc model synchronously.
3461 *
3462 * @category extraction
3463 * @since 4.0.0
3464 */
3465 export function extractJSDocsSync(options: ExtractJSDocsOptions): JSDocModel {
3466 // Share caches within an extraction, not across source snapshots.
3467 programCache.clear()
3468 packageMetadataCache.clear()
3469 barrelExportCache.clear()
3470 const cwd = path.resolve(options.cwd ?? process.cwd())
3471 const tsconfigPath = path.resolve(cwd, options.tsconfig)
3472 const entry = getProgram(tsconfigPath)
3473 if (entry.error !== undefined || entry.program === undefined) {
3474 throw new Error(entry.error ?? `Unable to read ${tsconfigPath}`)
3475 }
3476 const program = entry.program
3477 const checker = program.getTypeChecker()
3478 const sourceByPath = new Map(program.getSourceFiles().map((file) => [path.resolve(file.fileName), file]))
3479 const sourceFilesByFile = new Map(program.getSourceFiles().map((file) => [normalizeFile(cwd, file.fileName), file]))
3480 const files = globSync([...options.include], {
3481 cwd,
3482 absolute: true,
3483 nodir: true,
3484 ignore: [...options.exclude ?? []]
3485 }).sort()
3486 const modelFiles: Array<JSDocModelFile> = []
3487 for (const filename of files) {
3488 const source = fs.readFileSync(filename, "utf8")
3489 const file = normalizeFile(cwd, filename)
3490 const hash = hashSource(source)
3491 const sourceFile = sourceByPath.get(path.resolve(filename))
3492 if (sourceFile === undefined) {
3493 modelFiles.push({
3494 file,
3495 hash,
3496 diagnostics: [{ ...diagnostic("tsconfig", `${file} is not included in ${options.tsconfig}`), range: [0, 0] }],
3497 declarations: [],
3498 namespaces: []
3499 })
3500 continue
3501 }
3502 const result = parseSourceFileDocs(cwd, sourceFile, checker, entry)
3503 if (
3504 result.diagnostics.length === 0 && result.parsed.declarations.length === 0 &&
3505 result.parsed.namespaces.length === 0 && result.parsed.moduleJSDoc === undefined
3506 ) continue
3507 const fileDiagnostics = [...result.diagnostics]
3508 let importsValue: ParsedJSDocImports | undefined
3509 if (
3510 result.parsed.declarations.length > 0 || result.parsed.namespaces.length > 0 ||
3511 result.parsed.moduleJSDoc !== undefined
3512 ) {
3513 const imports = resolveJSDocImports(cwd, filename, sourceFile, checker)
3514 if (imports._tag === "Success") importsValue = imports.value
3515 else {
3516 fileDiagnostics.push({
3517 ...diagnostic(
3518 "imports",
3519 `Unable to resolve jsdocs imports: ${imports.error}. Add the missing barrel/package export or exclude this file from jsdocs.`
3520 ),
3521 range: [0, 0]
3522 })
3523 }
3524 }
3525 modelFiles.push({
3526 file,
3527 hash,
3528 diagnostics: fileDiagnostics,
3529 ...(importsValue === undefined ? {} : { imports: importsValue }),
3530 ...result.parsed
3531 })
3532 }
3533 const filesWithExampleDiagnostics = appendExampleImportDiagnostics(modelFiles)
3534 const withPublicSeeDiagnostics = buildJSDocApisWithPublicSeeDiagnostics(filesWithExampleDiagnostics, {
3535 sourceFilesByFile,
3536 checker,
3537 entry,
3538 cwd
3539 })
3540 return {
3541 version: 3,
3542 generatedBy: "@effect/jsdocs",
3543 generatedAt: new Date().toISOString(),
3544 inputHash: computeJSDocInputHash(options),
3545 files: withPublicSeeDiagnostics.files,
3546 apis: withPublicSeeDiagnostics.apis
3547 }
3548 }
3549
3550 /**
3551 * Extracts a complete JSDoc model in `Effect`.
3552 *
3553 * @category extraction
3554 * @since 4.0.0
3555 */
3556 export const extractJSDocs = (options: ExtractJSDocsOptions): Effect.Effect<JSDocModel> =>
3557 Effect.sync(() => extractJSDocsSync(options))
3558
3559 /**
3560 * Writes a JSDoc model as formatted JSON.
3561 *
3562 * @category persistence
3563 * @since 4.0.0
3564 */
3565 export function writeJSDocModel(cwd: string, output: string, model: JSDocModel) {
3566 const filename = path.resolve(cwd, output)
3567 fs.mkdirSync(path.dirname(filename), { recursive: true })
3568 fs.writeFileSync(filename, `${JSON.stringify(model, null, 2)}\n`)
3569 }
3570
3571 /**
3572 * Reads and validates the outer structure of a persisted JSDoc model.
3573 *
3574 * @category persistence
3575 * @since 4.0.0
3576 */
3577 export function readJSDocModel(filename: string): Result<JSDocModel, string> {
3578 if (!fs.existsSync(filename)) return { _tag: "Failure", error: "missing" }
3579 try {
3580 const parsed = JSON.parse(fs.readFileSync(filename, "utf8")) as JSDocModel
3581 if (parsed.version !== 3) return { _tag: "Failure", error: "Unsupported jsdocs model version" }
3582 if (!Array.isArray(parsed.files)) return { _tag: "Failure", error: "Invalid jsdocs model: files must be an array" }
3583 if (!Array.isArray(parsed.apis)) return { _tag: "Failure", error: "Invalid jsdocs model: apis must be an array" }
3584 return { _tag: "Success", value: parsed }
3585 } catch (error) {
3586 return { _tag: "Failure", error: `Invalid jsdocs model: ${error instanceof Error ? error.message : String(error)}` }
3587 }
3588 }
3589
3590 /**
3591 * Computes the content hash stored for a source file in a JSDoc model.
3592 *
3593 * @category hashing
3594 * @since 4.0.0
3595 */
3596 export function sourceHash(source: string): string {
3597 return hashSource(source)
3598 }