@sun-asterisk/impact-analyzer 1.0.0 → 1.0.2

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
@@ -1,24 +1,28 @@
1
1
  # Impact Analyzer
2
2
 
3
- Automated impact analysis tool for TypeScript/JavaScript projects. Analyzes code changes between git references and generates comprehensive impact reports.
3
+ Automated impact analysis for TypeScript/JavaScript projects. Analyzes code changes and generates comprehensive impact reports.
4
4
 
5
- ## Overview
5
+ ## Quick Start
6
6
 
7
- Impact Analyzer is a powerful tool designed to help development teams understand the full impact of code changes in their TypeScript/JavaScript projects. It detects changes between git commits/branches and automatically analyzes:
7
+ ### Installation
8
8
 
9
- - **API Endpoints** - Which REST APIs are affected by the changes
10
- - **Database Operations** - Which database tables and fields are impacted
11
- - **Pages/Components** - Which UI components and pages are modified
12
- - **Logic Impact** - Function call dependencies and impact scope
13
- - **Test Coverage** - Recommended test cases based on changes
9
+ ```bash
10
+ npm install @sun-asterisk/impact-analyzer
11
+ ```
12
+
13
+ ### Usage
14
+
15
+ ```bash
16
+ npx @sun-asterisk/impact-analyzer --input=src --base=origin/main
17
+ ```
14
18
 
15
- ### Key Benefits
19
+ ## Features
16
20
 
17
- - 🎯 **Reduce Testing Effort** - Know exactly what to test instead of full regression
18
- - 🚀 **Faster Code Reviews** - Reviewers can quickly understand the scope of changes
19
- - 📊 **Risk Assessment** - Automatically calculates impact scores and severity levels
20
- - 🔍 **Dependency Tracking** - Identifies all files and functions affected by changes
21
- - 📝 **Automated Reports** - Generates detailed markdown and JSON reports
21
+ - 📡 **API Impact** - Detect affected endpoints
22
+ - 💾 **Database Impact** - Track table and field changes
23
+ - 📄 **Component Impact** - Identify modified UI components
24
+ - 🔄 **Logic Impact** - Analyze function dependencies
25
+ - **Test Recommendations** - Suggest test cases
22
26
 
23
27
  ## Analysis Flow
24
28
 
@@ -115,216 +119,45 @@ Controller (@Get/@Post) ──┐
115
119
  Database ─────────────┘
116
120
  ```
117
121
 
118
- **Component Separation**
119
- - `MethodCallGraph`: Pure graph construction logic (no logging)
120
- - `EndpointDetector`: Endpoint impact analysis + verbose logging
121
- - `DatabaseDetector`: Database impact analysis + verbose logging
122
- - `ImpactAnalyzer`: Orchestration and aggregation
123
-
124
- ## Features
125
-
126
- ### 1. Change Detection
127
- - Detects modified, added, and deleted files between git references
128
- - Extracts changed symbols (functions, classes, methods) using AST parsing
129
- - Categorizes files by type (source, test, config)
130
- - Calculates line changes for each file
131
-
132
- ### 2. API Endpoint Analysis
133
- - Automatically detects affected REST API endpoints
134
- - Supports multiple frameworks:
135
- - NestJS decorators (`@Get()`, `@Post()`, etc.)
136
- - Express routes (`app.get()`, `router.post()`, etc.)
137
- - Fastify routes
138
- - Groups endpoints by controller
139
- - Shows impact level for each endpoint
140
-
141
- ### 3. Database Impact Analysis
142
- - Detects database operations across ORMs:
143
- - Prisma
144
- - TypeORM
145
- - Sequelize
146
- - Identifies affected tables and fields
147
- - Lists database operations (CREATE, UPDATE, DELETE, etc.)
148
- - Checks for migration files
149
- - Shows sample queries
150
-
151
- ### 4. Pages/Components Detection
152
- - Automatically detects UI changes
153
- - Supports:
154
- - Pages (React, Next.js, Vue, etc.)
155
- - Components
156
- - Views
157
- - Screens (React Native)
158
- - Groups by type for easy review
159
- - Shows status and line changes
160
-
161
- ### 5. Logic Impact Analysis
162
- - Builds dependency graphs
163
- - Finds direct and indirect callers of changed functions
164
- - Calculates risk levels based on impact scope
165
- - Detects control flow changes
166
-
167
- ### 7. Comprehensive Reporting
168
- - **Markdown Reports** - Formatted, readable reports with tables and sections
169
- - **JSON Reports** - Machine-readable output for CI/CD integration
170
- - **Console Output** - Quick summary with color-coded severity
171
- - **Impact Scoring** - Numerical score based on change magnitude
172
-
173
- ## Configuration
174
-
175
- ### Command Line Options
176
-
177
- ```bash
178
- node index.js [OPTIONS]
179
- ```
180
-
181
- | Option | Description | Default |
182
- |--------|-------------|---------|
183
- | `--input=DIR` | Source directory to analyze | `src` |
184
- | `--base=REF` | Base git reference (branch/commit) | `origin/main` |
185
- | `--head=REF` | Head git reference (branch/commit) | `HEAD` |
186
- | `--exclude=PATHS` | Comma-separated paths to exclude | `node_modules,dist,build,specs,coverage` |
187
- | `--output=FILE` | Output markdown file path | `impact-report.md` |
188
- | `--json=FILE` | Optional JSON output file | - |
189
- | `--max-depth=N` | Maximum dependency traversal depth | `3` |
190
- | `--include-tests` | Include test files in analysis | `false` |
191
- | `--no-fail` | Don't exit with error on critical impact | `false` |
192
- | `--verbose` | Show verbose output | `false` |
193
-
194
- ### Configuration File
195
-
196
- Default configuration in `config/default-config.js`:
197
-
198
- ```javascript
199
- {
200
- sourceDir: 'src',
201
- excludePaths: ['node_modules', 'dist', 'build', 'specs', 'coverage'],
202
- baseRef: 'origin/main',
203
- headRef: 'HEAD',
204
- maxDepth: 3,
205
- includeTests: false,
206
- verbose: false,
207
- outputFormat: 'markdown',
208
- outputFile: 'impact-report.md'
209
- }
210
- ```
211
-
212
- ### Environment Setup
213
-
214
- 1. **Prerequisites**
215
- - Node.js 16+
216
- - Git repository
217
- - npm or yarn
218
-
219
- 2. **Installation**
220
- ```bash
221
- cd impact-analyzer
222
- npm install
223
- # or
224
- yarn install
225
- ```
226
-
227
122
  ## Usage
228
123
 
229
- ### Basic Usage
230
-
231
- Analyze changes between current branch and main:
232
-
233
- ```bash
234
- node index.js --input=src --base=origin/main --head=HEAD
235
- ```
236
-
237
- ### Using the Shell Script
238
-
239
- The included shell script provides a convenient wrapper:
240
-
241
- ```bash
242
- # Make it executable
243
- chmod +x run-impact-analysis.sh
244
-
245
- # Run with defaults
246
- ./run-impact-analysis.sh
247
-
248
- # Run with custom options
249
- ./run-impact-analysis.sh --input=src --base=origin/develop --output=report.md
250
- ```
251
-
252
- ### NPM Scripts
253
-
254
- ```bash
255
- # Analyze local changes
256
- npm run analyze:local
257
-
258
- # Custom analysis
259
- npm run analyze -- --input=src --base=main --json=impact.json
260
- ```
261
-
262
- ### Common Scenarios
263
-
264
- #### 1. Analyze PR Changes
265
-
266
- ```bash
267
- # Compare feature branch against main
268
- node index.js \
269
- --input=src \
270
- --base=origin/main \
271
- --head=HEAD \
272
- --output=pr-impact.md
273
- ```
274
-
275
- #### 2. Analyze Specific Commit Range
124
+ ### CLI Options
276
125
 
277
126
  ```bash
278
- # Compare two commits
279
- node index.js \
280
- --input=src \
281
- --base=abc123 \
282
- --head=def456 \
283
- --output=commit-impact.md
127
+ npx @sun-asterisk/impact-analyzer [options]
284
128
  ```
285
129
 
286
- #### 3. Generate JSON Report for CI/CD
130
+ | Option | Description | Required |
131
+ |--------|-------------|----------|
132
+ | `--input` | Source directory path | ✅ |
133
+ | `--base` | Base git reference (branch/commit/tag) | ✅ |
134
+ | `--head` | Head git reference | No (default: `HEAD`) |
135
+ | `--output` | Markdown report output path | No |
136
+ | `--json` | JSON report output path | No |
137
+ | `--verbose` | Enable verbose logging | No |
287
138
 
288
- ```bash
289
- # Generate both markdown and JSON
290
- node index.js \
291
- --input=src \
292
- --base=origin/main \
293
- --head=HEAD \
294
- --output=impact-report.md \
295
- --json=impact-report.json
296
- ```
297
-
298
- #### 4. Analyze with Verbose Output
139
+ ### Examples
299
140
 
300
141
  ```bash
301
- # Show detailed logs
302
- node index.js \
303
- --input=src \
304
- --base=origin/main \
305
- --verbose
306
- ```
142
+ # Basic analysis
143
+ npx @sun-asterisk/impact-analyzer --input=src --base=origin/main
307
144
 
308
- #### 5. Continue on Critical Impact
145
+ # Generate reports
146
+ npx @sun-asterisk/impact-analyzer --input=src --base=origin/main --output=report.md --json=report.json
309
147
 
310
- ```bash
311
- # Don't fail CI on critical severity
312
- node index.js \
313
- --input=src \
314
- --base=origin/main \
315
- --no-fail
148
+ # Compare specific commits
149
+ npx @sun-asterisk/impact-analyzer --input=src --base=abc123 --head=def456
316
150
  ```
317
151
 
318
- ### CI/CD Integration
152
+ ## CI/CD Integration
319
153
 
320
- #### GitHub Actions Example
154
+ ### GitHub Actions
321
155
 
322
156
  ```yaml
323
157
  name: Impact Analysis
324
-
325
158
  on:
326
159
  pull_request:
327
- branches: [main, develop]
160
+ types: [opened, synchronize]
328
161
 
329
162
  jobs:
330
163
  analyze:
@@ -333,39 +166,26 @@ jobs:
333
166
  - uses: actions/checkout@v3
334
167
  with:
335
168
  fetch-depth: 0
336
-
337
- - name: Setup Node.js
338
- uses: actions/setup-node@v3
169
+
170
+ - uses: actions/setup-node@v3
339
171
  with:
340
172
  node-version: '18'
341
-
342
- - name: Install Dependencies
343
- run: |
344
- cd impact-analyzer
345
- npm install
346
-
173
+
347
174
  - name: Run Impact Analysis
348
175
  run: |
349
- cd impact-analyzer
350
- node index.js \
351
- --input=../src \
176
+ npx @sun-asterisk/impact-analyzer \
177
+ --input=src \
352
178
  --base=origin/${{ github.base_ref }} \
353
- --head=HEAD \
179
+ --head=${{ github.sha }} \
354
180
  --output=impact-report.md \
355
181
  --json=impact-report.json
356
-
357
- - name: Upload Report
358
- uses: actions/upload-artifact@v3
359
- with:
360
- name: impact-report
361
- path: impact-analyzer/impact-report.md
362
-
182
+
363
183
  - name: Comment PR
364
184
  uses: actions/github-script@v6
365
185
  with:
366
186
  script: |
367
187
  const fs = require('fs');
368
- const report = fs.readFileSync('impact-analyzer/impact-report.md', 'utf8');
188
+ const report = fs.readFileSync('impact-report.md', 'utf8');
369
189
  github.rest.issues.createComment({
370
190
  issue_number: context.issue.number,
371
191
  owner: context.repo.owner,
@@ -374,133 +194,85 @@ jobs:
374
194
  });
375
195
  ```
376
196
 
377
- #### GitLab CI Example
197
+ ### GitLab CI
378
198
 
379
199
  ```yaml
380
- impact_analysis:
200
+ impact-analysis:
381
201
  stage: test
202
+ image: node:18
382
203
  script:
383
- - cd impact-analyzer
384
- - npm install
385
- - |
386
- node index.js \
387
- --input=../src \
388
- --base=origin/main \
389
- --head=HEAD \
390
- --output=impact-report.md \
204
+ - npx @sun-asterisk/impact-analyzer
205
+ --input=src
206
+ --base=origin/$CI_MERGE_REQUEST_TARGET_BRANCH_NAME
207
+ --head=$CI_COMMIT_SHA
208
+ --output=impact-report.md
391
209
  --json=impact-report.json
392
210
  artifacts:
393
211
  paths:
394
- - impact-analyzer/impact-report.md
395
- - impact-analyzer/impact-report.json
396
- reports:
397
- dotenv: impact-analyzer/impact-report.json
212
+ - impact-report.md
213
+ - impact-report.json
214
+ only:
215
+ - merge_requests
398
216
  ```
399
217
 
400
- ### Reading the Report
401
-
402
- The generated report includes:
403
-
404
- 1. **📊 Summary** - Overview of changes and severity
405
- 2. **📡 Affected API Endpoints** - List of impacted APIs grouped by controller
406
- 3. **💾 Database Impact** - Tables, fields, and operations affected
407
- 4. **📄 Affected Pages/Components** - UI changes grouped by type
408
- 5. **🔄 Logic Impact** - Call dependencies and risk level
409
- 6. **✅ Recommended Test Cases** - Suggested tests based on changes
410
- 7. **📝 Changed Files** - Complete list of modified files
411
-
412
- #### Severity Levels
413
-
414
- - 🟢 **LOW** (0-20 points) - Minor changes, low risk
415
- - 🟡 **MEDIUM** (21-50 points) - Moderate impact, standard testing required
416
- - 🟠 **HIGH** (51-100 points) - Significant impact, thorough testing needed
417
- - 🔴 **CRITICAL** (100+ points) - Major changes, full regression testing recommended
418
-
419
- #### Impact Scoring
420
-
421
- The impact score is calculated based on:
422
- - Affected endpoints: +10 points each
423
- - Database tables impacted: +5 points each
424
- - Direct function callers: +3 points each
425
- - Indirect function callers: +1 point each
426
- - High risk logic: 1.5x multiplier
427
- - Database migration: +20 points
428
-
429
- ### Example Output
430
-
431
- ```markdown
432
- # 🔍 Impact Analysis Report
433
-
434
- ## 📊 Summary
435
-
436
- | Metric | Value |
437
- |--------|-------|
438
- | Files Changed | 5 |
439
- | Symbols Modified | 12 |
440
- | Impact Score | **45** |
441
- | Severity | 🟡 **MEDIUM** |
442
-
443
- ## 📡 Affected API Endpoints
218
+ ### Jenkins
219
+
220
+ ```groovy
221
+ pipeline {
222
+ agent any
223
+ stages {
224
+ stage('Impact Analysis') {
225
+ steps {
226
+ sh '''
227
+ npx @sun-asterisk/impact-analyzer \
228
+ --input=src \
229
+ --base=origin/main \
230
+ --output=impact-report.md \
231
+ --json=impact-report.json
232
+ '''
233
+ }
234
+ }
235
+ }
236
+ }
237
+ ```
444
238
 
445
- **Total Endpoints Affected:** 3
239
+ ## Report Output
446
240
 
447
- ### Endpoint List
448
- | Method | Path | Controller | Impact |
449
- |--------|------|------------|--------|
450
- | **GET** | `/api/users` | UserController | 🟡 medium |
451
- | **POST** | `/api/users` | UserController | 🔴 high |
241
+ ### Severity Levels
452
242
 
453
- ## 💾 Database Impact
243
+ - 🟢 **LOW** (0-20) - Minor changes
244
+ - 🟡 **MEDIUM** (21-50) - Moderate impact
245
+ - 🟠 **HIGH** (51-100) - Significant impact
246
+ - 🔴 **CRITICAL** (100+) - Major changes
454
247
 
455
- **Total Tables Affected:** 2
248
+ ### Impact Score Calculation
456
249
 
457
- ### Tables Summary
458
- | Table | Operations | Fields Count | Migration |
459
- |-------|------------|--------------|-----------|
460
- | `users` | UPDATE | 3 | ✅ Yes |
461
- | `profiles` | CREATE, UPDATE | 5 | ❌ No |
462
- ```
250
+ - Endpoints: +10 each
251
+ - DB Tables: +5 each
252
+ - Direct Callers: +3 each
253
+ - Indirect Callers: +1 each
254
+ - High Risk Logic: ×1.5
255
+ - DB Migration: +20
463
256
 
464
257
  ## Troubleshooting
465
258
 
466
259
  ### Common Issues
467
260
 
468
- 1. **"Source directory does not exist"**
469
- - Ensure the `--input` path is correct and relative to the analyzer directory
470
-
471
- 2. **"Base ref does not exist"**
472
- - Run `git fetch` to ensure remote branches are up to date
473
- - Verify the branch/commit exists: `git show origin/main`
474
-
475
- 3. **"No changes detected"**
476
- - Check if there are actual differences: `git diff origin/main HEAD`
477
- - Ensure you're in a git repository
478
-
479
- 4. **Parse errors for certain files**
480
- - The analyzer uses Babel parser with common plugins
481
- - Some experimental syntax may not be supported
482
- - These files will be logged and skipped
261
+ **"Source directory does not exist"**
262
+ - Verify `--input` path is correct
483
263
 
484
- ### Debug Mode
264
+ **"Base ref does not exist"**
265
+ - Run `git fetch` to update branches
266
+ - Verify branch exists: `git show origin/main`
485
267
 
486
- Run with verbose flag to see detailed logs:
268
+ **"No changes detected"**
269
+ - Check differences: `git diff origin/main HEAD`
487
270
 
271
+ **Debug Mode**
488
272
  ```bash
489
- node index.js --input=src --base=origin/main --verbose
273
+ npx @sun-asterisk/impact-analyzer --input=src --base=origin/main --verbose
490
274
  ```
491
275
 
492
- ## Contributing
493
-
494
- Contributions are welcome! Please ensure:
495
- - Code follows existing style (no spaces after dots)
496
- - All functions have single responsibility
497
- - Use descriptive variable and function names
498
- - Add tests for new features
499
-
500
276
  ## License
501
277
 
502
278
  MIT
503
-
504
- ## Support
505
-
506
- For issues, questions, or suggestions, please create an issue in the repository.
package/index.js CHANGED
File without changes
@@ -448,89 +448,64 @@ export class MethodCallGraph {
448
448
 
449
449
  /**
450
450
  * Get changed methods from git diff
451
- * Detects both:
452
- * 1. Methods that contain changed lines
453
- * 2. Method calls that were added/removed
451
+ * Uses ts-morph AST to detect which specific methods contain changes
454
452
  */
455
453
  getChangedMethods(diff, filePath) {
456
- const changedMethods = new Set();
457
- const changedMethodCalls = new Set();
458
-
459
454
  if (!diff || !filePath) return [];
460
455
 
461
456
  const sourceFile = this.project.getSourceFile(filePath);
462
457
  if (!sourceFile) return [];
463
458
 
464
- const classes = sourceFile.getClasses();
465
- if (classes.length === 0) return [];
466
-
467
- // Parse diff to extract changed line numbers
459
+ // Extract changed line numbers from diff
468
460
  const changedLines = this.extractChangedLineNumbers(diff);
469
-
470
461
  if (changedLines.length === 0) return [];
471
462
 
472
- // 1. Find methods that contain the changed lines
463
+ const changedMethods = [];
464
+
465
+ // Get all classes in the file
466
+ const classes = sourceFile.getClasses();
467
+
473
468
  for (const classDecl of classes) {
474
469
  const className = classDecl.getName();
470
+ if (!className) continue;
471
+
475
472
  const methods = classDecl.getMethods();
476
-
473
+
477
474
  for (const method of methods) {
478
475
  const methodName = method.getName();
479
- const startLine = method.getStartLineNumber();
480
- const endLine = method.getEndLineNumber();
481
-
482
- // Check if any changed line falls within this method's range
483
- const hasChangedLine = changedLines.some(
484
- lineNum => lineNum >= startLine && lineNum <= endLine
485
- );
486
-
487
- if (hasChangedLine) {
488
- const fullName = `${className}.${methodName}`;
489
- changedMethods.add(fullName);
490
- }
491
- }
492
- }
493
-
494
- // 2. Detect method calls that were modified in the diff
495
- const diffLines = diff.split('\n');
496
-
497
- for (const line of diffLines) {
498
- // Only look at added/removed lines
499
- if (!line.startsWith('+') && !line.startsWith('-')) continue;
500
-
501
- const codeLine = line.substring(1).trim();
502
-
503
- // Pattern: object.methodName(...) or await object.methodName(...)
504
- const methodCallPattern = /(?:await\s+)?(\w+)\.(\w+)\s*\(/g;
505
- let match;
506
-
507
- while ((match = methodCallPattern.exec(codeLine)) !== null) {
508
- const objectName = match[1];
509
- const methodName = match[2];
510
476
 
511
- // Try to resolve the type of the object
512
- const resolvedType = this.resolveObjectType(objectName, sourceFile, classes);
513
-
514
- if (resolvedType) {
515
- const fullName = `${resolvedType}.${methodName}`;
516
- changedMethodCalls.add(fullName);
477
+ // Check if this specific method contains changes
478
+ if (this.methodContainsChanges(method, changedLines)) {
479
+ changedMethods.push({
480
+ className: className,
481
+ methodName: methodName,
482
+ file: filePath,
483
+ fullName: `${className}.${methodName}`
484
+ });
517
485
  }
518
486
  }
519
487
  }
520
-
521
- // Combine both: methods containing changes + method calls that changed
522
- const allChangedMethods = [...changedMethods, ...changedMethodCalls];
523
488
 
524
- // Convert to objects with metadata
525
- return [...new Set(allChangedMethods)].map(fullName => {
526
- const parts = fullName.split('.');
527
- return {
528
- className: parts[0],
529
- methodName: parts[1],
530
- file: filePath,
531
- fullName: fullName
532
- };
533
- });
489
+ return changedMethods;
490
+ }
491
+
492
+ /**
493
+ * Check if a method contains actual code changes using ts-morph AST
494
+ */
495
+ methodContainsChanges(method, changedLines) {
496
+ const body = method.getBody();
497
+ if (!body) return false;
498
+
499
+ // Get the method body block (excluding signature and decorators)
500
+ const bodyStartLine = body.getStartLineNumber();
501
+ const bodyEndLine = body.getEndLineNumber();
502
+
503
+ // Check if any changed line is within the method body
504
+ const hasChangesInBody = changedLines.some(
505
+ line => line >= bodyStartLine && line <= bodyEndLine
506
+ );
507
+
508
+ return hasChangesInBody;
534
509
  }
535
510
 
536
511
  /**
package/package.json CHANGED
@@ -1,9 +1,12 @@
1
1
  {
2
2
  "name": "@sun-asterisk/impact-analyzer",
3
- "version": "1.0.0",
3
+ "version": "1.0.2",
4
4
  "description": "Automated impact analysis for TypeScript/JavaScript projects",
5
5
  "main": "index.js",
6
6
  "type": "module",
7
+ "bin": {
8
+ "impact-analyzer": "./index.js"
9
+ },
7
10
  "scripts": {
8
11
  "analyze": "node index.js",
9
12
  "analyze:local": "node index.js --input=src --base=origin/main --head=HEAD",
@@ -21,6 +24,5 @@
21
24
  "@babel/traverse": "^7.23.0",
22
25
  "glob": "^10.3.0",
23
26
  "ts-morph": "^27.0.2"
24
- },
25
- "devDependencies": {}
27
+ }
26
28
  }