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