@sun-asterisk/sunlint 1.1.7 → 1.2.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 (74) hide show
  1. package/.sunlint.json +1 -1
  2. package/CHANGELOG.md +83 -0
  3. package/README.md +66 -4
  4. package/config/presets/all.json +125 -0
  5. package/config/presets/beginner.json +16 -8
  6. package/config/presets/ci.json +12 -4
  7. package/config/presets/maintainability.json +38 -0
  8. package/config/presets/performance.json +32 -0
  9. package/config/presets/quality.json +103 -0
  10. package/config/presets/recommended.json +36 -12
  11. package/config/presets/security.json +88 -0
  12. package/config/presets/strict.json +15 -5
  13. package/config/rules/rules-registry-generated.json +6312 -0
  14. package/config/rules-summary.json +1941 -0
  15. package/core/adapters/sunlint-rule-adapter.js +452 -0
  16. package/core/analysis-orchestrator.js +4 -4
  17. package/core/config-manager.js +28 -5
  18. package/core/rule-selection-service.js +52 -55
  19. package/docs/CONFIGURATION.md +111 -3
  20. package/docs/LANGUAGE-SPECIFIC-RULES.md +308 -0
  21. package/docs/README.md +3 -0
  22. package/docs/STANDARDIZED-CATEGORY-FILTERING.md +156 -0
  23. package/engines/eslint-engine.js +92 -2
  24. package/engines/heuristic-engine.js +8 -31
  25. package/origin-rules/common-en.md +1320 -0
  26. package/origin-rules/dart-en.md +289 -0
  27. package/origin-rules/java-en.md +60 -0
  28. package/origin-rules/kotlin-mobile-en.md +453 -0
  29. package/origin-rules/reactjs-en.md +102 -0
  30. package/origin-rules/security-en.md +1055 -0
  31. package/origin-rules/swift-en.md +449 -0
  32. package/origin-rules/typescript-en.md +136 -0
  33. package/package.json +6 -5
  34. package/scripts/copy-rules.js +86 -0
  35. package/rules/README.md +0 -252
  36. package/rules/common/C002_no_duplicate_code/analyzer.js +0 -65
  37. package/rules/common/C002_no_duplicate_code/config.json +0 -23
  38. package/rules/common/C003_no_vague_abbreviations/analyzer.js +0 -418
  39. package/rules/common/C003_no_vague_abbreviations/config.json +0 -35
  40. package/rules/common/C006_function_naming/analyzer.js +0 -349
  41. package/rules/common/C006_function_naming/config.json +0 -86
  42. package/rules/common/C010_limit_block_nesting/analyzer.js +0 -389
  43. package/rules/common/C013_no_dead_code/analyzer.js +0 -206
  44. package/rules/common/C014_dependency_injection/analyzer.js +0 -338
  45. package/rules/common/C017_constructor_logic/analyzer.js +0 -314
  46. package/rules/common/C019_log_level_usage/analyzer.js +0 -362
  47. package/rules/common/C019_log_level_usage/config.json +0 -121
  48. package/rules/common/C029_catch_block_logging/analyzer.js +0 -373
  49. package/rules/common/C029_catch_block_logging/config.json +0 -59
  50. package/rules/common/C031_validation_separation/analyzer.js +0 -186
  51. package/rules/common/C041_no_sensitive_hardcode/analyzer.js +0 -292
  52. package/rules/common/C042_boolean_name_prefix/analyzer.js +0 -300
  53. package/rules/common/C043_no_console_or_print/analyzer.js +0 -304
  54. package/rules/common/C047_no_duplicate_retry_logic/analyzer.js +0 -351
  55. package/rules/common/C075_explicit_return_types/analyzer.js +0 -103
  56. package/rules/common/C076_single_test_behavior/analyzer.js +0 -121
  57. package/rules/docs/C002_no_duplicate_code.md +0 -57
  58. package/rules/docs/C031_validation_separation.md +0 -72
  59. package/rules/index.js +0 -149
  60. package/rules/migration/converter.js +0 -385
  61. package/rules/migration/mapping.json +0 -164
  62. package/rules/security/S026_json_schema_validation/analyzer.js +0 -251
  63. package/rules/security/S026_json_schema_validation/config.json +0 -27
  64. package/rules/security/S027_no_hardcoded_secrets/analyzer.js +0 -263
  65. package/rules/security/S027_no_hardcoded_secrets/config.json +0 -29
  66. package/rules/security/S029_csrf_protection/analyzer.js +0 -264
  67. package/rules/tests/C002_no_duplicate_code.test.js +0 -50
  68. package/rules/universal/C010/generic.js +0 -0
  69. package/rules/universal/C010/tree-sitter-analyzer.js +0 -0
  70. package/rules/utils/ast-utils.js +0 -191
  71. package/rules/utils/base-analyzer.js +0 -98
  72. package/rules/utils/pattern-matchers.js +0 -239
  73. package/rules/utils/rule-helpers.js +0 -264
  74. package/rules/utils/severity-constants.js +0 -93
@@ -1,292 +0,0 @@
1
- const fs = require('fs');
2
- const path = require('path');
3
-
4
- class C041Analyzer {
5
- constructor() {
6
- this.ruleId = 'C041';
7
- this.ruleName = 'No Hardcoded Sensitive Information';
8
- this.description = 'Không hardcode hoặc push thông tin nhạy cảm vào repo';
9
- }
10
-
11
- async analyze(files, language, options = {}) {
12
- const violations = [];
13
-
14
- for (const filePath of files) {
15
- if (options.verbose) {
16
- console.log(`🔍 Running C041 analysis on ${path.basename(filePath)}`);
17
- }
18
-
19
- try {
20
- const content = fs.readFileSync(filePath, 'utf8');
21
- const fileViolations = await this.analyzeFile(filePath, content, language, options);
22
- violations.push(...fileViolations);
23
- } catch (error) {
24
- console.warn(`⚠️ Failed to analyze ${filePath}: ${error.message}`);
25
- }
26
- }
27
-
28
- return violations;
29
- }
30
-
31
- async analyzeFile(filePath, content, language, config) {
32
- switch (language) {
33
- case 'typescript':
34
- case 'javascript':
35
- return this.analyzeTypeScript(filePath, content, config);
36
- default:
37
- return [];
38
- }
39
- }
40
-
41
- async analyzeTypeScript(filePath, content, config) {
42
- const violations = [];
43
- const lines = content.split('\n');
44
-
45
- lines.forEach((line, index) => {
46
- const lineNumber = index + 1;
47
- const trimmedLine = line.trim();
48
-
49
- // Skip comments and imports
50
- if (this.isCommentOrImport(trimmedLine)) {
51
- return;
52
- }
53
-
54
- // Find potential hardcoded sensitive values
55
- const sensitiveMatches = this.findSensitiveHardcode(trimmedLine, line);
56
-
57
- sensitiveMatches.forEach(match => {
58
- violations.push({
59
- ruleId: this.ruleId,
60
- file: filePath,
61
- line: lineNumber,
62
- column: match.column,
63
- message: match.message,
64
- severity: 'error',
65
- code: trimmedLine,
66
- type: match.type,
67
- confidence: match.confidence,
68
- suggestion: match.suggestion
69
- });
70
- });
71
- });
72
-
73
- return violations;
74
- }
75
-
76
- isCommentOrImport(line) {
77
- const trimmed = line.trim();
78
- return trimmed.startsWith('//') ||
79
- trimmed.startsWith('/*') ||
80
- trimmed.startsWith('*') ||
81
- trimmed.startsWith('import ') ||
82
- trimmed.startsWith('export ');
83
- }
84
-
85
- findSensitiveHardcode(line, originalLine) {
86
- const matches = [];
87
-
88
- // Skip template literals with variables - they are dynamic, not hardcoded
89
- if (line.includes('${') || line.includes('`')) {
90
- return matches;
91
- }
92
-
93
- // Skip if line is clearly configuration, type definition, or UI-related
94
- if (this.isConfigOrUIContext(line)) {
95
- return matches;
96
- }
97
-
98
- // Look for suspicious patterns with better context awareness
99
- const patterns = [
100
- {
101
- name: 'suspicious_password_variable',
102
- regex: /(const|let|var)\s+\w*[Pp]ass[Ww]ord\w*\s*=\s*['"`]([^'"`]{4,})['"`]/g,
103
- severity: 'error',
104
- message: 'Potential hardcoded password in variable assignment',
105
- suggestion: 'Move sensitive values to environment variables or secure config files'
106
- },
107
- {
108
- name: 'suspicious_secret_variable',
109
- regex: /(const|let|var)\s+\w*[Ss]ecret\w*\s*=\s*['"`]([^'"`]{6,})['"`]/g,
110
- severity: 'error',
111
- message: 'Potential hardcoded secret in variable assignment',
112
- suggestion: 'Use environment variables for secrets'
113
- },
114
- {
115
- name: 'suspicious_short_password',
116
- regex: /(const|let|var)\s+(?!use)\w*([Pp]ass|[Dd]b[Pp]ass|[Aa]dmin)(?!word[A-Z])\w*\s*=\s*['"`]([^'"`]{4,})['"`]/g,
117
- severity: 'error',
118
- message: 'Potential hardcoded password or admin credential',
119
- suggestion: 'Use environment variables for credentials'
120
- },
121
- {
122
- name: 'api_key',
123
- regex: /(const|let|var)\s+\w*[Aa]pi[Kk]ey\w*\s*=\s*['"`]([^'"`]{10,})['"`]/g,
124
- severity: 'error',
125
- message: 'Potential hardcoded API key detected',
126
- suggestion: 'Use environment variables for API keys'
127
- },
128
- {
129
- name: 'auth_token',
130
- regex: /(const|let|var)\s+\w*[Tt]oken\w*\s*=\s*['"`]([^'"`]{16,})['"`]/g,
131
- severity: 'error',
132
- message: 'Potential hardcoded authentication token detected',
133
- suggestion: 'Store tokens in secure storage, not in source code'
134
- },
135
- {
136
- name: 'database_url',
137
- regex: /['"`](mongodb|mysql|postgres|redis):\/\/[^'"`]+['"`]/gi,
138
- severity: 'error',
139
- message: 'Hardcoded database connection string detected',
140
- suggestion: 'Use environment variables for database connections'
141
- },
142
- {
143
- name: 'suspicious_url',
144
- regex: /['"`]https?:\/\/(?!localhost|127\.0\.0\.1|example\.com|test\.com|www\.w3\.org|www\.google\.com|googleapis\.com)[^'"`]{20,}['"`]/gi,
145
- severity: 'warning',
146
- message: 'Hardcoded external URL detected (consider configuration)',
147
- suggestion: 'Consider moving URLs to configuration files'
148
- }
149
- ];
150
-
151
- // Additional context-aware checks
152
- patterns.forEach(pattern => {
153
- let match;
154
- while ((match = pattern.regex.exec(line)) !== null) {
155
- // Skip false positives
156
- if (this.isFalsePositive(line, match[0], pattern.name)) {
157
- continue;
158
- }
159
-
160
- matches.push({
161
- type: pattern.name,
162
- column: match.index + 1,
163
- message: pattern.message,
164
- confidence: this.calculateConfidence(line, match[0], pattern.name),
165
- suggestion: pattern.suggestion
166
- });
167
- }
168
- });
169
-
170
- return matches;
171
- }
172
-
173
- isConfigOrUIContext(line) {
174
- const lowerLine = line.toLowerCase();
175
-
176
- // UI/Component contexts - likely false positives
177
- const uiContexts = [
178
- 'inputtype', 'type:', 'type =', 'type:', 'inputtype=',
179
- 'routes =', 'route:', 'path:', 'routes:',
180
- 'import {', 'export {', 'from ', 'import ',
181
- 'interface', 'type ', 'enum ',
182
- 'props:', 'defaultprops',
183
- 'schema', 'validator',
184
- 'hook', 'use', 'const use', 'import.*use',
185
- // React/UI specific
186
- 'textinput', 'input ', 'field ', 'form',
187
- 'component', 'page', 'screen', 'modal',
188
- // Route/navigation specific
189
- 'navigation', 'route', 'path', 'url:', 'route:',
190
- 'setuppassword', 'resetpassword', 'forgotpassword',
191
- 'changepassword', 'confirmpassword'
192
- ];
193
-
194
- return uiContexts.some(context => lowerLine.includes(context));
195
- }
196
-
197
- isFalsePositive(line, matchedText, patternName) {
198
- const lowerLine = line.toLowerCase();
199
- const lowerMatch = matchedText.toLowerCase();
200
-
201
- // Global false positive indicators
202
- const globalFalsePositives = [
203
- 'test', 'mock', 'example', 'demo', 'sample', 'placeholder', 'dummy', 'fake',
204
- 'xmlns', 'namespace', 'schema', 'w3.org', 'google.com', 'googleapis.com',
205
- 'error', 'message', 'missing', 'invalid', 'failed'
206
- ];
207
-
208
- // Check if the line contains any global false positive indicators
209
- const hasGlobalFalsePositive = globalFalsePositives.some(pattern =>
210
- lowerLine.includes(pattern) || lowerMatch.includes(pattern)
211
- );
212
-
213
- if (hasGlobalFalsePositive) {
214
- return true;
215
- }
216
-
217
- // Common false positive patterns
218
- const falsePositivePatterns = {
219
- 'suspicious_password_variable': [
220
- 'inputtype', 'type:', 'type =', 'activation', 'forgot_password', 'reset_password',
221
- 'setup_password', 'route', 'path', 'hook', 'use', 'change', 'confirm',
222
- 'validation', 'component', 'page', 'screen', 'textinput', 'input',
223
- 'trigger', 'useeffect', 'password.*trigger', 'renewpassword'
224
- ],
225
- 'suspicious_short_password': [
226
- 'inputtype', 'type:', 'type =', 'activation', 'forgot_password', 'reset_password',
227
- 'setup_password', 'route', 'path', 'hook', 'use', 'change', 'confirm',
228
- 'validation', 'component', 'page', 'screen', 'textinput'
229
- ],
230
- 'suspicious_secret_variable': [
231
- 'component', 'props', 'state', 'hook', 'use'
232
- ],
233
- 'suspicious_url': [
234
- 'localhost', '127.0.0.1', 'example.com', 'test.com', 'placeholder',
235
- 'mock', 'w3.org', 'google.com', 'recaptcha', 'googleapis.com'
236
- ],
237
- 'api_key': [
238
- 'test-', 'mock-', 'example-', 'demo-', 'missing', 'error', 'message'
239
- ]
240
- };
241
-
242
- const patterns = falsePositivePatterns[patternName] || [];
243
-
244
- // Check if line contains any pattern-specific false positive indicators
245
- const hasPatternFalsePositive = patterns.some(pattern =>
246
- lowerLine.includes(pattern) || lowerMatch.includes(pattern)
247
- );
248
-
249
- // Special handling for password-related patterns
250
- if (patternName === 'hardcoded_password') {
251
- // Allow if it's clearly UI/component related
252
- if (lowerLine.includes('input') ||
253
- lowerLine.includes('field') ||
254
- lowerLine.includes('form') ||
255
- lowerLine.includes('component') ||
256
- lowerLine.includes('type') ||
257
- lowerLine.includes('route') ||
258
- lowerLine.includes('path') ||
259
- lowerMatch.includes('activation') ||
260
- lowerMatch.includes('forgot_password') ||
261
- lowerMatch.includes('reset_password') ||
262
- lowerMatch.includes('setup_password')) {
263
- return true;
264
- }
265
- }
266
-
267
- return hasPatternFalsePositive;
268
- }
269
-
270
- calculateConfidence(line, match, patternName) {
271
- let confidence = 0.8; // Base confidence
272
-
273
- // Reduce confidence for potential false positives
274
- const lowerLine = line.toLowerCase();
275
-
276
- if (lowerLine.includes('test') || lowerLine.includes('mock') || lowerLine.includes('example')) {
277
- confidence -= 0.3;
278
- }
279
-
280
- if (lowerLine.includes('const') || lowerLine.includes('let') || lowerLine.includes('var')) {
281
- confidence += 0.1; // Variable assignments more likely to be hardcode
282
- }
283
-
284
- if (lowerLine.includes('type') || lowerLine.includes('component') || lowerLine.includes('props')) {
285
- confidence -= 0.2; // UI-related less likely to be sensitive
286
- }
287
-
288
- return Math.max(0.3, Math.min(1.0, confidence));
289
- }
290
- }
291
-
292
- module.exports = new C041Analyzer();
@@ -1,300 +0,0 @@
1
- /**
2
- * Heuristic analyzer for: C042 – Boolean variable names should start with proper prefixes
3
- * Purpose: Detect boolean variables that don't follow naming conventions
4
- */
5
-
6
- class C042Analyzer {
7
- constructor() {
8
- this.ruleId = 'C042';
9
- this.ruleName = 'Boolean Variable Naming';
10
- this.description = 'Boolean variable names should start with is, has, should, can, will, must, may, or check';
11
-
12
- // User requested to add "check" prefix
13
- this.booleanPrefixes = [
14
- 'is', 'has', 'should', 'can', 'will', 'must', 'may', 'check',
15
- 'are', 'were', 'was', 'could', 'might', 'shall', 'need', 'want'
16
- ];
17
-
18
- // Common non-boolean patterns to ignore (user feedback)
19
- this.ignoredPatterns = [
20
- // Fallback/default patterns: var = value || fallback
21
- /\w+\s*=\s*\w+\s*\|\|\s*[^|]/,
22
- // Assignment patterns that are clearly not boolean
23
- /\w+\s*=\s*['"`][^'"`]*['"`]/, // String assignments
24
- /\w+\s*=\s*\d+/, // Number assignments
25
- /\w+\s*=\s*\{/, // Object assignments
26
- /\w+\s*=\s*\[/, // Array assignments
27
- ];
28
-
29
- // Variables that commonly aren't boolean but might look like it
30
- this.commonNonBooleans = [
31
- 'value', 'result', 'data', 'config', 'name', 'id', 'key',
32
- 'path', 'url', 'src', 'href', 'text', 'message', 'error',
33
- 'response', 'request', 'params', 'options', 'settings'
34
- ];
35
- }
36
-
37
- async analyze(files, language, options = {}) {
38
- const violations = [];
39
-
40
- for (const filePath of files) {
41
- if (options.verbose) {
42
- console.log(`🔍 Running C042 analysis on ${require('path').basename(filePath)}`);
43
- }
44
-
45
- try {
46
- const content = require('fs').readFileSync(filePath, 'utf8');
47
- const fileViolations = this.analyzeFile(content, filePath);
48
- violations.push(...fileViolations);
49
- } catch (error) {
50
- console.warn(`⚠️ Failed to analyze ${filePath}: ${error.message}`);
51
- }
52
- }
53
-
54
- return violations;
55
- }
56
-
57
- analyzeFile(content, filePath) {
58
- const violations = [];
59
- const lines = content.split('\n');
60
-
61
- for (let i = 0; i < lines.length; i++) {
62
- const line = lines[i].trim();
63
-
64
- // Skip empty lines, comments, imports, and type declarations
65
- if (!line || line.startsWith('//') || line.startsWith('/*') ||
66
- line.startsWith('import') || line.startsWith('export') ||
67
- line.startsWith('declare') || line.startsWith('*')) {
68
- continue;
69
- }
70
-
71
- const lineViolations = this.analyzeDeclaration(line, i + 1);
72
- lineViolations.forEach(violation => {
73
- violations.push({
74
- ...violation,
75
- file: filePath
76
- });
77
- });
78
- }
79
-
80
- return violations;
81
- }
82
-
83
- analyzeDeclaration(line, lineNumber) {
84
- const violations = [];
85
-
86
- // Match variable declarations with boolean values
87
- const booleanAssignments = this.findBooleanAssignments(line);
88
-
89
- for (const assignment of booleanAssignments) {
90
- const { varName, isBooleanValue, hasPrefix, actualValue } = assignment;
91
-
92
- // Case 1: Variable is assigned a boolean value but doesn't have proper prefix
93
- if (isBooleanValue && !hasPrefix) {
94
- // Skip if this matches user feedback patterns (false positives)
95
- if (this.shouldSkipBooleanVariableCheck(varName, line, actualValue)) {
96
- continue;
97
- }
98
-
99
- violations.push({
100
- line: lineNumber,
101
- column: line.indexOf(varName) + 1,
102
- message: `Boolean variable '${varName}' should start with a descriptive prefix like 'is', 'has', 'should', 'can', or 'check'. Consider: ${this.generateSuggestions(varName).join(', ')}.`,
103
- severity: 'warning',
104
- ruleId: this.ruleId
105
- });
106
- }
107
-
108
- // Case 2: Variable has boolean prefix but is assigned a non-boolean value
109
- else if (hasPrefix && !isBooleanValue && actualValue && this.isDefinitelyNotBoolean(actualValue)) {
110
- // Only skip very basic cases for prefix misuse
111
- if (varName.length <= 2) {
112
- continue;
113
- }
114
-
115
- const prefix = this.extractPrefix(varName);
116
- violations.push({
117
- line: lineNumber,
118
- column: line.indexOf(varName) + 1,
119
- message: `Variable '${varName}' uses boolean prefix '${prefix}' but is assigned a non-boolean value. Consider renaming or changing the value.`,
120
- severity: 'warning',
121
- ruleId: this.ruleId
122
- });
123
- }
124
- }
125
-
126
- return violations;
127
- }
128
-
129
- findBooleanAssignments(line) {
130
- const assignments = [];
131
-
132
- // Match declaration patterns only (avoid duplicates)
133
- const patterns = [
134
- // let/const/var varName = value
135
- /(?:let|const|var)\s+(\w+)\s*(?::\s*\w+\s*)?=\s*(.+?)(?:;|$)/g,
136
- ];
137
-
138
- for (const pattern of patterns) {
139
- let match;
140
- const seenVariables = new Set(); // Avoid duplicates
141
-
142
- while ((match = pattern.exec(line)) !== null) {
143
- const varName = match[1];
144
- const value = match[2].trim();
145
-
146
- // Skip if already processed
147
- if (seenVariables.has(varName)) {
148
- continue;
149
- }
150
- seenVariables.add(varName);
151
-
152
- // Skip destructuring and complex patterns
153
- if (varName.includes('[') || varName.includes('{') || value.includes('{') || value.includes('[')) {
154
- continue;
155
- }
156
-
157
- const isBooleanValue = this.isBooleanValue(value);
158
- const hasPrefix = this.hasBooleanPrefix(varName);
159
-
160
- assignments.push({
161
- varName,
162
- isBooleanValue,
163
- hasPrefix,
164
- actualValue: value
165
- });
166
- }
167
- }
168
-
169
- return assignments;
170
- }
171
-
172
- isBooleanValue(value) {
173
- const trimmedValue = value.trim();
174
-
175
- // Direct boolean literals
176
- if (trimmedValue === 'true' || trimmedValue === 'false') {
177
- return true;
178
- }
179
-
180
- // Boolean expressions that clearly result in boolean
181
- const booleanExpressions = [
182
- /\w+\s*[<>!=]=/, // Comparisons
183
- /\w+\s*(&&|\|\|)/, // Logical operations (but not fallback patterns)
184
- /^\!\w+/, // Negation
185
- /instanceof\s+/, // instanceof
186
- /\.test\(/, // regex.test()
187
- /\.includes\(/, // array.includes()
188
- /\.hasOwnProperty\(/, // hasOwnProperty
189
- /\.some\(/, // array.some()
190
- /\.every\(/, // array.every()
191
- /typeof\s+.*\s*===/, // typeof checks
192
- /Math\.random\(\)\s*[<>]/, // Math.random() comparisons
193
- /\.length\s*[<>!=]=/, // Length comparisons
194
- ];
195
-
196
- // Exclude fallback patterns (user feedback - these are NOT boolean)
197
- if (trimmedValue.includes('||')) {
198
- // Check if it's a boolean expression or just a fallback
199
- // If the || is followed by a non-boolean value, it's likely a fallback
200
- const parts = trimmedValue.split('||');
201
- if (parts.length === 2) {
202
- const fallback = parts[1].trim();
203
- // If fallback is clearly not boolean, this is not a boolean assignment
204
- if (this.isDefinitelyNotBoolean(fallback) || /^\d+$/.test(fallback) || /^['"`]/.test(fallback)) {
205
- return false;
206
- }
207
- }
208
- }
209
-
210
- return booleanExpressions.some(pattern => pattern.test(trimmedValue));
211
- }
212
-
213
- hasBooleanPrefix(varName) {
214
- const lowerName = varName.toLowerCase();
215
- return this.booleanPrefixes.some(prefix =>
216
- lowerName.startsWith(prefix.toLowerCase()) &&
217
- lowerName.length > prefix.length
218
- );
219
- }
220
-
221
- extractPrefix(varName) {
222
- const lowerName = varName.toLowerCase();
223
- for (const prefix of this.booleanPrefixes) {
224
- if (lowerName.startsWith(prefix.toLowerCase())) {
225
- return prefix;
226
- }
227
- }
228
- return '';
229
- }
230
-
231
- shouldSkipBooleanVariableCheck(varName, line, value) {
232
- // Skip very short names
233
- if (varName.length <= 2) {
234
- return true;
235
- }
236
-
237
- // Skip common non-boolean variable names
238
- if (this.commonNonBooleans.includes(varName.toLowerCase())) {
239
- return true;
240
- }
241
-
242
- // Skip user feedback patterns (fallback/default patterns)
243
- if (this.ignoredPatterns.some(pattern => pattern.test(line))) {
244
- return true;
245
- }
246
-
247
- // Skip function parameters and loop variables
248
- if (line.includes('function') || line.includes('for') || line.includes('=>')) {
249
- return true;
250
- }
251
-
252
- return false;
253
- }
254
-
255
- isDefinitelyNotBoolean(value) {
256
- const trimmedValue = value.trim();
257
-
258
- // String literals (including single quotes)
259
- if (trimmedValue.match(/^['"`][^'"`]*['"`]$/)) {
260
- return true;
261
- }
262
-
263
- // Number literals
264
- if (trimmedValue.match(/^\d+(\.\d+)?$/)) {
265
- return true;
266
- }
267
-
268
- // Object/array literals
269
- if (trimmedValue.startsWith('{') || trimmedValue.startsWith('[')) {
270
- return true;
271
- }
272
-
273
- // null, undefined
274
- if (trimmedValue === 'null' || trimmedValue === 'undefined') {
275
- return true;
276
- }
277
-
278
- // Common non-boolean patterns
279
- if (trimmedValue.includes('new ') || trimmedValue.includes('function')) {
280
- return true;
281
- }
282
-
283
- return false;
284
- }
285
-
286
- generateSuggestions(varName) {
287
- const suggestions = [];
288
- const baseName = varName.replace(/^(is|has|should|can|will|must|may|check)/i, '');
289
- const capitalizedBase = baseName.charAt(0).toUpperCase() + baseName.slice(1);
290
-
291
- // Generate a few reasonable suggestions
292
- suggestions.push(`is${capitalizedBase}`);
293
- suggestions.push(`has${capitalizedBase}`);
294
- suggestions.push(`should${capitalizedBase}`);
295
-
296
- return suggestions.slice(0, 3); // Limit to 3 suggestions
297
- }
298
- }
299
-
300
- module.exports = C042Analyzer;