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: 4 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,10 @@ The lines that follow identify each reference by file, line, column, kind, and s
| How do I save the full snapshot? | `node dist/cli.js test/fixtures/basic --format json --output inventory.json` |
| How do I scan one TypeScript project? | `node dist/cli.js . --project tsconfig.build.json` |

For convention-based entry points, use a quoted pattern such as `--entry-glob 'src/routes/**/+page.ts'`. Combine it with `--package-entries` to include a package’s public entry files.

To review what an external caller can reach by invoking a handler, use `--entry-symbol GET`. If several declarations share that name, the CLI lists their snapshot IDs. File entries trace module initialization. Combining both options includes both starting points.

Repeat `--entry` to combine entry points or `--project` to select multiple configs. Output files must be new. Use `--strict` when a partial result should set exit code 2. The CLI still produces the report.

Check diagnostics before interpreting counts. Call sites measure source occurrences. Runtime dispatch, callbacks, and external consumers can introduce paths the scanner cannot see. Review declarations with no known path before considering removal.
Expand Down
28 changes: 23 additions & 5 deletions docs/reference.html
Original file line number Diff line number Diff line change
Expand Up @@ -60,11 +60,29 @@ <h2 id="cli">CLI options</h2>
<dd>Query one declaration by exact unique name or snapshot ID. Supports summary and JSON.</dd>
<dt><code>--package-entries</code></dt>
<dd>
Trace module initialization from the root package's explicit exports (or main) and bin targets. All runtime
Trace module initialization from the root package's exports (or main) and bin targets. All runtime
conditions and array alternatives contribute roots. Type-only branches, declaration files and JSON targets
are skipped. Combine with --entry for framework or implicit roots. For compiled packages select the emitting
--project so the compiler can map outputs to analyzed inputs. Wildcards and unmapped outputs require
explicit source entries instead. External invocations of exported functions are outside this trace.
--project so the compiler can map outputs to analyzed inputs. Subpath patterns such as
<code>"./features/*": "./dist/*.js"</code> expand against analyzed files and their predicted JavaScript
outputs. An exact subpath or a more specific pattern takes precedence, including private paths blocked with
<code>null</code>. If a target pattern has no matching source or predicted output, select its source
explicitly with <code>--entry</code>. External invocations of exported functions are outside this trace.
</dd>
<dt><code>--entry-symbol name-or-id</code></dt>
<dd>
Assume a function, method or constructor is invoked and trace calls from its body. For example, select
<code>GET</code> when reviewing a route handler. A repeated name requires the snapshot ID shown in the
ambiguity message. Repeat the option for multiple invocations. Add file entries to include module
initialization. The library accepts <code>reachability(inventory, [], { entrySymbols: ['GET'] })</code>. The
report records these assumptions as snapshot IDs in the optional <code>entrySymbols</code> array.
</dd>
<dt><code>--entry-glob glob</code></dt>
<dd>
Trace analyzed files matching a quoted, root-relative pattern such as <code>'src/routes/**/+page.ts'</code>.
Repeat the option or combine it with --entry and --package-entries. Each pattern must match an analyzed
file. Library callers can pass
<code>reachability(inventory, [], { entryGlobs: ['src/routes/**/+page.ts'] })</code>.
</dd>
<dt><code>--entry source-file</code></dt>
<dd>
Expand Down Expand Up @@ -162,8 +180,8 @@ <h2>Consuming the 0.x API</h2>
directory synchronously. The other queries operate on its inventory or reachability report, except
packageEntries(directory, inventory), which also reads the matching manifest and build configuration. Pass its
result to reachability. entryPath(report, symbolId) returns the ordered nodes of one shortest path, including
the module root and target, or null for an unreached ID. Select the ID with usages. Each non-root node carries
the edge kind and source location. summary, usageText and markdown render display text.
the selected file or invocation root and target, or null for an unreached ID. Select the ID with usages. Each
non-root node carries the edge kind and source location. summary, usageText and markdown render display text.
</p>
<p>
The <a href="report-schema.json">JSON Schema</a> describes all three CLI report shapes. For persisted data
Expand Down
4 changes: 4 additions & 0 deletions docs/report-schema.json
Original file line number Diff line number Diff line change
Expand Up @@ -442,6 +442,10 @@
"type": "string"
}
},
"entrySymbols": {
"type": "array",
"items": { "type": "string" }
},
"reached": {
"type": "array",
"items": {
Expand Down
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.1.0",
"version": "0.2.0",
"license": "MIT",
"type": "module",
"description": "Static code inventory for JavaScript and TypeScript. Find symbol usages and trace paths from entry points.",
Expand Down
15 changes: 11 additions & 4 deletions src/cli.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,8 @@ function main(): void {
allowPositionals: true,
options: {
'package-entries': { type: 'boolean' },
'entry-glob': { type: 'string', multiple: true },
'entry-symbol': { type: 'string', multiple: true },
entry: { type: 'string', multiple: true },
project: { type: 'string', multiple: true },
exclude: { type: 'string', multiple: true },
Expand All @@ -26,23 +28,28 @@ function main(): void {
});
if (values.help) {
process.stdout.write(
'Usage: code-inventory [directory] [--entry source-file] [--package-entries] [--project config] [--exclude glob] [--test glob] [--tooling glob] [--production glob] [--format summary|json|markdown] [--symbol name-or-id] [--output new-file] [--strict]\n',
'Usage: code-inventory [directory] [--entry source-file] [--entry-glob glob] [--entry-symbol name-or-id] [--package-entries] [--project config] [--exclude glob] [--test glob] [--tooling glob] [--production glob] [--format summary|json|markdown] [--symbol name-or-id] [--output new-file] [--strict]\n',
);
return;
}
if (positionals.length > 1) throw new Error('Provide at most one directory.');
if (!['summary', 'json', 'markdown'].includes(values.format)) throw new Error(`Unknown format: ${values.format}`);
const directory = positionals[0] ?? '.';
if (values.symbol && (values.entry || values['package-entries']))
throw new Error('Select either --entry or --symbol.');
const entryQuery = values.entry || values['entry-glob'] || values['entry-symbol'] || values['package-entries'];
if (values.symbol && entryQuery) throw new Error('Select either entry points or --symbol.');
if (values.symbol && values.format === 'markdown') throw new Error('--symbol supports summary and json formats.');
const inventory = scan(directory, {
projects: values.project ?? [],
exclude: values.exclude ?? [],
scopes: { test: values.test ?? [], tooling: values.tooling ?? [], production: values.production ?? [] },
});
const entries = [...(values.entry ?? []), ...(values['package-entries'] ? packageEntries(directory, inventory) : [])];
const paths = entries.length ? reachability(inventory, entries) : null;
const paths = entryQuery
? reachability(inventory, entries, {
entryGlobs: values['entry-glob'] ?? [],
entrySymbols: values['entry-symbol'] ?? [],
})
: null;
const selected = values.symbol ? usages(inventory, values.symbol) : null;
const output =
values.format === 'json'
Expand Down
3 changes: 2 additions & 1 deletion src/compiler.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import ts from 'typescript';
import { isBuiltin } from 'node:module';
import manifest from '../package.json' with { type: 'json' };
import { realpathSync } from 'node:fs';
import { resolve } from 'node:path';
import { loadProjects, projectOwners, fileRules } from './projects.ts';
Expand Down Expand Up @@ -32,7 +33,7 @@ export function scan(rootDirectory: string, settings: ScanOptions = {}): Invento
const analyzed = new Set<string>();
const inventory: Inventory = {
schemaVersion: 1,
analyzer: { name: 'code-inventory', version: '0.1.0', compilerVersion: ts.version },
analyzer: { name: 'code-inventory', version: manifest.version, compilerVersion: ts.version },
snapshotId: '',
config: {
path: configPath ? portablePath(root, configPath) : null,
Expand Down
2 changes: 1 addition & 1 deletion src/model.ts
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@ export interface SourceFile {
/** A portable deterministic snapshot; source text and absolute root paths are omitted. */
export interface Inventory {
schemaVersion: 1;
analyzer: { name: 'code-inventory'; version: '0.1.0'; compilerVersion: string };
analyzer: { name: 'code-inventory'; version: string; compilerVersion: string };
snapshotId: string;
config: {
path: string | null;
Expand Down
83 changes: 70 additions & 13 deletions src/package-entries.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,41 +5,94 @@ import { portablePath } from './discovery.ts';
import { readFileSync } from 'node:fs';
import { resolve, posix } from 'node:path';

/** Node substitutes the same nonempty subpath for every star in a target, including across directories. */
function capture(parts: string[], path: string): string | null {
if (!path.startsWith(parts[0]!)) return null;
const literals = parts.reduce((length, part) => length + part.length, 0);
const length = (path.length - literals) / (parts.length - 1);
if (length < 1 || !Number.isInteger(length)) return null;
const value = path.slice(parts[0]!.length, parts[0]!.length + length);
return parts.join(value) === path ? value : null;
}

type ExportPattern = { key: string; target: string };

function* expandPatterns(patterns: ExportPattern[], subpaths: string[], candidates: Set<string>) {
const exact = new Set(subpaths.filter((key) => !key.includes('*')));
// Node selects the longest prefix first, then the longest complete pattern.
const wildcardKeys = subpaths
.filter((key) => key.includes('*'))
.sort((a, b) => b.indexOf('*') - a.indexOf('*') || b.length - a.length);
const keys = wildcardKeys.map((key) => ({ key, parts: key.split('*') }));
if (keys.some(({ parts }) => parts.length !== 2)) throw new Error('An export subpath pattern must contain one star.');
for (const { key, target } of patterns) {
const parts = target.split('*');
let matched = false;
for (const path of candidates) {
const value = capture(parts, path);
if (value === null) continue;
matched = true;
const subpath = key.replaceAll('*', () => value);
if (exact.has(subpath)) continue;
const winner = keys.find(({ parts }) => capture(parts, subpath) !== null);
if (winner?.key === key) yield path;
}
if (!matched)
throw new Error(
'No analyzed source or compiler output matches package target: ' +
target +
'. Select the build config with --project or use --entry.',
);
}
}

/** Collect explicit runtime entry files from one package, across its declared conditions. */
export function packageEntries(directory: string, inventory: Inventory): string[] {
const manifest = JSON.parse(readFileSync(resolve(directory, 'package.json'), 'utf8'));
const files = new Set<string>();
function add(target: unknown): void {
const patterns: ExportPattern[] = [];
const exports = manifest.exports;
const subpaths =
exports && typeof exports === 'object' && Object.keys(exports).some((key) => key.startsWith('.'))
? Object.keys(exports)
: [];
function add(target: unknown, key = ''): void {
if (
typeof target !== 'string' ||
!target ||
target.includes('*') ||
(target.includes('*') && !key.includes('*')) ||
posix.isAbsolute(target) ||
target.includes('\\') ||
target.split('/').includes('..')
) {
throw new Error('Package entry requires an explicit local source path. Use --entry to select it.');
}
if (/\.json$/.test(target)) return;
if (!/\.d\.[cm]?ts$/.test(target)) files.add(posix.normalize(target));
if (/\.json$|\.d\.[cm]?ts$/.test(target)) return;
const path = posix.normalize(target);
if (path.includes('*')) patterns.push({ key, target: path });
else files.add(path);
}
function collect(target: unknown): void {
function collect(target: unknown, key = ''): void {
if (target === null) return;
if (Array.isArray(target)) {
for (const item of target) collect(item);
for (const item of target) collect(item, key);
} else if (typeof target === 'object') {
for (const [condition, value] of Object.entries(target)) {
if (condition !== 'types' && !condition.startsWith('types@')) collect(value);
if (condition !== 'types' && !condition.startsWith('types@')) collect(value, key);
}
} else add(target);
} else add(target, key);
}
if ('exports' in manifest) collect(manifest.exports);
if (subpaths.length) {
for (const key of subpaths) collect(exports[key], key);
} else if ('exports' in manifest) collect(exports);
else if ('main' in manifest) add(manifest.main);
if (typeof manifest.bin === 'string') add(manifest.bin);
else if (manifest.bin) Object.values(manifest.bin).forEach(add);
if (!files.size) throw new Error('No explicit package entries. Select a source file with --entry.');
else if (manifest.bin) Object.values(manifest.bin).forEach((target) => add(target));
const analyzed = new Set(inventory.files.filter((file) => file.status === 'analyzed').map((file) => file.path));
if ([...files].every((file) => analyzed.has(file))) return [...files].sort();
if (!patterns.length) {
if (!files.size) throw new Error('No explicit package entries. Select a source file with --entry.');
if ([...files].every((file) => analyzed.has(file))) return [...files].sort();
}
const sources = new Map<string, Set<string>>();
for (const project of loadProjects(directory, inventory.config.entries).ordered) {
if (!project.path || project.options.noEmit || project.options.emitDeclarationOnly) continue;
Expand All @@ -49,13 +102,17 @@ export function packageEntries(directory: string, inventory: Inventory): string[
if (!analyzed.has(source)) continue;
for (const output of ts.getOutputFileNames(config, input, !ts.sys.useCaseSensitiveFileNames)) {
const path = portablePath(directory, output);
if (!files.has(path)) continue;
if (!files.has(path) && !(patterns.length && /\.(?:[cm]?js|jsx)$/.test(path))) continue;
const candidates = sources.get(path) ?? new Set<string>();
candidates.add(source);
sources.set(path, candidates);
}
}
}
if (patterns.length) {
for (const file of expandPatterns(patterns, subpaths, new Set([...analyzed, ...sources.keys()]))) files.add(file);
if (!files.size) throw new Error('No analyzed files are exposed by these package entries.');
}
const roots = new Set<string>();
for (const file of files) {
if (analyzed.has(file)) roots.add(file);
Expand Down
10 changes: 7 additions & 3 deletions src/query.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import type { Finding, Inventory, Usage } from './model.ts';
import type { CodeSymbol, Finding, Inventory, Usage } from './model.ts';

/** Select by exact snapshot ID or by unambiguous declaration name. */
export function usages(inventory: Inventory, selector: string): Usage {
export function selectSymbol(inventory: Inventory, selector: string): CodeSymbol {
const matches = inventory.symbols.filter((symbol) => symbol.id === selector || symbol.name === selector);
if (matches.length !== 1) {
throw new Error(
Expand All @@ -10,7 +10,11 @@ export function usages(inventory: Inventory, selector: string): Usage {
: `Ambiguous symbol ${selector}; use one of these IDs:\n${matches.map((symbol) => symbol.id).join('\n')}`,
);
}
const symbol = matches[0]!;
return matches[0]!;
}

export function usages(inventory: Inventory, selector: string): Usage {
const symbol = selectSymbol(inventory, selector);
const references = inventory.references.filter((reference) => reference.targetId === symbol.id);
const calls = references.filter((reference) => reference.kind === 'call' || reference.kind === 'construct');
return {
Expand Down
33 changes: 28 additions & 5 deletions src/reachability.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { posix } from 'node:path';
import { selectSymbol } from './query.ts';
import type { CodeSymbol, Inventory, Location, ModuleReference } from './model.ts';

type Step = {
Expand All @@ -10,6 +11,7 @@ type Step = {
export interface Reachability {
snapshotId: string;
entries: string[];
entrySymbols?: string[];
completeness: Inventory['completeness'];
diagnostics: Inventory['diagnostics'];
/** One shortest-path predecessor per reached module or declaration. Roots have no predecessor. */
Expand All @@ -20,11 +22,31 @@ export interface Reachability {

const moduleId = (file: string) => 'module:' + file;

/** Trace resolved direct calls, construction and literal module edges from explicit source files. */
export function reachability(inventory: Inventory, files: readonly string[]): Reachability {
const entries = [...new Set(files.map((file) => posix.normalize(file)))].sort();
if (!entries.length) throw new Error('Select at least one entry file.');
/** Trace resolved direct calls, construction and literal module edges from selected source files. */
export function reachability(
inventory: Inventory,
files: readonly string[],
options: { entryGlobs?: readonly string[]; entrySymbols?: readonly string[] } = {},
): Reachability {
const selected = new Set(files.map((file) => posix.normalize(file)));
const analyzed = new Set(inventory.files.filter((file) => file.status === 'analyzed').map((file) => file.path));
for (const glob of options.entryGlobs ?? []) {
const pattern = glob.replace(/^\.\//, '');
const matches = [...analyzed].filter((file) => posix.matchesGlob(file, pattern));
if (!matches.length) throw new Error('No analyzed entry files match: ' + glob);
for (const file of matches) selected.add(file);
}
const entries = [...selected].sort();
const invoked = new Set<string>();
for (const selector of options.entrySymbols ?? []) {
const symbol = selectSymbol(inventory, selector);
if (!['function', 'method', 'constructor'].includes(symbol.kind)) {
throw new Error('Entry symbol must be a function, method or constructor: ' + selector);
}
invoked.add(symbol.id);
}
const entrySymbols = [...invoked].sort();
if (!entries.length && !entrySymbols.length) throw new Error('Select at least one entry file or symbol.');
for (const file of entries) {
if (!analyzed.has(file)) throw new Error('Entry file was not analyzed: ' + file);
}
Expand Down Expand Up @@ -66,7 +88,7 @@ export function reachability(inventory: Inventory, files: readonly string[]): Re
});
}

const queue = entries.map(moduleId);
const queue = [...entries.map(moduleId), ...entrySymbols];
const paths = new Map<string, Step | null>(queue.map((id) => [id, null]));
for (let index = 0; index < queue.length; index++) {
for (const { to, via } of edges.get(queue[index]!) ?? []) {
Expand All @@ -78,6 +100,7 @@ export function reachability(inventory: Inventory, files: readonly string[]): Re
return {
snapshotId: inventory.snapshotId,
entries,
...(entrySymbols.length ? { entrySymbols } : {}),
completeness: inventory.completeness,
diagnostics: inventory.diagnostics,
reached: [...paths].map(([id, via]) => ({ id, via })),
Expand Down
Loading