depgraph-core 1.0.2 → 1.5.0

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
@@ -3,33 +3,57 @@
3
3
  [![npm version](https://img.shields.io/npm/v/depgraph-core.svg)](https://www.npmjs.com/package/depgraph-core)
4
4
  [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
5
5
 
6
- **DepGraph Core** is a powerful static analysis tool designed to map code dependencies and simulate the ripple effect/impact of changes in JavaScript and TypeScript projects. By parsing imports, exports, functions, classes, and routing definitions, DepGraph constructs a comprehensive dependency graph, computes critical centrality metrics, and generates interactive impact simulations to prevent regression bugs in large codebases.
6
+ **DepGraph Core** is a powerful static analysis CLI that maps code dependencies and simulates the ripple-effect impact of changes across multi-language codebases — supporting JavaScript, TypeScript, Python, Go, C#, Java, Kotlin, PHP, Ruby, and Swift. By parsing imports, exports, functions, classes, interfaces, and methods, DepGraph constructs a comprehensive dependency graph, computes centrality metrics, and generates impact simulations helping you prevent regression bugs in large systems.
7
7
 
8
8
  ---
9
9
 
10
10
  ## 🚀 Key Features
11
11
 
12
- * 🔍 **Automated Code Parsing**: Parses JavaScript, TypeScript, React components/hooks (`.js`, `.jsx`, `.ts`, `.tsx`, `.mjs`, `.cjs`), extracting functions, classes, interfaces, types, React constructs, and Express API routes.
13
- * 🕸️ **Dependency Graph Reconstruction**: Resolves local imports and links entities across files to construct an internal representation of your codebase topology.
14
- * 📈 **Metrics & Centrality Analysis**: Calculates in-degree, out-degree, and centrality scores for every entity to automatically identify **Critical Nodes** (nodes that, if modified, carry high regression risks).
15
- * 💥 **Impact Simulation Engine**: Runs a reverse Breadth-First Search (BFS) to model the cascading impact of changes to a specific function or component. Generates a risk score, details affected nodes, defines a targeted testing plan, and provides actionable engineering recommendations.
16
- * 🖥️ **Rich CLI Interface**: Colorized and structured console feedback designed for human readability, with a `--no-color` flag optimized for CI/CD pipelines.
17
- * 💾 **Detailed JSON Outputs**: Exports a comprehensive report containing metadata, files breakdown, graph structure, and simulation metrics.
12
+ - 🔍 **Multi-Language AST & Regex Code Parsing**: Comprehensive native extractors for **10 languages**:
13
+ - **JavaScript / TypeScript / React** (`.js`, `.jsx`, `.ts`, `.tsx`, `.mjs`, `.cjs`)
14
+ - **Python** (`.py`)
15
+ - **Go** (`.go`)
16
+ - **C#** (`.cs`)
17
+ - **Java** (`.java`)
18
+ - **Kotlin** (`.kt`, `.kts`)
19
+ - **PHP** (`.php`)
20
+ - **Ruby** (`.rb`)
21
+ - **Swift** (`.swift`)
22
+ - 🕸️ **Dependency Graph Reconstruction**: Resolves local imports, aliases, namespace packages, and cross-file relationships to build a full topology map of your codebase.
23
+ - 📈 **Metrics & Centrality Analysis**: Calculates in-degree, out-degree, and centrality scores for every entity to automatically identify **Critical Nodes**.
24
+ - 💥 **Impact Simulation Engine**: Runs a reverse BFS to model the cascading impact of changing a specific function or class. Generates a risk score, lists affected nodes, and provides an actionable testing plan.
25
+ - 🧬 **Git Diff Integration**: Automatically detects changed entities from your git history (uncommitted changes, a specific commit, or a branch comparison) across all supported languages and runs impact simulation on every changed symbol.
26
+ - 🖥️ **Rich CLI Interface**: Colorized, human-readable output with a `--no-color` flag for CI/CD pipelines.
27
+ - 💾 **Detailed JSON Output**: Exports a comprehensive report containing graph structure, metrics, and simulation results.
18
28
 
19
29
  ---
20
30
 
21
- ## 📦 Installation
31
+ ## 🌐 Supported Languages
32
+
33
+ DepGraph Core provides native parsing and symbol extraction across 10 major programming languages:
34
+
35
+ | Language | Extensions | Extracted Entities | Import & Resolution Features |
36
+ | :--- | :--- | :--- | :--- |
37
+ | **JavaScript / TypeScript** | `.js`, `.jsx`, `.ts`, `.tsx`, `.mjs`, `.cjs` | Functions, Async functions, Classes, Methods, Interfaces, Type aliases, React Components, Hooks, Express routes | ESM (`import`/`export`), dynamic `import()`, CommonJS (`require()`, `module.exports`), named & default imports |
38
+ | **Python** | `.py` | Functions, Async functions, Classes, Methods | `import x`, `from x import y`, aliases (`as`), wildcard imports (`*`), `__all__` exports |
39
+ | **Go** | `.go` | Functions, Struct methods (pointer & value receivers), Structs, Interfaces | Single & grouped `import (...)`, import aliases, exported symbols (capitalized identifier convention) |
40
+ | **C#** | `.cs` | Classes, Records, Interfaces, Structs, Enums, Methods, Namespaces | Single & global `using`, static imports (`using static`), using aliases, public/internal exports |
41
+ | **Java** | `.java` | Classes, Interfaces, Records, Enums, Methods, Constructors | Single imports, wildcard imports (`.*`), static imports (`import static`), package tracking, public/protected exports |
42
+ | **Kotlin** | `.kt`, `.kts` | Classes (data, sealed, abstract, inner), Objects, Companion objects, Interfaces, Functions, Suspend functions | Direct imports, wildcard imports (`.*`), import aliases (`as`), packages |
43
+ | **PHP** | `.php` | Classes (abstract, final), Interfaces, Traits, Enums, Functions, Methods | Namespaces, single & grouped `use` statements, `use ... as` aliases, `require`/`include` file paths |
44
+ | **Ruby** | `.rb` | Classes, Modules, Instance methods, Class methods (`def self.`), `attr_accessor`/`reader`/`writer` | `require`, `require_relative`, `load`, `include`, `extend`, `prepend` |
45
+ | **Swift** | `.swift` | Classes, Structs, Enums, Protocols, Actors, Extensions (including `where` constraints), Functions, Initializers | Module imports, sub-module imports, kind-specifier imports (`import class/func/...`) |
22
46
 
23
- ### Global Installation
24
- Install `depgraph-core` globally via npm to run it anywhere:
47
+ ---
48
+
49
+ ## 📦 Installation
25
50
 
51
+ ### Global (recommended)
26
52
  ```bash
27
53
  npm install -g depgraph-core
28
54
  ```
29
55
 
30
- ### Run with `npx`
31
- Alternatively, execute it directly without local installation:
32
-
56
+ ### Via `npx` (no install required)
33
57
  ```bash
34
58
  npx depgraph-core <projectDir> [options]
35
59
  ```
@@ -46,73 +70,195 @@ depgraph <projectDir> [options]
46
70
 
47
71
  | Flag | Parameter | Description | Default |
48
72
  | :--- | :--- | :--- | :--- |
49
- | `--output` | `<file>` | Output path for the generated JSON report. | `./depgraph-output.json` |
50
- | `--impact` | `<name> <desc>` | Simulate changing a specific entity. Must supply its name and a reason/description. | `N/A` |
51
- | `--verbose` | — | Print per-file parsing and details. | `false` |
52
- | `--no-color` | — | Disable terminal ANSI color output (recommended for CI/CD logs). | `false` |
53
- | `--help`, `-h` | — | Display help message. | — |
73
+ | `--output` | `<file>` | Output path for the generated JSON report | `./depgraph-output.json` |
74
+ | `--impact` | `<name> <desc>` | Manually simulate changing a specific entity | |
75
+ | `--verbose` | — | Print per-file parsing details | `false` |
76
+ | `--no-color` | — | Disable ANSI color output (for CI/CD) | `false` |
77
+ | `--help`, `-h` | — | Show help message | — |
78
+
79
+ ### Git Flags
54
80
 
55
- ### Examples
81
+ | Flag | Parameter | Description |
82
+ | :--- | :--- | :--- |
83
+ | `--git-impact` | — | Auto-detect changed entities from git diff and run impact simulation |
84
+ | `--commit` | `<sha>` | Analyze a specific commit (vs its parent) |
85
+ | `--from` | `<branch>` | Compare from this branch (use with `--to`) |
86
+ | `--to` | `<branch>` | Compare to this branch (use with `--from`) |
87
+
88
+ ---
56
89
 
57
- #### 1. Generate a dependency report for a project
90
+ ## 📖 Examples
91
+
92
+ ### Standard Usage
93
+
94
+ #### Map a project
58
95
  ```bash
59
96
  depgraph ./src
60
97
  ```
61
98
 
62
- #### 2. Run with custom output path
99
+ #### Custom output path
63
100
  ```bash
64
101
  depgraph ./src --output ./reports/graph-report.json
65
102
  ```
66
103
 
67
- #### 3. Simulate impact of modifying a critical component or helper
104
+ #### Manually simulate a change
68
105
  ```bash
69
106
  depgraph ./src --impact "getUserById" "adding middleName field to returned object"
70
107
  ```
71
108
 
72
- #### 4. Run in CI Mode (silencing color output)
109
+ #### CI mode
73
110
  ```bash
74
111
  depgraph ./src --no-color --output ./ci/depgraph.json
75
112
  ```
76
113
 
77
114
  ---
78
115
 
116
+ ### 🧬 Git Diff Integration
117
+
118
+ `--git-impact` automatically reads your git diff, detects every function or class that changed, and runs an impact simulation for each one — no need to manually select a target entity.
119
+
120
+ #### ⚙️ How It Works under the Hood
121
+
122
+ 1. **Git Diff Execution**: Runs the appropriate git command depending on the mode:
123
+ - **Uncommitted Changes**: `git diff HEAD` (detects staged & unstaged changes).
124
+ - **Last Commit (or Specific Commit)**: `git diff <commit>~1 <commit>` (compares the target commit against its parent).
125
+ - **Branch Comparison**: `git diff <from>...<to>` (finds the merge base and diffs to the target branch).
126
+ 2. **Context Parsing**: Scans git diff context lines (headers starting with `@@`) to extract target entities.
127
+ 3. **No Regex Duplication**: Reuses the regex patterns defined in the language parsers (`jsEntityPatterns`, `pyEntityPatterns`, `goEntityPatterns`) via the language registry.
128
+ 4. **Fallback Parsers**: Contains built-in fallback parser logic for popular OOP languages like Java (`.java`) and C# (`.cs`) to extract method signatures.
129
+ 5. **Change Description Generation**: Automatically analyzes added/removed lines in the change hunk to build descriptive labels (e.g. `getUserById: 3 line(s) changed to 2 new line(s)`).
130
+
131
+ #### 📋 Git Commands Reference
132
+
133
+ | Mode | CLI Command | Under-the-hood Command | Description |
134
+ | :--- | :--- | :--- | :--- |
135
+ | **Uncommitted Changes** | `depgraph ./src --git-impact` | `git diff HEAD` | Analyze your current workspace changes |
136
+ | **Last Commit** | `depgraph ./src --git-impact --commit HEAD` | `git diff HEAD~1 HEAD` | Analyze the last commit |
137
+ | **Specific Commit** | `depgraph ./src --git-impact --commit <sha>` | `git diff <sha>~1 <sha>` | Analyze any commit by its SHA |
138
+ | **Branch Comparison** | `depgraph ./src --git-impact --from main --to feature/auth` | `git diff main...feature/auth` | Compare two branches |
139
+
140
+ #### 🖥️ CLI Output Example
141
+
142
+ Running `--git-impact` displays a colorized report of detected entities and runs an impact simulation for each one:
143
+
144
+ ```text
145
+ ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
146
+ DepGraph v1.0.0
147
+ ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
148
+
149
+ 🔍 Scanning .
150
+
151
+ 📊 Graph Summary
152
+ Files : 27
153
+ Nodes : 76
154
+ Edges : 252
155
+
156
+ 🔍 Reading git diff...
157
+
158
+ Found 2 changed entity(s):
159
+ → slugify (src/languages/javascript.ts)
160
+ → LanguageParser (src/languages/registry.ts)
161
+
162
+ Running impact simulation...
163
+
164
+ ──────────────────────────────────────────
165
+
166
+ 💥 Impact Simulation
167
+ Target : slugify__javascript
168
+ Change : slugify: 16 line(s) added
169
+ Risk Score : 0
170
+ Risk Level : LOW
171
+
172
+ ✓ No affected nodes found
173
+
174
+ 🧪 Testing Plan
175
+ → Test slugify directly after making changes
176
+
177
+ 💡 Recommendations
178
+ → Standard PR process is sufficient
179
+ → Unit tests for the changed node are enough
180
+
181
+ ──────────────────────────────────────────
182
+
183
+ 💥 Impact Simulation
184
+ Target : LanguageParser__registry
185
+ Change : LanguageParser: 6 line(s) added
186
+ Risk Score : 100
187
+ Risk Level : CRITICAL
188
+
189
+ 📋 Affected Nodes (3)
190
+
191
+ [CRITICAL] extractEntities
192
+ file : src/languages/go.ts
193
+ reason : extractEntities directly imports LanguageParser
194
+ action : Update extractEntities to handle the new interface of LanguageParser
195
+ breaking: YES
196
+
197
+ [CRITICAL] extractImports
198
+ file : src/languages/go.ts
199
+ reason : extractImports directly imports LanguageParser
200
+ action : Update extractImports to handle the new interface of LanguageParser
201
+ breaking: YES
202
+
203
+ [CRITICAL] extractExports
204
+ file : src/languages/go.ts
205
+ reason : extractExports directly imports LanguageParser
206
+ action : Update extractExports to handle the new interface of LanguageParser
207
+ breaking: YES
208
+
209
+ 🧪 Testing Plan
210
+ → Test LanguageParser directly after making changes
211
+ → Regression test extractEntities — direct dependent
212
+ → Regression test extractImports — direct dependent
213
+ → Regression test extractExports — direct dependent
214
+ → Run full test suite — 3 nodes affected
215
+
216
+ 💡 Recommendations
217
+ → Full team review required before merging
218
+ → Consider a phased rollout
219
+ → Run full regression test suite
220
+ → 3 breaking change(s) must be updated before deploying
221
+
222
+ ✅ Output written to ./depgraph-output.json
223
+ ```
224
+
225
+ **Supported languages for diff parsing:** All 10 languages (JavaScript/TypeScript, Python, Go, C#, Java, Kotlin, PHP, Ruby, and Swift) are fully supported via shared entity pattern registries and fallbacks.
226
+
227
+ ---
228
+
79
229
  ## 💥 Impact Simulation Mechanics
80
230
 
81
- When you simulate an impact using `--impact <name> <desc>`, the tool performs the following operations:
231
+ When running `--impact` or `--git-impact`, the tool performs:
232
+
82
233
  1. **Target Identification**: Locates the node matching the provided name.
83
- 2. **Reverse BFS Traversal**: Traverses backwards up the dependency graph up to a depth of 10 nodes to discover all direct and indirect dependents.
84
- 3. **Risk Scoring**: Calculates a score from `0` to `100` based on:
85
- * Number of critical-impact nodes (depth 1)
86
- * Number of high-impact nodes (depth 2)
87
- * Number of medium/low-impact nodes
88
- * The target node's in-degree (how many other entities import it)
234
+ 2. **Reverse BFS Traversal**: Traverses backwards up the dependency graph (up to depth 10) to find all direct and indirect dependents.
235
+ 3. **Risk Scoring**: Calculates a score from `0100` based on:
236
+ - Number of critical-impact nodes (depth 1)
237
+ - Number of high-impact nodes (depth 2)
238
+ - Number of medium/low-impact nodes
239
+ - The target node's in-degree
89
240
  4. **Risk Level Mapping**:
90
- * 🔴 **CRITICAL** (Score $\ge$ 75): Requires comprehensive review, phased rollouts, and global regression testing.
91
- * 🟡 **HIGH** (Score 50–74): Tech lead review recommended, feature flag encouraged.
92
- * 🔵 **MEDIUM** (Score 25–49): Standard peer code review, targeted module testing.
93
- * 🟢 **LOW** (Score < 25): Standard PR process is sufficient.
241
+ - 🔴 **CRITICAL** ( 75): Comprehensive review, phased rollout, full regression testing.
242
+ - 🟡 **HIGH** (50–74): Tech lead review, feature flag recommended.
243
+ - 🔵 **MEDIUM** (25–49): Standard peer review, targeted module testing.
244
+ - 🟢 **LOW** (< 25): Standard PR process is sufficient.
94
245
 
95
246
  ---
96
247
 
97
248
  ## 📁 Output JSON Schema
98
249
 
99
- The tool generates a JSON report containing the following structure:
100
-
101
250
  ```json
102
251
  {
103
252
  "meta": {
104
- "version": "1.0.0",
105
- "timestamp": "2026-07-16T02:45:52.311Z",
106
- "totalFiles": 25,
107
- "totalLines": 1968
253
+ "version": "1.0.2",
254
+ "timestamp": "2026-07-20T05:14:00.000Z",
255
+ "totalFiles": 26,
256
+ "totalLines": 2957
108
257
  },
109
258
  "summary": {
110
- "totalNodes": 55,
111
- "totalEdges": 191,
112
- "entryPoints": [ "main__app" ],
113
- "leafNodes": [ "formatDate__utils" ],
114
- "isolatedNodes": [],
115
- "criticalNodes": [ "dbClient__db" ]
259
+ "totalNodes": 70,
260
+ "totalEdges": 252,
261
+ "criticalNodes": ["simulateImpact__impact", "buildGraph__graph"]
116
262
  },
117
263
  "nodes": [
118
264
  {
@@ -125,30 +271,14 @@ The tool generates a JSON report containing the following structure:
125
271
  "complexity": "low",
126
272
  "inDegree": 3,
127
273
  "outDegree": 1,
128
- "centralityScore": 7,
129
- "connections": [ "dbClient__db", "getUserRoute__userController" ]
274
+ "centralityScore": 7
130
275
  }
131
276
  ],
132
277
  "edges": [
133
278
  {
134
279
  "from": "getUserRoute__userController",
135
280
  "to": "getUserById__userService",
136
- "type": "imports",
137
- "description": "getUserRoute imports getUserById from userService"
138
- }
139
- ],
140
- "files": [
141
- {
142
- "filePath": "src/services/userService.ts",
143
- "lang": "js",
144
- "lines": 42,
145
- "entities": [
146
- { "name": "getUserById", "type": "function", "line": 15, "complexity": "low" }
147
- ],
148
- "imports": [
149
- { "source": "../db", "names": ["dbClient"], "isLocal": true }
150
- ],
151
- "exports": [ "getUserById" ]
281
+ "type": "imports"
152
282
  }
153
283
  ],
154
284
  "impact": {
@@ -158,26 +288,15 @@ The tool generates a JSON report containing the following structure:
158
288
  "riskLevel": "HIGH",
159
289
  "affectedNodes": [
160
290
  {
161
- "nodeId": "getUserRoute__userController",
162
291
  "name": "getUserRoute",
163
292
  "file": "src/controllers/userController.ts",
164
293
  "depth": 1,
165
294
  "impact": "critical",
166
- "reason": "getUserRoute directly imports getUserById",
167
- "changeRequired": "Update getUserRoute to handle the new interface of getUserById",
168
295
  "breakingChange": true
169
296
  }
170
297
  ],
171
- "breakingChanges": [...],
172
- "testingPlan": [
173
- "Test getUserById directly after making changes",
174
- "Regression test getUserRoute — direct dependent"
175
- ],
176
- "recommendations": [
177
- "Tech lead review recommended",
178
- "Feature flag this change",
179
- "1 breaking change(s) must be updated before deploying"
180
- ]
298
+ "testingPlan": ["Test getUserById directly", "Regression test getUserRoute"],
299
+ "recommendations": ["Tech lead review recommended", "Feature flag this change"]
181
300
  }
182
301
  }
183
302
  ```
@@ -186,41 +305,25 @@ The tool generates a JSON report containing the following structure:
186
305
 
187
306
  ## 💻 Development & Contribution
188
307
 
189
- If you are developing or contributing to `depgraph-core`, follow these steps:
190
-
191
- ### Setup & Installation
192
- Clone the repository and install development dependencies:
308
+ ### Setup
193
309
  ```bash
310
+ git clone https://github.com/arafat2020/depgraph.git
311
+ cd depgraph
194
312
  npm install
195
313
  ```
196
314
 
197
315
  ### Commands
198
- * **Compile TypeScript**:
199
- ```bash
200
- npm run build
201
- ```
202
- * **Create Production Bundle**:
203
- Bundles the application into a standalone executable file `depgraph.js` via `esbuild`:
204
- ```bash
205
- npm run bundle
206
- ```
207
- * **Rebuild Code for Release**:
208
- Cleans, recompiles, and bundles the source:
209
- ```bash
210
- npm run release
211
- ```
212
- * **Run Test Suite**:
213
- Uses `vitest` for running tests:
214
- ```bash
215
- # Watch mode
216
- npm run test
217
-
218
- # Run tests once (useful for CI)
219
- npm run test:run
220
- ```
316
+
317
+ | Command | Description |
318
+ | :--- | :--- |
319
+ | `npm run build` | Compile TypeScript → `dist/` |
320
+ | `npm run bundle` | Bundle `dist/main.js` → `depgraph.js` via esbuild |
321
+ | `npm run release` | Build + bundle in one step |
322
+ | `npm run test` | Run tests in watch mode (vitest) |
323
+ | `npm run test:run` | Run tests once (for CI) |
221
324
 
222
325
  ---
223
326
 
224
327
  ## 📄 License
225
328
 
226
- This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.
329
+ This project is licensed under the MIT License see the [LICENSE](LICENSE) file for details.