@aiready/consistency 0.5.0 → 0.6.1

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