code-inventory 0.2.1 → 0.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -37,12 +37,18 @@ The lines that follow identify each reference by file, line, column, kind, and s
37
37
  | How do I save the full snapshot? | `node dist/cli.js test/fixtures/basic --format json --output inventory.json` |
38
38
  | How do I scan one TypeScript project? | `node dist/cli.js . --project tsconfig.build.json` |
39
39
 
40
+ In a Git checkout, run `npx code-inventory . --changed-since main` to see the declarations touched by tracked
41
+ source changes, their exports, and references grouped by caller or test file. Deleted files and removed base lines
42
+ appear separately. The query uses the current checkout, including staged and unstaged edits.
43
+
40
44
  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.
41
45
 
42
46
  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.
43
47
 
44
48
  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.
45
49
 
50
+ For scripts that save JSON, see the [0.x report compatibility rules](docs/reference.html#compatibility) and [CLI exit codes](docs/reference.html#exit-codes).
51
+
46
52
  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.
47
53
 
48
54
  ## Use the library
@@ -0,0 +1,3 @@
1
+ import type { Inventory } from './model.ts';
2
+ /** Compare a tree to the tracked working tree, resolving references only in the current inventory. */
3
+ export declare function changeImpactText(directory: string, base: string, inventory: Inventory): string;
@@ -0,0 +1,149 @@
1
+ import { execFileSync } from 'node:child_process';
2
+ import { resolve } from 'node:path';
3
+ import ts from 'typescript';
4
+ import { sourceExtension } from "./discovery.js";
5
+ function git(directory, ...args) {
6
+ return execFileSync('git', ['--literal-pathspecs', ...args], {
7
+ cwd: directory,
8
+ encoding: 'utf8',
9
+ stdio: ['ignore', 'pipe', 'pipe'],
10
+ timeout: 30_000,
11
+ maxBuffer: 64 * 1024 * 1024,
12
+ });
13
+ }
14
+ function range(first, last) {
15
+ return first === last ? String(first) : `${first}-${last}`;
16
+ }
17
+ /** Check the part of a changed line belonging to the parent between nested declaration spans. */
18
+ function ownsText(source, parent, children, start, end) {
19
+ let cursor = Math.max(start, parent.location.start);
20
+ const limit = Math.min(end, parent.location.end);
21
+ for (const child of children) {
22
+ if (source.slice(cursor, Math.min(limit, child.location.start)).trim())
23
+ return true;
24
+ cursor = Math.max(cursor, child.location.end);
25
+ }
26
+ return Boolean(source.slice(cursor, limit).trim());
27
+ }
28
+ /** Intersect Git's LF-delimited lines with the compiler's end-exclusive UTF-16 spans. */
29
+ function mapHunks(patch, file, source, declarations, changed, notes) {
30
+ const starts = [0];
31
+ for (const newline of source.matchAll(/\n/g))
32
+ starts.push(newline.index + 1);
33
+ declarations.sort((a, b) => a.location.start - b.location.start);
34
+ let next = 0;
35
+ let active = [];
36
+ let hunks = 0;
37
+ for (const hunk of patch.matchAll(/(?:^|\n)@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@/g)) {
38
+ hunks++;
39
+ const oldStart = Number(hunk[1]);
40
+ const oldCount = Number(hunk[2] ?? 1);
41
+ const first = Number(hunk[3]);
42
+ const count = Number(hunk[4] ?? 1);
43
+ if (oldCount)
44
+ notes.push(`Removed base lines: ${file}:${range(oldStart, oldStart + oldCount - 1)}`);
45
+ let outsideStart;
46
+ // A pure deletion has a zero-width position between two surviving lines.
47
+ for (let line = first; line < first + Math.max(1, count); line++) {
48
+ const start = starts[count ? line - 1 : line] ?? source.length;
49
+ const end = count ? (starts[line] ?? source.length) : start;
50
+ while (next < declarations.length && declarations[next].location.start < end) {
51
+ active.push(declarations[next++]);
52
+ }
53
+ active = active.filter((symbol) => symbol.location.end > start);
54
+ const children = groupBy(active, (symbol) => symbol.containerId);
55
+ for (const symbol of active) {
56
+ const nested = children.get(symbol.id);
57
+ if (!nested || ownsText(source, symbol, nested, start, end))
58
+ changed.add(symbol);
59
+ }
60
+ if (count && !active.length)
61
+ outsideStart ??= line;
62
+ if (outsideStart !== undefined && (active.length || line === first + count - 1)) {
63
+ notes.push(`Outside a declaration: ${file}:${range(outsideStart, active.length ? line - 1 : line)}`);
64
+ outsideStart = undefined;
65
+ }
66
+ }
67
+ }
68
+ if (!hunks)
69
+ notes.push(`No text hunks: ${file}`);
70
+ }
71
+ function groupBy(items, keyOf) {
72
+ const groups = new Map();
73
+ for (const item of items) {
74
+ const key = keyOf(item);
75
+ const group = groups.get(key);
76
+ if (group)
77
+ group.push(item);
78
+ else
79
+ groups.set(key, [item]);
80
+ }
81
+ return groups;
82
+ }
83
+ function referenceGroups(references, byId) {
84
+ const groups = new Map();
85
+ for (const ref of references) {
86
+ const { file, line, column } = ref.location;
87
+ const caller = ref.callerId ? byId.get(ref.callerId) : undefined;
88
+ const container = caller?.containerId ? byId.get(caller.containerId) : undefined;
89
+ const label = ref.scope === 'test' ? file : caller ? [container?.name, caller.name].filter(Boolean).join('.') : file;
90
+ const key = ref.scope === 'test' ? file : (ref.callerId ?? file);
91
+ let group = groups.get(key);
92
+ if (!group) {
93
+ group = { label: `[${ref.scope}] ${label}`, sites: [] };
94
+ groups.set(key, group);
95
+ }
96
+ group.sites.push(`${ref.kind} ${file}:${line}:${column}`);
97
+ }
98
+ return Array.from(groups.values(), ({ label, sites }) => ` ${label}: ${sites.join(', ')}`);
99
+ }
100
+ /** Compare a tree to the tracked working tree, resolving references only in the current inventory. */
101
+ export function changeImpactText(directory, base, inventory) {
102
+ if (!base)
103
+ throw new Error('Provide a Git revision for --changed-since.');
104
+ const tree = git(directory, 'rev-parse', '--verify', '--end-of-options', base + '^{tree}').trim();
105
+ const diff = ['diff', '--relative', '--no-ext-diff', '--no-textconv', '--no-renames', '--no-color'];
106
+ const fields = git(directory, ...diff, '--name-status', '-z', tree, '--', '.').split('\0');
107
+ const files = new Map(inventory.files.map((file) => [file.path, file]));
108
+ const symbolsByFile = groupBy(inventory.symbols, (symbol) => symbol.location.file);
109
+ const changed = new Set();
110
+ const notes = [];
111
+ for (let i = 0; i + 1 < fields.length; i += 2) {
112
+ const status = fields[i];
113
+ const path = fields[i + 1];
114
+ if (!sourceExtension.test(path))
115
+ continue;
116
+ if (status === 'D') {
117
+ notes.push(`Deleted file: ${path}`);
118
+ continue;
119
+ }
120
+ const file = files.get(path);
121
+ if (file?.status !== 'analyzed') {
122
+ notes.push(`Outside scan: ${path} (${file?.reason ?? 'not inventoried'})`);
123
+ continue;
124
+ }
125
+ const patch = git(directory, ...diff, '--unified=0', '--inter-hunk-context=0', tree, '--', path);
126
+ const source = ts.sys.readFile(resolve(directory, path));
127
+ if (source === undefined)
128
+ throw new Error(`Cannot read changed file: ${path}`);
129
+ mapHunks(patch, path, source, symbolsByFile.get(path) ?? [], changed, notes);
130
+ }
131
+ const byId = new Map(inventory.symbols.map((symbol) => [symbol.id, symbol]));
132
+ const byTarget = groupBy(inventory.references, (ref) => ref.targetId);
133
+ const lines = [`Change impact since ${base}`];
134
+ for (const symbol of changed) {
135
+ lines.push('', `${symbol.kind} ${symbol.name} (${symbol.location.file}:${symbol.location.line})`);
136
+ if (symbol.exportedAs.length)
137
+ lines.push(` Exports: ${symbol.exportedAs.join(', ')}`);
138
+ const groups = referenceGroups(byTarget.get(symbol.id) ?? [], byId);
139
+ lines.push(...(groups.length ? groups : [' No references found in this scan.']));
140
+ }
141
+ if (!changed.size && !notes.length)
142
+ lines.push('No tracked source changes.');
143
+ return [
144
+ ...lines,
145
+ ...notes,
146
+ `Analysis: ${inventory.completeness}; ${inventory.diagnostics.length} diagnostics`,
147
+ '',
148
+ ].join('\n');
149
+ }
package/dist/cli.js CHANGED
@@ -2,6 +2,7 @@
2
2
  import { parseArgs } from 'node:util';
3
3
  import { writeFileSync } from 'node:fs';
4
4
  import { packageEntries, reachability, scan, markdown, summary, usages, usageText } from "./index.js";
5
+ import { changeImpactText } from "./change-impact.js";
5
6
  import { reachabilityText } from "./report.js";
6
7
  /** Run a read-only scan; output files must be new paths to avoid overwriting user work. */
7
8
  function main() {
@@ -18,6 +19,7 @@ function main() {
18
19
  tooling: { type: 'string', multiple: true },
19
20
  production: { type: 'string', multiple: true },
20
21
  format: { type: 'string', default: 'summary' },
22
+ 'changed-since': { type: 'string' },
21
23
  symbol: { type: 'string' },
22
24
  output: { type: 'string' },
23
25
  strict: { type: 'boolean', default: false },
@@ -25,7 +27,7 @@ function main() {
25
27
  },
26
28
  });
27
29
  if (values.help) {
28
- process.stdout.write('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');
30
+ process.stdout.write('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] [--changed-since revision] [--output new-file] [--strict]\n');
29
31
  return;
30
32
  }
31
33
  if (positionals.length > 1)
@@ -38,36 +40,49 @@ function main() {
38
40
  throw new Error('Select either entry points or --symbol.');
39
41
  if (values.symbol && values.format === 'markdown')
40
42
  throw new Error('--symbol supports summary and json formats.');
43
+ const base = values['changed-since'];
44
+ if (base !== undefined && (entryQuery || values.symbol !== undefined || values.format !== 'summary'))
45
+ throw new Error('--changed-since is a standalone summary query.');
41
46
  const inventory = scan(directory, {
42
47
  projects: values.project ?? [],
43
48
  exclude: values.exclude ?? [],
44
49
  scopes: { test: values.test ?? [], tooling: values.tooling ?? [], production: values.production ?? [] },
45
50
  });
46
- const entries = [...(values.entry ?? []), ...(values['package-entries'] ? packageEntries(directory, inventory) : [])];
47
- const paths = entryQuery
48
- ? reachability(inventory, entries, {
49
- entryGlobs: values['entry-glob'] ?? [],
50
- entrySymbols: values['entry-symbol'] ?? [],
51
- })
52
- : null;
53
- const selected = values.symbol ? usages(inventory, values.symbol) : null;
54
- const output = values.format === 'json'
55
- ? JSON.stringify(selected
56
- ? {
57
- schemaVersion: inventory.schemaVersion,
58
- snapshotId: inventory.snapshotId,
59
- completeness: inventory.completeness,
60
- diagnostics: inventory.diagnostics,
61
- usage: selected,
62
- }
63
- : (paths ?? inventory), null, 2) + '\n'
64
- : paths
65
- ? reachabilityText(paths, values.format === 'markdown')
66
- : selected
67
- ? usageText(selected) + `Analysis: ${inventory.completeness}; ${inventory.diagnostics.length} diagnostics\n`
68
- : values.format === 'markdown'
69
- ? markdown(inventory)
70
- : summary(inventory);
51
+ let output;
52
+ if (base !== undefined) {
53
+ output = changeImpactText(directory, base, inventory);
54
+ }
55
+ else {
56
+ const entries = [
57
+ ...(values.entry ?? []),
58
+ ...(values['package-entries'] ? packageEntries(directory, inventory) : []),
59
+ ];
60
+ const paths = entryQuery
61
+ ? reachability(inventory, entries, {
62
+ entryGlobs: values['entry-glob'] ?? [],
63
+ entrySymbols: values['entry-symbol'] ?? [],
64
+ })
65
+ : null;
66
+ const selected = values.symbol ? usages(inventory, values.symbol) : null;
67
+ output =
68
+ values.format === 'json'
69
+ ? JSON.stringify(selected
70
+ ? {
71
+ schemaVersion: inventory.schemaVersion,
72
+ snapshotId: inventory.snapshotId,
73
+ completeness: inventory.completeness,
74
+ diagnostics: inventory.diagnostics,
75
+ usage: selected,
76
+ }
77
+ : (paths ?? inventory), null, 2) + '\n'
78
+ : paths
79
+ ? reachabilityText(paths, values.format === 'markdown')
80
+ : selected
81
+ ? usageText(selected) + `Analysis: ${inventory.completeness}; ${inventory.diagnostics.length} diagnostics\n`
82
+ : values.format === 'markdown'
83
+ ? markdown(inventory)
84
+ : summary(inventory);
85
+ }
71
86
  if (values.output)
72
87
  writeFileSync(values.output, output, { flag: 'wx' });
73
88
  else
@@ -1,4 +1,5 @@
1
1
  import type { Scope } from './model.ts';
2
+ export declare const sourceExtension: RegExp;
2
3
  /** Return sorted source paths without following symlinks or traversing build/dependency folders. */
3
4
  export declare function discover(root: string): string[];
4
5
  /** Normalize output paths independently of the host's directory separator. */
package/dist/discovery.js CHANGED
@@ -2,7 +2,7 @@ import { createHash } from 'node:crypto';
2
2
  import { readdirSync, readFileSync } from 'node:fs';
3
3
  import { relative, resolve, sep } from 'node:path';
4
4
  const excludedDirectories = new Set(['node_modules', '.git', 'dist', 'build', 'coverage', '.next', '.nuxt', '.output']);
5
- const sourceExtension = /\.(?:[cm]?[jt]s|[jt]sx)$/;
5
+ export const sourceExtension = /\.(?:[cm]?[jt]s|[jt]sx)$/;
6
6
  /** Return sorted source paths without following symlinks or traversing build/dependency folders. */
7
7
  export function discover(root) {
8
8
  const files = [];
@@ -28,9 +28,11 @@
28
28
  <strong>On this page</strong>
29
29
  <nav aria-label="On this page">
30
30
  <a href="#cli">CLI options</a>
31
+ <a href="#exit-codes">Exit codes</a>
31
32
  <a href="#projects">Project selection</a>
32
33
  <a href="#counts">Counts and findings</a>
33
34
  <a href="#snapshot">JSON snapshot</a>
35
+ <a href="#compatibility">Saved reports and upgrades</a>
34
36
  <a href="#boundaries">Analysis limits</a>
35
37
  </nav>
36
38
  </aside>
@@ -58,6 +60,16 @@
58
60
  </dd>
59
61
  <dt><code>--symbol name-or-id</code></dt>
60
62
  <dd>Query one declaration by exact unique name or snapshot ID. Supports summary and JSON.</dd>
63
+ <dt><code>--changed-since revision</code></dt>
64
+ <dd>
65
+ Compare a local Git revision directly with the tracked working tree under the scan root, including staged
66
+ and unstaged changes. Untracked files enter the diff once staged. The summary groups current references by
67
+ caller or test file and shows module exports, including re-exports. Changed lines select overlapping
68
+ declarations, including an enclosing declaration when the line also contains its own code. Reads include
69
+ callback arguments. Test references identify source sites and do not establish runtime coverage. Removed
70
+ lines use base coordinates. Deleted files and the old side of renames have no current declaration to query.
71
+ Use this option on its own with summary output.
72
+ </dd>
61
73
  <dt><code>--package-entries</code></dt>
62
74
  <dd>
63
75
  Trace module initialization from the root package's exports (or main) and bin targets. All runtime
@@ -94,13 +106,28 @@
94
106
  <dt><code>--output new-file</code></dt>
95
107
  <dd>Write the result to a new file. An existing path produces an error.</dd>
96
108
  <dt><code>--strict</code></dt>
97
- <dd>
98
- Write the report and exit with code 2 for a partial scan. A successful scan otherwise exits with 0. Invalid
99
- arguments and filesystem errors exit with 1.
100
- </dd>
109
+ <dd>Signal a partial scan after writing its report. See <a href="#exit-codes">exit codes</a>.</dd>
101
110
  <dt><code>-h</code>, <code>--help</code></dt>
102
111
  <dd>Print usage and exit.</dd>
103
112
  </dl>
113
+ <h2 id="exit-codes">Exit codes</h2>
114
+ <dl>
115
+ <dt><code>0</code> · Success</dt>
116
+ <dd>
117
+ The CLI printed help or produced the requested report. Without <code>--strict</code>, both complete and
118
+ partial scans succeed. Check the JSON <code>completeness</code> field when the distinction matters.
119
+ </dd>
120
+ <dt><code>1</code> · Command failed</dt>
121
+ <dd>
122
+ An invalid option, failed query, or read or write error sends an explanation to stderr. Stop before
123
+ consuming output. In particular, an existing <code>--output</code> file may be from an earlier run.
124
+ </dd>
125
+ <dt><code>2</code> · Strict scan produced a partial report</dt>
126
+ <dd>
127
+ Read the report from stdout or the new file named by <code>--output</code>. Inspect its diagnostics before
128
+ using the results. A complete scan with <code>--strict</code> exits with 0.
129
+ </dd>
130
+ </dl>
104
131
  <h2 id="projects">Project selection</h2>
105
132
  <pre><code>node dist/cli.js . --project tsconfig.build.json --exclude '**/generated/**' --test 'qa/**'</code></pre>
106
133
  <p>
@@ -188,14 +215,52 @@
188
215
  the selected file or invocation root and target, or null for an unreached ID. Select the ID with usages. Each
189
216
  non-root node carries the edge kind and source location. summary, usageText and markdown render display text.
190
217
  </p>
218
+ <h2 id="compatibility">Saved reports and 0.x upgrades</h2>
219
+ <p>
220
+ Use <code>--format json</code> for scripts. The packaged <a href="report-schema.json">JSON Schema</a> lists
221
+ the required properties, types, allowed values and nullable fields for each report. Summary, Markdown,
222
+ diagnostic messages and limitation text are for display. <code>--changed-since</code> produces a text summary.
223
+ </p>
224
+ <dl>
225
+ <dt>Full inventory</dt>
226
+ <dd>
227
+ Require <code>schemaVersion === 1</code> for the layout above. Save the full inventory to run new
228
+ <code>usages</code> or <code>reachability</code> queries later. Use <code>analyzer.version</code> and
229
+ <code>analyzer.compilerVersion</code> to identify the producer.
230
+ </dd>
231
+ <dt>Symbol query</dt>
232
+ <dd>
233
+ Require <code>schemaVersion === 1</code> and read <code>usage.symbol</code>,
234
+ <code>usage.references</code> and <code>usage.counts</code>. The CLI puts snapshot-wide diagnostics
235
+ alongside <code>usage</code>.
236
+ </dd>
237
+ <dt>Entry query</dt>
238
+ <dd>
239
+ In 0.3.0 this report has no <code>schemaVersion</code>. Validate it against the schema’s
240
+ <code>entryReport</code> definition. File roots appear in <code>entries</code>. The optional
241
+ <code>entrySymbols</code> lists explicitly invoked declarations. Use <code>reached</code> to reconstruct
242
+ paths and <code>declarations</code> to look up reachability status.
243
+ </dd>
244
+ </dl>
245
+ <p>
246
+ All three shapes carry <code>snapshotId</code>, <code>completeness</code> and <code>diagnostics</code>. Keep
247
+ the matching inventory or its producer metadata with a saved query. Treat IDs as opaque and join records only
248
+ within the same snapshot. A fresh scan with an improved resolver can produce different IDs, counts, paths or
249
+ diagnostics for the same source.
250
+ </p>
251
+ <p>
252
+ Within schema version 1, readers can rely on required fields and their documented meanings. Producers may add
253
+ optional fields and diagnostic codes. Ignore unfamiliar properties, handle unfamiliar codes, and allow
254
+ optional fields such as <code>files[].project</code> to be absent. A required field with a nullable type, such
255
+ as <code>references[].callerId</code>, is present even when its value is <code>null</code>.
256
+ </p>
191
257
  <p>
192
- The <a href="report-schema.json">JSON Schema</a> describes all three CLI report shapes. For persisted data
193
- check schemaVersion before reading a full inventory or symbol response. The entry response has the
194
- Reachability shape in the shipped TypeScript declarations. In 0.1.0 it has no schemaVersion. Keep analyzer and
195
- compiler versions from the full snapshot alongside query results. Use snapshot-local IDs for joins. Accept
196
- additional fields and unknown diagnostic codes. Compare counts across upgrades against source examples;
197
- changes in resolution can change a result even when its shape stays compatible. Keep the generating version
198
- for older snapshots. During 0.x the format and API can change.
258
+ During 0.x, a change that invalidates existing reports or breaks a reader following these rules belongs in a
259
+ new minor release with migration instructions. An incompatible JSON shape also needs a new schema version,
260
+ including an explicit version on a replacement for the unversioned entry report. A change to the documented
261
+ exit codes is likewise a breaking CLI change. Before moving to another minor release, validate a saved report
262
+ with the target schema and replay a representative query. For an unsupported version, retain the original
263
+ report and use its generating release until you migrate.
199
264
  </p>
200
265
  <p>
201
266
  TS-prefixed codes are compiler diagnostics. unresolved-module and dynamic-module identify missing module
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "code-inventory",
3
- "version": "0.2.1",
3
+ "version": "0.3.1",
4
4
  "license": "MIT",
5
5
  "type": "module",
6
6
  "description": "Static code inventory for JavaScript and TypeScript. Find symbol usages and trace paths from entry points.",
@@ -52,10 +52,10 @@
52
52
  "typescript": "npm:@typescript/typescript6@6.0.2"
53
53
  },
54
54
  "devDependencies": {
55
- "@types/node": "26.6.6",
56
- "vitest": "5.1.0",
57
- "prettier": "3.10.1",
55
+ "@types/node": "26.6.11",
58
56
  "eslint": "10.15.0",
59
- "typescript-eslint": "8.73.0"
57
+ "prettier": "3.10.1",
58
+ "typescript-eslint": "8.74.0",
59
+ "vitest": "5.1.2"
60
60
  }
61
61
  }