Something went wrong. Try again.
tsref is a Bun CLI for finding references to exported TypeScript APIs.
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397import ts from "typescript";import type { CollectedExport, CollectedMember } from "./exportCollector";import { normalizePath } from "./project";import { classifyReference, isDeclarationName } from "./referenceClassifier";import type { ReferenceKind, ReferenceRecord, SourceLocation } from "./types";
interface SymbolTarget { exportItem?: CollectedExport; memberItem?: CollectedMember;}
export interface ReferenceCollectionContext { languageService: ts.LanguageService; locationCache: Map<string, Map<number, SourceLocation>>; nodeCache: Map<string, Map<number, ts.Node | undefined>>;}
export function createReferenceCollectionContext(program: ts.Program): ReferenceCollectionContext { return { languageService: createLanguageService(program), locationCache: new Map(), nodeCache: new Map(), };}
export interface ReferenceCollectionOptions { countOnly?: boolean; includeImports?: boolean;}
export function collectReferences( program: ts.Program, checker: ts.TypeChecker, targetFilePath: string, exports: CollectedExport[], context = createReferenceCollectionContext(program), options: ReferenceCollectionOptions = {},): void { const includeImports = options.includeImports ?? true; const symbolTargets = new Map<ts.Symbol, SymbolTarget[]>();
for (const exportItem of exports) { for (const symbol of exportItem.symbols) { addSymbolTarget(symbolTargets, symbol, { exportItem }); }
for (const memberItem of exportItem.members) { for (const symbol of memberItem.symbols) { addSymbolTarget(symbolTargets, symbol, { memberItem }); } } }
const seen = new Set<string>();
for (const [symbol, targets] of symbolTargets) { for (const declaration of symbol.declarations ?? []) { const nameNode = getDeclarationNameNode(declaration);
if (!nameNode) { continue; }
const sourceFile = declaration.getSourceFile(); const references = context.languageService.findReferences(sourceFile.fileName, nameNode.getStart(sourceFile)) ?? [];
for (const referencedSymbol of references) { for (const reference of referencedSymbol.references) { recordReference( reference, program, targets, targetFilePath, seen, context, { countOnly: options.countOnly, includeImports }, ); } } } }}
function recordReference( reference: ts.ReferencedSymbolEntry, program: ts.Program, targets: SymbolTarget[], targetFilePath: string, seen: Set<string>, context: ReferenceCollectionContext, options: Required<Pick<ReferenceCollectionOptions, "includeImports">> & Pick<ReferenceCollectionOptions, "countOnly">,): void { if (reference.isDefinition) { return; }
const sourceFile = program.getSourceFile(reference.fileName);
if (!sourceFile || sourceFile.isDeclarationFile) { return; }
const isInternal = normalizePath(sourceFile.fileName) === targetFilePath;
if (options.countOnly && options.includeImports) { for (const target of targets) { const key = [ target.exportItem?.summary.exportName ?? "", target.memberItem?.summary.name ?? "", normalizePath(reference.fileName), reference.textSpan.start, ].join("\0");
if (seen.has(key)) { continue; }
seen.add(key);
if (target.exportItem) { addReferenceCount(target.exportItem.summary, isInternal); }
if (target.memberItem) { addReferenceCount(target.memberItem.summary, isInternal); } }
return; }
const node = getCachedNodeAtPosition(context, sourceFile, reference.textSpan.start);
if (!node) { return; }
const kind = classifyReference(node);
if (!options.includeImports && kind === "import") { return; }
if (isInternal && isDeclarationName(node) && kind !== "import" && kind !== "re-export") { return; }
const location = getCachedLocation(context, reference.textSpan.start, sourceFile);
for (const target of targets) { const key = [ target.exportItem?.summary.exportName ?? "", target.memberItem?.summary.name ?? "", location.filePath, location.line, location.column, kind, ].join("\0");
if (seen.has(key)) { continue; }
seen.add(key); if (target.exportItem) { addReference(target.exportItem.summary, kind, location, isInternal, options.countOnly); }
if (target.memberItem) { addReference(target.memberItem.summary, kind, location, isInternal, options.countOnly); } }}
function addReferenceCount( target: CollectedExport["summary"] | CollectedMember["summary"], isInternal: boolean,): void { if (isInternal) { target.internalReferenceCount = (target.internalReferenceCount ?? 0) + 1; } else { target.externalReferenceCount = (target.externalReferenceCount ?? 0) + 1; }}
function addReference( target: CollectedExport["summary"] | CollectedMember["summary"], kind: ReferenceKind, location: SourceLocation, isInternal: boolean, countOnly: boolean | undefined,): void { if (isInternal) { target.internalReferenceCount = (target.internalReferenceCount ?? 0) + 1; } else { target.externalReferenceCount = (target.externalReferenceCount ?? 0) + 1; }
if (countOnly) { return; }
target.references.push({ kind, location, isInternal, });}
function addSymbolTarget( symbolTargets: Map<ts.Symbol, SymbolTarget[]>, symbol: ts.Symbol, target: SymbolTarget,): void { const existing = symbolTargets.get(symbol);
if (existing) { existing.push(target); return; }
symbolTargets.set(symbol, [target]);}
function getLocation(positionIndex: number, sourceFile: ts.SourceFile): SourceLocation { const position = sourceFile.getLineAndCharacterOfPosition(positionIndex);
return { filePath: normalizePath(sourceFile.fileName), line: position.line + 1, column: position.character + 1, };}
function getCachedLocation( context: ReferenceCollectionContext, positionIndex: number, sourceFile: ts.SourceFile,): SourceLocation { const filePath = normalizePath(sourceFile.fileName); let fileCache = context.locationCache.get(filePath);
if (!fileCache) { fileCache = new Map(); context.locationCache.set(filePath, fileCache); }
let location = fileCache.get(positionIndex);
if (!location) { location = getLocation(positionIndex, sourceFile); fileCache.set(positionIndex, location); }
return location;}
function getCachedNodeAtPosition( context: ReferenceCollectionContext, sourceFile: ts.SourceFile, position: number,): ts.Node | undefined { const filePath = normalizePath(sourceFile.fileName); let fileCache = context.nodeCache.get(filePath);
if (!fileCache) { fileCache = new Map(); context.nodeCache.set(filePath, fileCache); }
if (!fileCache.has(position)) { fileCache.set(position, findNodeAtPosition(sourceFile, position)); }
return fileCache.get(position);}
function createLanguageService(program: ts.Program): ts.LanguageService { const sourceFiles = new Map( program .getSourceFiles() .filter((sourceFile) => !sourceFile.isDeclarationFile) .map((sourceFile) => [normalizePath(sourceFile.fileName), sourceFile.text]), ); const compilerOptions = program.getCompilerOptions();
return ts.createLanguageService({ getScriptFileNames: () => [...sourceFiles.keys()], getScriptVersion: () => "0", getScriptSnapshot: (fileName) => { const text = sourceFiles.get(normalizePath(fileName)) ?? ts.sys.readFile(fileName);
return text === undefined ? undefined : ts.ScriptSnapshot.fromString(text); }, getCurrentDirectory: () => process.cwd(), getCompilationSettings: () => compilerOptions, getDefaultLibFileName: (options) => ts.getDefaultLibFilePath(options), fileExists: ts.sys.fileExists, readFile: ts.sys.readFile, readDirectory: ts.sys.readDirectory, });}
function getDeclarationNameNode(declaration: ts.Declaration): ts.Node | undefined { if ( (ts.isFunctionDeclaration(declaration) || ts.isClassDeclaration(declaration) || ts.isInterfaceDeclaration(declaration) || ts.isTypeAliasDeclaration(declaration) || ts.isEnumDeclaration(declaration) || ts.isModuleDeclaration(declaration) || ts.isMethodDeclaration(declaration) || ts.isMethodSignature(declaration) || ts.isPropertyDeclaration(declaration) || ts.isPropertySignature(declaration) || ts.isGetAccessorDeclaration(declaration) || ts.isSetAccessorDeclaration(declaration)) && declaration.name ) { return declaration.name; }
if (ts.isVariableDeclaration(declaration)) { return declaration.name; }
if (ts.isExportSpecifier(declaration)) { return declaration.name; }
if (ts.isImportSpecifier(declaration)) { return declaration.name; }
if (ts.isImportClause(declaration) && declaration.name) { return declaration.name; }
return undefined;}
function findNodeAtPosition(sourceFile: ts.SourceFile, position: number): ts.Node | undefined { let best: ts.Node | undefined;
function visit(node: ts.Node): void { const start = node.getStart(sourceFile); const end = node.getEnd();
if (position < start || position >= end) { return; }
if (!best || node.getWidth(sourceFile) <= best.getWidth(sourceFile)) { best = node; }
ts.forEachChild(node, visit); }
visit(sourceFile);
return best;}
export function sortReferences(references: ReferenceRecord[]): ReferenceRecord[] { return references.sort((left, right) => { const file = left.location.filePath.localeCompare(right.location.filePath); if (file !== 0) return file;
const line = left.location.line - right.location.line; if (line !== 0) return line;
const column = left.location.column - right.location.column; if (column !== 0) return column;
return referenceKindOrder(left.kind) - referenceKindOrder(right.kind); });}
function referenceKindOrder(kind: ReferenceKind): number { const order: ReferenceKind[] = [ "import", "re-export", "construct", "call", "write", "read", "type", "jsx", "unknown", ];
return order.indexOf(kind);}