react-code-smell-detector 1.1.1 → 1.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (66) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +115 -11
  3. package/dist/analyzer.d.ts.map +1 -1
  4. package/dist/analyzer.js +65 -2
  5. package/dist/cli.js +134 -33
  6. package/dist/detectors/accessibility.d.ts +12 -0
  7. package/dist/detectors/accessibility.d.ts.map +1 -0
  8. package/dist/detectors/accessibility.js +191 -0
  9. package/dist/detectors/complexity.d.ts +17 -0
  10. package/dist/detectors/complexity.d.ts.map +1 -0
  11. package/dist/detectors/complexity.js +69 -0
  12. package/dist/detectors/debug.d.ts +10 -0
  13. package/dist/detectors/debug.d.ts.map +1 -0
  14. package/dist/detectors/debug.js +87 -0
  15. package/dist/detectors/imports.d.ts +22 -0
  16. package/dist/detectors/imports.d.ts.map +1 -0
  17. package/dist/detectors/imports.js +210 -0
  18. package/dist/detectors/index.d.ts +6 -0
  19. package/dist/detectors/index.d.ts.map +1 -1
  20. package/dist/detectors/index.js +8 -0
  21. package/dist/detectors/memoryLeak.d.ts +7 -0
  22. package/dist/detectors/memoryLeak.d.ts.map +1 -0
  23. package/dist/detectors/memoryLeak.js +111 -0
  24. package/dist/detectors/security.d.ts +12 -0
  25. package/dist/detectors/security.d.ts.map +1 -0
  26. package/dist/detectors/security.js +161 -0
  27. package/dist/fixer.d.ts +23 -0
  28. package/dist/fixer.d.ts.map +1 -0
  29. package/dist/fixer.js +133 -0
  30. package/dist/git.d.ts +28 -0
  31. package/dist/git.d.ts.map +1 -0
  32. package/dist/git.js +117 -0
  33. package/dist/htmlReporter.d.ts +6 -0
  34. package/dist/htmlReporter.d.ts.map +1 -0
  35. package/dist/htmlReporter.js +453 -0
  36. package/dist/reporter.js +26 -0
  37. package/dist/types/index.d.ts +10 -1
  38. package/dist/types/index.d.ts.map +1 -1
  39. package/dist/types/index.js +13 -0
  40. package/dist/watcher.d.ts +16 -0
  41. package/dist/watcher.d.ts.map +1 -0
  42. package/dist/watcher.js +89 -0
  43. package/package.json +8 -2
  44. package/src/analyzer.ts +0 -269
  45. package/src/cli.ts +0 -125
  46. package/src/detectors/deadCode.ts +0 -163
  47. package/src/detectors/dependencyArray.ts +0 -176
  48. package/src/detectors/hooksRules.ts +0 -101
  49. package/src/detectors/index.ts +0 -16
  50. package/src/detectors/javascript.ts +0 -169
  51. package/src/detectors/largeComponent.ts +0 -63
  52. package/src/detectors/magicValues.ts +0 -114
  53. package/src/detectors/memoization.ts +0 -177
  54. package/src/detectors/missingKey.ts +0 -105
  55. package/src/detectors/nestedTernary.ts +0 -75
  56. package/src/detectors/nextjs.ts +0 -124
  57. package/src/detectors/nodejs.ts +0 -199
  58. package/src/detectors/propDrilling.ts +0 -103
  59. package/src/detectors/reactNative.ts +0 -154
  60. package/src/detectors/typescript.ts +0 -151
  61. package/src/detectors/useEffect.ts +0 -117
  62. package/src/index.ts +0 -4
  63. package/src/parser/index.ts +0 -195
  64. package/src/reporter.ts +0 -278
  65. package/src/types/index.ts +0 -144
  66. package/tsconfig.json +0 -19
@@ -1,195 +0,0 @@
1
- import * as parser from '@babel/parser';
2
- import _traverse, { NodePath } from '@babel/traverse';
3
- import * as t from '@babel/types';
4
- import fs from 'fs/promises';
5
-
6
- // Handle ESM/CJS interop
7
- const traverse = (_traverse as unknown as { default: typeof _traverse }).default || _traverse;
8
-
9
- export interface ParsedComponent {
10
- name: string;
11
- startLine: number;
12
- endLine: number;
13
- node: t.FunctionDeclaration | t.ArrowFunctionExpression | t.FunctionExpression;
14
- path: NodePath;
15
- hooks: {
16
- useEffect: t.CallExpression[];
17
- useState: t.CallExpression[];
18
- useMemo: t.CallExpression[];
19
- useCallback: t.CallExpression[];
20
- useRef: t.CallExpression[];
21
- custom: t.CallExpression[];
22
- };
23
- props: string[];
24
- jsxDepth: number;
25
- }
26
-
27
- export interface ParseResult {
28
- ast: t.File;
29
- components: ParsedComponent[];
30
- imports: string[];
31
- sourceCode: string;
32
- }
33
-
34
- export async function parseFile(filePath: string): Promise<ParseResult> {
35
- const sourceCode = await fs.readFile(filePath, 'utf-8');
36
- return parseCode(sourceCode, filePath);
37
- }
38
-
39
- export function parseCode(sourceCode: string, filePath: string = 'unknown'): ParseResult {
40
- const ast = parser.parse(sourceCode, {
41
- sourceType: 'module',
42
- plugins: [
43
- 'jsx',
44
- 'typescript',
45
- 'decorators-legacy',
46
- 'classProperties',
47
- 'optionalChaining',
48
- 'nullishCoalescingOperator',
49
- ],
50
- sourceFilename: filePath,
51
- });
52
-
53
- const components: ParsedComponent[] = [];
54
- const imports: string[] = [];
55
-
56
- traverse(ast, {
57
- ImportDeclaration(path) {
58
- imports.push(path.node.source.value);
59
- },
60
-
61
- FunctionDeclaration(path) {
62
- if (isReactComponent(path.node.id?.name, path)) {
63
- components.push(extractComponentInfo(path.node.id?.name || 'Anonymous', path));
64
- }
65
- },
66
-
67
- VariableDeclarator(path) {
68
- const init = path.node.init;
69
- const id = path.node.id;
70
-
71
- if (
72
- t.isIdentifier(id) &&
73
- (t.isArrowFunctionExpression(init) || t.isFunctionExpression(init))
74
- ) {
75
- if (isReactComponent(id.name, path)) {
76
- components.push(extractComponentInfo(id.name, path, init));
77
- }
78
- }
79
- },
80
- });
81
-
82
- return { ast, components, imports, sourceCode };
83
- }
84
-
85
- function isReactComponent(name: string | undefined, path: NodePath): boolean {
86
- if (!name) return false;
87
-
88
- // Component names start with uppercase
89
- if (!/^[A-Z]/.test(name)) return false;
90
-
91
- // Check if it returns JSX
92
- let hasJSX = false;
93
- path.traverse({
94
- JSXElement() {
95
- hasJSX = true;
96
- },
97
- JSXFragment() {
98
- hasJSX = true;
99
- },
100
- });
101
-
102
- return hasJSX;
103
- }
104
-
105
- function extractComponentInfo(
106
- name: string,
107
- path: NodePath,
108
- node?: t.ArrowFunctionExpression | t.FunctionExpression
109
- ): ParsedComponent {
110
- const actualNode = node || (path.node as t.FunctionDeclaration);
111
- const loc = actualNode.loc;
112
-
113
- const hooks = {
114
- useEffect: [] as t.CallExpression[],
115
- useState: [] as t.CallExpression[],
116
- useMemo: [] as t.CallExpression[],
117
- useCallback: [] as t.CallExpression[],
118
- useRef: [] as t.CallExpression[],
119
- custom: [] as t.CallExpression[],
120
- };
121
-
122
- const props: string[] = [];
123
- let jsxDepth = 0;
124
-
125
- // Extract hooks
126
- path.traverse({
127
- CallExpression(callPath) {
128
- const callee = callPath.node.callee;
129
- if (t.isIdentifier(callee)) {
130
- const hookName = callee.name;
131
- if (hookName === 'useEffect') hooks.useEffect.push(callPath.node);
132
- else if (hookName === 'useState') hooks.useState.push(callPath.node);
133
- else if (hookName === 'useMemo') hooks.useMemo.push(callPath.node);
134
- else if (hookName === 'useCallback') hooks.useCallback.push(callPath.node);
135
- else if (hookName === 'useRef') hooks.useRef.push(callPath.node);
136
- else if (hookName.startsWith('use')) hooks.custom.push(callPath.node);
137
- }
138
- },
139
- });
140
-
141
- // Extract props
142
- const params = t.isFunctionDeclaration(actualNode)
143
- ? actualNode.params
144
- : actualNode.params;
145
-
146
- if (params.length > 0) {
147
- const firstParam = params[0];
148
- if (t.isObjectPattern(firstParam)) {
149
- firstParam.properties.forEach(prop => {
150
- if (t.isObjectProperty(prop) && t.isIdentifier(prop.key)) {
151
- props.push(prop.key.name);
152
- } else if (t.isRestElement(prop) && t.isIdentifier(prop.argument)) {
153
- props.push(`...${prop.argument.name}`);
154
- }
155
- });
156
- } else if (t.isIdentifier(firstParam)) {
157
- props.push(firstParam.name);
158
- }
159
- }
160
-
161
- // Calculate JSX nesting depth
162
- path.traverse({
163
- JSXElement: {
164
- enter() {
165
- jsxDepth++;
166
- },
167
- },
168
- });
169
-
170
- return {
171
- name,
172
- startLine: loc?.start.line || 0,
173
- endLine: loc?.end.line || 0,
174
- node: actualNode as any,
175
- path,
176
- hooks,
177
- props,
178
- jsxDepth: Math.floor(jsxDepth / 2), // Approximate depth
179
- };
180
- }
181
-
182
- export function getCodeSnippet(sourceCode: string, line: number, context: number = 2): string {
183
- const lines = sourceCode.split('\n');
184
- const start = Math.max(0, line - context - 1);
185
- const end = Math.min(lines.length, line + context);
186
-
187
- return lines
188
- .slice(start, end)
189
- .map((l, i) => {
190
- const lineNum = start + i + 1;
191
- const marker = lineNum === line ? '>' : ' ';
192
- return `${marker} ${lineNum.toString().padStart(4)} | ${l}`;
193
- })
194
- .join('\n');
195
- }
package/src/reporter.ts DELETED
@@ -1,278 +0,0 @@
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
- 'missing-key': '🔑 Missing Key',
247
- 'hooks-rules-violation': '⚠️ Hooks Rules Violation',
248
- 'dependency-array-issue': '📋 Dependency Array Issue',
249
- 'nested-ternary': '❓ Nested Ternary',
250
- 'dead-code': '💀 Dead Code',
251
- 'magic-value': '🔢 Magic Value',
252
- // Next.js
253
- 'nextjs-client-server-boundary': '▲ Next.js Client/Server Boundary',
254
- 'nextjs-missing-metadata': '▲ Next.js Missing Metadata',
255
- 'nextjs-image-unoptimized': '▲ Next.js Unoptimized Image',
256
- 'nextjs-router-misuse': '▲ Next.js Router Misuse',
257
- // React Native
258
- 'rn-inline-style': '📱 RN Inline Style',
259
- 'rn-missing-accessibility': '📱 RN Missing Accessibility',
260
- 'rn-performance-issue': '📱 RN Performance Issue',
261
- // Node.js
262
- 'nodejs-callback-hell': '🟢 Node.js Callback Hell',
263
- 'nodejs-unhandled-promise': '🟢 Node.js Unhandled Promise',
264
- 'nodejs-sync-io': '🟢 Node.js Sync I/O',
265
- 'nodejs-missing-error-handling': '🟢 Node.js Missing Error Handling',
266
- // JavaScript
267
- 'js-var-usage': '📜 JS var Usage',
268
- 'js-loose-equality': '📜 JS Loose Equality',
269
- 'js-implicit-coercion': '📜 JS Implicit Coercion',
270
- 'js-global-pollution': '📜 JS Global Pollution',
271
- // TypeScript
272
- 'ts-any-usage': '🔷 TS any Usage',
273
- 'ts-missing-return-type': '🔷 TS Missing Return Type',
274
- 'ts-non-null-assertion': '🔷 TS Non-null Assertion',
275
- 'ts-type-assertion': '🔷 TS Type Assertion',
276
- };
277
- return labels[type] || type;
278
- }
@@ -1,144 +0,0 @@
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
- | 'missing-key'
13
- | 'hooks-rules-violation'
14
- | 'dependency-array-issue'
15
- | 'nested-ternary'
16
- | 'dead-code'
17
- | 'magic-value'
18
- // Next.js specific
19
- | 'nextjs-client-server-boundary'
20
- | 'nextjs-missing-metadata'
21
- | 'nextjs-image-unoptimized'
22
- | 'nextjs-router-misuse'
23
- // React Native specific
24
- | 'rn-inline-style'
25
- | 'rn-missing-accessibility'
26
- | 'rn-performance-issue'
27
- // Node.js specific
28
- | 'nodejs-callback-hell'
29
- | 'nodejs-unhandled-promise'
30
- | 'nodejs-sync-io'
31
- | 'nodejs-missing-error-handling'
32
- // JavaScript specific
33
- | 'js-var-usage'
34
- | 'js-loose-equality'
35
- | 'js-implicit-coercion'
36
- | 'js-global-pollution'
37
- // TypeScript specific
38
- | 'ts-any-usage'
39
- | 'ts-missing-return-type'
40
- | 'ts-non-null-assertion'
41
- | 'ts-type-assertion';
42
-
43
- export interface CodeSmell {
44
- type: SmellType;
45
- severity: SmellSeverity;
46
- message: string;
47
- file: string;
48
- line: number;
49
- column: number;
50
- suggestion: string;
51
- codeSnippet?: string;
52
- }
53
-
54
- export interface ComponentInfo {
55
- name: string;
56
- file: string;
57
- startLine: number;
58
- endLine: number;
59
- lineCount: number;
60
- useEffectCount: number;
61
- useStateCount: number;
62
- useMemoCount: number;
63
- useCallbackCount: number;
64
- propsCount: number;
65
- propsDrillingDepth: number;
66
- hasExpensiveCalculation: boolean;
67
- }
68
-
69
- export interface FileAnalysis {
70
- file: string;
71
- components: ComponentInfo[];
72
- smells: CodeSmell[];
73
- imports: string[];
74
- }
75
-
76
- export interface AnalysisResult {
77
- files: FileAnalysis[];
78
- summary: AnalysisSummary;
79
- debtScore: TechnicalDebtScore;
80
- }
81
-
82
- export interface AnalysisSummary {
83
- totalFiles: number;
84
- totalComponents: number;
85
- totalSmells: number;
86
- smellsByType: Record<SmellType, number>;
87
- smellsBySeverity: Record<SmellSeverity, number>;
88
- }
89
-
90
- export interface TechnicalDebtScore {
91
- score: number; // 0-100, 100 = no debt
92
- grade: 'A' | 'B' | 'C' | 'D' | 'F';
93
- breakdown: {
94
- useEffectScore: number;
95
- propDrillingScore: number;
96
- componentSizeScore: number;
97
- memoizationScore: number;
98
- };
99
- estimatedRefactorTime: string; // e.g., "2-4 hours"
100
- }
101
-
102
- export interface DetectorConfig {
103
- maxUseEffectsPerComponent: number;
104
- maxPropDrillingDepth: number;
105
- maxComponentLines: number;
106
- maxPropsCount: number;
107
- checkMemoization: boolean;
108
- checkMissingKeys: boolean;
109
- checkHooksRules: boolean;
110
- checkDependencyArrays: boolean;
111
- maxTernaryDepth: number;
112
- checkDeadCode: boolean;
113
- checkMagicValues: boolean;
114
- magicNumberThreshold: number;
115
- // Framework detection
116
- checkNextjs: boolean;
117
- checkReactNative: boolean;
118
- checkNodejs: boolean;
119
- checkJavascript: boolean;
120
- checkTypescript: boolean;
121
- maxCallbackDepth: number;
122
- }
123
-
124
- export const DEFAULT_CONFIG: DetectorConfig = {
125
- maxUseEffectsPerComponent: 3,
126
- maxPropDrillingDepth: 3,
127
- maxComponentLines: 300,
128
- maxPropsCount: 7,
129
- checkMemoization: true,
130
- checkMissingKeys: true,
131
- checkHooksRules: true,
132
- checkDependencyArrays: true,
133
- maxTernaryDepth: 2,
134
- checkDeadCode: true,
135
- checkMagicValues: true,
136
- magicNumberThreshold: 10,
137
- // Framework detection - auto-enabled based on project
138
- checkNextjs: true,
139
- checkReactNative: true,
140
- checkNodejs: true,
141
- checkJavascript: true,
142
- checkTypescript: true,
143
- maxCallbackDepth: 3,
144
- };
package/tsconfig.json DELETED
@@ -1,19 +0,0 @@
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
- }