repograph-cli 0.0.0-stage β 0.1.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/LICENSE +21 -0
- package/README.md +193 -2
- package/dist/bin/cli.d.ts +2 -0
- package/dist/bin/cli.js +40 -0
- package/dist/src/api.d.ts +7 -0
- package/dist/src/api.js +22 -0
- package/dist/src/core/cluster.d.ts +3 -0
- package/dist/src/core/cluster.js +13 -0
- package/dist/src/core/graph.d.ts +16 -0
- package/dist/src/core/graph.js +76 -0
- package/dist/src/index.d.ts +3 -0
- package/dist/src/index.js +57 -0
- package/dist/src/renderer/htmlTemplate.d.ts +4 -0
- package/dist/src/renderer/htmlTemplate.js +297 -0
- package/dist/src/renderer/svgExport.d.ts +3 -0
- package/dist/src/renderer/svgExport.js +44 -0
- package/dist/src/scanner/extractor.d.ts +5 -0
- package/dist/src/scanner/extractor.js +127 -0
- package/dist/src/scanner/heuristics.d.ts +6 -0
- package/dist/src/scanner/heuristics.js +5 -0
- package/dist/src/scanner/walker.d.ts +2 -0
- package/dist/src/scanner/walker.js +49 -0
- package/dist/src/types.d.ts +36 -0
- package/dist/src/types.js +1 -0
- package/package.json +64 -4
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Karry
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,194 @@
|
|
|
1
|
-
#
|
|
1
|
+
# RepoGraph
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Turn any codebase into an interactive architecture map in 2 seconds. Zero server, full privacy, built for Claude & Claude Code.
|
|
4
|
+
|
|
5
|
+

|
|
6
|
+
|
|
7
|
+
[](https://www.npmjs.com/package/repograph-cli) [](LICENSE) [](https://nodejs.org/) 
|
|
8
|
+
|
|
9
|
+
π **[Try the interactive live demo](https://karry1123.github.io/repograph/)** (zustand's architecture, generated with one command)
|
|
10
|
+
|
|
11
|
+
Find the files that matter before changing the code. RepoGraph scans local imports, groups source files by directory and likely architectural layer, and writes an interactive HTML map. Directory clustering and utility folding help keep shared helpers from turning the view into a spiderweb. Three MCP tools let Claude inspect architecture and trace the impact of a proposed change.
|
|
12
|
+
|
|
13
|
+
β2 secondsβ describes the quickstart experience, not a measured performance guarantee. Scan time and HTML size depend on the repository; a small map can be ~40 KB. No account, server, or configuration file is required.
|
|
14
|
+
|
|
15
|
+
## Quickstart
|
|
16
|
+
|
|
17
|
+
```sh
|
|
18
|
+
npx repograph-cli .
|
|
19
|
+
```
|
|
20
|
+
|
|
21
|
+
Open the printed `file:///.../repograph.html` link. Click a file to see its incoming callers in cyan and outgoing dependencies in red. Double-click directory boxes to collapse or expand them. Press `f` to fit the graph to the viewport. Search matches subsequences in full file paths; the minimap lets you jump around large graphs.
|
|
22
|
+
|
|
23
|
+
Node.js 18 or newer is required. Scanning stays on your machine. The HTML embeds your file paths and graph data, so treat it as repository information when sharing. Opening the interactive map downloads pinned Cytoscape/layout scripts from public CDNs; no source or graph data is sent by RepoGraph. The CDN scripts must be reachable on first opening. SVG, JSON, and Mermaid exports need no browser CDN scripts.
|
|
24
|
+
|
|
25
|
+
## CLI reference
|
|
26
|
+
|
|
27
|
+
```text
|
|
28
|
+
repograph [path] [options]
|
|
29
|
+
repograph mcp
|
|
30
|
+
|
|
31
|
+
Options:
|
|
32
|
+
-o, --output <file> Write to a file
|
|
33
|
+
--theme <theme> dark | light | matrix (default: dark)
|
|
34
|
+
--max-depth <n> Maximum directory nesting (default: 6)
|
|
35
|
+
--no-collapse-utils Show utility candidates immediately
|
|
36
|
+
--format <format> html | json | mermaid | svg (default: html)
|
|
37
|
+
-V, --version Show version
|
|
38
|
+
-h, --help Show help
|
|
39
|
+
```
|
|
40
|
+
|
|
41
|
+
The path defaults to `.`. HTML defaults to `./repograph.html` in your current working directory and prints its absolute file URL after writing. Other formats print to stdout unless `--output` is supplied. Output directories are created automatically. `--max-depth 0` scans only root files.
|
|
42
|
+
|
|
43
|
+
```sh
|
|
44
|
+
npx repograph-cli ./my-app --output ./architecture.html --theme matrix
|
|
45
|
+
npx repograph-cli . --format json > graph.json
|
|
46
|
+
npx repograph-cli . --format mermaid --output architecture.mmd
|
|
47
|
+
npx repograph-cli . --format svg --output architecture.svg
|
|
48
|
+
npx repograph-cli . --max-depth 10 --no-collapse-utils
|
|
49
|
+
```
|
|
50
|
+
|
|
51
|
+
The static SVG arranges files in entry β business β unknown β data β util columns. Mermaid exports preserve nested directory subgraphs. Both include utility candidates; HTML initially hides folded utilities and their edges.
|
|
52
|
+
|
|
53
|
+
## Use with Claude
|
|
54
|
+
|
|
55
|
+
### Install from the MCP Registry
|
|
56
|
+
|
|
57
|
+
Registry metadata is prepared under the name `io.github.Karry1123/repograph`. After publication to the [official MCP Registry](https://registry.modelcontextprotocol.io), look up that name in a registry-compatible client; the manual Claude setup below also works.
|
|
58
|
+
|
|
59
|
+
### Claude Desktop
|
|
60
|
+
|
|
61
|
+
Add this entry to `claude_desktop_config.json`, merging it with existing servers:
|
|
62
|
+
|
|
63
|
+
```json
|
|
64
|
+
{
|
|
65
|
+
"mcpServers": {
|
|
66
|
+
"repograph": {
|
|
67
|
+
"command": "npx",
|
|
68
|
+
"args": ["-y", "repograph-cli", "mcp"]
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
```
|
|
73
|
+
|
|
74
|
+
Restart Claude Desktop, then ask: βScan my repository at `/absolute/path/to/project` and show the impact of changing `src/core/graph.ts`.β Use an absolute repository path; the MCP server may start with a different working directory. Windows paths work too, for example `F:\\RepoGraph` in JSON.
|
|
75
|
+
|
|
76
|
+
### Claude Code
|
|
77
|
+
|
|
78
|
+
```sh
|
|
79
|
+
claude mcp add repograph -- npx -y repograph-cli mcp
|
|
80
|
+
```
|
|
81
|
+
|
|
82
|
+
Ask Claude to generate an architecture map before a refactor, or find all transitive callers of a module before editing it. MCP mode uses stdio for the protocol and writes errors only to stderr.
|
|
83
|
+
|
|
84
|
+
### Tools
|
|
85
|
+
|
|
86
|
+
| Tool | Arguments | Result |
|
|
87
|
+
| --- | --- | --- |
|
|
88
|
+
| `scan_repository_graph` | `path` (required string), `maxDepth` (integer, default `6`), `collapseUtils` (boolean, default `true`) | ArchitectureGraph JSON with nodes, edges, nested clusters, and metrics |
|
|
89
|
+
| `generate_architecture_html` | `path` (required string), `outputPath` (default `"./repograph.html"`), `theme` (`dark`, `light`, or `matrix`, default `dark`) | `{ success: true, filePath, nodeCount }` |
|
|
90
|
+
| `query_impact_path` | `path` (required string), `changedFile` (required relative file ID or absolute path) | Normalized changed file, direct dependents, transitive dependents with BFS depth, affected clusters, and blast radius |
|
|
91
|
+
|
|
92
|
+
For HTML generation, a relative `outputPath` is resolved against the repository path. An absolute output path is used directly. The tools use a utility fan-in threshold of 15. Missing changed files return an error with the closest matching IDs. `transitiveDependents` includes direct callers at depth 1; `blastRadius` counts unique affected files and excludes the changed file itself.
|
|
93
|
+
|
|
94
|
+
## How the map works
|
|
95
|
+
|
|
96
|
+
### Imports become edges
|
|
97
|
+
|
|
98
|
+
Each source file becomes a node with a forward-slash relative ID. Local imports become directed edges from importer to dependency. JavaScript and TypeScript use Babel, with a regex fallback for unsupported syntax. Repeated references of the same type are combined with an edge weight. External packages are dropped. Class inheritance through an imported binding gets an `inheritance` edge; `import()` gets a `dynamic` edge.
|
|
99
|
+
|
|
100
|
+
RepoGraph tries source extensions, directory index files, NodeNext `.js` β `.ts` equivalents, and a heuristic `@/` β `src/` alias. It does not execute code or load project-specific compiler plugins. Computed imports and custom aliases can be missed.
|
|
101
|
+
|
|
102
|
+
### Layers give the graph meaning
|
|
103
|
+
|
|
104
|
+
| Layer | File or directory clues | Colour |
|
|
105
|
+
| --- | --- | --- |
|
|
106
|
+
| Entry | controller, route, router, handler, api, endpoint, cli, app, server, main; root index | Cyan |
|
|
107
|
+
| Business | service, usecase, core, domain, logic, manager | Magenta |
|
|
108
|
+
| Data | repo, repository, model, schema, entity, store, db, dao, migration | Amber |
|
|
109
|
+
| Util | util, utils, helpers, common, shared, lib, constants, types, config; high fan-in | Slate |
|
|
110
|
+
| Unknown | Everything else | Indigo |
|
|
111
|
+
|
|
112
|
+
Classification checks entry, business, data, then utility clues. It is an explainable filename heuristic, not a semantic judgement about your design. Clusters reflect the first two directory levels and retain nested parents.
|
|
113
|
+
|
|
114
|
+
### Utility folding reduces noise
|
|
115
|
+
|
|
116
|
+
Files with more than 12 incoming callers and at most two outgoing dependencies, or utility-like names, are folding candidates. CLI/API default to 12; MCP defaults to 15. Folded nodes and their edges stay in the graph data and impact analysis but disappear from the initial HTML view. βShow utilitiesβ reveals them. Degree counts use unique neighboring files, not repeated imports.
|
|
117
|
+
|
|
118
|
+
### Blast radius follows callers
|
|
119
|
+
|
|
120
|
+
Impact analysis performs a breadth-first search over reverse edges. It handles cycles, visits each file once, and records the shortest caller depth. The inspector lists direct callers and dependencies; the highlight traces both full transitive chains. If a cycle belongs to both chains, the dependency highlight takes precedence.
|
|
121
|
+
|
|
122
|
+
Dead-code warnings count files with no incoming local edges that do not look like entry points. Treat these as review hints: frameworks, reflection, external consumers, and dynamic loading can all create valid files with no static callers. Coupling factor is average unique out-degree; density is edges divided by `n * (n - 1)` (zero for fewer than two files). LOC counts nonblank source lines, including comments.
|
|
123
|
+
|
|
124
|
+
## Supported languages and scan rules
|
|
125
|
+
|
|
126
|
+
| Language | Resolution |
|
|
127
|
+
| --- | --- |
|
|
128
|
+
| JavaScript / TypeScript | ESM imports/re-exports, `require()`, dynamic imports, imported superclass bindings; JS/JSX/MJS/CJS/TS/TSX/MTS/CTS |
|
|
129
|
+
| Python | `import a.b`, absolute and relative `from` imports, `.py` modules and `__init__.py` packages |
|
|
130
|
+
| Go | Single imports and import blocks; paths under the root `go.mod` module resolve to every scanned `.go` file in the target directory |
|
|
131
|
+
| Rust | `mod x;` resolves to `x.rs` or `x/mod.rs`; `use crate::...` resolves modules under `src/` |
|
|
132
|
+
|
|
133
|
+
Root and nested `.gitignore` rules are respected. RepoGraph skips dependency, build, cache, and editor directories, including `node_modules`, `.git`, `dist`, `build`, `out`, `coverage`, `__pycache__`, `.venv`, `venv`, `.next`, `.nuxt`, `target`, `vendor`, `.idea`, `.vscode`, and `.cache`. Symlinks are skipped to prevent cycles. Files larger than 1.5 MB and `*.min.js` are excluded. Test/spec files are excluded from the main graph, with their count retained as `metrics.excludedTestFiles`.
|
|
134
|
+
|
|
135
|
+
Python, Go, and Rust resolution is intentionally static and heuristic: workspace manifests, build tags, Python import hooks, Rust macros, and non-root Go modules are not evaluated. Only files included in the scan can become nodes or targets.
|
|
136
|
+
|
|
137
|
+
## Where it fits
|
|
138
|
+
|
|
139
|
+
This table describes the tools' focus rather than a feature-completeness or performance benchmark. Check each project's current documentation for its full capabilities.
|
|
140
|
+
|
|
141
|
+
| | RepoGraph | Madge | CodeSee | Gitingest |
|
|
142
|
+
| --- | --- | --- | --- | --- |
|
|
143
|
+
| Primary output | Local interactive HTML architecture map | Module dependency graphs | Code exploration and mapping platform | Repository text context |
|
|
144
|
+
| Workflow | CLI + three MCP tools | Dependency analysis CLI/API | Platform workflow | Ingest code for LLM context |
|
|
145
|
+
| Main emphasis | Layers, utility folding, caller impact | Module relationships and cycles | Collaborative code understanding | Shareable code context |
|
|
146
|
+
| RepoGraph's approach | No server; embedded graph snapshot | Complementary dependency tooling | Different platform model | Complementary text-first tooling |
|
|
147
|
+
|
|
148
|
+
## Programmatic use
|
|
149
|
+
|
|
150
|
+
```ts
|
|
151
|
+
import { analyzeRepository } from 'repograph-cli/dist/src/api.js';
|
|
152
|
+
import { impactPath } from 'repograph-cli/dist/src/core/graph.js';
|
|
153
|
+
import { renderToHtml } from 'repograph-cli/dist/src/renderer/htmlTemplate.js';
|
|
154
|
+
|
|
155
|
+
const graph = await analyzeRepository('.', {
|
|
156
|
+
maxDepth: 6,
|
|
157
|
+
collapseUtils: true,
|
|
158
|
+
utilThreshold: 12,
|
|
159
|
+
});
|
|
160
|
+
const impact = impactPath(graph, 'src/api.ts');
|
|
161
|
+
const html = renderToHtml(graph, { theme: 'dark' });
|
|
162
|
+
```
|
|
163
|
+
|
|
164
|
+
`createServer()` and `startMcpServer()` are exported from `dist/src/index.js`; importing the module does not start a transport. The graph data model lives in `src/types.ts` and ships with generated TypeScript declarations.
|
|
165
|
+
|
|
166
|
+
## Contributing
|
|
167
|
+
|
|
168
|
+
```sh
|
|
169
|
+
npm install
|
|
170
|
+
npm run build
|
|
171
|
+
node dist/bin/cli.js . --output demo/self.html
|
|
172
|
+
node dist/bin/cli.js . --format json
|
|
173
|
+
node dist/bin/cli.js . --format mermaid
|
|
174
|
+
```
|
|
175
|
+
|
|
176
|
+
During development, use `npm run dev -- .`. On Windows PowerShell installations that block `npm.ps1`, use `npm.cmd`. Keep path IDs portable, avoid executing scanned code, and test resolution changes against a small repository containing the relevant imports. Include reproduction steps and the expected edges in bug reports or contributions.
|
|
177
|
+
|
|
178
|
+
## License
|
|
179
|
+
|
|
180
|
+
MIT Β© 2026 Karry. See [LICENSE](LICENSE).
|
|
181
|
+
|
|
182
|
+
## Roadmap Β· star to vote
|
|
183
|
+
|
|
184
|
+
- [x] TypeScript/JavaScript
|
|
185
|
+
- [x] Python
|
|
186
|
+
- [x] Go
|
|
187
|
+
- [x] Rust
|
|
188
|
+
- [ ] Java/Kotlin (unlocks at 200 β)
|
|
189
|
+
- [ ] C# (300 β)
|
|
190
|
+
- [ ] PHP/Ruby (500 β)
|
|
191
|
+
- [ ] Monorepo workspace + tsconfig paths alias resolution (200 β)
|
|
192
|
+
- [ ] VS Code extension (1000 β)
|
|
193
|
+
|
|
194
|
+
Star to vote, open a [Language Support Request issue](https://github.com/Karry1123/repograph/issues/new?template=language_support_request.yml), and share the imports and project layout you need supported. These thresholds guide priorities rather than promise delivery dates.
|
package/dist/bin/cli.js
ADDED
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { Command, InvalidArgumentError } from 'commander';
|
|
3
|
+
import { mkdir, writeFile } from 'node:fs/promises';
|
|
4
|
+
import path from 'node:path';
|
|
5
|
+
import { pathToFileURL } from 'node:url';
|
|
6
|
+
import { analyzeRepository } from '../src/api.js';
|
|
7
|
+
import { renderToHtml } from '../src/renderer/htmlTemplate.js';
|
|
8
|
+
import { renderToMermaid, renderToSvg } from '../src/renderer/svgExport.js';
|
|
9
|
+
import { startMcpServer } from '../src/index.js';
|
|
10
|
+
const program = new Command();
|
|
11
|
+
program.name('repograph-cli').version('0.1.1').description('Turn a local codebase into an interactive architecture map')
|
|
12
|
+
.argument('[path]', 'Repository directory', '.')
|
|
13
|
+
.option('-o, --output <file>', 'Output file (HTML defaults to repograph.html)')
|
|
14
|
+
.option('--theme <theme>', 'dark, light, or matrix', 'dark')
|
|
15
|
+
.option('--max-depth <n>', 'Maximum directory depth', value => {
|
|
16
|
+
if (!/^\d+$/.test(value))
|
|
17
|
+
throw new InvalidArgumentError('Expected a nonnegative integer');
|
|
18
|
+
return Number(value);
|
|
19
|
+
}, 6)
|
|
20
|
+
.option('--no-collapse-utils', 'Show utility nodes initially')
|
|
21
|
+
.option('--format <format>', 'html, json, mermaid, or svg', 'html')
|
|
22
|
+
.action(async (directory, options) => {
|
|
23
|
+
if (!['dark', 'light', 'matrix'].includes(options.theme))
|
|
24
|
+
throw new Error('Theme must be dark, light, or matrix');
|
|
25
|
+
if (!['html', 'json', 'mermaid', 'svg'].includes(options.format))
|
|
26
|
+
throw new Error('Format must be html, json, mermaid, or svg');
|
|
27
|
+
const graph = await analyzeRepository(directory, options);
|
|
28
|
+
const content = options.format === 'json' ? JSON.stringify(graph, null, 2) + '\n' : options.format === 'mermaid' ? renderToMermaid(graph) : options.format === 'svg' ? renderToSvg(graph) : renderToHtml(graph, { theme: options.theme });
|
|
29
|
+
if (options.output || options.format === 'html') {
|
|
30
|
+
const output = path.resolve(options.output ?? 'repograph.html');
|
|
31
|
+
await mkdir(path.dirname(output), { recursive: true });
|
|
32
|
+
await writeFile(output, content, 'utf8');
|
|
33
|
+
if (options.format === 'html')
|
|
34
|
+
console.log(pathToFileURL(output).href);
|
|
35
|
+
}
|
|
36
|
+
else
|
|
37
|
+
process.stdout.write(content);
|
|
38
|
+
});
|
|
39
|
+
program.command('mcp').description('Start the MCP stdio server').action(async () => { await startMcpServer(); });
|
|
40
|
+
program.parseAsync().catch(error => { console.error(error instanceof Error ? error.message : error); process.exitCode = 1; });
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import type { ArchitectureGraph } from './types.js';
|
|
2
|
+
export interface AnalyzeOptions {
|
|
3
|
+
maxDepth?: number;
|
|
4
|
+
collapseUtils?: boolean;
|
|
5
|
+
utilThreshold?: number;
|
|
6
|
+
}
|
|
7
|
+
export declare function analyzeRepository(directory: string, options?: AnalyzeOptions): Promise<ArchitectureGraph>;
|
package/dist/src/api.js
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
import path from 'node:path';
|
|
2
|
+
import { stat } from 'node:fs/promises';
|
|
3
|
+
import { walkRepository } from './scanner/walker.js';
|
|
4
|
+
import { extractImports } from './scanner/extractor.js';
|
|
5
|
+
import { isTestFile } from './scanner/heuristics.js';
|
|
6
|
+
import { buildGraph, pruneNoise } from './core/graph.js';
|
|
7
|
+
export async function analyzeRepository(directory, options = {}) {
|
|
8
|
+
const root = path.resolve(directory);
|
|
9
|
+
if (!(await stat(root)).isDirectory())
|
|
10
|
+
throw new Error('Repository path must be a directory: ' + root);
|
|
11
|
+
const maxDepth = options.maxDepth ?? 6;
|
|
12
|
+
if (!Number.isInteger(maxDepth) || maxDepth < 0)
|
|
13
|
+
throw new Error('maxDepth must be a nonnegative integer');
|
|
14
|
+
const scanned = await walkRepository(root, maxDepth);
|
|
15
|
+
const testFileCount = scanned.filter(isTestFile).length;
|
|
16
|
+
const files = scanned.filter(file => !isTestFile(file));
|
|
17
|
+
const { edges, loc } = await extractImports(root, files);
|
|
18
|
+
const graph = buildGraph(root, files, edges, loc);
|
|
19
|
+
// Keep the specified public model intact while exposing the excluded count.
|
|
20
|
+
Object.assign(graph.metrics, { excludedTestFiles: testFileCount });
|
|
21
|
+
return options.collapseUtils === false ? graph : pruneNoise(graph, { threshold: options.utilThreshold ?? 12 });
|
|
22
|
+
}
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import { isEntryLike, isUtility, nameTokens } from '../scanner/heuristics.js';
|
|
2
|
+
export const LAYER_COLORS = { entry: '#22d3ee', business: '#e879f9', data: '#fbbf24', util: '#94a3b8', unknown: '#818cf8' };
|
|
3
|
+
export function classifyLayer(node) {
|
|
4
|
+
if (isEntryLike(node.id))
|
|
5
|
+
return 'entry';
|
|
6
|
+
if (/(?:^|[/_.-])(?:services?|usecases?|core|domain|logic|managers?)(?:[/_.-]|$)/i.test(nameTokens(node.id)))
|
|
7
|
+
return 'business';
|
|
8
|
+
if (/(?:^|[/_.-])(?:repos?|repositories|repository|models?|schemas?|entities|entity|stores?|db|dao|migrations?)(?:[/_.-]|$)/i.test(nameTokens(node.id)))
|
|
9
|
+
return 'data';
|
|
10
|
+
if (isUtility(node))
|
|
11
|
+
return 'util';
|
|
12
|
+
return 'unknown';
|
|
13
|
+
}
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import type { ArchitectureGraph, CodeEdge } from '../types.js';
|
|
2
|
+
export declare function adjacencyList(graph: ArchitectureGraph, reverse?: boolean): Map<string, Set<string>>;
|
|
3
|
+
export declare function buildGraph(rootPath: string, files: string[], edges: CodeEdge[], loc: Map<string, number>): ArchitectureGraph;
|
|
4
|
+
export declare function pruneNoise(graph: ArchitectureGraph, { threshold }?: {
|
|
5
|
+
threshold?: number;
|
|
6
|
+
}): ArchitectureGraph;
|
|
7
|
+
export declare function impactPath(graph: ArchitectureGraph, changedFile: string): {
|
|
8
|
+
changedFile: string;
|
|
9
|
+
directDependents: string[];
|
|
10
|
+
transitiveDependents: {
|
|
11
|
+
id: string;
|
|
12
|
+
depth: number;
|
|
13
|
+
}[];
|
|
14
|
+
affectedClusters: string[];
|
|
15
|
+
blastRadius: number;
|
|
16
|
+
};
|
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
import path from 'node:path';
|
|
2
|
+
import { classifyLayer } from './cluster.js';
|
|
3
|
+
import { isEntryLike, isUtility } from '../scanner/heuristics.js';
|
|
4
|
+
import { normalize } from '../scanner/walker.js';
|
|
5
|
+
export function adjacencyList(graph, reverse = false) {
|
|
6
|
+
const map = new Map(graph.nodes.map(node => [node.id, new Set()]));
|
|
7
|
+
for (const edge of graph.edges)
|
|
8
|
+
map.get(reverse ? edge.target : edge.source)?.add(reverse ? edge.source : edge.target);
|
|
9
|
+
return map;
|
|
10
|
+
}
|
|
11
|
+
export function buildGraph(rootPath, files, edges, loc) {
|
|
12
|
+
const clusters = new Map();
|
|
13
|
+
const nodes = files.map(id => {
|
|
14
|
+
const dirs = id.split('/').slice(0, -1).slice(0, 2);
|
|
15
|
+
if (!dirs.length)
|
|
16
|
+
dirs.push('(root)');
|
|
17
|
+
let parent;
|
|
18
|
+
for (let n = 1; n <= dirs.length; n++) {
|
|
19
|
+
const clusterId = 'cluster:' + dirs.slice(0, n).join('/');
|
|
20
|
+
clusters.set(clusterId, { id: clusterId, label: dirs[n - 1], ...(parent ? { parent } : {}) });
|
|
21
|
+
parent = clusterId;
|
|
22
|
+
}
|
|
23
|
+
return { id, label: path.posix.basename(id), layer: 'unknown', cluster: parent, inDegree: 0, outDegree: 0, linesOfCode: loc.get(id) ?? 0, language: /\.py$/.test(id) ? 'Python' : /\.go$/.test(id) ? 'Go' : /\.rs$/.test(id) ? 'Rust' : /\.[cm]?tsx?$/.test(id) ? 'TypeScript' : 'JavaScript' };
|
|
24
|
+
});
|
|
25
|
+
const graph = { rootPath, generatedAt: new Date().toISOString(), nodes, edges, clusters: [...clusters.values()], metrics: { totalFiles: nodes.length, totalEdges: edges.length, density: 0, couplingFactor: 0, deadCodeCount: 0, foldedUtilityCount: 0 } };
|
|
26
|
+
const outgoing = adjacencyList(graph), incoming = adjacencyList(graph, true);
|
|
27
|
+
for (const node of nodes) {
|
|
28
|
+
node.inDegree = incoming.get(node.id).size;
|
|
29
|
+
node.outDegree = outgoing.get(node.id).size;
|
|
30
|
+
node.layer = classifyLayer(node);
|
|
31
|
+
}
|
|
32
|
+
const n = nodes.length;
|
|
33
|
+
graph.metrics.density = n > 1 ? edges.length / (n * (n - 1)) : 0;
|
|
34
|
+
graph.metrics.couplingFactor = n ? nodes.reduce((sum, node) => sum + node.outDegree, 0) / n : 0;
|
|
35
|
+
graph.metrics.deadCodeCount = nodes.filter(node => node.inDegree === 0 && !isEntryLike(node.id)).length;
|
|
36
|
+
return graph;
|
|
37
|
+
}
|
|
38
|
+
// Preserve the full edge set for utilities toggling and impact queries. Renderers
|
|
39
|
+
// exclude edges touching isFolded nodes from the initial main view.
|
|
40
|
+
export function pruneNoise(graph, { threshold = 12 } = {}) {
|
|
41
|
+
for (const node of graph.nodes)
|
|
42
|
+
node.isFolded = isUtility(node, threshold);
|
|
43
|
+
graph.metrics.foldedUtilityCount = graph.nodes.filter(node => node.isFolded).length;
|
|
44
|
+
return graph;
|
|
45
|
+
}
|
|
46
|
+
export function impactPath(graph, changedFile) {
|
|
47
|
+
const id = normalize(path.isAbsolute(changedFile) ? path.relative(graph.rootPath, changedFile) : changedFile).replace(/^\.\//, '');
|
|
48
|
+
if (!graph.nodes.some(node => node.id === id)) {
|
|
49
|
+
const score = (candidate) => {
|
|
50
|
+
const a = id.toLowerCase(), b = candidate.toLowerCase();
|
|
51
|
+
const row = Array.from({ length: b.length + 1 }, (_, i) => i);
|
|
52
|
+
for (let i = 1; i <= a.length; i++) {
|
|
53
|
+
let prev = row[0];
|
|
54
|
+
row[0] = i;
|
|
55
|
+
for (let j = 1; j <= b.length; j++) {
|
|
56
|
+
const old = row[j];
|
|
57
|
+
row[j] = Math.min(row[j] + 1, row[j - 1] + 1, prev + (a[i - 1] === b[j - 1] ? 0 : 1));
|
|
58
|
+
prev = old;
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
return row[b.length];
|
|
62
|
+
};
|
|
63
|
+
throw new Error('File not found: ' + id + '. Closest matching ids: ' + graph.nodes.map(node => node.id).sort((a, b) => score(a) - score(b)).slice(0, 5).join(', '));
|
|
64
|
+
}
|
|
65
|
+
const reverse = adjacencyList(graph, true), visited = new Set([id]), queue = [{ id, depth: 0 }], dependents = [];
|
|
66
|
+
for (let i = 0; i < queue.length; i++)
|
|
67
|
+
for (const caller of reverse.get(queue[i].id) ?? []) {
|
|
68
|
+
if (!visited.has(caller)) {
|
|
69
|
+
visited.add(caller);
|
|
70
|
+
const item = { id: caller, depth: queue[i].depth + 1 };
|
|
71
|
+
queue.push(item);
|
|
72
|
+
dependents.push(item);
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
return { changedFile: id, directDependents: [...(reverse.get(id) ?? [])], transitiveDependents: dependents, affectedClusters: [...new Set(graph.nodes.filter(node => dependents.some(item => item.id === node.id)).map(node => node.cluster))], blastRadius: dependents.length };
|
|
76
|
+
}
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
|
|
2
|
+
import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
|
|
3
|
+
import { z } from 'zod';
|
|
4
|
+
import { mkdir, writeFile } from 'node:fs/promises';
|
|
5
|
+
import path from 'node:path';
|
|
6
|
+
import { pathToFileURL } from 'node:url';
|
|
7
|
+
import { analyzeRepository } from './api.js';
|
|
8
|
+
import { impactPath } from './core/graph.js';
|
|
9
|
+
import { renderToHtml } from './renderer/htmlTemplate.js';
|
|
10
|
+
export function createServer() {
|
|
11
|
+
const server = new McpServer({ name: 'repograph-cli', version: '0.1.1' });
|
|
12
|
+
const result = (data) => ({ content: [{ type: 'text', text: JSON.stringify(data, null, 2) }] });
|
|
13
|
+
const failure = (error) => ({ ...result({ error: error instanceof Error ? error.message : String(error) }), isError: true });
|
|
14
|
+
server.tool('scan_repository_graph', 'Scan a local codebase into an architecture graph. Test files and external imports are excluded.', {
|
|
15
|
+
path: z.string(), maxDepth: z.number().int().nonnegative().default(6), collapseUtils: z.boolean().default(true)
|
|
16
|
+
}, async (args) => {
|
|
17
|
+
try {
|
|
18
|
+
return result(await analyzeRepository(args.path, { ...args, utilThreshold: 15 }));
|
|
19
|
+
}
|
|
20
|
+
catch (error) {
|
|
21
|
+
return failure(error);
|
|
22
|
+
}
|
|
23
|
+
});
|
|
24
|
+
server.tool('generate_architecture_html', 'Write a self-contained interactive architecture map of a local codebase.', {
|
|
25
|
+
path: z.string(), outputPath: z.string().default('./repograph.html'), theme: z.enum(['dark', 'light', 'matrix']).default('dark')
|
|
26
|
+
}, async (args) => {
|
|
27
|
+
try {
|
|
28
|
+
const graph = await analyzeRepository(args.path, { utilThreshold: 15 });
|
|
29
|
+
const filePath = path.resolve(args.path, args.outputPath);
|
|
30
|
+
await mkdir(path.dirname(filePath), { recursive: true });
|
|
31
|
+
await writeFile(filePath, renderToHtml(graph, { theme: args.theme }), 'utf8');
|
|
32
|
+
return result({ success: true, filePath, nodeCount: graph.nodes.length });
|
|
33
|
+
}
|
|
34
|
+
catch (error) {
|
|
35
|
+
return failure(error);
|
|
36
|
+
}
|
|
37
|
+
});
|
|
38
|
+
server.tool('query_impact_path', 'Find direct and transitive callers of a changed file, with BFS depths and affected clusters.', {
|
|
39
|
+
path: z.string(), changedFile: z.string()
|
|
40
|
+
}, async (args) => {
|
|
41
|
+
try {
|
|
42
|
+
return result(impactPath(await analyzeRepository(args.path, { utilThreshold: 15 }), args.changedFile));
|
|
43
|
+
}
|
|
44
|
+
catch (error) {
|
|
45
|
+
return failure(error);
|
|
46
|
+
}
|
|
47
|
+
});
|
|
48
|
+
return server;
|
|
49
|
+
}
|
|
50
|
+
export async function startMcpServer() {
|
|
51
|
+
const server = createServer();
|
|
52
|
+
await server.connect(new StdioServerTransport());
|
|
53
|
+
return server;
|
|
54
|
+
}
|
|
55
|
+
if (process.argv[1] && import.meta.url === pathToFileURL(path.resolve(process.argv[1])).href) {
|
|
56
|
+
startMcpServer().catch(error => { console.error(error); process.exitCode = 1; });
|
|
57
|
+
}
|
|
@@ -0,0 +1,297 @@
|
|
|
1
|
+
import { LAYER_COLORS } from '../core/cluster.js';
|
|
2
|
+
export function renderToHtml(graph, options) {
|
|
3
|
+
// HTML is shareable: retain the repository label without embedding a local path.
|
|
4
|
+
const rootLabel = graph.rootPath.replace(/\\/g, '/').replace(/\/$/, '').split('/').pop() || 'repository';
|
|
5
|
+
const json = JSON.stringify({ ...graph, rootPath: rootLabel }).replace(/</g, '\\u003c').replace(/\u2028/g, '\\u2028').replace(/\u2029/g, '\\u2029');
|
|
6
|
+
return `<!DOCTYPE html>
|
|
7
|
+
<html lang="en" data-theme="${options.theme}">
|
|
8
|
+
<head>
|
|
9
|
+
<meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
|
|
10
|
+
<meta name="color-scheme" content="dark light">
|
|
11
|
+
<title>RepoGraph Β· Architecture map</title>
|
|
12
|
+
<style>
|
|
13
|
+
:root{--bg:#0f172a;--canvas:#090d16;--panel:#111b2d;--text:#e2e8f0;--muted:#94a3b8;--line:#29364c;--accent:#22d3ee;--pink:#e879f9;--amber:#fbbf24;--shadow:0 12px 40px #0005;--incoming:#22d3ee;--outgoing:#fb7185}
|
|
14
|
+
[data-theme=light]{--bg:#f1f5f9;--canvas:#f8fafc;--panel:#fff;--text:#0f172a;--muted:#526277;--line:#cbd5e1;--accent:#0284c7;--pink:#a21caf;--amber:#b45309;--shadow:0 12px 40px #33415515;--incoming:#0284c7;--outgoing:#dc2626}
|
|
15
|
+
[data-theme=matrix]{--bg:#020802;--canvas:#000;--panel:#041004;--text:#b2ffba;--muted:#6ea879;--line:#184721;--accent:#39ff6b;--pink:#aaff88;--amber:#d5ff53;--shadow:0 12px 40px #00ff1110;--incoming:#39ff6b;--outgoing:#ff6363}
|
|
16
|
+
*{box-sizing:border-box}body{margin:0;height:100vh;overflow:hidden;background:var(--bg);color:var(--text);font:13px/1.5 system-ui,-apple-system,BlinkMacSystemFont,"Segoe UI",sans-serif}button,input,select{font:inherit}button{cursor:pointer;color:var(--text);background:var(--panel);border:1px solid var(--line);border-radius:8px;padding:8px 12px;transition:background .15s,border-color .15s}button:hover{border-color:var(--accent)}button:focus-visible,input:focus-visible,select:focus-visible,a:focus-visible{outline:2px solid var(--accent);outline-offset:3px}button:disabled{opacity:.4;cursor:default}header{height:72px;display:flex;align-items:center;gap:24px;padding:0 24px;border-bottom:1px solid var(--line);position:relative;z-index:3;background:var(--bg)}.brand{display:flex;align-items:center;gap:10px;white-space:nowrap}.logo{display:grid;place-items:center;background:var(--accent);color:var(--canvas);width:32px;height:32px;border-radius:9px;font-size:21px;font-weight:800}.brand strong{font-size:18px;letter-spacing:-.6px}.version{font:10px monospace;color:var(--muted);border:1px solid var(--line);padding:2px 5px;border-radius:4px}.metrics{display:flex;align-items:center;gap:0;margin:auto;border:1px solid var(--line);background:var(--panel);border-radius:24px;overflow:hidden}.metric{padding:7px 17px;border-right:1px solid var(--line);white-space:nowrap}.metric:last-child{border:0}.metric b{margin-right:5px;font-variant-numeric:tabular-nums}.metric span{font-size:11px;color:var(--muted)}.metric.warning b{color:var(--amber)}.header-actions{display:flex;gap:8px;align-items:center}select{background:var(--panel);color:var(--text);border:1px solid var(--line);border-radius:8px;padding:8px}.workspace{height:calc(100vh - 72px);position:relative;display:flex}#cy{position:absolute;inset:0 320px 0 0;background:var(--canvas)}.toolbar{position:absolute;left:22px;top:22px;display:flex;gap:8px;align-items:center;z-index:2}.search-wrap{position:relative}.search-wrap:before{content:'β';position:absolute;left:12px;top:4px;font-size:24px;color:var(--muted)}#search{background:var(--panel);border:1px solid var(--line);color:var(--text);width:280px;padding:11px 52px 11px 38px;border-radius:10px;box-shadow:var(--shadow)}#search::placeholder{color:var(--muted)}.key{position:absolute;right:10px;top:11px;font:11px monospace;color:var(--muted);border:1px solid var(--line);padding:0 4px;border-radius:3px}.search-results{position:absolute;top:51px;left:0;background:var(--panel);border:1px solid var(--line);border-radius:10px;box-shadow:var(--shadow);width:350px;max-height:320px;overflow:auto;display:none}.search-results.open{display:block}.search-result{display:block;text-align:left;border:0;border-radius:0;width:100%;padding:10px 13px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;font:11px/1.6 monospace}.search-result:hover{background:var(--bg);color:var(--accent)}.search-caption{padding:8px 13px;color:var(--muted);font-size:11px;border-bottom:1px solid var(--line)}.controls{display:flex;gap:6px}.controls button{box-shadow:var(--shadow);height:41px}.utilities{position:absolute;left:22px;top:79px;display:flex;gap:9px;align-items:center;background:var(--panel);padding:8px 12px;border:1px solid var(--line);border-radius:9px;color:var(--muted);font-size:12px;z-index:2;box-shadow:var(--shadow);cursor:pointer}.utilities input{accent-color:var(--accent);margin:0}.utilities strong{color:var(--text);font-size:11px;background:var(--bg);padding:0 5px;border-radius:4px}.legend{position:absolute;left:22px;bottom:42px;background:var(--panel);border:1px solid var(--line);border-radius:10px;padding:13px 15px;box-shadow:var(--shadow);z-index:2;min-width:165px}.eyebrow{text-transform:uppercase;font-size:10px;letter-spacing:1.5px;color:var(--muted);margin-bottom:10px}.legend-row{display:flex;align-items:center;gap:9px;margin-top:7px;font-size:12px}.dot{width:9px;height:9px;border-radius:50%;display:inline-block;flex-shrink:0}.legend-row small{margin-left:auto;color:var(--muted);font-variant-numeric:tabular-nums}.legend-separator{border-top:1px solid var(--line);margin:12px 0 8px}.line-key{display:inline-block;width:16px;height:2px;background:var(--muted)}.line-key.in{background:var(--incoming)}.line-key.out{background:var(--outgoing)}#sidebar{position:absolute;right:0;top:0;bottom:0;width:320px;background:var(--bg);border-left:1px solid var(--line);overflow:auto;z-index:3}.side-top{padding:22px;border-bottom:1px solid var(--line)}.side-title{font-size:15px;font-weight:650;margin:0 0 7px}.side-sub{color:var(--muted);font-size:12px;margin:0}.side-body{padding:22px}.empty-icon{width:56px;height:56px;display:grid;place-items:center;margin:24px 0 20px;border-radius:15px;border:1px solid var(--line);color:var(--accent);font-size:26px}.empty-title{font-size:17px;font-weight:600}.hint{color:var(--muted);font-size:12px;line-height:1.8}.hint-list{padding-left:17px;color:var(--muted);font-size:12px;line-height:1.9}.hint-list li{padding:3px 0}.repo-path{font:11px/1.7 monospace;overflow-wrap:anywhere;color:var(--muted);margin-top:20px;padding-top:15px;border-top:1px solid var(--line)}.file-path{font:12px/1.8 monospace;overflow-wrap:anywhere;margin:0 0 15px}.badge{display:inline-flex;align-items:center;gap:6px;font-size:11px;padding:3px 8px;border-radius:6px;background:var(--panel);border:1px solid var(--line);margin:0 5px 5px 0}.stats-grid{display:grid;grid-template-columns:1fr 1fr;gap:9px;margin:18px 0}.stat-card{padding:12px;background:var(--panel);border:1px solid var(--line);border-radius:9px}.stat-card b{font-size:20px;display:block;font-weight:600;line-height:1.3}.stat-card span{font-size:10px;color:var(--muted);text-transform:uppercase;letter-spacing:.8px}.detail-heading{font-size:11px;text-transform:uppercase;letter-spacing:1px;margin:22px 0 10px;color:var(--muted);display:flex;justify-content:space-between}.file-list{display:flex;flex-direction:column;gap:5px}.file-link{display:flex;align-items:center;gap:8px;text-align:left;width:100%;font:11px/1.6 monospace;padding:7px 9px;border-radius:6px;overflow-wrap:anywhere}.file-link span:last-child{min-width:0;overflow-wrap:anywhere}.no-items{color:var(--muted);font-size:12px;font-style:italic}.selection-note{padding:10px 12px;border-left:2px solid var(--accent);background:var(--panel);color:var(--muted);font-size:11px;margin-top:18px;line-height:1.8}.radar{position:absolute;right:340px;bottom:42px;width:190px;height:135px;border:1px solid var(--line);border-radius:10px;background:var(--panel);box-shadow:var(--shadow);z-index:2;overflow:hidden}.radar-label{position:absolute;left:10px;top:7px;font-size:9px;letter-spacing:1.5px;color:var(--muted);pointer-events:none}.radar canvas{width:100%;height:100%;cursor:crosshair}.statusbar{position:absolute;bottom:0;left:0;right:320px;height:27px;border-top:1px solid var(--line);background:var(--bg);display:flex;align-items:center;gap:18px;padding:0 18px;color:var(--muted);font:10px monospace;z-index:2}.statusbar .spacer{flex:1}.status-indicator{display:inline-block;width:5px;height:5px;border-radius:50%;background:var(--accent);margin-right:6px}.toast{position:absolute;left:50%;bottom:46px;transform:translateX(-50%);max-width:500px;padding:10px 18px;background:var(--panel);color:var(--text);border:1px solid var(--line);border-radius:10px;box-shadow:var(--shadow);z-index:6;display:none;font-size:12px}.toast.open{display:block}.loading{position:absolute;inset:0 320px 0 0;display:grid;place-items:center;background:var(--canvas);z-index:5}.loading-card{max-width:460px;padding:28px;text-align:center}.loading-card strong{font-size:19px;display:block;margin:14px}.loading-card p{color:var(--muted);line-height:1.8}.spinner{width:32px;height:32px;border:2px solid var(--line);border-top-color:var(--accent);border-radius:50%;animation:spin 1s linear infinite;margin:auto}@keyframes spin{to{transform:rotate(360deg)}}dialog{color:var(--text);background:var(--panel);border:1px solid var(--line);border-radius:15px;padding:26px;max-width:540px;box-shadow:var(--shadow)}dialog::backdrop{background:#0008}dialog h2{margin:0 0 15px;font-size:20px}dialog p{color:var(--muted);line-height:1.8}dialog kbd{border:1px solid var(--line);border-radius:4px;padding:1px 5px;color:var(--text)}.help-row{display:flex;justify-content:space-between;gap:30px;padding:8px 0;border-bottom:1px solid var(--line)}.help-row span{color:var(--muted)}.help-close{margin-top:20px;float:right}.cluster-note{color:var(--amber);font-size:12px;padding:10px;background:var(--panel);border:1px solid var(--line);border-radius:8px;margin-top:14px}
|
|
17
|
+
@media(max-width:1180px){header{padding:0 16px;gap:12px}.metric{padding:7px 10px}.metric span{font-size:10px}.version{display:none}.toolbar{gap:6px;left:16px}#search{width:220px}.controls button{padding:8px}.utilities{left:16px}.brand strong{font-size:16px}}
|
|
18
|
+
@media(max-width:960px){.metric:nth-child(4),.metric:nth-child(5){display:none}.header-actions select{width:80px}#sidebar{width:270px}#cy,.loading{right:270px}.radar{right:286px;width:155px;height:110px}.statusbar{right:270px}.toolbar{flex-wrap:wrap;right:285px}.controls button{height:36px}.utilities{top:122px}#search{width:230px}.legend{bottom:42px;padding:10px;min-width:145px}}
|
|
19
|
+
@media(max-width:700px){header{height:62px;gap:8px}.brand strong{font-size:14px}.logo{width:27px;height:27px;font-size:18px}.metrics{margin-left:auto;margin-right:0}.metric{padding:5px 9px}.metric:nth-child(n+3){display:none}.metric span{display:none}.header-actions select{width:70px;font-size:11px;padding:6px}.header-actions button{padding:6px 9px}.workspace{height:calc(100vh - 62px)}#sidebar{top:auto;bottom:27px;width:100%;height:190px;border-left:0;border-top:1px solid var(--line)}.side-top{padding:12px 16px}.side-body{padding:12px 16px}.side-body .empty-icon,.side-body .hint-list,.side-body .repo-path{display:none}.empty-title{font-size:14px}#cy,.loading{right:0;bottom:217px}.statusbar{right:0;font-size:9px;gap:8px}.radar{right:14px;bottom:232px;width:135px;height:95px}.legend{bottom:232px;font-size:10px;min-width:120px;padding:9px}.legend .legend-separator,.legend .chain-key{display:none}.legend-row{font-size:10px;margin-top:4px}.toolbar{right:14px;left:14px;top:14px;flex-wrap:nowrap}#search{width:190px;padding-right:12px}.search-wrap .key{display:none}.search-results{width:280px}.utilities{top:68px;left:14px}.controls{margin-left:auto}.controls button{font-size:11px}.stats-grid{grid-template-columns:repeat(4,1fr);margin:12px 0}.stat-card{padding:8px}.stat-card b{font-size:16px}.toast{bottom:225px;width:80%}}
|
|
20
|
+
@media(prefers-reduced-motion:reduce){*{animation:none!important;transition:none!important}}
|
|
21
|
+
</style>
|
|
22
|
+
</head>
|
|
23
|
+
<body>
|
|
24
|
+
<header>
|
|
25
|
+
<div class="brand"><div class="logo" aria-hidden="true">β</div><strong>repograph-cli</strong><span class="version">v0.1.1</span></div>
|
|
26
|
+
<div class="metrics" aria-label="Repository metrics" id="metrics"></div>
|
|
27
|
+
<div class="header-actions"><select id="theme" aria-label="Color theme"><option value="dark">Dark</option><option value="light">Light</option><option value="matrix">Matrix</option></select><button id="help-button" aria-label="Help and keyboard shortcuts">?</button></div>
|
|
28
|
+
</header>
|
|
29
|
+
<main class="workspace">
|
|
30
|
+
<div id="cy" role="application" aria-label="Interactive repository architecture graph"></div>
|
|
31
|
+
<div class="toolbar"><div class="search-wrap"><label for="search" hidden>Find files</label><input id="search" autocomplete="off" spellcheck="false" placeholder="Find a file or pathβ¦"><span class="key">/</span><div class="search-results" id="search-results"></div></div><div class="controls"><button id="relayout" title="Run force-directed layout again">Re-layout</button><button id="fit" title="Fit visible graph (F)">Fit</button></div></div>
|
|
32
|
+
<label class="utilities"><input type="checkbox" id="show-utils">Show utilities <strong id="folded-count">0</strong></label>
|
|
33
|
+
<div class="legend"><div class="eyebrow">Architecture layers</div><div id="layer-legend"></div><div class="legend-separator"></div><div class="legend-row chain-key"><span class="line-key in"></span>Incoming callers</div><div class="legend-row chain-key"><span class="line-key out"></span>Outgoing dependencies</div></div>
|
|
34
|
+
<aside id="sidebar" aria-label="File inspector"><div class="side-top"><h1 class="side-title">Architecture explorer</h1><p class="side-sub">Follow the connections in your code.</p></div><div class="side-body" id="details"></div></aside>
|
|
35
|
+
<div class="radar"><span class="radar-label">OVERVIEW</span><canvas id="minimap" aria-label="Graph overview; click to pan"></canvas></div>
|
|
36
|
+
<footer class="statusbar"><span><i class="status-indicator"></i><span id="status">Preparing graph</span></span><span id="zoom">100%</span><span class="spacer"></span><span id="generated"></span><span>LOCAL SNAPSHOT</span></footer>
|
|
37
|
+
<div id="loading" class="loading"><div class="loading-card"><div class="spinner"></div><strong>Mapping your codebase</strong><p id="loading-message">Loading the graph engine and arranging your architectureβ¦</p></div></div>
|
|
38
|
+
<div id="toast" class="toast" role="status" aria-live="polite"></div>
|
|
39
|
+
</main>
|
|
40
|
+
<dialog id="help"><h2>Explore your architecture</h2><p>Each dot is a source file. Arrows point from a caller to its dependency. Boxes group files by their first two directory levels.</p><div class="help-row"><span>Search file paths</span><kbd>/</kbd></div><div class="help-row"><span>Fit visible graph</span><kbd>F</kbd></div><div class="help-row"><span>Reset selection and search</span><kbd>Esc</kbd></div><div class="help-row"><span>Inspect dependencies and callers</span><kbd>Click a file</kbd></div><div class="help-row"><span>Collapse or expand a directory</span><kbd>Double-click a box</kbd></div><p>Cyan shows the incoming caller chain. Red shows the outgoing dependency chain. A file can belong to both chains when imports form a cycle. Dead-code warnings are heuristic: framework entry points and dynamically loaded modules may have no static callers.</p><p>Utilities remain part of the saved graph and impact queries. Use the utilities toggle to reveal them. This page uses a frozen scan; run RepoGraph again to refresh it.</p><button class="help-close" id="help-close">Got it</button></dialog>
|
|
41
|
+
<script id="graph-data" type="application/json">${json}</script>
|
|
42
|
+
<script src="https://cdnjs.cloudflare.com/ajax/libs/cytoscape/3.30.4/cytoscape.min.js"></script>
|
|
43
|
+
<script src="https://cdn.jsdelivr.net/npm/layout-base@2.0.1/layout-base.js"></script>
|
|
44
|
+
<script src="https://cdn.jsdelivr.net/npm/cose-base@2.2.0/cose-base.js"></script>
|
|
45
|
+
<script src="https://cdn.jsdelivr.net/npm/cytoscape-fcose@2.2.0/cytoscape-fcose.js"></script>
|
|
46
|
+
<script>
|
|
47
|
+
(() => {
|
|
48
|
+
'use strict';
|
|
49
|
+
const graph = JSON.parse(document.getElementById('graph-data').textContent);
|
|
50
|
+
const colors = ${JSON.stringify(LAYER_COLORS)};
|
|
51
|
+
const $ = id => document.getElementById(id);
|
|
52
|
+
const nodesById = new Map(graph.nodes.map(node => [node.id, node]));
|
|
53
|
+
const clustersById = new Map(graph.clusters.map(cluster => [cluster.id, cluster]));
|
|
54
|
+
const incoming = new Map(graph.nodes.map(node => [node.id, new Set()]));
|
|
55
|
+
const outgoing = new Map(graph.nodes.map(node => [node.id, new Set()]));
|
|
56
|
+
graph.edges.forEach(edge => { incoming.get(edge.target)?.add(edge.source); outgoing.get(edge.source)?.add(edge.target); });
|
|
57
|
+
const collapsed = new Set();
|
|
58
|
+
const savedPositions = new Map();
|
|
59
|
+
const clusterPositions = new Map();
|
|
60
|
+
let selectedId = null;
|
|
61
|
+
let cy, layout, radarTransform, framePending = false, toastTimer;
|
|
62
|
+
const reducedMotion = window.matchMedia('(prefers-reduced-motion: reduce)').matches;
|
|
63
|
+
const css = name => getComputedStyle(document.documentElement).getPropertyValue(name).trim();
|
|
64
|
+
const element = (tag, className, text) => { const el = document.createElement(tag); if (className) el.className = className; if (text !== undefined) el.textContent = text; return el; };
|
|
65
|
+
function toast(message) { $('toast').textContent = message; $('toast').classList.add('open'); clearTimeout(toastTimer); toastTimer = setTimeout(() => $('toast').classList.remove('open'), 3000); }
|
|
66
|
+
function metric(value, label, warning) { const item = element('div', 'metric' + (warning ? ' warning' : '')); item.append(element('b', '', String(value)), element('span', '', label)); $('metrics').append(item); }
|
|
67
|
+
metric(graph.metrics.totalFiles, 'Total files'); metric(graph.metrics.totalEdges, 'Edges'); metric(graph.metrics.couplingFactor.toFixed(2), 'Coupling factor'); metric(graph.metrics.deadCodeCount, 'Dead-code warnings', true); metric(graph.metrics.foldedUtilityCount, 'Folded utilities');
|
|
68
|
+
$('folded-count').textContent = graph.metrics.foldedUtilityCount;
|
|
69
|
+
$('generated').textContent = new Date(graph.generatedAt).toLocaleString();
|
|
70
|
+
$('theme').value = document.documentElement.dataset.theme;
|
|
71
|
+
for (const [layer, color] of Object.entries(colors)) {
|
|
72
|
+
const row = element('div', 'legend-row'); const dot = element('span', 'dot'); dot.style.background = color;
|
|
73
|
+
row.append(dot, element('span', '', layer.charAt(0).toUpperCase() + layer.slice(1)), element('small', '', String(graph.nodes.filter(node => node.layer === layer).length)));
|
|
74
|
+
$('layer-legend').append(row);
|
|
75
|
+
}
|
|
76
|
+
function emptyInspector() {
|
|
77
|
+
$('details').replaceChildren();
|
|
78
|
+
$('details').append(element('div', 'empty-icon', 'β'), element('div', 'empty-title', 'Find the center of change'), element('p', 'hint', 'Select a source file to trace its callers, dependencies, and blast radius.'));
|
|
79
|
+
const list = element('ul', 'hint-list');
|
|
80
|
+
['Search uses subsequence matching across full paths.', 'Double-click a directory box or collapsed node to collapse or expand.', 'Press F to fit the graph.', 'Drag nodes to arrange your map; scroll to zoom.', 'Click the background to clear a selection.'].forEach(text => list.append(element('li', '', text)));
|
|
81
|
+
$('details').append(list, element('div', 'repo-path', graph.rootPath + '\\n' + graph.nodes.length + ' source files Β· ' + (graph.metrics.excludedTestFiles || 0) + ' test files excluded'));
|
|
82
|
+
}
|
|
83
|
+
emptyInspector();
|
|
84
|
+
if (typeof cytoscape === 'undefined') { $('loading-message').textContent = 'The CDN graph engine could not load. Connect to the internet and reopen this file. All repository data is embedded in this HTML.'; document.querySelector('.spinner').style.display = 'none'; return; }
|
|
85
|
+
function styleSheet() {
|
|
86
|
+
return [
|
|
87
|
+
{ selector: 'node.file', style: { 'background-color': 'data(color)', 'label': 'data(label)', 'color': css('--text'), 'font-size': 10, 'font-family': 'system-ui, sans-serif', 'text-valign': 'bottom', 'text-margin-y': 7, 'text-outline-color': css('--canvas'), 'text-outline-width': 2, 'width': 'data(size)', 'height': 'data(size)', 'border-width': 1.5, 'border-color': 'data(color)', 'border-opacity': .3, 'background-opacity': .9, 'overlay-opacity': 0, 'min-zoomed-font-size': 5 } },
|
|
88
|
+
{ selector: 'node.cluster', style: { 'shape': 'round-rectangle', 'background-color': css('--panel'), 'background-opacity': .24, 'border-width': 1, 'border-color': css('--line'), 'border-style': 'solid', 'label': 'data(label)', 'color': css('--muted'), 'font-size': 12, 'font-weight': 600, 'text-valign': 'top', 'text-halign': 'left', 'text-margin-x': 12, 'text-margin-y': 9, 'padding': 28, 'compound-sizing-wrt-labels': 'include', 'overlay-opacity': 0 } },
|
|
89
|
+
{ selector: 'node.meta', style: { 'shape': 'round-rectangle', 'width': 125, 'height': 48, 'background-color': css('--panel'), 'background-opacity': 1, 'border-color': css('--accent'), 'border-width': 1.5, 'label': 'data(label)', 'color': css('--text'), 'font-size': 11, 'text-wrap': 'wrap', 'text-valign': 'center', 'text-halign': 'center', 'text-margin-y': 0 } },
|
|
90
|
+
{ selector: 'edge', style: { 'curve-style': 'bezier', 'width': 1.2, 'line-color': css('--muted'), 'target-arrow-color': css('--muted'), 'target-arrow-shape': 'triangle', 'arrow-scale': .65, 'opacity': .4, 'overlay-opacity': 0 } },
|
|
91
|
+
{ selector: 'edge[type = "dynamic"]', style: { 'line-style': 'dashed' } },
|
|
92
|
+
{ selector: 'edge[type = "inheritance"]', style: { 'width': 2.2, 'target-arrow-shape': 'triangle-backcurve' } },
|
|
93
|
+
{ selector: '.dim', style: { 'opacity': .15 } },
|
|
94
|
+
{ selector: '.search-dim', style: { 'opacity': .15 } },
|
|
95
|
+
{ selector: 'node.incoming', style: { 'background-color': css('--incoming'), 'border-color': css('--incoming'), 'opacity': 1 } },
|
|
96
|
+
{ selector: 'edge.incoming', style: { 'line-color': css('--incoming'), 'target-arrow-color': css('--incoming'), 'width': 2, 'opacity': .9 } },
|
|
97
|
+
{ selector: 'node.outgoing', style: { 'background-color': css('--outgoing'), 'border-color': css('--outgoing'), 'opacity': 1 } },
|
|
98
|
+
{ selector: 'edge.outgoing', style: { 'line-color': css('--outgoing'), 'target-arrow-color': css('--outgoing'), 'width': 2, 'opacity': .9 } },
|
|
99
|
+
{ selector: 'node.focus', style: { 'border-width': 4, 'border-color': css('--text'), 'background-color': css('--accent'), 'width': 30, 'height': 30, 'font-weight': 700, 'font-size': 12, 'opacity': 1 } },
|
|
100
|
+
{ selector: '.hidden', style: { 'display': 'none' } }
|
|
101
|
+
];
|
|
102
|
+
}
|
|
103
|
+
const elements = graph.clusters.map(cluster => ({ data: { id: cluster.id, label: cluster.label, ...(cluster.parent ? { parent: cluster.parent } : {}) }, classes: 'cluster' }));
|
|
104
|
+
graph.nodes.forEach(node => elements.push({ data: { ...node, parent: node.cluster, color: colors[node.layer], size: Math.min(28, 14 + Math.sqrt(node.inDegree + node.outDegree) * 2) }, classes: 'file' }));
|
|
105
|
+
graph.edges.forEach((edge, i) => elements.push({ data: { ...edge, id: 'edge:' + i } }));
|
|
106
|
+
cy = cytoscape({ container: $('cy'), elements, style: styleSheet(), layout: { name: 'preset' }, wheelSensitivity: .2, minZoom: .03, maxZoom: 4, boxSelectionEnabled: false, autounselectify: true });
|
|
107
|
+
function clusterContains(clusterId, node) {
|
|
108
|
+
let current = node.cluster;
|
|
109
|
+
while (current) { if (current === clusterId) return true; current = clustersById.get(current)?.parent; }
|
|
110
|
+
return false;
|
|
111
|
+
}
|
|
112
|
+
function visibleRepresentative(nodeId) {
|
|
113
|
+
const node = nodesById.get(nodeId); if (!node || (node.isFolded && !$('show-utils').checked)) return null;
|
|
114
|
+
let current = node.cluster, representative = nodeId;
|
|
115
|
+
while (current) { if (collapsed.has(current)) representative = 'meta:' + current; current = clustersById.get(current)?.parent; }
|
|
116
|
+
return representative;
|
|
117
|
+
}
|
|
118
|
+
function refreshVisibility() {
|
|
119
|
+
cy.nodes('.meta').forEach(node => clusterPositions.set(node.data('clusterId'), { ...node.position() }));
|
|
120
|
+
cy.batch(() => {
|
|
121
|
+
cy.elements('.meta, .meta-edge').remove();
|
|
122
|
+
cy.elements().removeClass('hidden');
|
|
123
|
+
graph.nodes.forEach(node => { if (visibleRepresentative(node.id) !== node.id) cy.getElementById(node.id).addClass('hidden'); });
|
|
124
|
+
for (const cluster of graph.clusters) {
|
|
125
|
+
let ancestor = cluster.parent, hidden = collapsed.has(cluster.id);
|
|
126
|
+
while (ancestor) { hidden = hidden || collapsed.has(ancestor); ancestor = clustersById.get(ancestor)?.parent; }
|
|
127
|
+
if (hidden) cy.getElementById(cluster.id).addClass('hidden');
|
|
128
|
+
}
|
|
129
|
+
for (const id of collapsed) {
|
|
130
|
+
const cluster = clustersById.get(id); let ancestor = cluster.parent, obscured = false;
|
|
131
|
+
while (ancestor) { if (collapsed.has(ancestor)) obscured = true; ancestor = clustersById.get(ancestor)?.parent; }
|
|
132
|
+
if (obscured) continue;
|
|
133
|
+
const children = graph.nodes.filter(node => clusterContains(id, node) && (!node.isFolded || $('show-utils').checked));
|
|
134
|
+
if (!children.length) continue;
|
|
135
|
+
const position = clusterPositions.get(id) || { x: 0, y: 0 };
|
|
136
|
+
cy.add({ data: { id: 'meta:' + id, clusterId: id, label: cluster.label + ' Β· ' + children.length + ' files', ...(cluster.parent ? { parent: cluster.parent } : {}) }, classes: 'meta', position });
|
|
137
|
+
}
|
|
138
|
+
const metaEdges = new Set();
|
|
139
|
+
graph.edges.forEach((edge, i) => {
|
|
140
|
+
const a = visibleRepresentative(edge.source), b = visibleRepresentative(edge.target);
|
|
141
|
+
if (a !== edge.source || b !== edge.target) cy.getElementById('edge:' + i).addClass('hidden');
|
|
142
|
+
if (!a || !b || a === b || (a === edge.source && b === edge.target)) return;
|
|
143
|
+
const key = a + '\\0' + b;
|
|
144
|
+
if (!metaEdges.has(key) && cy.getElementById(a).length && cy.getElementById(b).length) { metaEdges.add(key); cy.add({ data: { id: 'meta-edge:' + i, source: a, target: b, type: edge.type }, classes: 'meta-edge' }); }
|
|
145
|
+
});
|
|
146
|
+
// Hide empty compound boxes after utility filtering.
|
|
147
|
+
[...graph.clusters].reverse().forEach(cluster => { const el = cy.getElementById(cluster.id); if (!el.descendants().nodes().filter(n => !n.hasClass('cluster') && !n.hasClass('hidden')).length) el.addClass('hidden'); });
|
|
148
|
+
});
|
|
149
|
+
if (selectedId) highlight(selectedId);
|
|
150
|
+
applySearch(); updateStatus(); scheduleRadar();
|
|
151
|
+
}
|
|
152
|
+
function runLayout() {
|
|
153
|
+
if (layout) layout.stop();
|
|
154
|
+
$('relayout').disabled = true;
|
|
155
|
+
const visible = cy.elements().filter(el => !el.hasClass('hidden'));
|
|
156
|
+
const useFcose = typeof cytoscapeFcose !== 'undefined';
|
|
157
|
+
cy.one('layoutstop', () => { cy.fit(undefined, 40); scheduleRadar(); updateStatus(); });
|
|
158
|
+
layout = visible.layout({ name: useFcose ? 'fcose' : 'cose', quality: 'default', animate: false, randomize: true, fit: false, padding: 40, nodeDimensionsIncludeLabels: true, nodeRepulsion: () => 6500, idealEdgeLength: () => 95, edgeElasticity: () => .35, gravity: .22, numIter: 2000, tile: true, packComponents: true, stop: () => { $('relayout').disabled = false; $('loading').style.display = 'none'; scheduleRadar(); updateStatus(); } });
|
|
159
|
+
try { layout.run(); } catch (error) { $('relayout').disabled = false; $('loading').style.display = 'none'; visible.layout({ name: 'grid', fit: true, padding: 65 }).run(); toast('Force layout unavailable; showing a grid.'); console.error(error); }
|
|
160
|
+
}
|
|
161
|
+
function chain(start, adjacency) {
|
|
162
|
+
const visited = new Set([start]), queue = [start];
|
|
163
|
+
for (let i = 0; i < queue.length; i++) for (const id of adjacency.get(queue[i]) || []) if (!visited.has(id)) { visited.add(id); queue.push(id); }
|
|
164
|
+
return visited;
|
|
165
|
+
}
|
|
166
|
+
function highlight(id) {
|
|
167
|
+
cy.elements().removeClass('dim incoming outgoing focus');
|
|
168
|
+
const callers = chain(id, incoming), dependencies = chain(id, outgoing);
|
|
169
|
+
cy.elements().not('.cluster').addClass('dim');
|
|
170
|
+
function mark(ids, name) {
|
|
171
|
+
ids.forEach(key => { const rep = visibleRepresentative(key); if (rep) cy.getElementById(rep).removeClass('dim').addClass(name); });
|
|
172
|
+
graph.edges.forEach((edge, i) => {
|
|
173
|
+
if (!ids.has(edge.source) || !ids.has(edge.target)) return;
|
|
174
|
+
cy.getElementById('edge:' + i).removeClass('dim').addClass(name);
|
|
175
|
+
const a = visibleRepresentative(edge.source), b = visibleRepresentative(edge.target);
|
|
176
|
+
cy.edges('.meta-edge').filter(el => el.data('source') === a && el.data('target') === b).removeClass('dim').addClass(name);
|
|
177
|
+
});
|
|
178
|
+
}
|
|
179
|
+
mark(callers, 'incoming'); mark(dependencies, 'outgoing');
|
|
180
|
+
const rep = visibleRepresentative(id); if (rep) cy.getElementById(rep).removeClass('dim').addClass('focus');
|
|
181
|
+
scheduleRadar();
|
|
182
|
+
}
|
|
183
|
+
function showNode(id, center) {
|
|
184
|
+
const node = nodesById.get(id); if (!node) return;
|
|
185
|
+
selectedId = id; highlight(id); inspector(node);
|
|
186
|
+
if (center) { const rep = visibleRepresentative(id); if (rep) cy.animate({ center: { eles: cy.getElementById(rep) }, duration: reducedMotion ? 0 : 250 }); else toast('This utility is folded. Enable Show utilities to reveal it.'); }
|
|
187
|
+
}
|
|
188
|
+
function inspector(node) {
|
|
189
|
+
const details = $('details'); details.replaceChildren();
|
|
190
|
+
details.append(element('p', 'file-path', node.id));
|
|
191
|
+
const badge = element('span', 'badge'); const dot = element('span', 'dot'); dot.style.background = colors[node.layer]; badge.append(dot, document.createTextNode(node.layer)); details.append(badge, element('span', 'badge', node.language || 'Source'));
|
|
192
|
+
const grid = element('div', 'stats-grid');
|
|
193
|
+
[[node.inDegree, 'Callers'], [node.outDegree, 'Dependencies'], [node.linesOfCode, 'LOC'], [chain(node.id, incoming).size - 1, 'Blast radius']].forEach(([value, label]) => { const card = element('div', 'stat-card'); card.append(element('b', '', String(value)), element('span', '', label)); grid.append(card); });
|
|
194
|
+
details.append(grid);
|
|
195
|
+
details.append(element('div', 'hint', 'Cluster: ' + node.cluster.replace(/^cluster:/, '')));
|
|
196
|
+
if (node.isFolded) details.append(element('div', 'cluster-note', 'Utility candidate Β· folded until Show utilities is enabled.'));
|
|
197
|
+
if (!node.inDegree) details.append(element('div', 'selection-note', node.layer === 'entry' ? 'Entry-like file Β· no static callers.' : 'No static callers found. This may be unused code or an implicit runtime entry point.'));
|
|
198
|
+
function fileList(title, ids) {
|
|
199
|
+
const heading = element('div', 'detail-heading'); heading.append(element('span', '', title), element('span', '', String(ids.size))); details.append(heading);
|
|
200
|
+
const list = element('div', 'file-list');
|
|
201
|
+
[...ids].sort().forEach(id => { const target = nodesById.get(id); const button = element('button', 'file-link'); const dot = element('span', 'dot'); dot.style.background = colors[target.layer]; button.append(dot, element('span', '', id)); button.addEventListener('click', () => showNode(id, true)); list.append(button); });
|
|
202
|
+
if (!ids.size) list.append(element('div', 'no-items', 'None found'));
|
|
203
|
+
details.append(list);
|
|
204
|
+
}
|
|
205
|
+
fileList('Incoming callers', incoming.get(node.id)); fileList('Dependencies', outgoing.get(node.id));
|
|
206
|
+
details.append(element('div', 'selection-note', 'Highlight follows the full transitive graph. Sidebar lists direct connections. Red = dependency chain; cyan = caller chain.'));
|
|
207
|
+
}
|
|
208
|
+
function reset() { selectedId = null; cy.elements().removeClass('dim incoming outgoing focus'); emptyInspector(); scheduleRadar(); }
|
|
209
|
+
function fuzzy(query, value) { let index = 0; for (const char of value.toLowerCase()) if (char === query[index]) index++; return index === query.length; }
|
|
210
|
+
function applySearch() {
|
|
211
|
+
const query = $('search').value.trim().toLowerCase();
|
|
212
|
+
cy.elements().removeClass('search-dim');
|
|
213
|
+
const results = $('search-results'); results.replaceChildren(); results.classList.toggle('open', Boolean(query));
|
|
214
|
+
if (!query) return;
|
|
215
|
+
const matches = graph.nodes.filter(node => fuzzy(query, node.id));
|
|
216
|
+
const matchIds = new Set(matches.map(node => node.id));
|
|
217
|
+
const visibleIds = new Set(matches.map(node => visibleRepresentative(node.id)).filter(Boolean));
|
|
218
|
+
cy.nodes().not('.cluster').forEach(node => { if (!visibleIds.has(node.id())) node.addClass('search-dim'); });
|
|
219
|
+
cy.edges().forEach(edge => { if (!matchIds.has(edge.data('source')) && !matchIds.has(edge.data('target'))) edge.addClass('search-dim'); });
|
|
220
|
+
results.append(element('div', 'search-caption', matches.length + ' matching files' + (matches.length > 25 ? ' Β· showing first 25' : '')));
|
|
221
|
+
matches.slice(0, 25).forEach(node => { const button = element('button', 'search-result', node.id + (node.isFolded && !$('show-utils').checked ? ' (folded)' : '')); button.addEventListener('click', () => { showNode(node.id, true); results.classList.remove('open'); }); results.append(button); });
|
|
222
|
+
scheduleRadar();
|
|
223
|
+
}
|
|
224
|
+
function toggleCluster(id) {
|
|
225
|
+
if (collapsed.has(id)) {
|
|
226
|
+
collapsed.delete(id);
|
|
227
|
+
refreshVisibility();
|
|
228
|
+
const positions = savedPositions.get(id);
|
|
229
|
+
if (positions) cy.batch(() => positions.forEach((position, key) => cy.getElementById(key).position(position)));
|
|
230
|
+
savedPositions.delete(id);
|
|
231
|
+
} else {
|
|
232
|
+
const children = cy.nodes('.file').filter(node => clusterContains(id, nodesById.get(node.id())));
|
|
233
|
+
savedPositions.set(id, new Map(children.map(node => [node.id(), { ...node.position() }])));
|
|
234
|
+
const visible = children.filter(node => !node.hasClass('hidden'));
|
|
235
|
+
const points = visible.length ? visible : children;
|
|
236
|
+
clusterPositions.set(id, { x: points.reduce((sum, node) => sum + node.position('x'), 0) / Math.max(points.length, 1), y: points.reduce((sum, node) => sum + node.position('y'), 0) / Math.max(points.length, 1) });
|
|
237
|
+
collapsed.add(id);
|
|
238
|
+
refreshVisibility();
|
|
239
|
+
}
|
|
240
|
+
scheduleRadar(); updateStatus(); toast((collapsed.has(id) ? 'Collapsed ' : 'Expanded ') + clustersById.get(id).label);
|
|
241
|
+
}
|
|
242
|
+
cy.on('dbltap', 'node.cluster, node.meta', event => {
|
|
243
|
+
const target = event.target;
|
|
244
|
+
toggleCluster(target.hasClass('meta') ? target.data('clusterId') : target.id());
|
|
245
|
+
});
|
|
246
|
+
cy.on('tap', 'node.file', event => {
|
|
247
|
+
showNode(event.target.id(), false); $('search-results').classList.remove('open');
|
|
248
|
+
});
|
|
249
|
+
cy.on('tap', event => { if (event.target === cy) { reset(); $('search-results').classList.remove('open'); } });
|
|
250
|
+
function updateStatus() { $('status').textContent = cy.nodes('.file').filter(node => !node.hasClass('hidden')).length + ' files visible Β· ' + collapsed.size + ' collapsed'; $('zoom').textContent = Math.round(cy.zoom() * 100) + '%'; }
|
|
251
|
+
function scheduleRadar() { if (framePending) return; framePending = true; requestAnimationFrame(() => { framePending = false; drawRadar(); }); }
|
|
252
|
+
function drawRadar() {
|
|
253
|
+
const canvas = $('minimap'), rect = canvas.getBoundingClientRect(), dpr = window.devicePixelRatio || 1;
|
|
254
|
+
canvas.width = Math.round(rect.width * dpr); canvas.height = Math.round(rect.height * dpr);
|
|
255
|
+
const context = canvas.getContext('2d'); context.scale(dpr, dpr); context.clearRect(0, 0, rect.width, rect.height);
|
|
256
|
+
const visible = cy.nodes().filter(node => !node.hasClass('cluster') && !node.hasClass('hidden'));
|
|
257
|
+
if (!visible.length) return;
|
|
258
|
+
const bounds = visible.boundingBox({ includeLabels: false, includeOverlays: false }), padding = 16;
|
|
259
|
+
const scale = Math.min((rect.width - padding * 2) / Math.max(bounds.w, 1), (rect.height - padding * 2 - 10) / Math.max(bounds.h, 1));
|
|
260
|
+
const offsetX = (rect.width - bounds.w * scale) / 2 - bounds.x1 * scale, offsetY = (rect.height - bounds.h * scale) / 2 - bounds.y1 * scale + 6;
|
|
261
|
+
radarTransform = { scale, offsetX, offsetY };
|
|
262
|
+
const point = node => ({ x: node.position('x') * scale + offsetX, y: node.position('y') * scale + offsetY });
|
|
263
|
+
context.strokeStyle = css('--muted'); context.globalAlpha = .18; context.lineWidth = .6;
|
|
264
|
+
cy.edges().filter(edge => !edge.hasClass('hidden')).forEach(edge => { const a = point(edge.source()), b = point(edge.target()); context.beginPath(); context.moveTo(a.x, a.y); context.lineTo(b.x, b.y); context.stroke(); });
|
|
265
|
+
visible.forEach(node => { const p = point(node); context.globalAlpha = node.hasClass('dim') || node.hasClass('search-dim') ? .2 : .9; context.fillStyle = node.hasClass('focus') ? css('--text') : node.data('color') || css('--accent'); context.beginPath(); context.arc(p.x, p.y, node.hasClass('focus') ? 2.7 : 1.8, 0, Math.PI * 2); context.fill(); });
|
|
266
|
+
const extent = cy.extent(); context.globalAlpha = .8; context.strokeStyle = css('--accent'); context.lineWidth = 1;
|
|
267
|
+
context.strokeRect(extent.x1 * scale + offsetX, extent.y1 * scale + offsetY, extent.w * scale, extent.h * scale); context.globalAlpha = 1;
|
|
268
|
+
}
|
|
269
|
+
$('minimap').addEventListener('click', event => { if (!radarTransform) return; const rect = $('minimap').getBoundingClientRect(), t = radarTransform; const x = (event.clientX - rect.left - t.offsetX) / t.scale, y = (event.clientY - rect.top - t.offsetY) / t.scale; cy.pan({ x: cy.width() / 2 - x * cy.zoom(), y: cy.height() / 2 - y * cy.zoom() }); });
|
|
270
|
+
cy.on('pan zoom position layoutstop', () => { scheduleRadar(); updateStatus(); });
|
|
271
|
+
let userAdjusted = false;
|
|
272
|
+
$('cy').addEventListener('wheel', () => { userAdjusted = true; }, { passive: true });
|
|
273
|
+
$('cy').addEventListener('pointerdown', () => { userAdjusted = true; });
|
|
274
|
+
new ResizeObserver(() => { cy.resize(); if (!userAdjusted && cy.nodes().length) cy.fit(undefined, 40); scheduleRadar(); }).observe($('cy'));
|
|
275
|
+
$('show-utils').addEventListener('change', () => { refreshVisibility(); runLayout(); });
|
|
276
|
+
$('search').addEventListener('input', applySearch);
|
|
277
|
+
$('search').addEventListener('focus', applySearch);
|
|
278
|
+
$('search').addEventListener('keydown', event => { if (event.key === 'Enter') { const first = $('search-results').querySelector('button'); if (first) first.click(); } });
|
|
279
|
+
$('relayout').addEventListener('click', runLayout);
|
|
280
|
+
function fit() { cy.fit(undefined, 40); scheduleRadar(); }
|
|
281
|
+
$('fit').addEventListener('click', fit);
|
|
282
|
+
$('theme').addEventListener('change', () => { document.documentElement.dataset.theme = $('theme').value; cy.style(styleSheet()); scheduleRadar(); });
|
|
283
|
+
$('help-button').addEventListener('click', () => $('help').showModal());
|
|
284
|
+
$('help-close').addEventListener('click', () => $('help').close());
|
|
285
|
+
document.addEventListener('keydown', event => {
|
|
286
|
+
const typing = /INPUT|TEXTAREA|SELECT/.test(document.activeElement.tagName);
|
|
287
|
+
if (event.key === '/' && !typing) { event.preventDefault(); $('search').focus(); }
|
|
288
|
+
if (event.key.toLowerCase() === 'f' && !typing) fit();
|
|
289
|
+
if (event.key === 'Escape') { $('search').value = ''; applySearch(); $('search').blur(); reset(); }
|
|
290
|
+
});
|
|
291
|
+
if (!graph.nodes.length) { $('loading').style.display = 'none'; toast('No source files found. Check the scan path, ignore rules, and maximum depth.'); }
|
|
292
|
+
refreshVisibility(); if (graph.nodes.length) runLayout();
|
|
293
|
+
})();
|
|
294
|
+
</script>
|
|
295
|
+
</body>
|
|
296
|
+
</html>`;
|
|
297
|
+
}
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
import { LAYER_COLORS } from '../core/cluster.js';
|
|
2
|
+
const xml = (text) => text.replace(/[&<>"']/g, c => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' })[c]);
|
|
3
|
+
export function renderToMermaid(graph) {
|
|
4
|
+
const ids = new Map(graph.nodes.map((node, i) => [node.id, 'n' + i]));
|
|
5
|
+
const clusters = new Map(graph.clusters.map((cluster, i) => [cluster.id, 'c' + i]));
|
|
6
|
+
const lines = ['graph LR'];
|
|
7
|
+
function group(id, depth) {
|
|
8
|
+
const cluster = graph.clusters.find(item => item.id === id);
|
|
9
|
+
const indent = ' '.repeat(depth);
|
|
10
|
+
lines.push(indent + 'subgraph ' + clusters.get(id) + '["' + xml(cluster.label) + '"]');
|
|
11
|
+
for (const child of graph.clusters.filter(item => item.parent === id))
|
|
12
|
+
group(child.id, depth + 1);
|
|
13
|
+
for (const node of graph.nodes.filter(item => item.cluster === id))
|
|
14
|
+
lines.push(indent + ' ' + ids.get(node.id) + '["' + xml(node.id) + '"]');
|
|
15
|
+
lines.push(indent + 'end');
|
|
16
|
+
}
|
|
17
|
+
for (const cluster of graph.clusters.filter(item => !item.parent))
|
|
18
|
+
group(cluster.id, 1);
|
|
19
|
+
for (const edge of graph.edges)
|
|
20
|
+
lines.push(' ' + ids.get(edge.source) + (edge.type === 'dynamic' ? ' -.-> ' : edge.type === 'inheritance' ? ' ==>|extends| ' : ' --> ') + ids.get(edge.target));
|
|
21
|
+
return lines.join('\n') + '\n';
|
|
22
|
+
}
|
|
23
|
+
export function renderToSvg(graph) {
|
|
24
|
+
const layers = ['entry', 'business', 'unknown', 'data', 'util'];
|
|
25
|
+
const positions = new Map();
|
|
26
|
+
let maxRows = 1;
|
|
27
|
+
for (let col = 0; col < layers.length; col++) {
|
|
28
|
+
const nodes = graph.nodes.filter(node => node.layer === layers[col]);
|
|
29
|
+
maxRows = Math.max(maxRows, nodes.length);
|
|
30
|
+
nodes.forEach((node, row) => positions.set(node.id, { x: 30 + col * 270, y: 90 + row * 70 }));
|
|
31
|
+
}
|
|
32
|
+
const width = 1390, height = maxRows * 70 + 110;
|
|
33
|
+
const elements = ['<svg xmlns="http://www.w3.org/2000/svg" width="' + width + '" height="' + height + '" viewBox="0 0 ' + width + ' ' + height + '" role="img" aria-label="Repository architecture map">', '<defs><marker id="arrow" markerWidth="8" markerHeight="8" refX="7" refY="4" orient="auto"><path d="M0 0L8 4L0 8" fill="#64748b"/></marker></defs>', '<rect width="100%" height="100%" fill="#0f172a"/>'];
|
|
34
|
+
layers.forEach((layer, i) => elements.push('<text x="' + (30 + i * 270) + '" y="35" fill="' + LAYER_COLORS[layer] + '" font-family="sans-serif" font-size="18">' + layer.toUpperCase() + '</text>'));
|
|
35
|
+
for (const edge of graph.edges) {
|
|
36
|
+
const a = positions.get(edge.source), b = positions.get(edge.target);
|
|
37
|
+
elements.push('<path d="M' + (a.x + 110) + ' ' + a.y + 'L' + (b.x + 110) + ' ' + b.y + '" stroke="#64748b" stroke-opacity=".5" fill="none" marker-end="url(#arrow)"/>');
|
|
38
|
+
}
|
|
39
|
+
for (const node of graph.nodes) {
|
|
40
|
+
const p = positions.get(node.id);
|
|
41
|
+
elements.push('<g><title>' + xml(node.id) + '</title><rect x="' + p.x + '" y="' + (p.y - 20) + '" width="225" height="40" rx="8" fill="#172033" stroke="' + LAYER_COLORS[node.layer] + '"/><text x="' + (p.x + 10) + '" y="' + (p.y + 5) + '" fill="#e2e8f0" font-family="monospace" font-size="12">' + xml(node.label.length > 28 ? node.label.slice(0, 25) + 'β¦' : node.label) + '</text></g>');
|
|
42
|
+
}
|
|
43
|
+
return elements.join('\n') + '\n</svg>\n';
|
|
44
|
+
}
|
|
@@ -0,0 +1,127 @@
|
|
|
1
|
+
import { readFile } from 'node:fs/promises';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import { parse } from '@babel/parser';
|
|
4
|
+
import traverseModule from '@babel/traverse';
|
|
5
|
+
import { normalize } from './walker.js';
|
|
6
|
+
const traverse = typeof traverseModule === 'function' ? traverseModule : traverseModule.default;
|
|
7
|
+
const extensions = ['.ts', '.tsx', '.js', '.jsx', '.mjs', '.cjs', '.mts', '.cts'];
|
|
8
|
+
export async function extractImports(root, files) {
|
|
9
|
+
const known = new Set(files), edges = new Map(), loc = new Map();
|
|
10
|
+
let goModule = '';
|
|
11
|
+
try {
|
|
12
|
+
goModule = (await readFile(path.join(root, 'go.mod'), 'utf8')).match(/^\s*module\s+([^\s]+)/m)?.[1] ?? '';
|
|
13
|
+
}
|
|
14
|
+
catch { /* No Go module. */ }
|
|
15
|
+
function first(candidates) { return candidates.map(x => normalize(path.posix.normalize(normalize(x))).replace(/^\.\//, '')).find(x => known.has(x)); }
|
|
16
|
+
function jsResolve(file, spec) {
|
|
17
|
+
if (!spec.startsWith('.') && !spec.startsWith('@/'))
|
|
18
|
+
return;
|
|
19
|
+
const base = spec.startsWith('@/') ? 'src/' + spec.slice(2) : path.posix.join(path.posix.dirname(file), spec);
|
|
20
|
+
const remaps = /\.[cm]?js$/.test(base) ? [base.replace(/\.js$/, '.ts').replace(/\.mjs$/, '.mts').replace(/\.cjs$/, '.cts'), base.replace(/\.js$/, '.tsx')] : [];
|
|
21
|
+
return first([base, ...remaps, ...extensions.map(ext => base + ext), ...extensions.map(ext => base + '/index' + ext)]);
|
|
22
|
+
}
|
|
23
|
+
function add(source, target, type = 'import') {
|
|
24
|
+
if (!target || source === target)
|
|
25
|
+
return;
|
|
26
|
+
const key = source + '\0' + target + '\0' + type;
|
|
27
|
+
const prior = edges.get(key);
|
|
28
|
+
if (prior)
|
|
29
|
+
prior.weight += 1;
|
|
30
|
+
else
|
|
31
|
+
edges.set(key, { source, target, type, weight: 1 });
|
|
32
|
+
}
|
|
33
|
+
for (const file of files) {
|
|
34
|
+
const text = await readFile(path.join(root, file), 'utf8');
|
|
35
|
+
loc.set(file, text ? text.split(/\r?\n/).filter(line => line.trim()).length : 0);
|
|
36
|
+
if (/\.[cm]?[jt]sx?$/.test(file)) {
|
|
37
|
+
const bindings = new Map();
|
|
38
|
+
try {
|
|
39
|
+
const ast = parse(text, { sourceType: 'unambiguous', plugins: ['typescript', 'jsx', 'decorators-legacy'], allowReturnOutsideFunction: true });
|
|
40
|
+
traverse(ast, {
|
|
41
|
+
ImportDeclaration(p) {
|
|
42
|
+
const spec = p.node.source.value;
|
|
43
|
+
add(file, jsResolve(file, spec));
|
|
44
|
+
for (const binding of p.node.specifiers)
|
|
45
|
+
bindings.set(binding.local.name, spec);
|
|
46
|
+
},
|
|
47
|
+
ExportNamedDeclaration(p) { if (p.node.source)
|
|
48
|
+
add(file, jsResolve(file, p.node.source.value)); },
|
|
49
|
+
ExportAllDeclaration(p) { add(file, jsResolve(file, p.node.source.value)); },
|
|
50
|
+
CallExpression(p) {
|
|
51
|
+
const callee = p.node.callee, arg = p.node.arguments[0];
|
|
52
|
+
if (arg?.type === 'StringLiteral' && ((callee.type === 'Identifier' && callee.name === 'require') || callee.type === 'Import'))
|
|
53
|
+
add(file, jsResolve(file, arg.value), callee.type === 'Import' ? 'dynamic' : 'import');
|
|
54
|
+
}
|
|
55
|
+
});
|
|
56
|
+
traverse(ast, { ClassDeclaration(p) {
|
|
57
|
+
const base = p.node.superClass;
|
|
58
|
+
const name = base?.type === 'Identifier' ? base.name : base?.type === 'MemberExpression' && base.object.type === 'Identifier' ? base.object.name : undefined;
|
|
59
|
+
if (name && bindings.has(name))
|
|
60
|
+
add(file, jsResolve(file, bindings.get(name)), 'inheritance');
|
|
61
|
+
} });
|
|
62
|
+
}
|
|
63
|
+
catch {
|
|
64
|
+
for (const match of text.matchAll(/(?:\b(?:import|export)\s+(?:[^;'"\n]*?\s+from\s*)?|\brequire\s*\(\s*|\bimport\s*\(\s*)['"]([^'"]+)['"]/g))
|
|
65
|
+
add(file, jsResolve(file, match[1]), /import\s*\(/.test(match[0]) ? 'dynamic' : 'import');
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
else if (file.endsWith('.py')) {
|
|
69
|
+
const resolvePy = (module) => {
|
|
70
|
+
const dots = module.match(/^\.+/)?.[0].length ?? 0;
|
|
71
|
+
const suffix = module.slice(dots).replace(/\./g, '/');
|
|
72
|
+
let base = path.posix.dirname(file);
|
|
73
|
+
for (let n = 1; n < dots; n++)
|
|
74
|
+
base = path.posix.dirname(base);
|
|
75
|
+
const candidates = dots ? [path.posix.join(base, suffix)] : [path.posix.join(path.posix.dirname(file), suffix), suffix];
|
|
76
|
+
return first(candidates.flatMap(x => [x + '.py', x + '/__init__.py']));
|
|
77
|
+
};
|
|
78
|
+
for (const match of text.matchAll(/^\s*import\s+([^\n#]+)/gm)) {
|
|
79
|
+
for (const part of match[1].split(','))
|
|
80
|
+
add(file, resolvePy(part.trim().split(/\s+as\s+/)[0]));
|
|
81
|
+
}
|
|
82
|
+
for (const match of text.matchAll(/^\s*from\s+([.\w]+)\s+import\s+([^\n#]+)/gm)) {
|
|
83
|
+
const parent = resolvePy(match[1]);
|
|
84
|
+
if (parent)
|
|
85
|
+
add(file, parent);
|
|
86
|
+
for (const part of match[2].replace(/[()]/g, '').split(',')) {
|
|
87
|
+
const name = part.trim().split(/\s+/)[0];
|
|
88
|
+
if (name && name !== '*')
|
|
89
|
+
add(file, resolvePy(match[1] + (match[1].endsWith('.') ? '' : '.') + name));
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
else if (file.endsWith('.go') && goModule) {
|
|
94
|
+
const imports = [];
|
|
95
|
+
for (const match of text.matchAll(/\bimport\s*\(([\s\S]*?)\)|\bimport\s+(?:[\w.]+\s+)?"([^"\n]+)"/g)) {
|
|
96
|
+
if (match[2])
|
|
97
|
+
imports.push(match[2]);
|
|
98
|
+
else
|
|
99
|
+
for (const quoted of match[1].matchAll(/"([^"\n]+)"/g))
|
|
100
|
+
imports.push(quoted[1]);
|
|
101
|
+
}
|
|
102
|
+
for (const spec of imports)
|
|
103
|
+
if (spec === goModule || spec.startsWith(goModule + '/')) {
|
|
104
|
+
const dir = spec.slice(goModule.length).replace(/^\//, '') || '.';
|
|
105
|
+
for (const target of files)
|
|
106
|
+
if (target.endsWith('.go') && path.posix.dirname(target) === dir)
|
|
107
|
+
add(file, target);
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
else if (file.endsWith('.rs')) {
|
|
111
|
+
for (const match of text.matchAll(/\bmod\s+(\w+)\s*;/g)) {
|
|
112
|
+
const dir = path.posix.dirname(file);
|
|
113
|
+
const base = /(?:^|\/)(?:lib|main|mod)\.rs$/.test(file) ? dir : file.slice(0, -3);
|
|
114
|
+
add(file, first([base + '/' + match[1] + '.rs', base + '/' + match[1] + '/mod.rs']));
|
|
115
|
+
}
|
|
116
|
+
for (const match of text.matchAll(/\buse\s+crate::([\w:]+)/g)) {
|
|
117
|
+
const parts = match[1].split('::').filter(Boolean), candidates = [];
|
|
118
|
+
for (let n = parts.length; n > 0; n--) {
|
|
119
|
+
const base = 'src/' + parts.slice(0, n).join('/');
|
|
120
|
+
candidates.push(base + '.rs', base + '/mod.rs');
|
|
121
|
+
}
|
|
122
|
+
add(file, first(candidates));
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
return { edges: [...edges.values()], loc };
|
|
127
|
+
}
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
import type { CodeNode } from '../types.js';
|
|
2
|
+
export declare const nameTokens: (id: string) => string;
|
|
3
|
+
export declare const isUtilityName: (id: string) => boolean;
|
|
4
|
+
export declare const isUtility: (node: CodeNode, threshold?: number) => boolean;
|
|
5
|
+
export declare const isTestFile: (id: string) => boolean;
|
|
6
|
+
export declare const isEntryLike: (id: string) => boolean;
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
export const nameTokens = (id) => id.replace(/([a-z0-9])([A-Z])/g, '$1/$2');
|
|
2
|
+
export const isUtilityName = (id) => /(?:^|[/_.-])(?:utils?|helpers?|common|shared|lib|constants|types|config)(?:[/_.-]|$)/i.test(nameTokens(id));
|
|
3
|
+
export const isUtility = (node, threshold = 12) => (node.inDegree > threshold && node.outDegree <= 2) || isUtilityName(node.id);
|
|
4
|
+
export const isTestFile = (id) => /(?:^|\/)(?:__tests__|tests?|specs?)(?:\/|\.|$)|(?:[._-](?:test|spec))\.[^/]+$|(?:^|\/)test_[^/]+\.py$/i.test(id);
|
|
5
|
+
export const isEntryLike = (id) => /(?:^|[/_.-])(?:controllers?|routes?|routers?|handlers?|api|endpoints?|cli|app|server|main)(?:[/_.-]|$)/i.test(nameTokens(id)) || /^index\.[^/]+$/.test(id) || /(?:^|\/)(?:__main__|manage)\.py$/.test(id);
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
import { readdir, readFile, stat } from 'node:fs/promises';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import ignore from 'ignore';
|
|
4
|
+
export const normalize = (value) => value.replace(/\\/g, '/');
|
|
5
|
+
const skipped = new Set('node_modules .git dist build out coverage __pycache__ .venv venv .next .nuxt target vendor .idea .vscode .cache'.split(' '));
|
|
6
|
+
const source = /\.(?:js|jsx|mjs|cjs|ts|tsx|mts|cts|py|go|rs)$/i;
|
|
7
|
+
export async function walkRepository(root, maxDepth = 6) {
|
|
8
|
+
const files = [];
|
|
9
|
+
async function visit(dir, depth, inherited) {
|
|
10
|
+
let rules = inherited;
|
|
11
|
+
try {
|
|
12
|
+
rules = [...rules, { base: dir, matcher: ignore().add(await readFile(path.join(dir, '.gitignore'), 'utf8')) }];
|
|
13
|
+
}
|
|
14
|
+
catch (error) {
|
|
15
|
+
if (error.code !== 'ENOENT')
|
|
16
|
+
throw error;
|
|
17
|
+
}
|
|
18
|
+
const entries = await readdir(dir, { withFileTypes: true });
|
|
19
|
+
entries.sort((a, b) => a.name.localeCompare(b.name));
|
|
20
|
+
for (const entry of entries) {
|
|
21
|
+
if (entry.isSymbolicLink())
|
|
22
|
+
continue;
|
|
23
|
+
const absolute = path.join(dir, entry.name);
|
|
24
|
+
if (entry.isDirectory() && skipped.has(entry.name))
|
|
25
|
+
continue;
|
|
26
|
+
let ignored = false;
|
|
27
|
+
for (const rule of rules) {
|
|
28
|
+
const relative = normalize(path.relative(rule.base, absolute)) + (entry.isDirectory() ? '/' : '');
|
|
29
|
+
const result = rule.matcher.test(relative);
|
|
30
|
+
if (result.ignored)
|
|
31
|
+
ignored = true;
|
|
32
|
+
else if (result.unignored)
|
|
33
|
+
ignored = false;
|
|
34
|
+
}
|
|
35
|
+
if (ignored)
|
|
36
|
+
continue;
|
|
37
|
+
if (entry.isDirectory()) {
|
|
38
|
+
if (depth < maxDepth)
|
|
39
|
+
await visit(absolute, depth + 1, rules);
|
|
40
|
+
}
|
|
41
|
+
else if (entry.isFile() && source.test(entry.name) && !/\.min\.js$/i.test(entry.name)) {
|
|
42
|
+
if ((await stat(absolute)).size <= 1.5 * 1024 * 1024)
|
|
43
|
+
files.push(normalize(path.relative(root, absolute)));
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
await visit(root, 0, []);
|
|
48
|
+
return files;
|
|
49
|
+
}
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
export interface CodeNode {
|
|
2
|
+
id: string;
|
|
3
|
+
label: string;
|
|
4
|
+
layer: 'entry' | 'business' | 'data' | 'util' | 'unknown';
|
|
5
|
+
cluster: string;
|
|
6
|
+
inDegree: number;
|
|
7
|
+
outDegree: number;
|
|
8
|
+
linesOfCode: number;
|
|
9
|
+
isFolded?: boolean;
|
|
10
|
+
language?: string;
|
|
11
|
+
}
|
|
12
|
+
export interface CodeEdge {
|
|
13
|
+
source: string;
|
|
14
|
+
target: string;
|
|
15
|
+
type: 'import' | 'dynamic' | 'inheritance';
|
|
16
|
+
weight: number;
|
|
17
|
+
}
|
|
18
|
+
export interface ArchitectureGraph {
|
|
19
|
+
rootPath: string;
|
|
20
|
+
generatedAt: string;
|
|
21
|
+
nodes: CodeNode[];
|
|
22
|
+
edges: CodeEdge[];
|
|
23
|
+
clusters: Array<{
|
|
24
|
+
id: string;
|
|
25
|
+
label: string;
|
|
26
|
+
parent?: string;
|
|
27
|
+
}>;
|
|
28
|
+
metrics: {
|
|
29
|
+
totalFiles: number;
|
|
30
|
+
totalEdges: number;
|
|
31
|
+
density: number;
|
|
32
|
+
couplingFactor: number;
|
|
33
|
+
deadCodeCount: number;
|
|
34
|
+
foldedUtilityCount: number;
|
|
35
|
+
};
|
|
36
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
package/package.json
CHANGED
|
@@ -1,6 +1,66 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "repograph-cli",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"description": "
|
|
6
|
-
|
|
3
|
+
"version": "0.1.1",
|
|
4
|
+
"mcpName": "io.github.Karry1123/repograph",
|
|
5
|
+
"description": "Instant, interactive architecture maps for any codebase. Zero-config CLI + MCP server for Claude Code & Claude Desktop.",
|
|
6
|
+
"type": "module",
|
|
7
|
+
"bin": {
|
|
8
|
+
"repograph": "dist/bin/cli.js",
|
|
9
|
+
"repograph-cli": "dist/bin/cli.js"
|
|
10
|
+
},
|
|
11
|
+
"scripts": {
|
|
12
|
+
"build": "tsc",
|
|
13
|
+
"check:server-json": "node scripts/check-server-json.mjs",
|
|
14
|
+
"dev": "tsx bin/cli.ts",
|
|
15
|
+
"start": "node dist/src/index.js",
|
|
16
|
+
"mcp": "node dist/src/index.js",
|
|
17
|
+
"prepublishOnly": "npm run build"
|
|
18
|
+
},
|
|
19
|
+
"files": [
|
|
20
|
+
"dist",
|
|
21
|
+
"README.md",
|
|
22
|
+
"LICENSE"
|
|
23
|
+
],
|
|
24
|
+
"engines": {
|
|
25
|
+
"node": ">=18.0.0"
|
|
26
|
+
},
|
|
27
|
+
"license": "MIT",
|
|
28
|
+
"author": "Karry",
|
|
29
|
+
"dependencies": {
|
|
30
|
+
"@modelcontextprotocol/sdk": "^1.0.0",
|
|
31
|
+
"commander": "^13.0.0",
|
|
32
|
+
"ignore": "^7.0.0",
|
|
33
|
+
"@babel/parser": "^7.26.0",
|
|
34
|
+
"@babel/traverse": "^7.26.0",
|
|
35
|
+
"zod": "^3.24.0"
|
|
36
|
+
},
|
|
37
|
+
"devDependencies": {
|
|
38
|
+
"typescript": "^5.7.0",
|
|
39
|
+
"@types/node": "^22.0.0",
|
|
40
|
+
"@types/babel__traverse": "^7.20.0",
|
|
41
|
+
"tsx": "^4.19.0"
|
|
42
|
+
},
|
|
43
|
+
"keywords": [
|
|
44
|
+
"mcp",
|
|
45
|
+
"model-context-protocol",
|
|
46
|
+
"claude",
|
|
47
|
+
"claude-code",
|
|
48
|
+
"architecture",
|
|
49
|
+
"code-visualization",
|
|
50
|
+
"dependency-graph",
|
|
51
|
+
"ast",
|
|
52
|
+
"codebase",
|
|
53
|
+
"cytoscape"
|
|
54
|
+
],
|
|
55
|
+
"repository": {
|
|
56
|
+
"type": "git",
|
|
57
|
+
"url": "git+https://github.com/Karry1123/repograph.git"
|
|
58
|
+
},
|
|
59
|
+
"homepage": "https://github.com/Karry1123/repograph#readme",
|
|
60
|
+
"bugs": {
|
|
61
|
+
"url": "https://github.com/Karry1123/repograph/issues"
|
|
62
|
+
},
|
|
63
|
+
"publishConfig": {
|
|
64
|
+
"access": "public"
|
|
65
|
+
}
|
|
66
|
+
}
|