react-code-smell-detector 1.0.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.
Files changed (47) hide show
  1. package/README.md +179 -0
  2. package/dist/analyzer.d.ts +10 -0
  3. package/dist/analyzer.d.ts.map +1 -0
  4. package/dist/analyzer.js +169 -0
  5. package/dist/cli.d.ts +3 -0
  6. package/dist/cli.d.ts.map +1 -0
  7. package/dist/cli.js +113 -0
  8. package/dist/detectors/index.d.ts +5 -0
  9. package/dist/detectors/index.d.ts.map +1 -0
  10. package/dist/detectors/index.js +4 -0
  11. package/dist/detectors/largeComponent.d.ts +4 -0
  12. package/dist/detectors/largeComponent.d.ts.map +1 -0
  13. package/dist/detectors/largeComponent.js +51 -0
  14. package/dist/detectors/memoization.d.ts +4 -0
  15. package/dist/detectors/memoization.d.ts.map +1 -0
  16. package/dist/detectors/memoization.js +150 -0
  17. package/dist/detectors/propDrilling.d.ts +5 -0
  18. package/dist/detectors/propDrilling.d.ts.map +1 -0
  19. package/dist/detectors/propDrilling.js +82 -0
  20. package/dist/detectors/useEffect.d.ts +4 -0
  21. package/dist/detectors/useEffect.d.ts.map +1 -0
  22. package/dist/detectors/useEffect.js +101 -0
  23. package/dist/index.d.ts +5 -0
  24. package/dist/index.d.ts.map +1 -0
  25. package/dist/index.js +4 -0
  26. package/dist/parser/index.d.ts +29 -0
  27. package/dist/parser/index.d.ts.map +1 -0
  28. package/dist/parser/index.js +151 -0
  29. package/dist/reporter.d.ts +8 -0
  30. package/dist/reporter.d.ts.map +1 -0
  31. package/dist/reporter.js +217 -0
  32. package/dist/types/index.d.ts +64 -0
  33. package/dist/types/index.d.ts.map +1 -0
  34. package/dist/types/index.js +7 -0
  35. package/package.json +45 -0
  36. package/src/analyzer.ts +216 -0
  37. package/src/cli.ts +125 -0
  38. package/src/detectors/index.ts +4 -0
  39. package/src/detectors/largeComponent.ts +63 -0
  40. package/src/detectors/memoization.ts +177 -0
  41. package/src/detectors/propDrilling.ts +103 -0
  42. package/src/detectors/useEffect.ts +117 -0
  43. package/src/index.ts +4 -0
  44. package/src/parser/index.ts +195 -0
  45. package/src/reporter.ts +248 -0
  46. package/src/types/index.ts +86 -0
  47. package/tsconfig.json +19 -0
@@ -0,0 +1,248 @@
1
+ import chalk from 'chalk';
2
+ import { AnalysisResult, CodeSmell, SmellSeverity } from './types/index.js';
3
+ import path from 'path';
4
+
5
+ export interface ReporterOptions {
6
+ format: 'console' | 'json' | 'markdown';
7
+ showCodeSnippets: boolean;
8
+ rootDir: string;
9
+ }
10
+
11
+ export function reportResults(result: AnalysisResult, options: ReporterOptions): string {
12
+ switch (options.format) {
13
+ case 'json':
14
+ return JSON.stringify(result, null, 2);
15
+ case 'markdown':
16
+ return formatMarkdown(result, options);
17
+ case 'console':
18
+ default:
19
+ return formatConsole(result, options);
20
+ }
21
+ }
22
+
23
+ function formatConsole(result: AnalysisResult, options: ReporterOptions): string {
24
+ const lines: string[] = [];
25
+ const { summary, debtScore, files } = result;
26
+
27
+ // Header
28
+ lines.push('');
29
+ lines.push(chalk.bold.cyan('╔══════════════════════════════════════════════════════════════╗'));
30
+ lines.push(chalk.bold.cyan('║') + chalk.bold.white(' 🔍 React Code Smell Detector Report ') + chalk.bold.cyan('║'));
31
+ lines.push(chalk.bold.cyan('╚══════════════════════════════════════════════════════════════╝'));
32
+ lines.push('');
33
+
34
+ // Technical Debt Score
35
+ const gradeColor = getGradeColor(debtScore.grade);
36
+ lines.push(chalk.bold('📊 Technical Debt Score'));
37
+ lines.push('');
38
+ lines.push(` ${chalk.bold('Grade:')} ${gradeColor(debtScore.grade)} ${getScoreBar(debtScore.score)} ${debtScore.score}/100`);
39
+ lines.push('');
40
+ lines.push(chalk.dim(' Breakdown:'));
41
+ lines.push(` ${chalk.yellow('⚡')} useEffect: ${getSmallBar(debtScore.breakdown.useEffectScore)} ${debtScore.breakdown.useEffectScore}`);
42
+ lines.push(` ${chalk.blue('🔗')} Prop Drilling: ${getSmallBar(debtScore.breakdown.propDrillingScore)} ${debtScore.breakdown.propDrillingScore}`);
43
+ lines.push(` ${chalk.magenta('📐')} Component Size:${getSmallBar(debtScore.breakdown.componentSizeScore)} ${debtScore.breakdown.componentSizeScore}`);
44
+ lines.push(` ${chalk.green('💾')} Memoization: ${getSmallBar(debtScore.breakdown.memoizationScore)} ${debtScore.breakdown.memoizationScore}`);
45
+ lines.push('');
46
+ lines.push(` ${chalk.dim('Estimated refactor time:')} ${chalk.yellow(debtScore.estimatedRefactorTime)}`);
47
+ lines.push('');
48
+
49
+ // Summary
50
+ lines.push(chalk.bold('📈 Summary'));
51
+ lines.push('');
52
+ lines.push(` Files analyzed: ${chalk.cyan(summary.totalFiles)}`);
53
+ lines.push(` Components found: ${chalk.cyan(summary.totalComponents)}`);
54
+ lines.push(` Total issues: ${getSeverityLabel(summary.totalSmells, summary.smellsBySeverity)}`);
55
+ lines.push('');
56
+
57
+ // Issues by type
58
+ if (summary.totalSmells > 0) {
59
+ lines.push(chalk.bold('🏷️ Issues by Type'));
60
+ lines.push('');
61
+ Object.entries(summary.smellsByType).forEach(([type, count]) => {
62
+ if (count > 0) {
63
+ lines.push(` ${chalk.dim('•')} ${formatSmellType(type)}: ${chalk.yellow(count)}`);
64
+ }
65
+ });
66
+ lines.push('');
67
+ }
68
+
69
+ // Detailed findings
70
+ if (files.some(f => f.smells.length > 0)) {
71
+ lines.push(chalk.bold('📋 Detailed Findings'));
72
+ lines.push('');
73
+
74
+ files.forEach(file => {
75
+ if (file.smells.length === 0) return;
76
+
77
+ const relativePath = path.relative(options.rootDir, file.file);
78
+ lines.push(chalk.bold.underline(relativePath));
79
+ lines.push('');
80
+
81
+ file.smells.forEach(smell => {
82
+ const icon = getSeverityIcon(smell.severity);
83
+ const color = getSeverityColor(smell.severity);
84
+
85
+ lines.push(` ${icon} ${color(smell.message)}`);
86
+ lines.push(` ${chalk.dim('Line')} ${smell.line} ${chalk.dim('•')} ${chalk.italic.cyan(smell.suggestion)}`);
87
+
88
+ if (options.showCodeSnippets && smell.codeSnippet) {
89
+ lines.push('');
90
+ smell.codeSnippet.split('\n').forEach(line => {
91
+ if (line.startsWith('>')) {
92
+ lines.push(chalk.red(line));
93
+ } else {
94
+ lines.push(chalk.dim(line));
95
+ }
96
+ });
97
+ }
98
+ lines.push('');
99
+ });
100
+ });
101
+ }
102
+
103
+ // Footer
104
+ if (summary.totalSmells === 0) {
105
+ lines.push(chalk.green.bold('✨ No code smells detected! Your code looks great.'));
106
+ } else {
107
+ lines.push(chalk.dim('─'.repeat(64)));
108
+ lines.push(chalk.dim(`Found ${summary.totalSmells} issue(s). Run with --help for more options.`));
109
+ }
110
+ lines.push('');
111
+
112
+ return lines.join('\n');
113
+ }
114
+
115
+ function formatMarkdown(result: AnalysisResult, options: ReporterOptions): string {
116
+ const lines: string[] = [];
117
+ const { summary, debtScore, files } = result;
118
+
119
+ lines.push('# React Code Smell Detector Report');
120
+ lines.push('');
121
+ lines.push('## Technical Debt Score');
122
+ lines.push('');
123
+ lines.push(`| Metric | Score |`);
124
+ lines.push(`|--------|-------|`);
125
+ lines.push(`| **Overall Grade** | **${debtScore.grade}** (${debtScore.score}/100) |`);
126
+ lines.push(`| useEffect Usage | ${debtScore.breakdown.useEffectScore}/100 |`);
127
+ lines.push(`| Prop Drilling | ${debtScore.breakdown.propDrillingScore}/100 |`);
128
+ lines.push(`| Component Size | ${debtScore.breakdown.componentSizeScore}/100 |`);
129
+ lines.push(`| Memoization | ${debtScore.breakdown.memoizationScore}/100 |`);
130
+ lines.push('');
131
+ lines.push(`**Estimated Refactor Time:** ${debtScore.estimatedRefactorTime}`);
132
+ lines.push('');
133
+
134
+ lines.push('## Summary');
135
+ lines.push('');
136
+ lines.push(`- **Files analyzed:** ${summary.totalFiles}`);
137
+ lines.push(`- **Components found:** ${summary.totalComponents}`);
138
+ lines.push(`- **Total issues:** ${summary.totalSmells}`);
139
+ lines.push(` - Errors: ${summary.smellsBySeverity.error}`);
140
+ lines.push(` - Warnings: ${summary.smellsBySeverity.warning}`);
141
+ lines.push(` - Info: ${summary.smellsBySeverity.info}`);
142
+ lines.push('');
143
+
144
+ if (summary.totalSmells > 0) {
145
+ lines.push('## Issues by Type');
146
+ lines.push('');
147
+ Object.entries(summary.smellsByType).forEach(([type, count]) => {
148
+ if (count > 0) {
149
+ lines.push(`- ${formatSmellType(type)}: ${count}`);
150
+ }
151
+ });
152
+ lines.push('');
153
+
154
+ lines.push('## Detailed Findings');
155
+ lines.push('');
156
+
157
+ files.forEach(file => {
158
+ if (file.smells.length === 0) return;
159
+
160
+ const relativePath = path.relative(options.rootDir, file.file);
161
+ lines.push(`### ${relativePath}`);
162
+ lines.push('');
163
+
164
+ file.smells.forEach(smell => {
165
+ const icon = smell.severity === 'error' ? '🔴' : smell.severity === 'warning' ? '🟡' : '🔵';
166
+ lines.push(`#### ${icon} ${smell.message}`);
167
+ lines.push('');
168
+ lines.push(`- **Line:** ${smell.line}`);
169
+ lines.push(`- **Severity:** ${smell.severity}`);
170
+ lines.push(`- **Suggestion:** ${smell.suggestion}`);
171
+
172
+ if (options.showCodeSnippets && smell.codeSnippet) {
173
+ lines.push('');
174
+ lines.push('```tsx');
175
+ lines.push(smell.codeSnippet);
176
+ lines.push('```');
177
+ }
178
+ lines.push('');
179
+ });
180
+ });
181
+ }
182
+
183
+ return lines.join('\n');
184
+ }
185
+
186
+ // Helper functions
187
+ function getGradeColor(grade: string): (text: string) => string {
188
+ switch (grade) {
189
+ case 'A': return chalk.green.bold;
190
+ case 'B': return chalk.greenBright.bold;
191
+ case 'C': return chalk.yellow.bold;
192
+ case 'D': return chalk.rgb(255, 165, 0).bold;
193
+ case 'F': return chalk.red.bold;
194
+ default: return chalk.white.bold;
195
+ }
196
+ }
197
+
198
+ function getScoreBar(score: number): string {
199
+ const filled = Math.round(score / 5);
200
+ const empty = 20 - filled;
201
+ const color = score >= 80 ? chalk.green : score >= 60 ? chalk.yellow : chalk.red;
202
+ return color('█'.repeat(filled)) + chalk.dim('░'.repeat(empty));
203
+ }
204
+
205
+ function getSmallBar(score: number): string {
206
+ const filled = Math.round(score / 10);
207
+ const empty = 10 - filled;
208
+ const color = score >= 80 ? chalk.green : score >= 60 ? chalk.yellow : chalk.red;
209
+ return color('█'.repeat(filled)) + chalk.dim('░'.repeat(empty));
210
+ }
211
+
212
+ function getSeverityIcon(severity: SmellSeverity): string {
213
+ switch (severity) {
214
+ case 'error': return chalk.red('✖');
215
+ case 'warning': return chalk.yellow('⚠');
216
+ case 'info': return chalk.blue('ℹ');
217
+ }
218
+ }
219
+
220
+ function getSeverityColor(severity: SmellSeverity): (text: string) => string {
221
+ switch (severity) {
222
+ case 'error': return chalk.red;
223
+ case 'warning': return chalk.yellow;
224
+ case 'info': return chalk.blue;
225
+ }
226
+ }
227
+
228
+ function getSeverityLabel(total: number, bySeverity: Record<SmellSeverity, number>): string {
229
+ const parts: string[] = [];
230
+ if (bySeverity.error > 0) parts.push(chalk.red(`${bySeverity.error} error(s)`));
231
+ if (bySeverity.warning > 0) parts.push(chalk.yellow(`${bySeverity.warning} warning(s)`));
232
+ if (bySeverity.info > 0) parts.push(chalk.blue(`${bySeverity.info} info`));
233
+ return parts.length > 0 ? parts.join(', ') : chalk.green('0');
234
+ }
235
+
236
+ function formatSmellType(type: string): string {
237
+ const labels: Record<string, string> = {
238
+ 'useEffect-overuse': '⚡ useEffect Overuse',
239
+ 'prop-drilling': '🔗 Prop Drilling',
240
+ 'large-component': '📐 Large Component',
241
+ 'unmemoized-calculation': '💾 Unmemoized Calculation',
242
+ 'missing-dependency': '🔍 Missing Dependency',
243
+ 'state-in-loop': '🔄 State in Loop',
244
+ 'inline-function-prop': '📎 Inline Function Prop',
245
+ 'deep-nesting': '📊 Deep Nesting',
246
+ };
247
+ return labels[type] || type;
248
+ }
@@ -0,0 +1,86 @@
1
+ export type SmellSeverity = 'error' | 'warning' | 'info';
2
+
3
+ export type SmellType =
4
+ | 'useEffect-overuse'
5
+ | 'prop-drilling'
6
+ | 'large-component'
7
+ | 'unmemoized-calculation'
8
+ | 'missing-dependency'
9
+ | 'state-in-loop'
10
+ | 'inline-function-prop'
11
+ | 'deep-nesting';
12
+
13
+ export interface CodeSmell {
14
+ type: SmellType;
15
+ severity: SmellSeverity;
16
+ message: string;
17
+ file: string;
18
+ line: number;
19
+ column: number;
20
+ suggestion: string;
21
+ codeSnippet?: string;
22
+ }
23
+
24
+ export interface ComponentInfo {
25
+ name: string;
26
+ file: string;
27
+ startLine: number;
28
+ endLine: number;
29
+ lineCount: number;
30
+ useEffectCount: number;
31
+ useStateCount: number;
32
+ useMemoCount: number;
33
+ useCallbackCount: number;
34
+ propsCount: number;
35
+ propsDrillingDepth: number;
36
+ hasExpensiveCalculation: boolean;
37
+ }
38
+
39
+ export interface FileAnalysis {
40
+ file: string;
41
+ components: ComponentInfo[];
42
+ smells: CodeSmell[];
43
+ imports: string[];
44
+ }
45
+
46
+ export interface AnalysisResult {
47
+ files: FileAnalysis[];
48
+ summary: AnalysisSummary;
49
+ debtScore: TechnicalDebtScore;
50
+ }
51
+
52
+ export interface AnalysisSummary {
53
+ totalFiles: number;
54
+ totalComponents: number;
55
+ totalSmells: number;
56
+ smellsByType: Record<SmellType, number>;
57
+ smellsBySeverity: Record<SmellSeverity, number>;
58
+ }
59
+
60
+ export interface TechnicalDebtScore {
61
+ score: number; // 0-100, 100 = no debt
62
+ grade: 'A' | 'B' | 'C' | 'D' | 'F';
63
+ breakdown: {
64
+ useEffectScore: number;
65
+ propDrillingScore: number;
66
+ componentSizeScore: number;
67
+ memoizationScore: number;
68
+ };
69
+ estimatedRefactorTime: string; // e.g., "2-4 hours"
70
+ }
71
+
72
+ export interface DetectorConfig {
73
+ maxUseEffectsPerComponent: number;
74
+ maxPropDrillingDepth: number;
75
+ maxComponentLines: number;
76
+ maxPropsCount: number;
77
+ checkMemoization: boolean;
78
+ }
79
+
80
+ export const DEFAULT_CONFIG: DetectorConfig = {
81
+ maxUseEffectsPerComponent: 3,
82
+ maxPropDrillingDepth: 3,
83
+ maxComponentLines: 300,
84
+ maxPropsCount: 7,
85
+ checkMemoization: true,
86
+ };
package/tsconfig.json ADDED
@@ -0,0 +1,19 @@
1
+ {
2
+ "compilerOptions": {
3
+ "target": "ES2022",
4
+ "module": "ESNext",
5
+ "moduleResolution": "bundler",
6
+ "lib": ["ES2022"],
7
+ "outDir": "./dist",
8
+ "rootDir": "./src",
9
+ "declaration": true,
10
+ "declarationMap": true,
11
+ "strict": true,
12
+ "esModuleInterop": true,
13
+ "skipLibCheck": true,
14
+ "forceConsistentCasingInFileNames": true,
15
+ "resolveJsonModule": true
16
+ },
17
+ "include": ["src/**/*"],
18
+ "exclude": ["node_modules", "dist"]
19
+ }