60 lines
2 KiB
TypeScript
60 lines
2 KiB
TypeScript
import { readFileSync } from 'node:fs';
|
|
import ts from 'typescript';
|
|
|
|
/** Runtime edges only: type imports and type re-exports cannot initialize a module. */
|
|
export function runtimeImports(file: string, sourceText = readFileSync(file, 'utf8')): string[] {
|
|
const source = ts.createSourceFile(file, sourceText, ts.ScriptTarget.Latest, true);
|
|
const imports = new Set<string>();
|
|
function visit(node: ts.Node) {
|
|
if (ts.isImportDeclaration(node) && ts.isStringLiteral(node.moduleSpecifier)) {
|
|
const clause = node.importClause;
|
|
const bindings = clause?.namedBindings;
|
|
const typesOnly =
|
|
clause?.isTypeOnly ||
|
|
(clause &&
|
|
!clause.name &&
|
|
bindings &&
|
|
ts.isNamedImports(bindings) &&
|
|
bindings.elements.length > 0 &&
|
|
bindings.elements.every(item => item.isTypeOnly));
|
|
if (!typesOnly) imports.add(node.moduleSpecifier.text);
|
|
}
|
|
if (
|
|
ts.isExportDeclaration(node) &&
|
|
!node.isTypeOnly &&
|
|
node.moduleSpecifier &&
|
|
ts.isStringLiteral(node.moduleSpecifier)
|
|
) {
|
|
const clause = node.exportClause;
|
|
if (
|
|
!clause ||
|
|
!ts.isNamedExports(clause) ||
|
|
!clause.elements.length ||
|
|
clause.elements.some(item => !item.isTypeOnly)
|
|
) {
|
|
imports.add(node.moduleSpecifier.text);
|
|
}
|
|
}
|
|
if (
|
|
ts.isCallExpression(node) &&
|
|
(node.expression.kind === ts.SyntaxKind.ImportKeyword ||
|
|
(ts.isIdentifier(node.expression) && node.expression.text === 'require')) &&
|
|
node.arguments[0] &&
|
|
ts.isStringLiteral(node.arguments[0])
|
|
) {
|
|
imports.add(node.arguments[0].text);
|
|
}
|
|
if (
|
|
ts.isImportEqualsDeclaration(node) &&
|
|
!node.isTypeOnly &&
|
|
ts.isExternalModuleReference(node.moduleReference) &&
|
|
node.moduleReference.expression &&
|
|
ts.isStringLiteral(node.moduleReference.expression)
|
|
) {
|
|
imports.add(node.moduleReference.expression.text);
|
|
}
|
|
ts.forEachChild(node, visit);
|
|
}
|
|
visit(source);
|
|
return [...imports];
|
|
}
|