@aiready/consistency 0.21.8 → 0.21.11

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 (136) hide show
  1. package/.turbo/turbo-build.log +23 -24
  2. package/.turbo/turbo-format-check.log +1 -1
  3. package/.turbo/turbo-lint.log +1 -1
  4. package/.turbo/turbo-test.log +18 -19
  5. package/.turbo/turbo-type-check.log +1 -1
  6. package/dist/index.d.mts +3 -3
  7. package/dist/index.d.ts +3 -3
  8. package/dist/index.js +4 -4
  9. package/dist/index.mjs +3 -3
  10. package/package.json +2 -2
  11. package/src/__tests__/provider.test.ts +6 -34
  12. package/src/index.ts +3 -3
  13. package/src/provider.ts +2 -2
  14. package/dist/__tests__/analyzer.test.d.ts +0 -2
  15. package/dist/__tests__/analyzer.test.d.ts.map +0 -1
  16. package/dist/__tests__/analyzer.test.js +0 -157
  17. package/dist/__tests__/analyzer.test.js.map +0 -1
  18. package/dist/__tests__/language-filter.test.d.ts +0 -2
  19. package/dist/__tests__/language-filter.test.d.ts.map +0 -1
  20. package/dist/__tests__/language-filter.test.js +0 -46
  21. package/dist/__tests__/language-filter.test.js.map +0 -1
  22. package/dist/__tests__/scoring.test.d.ts +0 -2
  23. package/dist/__tests__/scoring.test.d.ts.map +0 -1
  24. package/dist/__tests__/scoring.test.js +0 -118
  25. package/dist/__tests__/scoring.test.js.map +0 -1
  26. package/dist/analyzer.d.ts +0 -7
  27. package/dist/analyzer.d.ts.map +0 -1
  28. package/dist/analyzer.js +0 -160
  29. package/dist/analyzer.js.map +0 -1
  30. package/dist/analyzers/naming-ast.d.ts +0 -7
  31. package/dist/analyzers/naming-ast.d.ts.map +0 -1
  32. package/dist/analyzers/naming-ast.js +0 -253
  33. package/dist/analyzers/naming-ast.js.map +0 -1
  34. package/dist/analyzers/naming-constants.d.ts +0 -21
  35. package/dist/analyzers/naming-constants.d.ts.map +0 -1
  36. package/dist/analyzers/naming-constants.js +0 -96
  37. package/dist/analyzers/naming-constants.js.map +0 -1
  38. package/dist/analyzers/naming-python.d.ts +0 -16
  39. package/dist/analyzers/naming-python.d.ts.map +0 -1
  40. package/dist/analyzers/naming-python.js +0 -165
  41. package/dist/analyzers/naming-python.js.map +0 -1
  42. package/dist/analyzers/naming.d.ts +0 -6
  43. package/dist/analyzers/naming.d.ts.map +0 -1
  44. package/dist/analyzers/naming.js +0 -234
  45. package/dist/analyzers/naming.js.map +0 -1
  46. package/dist/analyzers/patterns.d.ts +0 -10
  47. package/dist/analyzers/patterns.d.ts.map +0 -1
  48. package/dist/analyzers/patterns.js +0 -197
  49. package/dist/analyzers/patterns.js.map +0 -1
  50. package/dist/chunk-2BTBNG6X.mjs +0 -814
  51. package/dist/chunk-3ZB6FFRL.mjs +0 -661
  52. package/dist/chunk-5UFRGXSB.mjs +0 -783
  53. package/dist/chunk-66M3TIO7.mjs +0 -837
  54. package/dist/chunk-6BM5MV3S.mjs +0 -719
  55. package/dist/chunk-6H3JHDP7.mjs +0 -832
  56. package/dist/chunk-7PHHJOGC.mjs +0 -1374
  57. package/dist/chunk-AASFXGUR.mjs +0 -1622
  58. package/dist/chunk-AR7DIZLP.mjs +0 -827
  59. package/dist/chunk-BDDMOIU2.mjs +0 -385
  60. package/dist/chunk-BMILMNKJ.mjs +0 -1633
  61. package/dist/chunk-BYY6MD5T.mjs +0 -729
  62. package/dist/chunk-CA4Q5JBK.mjs +0 -1143
  63. package/dist/chunk-CF4LU7KE.mjs +0 -384
  64. package/dist/chunk-CJINEUIH.mjs +0 -1369
  65. package/dist/chunk-CLWNLHDB.mjs +0 -909
  66. package/dist/chunk-CZUJTDNH.mjs +0 -848
  67. package/dist/chunk-DNGW3WQK.mjs +0 -810
  68. package/dist/chunk-DSI3TEO2.mjs +0 -662
  69. package/dist/chunk-EIQ5K6OO.mjs +0 -1579
  70. package/dist/chunk-FEJODRK5.mjs +0 -783
  71. package/dist/chunk-FK56AZ43.mjs +0 -817
  72. package/dist/chunk-H6S7WKSQ.mjs +0 -729
  73. package/dist/chunk-HAOJLJNB.mjs +0 -1290
  74. package/dist/chunk-HJCP36VW.mjs +0 -821
  75. package/dist/chunk-HPG7P6PD.mjs +0 -1372
  76. package/dist/chunk-IVRBV7SE.mjs +0 -1295
  77. package/dist/chunk-IXBC6GVT.mjs +0 -832
  78. package/dist/chunk-J5IFYDVU.mjs +0 -1579
  79. package/dist/chunk-KWQVBF7K.mjs +0 -831
  80. package/dist/chunk-LD3CHHU2.mjs +0 -1297
  81. package/dist/chunk-LMOXGPCM.mjs +0 -722
  82. package/dist/chunk-LSXZH6X6.mjs +0 -810
  83. package/dist/chunk-LUAREV6A.mjs +0 -508
  84. package/dist/chunk-MAPVFXBP.mjs +0 -708
  85. package/dist/chunk-MM2PLUCH.mjs +0 -1376
  86. package/dist/chunk-NPWCJZUG.mjs +0 -708
  87. package/dist/chunk-ON73WHHU.mjs +0 -1310
  88. package/dist/chunk-P6NVKUBB.mjs +0 -831
  89. package/dist/chunk-Q3KTWDSL.mjs +0 -808
  90. package/dist/chunk-Q5XMWG33.mjs +0 -661
  91. package/dist/chunk-QOIPVP6P.mjs +0 -1607
  92. package/dist/chunk-RMEQWG52.mjs +0 -1633
  93. package/dist/chunk-S6BZVTWN.mjs +0 -731
  94. package/dist/chunk-TE6JYZD3.mjs +0 -810
  95. package/dist/chunk-TLVLM3M5.mjs +0 -771
  96. package/dist/chunk-TXHPUU7A.mjs +0 -863
  97. package/dist/chunk-UMBBTNQN.mjs +0 -787
  98. package/dist/chunk-V2UPXL7L.mjs +0 -842
  99. package/dist/chunk-VODCPPET.mjs +0 -1292
  100. package/dist/chunk-W6UGMKRV.mjs +0 -1310
  101. package/dist/chunk-WGH4TGZ3.mjs +0 -1288
  102. package/dist/chunk-WTBDNCEN.mjs +0 -1352
  103. package/dist/chunk-XVW5DKJQ.mjs +0 -1619
  104. package/dist/chunk-YCDCIOJN.mjs +0 -842
  105. package/dist/chunk-YEHXYHGY.mjs +0 -1497
  106. package/dist/chunk-YHHXE2JX.mjs +0 -912
  107. package/dist/chunk-ZB6UK276.mjs +0 -662
  108. package/dist/chunk-ZG3KFSD3.mjs +0 -1142
  109. package/dist/cli.d.ts.map +0 -1
  110. package/dist/cli.js.map +0 -1
  111. package/dist/index.d.ts.map +0 -1
  112. package/dist/index.js.map +0 -1
  113. package/dist/scoring.d.ts +0 -12
  114. package/dist/scoring.d.ts.map +0 -1
  115. package/dist/scoring.js +0 -110
  116. package/dist/scoring.js.map +0 -1
  117. package/dist/types.d.ts +0 -53
  118. package/dist/types.d.ts.map +0 -1
  119. package/dist/types.js +0 -2
  120. package/dist/types.js.map +0 -1
  121. package/dist/utils/ast-parser.d.ts +0 -46
  122. package/dist/utils/ast-parser.d.ts.map +0 -1
  123. package/dist/utils/ast-parser.js +0 -157
  124. package/dist/utils/ast-parser.js.map +0 -1
  125. package/dist/utils/config-loader.d.ts +0 -19
  126. package/dist/utils/config-loader.d.ts.map +0 -1
  127. package/dist/utils/config-loader.js +0 -31
  128. package/dist/utils/config-loader.js.map +0 -1
  129. package/dist/utils/context-detector.d.ts +0 -40
  130. package/dist/utils/context-detector.d.ts.map +0 -1
  131. package/dist/utils/context-detector.js +0 -225
  132. package/dist/utils/context-detector.js.map +0 -1
  133. package/dist/utils/scope-tracker.d.ts +0 -87
  134. package/dist/utils/scope-tracker.d.ts.map +0 -1
  135. package/dist/utils/scope-tracker.js +0 -161
  136. package/dist/utils/scope-tracker.js.map +0 -1
@@ -1,1297 +0,0 @@
1
- // src/analyzers/naming-ast.ts
2
- import { loadConfig } from "@aiready/core";
3
- import { dirname } from "path";
4
-
5
- // src/utils/ast-parser.ts
6
- import { parse } from "@typescript-eslint/typescript-estree";
7
- import { readFileSync } from "fs";
8
- function parseFile(filePath, content) {
9
- try {
10
- const code = content ?? readFileSync(filePath, "utf-8");
11
- const isTypeScript = filePath.match(/\.tsx?$/);
12
- return parse(code, {
13
- jsx: filePath.match(/\.[jt]sx$/i) !== null,
14
- loc: true,
15
- range: true,
16
- comment: false,
17
- tokens: false,
18
- // Relaxed parsing for JavaScript files
19
- sourceType: "module",
20
- ecmaVersion: "latest",
21
- // Only use TypeScript parser features for .ts/.tsx files
22
- filePath: isTypeScript ? filePath : void 0
23
- });
24
- } catch (error) {
25
- console.warn(`Failed to parse ${filePath}:`, error instanceof Error ? error.message : error);
26
- return null;
27
- }
28
- }
29
- function traverseAST(node, visitor, parent = null) {
30
- if (!node) return;
31
- visitor.enter?.(node, parent);
32
- for (const key of Object.keys(node)) {
33
- const value = node[key];
34
- if (Array.isArray(value)) {
35
- for (const child of value) {
36
- if (child && typeof child === "object" && "type" in child) {
37
- traverseAST(child, visitor, node);
38
- }
39
- }
40
- } else if (value && typeof value === "object" && "type" in value) {
41
- traverseAST(value, visitor, node);
42
- }
43
- }
44
- visitor.leave?.(node, parent);
45
- }
46
- function isLoopStatement(node) {
47
- return [
48
- "ForStatement",
49
- "ForInStatement",
50
- "ForOfStatement",
51
- "WhileStatement",
52
- "DoWhileStatement"
53
- ].includes(node.type);
54
- }
55
- function getFunctionName(node) {
56
- switch (node.type) {
57
- case "FunctionDeclaration":
58
- return node.id?.name ?? null;
59
- case "FunctionExpression":
60
- return node.id?.name ?? null;
61
- case "ArrowFunctionExpression":
62
- return null;
63
- // Arrow functions don't have names directly
64
- case "MethodDefinition":
65
- if (node.key.type === "Identifier") {
66
- return node.key.name;
67
- }
68
- return null;
69
- default:
70
- return null;
71
- }
72
- }
73
- function getLineNumber(node) {
74
- return node.loc?.start.line ?? 0;
75
- }
76
- function isCoverageContext(node, ancestors) {
77
- const coveragePatterns = /coverage|summary|metrics|pct|percent|statements|branches|functions|lines/i;
78
- if (node.type === "Identifier" && coveragePatterns.test(node.name)) {
79
- return true;
80
- }
81
- for (const ancestor of ancestors.slice(-3)) {
82
- if (ancestor.type === "MemberExpression") {
83
- const memberExpr = ancestor;
84
- if (memberExpr.object.type === "Identifier" && coveragePatterns.test(memberExpr.object.name)) {
85
- return true;
86
- }
87
- }
88
- if (ancestor.type === "ObjectPattern" || ancestor.type === "ObjectExpression") {
89
- const parent = ancestors[ancestors.indexOf(ancestor) - 1];
90
- if (parent?.type === "VariableDeclarator") {
91
- const varDecl = parent;
92
- if (varDecl.id.type === "Identifier" && coveragePatterns.test(varDecl.id.name)) {
93
- return true;
94
- }
95
- }
96
- }
97
- }
98
- return false;
99
- }
100
-
101
- // src/utils/scope-tracker.ts
102
- var ScopeTracker = class {
103
- constructor(rootNode) {
104
- this.allScopes = [];
105
- this.rootScope = {
106
- type: "global",
107
- node: rootNode,
108
- parent: null,
109
- children: [],
110
- variables: /* @__PURE__ */ new Map()
111
- };
112
- this.currentScope = this.rootScope;
113
- this.allScopes.push(this.rootScope);
114
- }
115
- /**
116
- * Enter a new scope
117
- */
118
- enterScope(type, node) {
119
- const newScope = {
120
- type,
121
- node,
122
- parent: this.currentScope,
123
- children: [],
124
- variables: /* @__PURE__ */ new Map()
125
- };
126
- this.currentScope.children.push(newScope);
127
- this.currentScope = newScope;
128
- this.allScopes.push(newScope);
129
- }
130
- /**
131
- * Exit current scope and return to parent
132
- */
133
- exitScope() {
134
- if (this.currentScope.parent) {
135
- this.currentScope = this.currentScope.parent;
136
- }
137
- }
138
- /**
139
- * Declare a variable in the current scope
140
- */
141
- declareVariable(name, node, line, options = {}) {
142
- const varInfo = {
143
- name,
144
- node,
145
- declarationLine: line,
146
- references: [],
147
- type: options.type,
148
- isParameter: options.isParameter ?? false,
149
- isDestructured: options.isDestructured ?? false,
150
- isLoopVariable: options.isLoopVariable ?? false
151
- };
152
- this.currentScope.variables.set(name, varInfo);
153
- }
154
- /**
155
- * Add a reference to a variable
156
- */
157
- addReference(name, node) {
158
- const varInfo = this.findVariable(name);
159
- if (varInfo) {
160
- varInfo.references.push(node);
161
- }
162
- }
163
- /**
164
- * Find a variable in current or parent scopes
165
- */
166
- findVariable(name) {
167
- let scope = this.currentScope;
168
- while (scope) {
169
- const varInfo = scope.variables.get(name);
170
- if (varInfo) {
171
- return varInfo;
172
- }
173
- scope = scope.parent;
174
- }
175
- return null;
176
- }
177
- /**
178
- * Get all variables in current scope (not including parent scopes)
179
- */
180
- getCurrentScopeVariables() {
181
- return Array.from(this.currentScope.variables.values());
182
- }
183
- /**
184
- * Get all variables across all scopes
185
- */
186
- getAllVariables() {
187
- const allVars = [];
188
- for (const scope of this.allScopes) {
189
- allVars.push(...Array.from(scope.variables.values()));
190
- }
191
- return allVars;
192
- }
193
- /**
194
- * Calculate actual usage count (references minus declaration)
195
- */
196
- getUsageCount(varInfo) {
197
- return varInfo.references.length;
198
- }
199
- /**
200
- * Check if a variable is short-lived (used within N lines)
201
- */
202
- isShortLived(varInfo, maxLines = 5) {
203
- if (varInfo.references.length === 0) {
204
- return false;
205
- }
206
- const declarationLine = varInfo.declarationLine;
207
- const maxUsageLine = Math.max(
208
- ...varInfo.references.map((ref) => ref.loc?.start.line ?? declarationLine)
209
- );
210
- return maxUsageLine - declarationLine <= maxLines;
211
- }
212
- /**
213
- * Check if a variable is used in a limited scope (e.g., only in one callback)
214
- */
215
- isLocallyScoped(varInfo) {
216
- if (varInfo.references.length === 0) return false;
217
- const lines = varInfo.references.map((ref) => ref.loc?.start.line ?? 0);
218
- const minLine = Math.min(...lines);
219
- const maxLine = Math.max(...lines);
220
- return maxLine - minLine <= 3;
221
- }
222
- /**
223
- * Get current scope type
224
- */
225
- getCurrentScopeType() {
226
- return this.currentScope.type;
227
- }
228
- /**
229
- * Check if currently in a loop scope
230
- */
231
- isInLoop() {
232
- let scope = this.currentScope;
233
- while (scope) {
234
- if (scope.type === "loop") {
235
- return true;
236
- }
237
- scope = scope.parent;
238
- }
239
- return false;
240
- }
241
- /**
242
- * Check if currently in a function scope
243
- */
244
- isInFunction() {
245
- let scope = this.currentScope;
246
- while (scope) {
247
- if (scope.type === "function") {
248
- return true;
249
- }
250
- scope = scope.parent;
251
- }
252
- return false;
253
- }
254
- /**
255
- * Get the root scope
256
- */
257
- getRootScope() {
258
- return this.rootScope;
259
- }
260
- };
261
-
262
- // src/utils/context-detector.ts
263
- function detectFileType(filePath, ast) {
264
- const path = filePath.toLowerCase();
265
- if (path.match(/\.(test|spec)\.(ts|tsx|js|jsx)$/) || path.includes("__tests__")) {
266
- return "test";
267
- }
268
- if (path.endsWith(".d.ts") || path.includes("types")) {
269
- return "types";
270
- }
271
- if (path.match(/config|\.config\.|rc\.|setup/) || path.includes("configuration")) {
272
- return "config";
273
- }
274
- return "production";
275
- }
276
- function detectCodeLayer(ast) {
277
- let hasAPIIndicators = 0;
278
- let hasBusinessIndicators = 0;
279
- let hasDataIndicators = 0;
280
- let hasUtilityIndicators = 0;
281
- traverseAST(ast, {
282
- enter: (node) => {
283
- if (node.type === "ImportDeclaration") {
284
- const source = node.source.value;
285
- if (source.match(/express|fastify|koa|@nestjs|axios|fetch|http/i)) {
286
- hasAPIIndicators++;
287
- }
288
- if (source.match(/database|prisma|typeorm|sequelize|mongoose|pg|mysql/i)) {
289
- hasDataIndicators++;
290
- }
291
- }
292
- if (node.type === "FunctionDeclaration" && node.id) {
293
- const name = node.id.name;
294
- if (name.match(/^(get|post|put|delete|patch|handle|api|route|controller)/i)) {
295
- hasAPIIndicators++;
296
- }
297
- if (name.match(/^(calculate|process|validate|transform|compute|analyze)/i)) {
298
- hasBusinessIndicators++;
299
- }
300
- if (name.match(/^(find|create|update|delete|save|fetch|query|insert)/i)) {
301
- hasDataIndicators++;
302
- }
303
- if (name.match(/^(format|parse|convert|normalize|sanitize|encode|decode)/i)) {
304
- hasUtilityIndicators++;
305
- }
306
- }
307
- if (node.type === "ExportNamedDeclaration" || node.type === "ExportDefaultDeclaration") {
308
- if (node.type === "ExportNamedDeclaration" && node.declaration) {
309
- if (node.declaration.type === "FunctionDeclaration" && node.declaration.id) {
310
- const name = node.declaration.id.name;
311
- if (name.match(/handler|route|api|controller/i)) {
312
- hasAPIIndicators += 2;
313
- }
314
- }
315
- }
316
- }
317
- }
318
- });
319
- const scores = {
320
- api: hasAPIIndicators,
321
- business: hasBusinessIndicators,
322
- data: hasDataIndicators,
323
- utility: hasUtilityIndicators
324
- };
325
- const maxScore = Math.max(...Object.values(scores));
326
- if (maxScore === 0) {
327
- return "unknown";
328
- }
329
- if (scores.api === maxScore) return "api";
330
- if (scores.data === maxScore) return "data";
331
- if (scores.business === maxScore) return "business";
332
- if (scores.utility === maxScore) return "utility";
333
- return "unknown";
334
- }
335
- function calculateComplexity(node) {
336
- let complexity = 1;
337
- traverseAST(node, {
338
- enter: (childNode) => {
339
- switch (childNode.type) {
340
- case "IfStatement":
341
- case "ConditionalExpression":
342
- // ternary
343
- case "SwitchCase":
344
- case "ForStatement":
345
- case "ForInStatement":
346
- case "ForOfStatement":
347
- case "WhileStatement":
348
- case "DoWhileStatement":
349
- case "CatchClause":
350
- complexity++;
351
- break;
352
- case "LogicalExpression":
353
- if (childNode.operator === "&&" || childNode.operator === "||") {
354
- complexity++;
355
- }
356
- break;
357
- }
358
- }
359
- });
360
- return complexity;
361
- }
362
- function buildCodeContext(filePath, ast) {
363
- const fileType = detectFileType(filePath, ast);
364
- const codeLayer = detectCodeLayer(ast);
365
- let totalComplexity = 0;
366
- let functionCount = 0;
367
- traverseAST(ast, {
368
- enter: (node) => {
369
- if (node.type === "FunctionDeclaration" || node.type === "FunctionExpression" || node.type === "ArrowFunctionExpression") {
370
- totalComplexity += calculateComplexity(node);
371
- functionCount++;
372
- }
373
- }
374
- });
375
- const avgComplexity = functionCount > 0 ? totalComplexity / functionCount : 1;
376
- return {
377
- fileType,
378
- codeLayer,
379
- complexity: Math.round(avgComplexity),
380
- isTestFile: fileType === "test",
381
- isTypeDefinition: fileType === "types"
382
- };
383
- }
384
- function adjustSeverity(baseSeverity, context, issueType) {
385
- if (context.isTestFile) {
386
- if (baseSeverity === "minor") return "info";
387
- if (baseSeverity === "major") return "minor";
388
- }
389
- if (context.isTypeDefinition) {
390
- if (baseSeverity === "minor") return "info";
391
- }
392
- if (context.codeLayer === "api") {
393
- if (baseSeverity === "info" && issueType === "unclear") return "minor";
394
- if (baseSeverity === "minor" && issueType === "unclear") return "major";
395
- }
396
- if (context.complexity > 10) {
397
- if (baseSeverity === "info") return "minor";
398
- }
399
- if (context.codeLayer === "utility") {
400
- if (baseSeverity === "minor" && issueType === "abbreviation") return "info";
401
- }
402
- return baseSeverity;
403
- }
404
- function isAcceptableInContext(name, context, options) {
405
- if (options.isLoopVariable && ["i", "j", "k", "l", "n", "m"].includes(name)) {
406
- return true;
407
- }
408
- if (context.isTestFile) {
409
- if (["a", "b", "c", "x", "y", "z"].includes(name) && options.isParameter) {
410
- return true;
411
- }
412
- }
413
- if (context.codeLayer === "utility" && ["x", "y", "z"].includes(name)) {
414
- return true;
415
- }
416
- if (options.isDestructured) {
417
- if (["s", "b", "f", "l"].includes(name)) {
418
- return true;
419
- }
420
- }
421
- if (options.isParameter && (options.complexity ?? context.complexity) < 3) {
422
- if (name.length >= 2) {
423
- return true;
424
- }
425
- }
426
- return false;
427
- }
428
-
429
- // src/analyzers/naming-ast.ts
430
- var COMMON_SHORT_WORDS = /* @__PURE__ */ new Set([
431
- "day",
432
- "key",
433
- "net",
434
- "to",
435
- "go",
436
- "for",
437
- "not",
438
- "new",
439
- "old",
440
- "top",
441
- "end",
442
- "run",
443
- "try",
444
- "use",
445
- "get",
446
- "set",
447
- "add",
448
- "put",
449
- "map",
450
- "log",
451
- "row",
452
- "col",
453
- "tab",
454
- "box",
455
- "div",
456
- "nav",
457
- "tag",
458
- "any",
459
- "all",
460
- "one",
461
- "two",
462
- "out",
463
- "off",
464
- "on",
465
- "yes",
466
- "no",
467
- "now",
468
- "max",
469
- "min",
470
- "sum",
471
- "avg",
472
- "ref",
473
- "src",
474
- "dst",
475
- "raw",
476
- "def",
477
- "sub",
478
- "pub",
479
- "pre",
480
- "mid",
481
- "alt",
482
- "opt",
483
- "tmp",
484
- "ext",
485
- "sep",
486
- "and",
487
- "from",
488
- "how",
489
- "pad",
490
- "bar",
491
- "non",
492
- "tax",
493
- "cat",
494
- "dog",
495
- "car",
496
- "bus",
497
- "web",
498
- "app",
499
- "war",
500
- "law",
501
- "pay",
502
- "buy",
503
- "win",
504
- "cut",
505
- "hit",
506
- "hot",
507
- "pop",
508
- "job",
509
- "age",
510
- "act",
511
- "let",
512
- "lot",
513
- "bad",
514
- "big",
515
- "far",
516
- "few",
517
- "own",
518
- "per",
519
- "red",
520
- "low",
521
- "see",
522
- "six",
523
- "ten",
524
- "way",
525
- "who",
526
- "why",
527
- "yet",
528
- "via",
529
- "due",
530
- "fee",
531
- "fun",
532
- "gas",
533
- "gay",
534
- "god",
535
- "gun",
536
- "guy",
537
- "ice",
538
- "ill",
539
- "kid",
540
- "mad",
541
- "man",
542
- "mix",
543
- "mom",
544
- "mrs",
545
- "nor",
546
- "odd",
547
- "oil",
548
- "pan",
549
- "pet",
550
- "pit",
551
- "pot",
552
- "pow",
553
- "pro",
554
- "raw",
555
- "rep",
556
- "rid",
557
- "sad",
558
- "sea",
559
- "sit",
560
- "sky",
561
- "son",
562
- "tea",
563
- "tie",
564
- "tip",
565
- "van",
566
- "war",
567
- "win",
568
- "won"
569
- ]);
570
- var ACCEPTABLE_ABBREVIATIONS = /* @__PURE__ */ new Set([
571
- "id",
572
- "uid",
573
- "gid",
574
- "pid",
575
- "i",
576
- "j",
577
- "k",
578
- "n",
579
- "m",
580
- "url",
581
- "uri",
582
- "api",
583
- "cdn",
584
- "dns",
585
- "ip",
586
- "tcp",
587
- "udp",
588
- "http",
589
- "ssl",
590
- "tls",
591
- "utm",
592
- "seo",
593
- "rss",
594
- "xhr",
595
- "ajax",
596
- "cors",
597
- "ws",
598
- "wss",
599
- "json",
600
- "xml",
601
- "yaml",
602
- "csv",
603
- "html",
604
- "css",
605
- "svg",
606
- "pdf",
607
- "img",
608
- "txt",
609
- "doc",
610
- "docx",
611
- "xlsx",
612
- "ppt",
613
- "md",
614
- "rst",
615
- "jpg",
616
- "png",
617
- "gif",
618
- "db",
619
- "sql",
620
- "orm",
621
- "dao",
622
- "dto",
623
- "ddb",
624
- "rds",
625
- "nosql",
626
- "fs",
627
- "dir",
628
- "tmp",
629
- "src",
630
- "dst",
631
- "bin",
632
- "lib",
633
- "pkg",
634
- "os",
635
- "env",
636
- "arg",
637
- "cli",
638
- "cmd",
639
- "exe",
640
- "cwd",
641
- "pwd",
642
- "ui",
643
- "ux",
644
- "gui",
645
- "dom",
646
- "ref",
647
- "req",
648
- "res",
649
- "ctx",
650
- "err",
651
- "msg",
652
- "auth",
653
- "max",
654
- "min",
655
- "avg",
656
- "sum",
657
- "abs",
658
- "cos",
659
- "sin",
660
- "tan",
661
- "log",
662
- "exp",
663
- "pow",
664
- "sqrt",
665
- "std",
666
- "var",
667
- "int",
668
- "num",
669
- "idx",
670
- "now",
671
- "utc",
672
- "tz",
673
- "ms",
674
- "sec",
675
- "hr",
676
- "min",
677
- "yr",
678
- "mo",
679
- "app",
680
- "cfg",
681
- "config",
682
- "init",
683
- "len",
684
- "val",
685
- "str",
686
- "obj",
687
- "arr",
688
- "gen",
689
- "def",
690
- "raw",
691
- "new",
692
- "old",
693
- "pre",
694
- "post",
695
- "sub",
696
- "pub",
697
- "ts",
698
- "js",
699
- "jsx",
700
- "tsx",
701
- "py",
702
- "rb",
703
- "vue",
704
- "re",
705
- "fn",
706
- "fns",
707
- "mod",
708
- "opts",
709
- "dev",
710
- "s3",
711
- "ec2",
712
- "sqs",
713
- "sns",
714
- "vpc",
715
- "ami",
716
- "iam",
717
- "acl",
718
- "elb",
719
- "alb",
720
- "nlb",
721
- "aws",
722
- "ses",
723
- "gst",
724
- "cdk",
725
- "btn",
726
- "buf",
727
- "agg",
728
- "ocr",
729
- "ai",
730
- "cf",
731
- "cfn",
732
- "ga",
733
- "fcp",
734
- "lcp",
735
- "cls",
736
- "ttfb",
737
- "tti",
738
- "fid",
739
- "fps",
740
- "qps",
741
- "rps",
742
- "tps",
743
- "wpm",
744
- "po",
745
- "e2e",
746
- "a11y",
747
- "i18n",
748
- "l10n",
749
- "spy",
750
- "sk",
751
- "fy",
752
- "faq",
753
- "og",
754
- "seo",
755
- "cta",
756
- "roi",
757
- "kpi",
758
- "ttl",
759
- "pct",
760
- "mac",
761
- "hex",
762
- "esm",
763
- "git",
764
- "rec",
765
- "loc",
766
- "dup",
767
- "is",
768
- "has",
769
- "can",
770
- "did",
771
- "was",
772
- "are",
773
- "d",
774
- "t",
775
- "dt",
776
- "s",
777
- "b",
778
- "f",
779
- "l",
780
- // Coverage metrics
781
- "vid",
782
- "pic",
783
- "img",
784
- "doc",
785
- "msg"
786
- ]);
787
- async function analyzeNamingAST(files) {
788
- const issues = [];
789
- const rootDir = files.length > 0 ? dirname(files[0]) : process.cwd();
790
- const config = loadConfig(rootDir);
791
- const consistencyConfig = config?.tools?.["consistency"];
792
- const customAbbreviations = new Set(consistencyConfig?.acceptedAbbreviations || []);
793
- const customShortWords = new Set(consistencyConfig?.shortWords || []);
794
- const disabledChecks = new Set(consistencyConfig?.disableChecks || []);
795
- const allAbbreviations = /* @__PURE__ */ new Set([...ACCEPTABLE_ABBREVIATIONS, ...customAbbreviations]);
796
- const allShortWords = /* @__PURE__ */ new Set([...COMMON_SHORT_WORDS, ...customShortWords]);
797
- for (const file of files) {
798
- try {
799
- const ast = parseFile(file);
800
- if (!ast) continue;
801
- const fileIssues = analyzeFileNamingAST(
802
- file,
803
- ast,
804
- allAbbreviations,
805
- allShortWords,
806
- disabledChecks
807
- );
808
- issues.push(...fileIssues);
809
- } catch (error) {
810
- console.warn(`Skipping ${file} due to parse error:`, error);
811
- }
812
- }
813
- return issues;
814
- }
815
- function analyzeFileNamingAST(file, ast, allAbbreviations, allShortWords, disabledChecks) {
816
- const issues = [];
817
- const scopeTracker = new ScopeTracker(ast);
818
- const context = buildCodeContext(file, ast);
819
- const ancestors = [];
820
- traverseAST(ast, {
821
- enter: (node, parent) => {
822
- ancestors.push(node);
823
- if (node.type === "FunctionDeclaration" || node.type === "FunctionExpression" || node.type === "ArrowFunctionExpression") {
824
- scopeTracker.enterScope("function", node);
825
- if ("params" in node) {
826
- for (const param of node.params) {
827
- if (param.type === "Identifier") {
828
- scopeTracker.declareVariable(param.name, param, getLineNumber(param), {
829
- isParameter: true
830
- });
831
- } else if (param.type === "ObjectPattern" || param.type === "ArrayPattern") {
832
- extractIdentifiersFromPattern(param, scopeTracker, true);
833
- }
834
- }
835
- }
836
- } else if (node.type === "BlockStatement") {
837
- scopeTracker.enterScope("block", node);
838
- } else if (isLoopStatement(node)) {
839
- scopeTracker.enterScope("loop", node);
840
- } else if (node.type === "ClassDeclaration") {
841
- scopeTracker.enterScope("class", node);
842
- }
843
- if (node.type === "VariableDeclarator") {
844
- if (node.id.type === "Identifier") {
845
- const isInCoverage = isCoverageContext(node, ancestors);
846
- scopeTracker.declareVariable(
847
- node.id.name,
848
- node.id,
849
- getLineNumber(node.id),
850
- {
851
- type: "typeAnnotation" in node.id ? node.id.typeAnnotation : null,
852
- isDestructured: false,
853
- isLoopVariable: scopeTracker.getCurrentScopeType() === "loop"
854
- }
855
- );
856
- } else if (node.id.type === "ObjectPattern" || node.id.type === "ArrayPattern") {
857
- extractIdentifiersFromPattern(node.id, scopeTracker, false, ancestors);
858
- }
859
- }
860
- if (node.type === "Identifier" && parent) {
861
- if (parent.type !== "VariableDeclarator" || parent.id !== node) {
862
- if (parent.type !== "FunctionDeclaration" || parent.id !== node) {
863
- scopeTracker.addReference(node.name, node);
864
- }
865
- }
866
- }
867
- },
868
- leave: (node) => {
869
- ancestors.pop();
870
- if (node.type === "FunctionDeclaration" || node.type === "FunctionExpression" || node.type === "ArrowFunctionExpression" || node.type === "BlockStatement" || isLoopStatement(node) || node.type === "ClassDeclaration") {
871
- scopeTracker.exitScope();
872
- }
873
- }
874
- });
875
- const allVariables = scopeTracker.getAllVariables();
876
- for (const varInfo of allVariables) {
877
- const name = varInfo.name;
878
- const line = varInfo.declarationLine;
879
- if (disabledChecks.has("single-letter") && name.length === 1) continue;
880
- if (disabledChecks.has("abbreviation") && name.length <= 3) continue;
881
- const isInCoverage = ["s", "b", "f", "l"].includes(name) && varInfo.isDestructured;
882
- if (isInCoverage) continue;
883
- const functionComplexity = varInfo.node.type === "Identifier" && "parent" in varInfo.node ? calculateComplexity(varInfo.node) : context.complexity;
884
- if (isAcceptableInContext(name, context, {
885
- isLoopVariable: varInfo.isLoopVariable || allAbbreviations.has(name),
886
- isParameter: varInfo.isParameter,
887
- isDestructured: varInfo.isDestructured,
888
- complexity: functionComplexity
889
- })) {
890
- continue;
891
- }
892
- if (name.length === 1 && !allAbbreviations.has(name) && !allShortWords.has(name)) {
893
- const isShortLived = scopeTracker.isShortLived(varInfo, 5);
894
- if (!isShortLived) {
895
- issues.push({
896
- file,
897
- line,
898
- type: "poor-naming",
899
- identifier: name,
900
- severity: adjustSeverity("minor", context, "poor-naming"),
901
- suggestion: `Use descriptive variable name instead of single letter '${name}'`
902
- });
903
- }
904
- continue;
905
- }
906
- if (name.length >= 2 && name.length <= 3) {
907
- if (!allShortWords.has(name.toLowerCase()) && !allAbbreviations.has(name.toLowerCase())) {
908
- const isShortLived = scopeTracker.isShortLived(varInfo, 5);
909
- if (!isShortLived) {
910
- issues.push({
911
- file,
912
- line,
913
- type: "abbreviation",
914
- identifier: name,
915
- severity: adjustSeverity("info", context, "abbreviation"),
916
- suggestion: `Consider using full word instead of abbreviation '${name}'`
917
- });
918
- }
919
- }
920
- continue;
921
- }
922
- if (!disabledChecks.has("convention-mix") && file.match(/\.(ts|tsx|js|jsx)$/)) {
923
- if (name.includes("_") && !name.startsWith("_") && name.toLowerCase() === name) {
924
- const camelCase = name.replace(/_([a-z])/g, (_, letter) => letter.toUpperCase());
925
- issues.push({
926
- file,
927
- line,
928
- type: "convention-mix",
929
- identifier: name,
930
- severity: adjustSeverity("minor", context, "convention-mix"),
931
- suggestion: `Use camelCase '${camelCase}' instead of snake_case in TypeScript/JavaScript`
932
- });
933
- }
934
- }
935
- }
936
- if (!disabledChecks.has("unclear")) {
937
- traverseAST(ast, {
938
- enter: (node) => {
939
- if (node.type === "FunctionDeclaration" || node.type === "MethodDefinition") {
940
- const name = getFunctionName(node);
941
- if (!name) return;
942
- const line = getLineNumber(node);
943
- if (["main", "init", "setup", "bootstrap"].includes(name)) return;
944
- const hasActionVerb = name.match(/^(get|set|is|has|can|should|create|update|delete|fetch|load|save|process|handle|validate|check|find|search|filter|map|reduce|make|do|run|start|stop|build|parse|format|render|calculate|compute|generate|transform|convert|normalize|sanitize|encode|decode|compress|extract|merge|split|join|sort|compare|test|verify|ensure|apply|execute|invoke|call|emit|dispatch|trigger|listen|subscribe|unsubscribe|add|remove|clear|reset|toggle|enable|disable|open|close|connect|disconnect|send|receive|read|write|import|export|register|unregister|mount|unmount|track|store|persist|upsert|derive|classify|combine|discover|activate|require|assert|expect|mask|escape|sign|put|list|complete|page|safe|mock|pick|pluralize|text|count|detect|select)/);
945
- const isFactoryPattern = name.match(/(Factory|Builder|Creator|Generator|Provider|Adapter|Mock)$/);
946
- const isEventHandler = name.match(/^on[A-Z]/);
947
- const isDescriptiveLong = name.length > 15;
948
- const isReactHook = name.match(/^use[A-Z]/);
949
- const isHelperPattern = name.match(/^(to|from|with|without|for|as|into)\w+/) || name.match(/^\w+(To|From|With|Without|For|As|Into)\w*$/);
950
- const isUtilityName = ["cn", "proxy", "sitemap", "robots", "gtag"].includes(name);
951
- const isLanguageKeyword = ["constructor", "toString", "valueOf", "toJSON"].includes(name);
952
- const isFrameworkPattern = name.match(/^(goto|fill|click|select|submit|wait|expect)\w*/);
953
- const isDescriptivePattern = name.match(/^(default|total|count|sum|avg|max|min|initial|current|previous|next)\w+/) || name.match(/\w+(Count|Total|Sum|Average|List|Map|Set|Config|Settings|Options|Props|Data|Info|Details|State|Status|Response|Result)$/);
954
- const capitalCount = (name.match(/[A-Z]/g) || []).length;
955
- const isCompoundWord = capitalCount >= 3;
956
- if (!hasActionVerb && !isFactoryPattern && !isEventHandler && !isDescriptiveLong && !isReactHook && !isHelperPattern && !isUtilityName && !isDescriptivePattern && !isCompoundWord && !isLanguageKeyword && !isFrameworkPattern) {
957
- issues.push({
958
- file,
959
- line,
960
- type: "unclear",
961
- identifier: name,
962
- severity: adjustSeverity("info", context, "unclear"),
963
- suggestion: `Function '${name}' should start with an action verb (get, set, create, etc.)`
964
- });
965
- }
966
- }
967
- }
968
- });
969
- }
970
- return issues;
971
- }
972
- function extractIdentifiersFromPattern(pattern, scopeTracker, isParameter, ancestors) {
973
- if (pattern.type === "ObjectPattern") {
974
- for (const prop of pattern.properties) {
975
- if (prop.type === "Property" && prop.value.type === "Identifier") {
976
- scopeTracker.declareVariable(
977
- prop.value.name,
978
- prop.value,
979
- getLineNumber(prop.value),
980
- {
981
- isParameter,
982
- isDestructured: true
983
- }
984
- );
985
- } else if (prop.type === "RestElement" && prop.argument.type === "Identifier") {
986
- scopeTracker.declareVariable(
987
- prop.argument.name,
988
- prop.argument,
989
- getLineNumber(prop.argument),
990
- {
991
- isParameter,
992
- isDestructured: true
993
- }
994
- );
995
- }
996
- }
997
- } else if (pattern.type === "ArrayPattern") {
998
- for (const element of pattern.elements) {
999
- if (element && element.type === "Identifier") {
1000
- scopeTracker.declareVariable(
1001
- element.name,
1002
- element,
1003
- getLineNumber(element),
1004
- {
1005
- isParameter,
1006
- isDestructured: true
1007
- }
1008
- );
1009
- }
1010
- }
1011
- }
1012
- }
1013
-
1014
- // src/analyzers/patterns.ts
1015
- import { readFileContent } from "@aiready/core";
1016
- async function analyzePatterns(files) {
1017
- const issues = [];
1018
- const errorHandlingIssues = await analyzeErrorHandling(files);
1019
- issues.push(...errorHandlingIssues);
1020
- const asyncIssues = await analyzeAsyncPatterns(files);
1021
- issues.push(...asyncIssues);
1022
- const importIssues = await analyzeImportStyles(files);
1023
- issues.push(...importIssues);
1024
- return issues;
1025
- }
1026
- async function analyzeErrorHandling(files) {
1027
- const patterns = {
1028
- tryCatch: [],
1029
- throwsError: [],
1030
- returnsNull: [],
1031
- returnsError: []
1032
- };
1033
- for (const file of files) {
1034
- const content = await readFileContent(file);
1035
- if (content.includes("try {") || content.includes("} catch")) {
1036
- patterns.tryCatch.push(file);
1037
- }
1038
- if (content.match(/throw new \w*Error/)) {
1039
- patterns.throwsError.push(file);
1040
- }
1041
- if (content.match(/return null/)) {
1042
- patterns.returnsNull.push(file);
1043
- }
1044
- if (content.match(/return \{ error:/)) {
1045
- patterns.returnsError.push(file);
1046
- }
1047
- }
1048
- const issues = [];
1049
- const strategiesUsed = Object.values(patterns).filter((p) => p.length > 0).length;
1050
- if (strategiesUsed > 2) {
1051
- issues.push({
1052
- files: [.../* @__PURE__ */ new Set([
1053
- ...patterns.tryCatch,
1054
- ...patterns.throwsError,
1055
- ...patterns.returnsNull,
1056
- ...patterns.returnsError
1057
- ])],
1058
- type: "error-handling",
1059
- description: "Inconsistent error handling strategies across codebase",
1060
- examples: [
1061
- patterns.tryCatch.length > 0 ? `Try-catch used in ${patterns.tryCatch.length} files` : "",
1062
- patterns.throwsError.length > 0 ? `Throws errors in ${patterns.throwsError.length} files` : "",
1063
- patterns.returnsNull.length > 0 ? `Returns null in ${patterns.returnsNull.length} files` : "",
1064
- patterns.returnsError.length > 0 ? `Returns error objects in ${patterns.returnsError.length} files` : ""
1065
- ].filter((e) => e),
1066
- severity: "major"
1067
- });
1068
- }
1069
- return issues;
1070
- }
1071
- async function analyzeAsyncPatterns(files) {
1072
- const patterns = {
1073
- asyncAwait: [],
1074
- promises: [],
1075
- callbacks: []
1076
- };
1077
- for (const file of files) {
1078
- const content = await readFileContent(file);
1079
- if (content.match(/async\s+(function|\(|[a-zA-Z])/)) {
1080
- patterns.asyncAwait.push(file);
1081
- }
1082
- if (content.match(/\.then\(/) || content.match(/\.catch\(/)) {
1083
- patterns.promises.push(file);
1084
- }
1085
- if (content.match(/callback\s*\(/) || content.match(/\(\s*err\s*,/)) {
1086
- patterns.callbacks.push(file);
1087
- }
1088
- }
1089
- const issues = [];
1090
- if (patterns.callbacks.length > 0 && patterns.asyncAwait.length > 0) {
1091
- issues.push({
1092
- files: [...patterns.callbacks, ...patterns.asyncAwait],
1093
- type: "async-style",
1094
- description: "Mixed async patterns: callbacks and async/await",
1095
- examples: [
1096
- `Callbacks found in: ${patterns.callbacks.slice(0, 3).join(", ")}`,
1097
- `Async/await used in: ${patterns.asyncAwait.slice(0, 3).join(", ")}`
1098
- ],
1099
- severity: "minor"
1100
- });
1101
- }
1102
- if (patterns.promises.length > patterns.asyncAwait.length * 0.3 && patterns.asyncAwait.length > 0) {
1103
- issues.push({
1104
- files: patterns.promises,
1105
- type: "async-style",
1106
- description: "Consider using async/await instead of promise chains for consistency",
1107
- examples: patterns.promises.slice(0, 5),
1108
- severity: "info"
1109
- });
1110
- }
1111
- return issues;
1112
- }
1113
- async function analyzeImportStyles(files) {
1114
- const patterns = {
1115
- esModules: [],
1116
- commonJS: [],
1117
- mixed: []
1118
- };
1119
- for (const file of files) {
1120
- const content = await readFileContent(file);
1121
- const hasESM = content.match(/^import\s+/m);
1122
- const hasCJS = content.match(/require\s*\(/);
1123
- if (hasESM && hasCJS) {
1124
- patterns.mixed.push(file);
1125
- } else if (hasESM) {
1126
- patterns.esModules.push(file);
1127
- } else if (hasCJS) {
1128
- patterns.commonJS.push(file);
1129
- }
1130
- }
1131
- const issues = [];
1132
- if (patterns.mixed.length > 0) {
1133
- issues.push({
1134
- files: patterns.mixed,
1135
- type: "import-style",
1136
- description: "Mixed ES modules and CommonJS imports in same files",
1137
- examples: patterns.mixed.slice(0, 5),
1138
- severity: "major"
1139
- });
1140
- }
1141
- if (patterns.esModules.length > 0 && patterns.commonJS.length > 0) {
1142
- const ratio = patterns.commonJS.length / (patterns.esModules.length + patterns.commonJS.length);
1143
- if (ratio > 0.2 && ratio < 0.8) {
1144
- issues.push({
1145
- files: [...patterns.esModules, ...patterns.commonJS],
1146
- type: "import-style",
1147
- description: "Inconsistent import styles across project",
1148
- examples: [
1149
- `ES modules: ${patterns.esModules.length} files`,
1150
- `CommonJS: ${patterns.commonJS.length} files`
1151
- ],
1152
- severity: "minor"
1153
- });
1154
- }
1155
- }
1156
- return issues;
1157
- }
1158
-
1159
- // src/analyzer.ts
1160
- import { scanFiles } from "@aiready/core";
1161
- async function analyzeConsistency(options) {
1162
- const {
1163
- checkNaming = true,
1164
- checkPatterns = true,
1165
- checkArchitecture = false,
1166
- // Not implemented yet
1167
- minSeverity = "info",
1168
- ...scanOptions
1169
- } = options;
1170
- const filePaths = await scanFiles(scanOptions);
1171
- const namingIssues = checkNaming ? await analyzeNamingAST(filePaths) : [];
1172
- const patternIssues = checkPatterns ? await analyzePatterns(filePaths) : [];
1173
- const results = [];
1174
- const fileIssuesMap = /* @__PURE__ */ new Map();
1175
- for (const issue of namingIssues) {
1176
- if (!shouldIncludeSeverity(issue.severity, minSeverity)) {
1177
- continue;
1178
- }
1179
- const consistencyIssue = {
1180
- type: issue.type === "convention-mix" ? "naming-inconsistency" : "naming-quality",
1181
- category: "naming",
1182
- severity: issue.severity,
1183
- message: `${issue.type}: ${issue.identifier}`,
1184
- location: {
1185
- file: issue.file,
1186
- line: issue.line,
1187
- column: issue.column
1188
- },
1189
- suggestion: issue.suggestion
1190
- };
1191
- if (!fileIssuesMap.has(issue.file)) {
1192
- fileIssuesMap.set(issue.file, []);
1193
- }
1194
- fileIssuesMap.get(issue.file).push(consistencyIssue);
1195
- }
1196
- for (const issue of patternIssues) {
1197
- if (!shouldIncludeSeverity(issue.severity, minSeverity)) {
1198
- continue;
1199
- }
1200
- const consistencyIssue = {
1201
- type: "pattern-inconsistency",
1202
- category: "patterns",
1203
- severity: issue.severity,
1204
- message: issue.description,
1205
- location: {
1206
- file: issue.files[0] || "multiple files",
1207
- line: 1
1208
- },
1209
- examples: issue.examples,
1210
- suggestion: `Standardize ${issue.type} patterns across ${issue.files.length} files`
1211
- };
1212
- const firstFile = issue.files[0];
1213
- if (firstFile && !fileIssuesMap.has(firstFile)) {
1214
- fileIssuesMap.set(firstFile, []);
1215
- }
1216
- if (firstFile) {
1217
- fileIssuesMap.get(firstFile).push(consistencyIssue);
1218
- }
1219
- }
1220
- for (const [fileName, issues] of fileIssuesMap) {
1221
- results.push({
1222
- fileName,
1223
- issues,
1224
- metrics: {
1225
- consistencyScore: calculateConsistencyScore(issues)
1226
- }
1227
- });
1228
- }
1229
- const recommendations = generateRecommendations(namingIssues, patternIssues);
1230
- return {
1231
- summary: {
1232
- totalIssues: namingIssues.length + patternIssues.length,
1233
- namingIssues: namingIssues.length,
1234
- patternIssues: patternIssues.length,
1235
- architectureIssues: 0,
1236
- filesAnalyzed: filePaths.length
1237
- },
1238
- results,
1239
- recommendations
1240
- };
1241
- }
1242
- function shouldIncludeSeverity(severity, minSeverity) {
1243
- const severityLevels = { info: 0, minor: 1, major: 2, critical: 3 };
1244
- return severityLevels[severity] >= severityLevels[minSeverity];
1245
- }
1246
- function calculateConsistencyScore(issues) {
1247
- const weights = { critical: 10, major: 5, minor: 2, info: 1 };
1248
- const totalWeight = issues.reduce((sum, issue) => sum + weights[issue.severity], 0);
1249
- return Math.max(0, 1 - totalWeight / 100);
1250
- }
1251
- function generateRecommendations(namingIssues, patternIssues) {
1252
- const recommendations = [];
1253
- if (namingIssues.length > 0) {
1254
- const conventionMixCount = namingIssues.filter((i) => i.type === "convention-mix").length;
1255
- if (conventionMixCount > 0) {
1256
- recommendations.push(
1257
- `Standardize naming conventions: Found ${conventionMixCount} snake_case variables in TypeScript/JavaScript (use camelCase)`
1258
- );
1259
- }
1260
- const poorNamingCount = namingIssues.filter((i) => i.type === "poor-naming").length;
1261
- if (poorNamingCount > 0) {
1262
- recommendations.push(
1263
- `Improve variable naming: Found ${poorNamingCount} single-letter or unclear variable names`
1264
- );
1265
- }
1266
- }
1267
- if (patternIssues.length > 0) {
1268
- const errorHandlingIssues = patternIssues.filter((i) => i.type === "error-handling");
1269
- if (errorHandlingIssues.length > 0) {
1270
- recommendations.push(
1271
- "Standardize error handling strategy across the codebase (prefer try-catch with typed errors)"
1272
- );
1273
- }
1274
- const asyncIssues = patternIssues.filter((i) => i.type === "async-style");
1275
- if (asyncIssues.length > 0) {
1276
- recommendations.push(
1277
- "Use async/await consistently instead of mixing with promise chains or callbacks"
1278
- );
1279
- }
1280
- const importIssues = patternIssues.filter((i) => i.type === "import-style");
1281
- if (importIssues.length > 0) {
1282
- recommendations.push(
1283
- "Use ES modules consistently across the project (avoid mixing with CommonJS)"
1284
- );
1285
- }
1286
- }
1287
- if (recommendations.length === 0) {
1288
- recommendations.push("No major consistency issues found! Your codebase follows good practices.");
1289
- }
1290
- return recommendations;
1291
- }
1292
-
1293
- export {
1294
- analyzeNamingAST,
1295
- analyzePatterns,
1296
- analyzeConsistency
1297
- };