@aiready/consistency 0.21.4 → 0.21.6

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,1144 @@
1
+ // src/analyzers/naming-constants.ts
2
+ var VAGUE_NAMES = /* @__PURE__ */ new Set([
3
+ "data",
4
+ "info",
5
+ "item",
6
+ "obj",
7
+ "val",
8
+ "tmp",
9
+ "temp",
10
+ "thing",
11
+ "stuff",
12
+ "res",
13
+ "ret",
14
+ "result",
15
+ "output",
16
+ "input",
17
+ "params",
18
+ "args",
19
+ "props",
20
+ "state",
21
+ "value",
22
+ "list",
23
+ "array",
24
+ "map",
25
+ "set",
26
+ "manager",
27
+ "handler",
28
+ "helper",
29
+ "util",
30
+ "common"
31
+ ]);
32
+ var ACCEPTABLE_ABBREVIATIONS = /* @__PURE__ */ new Set([
33
+ // Standard identifiers
34
+ "id",
35
+ "uid",
36
+ "gid",
37
+ "pid",
38
+ // Loop counters and iterators
39
+ "i",
40
+ "j",
41
+ "k",
42
+ "n",
43
+ "m",
44
+ // Web/Network
45
+ "url",
46
+ "uri",
47
+ "api",
48
+ "cdn",
49
+ "dns",
50
+ "ip",
51
+ "tcp",
52
+ "udp",
53
+ "http",
54
+ "ssl",
55
+ "tls",
56
+ "utm",
57
+ "seo",
58
+ "rss",
59
+ "xhr",
60
+ "ajax",
61
+ "cors",
62
+ "ws",
63
+ "wss",
64
+ // Data formats
65
+ "json",
66
+ "xml",
67
+ "yaml",
68
+ "csv",
69
+ "html",
70
+ "css",
71
+ "svg",
72
+ "pdf",
73
+ // File types & extensions
74
+ "img",
75
+ "txt",
76
+ "doc",
77
+ "docx",
78
+ "xlsx",
79
+ "ppt",
80
+ "md",
81
+ "rst",
82
+ "jpg",
83
+ "png",
84
+ "gif",
85
+ // Databases
86
+ "db",
87
+ "sql",
88
+ "orm",
89
+ "dao",
90
+ "dto",
91
+ "ddb",
92
+ "rds",
93
+ "nosql",
94
+ // File system
95
+ "fs",
96
+ "dir",
97
+ "tmp",
98
+ "src",
99
+ "dst",
100
+ "bin",
101
+ "lib",
102
+ "pkg",
103
+ // Operating system
104
+ "os",
105
+ "env",
106
+ "arg",
107
+ "cli",
108
+ "cmd",
109
+ "exe",
110
+ "cwd",
111
+ "pwd",
112
+ // UI/UX
113
+ "ui",
114
+ "ux",
115
+ "gui",
116
+ "dom",
117
+ "ref",
118
+ // Request/Response
119
+ "req",
120
+ "res",
121
+ "ctx",
122
+ "err",
123
+ "msg",
124
+ "auth",
125
+ // Mathematics/Computing
126
+ "max",
127
+ "min",
128
+ "avg",
129
+ "sum",
130
+ "abs",
131
+ "cos",
132
+ "sin",
133
+ "tan",
134
+ "log",
135
+ "exp",
136
+ "pow",
137
+ "sqrt",
138
+ "std",
139
+ "var",
140
+ "int",
141
+ "num",
142
+ "idx",
143
+ // Time
144
+ "now",
145
+ "utc",
146
+ "tz",
147
+ "ms",
148
+ "sec",
149
+ "hr",
150
+ "min",
151
+ "yr",
152
+ "mo",
153
+ // Common patterns
154
+ "app",
155
+ "cfg",
156
+ "config",
157
+ "init",
158
+ "len",
159
+ "val",
160
+ "str",
161
+ "obj",
162
+ "arr",
163
+ "gen",
164
+ "def",
165
+ "raw",
166
+ "new",
167
+ "old",
168
+ "pre",
169
+ "post",
170
+ "sub",
171
+ "pub",
172
+ // Programming/Framework specific
173
+ "ts",
174
+ "js",
175
+ "jsx",
176
+ "tsx",
177
+ "py",
178
+ "rb",
179
+ "vue",
180
+ "re",
181
+ "fn",
182
+ "fns",
183
+ "mod",
184
+ "opts",
185
+ "dev",
186
+ // Cloud/Infrastructure
187
+ "s3",
188
+ "ec2",
189
+ "sqs",
190
+ "sns",
191
+ "vpc",
192
+ "ami",
193
+ "iam",
194
+ "acl",
195
+ "elb",
196
+ "alb",
197
+ "nlb",
198
+ "aws",
199
+ "ses",
200
+ "gst",
201
+ "cdk",
202
+ "btn",
203
+ "buf",
204
+ "agg",
205
+ "ocr",
206
+ "ai",
207
+ "cf",
208
+ "cfn",
209
+ "ga",
210
+ // Metrics/Performance
211
+ "fcp",
212
+ "lcp",
213
+ "cls",
214
+ "ttfb",
215
+ "tti",
216
+ "fid",
217
+ "fps",
218
+ "qps",
219
+ "rps",
220
+ "tps",
221
+ "wpm",
222
+ // Testing & i18n
223
+ "po",
224
+ "e2e",
225
+ "a11y",
226
+ "i18n",
227
+ "l10n",
228
+ "spy",
229
+ // Domain-specific abbreviations (context-aware)
230
+ "sk",
231
+ "fy",
232
+ "faq",
233
+ "og",
234
+ "seo",
235
+ "cta",
236
+ "roi",
237
+ "kpi",
238
+ "ttl",
239
+ "pct",
240
+ // Technical abbreviations
241
+ "mac",
242
+ "hex",
243
+ "esm",
244
+ "git",
245
+ "rec",
246
+ "loc",
247
+ "dup",
248
+ // Boolean helpers (these are intentional short names)
249
+ "is",
250
+ "has",
251
+ "can",
252
+ "did",
253
+ "was",
254
+ "are",
255
+ // Date/Time context (when in date contexts)
256
+ "d",
257
+ "t",
258
+ "dt",
259
+ // Coverage metrics (industry standard: statements/branches/functions/lines)
260
+ "s",
261
+ "b",
262
+ "f",
263
+ "l",
264
+ // Common media/content abbreviations
265
+ "vid",
266
+ "pic",
267
+ "img",
268
+ "doc",
269
+ "msg"
270
+ ]);
271
+ function detectNamingConventions(files, allIssues) {
272
+ const camelCaseCount = allIssues.filter(
273
+ (i) => i.type === "convention-mix"
274
+ ).length;
275
+ const totalChecks = files.length * 10;
276
+ if (camelCaseCount / totalChecks > 0.3) {
277
+ return { dominantConvention: "mixed", conventionScore: 0.5 };
278
+ }
279
+ return { dominantConvention: "camelCase", conventionScore: 0.9 };
280
+ }
281
+
282
+ // src/analyzers/naming-ast.ts
283
+ import { Severity as Severity2 } from "@aiready/core";
284
+
285
+ // src/utils/ast-parser.ts
286
+ import { parse } from "@typescript-eslint/typescript-estree";
287
+ import { readFileSync } from "fs";
288
+ function parseFile(filePath, content) {
289
+ try {
290
+ const code = content ?? readFileSync(filePath, "utf-8");
291
+ const isTypeScript = filePath.match(/\.tsx?$/);
292
+ return parse(code, {
293
+ jsx: filePath.match(/\.[jt]sx$/i) !== null,
294
+ loc: true,
295
+ range: true,
296
+ comment: false,
297
+ tokens: false,
298
+ // Relaxed parsing for JavaScript files
299
+ sourceType: "module",
300
+ ecmaVersion: "latest",
301
+ // Only use TypeScript parser features for .ts/.tsx files
302
+ filePath: isTypeScript ? filePath : void 0
303
+ });
304
+ } catch (error) {
305
+ void error;
306
+ return null;
307
+ }
308
+ }
309
+ function traverseAST(node, visitor, parent = null) {
310
+ if (!node) return;
311
+ visitor.enter?.(node, parent);
312
+ for (const key of Object.keys(node)) {
313
+ const value = node[key];
314
+ if (Array.isArray(value)) {
315
+ for (const child of value) {
316
+ if (child && typeof child === "object" && "type" in child) {
317
+ traverseAST(child, visitor, node);
318
+ }
319
+ }
320
+ } else if (value && typeof value === "object" && "type" in value) {
321
+ traverseAST(value, visitor, node);
322
+ }
323
+ }
324
+ visitor.leave?.(node, parent);
325
+ }
326
+ function isLoopStatement(node) {
327
+ return [
328
+ "ForStatement",
329
+ "ForInStatement",
330
+ "ForOfStatement",
331
+ "WhileStatement",
332
+ "DoWhileStatement"
333
+ ].includes(node.type);
334
+ }
335
+ function getLineNumber(node) {
336
+ return node.loc?.start.line ?? 0;
337
+ }
338
+
339
+ // src/utils/context-detector.ts
340
+ import { Severity } from "@aiready/core";
341
+ function detectFileType(filePath, ast) {
342
+ void ast;
343
+ const path = filePath.toLowerCase();
344
+ if (path.match(/\.(test|spec)\.(ts|tsx|js|jsx)$/) || path.includes("__tests__")) {
345
+ return "test";
346
+ }
347
+ if (path.endsWith(".d.ts") || path.includes("types")) {
348
+ return "types";
349
+ }
350
+ if (path.match(/config|\.config\.|rc\.|setup/) || path.includes("configuration")) {
351
+ return "config";
352
+ }
353
+ return "production";
354
+ }
355
+ function detectCodeLayer(ast) {
356
+ let hasAPIIndicators = 0;
357
+ let hasBusinessIndicators = 0;
358
+ let hasDataIndicators = 0;
359
+ let hasUtilityIndicators = 0;
360
+ traverseAST(ast, {
361
+ enter: (node) => {
362
+ if (node.type === "ImportDeclaration") {
363
+ const source = node.source.value;
364
+ if (source.match(/express|fastify|koa|@nestjs|axios|fetch|http/i)) {
365
+ hasAPIIndicators++;
366
+ }
367
+ if (source.match(/database|prisma|typeorm|sequelize|mongoose|pg|mysql/i)) {
368
+ hasDataIndicators++;
369
+ }
370
+ }
371
+ if (node.type === "FunctionDeclaration" && node.id) {
372
+ const name = node.id.name;
373
+ if (name.match(
374
+ /^(get|post|put|delete|patch|handle|api|route|controller)/i
375
+ )) {
376
+ hasAPIIndicators++;
377
+ }
378
+ if (name.match(/^(calculate|process|validate|transform|compute|analyze)/i)) {
379
+ hasBusinessIndicators++;
380
+ }
381
+ if (name.match(/^(find|create|update|delete|save|fetch|query|insert)/i)) {
382
+ hasDataIndicators++;
383
+ }
384
+ if (name.match(
385
+ /^(format|parse|convert|normalize|sanitize|encode|decode)/i
386
+ )) {
387
+ hasUtilityIndicators++;
388
+ }
389
+ }
390
+ if (node.type === "ExportNamedDeclaration" || node.type === "ExportDefaultDeclaration") {
391
+ if (node.type === "ExportNamedDeclaration" && node.declaration) {
392
+ if (node.declaration.type === "FunctionDeclaration" && node.declaration.id) {
393
+ const name = node.declaration.id.name;
394
+ if (name.match(/handler|route|api|controller/i)) {
395
+ hasAPIIndicators += 2;
396
+ }
397
+ }
398
+ }
399
+ }
400
+ }
401
+ });
402
+ const scores = {
403
+ api: hasAPIIndicators,
404
+ business: hasBusinessIndicators,
405
+ data: hasDataIndicators,
406
+ utility: hasUtilityIndicators
407
+ };
408
+ const maxScore = Math.max(...Object.values(scores));
409
+ if (maxScore === 0) {
410
+ return "unknown";
411
+ }
412
+ if (scores.api === maxScore) return "api";
413
+ if (scores.data === maxScore) return "data";
414
+ if (scores.business === maxScore) return "business";
415
+ if (scores.utility === maxScore) return "utility";
416
+ return "unknown";
417
+ }
418
+ function calculateComplexity(node) {
419
+ let complexity = 1;
420
+ traverseAST(node, {
421
+ enter: (childNode) => {
422
+ switch (childNode.type) {
423
+ case "IfStatement":
424
+ case "ConditionalExpression":
425
+ // ternary
426
+ case "SwitchCase":
427
+ case "ForStatement":
428
+ case "ForInStatement":
429
+ case "ForOfStatement":
430
+ case "WhileStatement":
431
+ case "DoWhileStatement":
432
+ case "CatchClause":
433
+ complexity++;
434
+ break;
435
+ case "LogicalExpression":
436
+ if (childNode.operator === "&&" || childNode.operator === "||") {
437
+ complexity++;
438
+ }
439
+ break;
440
+ }
441
+ }
442
+ });
443
+ return complexity;
444
+ }
445
+ function buildCodeContext(filePath, ast) {
446
+ const fileType = detectFileType(filePath, ast);
447
+ const codeLayer = detectCodeLayer(ast);
448
+ let totalComplexity = 0;
449
+ let functionCount = 0;
450
+ traverseAST(ast, {
451
+ enter: (node) => {
452
+ if (node.type === "FunctionDeclaration" || node.type === "FunctionExpression" || node.type === "ArrowFunctionExpression") {
453
+ totalComplexity += calculateComplexity(node);
454
+ functionCount++;
455
+ }
456
+ }
457
+ });
458
+ const avgComplexity = functionCount > 0 ? totalComplexity / functionCount : 1;
459
+ return {
460
+ fileType,
461
+ codeLayer,
462
+ complexity: Math.round(avgComplexity),
463
+ isTestFile: fileType === "test",
464
+ isTypeDefinition: fileType === "types"
465
+ };
466
+ }
467
+ function adjustSeverity(baseSeverity, context, issueType) {
468
+ const getEnum = (s) => {
469
+ if (s === Severity.Critical || s === "critical") return Severity.Critical;
470
+ if (s === Severity.Major || s === "major") return Severity.Major;
471
+ if (s === Severity.Minor || s === "minor") return Severity.Minor;
472
+ return Severity.Info;
473
+ };
474
+ let currentSev = getEnum(baseSeverity);
475
+ if (context.isTestFile) {
476
+ if (currentSev === Severity.Minor) currentSev = Severity.Info;
477
+ if (currentSev === Severity.Major) currentSev = Severity.Minor;
478
+ }
479
+ if (context.isTypeDefinition) {
480
+ if (currentSev === Severity.Minor) currentSev = Severity.Info;
481
+ }
482
+ if (context.codeLayer === "api") {
483
+ if (currentSev === Severity.Info && issueType === "unclear")
484
+ currentSev = Severity.Minor;
485
+ if (currentSev === Severity.Minor && issueType === "unclear")
486
+ currentSev = Severity.Major;
487
+ }
488
+ if (context.complexity > 10) {
489
+ if (currentSev === Severity.Info) currentSev = Severity.Minor;
490
+ }
491
+ if (context.codeLayer === "utility") {
492
+ if (currentSev === Severity.Minor && issueType === "abbreviation")
493
+ currentSev = Severity.Info;
494
+ }
495
+ return currentSev;
496
+ }
497
+ function isAcceptableInContext(name, context, options) {
498
+ if (options.isLoopVariable && ["i", "j", "k", "l", "n", "m"].includes(name)) {
499
+ return true;
500
+ }
501
+ if (context.isTestFile) {
502
+ if (["a", "b", "c", "x", "y", "z"].includes(name) && options.isParameter) {
503
+ return true;
504
+ }
505
+ }
506
+ if (context.codeLayer === "utility" && ["x", "y", "z"].includes(name)) {
507
+ return true;
508
+ }
509
+ if (options.isDestructured) {
510
+ if (["s", "b", "f", "l"].includes(name)) {
511
+ return true;
512
+ }
513
+ }
514
+ if (options.isParameter && (options.complexity ?? context.complexity) < 3) {
515
+ if (name.length >= 2) {
516
+ return true;
517
+ }
518
+ }
519
+ return false;
520
+ }
521
+
522
+ // src/analyzers/naming-ast.ts
523
+ async function analyzeNamingAST(filePaths) {
524
+ const allIssues = [];
525
+ for (const filePath of filePaths) {
526
+ try {
527
+ const ast = parseFile(filePath);
528
+ if (!ast) continue;
529
+ const context = buildCodeContext(filePath, ast);
530
+ const issues = analyzeIdentifiers(ast, filePath, context);
531
+ allIssues.push(...issues);
532
+ } catch (err) {
533
+ void err;
534
+ }
535
+ }
536
+ return allIssues;
537
+ }
538
+ function analyzeIdentifiers(ast, filePath, context) {
539
+ const issues = [];
540
+ const scopeTracker = new ScopeTracker();
541
+ traverseAST(ast, {
542
+ enter: (node) => {
543
+ if (node.type === "VariableDeclarator" && node.id.type === "Identifier") {
544
+ const isParameter = false;
545
+ const isLoopVariable = isLoopStatement(node.parent?.parent);
546
+ scopeTracker.declareVariable(
547
+ node.id.name,
548
+ node.id,
549
+ getLineNumber(node.id),
550
+ { isParameter, isLoopVariable }
551
+ );
552
+ }
553
+ if (node.type === "FunctionDeclaration" || node.type === "FunctionExpression" || node.type === "ArrowFunctionExpression") {
554
+ const isArrowParameter = node.type === "ArrowFunctionExpression";
555
+ node.params.forEach((param) => {
556
+ if (param.type === "Identifier") {
557
+ scopeTracker.declareVariable(
558
+ param.name,
559
+ param,
560
+ getLineNumber(param),
561
+ { isParameter: true, isArrowParameter }
562
+ );
563
+ } else if (param.type === "ObjectPattern") {
564
+ extractDestructuredIdentifiers(param, scopeTracker, {
565
+ isParameter: true,
566
+ isArrowParameter
567
+ });
568
+ }
569
+ });
570
+ }
571
+ if ((node.type === "ClassDeclaration" || node.type === "TSInterfaceDeclaration" || node.type === "TSTypeAliasDeclaration") && node.id) {
572
+ checkNamingConvention(
573
+ node.id.name,
574
+ "PascalCase",
575
+ node.id,
576
+ filePath,
577
+ issues,
578
+ context
579
+ );
580
+ }
581
+ }
582
+ });
583
+ for (const varInfo of scopeTracker.getVariables()) {
584
+ checkVariableNaming(varInfo, filePath, issues, context);
585
+ }
586
+ return issues;
587
+ }
588
+ function checkNamingConvention(name, convention, node, file, issues, context) {
589
+ let isValid = true;
590
+ if (convention === "PascalCase") {
591
+ isValid = /^[A-Z][a-zA-Z0-9]*$/.test(name);
592
+ } else if (convention === "camelCase") {
593
+ isValid = /^[a-z][a-zA-Z0-9]*$/.test(name);
594
+ } else if (convention === "UPPER_CASE") {
595
+ isValid = /^[A-Z][A-Z0-9_]*$/.test(name);
596
+ }
597
+ if (!isValid) {
598
+ const severity = adjustSeverity(Severity2.Info, context, "convention-mix");
599
+ issues.push({
600
+ file,
601
+ line: getLineNumber(node),
602
+ type: "convention-mix",
603
+ identifier: name,
604
+ severity,
605
+ suggestion: `Follow ${convention} for this identifier`
606
+ });
607
+ }
608
+ }
609
+ function checkVariableNaming(varInfo, file, issues, context) {
610
+ const { name, line, options } = varInfo;
611
+ const nameLower = name.toLowerCase();
612
+ if (isAcceptableInContext(name, context, options)) {
613
+ return;
614
+ }
615
+ if (name.length === 1 && !options.isLoopVariable && !options.isArrowParameter && !ACCEPTABLE_ABBREVIATIONS.has(nameLower)) {
616
+ const severity = adjustSeverity(Severity2.Minor, context, "poor-naming");
617
+ issues.push({
618
+ file,
619
+ line,
620
+ type: "poor-naming",
621
+ identifier: name,
622
+ severity,
623
+ suggestion: "Use a more descriptive name than a single letter"
624
+ });
625
+ }
626
+ if (VAGUE_NAMES.has(nameLower)) {
627
+ const severity = adjustSeverity(Severity2.Minor, context, "poor-naming");
628
+ issues.push({
629
+ file,
630
+ line,
631
+ type: "poor-naming",
632
+ identifier: name,
633
+ severity,
634
+ suggestion: `Avoid vague names like '${name}'. What does this data represent?`
635
+ });
636
+ }
637
+ if (name.length > 1 && name.length <= 3 && !options.isLoopVariable && !ACCEPTABLE_ABBREVIATIONS.has(nameLower)) {
638
+ const severity = adjustSeverity(Severity2.Info, context, "abbreviation");
639
+ issues.push({
640
+ file,
641
+ line,
642
+ type: "abbreviation",
643
+ identifier: name,
644
+ severity,
645
+ suggestion: "Avoid non-standard abbreviations"
646
+ });
647
+ }
648
+ }
649
+ var ScopeTracker = class {
650
+ constructor() {
651
+ this.variables = [];
652
+ }
653
+ declareVariable(name, node, line, options = {}) {
654
+ this.variables.push({ name, node, line, options });
655
+ }
656
+ getVariables() {
657
+ return this.variables;
658
+ }
659
+ };
660
+ function extractDestructuredIdentifiers(node, scopeTracker, options = {}) {
661
+ const { isParameter = false, isArrowParameter = false } = options;
662
+ if (node.type === "ObjectPattern") {
663
+ node.properties.forEach((prop) => {
664
+ if (prop.type === "Property" && prop.value.type === "Identifier") {
665
+ scopeTracker.declareVariable(
666
+ prop.value.name,
667
+ prop.value,
668
+ getLineNumber(prop.value),
669
+ {
670
+ isParameter,
671
+ isDestructured: true,
672
+ isArrowParameter
673
+ }
674
+ );
675
+ }
676
+ });
677
+ } else if (node.type === "ArrayPattern") {
678
+ for (const element of node.elements) {
679
+ if (element?.type === "Identifier") {
680
+ scopeTracker.declareVariable(
681
+ element.name,
682
+ element,
683
+ getLineNumber(element),
684
+ {
685
+ isParameter,
686
+ isDestructured: true,
687
+ isArrowParameter
688
+ }
689
+ );
690
+ }
691
+ }
692
+ }
693
+ }
694
+
695
+ // src/analyzers/patterns.ts
696
+ import { readFileSync as readFileSync2 } from "fs";
697
+ import { Severity as Severity3 } from "@aiready/core";
698
+ async function analyzePatterns(filePaths) {
699
+ const issues = [];
700
+ const contents = /* @__PURE__ */ new Map();
701
+ const tryCatchPattern = /try\s*\{/g;
702
+ const styleStats = {
703
+ tryCatch: 0,
704
+ thenCatch: 0,
705
+ asyncAwait: 0,
706
+ commonJs: 0,
707
+ esm: 0
708
+ };
709
+ for (const filePath of filePaths) {
710
+ try {
711
+ const content = readFileSync2(filePath, "utf-8");
712
+ contents.set(filePath, content);
713
+ if (content.match(tryCatchPattern)) styleStats.tryCatch++;
714
+ if (content.match(/\.catch\s*\(/)) styleStats.thenCatch++;
715
+ if (content.match(/\bawait\b/)) styleStats.asyncAwait++;
716
+ if (content.match(/\brequire\s*\(/)) styleStats.commonJs++;
717
+ if (content.match(/\bimport\b.*\bfrom\b/)) styleStats.esm++;
718
+ } catch (err) {
719
+ void err;
720
+ }
721
+ }
722
+ if (styleStats.tryCatch > 0 && styleStats.thenCatch > 0) {
723
+ const dominant = styleStats.tryCatch >= styleStats.thenCatch ? "try-catch" : ".catch()";
724
+ const minority = dominant === "try-catch" ? ".catch()" : "try-catch";
725
+ issues.push({
726
+ files: filePaths.filter((f) => {
727
+ const c = contents.get(f) || "";
728
+ return minority === "try-catch" ? c.match(tryCatchPattern) : c.match(/\.catch\s*\(/);
729
+ }),
730
+ type: "pattern-inconsistency",
731
+ description: `Mixed error handling styles: codebase primarily uses ${dominant}, but found ${minority} in some files.`,
732
+ examples: [dominant, minority],
733
+ severity: Severity3.Minor
734
+ });
735
+ }
736
+ if (styleStats.commonJs > 0 && styleStats.esm > 0) {
737
+ const minority = styleStats.esm >= styleStats.commonJs ? "CommonJS (require)" : "ESM (import)";
738
+ issues.push({
739
+ files: filePaths.filter((f) => {
740
+ const c = contents.get(f) || "";
741
+ return minority === "CommonJS (require)" ? c.match(/\brequire\s*\(/) : c.match(/\bimport\b/);
742
+ }),
743
+ type: "pattern-inconsistency",
744
+ description: `Mixed module systems: found both ESM and CommonJS.`,
745
+ examples: ['import X from "y"', 'const X = require("y")'],
746
+ severity: Severity3.Major
747
+ });
748
+ }
749
+ return issues;
750
+ }
751
+
752
+ // src/scoring.ts
753
+ import { calculateProductivityImpact, ToolName } from "@aiready/core";
754
+ function calculateConsistencyScore(issues, totalFilesAnalyzed, costConfig) {
755
+ void costConfig;
756
+ const criticalIssues = issues.filter((i) => i.severity === "critical").length;
757
+ const majorIssues = issues.filter((i) => i.severity === "major").length;
758
+ const minorIssues = issues.filter((i) => i.severity === "minor").length;
759
+ const totalIssues = issues.length;
760
+ const issuesPerFile = totalFilesAnalyzed > 0 ? totalIssues / totalFilesAnalyzed : 0;
761
+ const densityPenalty = Math.min(50, issuesPerFile * 15);
762
+ const weightedCount = criticalIssues * 10 + majorIssues * 3 + minorIssues * 0.5;
763
+ const avgWeightedIssuesPerFile = totalFilesAnalyzed > 0 ? weightedCount / totalFilesAnalyzed : 0;
764
+ const severityPenalty = Math.min(50, avgWeightedIssuesPerFile * 2);
765
+ const rawScore = 100 - densityPenalty - severityPenalty;
766
+ const score = Math.max(0, Math.min(100, Math.round(rawScore)));
767
+ const factors = [
768
+ {
769
+ name: "Issue Density",
770
+ impact: -Math.round(densityPenalty),
771
+ description: `${issuesPerFile.toFixed(2)} issues per file ${issuesPerFile < 1 ? "(excellent)" : issuesPerFile < 3 ? "(acceptable)" : "(high)"}`
772
+ }
773
+ ];
774
+ if (criticalIssues > 0) {
775
+ const criticalImpact = Math.min(30, criticalIssues * 10);
776
+ factors.push({
777
+ name: "Critical Issues",
778
+ impact: -criticalImpact,
779
+ description: `${criticalIssues} critical consistency issue${criticalIssues > 1 ? "s" : ""} (high AI confusion risk)`
780
+ });
781
+ }
782
+ if (majorIssues > 0) {
783
+ const majorImpact = Math.min(20, Math.round(majorIssues * 3));
784
+ factors.push({
785
+ name: "Major Issues",
786
+ impact: -majorImpact,
787
+ description: `${majorIssues} major issue${majorIssues > 1 ? "s" : ""} (moderate AI confusion risk)`
788
+ });
789
+ }
790
+ if (minorIssues > 0 && minorIssues >= totalFilesAnalyzed) {
791
+ const minorImpact = -Math.round(minorIssues * 0.5);
792
+ factors.push({
793
+ name: "Minor Issues",
794
+ impact: minorImpact,
795
+ description: `${minorIssues} minor issue${minorIssues > 1 ? "s" : ""} (slight AI confusion risk)`
796
+ });
797
+ }
798
+ const recommendations = [];
799
+ if (criticalIssues > 0) {
800
+ const estimatedImpact = Math.min(30, criticalIssues * 10);
801
+ recommendations.push({
802
+ action: "Fix critical naming/pattern inconsistencies (highest AI confusion risk)",
803
+ estimatedImpact,
804
+ priority: "high"
805
+ });
806
+ }
807
+ if (majorIssues > 5) {
808
+ const estimatedImpact = Math.min(15, Math.round(majorIssues / 2));
809
+ recommendations.push({
810
+ action: "Standardize naming conventions across codebase",
811
+ estimatedImpact,
812
+ priority: "medium"
813
+ });
814
+ }
815
+ if (issuesPerFile > 3) {
816
+ recommendations.push({
817
+ action: "Establish and enforce coding style guide to reduce inconsistencies",
818
+ estimatedImpact: 12,
819
+ priority: "medium"
820
+ });
821
+ }
822
+ if (totalIssues > 20 && minorIssues / totalIssues > 0.7) {
823
+ recommendations.push({
824
+ action: "Enable linter/formatter to automatically fix minor style issues",
825
+ estimatedImpact: 8,
826
+ priority: "low"
827
+ });
828
+ }
829
+ const productivityImpact = calculateProductivityImpact(issues);
830
+ return {
831
+ toolName: ToolName.NamingConsistency,
832
+ score,
833
+ rawMetrics: {
834
+ totalIssues,
835
+ criticalIssues,
836
+ majorIssues,
837
+ minorIssues,
838
+ issuesPerFile: Math.round(issuesPerFile * 100) / 100,
839
+ avgWeightedIssuesPerFile: Math.round(avgWeightedIssuesPerFile * 100) / 100,
840
+ // Business value metrics
841
+ estimatedDeveloperHours: productivityImpact.totalHours
842
+ },
843
+ factors,
844
+ recommendations
845
+ };
846
+ }
847
+
848
+ // src/analyzer.ts
849
+ import {
850
+ scanFiles,
851
+ Severity as Severity5,
852
+ IssueType,
853
+ getSeverityLevel
854
+ } from "@aiready/core";
855
+
856
+ // src/analyzers/naming-generalized.ts
857
+ import { getParser, Severity as Severity4 } from "@aiready/core";
858
+ import { readFileSync as readFileSync3 } from "fs";
859
+ var COMMON_ABBREVIATIONS = /* @__PURE__ */ new Set([
860
+ "id",
861
+ "db",
862
+ "fs",
863
+ "os",
864
+ "ip",
865
+ "ui",
866
+ "ux",
867
+ "api",
868
+ "env",
869
+ "url",
870
+ "req",
871
+ "res",
872
+ "err",
873
+ "ctx",
874
+ "cb",
875
+ "idx",
876
+ "src",
877
+ "dir",
878
+ "app",
879
+ "dev",
880
+ "qa",
881
+ "dto",
882
+ "dao",
883
+ "ref",
884
+ "ast",
885
+ "dom",
886
+ "log",
887
+ "msg",
888
+ "pkg",
889
+ "css",
890
+ "html",
891
+ "xml",
892
+ "jsx",
893
+ "tsx",
894
+ "ts",
895
+ "js"
896
+ ]);
897
+ async function analyzeNamingGeneralized(files) {
898
+ const issues = [];
899
+ for (const file of files) {
900
+ const parser = await getParser(file);
901
+ if (!parser) continue;
902
+ try {
903
+ const code = readFileSync3(file, "utf-8");
904
+ if (!code.trim()) continue;
905
+ await parser.initialize();
906
+ const result = parser.parse(code, file);
907
+ const conventions = parser.getNamingConventions();
908
+ const exceptions = new Set(conventions.exceptions || []);
909
+ for (const exp of result.exports) {
910
+ if (!exp.name || exp.name === "default") continue;
911
+ if (exceptions.has(exp.name)) continue;
912
+ if (COMMON_ABBREVIATIONS.has(exp.name.toLowerCase())) continue;
913
+ let pattern;
914
+ if (exp.type === "class") {
915
+ pattern = conventions.classPattern;
916
+ } else if (exp.type === "interface" && conventions.interfacePattern) {
917
+ pattern = conventions.interfacePattern;
918
+ } else if (exp.type === "type" && conventions.typePattern) {
919
+ pattern = conventions.typePattern;
920
+ } else if (exp.type === "function") {
921
+ if (/^[A-Z][a-zA-Z0-9]*$/.test(exp.name) || /^[A-Z][A-Z0-9_]*$/.test(exp.name)) {
922
+ continue;
923
+ }
924
+ pattern = conventions.functionPattern;
925
+ } else if (exp.type === "const") {
926
+ if ([
927
+ "handler",
928
+ "GET",
929
+ "POST",
930
+ "PUT",
931
+ "DELETE",
932
+ "PATCH",
933
+ "OPTIONS",
934
+ "HEAD"
935
+ ].includes(exp.name))
936
+ continue;
937
+ if (conventions.constantPattern.test(exp.name) || conventions.variablePattern.test(exp.name)) {
938
+ continue;
939
+ }
940
+ pattern = conventions.constantPattern;
941
+ } else {
942
+ pattern = conventions.variablePattern;
943
+ }
944
+ if (pattern && !pattern.test(exp.name)) {
945
+ issues.push({
946
+ type: "naming-inconsistency",
947
+ identifier: exp.name,
948
+ file,
949
+ line: exp.loc?.start.line || 1,
950
+ column: exp.loc?.start.column || 0,
951
+ // Recalibrate naming issues to Minor to differentiate from structural/architectural issues
952
+ severity: Severity4.Minor,
953
+ category: "naming",
954
+ suggestion: `Follow ${parser.language} ${exp.type} naming convention: ${pattern.toString()}`
955
+ });
956
+ }
957
+ }
958
+ for (const imp of result.imports) {
959
+ for (const spec of imp.specifiers) {
960
+ if (!spec || spec === "*" || spec === "default") continue;
961
+ if (exceptions.has(spec)) continue;
962
+ if (COMMON_ABBREVIATIONS.has(spec.toLowerCase())) continue;
963
+ if (spec.includes(".")) continue;
964
+ if (!conventions.variablePattern.test(spec) && !conventions.classPattern.test(spec) && (!conventions.constantPattern || !conventions.constantPattern.test(spec)) && (!conventions.typePattern || !conventions.typePattern.test(spec)) && (!conventions.interfacePattern || !conventions.interfacePattern.test(spec)) && !/^[A-Z][A-Z0-9_]*$/.test(spec)) {
965
+ issues.push({
966
+ type: "naming-inconsistency",
967
+ identifier: spec,
968
+ file,
969
+ line: imp.loc?.start.line || 1,
970
+ column: imp.loc?.start.column || 0,
971
+ severity: Severity4.Info,
972
+ // Reduced from Minor to Info for imports
973
+ category: "naming",
974
+ suggestion: `Imported identifier '${spec}' may not follow standard conventions for this language.`
975
+ });
976
+ }
977
+ }
978
+ }
979
+ } catch (error) {
980
+ const errorMessage = error instanceof Error ? error.message : String(error);
981
+ console.debug(
982
+ `Consistency: Skipping unparseable file ${file}: ${errorMessage.split("\\n")[0]}`
983
+ );
984
+ }
985
+ }
986
+ return issues;
987
+ }
988
+
989
+ // src/analyzer.ts
990
+ async function analyzeConsistency(options) {
991
+ const {
992
+ checkNaming = true,
993
+ checkPatterns = true,
994
+ checkArchitecture = false,
995
+ // Not implemented yet
996
+ minSeverity = Severity5.Info,
997
+ ...scanOptions
998
+ } = options;
999
+ void checkArchitecture;
1000
+ const filePaths = await scanFiles(scanOptions);
1001
+ let namingIssues = [];
1002
+ if (checkNaming) {
1003
+ namingIssues = await analyzeNamingGeneralized(filePaths);
1004
+ const tsJsFiles = filePaths.filter((f) => /\.(ts|tsx|js|jsx)$/i.test(f));
1005
+ if (tsJsFiles.length > 0) {
1006
+ const deepTsIssues = await analyzeNamingAST(tsJsFiles);
1007
+ namingIssues = [...namingIssues, ...deepTsIssues];
1008
+ }
1009
+ }
1010
+ const patternIssues = checkPatterns ? await analyzePatterns(filePaths) : [];
1011
+ const results = [];
1012
+ const fileIssuesMap = /* @__PURE__ */ new Map();
1013
+ for (const issue of namingIssues) {
1014
+ if (!shouldIncludeSeverity(issue.severity, minSeverity)) continue;
1015
+ const fileName = issue.fileName || issue.file || issue.filePath || "unknown";
1016
+ if (!fileIssuesMap.has(fileName)) fileIssuesMap.set(fileName, []);
1017
+ fileIssuesMap.get(fileName).push(issue);
1018
+ }
1019
+ for (const issue of patternIssues) {
1020
+ if (!shouldIncludeSeverity(issue.severity, minSeverity)) continue;
1021
+ const anyIssue = issue;
1022
+ const fileName = anyIssue.fileName || anyIssue.file || anyIssue.filePath || (Array.isArray(issue.files) ? issue.files[0] : "unknown");
1023
+ if (!fileIssuesMap.has(fileName)) fileIssuesMap.set(fileName, []);
1024
+ fileIssuesMap.get(fileName).push(issue);
1025
+ }
1026
+ for (const [fileName, issues] of fileIssuesMap.entries()) {
1027
+ const scoreResult = calculateConsistencyScore(
1028
+ issues,
1029
+ filePaths.length
1030
+ );
1031
+ results.push({
1032
+ fileName,
1033
+ issues: issues.map((i) => transformToIssue(i)),
1034
+ metrics: {
1035
+ consistencyScore: scoreResult.score / 100
1036
+ }
1037
+ });
1038
+ }
1039
+ const recommendations = [];
1040
+ if (namingIssues.length > 0) {
1041
+ recommendations.push("Standardize naming conventions across the codebase");
1042
+ }
1043
+ if (patternIssues.length > 0) {
1044
+ recommendations.push("Consolidate repetitive implementation patterns");
1045
+ }
1046
+ if (results.some((r) => (r.metrics?.consistencyScore ?? 1) < 0.8)) {
1047
+ recommendations.push(
1048
+ "Improve cross-module consistency to reduce AI confusion"
1049
+ );
1050
+ }
1051
+ return {
1052
+ results,
1053
+ summary: {
1054
+ filesAnalyzed: filePaths.length,
1055
+ totalIssues: results.reduce((acc, r) => acc + r.issues.length, 0),
1056
+ namingIssues: namingIssues.length,
1057
+ patternIssues: patternIssues.length,
1058
+ architectureIssues: 0
1059
+ },
1060
+ recommendations,
1061
+ metadata: {
1062
+ toolName: "naming-consistency",
1063
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
1064
+ }
1065
+ };
1066
+ }
1067
+ function shouldIncludeSeverity(severity, minSeverity) {
1068
+ return getSeverityLevel(severity) >= getSeverityLevel(minSeverity);
1069
+ }
1070
+ function getIssueType(type) {
1071
+ if (!type) return IssueType.NamingInconsistency;
1072
+ const typeMap = {
1073
+ "naming-inconsistency": IssueType.NamingInconsistency,
1074
+ "naming-quality": IssueType.NamingQuality,
1075
+ "pattern-inconsistency": IssueType.PatternInconsistency,
1076
+ "architecture-inconsistency": IssueType.ArchitectureInconsistency,
1077
+ "error-handling": IssueType.PatternInconsistency,
1078
+ "async-style": IssueType.PatternInconsistency,
1079
+ "import-style": IssueType.PatternInconsistency,
1080
+ "api-design": IssueType.PatternInconsistency
1081
+ };
1082
+ return typeMap[type] || IssueType.NamingInconsistency;
1083
+ }
1084
+ function transformToIssue(i) {
1085
+ if (i.message && i.location) {
1086
+ return {
1087
+ type: getIssueType(i.type),
1088
+ severity: i.severity,
1089
+ message: i.message,
1090
+ location: i.location,
1091
+ suggestion: i.suggestion
1092
+ };
1093
+ }
1094
+ if (i.identifier || i.type) {
1095
+ const line = i.line || 1;
1096
+ const column = i.column || 1;
1097
+ return {
1098
+ type: getIssueType(i.type),
1099
+ severity: i.severity,
1100
+ message: i.suggestion ? `Naming issue: ${i.suggestion}` : `Naming issue for '${i.identifier || "unknown"}'`,
1101
+ location: {
1102
+ file: i.file || i.fileName || "",
1103
+ line,
1104
+ column,
1105
+ endLine: line,
1106
+ endColumn: column + (i.identifier?.length || 10)
1107
+ },
1108
+ suggestion: i.suggestion
1109
+ };
1110
+ }
1111
+ if (i.description || i.files) {
1112
+ const fileName = Array.isArray(i.files) ? i.files[0] : i.file || "";
1113
+ return {
1114
+ type: getIssueType(i.type),
1115
+ severity: i.severity,
1116
+ message: i.description || "Pattern inconsistency found",
1117
+ location: {
1118
+ file: fileName,
1119
+ line: 1,
1120
+ column: 1,
1121
+ endLine: 1,
1122
+ endColumn: 10
1123
+ },
1124
+ suggestion: i.examples?.[0]
1125
+ };
1126
+ }
1127
+ return {
1128
+ type: getIssueType(i.type),
1129
+ severity: i.severity,
1130
+ message: i.message || "Unknown issue",
1131
+ location: i.location || { file: "", line: 1, column: 1 },
1132
+ suggestion: i.suggestion
1133
+ };
1134
+ }
1135
+
1136
+ export {
1137
+ VAGUE_NAMES,
1138
+ ACCEPTABLE_ABBREVIATIONS,
1139
+ detectNamingConventions,
1140
+ analyzeNamingAST,
1141
+ analyzePatterns,
1142
+ calculateConsistencyScore,
1143
+ analyzeConsistency
1144
+ };