Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "code-inventory",
"version": "0.3.2",
"version": "0.3.3",
"license": "MIT",
"type": "module",
"description": "Static code inventory for JavaScript and TypeScript. Find symbol usages and trace paths from entry points.",
Expand Down
34 changes: 31 additions & 3 deletions src/compiler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -465,11 +465,39 @@ function analyze(
});
}

function isCommonJsRequire(expression: ts.Expression): boolean {
if (!ts.isIdentifier(expression) || expression.text !== 'require') return false;
const binding = checker.getSymbolAtLocation(expression);
return (
!binding?.declarations?.length ||
binding.declarations.every(
(decl) =>
decl.getSourceFile().isDeclarationFile &&
ts.isVariableDeclaration(decl) &&
!!decl.parent.parent.parent &&
(ts.isSourceFile(decl.parent.parent.parent) ||
(ts.isModuleBlock(decl.parent.parent.parent) &&
!!(decl.parent.parent.parent.parent.flags & ts.NodeFlags.GlobalAugmentation))),
)
);
}

function visit(node: ts.Node, callerId: string | null, callTargetNode?: ts.Node): void {
const declaration = byNode.get(node);
if (declaration) callerId = declaration.id;
if (ts.isImportDeclaration(node))
addModule(node, node.moduleSpecifier, 'import', callerId, node.importClause?.isTypeOnly ?? false);
if (ts.isImportDeclaration(node)) {
const clause = node.importClause;
const bindings = clause?.namedBindings;
const erased =
clause?.isTypeOnly ||
(!options.verbatimModuleSyntax &&
!clause?.name &&
bindings &&
ts.isNamedImports(bindings) &&
bindings.elements.length > 0 &&
bindings.elements.every((item) => item.isTypeOnly));
addModule(node, node.moduleSpecifier, 'import', callerId, Boolean(erased));
}
if (ts.isExportDeclaration(node) && node.moduleSpecifier)
addModule(node, node.moduleSpecifier, 'export', callerId, node.isTypeOnly);
if (ts.isImportEqualsDeclaration(node) && ts.isExternalModuleReference(node.moduleReference)) {
Expand All @@ -479,7 +507,7 @@ function analyze(
const expression = unwrap(node.expression);
if (expression.kind === ts.SyntaxKind.ImportKeyword)
addModule(node, node.arguments?.[0], 'dynamic-import', callerId);
else if (ts.isIdentifier(expression) && expression.text === 'require' && !resolveExpression(expression)) {
else if (isCommonJsRequire(expression)) {
addModule(node, node.arguments?.[0], 'require', callerId);
} else {
const target = resolveExpression(expression);
Expand Down
46 changes: 46 additions & 0 deletions test/module-edges.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
import { mkdtempSync, writeFileSync, rmSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { expect, it, onTestFinished } from 'vitest';
import { reachability, scan } from '../src/index.ts';

function fixture(files: Record<string, string>) {
const root = mkdtempSync(join(tmpdir(), 'inventory-edges-'));
onTestFinished(() => rmSync(root, { recursive: true, force: true }));
for (const [file, content] of Object.entries(files)) writeFileSync(join(root, file), content);
return root;
}

it('distinguishes a CommonJS loader from parameter and import bindings named require', () => {
const root = fixture({
'settings.cjs': 'exports.ready = true;',
'loader.cjs': "require('./settings.cjs');",
'callback.ts': 'export function custom(name: string) { return name; }',
'shadow.ts': "export function call(require: (name: string) => void) { require('./settings.cjs'); }",
'alias.ts': "import { custom as require } from './callback'; require('./settings.cjs');",
});
const inventory = scan(root);
expect(inventory.modules.filter((edge) => edge.kind === 'require').map((edge) => edge.location.file)).toEqual([
'loader.cjs',
]);
});

it.each([false, true])('follows inline type imports according to verbatimModuleSyntax=%s', (verbatimModuleSyntax) => {
const root = fixture({
'tsconfig.json': JSON.stringify({
compilerOptions: { module: 'esnext', moduleResolution: 'bundler', verbatimModuleSyntax },
}),
'settings.ts': 'export type Options = {}; export const value = 1;',
'entry.ts': "import { type Options } from './settings'; export type Config = Options;",
'whole.ts': "import type { Options } from './settings'; export type Config = Options;",
'mixed.ts': "import { type Options, value } from './settings'; export const pair: [Options, number] = [{}, value];",
'side.ts': "import './settings';",
});
const inventory = scan(root);
const loadsSettings = (entry: string) =>
reachability(inventory, [entry]).reached.some((node) => node.id === 'module:settings.ts');
expect(loadsSettings('entry.ts')).toBe(verbatimModuleSyntax);
expect(loadsSettings('whole.ts')).toBe(false);
expect(loadsSettings('mixed.ts')).toBe(true);
expect(loadsSettings('side.ts')).toBe(true);
});