@aiready/consistency 0.16.0 → 0.16.3

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,1622 @@
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(
389
+ (i) => i.type === "convention-mix"
390
+ ).length;
391
+ const totalChecks = files.length * 10;
392
+ if (camelCaseCount / totalChecks > 0.3) {
393
+ return { dominantConvention: "mixed", conventionScore: 0.5 };
394
+ }
395
+ return { dominantConvention: "camelCase", conventionScore: 0.9 };
396
+ }
397
+
398
+ // src/utils/ast-parser.ts
399
+ import { parse } from "@typescript-eslint/typescript-estree";
400
+ import { readFileSync } from "fs";
401
+ function parseFile(filePath, content) {
402
+ try {
403
+ const code = content ?? readFileSync(filePath, "utf-8");
404
+ const isTypeScript = filePath.match(/\.tsx?$/);
405
+ return parse(code, {
406
+ jsx: filePath.match(/\.[jt]sx$/i) !== null,
407
+ loc: true,
408
+ range: true,
409
+ comment: false,
410
+ tokens: false,
411
+ // Relaxed parsing for JavaScript files
412
+ sourceType: "module",
413
+ ecmaVersion: "latest",
414
+ // Only use TypeScript parser features for .ts/.tsx files
415
+ filePath: isTypeScript ? filePath : void 0
416
+ });
417
+ } catch (error) {
418
+ void error;
419
+ return null;
420
+ }
421
+ }
422
+ function traverseAST(node, visitor, parent = null) {
423
+ if (!node) return;
424
+ visitor.enter?.(node, parent);
425
+ for (const key of Object.keys(node)) {
426
+ const value = node[key];
427
+ if (Array.isArray(value)) {
428
+ for (const child of value) {
429
+ if (child && typeof child === "object" && "type" in child) {
430
+ traverseAST(child, visitor, node);
431
+ }
432
+ }
433
+ } else if (value && typeof value === "object" && "type" in value) {
434
+ traverseAST(value, visitor, node);
435
+ }
436
+ }
437
+ visitor.leave?.(node, parent);
438
+ }
439
+ function isLoopStatement(node) {
440
+ return [
441
+ "ForStatement",
442
+ "ForInStatement",
443
+ "ForOfStatement",
444
+ "WhileStatement",
445
+ "DoWhileStatement"
446
+ ].includes(node.type);
447
+ }
448
+ function getFunctionName(node) {
449
+ switch (node.type) {
450
+ case "FunctionDeclaration":
451
+ return node.id?.name ?? null;
452
+ case "FunctionExpression":
453
+ return node.id?.name ?? null;
454
+ case "ArrowFunctionExpression":
455
+ return null;
456
+ // Arrow functions don't have names directly
457
+ case "MethodDefinition":
458
+ if (node.key.type === "Identifier") {
459
+ return node.key.name;
460
+ }
461
+ return null;
462
+ default:
463
+ return null;
464
+ }
465
+ }
466
+ function getLineNumber(node) {
467
+ return node.loc?.start.line ?? 0;
468
+ }
469
+ function isCoverageContext(node, ancestors) {
470
+ const coveragePatterns = /coverage|summary|metrics|pct|percent|statements|branches|functions|lines/i;
471
+ if (node.type === "Identifier" && coveragePatterns.test(node.name)) {
472
+ return true;
473
+ }
474
+ for (const ancestor of ancestors.slice(-3)) {
475
+ if (ancestor.type === "MemberExpression") {
476
+ const memberExpr = ancestor;
477
+ if (memberExpr.object.type === "Identifier" && coveragePatterns.test(memberExpr.object.name)) {
478
+ return true;
479
+ }
480
+ }
481
+ if (ancestor.type === "ObjectPattern" || ancestor.type === "ObjectExpression") {
482
+ const parent = ancestors[ancestors.indexOf(ancestor) - 1];
483
+ if (parent?.type === "VariableDeclarator") {
484
+ const varDecl = parent;
485
+ if (varDecl.id.type === "Identifier" && coveragePatterns.test(varDecl.id.name)) {
486
+ return true;
487
+ }
488
+ }
489
+ }
490
+ }
491
+ return false;
492
+ }
493
+
494
+ // src/utils/scope-tracker.ts
495
+ var ScopeTracker = class {
496
+ constructor(rootNode) {
497
+ this.allScopes = [];
498
+ this.rootScope = {
499
+ type: "global",
500
+ node: rootNode,
501
+ parent: null,
502
+ children: [],
503
+ variables: /* @__PURE__ */ new Map()
504
+ };
505
+ this.currentScope = this.rootScope;
506
+ this.allScopes.push(this.rootScope);
507
+ }
508
+ /**
509
+ * Enter a new scope
510
+ */
511
+ enterScope(type, node) {
512
+ const newScope = {
513
+ type,
514
+ node,
515
+ parent: this.currentScope,
516
+ children: [],
517
+ variables: /* @__PURE__ */ new Map()
518
+ };
519
+ this.currentScope.children.push(newScope);
520
+ this.currentScope = newScope;
521
+ this.allScopes.push(newScope);
522
+ }
523
+ /**
524
+ * Exit current scope and return to parent
525
+ */
526
+ exitScope() {
527
+ if (this.currentScope.parent) {
528
+ this.currentScope = this.currentScope.parent;
529
+ }
530
+ }
531
+ /**
532
+ * Declare a variable in the current scope
533
+ */
534
+ declareVariable(name, node, line, options = {}) {
535
+ const varInfo = {
536
+ name,
537
+ node,
538
+ declarationLine: line,
539
+ references: [],
540
+ type: options.type,
541
+ isParameter: options.isParameter ?? false,
542
+ isDestructured: options.isDestructured ?? false,
543
+ isLoopVariable: options.isLoopVariable ?? false
544
+ };
545
+ this.currentScope.variables.set(name, varInfo);
546
+ }
547
+ /**
548
+ * Add a reference to a variable
549
+ */
550
+ addReference(name, node) {
551
+ const varInfo = this.findVariable(name);
552
+ if (varInfo) {
553
+ varInfo.references.push(node);
554
+ }
555
+ }
556
+ /**
557
+ * Find a variable in current or parent scopes
558
+ */
559
+ findVariable(name) {
560
+ let scope = this.currentScope;
561
+ while (scope) {
562
+ const varInfo = scope.variables.get(name);
563
+ if (varInfo) {
564
+ return varInfo;
565
+ }
566
+ scope = scope.parent;
567
+ }
568
+ return null;
569
+ }
570
+ /**
571
+ * Get all variables in current scope (not including parent scopes)
572
+ */
573
+ getCurrentScopeVariables() {
574
+ return Array.from(this.currentScope.variables.values());
575
+ }
576
+ /**
577
+ * Get all variables across all scopes
578
+ */
579
+ getAllVariables() {
580
+ const allVars = [];
581
+ for (const scope of this.allScopes) {
582
+ allVars.push(...Array.from(scope.variables.values()));
583
+ }
584
+ return allVars;
585
+ }
586
+ /**
587
+ * Calculate actual usage count (references minus declaration)
588
+ */
589
+ getUsageCount(varInfo) {
590
+ return varInfo.references.length;
591
+ }
592
+ /**
593
+ * Check if a variable is short-lived (used within N lines)
594
+ */
595
+ isShortLived(varInfo, maxLines = 5) {
596
+ if (varInfo.references.length === 0) {
597
+ return false;
598
+ }
599
+ const declarationLine = varInfo.declarationLine;
600
+ const maxUsageLine = Math.max(
601
+ ...varInfo.references.map((ref) => ref.loc?.start.line ?? declarationLine)
602
+ );
603
+ return maxUsageLine - declarationLine <= maxLines;
604
+ }
605
+ /**
606
+ * Check if a variable is used in a limited scope (e.g., only in one callback)
607
+ */
608
+ isLocallyScoped(varInfo) {
609
+ if (varInfo.references.length === 0) return false;
610
+ const lines = varInfo.references.map((ref) => ref.loc?.start.line ?? 0);
611
+ const minLine = Math.min(...lines);
612
+ const maxLine = Math.max(...lines);
613
+ return maxLine - minLine <= 3;
614
+ }
615
+ /**
616
+ * Get current scope type
617
+ */
618
+ getCurrentScopeType() {
619
+ return this.currentScope.type;
620
+ }
621
+ /**
622
+ * Check if currently in a loop scope
623
+ */
624
+ isInLoop() {
625
+ let scope = this.currentScope;
626
+ while (scope) {
627
+ if (scope.type === "loop") {
628
+ return true;
629
+ }
630
+ scope = scope.parent;
631
+ }
632
+ return false;
633
+ }
634
+ /**
635
+ * Check if currently in a function scope
636
+ */
637
+ isInFunction() {
638
+ let scope = this.currentScope;
639
+ while (scope) {
640
+ if (scope.type === "function") {
641
+ return true;
642
+ }
643
+ scope = scope.parent;
644
+ }
645
+ return false;
646
+ }
647
+ /**
648
+ * Get the root scope
649
+ */
650
+ getRootScope() {
651
+ return this.rootScope;
652
+ }
653
+ };
654
+
655
+ // src/utils/context-detector.ts
656
+ import { Severity } from "@aiready/core";
657
+ function detectFileType(filePath, ast) {
658
+ void ast;
659
+ const path = filePath.toLowerCase();
660
+ if (path.match(/\.(test|spec)\.(ts|tsx|js|jsx)$/) || path.includes("__tests__")) {
661
+ return "test";
662
+ }
663
+ if (path.endsWith(".d.ts") || path.includes("types")) {
664
+ return "types";
665
+ }
666
+ if (path.match(/config|\.config\.|rc\.|setup/) || path.includes("configuration")) {
667
+ return "config";
668
+ }
669
+ return "production";
670
+ }
671
+ function detectCodeLayer(ast) {
672
+ let hasAPIIndicators = 0;
673
+ let hasBusinessIndicators = 0;
674
+ let hasDataIndicators = 0;
675
+ let hasUtilityIndicators = 0;
676
+ traverseAST(ast, {
677
+ enter: (node) => {
678
+ if (node.type === "ImportDeclaration") {
679
+ const source = node.source.value;
680
+ if (source.match(/express|fastify|koa|@nestjs|axios|fetch|http/i)) {
681
+ hasAPIIndicators++;
682
+ }
683
+ if (source.match(/database|prisma|typeorm|sequelize|mongoose|pg|mysql/i)) {
684
+ hasDataIndicators++;
685
+ }
686
+ }
687
+ if (node.type === "FunctionDeclaration" && node.id) {
688
+ const name = node.id.name;
689
+ if (name.match(
690
+ /^(get|post|put|delete|patch|handle|api|route|controller)/i
691
+ )) {
692
+ hasAPIIndicators++;
693
+ }
694
+ if (name.match(/^(calculate|process|validate|transform|compute|analyze)/i)) {
695
+ hasBusinessIndicators++;
696
+ }
697
+ if (name.match(/^(find|create|update|delete|save|fetch|query|insert)/i)) {
698
+ hasDataIndicators++;
699
+ }
700
+ if (name.match(
701
+ /^(format|parse|convert|normalize|sanitize|encode|decode)/i
702
+ )) {
703
+ hasUtilityIndicators++;
704
+ }
705
+ }
706
+ if (node.type === "ExportNamedDeclaration" || node.type === "ExportDefaultDeclaration") {
707
+ if (node.type === "ExportNamedDeclaration" && node.declaration) {
708
+ if (node.declaration.type === "FunctionDeclaration" && node.declaration.id) {
709
+ const name = node.declaration.id.name;
710
+ if (name.match(/handler|route|api|controller/i)) {
711
+ hasAPIIndicators += 2;
712
+ }
713
+ }
714
+ }
715
+ }
716
+ }
717
+ });
718
+ const scores = {
719
+ api: hasAPIIndicators,
720
+ business: hasBusinessIndicators,
721
+ data: hasDataIndicators,
722
+ utility: hasUtilityIndicators
723
+ };
724
+ const maxScore = Math.max(...Object.values(scores));
725
+ if (maxScore === 0) {
726
+ return "unknown";
727
+ }
728
+ if (scores.api === maxScore) return "api";
729
+ if (scores.data === maxScore) return "data";
730
+ if (scores.business === maxScore) return "business";
731
+ if (scores.utility === maxScore) return "utility";
732
+ return "unknown";
733
+ }
734
+ function calculateComplexity(node) {
735
+ let complexity = 1;
736
+ traverseAST(node, {
737
+ enter: (childNode) => {
738
+ switch (childNode.type) {
739
+ case "IfStatement":
740
+ case "ConditionalExpression":
741
+ // ternary
742
+ case "SwitchCase":
743
+ case "ForStatement":
744
+ case "ForInStatement":
745
+ case "ForOfStatement":
746
+ case "WhileStatement":
747
+ case "DoWhileStatement":
748
+ case "CatchClause":
749
+ complexity++;
750
+ break;
751
+ case "LogicalExpression":
752
+ if (childNode.operator === "&&" || childNode.operator === "||") {
753
+ complexity++;
754
+ }
755
+ break;
756
+ }
757
+ }
758
+ });
759
+ return complexity;
760
+ }
761
+ function buildCodeContext(filePath, ast) {
762
+ const fileType = detectFileType(filePath, ast);
763
+ const codeLayer = detectCodeLayer(ast);
764
+ let totalComplexity = 0;
765
+ let functionCount = 0;
766
+ traverseAST(ast, {
767
+ enter: (node) => {
768
+ if (node.type === "FunctionDeclaration" || node.type === "FunctionExpression" || node.type === "ArrowFunctionExpression") {
769
+ totalComplexity += calculateComplexity(node);
770
+ functionCount++;
771
+ }
772
+ }
773
+ });
774
+ const avgComplexity = functionCount > 0 ? totalComplexity / functionCount : 1;
775
+ return {
776
+ fileType,
777
+ codeLayer,
778
+ complexity: Math.round(avgComplexity),
779
+ isTestFile: fileType === "test",
780
+ isTypeDefinition: fileType === "types"
781
+ };
782
+ }
783
+ function adjustSeverity(baseSeverity, context, issueType) {
784
+ const map = {
785
+ [Severity.Info]: Severity.Info,
786
+ [Severity.Minor]: Severity.Minor,
787
+ [Severity.Major]: Severity.Major,
788
+ [Severity.Critical]: Severity.Critical,
789
+ info: Severity.Info,
790
+ minor: Severity.Minor,
791
+ major: Severity.Major,
792
+ critical: Severity.Critical
793
+ };
794
+ let currentSev = map[baseSeverity] || Severity.Info;
795
+ if (context.isTestFile) {
796
+ if (currentSev === Severity.Minor) currentSev = Severity.Info;
797
+ if (currentSev === Severity.Major) currentSev = Severity.Minor;
798
+ }
799
+ if (context.isTypeDefinition) {
800
+ if (currentSev === Severity.Minor) currentSev = Severity.Info;
801
+ }
802
+ if (context.codeLayer === "api") {
803
+ if (currentSev === Severity.Info && issueType === "unclear")
804
+ currentSev = Severity.Minor;
805
+ if (currentSev === Severity.Minor && issueType === "unclear")
806
+ currentSev = Severity.Major;
807
+ }
808
+ if (context.complexity > 10) {
809
+ if (currentSev === Severity.Info) currentSev = Severity.Minor;
810
+ }
811
+ if (context.codeLayer === "utility") {
812
+ if (currentSev === Severity.Minor && issueType === "abbreviation")
813
+ currentSev = Severity.Info;
814
+ }
815
+ return currentSev;
816
+ }
817
+ function isAcceptableInContext(name, context, options) {
818
+ if (options.isLoopVariable && ["i", "j", "k", "l", "n", "m"].includes(name)) {
819
+ return true;
820
+ }
821
+ if (context.isTestFile) {
822
+ if (["a", "b", "c", "x", "y", "z"].includes(name) && options.isParameter) {
823
+ return true;
824
+ }
825
+ }
826
+ if (context.codeLayer === "utility" && ["x", "y", "z"].includes(name)) {
827
+ return true;
828
+ }
829
+ if (options.isDestructured) {
830
+ if (["s", "b", "f", "l"].includes(name)) {
831
+ return true;
832
+ }
833
+ }
834
+ if (options.isParameter && (options.complexity ?? context.complexity) < 3) {
835
+ if (name.length >= 2) {
836
+ return true;
837
+ }
838
+ }
839
+ return false;
840
+ }
841
+
842
+ // src/utils/config-loader.ts
843
+ import { loadConfig } from "@aiready/core";
844
+ import { dirname } from "path";
845
+ async function loadNamingConfig(files) {
846
+ const rootDir = files.length > 0 ? dirname(files[0]) : process.cwd();
847
+ const config = await loadConfig(rootDir);
848
+ const consistencyConfig = config?.tools?.["consistency"];
849
+ const customAbbreviations = new Set(
850
+ consistencyConfig?.acceptedAbbreviations || []
851
+ );
852
+ const customShortWords = new Set(consistencyConfig?.shortWords || []);
853
+ const disabledChecks = new Set(consistencyConfig?.disableChecks || []);
854
+ const allAbbreviations = /* @__PURE__ */ new Set([
855
+ ...ACCEPTABLE_ABBREVIATIONS,
856
+ ...customAbbreviations
857
+ ]);
858
+ const allShortWords = /* @__PURE__ */ new Set([...COMMON_SHORT_WORDS, ...customShortWords]);
859
+ return {
860
+ customAbbreviations,
861
+ customShortWords,
862
+ disabledChecks,
863
+ allAbbreviations,
864
+ allShortWords
865
+ };
866
+ }
867
+
868
+ // src/analyzers/naming-ast.ts
869
+ async function analyzeNamingAST(files) {
870
+ const issues = [];
871
+ const { allAbbreviations, allShortWords, disabledChecks } = await loadNamingConfig(files);
872
+ const supportedFiles = files.filter(
873
+ (file) => /\.(js|jsx|ts|tsx)$/i.test(file)
874
+ );
875
+ for (const file of supportedFiles) {
876
+ try {
877
+ const ast = parseFile(file);
878
+ if (!ast) continue;
879
+ const fileIssues = analyzeFileNamingAST(
880
+ file,
881
+ ast,
882
+ allAbbreviations,
883
+ allShortWords,
884
+ disabledChecks
885
+ );
886
+ issues.push(...fileIssues);
887
+ } catch (error) {
888
+ console.warn(`Skipping ${file} due to parse error:`, error);
889
+ }
890
+ }
891
+ return issues;
892
+ }
893
+ function analyzeFileNamingAST(file, ast, allAbbreviations, allShortWords, disabledChecks) {
894
+ const issues = [];
895
+ const scopeTracker = new ScopeTracker(ast);
896
+ const context = buildCodeContext(file, ast);
897
+ const ancestors = [];
898
+ traverseAST(ast, {
899
+ enter: (node, parent) => {
900
+ ancestors.push(node);
901
+ if (node.type === "FunctionDeclaration" || node.type === "FunctionExpression" || node.type === "ArrowFunctionExpression") {
902
+ scopeTracker.enterScope("function", node);
903
+ if ("params" in node) {
904
+ for (const param of node.params) {
905
+ if (param.type === "Identifier") {
906
+ scopeTracker.declareVariable(
907
+ param.name,
908
+ param,
909
+ getLineNumber(param),
910
+ {
911
+ isParameter: true
912
+ }
913
+ );
914
+ } else if (param.type === "ObjectPattern" || param.type === "ArrayPattern") {
915
+ extractIdentifiersFromPattern(param, scopeTracker, true);
916
+ }
917
+ }
918
+ }
919
+ } else if (node.type === "BlockStatement") {
920
+ scopeTracker.enterScope("block", node);
921
+ } else if (isLoopStatement(node)) {
922
+ scopeTracker.enterScope("loop", node);
923
+ } else if (node.type === "ClassDeclaration") {
924
+ scopeTracker.enterScope("class", node);
925
+ }
926
+ if (node.type === "VariableDeclarator") {
927
+ if (node.id.type === "Identifier") {
928
+ void isCoverageContext(node, ancestors);
929
+ scopeTracker.declareVariable(
930
+ node.id.name,
931
+ node.id,
932
+ getLineNumber(node.id),
933
+ {
934
+ type: "typeAnnotation" in node.id ? node.id.typeAnnotation : null,
935
+ isDestructured: false,
936
+ isLoopVariable: scopeTracker.getCurrentScopeType() === "loop"
937
+ }
938
+ );
939
+ } else if (node.id.type === "ObjectPattern" || node.id.type === "ArrayPattern") {
940
+ extractIdentifiersFromPattern(
941
+ node.id,
942
+ scopeTracker,
943
+ false,
944
+ ancestors
945
+ );
946
+ }
947
+ }
948
+ if (node.type === "Identifier" && parent) {
949
+ if (parent.type !== "VariableDeclarator" || parent.id !== node) {
950
+ if (parent.type !== "FunctionDeclaration" || parent.id !== node) {
951
+ scopeTracker.addReference(node.name, node);
952
+ }
953
+ }
954
+ }
955
+ },
956
+ leave: (node) => {
957
+ ancestors.pop();
958
+ if (node.type === "FunctionDeclaration" || node.type === "FunctionExpression" || node.type === "ArrowFunctionExpression" || node.type === "BlockStatement" || isLoopStatement(node) || node.type === "ClassDeclaration") {
959
+ scopeTracker.exitScope();
960
+ }
961
+ }
962
+ });
963
+ const allVariables = scopeTracker.getAllVariables();
964
+ for (const varInfo of allVariables) {
965
+ const name = varInfo.name;
966
+ const line = varInfo.declarationLine;
967
+ if (disabledChecks.has("single-letter") && name.length === 1) continue;
968
+ if (disabledChecks.has("abbreviation") && name.length <= 3) continue;
969
+ const isInCoverage = ["s", "b", "f", "l"].includes(name) && varInfo.isDestructured;
970
+ if (isInCoverage) continue;
971
+ const functionComplexity = varInfo.node.type === "Identifier" && "parent" in varInfo.node ? calculateComplexity(varInfo.node) : context.complexity;
972
+ if (isAcceptableInContext(name, context, {
973
+ isLoopVariable: varInfo.isLoopVariable || allAbbreviations.has(name),
974
+ isParameter: varInfo.isParameter,
975
+ isDestructured: varInfo.isDestructured,
976
+ complexity: functionComplexity
977
+ })) {
978
+ continue;
979
+ }
980
+ if (name.length === 1 && !allAbbreviations.has(name) && !allShortWords.has(name)) {
981
+ const isShortLived = scopeTracker.isShortLived(varInfo, 5);
982
+ if (!isShortLived) {
983
+ issues.push({
984
+ file,
985
+ line,
986
+ type: "poor-naming",
987
+ identifier: name,
988
+ severity: adjustSeverity("minor", context, "poor-naming"),
989
+ suggestion: `Use descriptive variable name instead of single letter '${name}'`
990
+ });
991
+ }
992
+ continue;
993
+ }
994
+ if (name.length >= 2 && name.length <= 3) {
995
+ if (!allShortWords.has(name.toLowerCase()) && !allAbbreviations.has(name.toLowerCase())) {
996
+ const isShortLived = scopeTracker.isShortLived(varInfo, 5);
997
+ if (!isShortLived) {
998
+ issues.push({
999
+ file,
1000
+ line,
1001
+ type: "abbreviation",
1002
+ identifier: name,
1003
+ severity: adjustSeverity("info", context, "abbreviation"),
1004
+ suggestion: `Consider using full word instead of abbreviation '${name}'`
1005
+ });
1006
+ }
1007
+ }
1008
+ continue;
1009
+ }
1010
+ if (!disabledChecks.has("convention-mix") && file.match(/\.(ts|tsx|js|jsx)$/)) {
1011
+ if (name.includes("_") && !name.startsWith("_") && name.toLowerCase() === name) {
1012
+ const camelCase = name.replace(
1013
+ /_([a-z])/g,
1014
+ (_, letter) => letter.toUpperCase()
1015
+ );
1016
+ issues.push({
1017
+ file,
1018
+ line,
1019
+ type: "convention-mix",
1020
+ identifier: name,
1021
+ severity: adjustSeverity("minor", context, "convention-mix"),
1022
+ suggestion: `Use camelCase '${camelCase}' instead of snake_case in TypeScript/JavaScript`
1023
+ });
1024
+ }
1025
+ }
1026
+ }
1027
+ if (!disabledChecks.has("unclear")) {
1028
+ traverseAST(ast, {
1029
+ enter: (node) => {
1030
+ if (node.type === "FunctionDeclaration" || node.type === "MethodDefinition") {
1031
+ const name = getFunctionName(node);
1032
+ if (!name) return;
1033
+ const line = getLineNumber(node);
1034
+ if (["main", "init", "setup", "bootstrap"].includes(name)) return;
1035
+ const hasActionVerb = name.match(
1036
+ /^(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)/
1037
+ );
1038
+ const isFactoryPattern = name.match(
1039
+ /(Factory|Builder|Creator|Generator|Provider|Adapter|Mock)$/
1040
+ );
1041
+ const isEventHandler = name.match(/^on[A-Z]/);
1042
+ const isDescriptiveLong = name.length > 15;
1043
+ const isReactHook = name.match(/^use[A-Z]/);
1044
+ const isHelperPattern = name.match(/^(to|from|with|without|for|as|into)\w+/) || name.match(/^\w+(To|From|With|Without|For|As|Into)\w*$/);
1045
+ const isUtilityName = [
1046
+ "cn",
1047
+ "proxy",
1048
+ "sitemap",
1049
+ "robots",
1050
+ "gtag"
1051
+ ].includes(name);
1052
+ const isLanguageKeyword = [
1053
+ "constructor",
1054
+ "toString",
1055
+ "valueOf",
1056
+ "toJSON"
1057
+ ].includes(name);
1058
+ const isFrameworkPattern = name.match(
1059
+ /^(goto|fill|click|select|submit|wait|expect)\w*/
1060
+ );
1061
+ const isDescriptivePattern = name.match(
1062
+ /^(default|total|count|sum|avg|max|min|initial|current|previous|next)\w+/
1063
+ ) || name.match(
1064
+ /\w+(Count|Total|Sum|Average|List|Map|Set|Config|Settings|Options|Props|Data|Info|Details|State|Status|Response|Result)$/
1065
+ );
1066
+ const capitalCount = (name.match(/[A-Z]/g) || []).length;
1067
+ const isCompoundWord = capitalCount >= 3;
1068
+ if (!hasActionVerb && !isFactoryPattern && !isEventHandler && !isDescriptiveLong && !isReactHook && !isHelperPattern && !isUtilityName && !isDescriptivePattern && !isCompoundWord && !isLanguageKeyword && !isFrameworkPattern) {
1069
+ issues.push({
1070
+ file,
1071
+ line,
1072
+ type: "unclear",
1073
+ identifier: name,
1074
+ severity: adjustSeverity("info", context, "unclear"),
1075
+ suggestion: `Function '${name}' should start with an action verb (get, set, create, etc.)`
1076
+ });
1077
+ }
1078
+ }
1079
+ }
1080
+ });
1081
+ }
1082
+ return issues;
1083
+ }
1084
+ function extractIdentifiersFromPattern(pattern, scopeTracker, isParameter, ancestors) {
1085
+ void ancestors;
1086
+ if (pattern.type === "ObjectPattern") {
1087
+ for (const prop of pattern.properties) {
1088
+ if (prop.type === "Property" && prop.value.type === "Identifier") {
1089
+ scopeTracker.declareVariable(
1090
+ prop.value.name,
1091
+ prop.value,
1092
+ getLineNumber(prop.value),
1093
+ {
1094
+ isParameter,
1095
+ isDestructured: true
1096
+ }
1097
+ );
1098
+ } else if (prop.type === "RestElement" && prop.argument.type === "Identifier") {
1099
+ scopeTracker.declareVariable(
1100
+ prop.argument.name,
1101
+ prop.argument,
1102
+ getLineNumber(prop.argument),
1103
+ {
1104
+ isParameter,
1105
+ isDestructured: true
1106
+ }
1107
+ );
1108
+ }
1109
+ }
1110
+ } else if (pattern.type === "ArrayPattern") {
1111
+ for (const element of pattern.elements) {
1112
+ if (element && element.type === "Identifier") {
1113
+ scopeTracker.declareVariable(
1114
+ element.name,
1115
+ element,
1116
+ getLineNumber(element),
1117
+ {
1118
+ isParameter,
1119
+ isDestructured: true
1120
+ }
1121
+ );
1122
+ }
1123
+ }
1124
+ }
1125
+ }
1126
+
1127
+ // src/analyzers/patterns.ts
1128
+ import { readFileContent } from "@aiready/core";
1129
+ async function analyzePatterns(files) {
1130
+ const issues = [];
1131
+ const errorHandlingIssues = await analyzeErrorHandling(files);
1132
+ issues.push(...errorHandlingIssues);
1133
+ const asyncIssues = await analyzeAsyncPatterns(files);
1134
+ issues.push(...asyncIssues);
1135
+ const importIssues = await analyzeImportStyles(files);
1136
+ issues.push(...importIssues);
1137
+ return issues;
1138
+ }
1139
+ async function analyzeErrorHandling(files) {
1140
+ const patterns = {
1141
+ tryCatch: [],
1142
+ throwsError: [],
1143
+ returnsNull: [],
1144
+ returnsError: []
1145
+ };
1146
+ for (const file of files) {
1147
+ const content = await readFileContent(file);
1148
+ if (content.includes("try {") || content.includes("} catch")) {
1149
+ patterns.tryCatch.push(file);
1150
+ }
1151
+ if (content.match(/throw new \w*Error/)) {
1152
+ patterns.throwsError.push(file);
1153
+ }
1154
+ if (content.match(/return null/)) {
1155
+ patterns.returnsNull.push(file);
1156
+ }
1157
+ if (content.match(/return \{ error:/)) {
1158
+ patterns.returnsError.push(file);
1159
+ }
1160
+ }
1161
+ const issues = [];
1162
+ const strategiesUsed = Object.values(patterns).filter(
1163
+ (p) => p.length > 0
1164
+ ).length;
1165
+ if (strategiesUsed > 2) {
1166
+ issues.push({
1167
+ files: [
1168
+ .../* @__PURE__ */ new Set([
1169
+ ...patterns.tryCatch,
1170
+ ...patterns.throwsError,
1171
+ ...patterns.returnsNull,
1172
+ ...patterns.returnsError
1173
+ ])
1174
+ ],
1175
+ type: "error-handling",
1176
+ description: "Inconsistent error handling strategies across codebase",
1177
+ examples: [
1178
+ patterns.tryCatch.length > 0 ? `Try-catch used in ${patterns.tryCatch.length} files` : "",
1179
+ patterns.throwsError.length > 0 ? `Throws errors in ${patterns.throwsError.length} files` : "",
1180
+ patterns.returnsNull.length > 0 ? `Returns null in ${patterns.returnsNull.length} files` : "",
1181
+ patterns.returnsError.length > 0 ? `Returns error objects in ${patterns.returnsError.length} files` : ""
1182
+ ].filter((e) => e),
1183
+ severity: "major"
1184
+ });
1185
+ }
1186
+ return issues;
1187
+ }
1188
+ async function analyzeAsyncPatterns(files) {
1189
+ const patterns = {
1190
+ asyncAwait: [],
1191
+ promises: [],
1192
+ callbacks: []
1193
+ };
1194
+ for (const file of files) {
1195
+ const content = await readFileContent(file);
1196
+ if (content.match(/async\s+(function|\(|[a-zA-Z])/)) {
1197
+ patterns.asyncAwait.push(file);
1198
+ }
1199
+ if (content.match(/\.then\(/) || content.match(/\.catch\(/)) {
1200
+ patterns.promises.push(file);
1201
+ }
1202
+ if (content.match(/callback\s*\(/) || content.match(/\(\s*err\s*,/)) {
1203
+ patterns.callbacks.push(file);
1204
+ }
1205
+ }
1206
+ const issues = [];
1207
+ if (patterns.callbacks.length > 0 && patterns.asyncAwait.length > 0) {
1208
+ issues.push({
1209
+ files: [...patterns.callbacks, ...patterns.asyncAwait],
1210
+ type: "async-style",
1211
+ description: "Mixed async patterns: callbacks and async/await",
1212
+ examples: [
1213
+ `Callbacks found in: ${patterns.callbacks.slice(0, 3).join(", ")}`,
1214
+ `Async/await used in: ${patterns.asyncAwait.slice(0, 3).join(", ")}`
1215
+ ],
1216
+ severity: "minor"
1217
+ });
1218
+ }
1219
+ if (patterns.promises.length > patterns.asyncAwait.length * 0.3 && patterns.asyncAwait.length > 0) {
1220
+ issues.push({
1221
+ files: patterns.promises,
1222
+ type: "async-style",
1223
+ description: "Consider using async/await instead of promise chains for consistency",
1224
+ examples: patterns.promises.slice(0, 5),
1225
+ severity: "info"
1226
+ });
1227
+ }
1228
+ return issues;
1229
+ }
1230
+ async function analyzeImportStyles(files) {
1231
+ const patterns = {
1232
+ esModules: [],
1233
+ commonJS: [],
1234
+ mixed: []
1235
+ };
1236
+ for (const file of files) {
1237
+ const content = await readFileContent(file);
1238
+ const hasESM = content.match(/^import\s+/m);
1239
+ const hasCJS = hasActualRequireCalls(content);
1240
+ if (hasESM && hasCJS) {
1241
+ patterns.mixed.push(file);
1242
+ } else if (hasESM) {
1243
+ patterns.esModules.push(file);
1244
+ } else if (hasCJS) {
1245
+ patterns.commonJS.push(file);
1246
+ }
1247
+ }
1248
+ const issues = [];
1249
+ if (patterns.mixed.length > 0) {
1250
+ issues.push({
1251
+ files: patterns.mixed,
1252
+ type: "import-style",
1253
+ description: "Mixed ES modules and CommonJS imports in same files",
1254
+ examples: patterns.mixed.slice(0, 5),
1255
+ severity: "major"
1256
+ });
1257
+ }
1258
+ if (patterns.esModules.length > 0 && patterns.commonJS.length > 0) {
1259
+ const ratio = patterns.commonJS.length / (patterns.esModules.length + patterns.commonJS.length);
1260
+ if (ratio > 0.2 && ratio < 0.8) {
1261
+ issues.push({
1262
+ files: [...patterns.esModules, ...patterns.commonJS],
1263
+ type: "import-style",
1264
+ description: "Inconsistent import styles across project",
1265
+ examples: [
1266
+ `ES modules: ${patterns.esModules.length} files`,
1267
+ `CommonJS: ${patterns.commonJS.length} files`
1268
+ ],
1269
+ severity: "minor"
1270
+ });
1271
+ }
1272
+ }
1273
+ return issues;
1274
+ }
1275
+ function hasActualRequireCalls(content) {
1276
+ let cleaned = content.replace(/\/\/.*$/gm, "");
1277
+ cleaned = cleaned.replace(/\/\*[\s\S]*?\*\//g, "");
1278
+ cleaned = cleaned.replace(/"[^"\n]*"/g, '""');
1279
+ cleaned = cleaned.replace(/'[^'\n]*'/g, "''");
1280
+ cleaned = cleaned.replace(/`[^`]*`/g, "``");
1281
+ cleaned = cleaned.replace(/\/[^/\n]*require[^/\n]*\/[gimsuvy]*/g, "");
1282
+ return /require\s*\(/.test(cleaned);
1283
+ }
1284
+
1285
+ // src/analyzer.ts
1286
+ import { scanFiles, Severity as Severity2 } from "@aiready/core";
1287
+
1288
+ // src/analyzers/naming-python.ts
1289
+ import { getParser } from "@aiready/core";
1290
+ async function analyzePythonNaming(files) {
1291
+ const issues = [];
1292
+ const parser = getParser("dummy.py");
1293
+ if (!parser) {
1294
+ console.warn("Python parser not available");
1295
+ return issues;
1296
+ }
1297
+ const pythonFiles = files.filter((f) => f.toLowerCase().endsWith(".py"));
1298
+ for (const file of pythonFiles) {
1299
+ try {
1300
+ const fs = await import("fs");
1301
+ const code = await fs.promises.readFile(file, "utf-8");
1302
+ const result = parser.parse(code, file);
1303
+ for (const exp of result.exports) {
1304
+ const nameIssue = checkPythonNaming(
1305
+ exp.name,
1306
+ exp.type,
1307
+ file,
1308
+ exp.loc?.start.line || 0
1309
+ );
1310
+ if (nameIssue) {
1311
+ issues.push(nameIssue);
1312
+ }
1313
+ }
1314
+ for (const imp of result.imports) {
1315
+ for (const spec of imp.specifiers) {
1316
+ if (spec !== "*" && spec !== "default") {
1317
+ const nameIssue = checkPythonNaming(
1318
+ spec,
1319
+ "variable",
1320
+ file,
1321
+ imp.loc?.start.line || 0
1322
+ );
1323
+ if (nameIssue) {
1324
+ issues.push(nameIssue);
1325
+ }
1326
+ }
1327
+ }
1328
+ }
1329
+ } catch (error) {
1330
+ console.warn(`Skipping ${file} due to error:`, error);
1331
+ }
1332
+ }
1333
+ return issues;
1334
+ }
1335
+ function checkPythonNaming(identifier, type, file, line) {
1336
+ const parser = getParser("dummy.py");
1337
+ const conventions = parser?.getNamingConventions();
1338
+ if (!conventions) return null;
1339
+ if (conventions.exceptions?.includes(identifier)) {
1340
+ return null;
1341
+ }
1342
+ if (type === "class") {
1343
+ if (!conventions.classPattern.test(identifier)) {
1344
+ return {
1345
+ type: "poor-naming",
1346
+ identifier,
1347
+ file,
1348
+ line,
1349
+ column: 0,
1350
+ severity: "major",
1351
+ category: "naming",
1352
+ suggestion: `Class names should use PascalCase (e.g., ${toPascalCase(identifier)})`
1353
+ };
1354
+ }
1355
+ } else if (type === "function") {
1356
+ if (!conventions.functionPattern.test(identifier)) {
1357
+ if (/^[a-z][a-zA-Z0-9]*$/.test(identifier) && /[A-Z]/.test(identifier)) {
1358
+ return {
1359
+ type: "convention-mix",
1360
+ identifier,
1361
+ file,
1362
+ line,
1363
+ column: 0,
1364
+ severity: "major",
1365
+ category: "naming",
1366
+ suggestion: `Function names should use snake_case, not camelCase (e.g., ${toSnakeCase(identifier)})`
1367
+ };
1368
+ }
1369
+ }
1370
+ } else if (type === "const" || type === "variable") {
1371
+ if (identifier === identifier.toUpperCase() && identifier.length > 1) {
1372
+ if (!conventions.constantPattern.test(identifier)) {
1373
+ return {
1374
+ type: "poor-naming",
1375
+ identifier,
1376
+ file,
1377
+ line,
1378
+ column: 0,
1379
+ severity: "minor",
1380
+ category: "naming",
1381
+ suggestion: "Constants should use UPPER_CASE_WITH_UNDERSCORES"
1382
+ };
1383
+ }
1384
+ } else {
1385
+ if (!conventions.variablePattern.test(identifier)) {
1386
+ if (/^[a-z][a-zA-Z0-9]*$/.test(identifier) && /[A-Z]/.test(identifier)) {
1387
+ return {
1388
+ type: "convention-mix",
1389
+ identifier,
1390
+ file,
1391
+ line,
1392
+ column: 0,
1393
+ severity: "major",
1394
+ category: "naming",
1395
+ suggestion: `Variable names should use snake_case, not camelCase (e.g., ${toSnakeCase(identifier)})`
1396
+ };
1397
+ }
1398
+ }
1399
+ }
1400
+ }
1401
+ return null;
1402
+ }
1403
+ function toSnakeCase(str) {
1404
+ return str.replace(/([A-Z])/g, "_$1").toLowerCase().replace(/^_/, "");
1405
+ }
1406
+ function toPascalCase(str) {
1407
+ return str.split("_").map((word) => word.charAt(0).toUpperCase() + word.slice(1).toLowerCase()).join("");
1408
+ }
1409
+
1410
+ // src/analyzer.ts
1411
+ async function analyzeConsistency(options) {
1412
+ const {
1413
+ checkNaming = true,
1414
+ checkPatterns = true,
1415
+ checkArchitecture = false,
1416
+ // Not implemented yet
1417
+ minSeverity = Severity2.Info,
1418
+ ...scanOptions
1419
+ } = options;
1420
+ void checkArchitecture;
1421
+ const filePaths = await scanFiles(scanOptions);
1422
+ const tsJsFiles = filePaths.filter((f) => /\.(ts|tsx|js|jsx)$/i.test(f));
1423
+ const pythonFiles = filePaths.filter((f) => /\.py$/i.test(f));
1424
+ let namingIssues = [];
1425
+ if (checkNaming) {
1426
+ const tsJsNamingIssues = tsJsFiles.length > 0 ? await analyzeNamingAST(tsJsFiles) : [];
1427
+ const pythonNamingIssues = pythonFiles.length > 0 ? await analyzePythonNaming(pythonFiles) : [];
1428
+ namingIssues = [...tsJsNamingIssues, ...pythonNamingIssues];
1429
+ }
1430
+ const patternIssues = checkPatterns ? await analyzePatterns(filePaths) : [];
1431
+ const results = [];
1432
+ const fileIssuesMap = /* @__PURE__ */ new Map();
1433
+ for (const issue of namingIssues) {
1434
+ if (!shouldIncludeSeverity(issue.severity, minSeverity)) {
1435
+ continue;
1436
+ }
1437
+ const consistencyIssue = {
1438
+ type: issue.type === "convention-mix" ? "naming-inconsistency" : "naming-quality",
1439
+ category: "naming",
1440
+ severity: issue.severity,
1441
+ message: `${issue.type}: ${issue.identifier}`,
1442
+ location: {
1443
+ file: issue.file,
1444
+ line: issue.line,
1445
+ column: issue.column
1446
+ },
1447
+ suggestion: issue.suggestion
1448
+ };
1449
+ if (!fileIssuesMap.has(issue.file)) {
1450
+ fileIssuesMap.set(issue.file, []);
1451
+ }
1452
+ fileIssuesMap.get(issue.file).push(consistencyIssue);
1453
+ }
1454
+ for (const issue of patternIssues) {
1455
+ if (!shouldIncludeSeverity(issue.severity, minSeverity)) {
1456
+ continue;
1457
+ }
1458
+ const consistencyIssue = {
1459
+ type: "pattern-inconsistency",
1460
+ category: "patterns",
1461
+ severity: issue.severity,
1462
+ message: issue.description,
1463
+ location: {
1464
+ file: issue.files[0] || "multiple files",
1465
+ line: 1
1466
+ },
1467
+ examples: issue.examples,
1468
+ suggestion: `Standardize ${issue.type} patterns across ${issue.files.length} files`
1469
+ };
1470
+ const firstFile = issue.files[0];
1471
+ if (firstFile && !fileIssuesMap.has(firstFile)) {
1472
+ fileIssuesMap.set(firstFile, []);
1473
+ }
1474
+ if (firstFile) {
1475
+ fileIssuesMap.get(firstFile).push(consistencyIssue);
1476
+ }
1477
+ }
1478
+ for (const [fileName, issues] of fileIssuesMap) {
1479
+ results.push({
1480
+ fileName,
1481
+ issues,
1482
+ metrics: {
1483
+ consistencyScore: calculateConsistencyScore(issues)
1484
+ }
1485
+ });
1486
+ }
1487
+ results.sort((fileResultA, fileResultB) => {
1488
+ const severityOrder = {
1489
+ 4: 0,
1490
+ // Critical
1491
+ 3: 1,
1492
+ // Major
1493
+ 2: 2,
1494
+ // Minor
1495
+ 1: 3
1496
+ // Info
1497
+ };
1498
+ const maxSeverityA = Math.min(
1499
+ ...fileResultA.issues.map((i) => severityOrder[getSeverityLevel(i.severity)] ?? 3)
1500
+ );
1501
+ const maxSeverityB = Math.min(
1502
+ ...fileResultB.issues.map((i) => severityOrder[getSeverityLevel(i.severity)] ?? 3)
1503
+ );
1504
+ if (maxSeverityA !== maxSeverityB) {
1505
+ return maxSeverityA - maxSeverityB;
1506
+ }
1507
+ return fileResultB.issues.length - fileResultA.issues.length;
1508
+ });
1509
+ const recommendations = generateRecommendations(namingIssues, patternIssues);
1510
+ const namingCountFiltered = namingIssues.filter(
1511
+ (i) => shouldIncludeSeverity(i.severity, minSeverity)
1512
+ ).length;
1513
+ const patternCountFiltered = patternIssues.filter(
1514
+ (i) => shouldIncludeSeverity(i.severity, minSeverity)
1515
+ ).length;
1516
+ return {
1517
+ summary: {
1518
+ totalIssues: namingCountFiltered + patternCountFiltered,
1519
+ namingIssues: namingCountFiltered,
1520
+ patternIssues: patternCountFiltered,
1521
+ architectureIssues: 0,
1522
+ filesAnalyzed: filePaths.length
1523
+ },
1524
+ results,
1525
+ recommendations
1526
+ };
1527
+ }
1528
+ function getSeverityLevel(s) {
1529
+ const map = {
1530
+ [Severity2.Critical]: 4,
1531
+ [Severity2.Major]: 3,
1532
+ [Severity2.Minor]: 2,
1533
+ [Severity2.Info]: 1,
1534
+ critical: 4,
1535
+ major: 3,
1536
+ minor: 2,
1537
+ info: 1
1538
+ };
1539
+ if (map[s] !== void 0) return map[s];
1540
+ const lower = String(s).toLowerCase();
1541
+ return map[lower] ?? 0;
1542
+ }
1543
+ function shouldIncludeSeverity(severity, minSeverity) {
1544
+ return getSeverityLevel(severity) >= getSeverityLevel(minSeverity);
1545
+ }
1546
+ function calculateConsistencyScore(issues) {
1547
+ const weights = {
1548
+ 4: 10,
1549
+ // Critical
1550
+ 3: 5,
1551
+ // Major
1552
+ 2: 2,
1553
+ // Minor
1554
+ 1: 1
1555
+ // Info
1556
+ };
1557
+ const totalWeight = issues.reduce(
1558
+ (sum, issue) => sum + (weights[getSeverityLevel(issue.severity)] ?? 1),
1559
+ 0
1560
+ );
1561
+ return Math.max(0, 1 - totalWeight / 100);
1562
+ }
1563
+ function generateRecommendations(namingIssues, patternIssues) {
1564
+ const recommendations = [];
1565
+ if (namingIssues.length > 0) {
1566
+ const conventionMixCount = namingIssues.filter(
1567
+ (i) => i.type === "convention-mix"
1568
+ ).length;
1569
+ if (conventionMixCount > 0) {
1570
+ recommendations.push(
1571
+ `Standardize naming conventions: Found ${conventionMixCount} snake_case variables in TypeScript/JavaScript (use camelCase)`
1572
+ );
1573
+ }
1574
+ const poorNamingCount = namingIssues.filter(
1575
+ (i) => i.type === "poor-naming"
1576
+ ).length;
1577
+ if (poorNamingCount > 0) {
1578
+ recommendations.push(
1579
+ `Improve variable naming: Found ${poorNamingCount} single-letter or unclear variable names`
1580
+ );
1581
+ }
1582
+ }
1583
+ if (patternIssues.length > 0) {
1584
+ const errorHandlingIssues = patternIssues.filter(
1585
+ (i) => i.type === "error-handling"
1586
+ );
1587
+ if (errorHandlingIssues.length > 0) {
1588
+ recommendations.push(
1589
+ "Standardize error handling strategy across the codebase (prefer try-catch with typed errors)"
1590
+ );
1591
+ }
1592
+ const asyncIssues = patternIssues.filter((i) => i.type === "async-style");
1593
+ if (asyncIssues.length > 0) {
1594
+ recommendations.push(
1595
+ "Use async/await consistently instead of mixing with promise chains or callbacks"
1596
+ );
1597
+ }
1598
+ const importIssues = patternIssues.filter((i) => i.type === "import-style");
1599
+ if (importIssues.length > 0) {
1600
+ recommendations.push(
1601
+ "Use ES modules consistently across the project (avoid mixing with CommonJS)"
1602
+ );
1603
+ }
1604
+ }
1605
+ if (recommendations.length === 0) {
1606
+ recommendations.push(
1607
+ "No major consistency issues found! Your codebase follows good practices."
1608
+ );
1609
+ }
1610
+ return recommendations;
1611
+ }
1612
+
1613
+ export {
1614
+ COMMON_SHORT_WORDS,
1615
+ ACCEPTABLE_ABBREVIATIONS,
1616
+ snakeCaseToCamelCase,
1617
+ detectNamingConventions,
1618
+ loadNamingConfig,
1619
+ analyzeNamingAST,
1620
+ analyzePatterns,
1621
+ analyzeConsistency
1622
+ };