@eduardbar/drift 0.2.3 → 0.4.0

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.
package/dist/analyzer.js CHANGED
@@ -1,3 +1,5 @@
1
+ import * as fs from 'node:fs';
2
+ import * as path from 'node:path';
1
3
  import { Project, SyntaxKind, } from 'ts-morph';
2
4
  // Rules and their drift score weight
3
5
  const RULE_WEIGHTS = {
@@ -11,6 +13,21 @@ const RULE_WEIGHTS = {
11
13
  'catch-swallow': { severity: 'warning', weight: 10 },
12
14
  'magic-number': { severity: 'info', weight: 3 },
13
15
  'any-abuse': { severity: 'warning', weight: 8 },
16
+ // Phase 1: complexity detection
17
+ 'high-complexity': { severity: 'error', weight: 15 },
18
+ 'deep-nesting': { severity: 'warning', weight: 12 },
19
+ 'too-many-params': { severity: 'warning', weight: 8 },
20
+ 'high-coupling': { severity: 'warning', weight: 10 },
21
+ 'promise-style-mix': { severity: 'warning', weight: 7 },
22
+ // Phase 2: cross-file dead code
23
+ 'unused-export': { severity: 'warning', weight: 8 },
24
+ 'dead-file': { severity: 'warning', weight: 10 },
25
+ 'unused-dependency': { severity: 'warning', weight: 6 },
26
+ // Phase 3: architectural boundaries
27
+ 'circular-dependency': { severity: 'error', weight: 14 },
28
+ // Phase 3b/c: layer and module boundary enforcement (require drift.config.ts)
29
+ 'layer-violation': { severity: 'error', weight: 16 },
30
+ 'cross-boundary-import': { severity: 'warning', weight: 10 },
14
31
  };
15
32
  function hasIgnoreComment(file, line) {
16
33
  const lines = file.getFullText().split('\n');
@@ -38,6 +55,9 @@ function getSnippet(node, file) {
38
55
  function getFunctionLikeLines(node) {
39
56
  return node.getEndLineNumber() - node.getStartLineNumber();
40
57
  }
58
+ // ---------------------------------------------------------------------------
59
+ // Existing rules
60
+ // ---------------------------------------------------------------------------
41
61
  function detectLargeFile(file) {
42
62
  const lineCount = file.getEndLineNumber();
43
63
  if (lineCount > 300) {
@@ -211,6 +231,286 @@ function detectMissingReturnTypes(file) {
211
231
  }
212
232
  return issues;
213
233
  }
234
+ // ---------------------------------------------------------------------------
235
+ // Phase 1: complexity detection rules
236
+ // ---------------------------------------------------------------------------
237
+ /**
238
+ * Cyclomatic complexity: count decision points in a function.
239
+ * Each if/else if/ternary/?:/for/while/do/case/catch/&&/|| adds 1.
240
+ * Threshold: > 10 is considered high complexity.
241
+ */
242
+ function getCyclomaticComplexity(fn) {
243
+ let complexity = 1; // base path
244
+ const incrementKinds = [
245
+ SyntaxKind.IfStatement,
246
+ SyntaxKind.ForStatement,
247
+ SyntaxKind.ForInStatement,
248
+ SyntaxKind.ForOfStatement,
249
+ SyntaxKind.WhileStatement,
250
+ SyntaxKind.DoStatement,
251
+ SyntaxKind.CaseClause,
252
+ SyntaxKind.CatchClause,
253
+ SyntaxKind.ConditionalExpression, // ternary
254
+ SyntaxKind.AmpersandAmpersandToken,
255
+ SyntaxKind.BarBarToken,
256
+ SyntaxKind.QuestionQuestionToken, // ??
257
+ ];
258
+ for (const kind of incrementKinds) {
259
+ complexity += fn.getDescendantsOfKind(kind).length;
260
+ }
261
+ return complexity;
262
+ }
263
+ function detectHighComplexity(file) {
264
+ const issues = [];
265
+ const fns = [
266
+ ...file.getFunctions(),
267
+ ...file.getDescendantsOfKind(SyntaxKind.ArrowFunction),
268
+ ...file.getDescendantsOfKind(SyntaxKind.FunctionExpression),
269
+ ...file.getClasses().flatMap((c) => c.getMethods()),
270
+ ];
271
+ for (const fn of fns) {
272
+ const complexity = getCyclomaticComplexity(fn);
273
+ if (complexity > 10) {
274
+ const startLine = fn.getStartLineNumber();
275
+ if (hasIgnoreComment(file, startLine))
276
+ continue;
277
+ issues.push({
278
+ rule: 'high-complexity',
279
+ severity: 'error',
280
+ message: `Cyclomatic complexity is ${complexity} (threshold: 10). AI generates correct code, not simple code.`,
281
+ line: startLine,
282
+ column: fn.getStartLinePos(),
283
+ snippet: getSnippet(fn, file),
284
+ });
285
+ }
286
+ }
287
+ return issues;
288
+ }
289
+ /**
290
+ * Deep nesting: count the maximum nesting depth of control flow inside a function.
291
+ * Counts: if, for, while, do, try, switch.
292
+ * Threshold: > 3 levels.
293
+ */
294
+ function getMaxNestingDepth(fn) {
295
+ const nestingKinds = new Set([
296
+ SyntaxKind.IfStatement,
297
+ SyntaxKind.ForStatement,
298
+ SyntaxKind.ForInStatement,
299
+ SyntaxKind.ForOfStatement,
300
+ SyntaxKind.WhileStatement,
301
+ SyntaxKind.DoStatement,
302
+ SyntaxKind.TryStatement,
303
+ SyntaxKind.SwitchStatement,
304
+ ]);
305
+ let maxDepth = 0;
306
+ function walk(node, depth) {
307
+ if (nestingKinds.has(node.getKind())) {
308
+ depth++;
309
+ if (depth > maxDepth)
310
+ maxDepth = depth;
311
+ }
312
+ for (const child of node.getChildren()) {
313
+ walk(child, depth);
314
+ }
315
+ }
316
+ walk(fn, 0);
317
+ return maxDepth;
318
+ }
319
+ function detectDeepNesting(file) {
320
+ const issues = [];
321
+ const fns = [
322
+ ...file.getFunctions(),
323
+ ...file.getDescendantsOfKind(SyntaxKind.ArrowFunction),
324
+ ...file.getDescendantsOfKind(SyntaxKind.FunctionExpression),
325
+ ...file.getClasses().flatMap((c) => c.getMethods()),
326
+ ];
327
+ for (const fn of fns) {
328
+ const depth = getMaxNestingDepth(fn);
329
+ if (depth > 3) {
330
+ const startLine = fn.getStartLineNumber();
331
+ if (hasIgnoreComment(file, startLine))
332
+ continue;
333
+ issues.push({
334
+ rule: 'deep-nesting',
335
+ severity: 'warning',
336
+ message: `Maximum nesting depth is ${depth} (threshold: 3). Deep nesting is the #1 readability killer.`,
337
+ line: startLine,
338
+ column: fn.getStartLinePos(),
339
+ snippet: getSnippet(fn, file),
340
+ });
341
+ }
342
+ }
343
+ return issues;
344
+ }
345
+ /**
346
+ * Too many parameters: functions with more than 4 parameters.
347
+ * AI avoids refactoring parameters into objects/options bags.
348
+ */
349
+ function detectTooManyParams(file) {
350
+ const issues = [];
351
+ const fns = [
352
+ ...file.getFunctions(),
353
+ ...file.getDescendantsOfKind(SyntaxKind.ArrowFunction),
354
+ ...file.getDescendantsOfKind(SyntaxKind.FunctionExpression),
355
+ ...file.getClasses().flatMap((c) => c.getMethods()),
356
+ ];
357
+ for (const fn of fns) {
358
+ const paramCount = fn.getParameters().length;
359
+ if (paramCount > 4) {
360
+ const startLine = fn.getStartLineNumber();
361
+ if (hasIgnoreComment(file, startLine))
362
+ continue;
363
+ issues.push({
364
+ rule: 'too-many-params',
365
+ severity: 'warning',
366
+ message: `Function has ${paramCount} parameters (threshold: 4). AI avoids refactoring into options objects.`,
367
+ line: startLine,
368
+ column: fn.getStartLinePos(),
369
+ snippet: getSnippet(fn, file),
370
+ });
371
+ }
372
+ }
373
+ return issues;
374
+ }
375
+ /**
376
+ * High coupling: files with more than 10 distinct import sources.
377
+ * AI imports broadly without considering module cohesion.
378
+ */
379
+ function detectHighCoupling(file) {
380
+ const imports = file.getImportDeclarations();
381
+ const sources = new Set(imports.map((i) => i.getModuleSpecifierValue()));
382
+ if (sources.size > 10) {
383
+ return [
384
+ {
385
+ rule: 'high-coupling',
386
+ severity: 'warning',
387
+ message: `File imports from ${sources.size} distinct modules (threshold: 10). High coupling makes refactoring dangerous.`,
388
+ line: 1,
389
+ column: 1,
390
+ snippet: `// ${sources.size} import sources`,
391
+ },
392
+ ];
393
+ }
394
+ return [];
395
+ }
396
+ /**
397
+ * Promise style mix: async/await and .then()/.catch() used in the same file.
398
+ * AI generates both styles without consistency.
399
+ */
400
+ function detectPromiseStyleMix(file) {
401
+ const text = file.getFullText();
402
+ // detect .then( or .catch( calls (property access on a promise)
403
+ const hasThen = file.getDescendantsOfKind(SyntaxKind.PropertyAccessExpression).some((node) => {
404
+ const name = node.getName();
405
+ return name === 'then' || name === 'catch';
406
+ });
407
+ // detect async keyword usage
408
+ const hasAsync = file.getDescendantsOfKind(SyntaxKind.AsyncKeyword).length > 0 ||
409
+ /\bawait\b/.test(text);
410
+ if (hasThen && hasAsync) {
411
+ return [
412
+ {
413
+ rule: 'promise-style-mix',
414
+ severity: 'warning',
415
+ message: `File mixes async/await with .then()/.catch(). AI generates both styles without picking one.`,
416
+ line: 1,
417
+ column: 1,
418
+ snippet: `// mixed promise styles detected`,
419
+ },
420
+ ];
421
+ }
422
+ return [];
423
+ }
424
+ /**
425
+ * Magic numbers: numeric literals used directly in logic outside of named constants.
426
+ * Excludes 0, 1, -1 (universally understood) and array indices in obvious patterns.
427
+ */
428
+ function detectMagicNumbers(file) {
429
+ const issues = [];
430
+ const ALLOWED = new Set([0, 1, -1, 2, 100]);
431
+ for (const node of file.getDescendantsOfKind(SyntaxKind.NumericLiteral)) {
432
+ const value = Number(node.getLiteralValue());
433
+ if (ALLOWED.has(value))
434
+ continue;
435
+ // Skip: variable/const initializers at top level (those ARE the named constants)
436
+ const parent = node.getParent();
437
+ if (!parent)
438
+ continue;
439
+ const parentKind = parent.getKind();
440
+ if (parentKind === SyntaxKind.VariableDeclaration ||
441
+ parentKind === SyntaxKind.PropertyAssignment ||
442
+ parentKind === SyntaxKind.EnumMember ||
443
+ parentKind === SyntaxKind.Parameter)
444
+ continue;
445
+ const line = node.getStartLineNumber();
446
+ if (hasIgnoreComment(file, line))
447
+ continue;
448
+ issues.push({
449
+ rule: 'magic-number',
450
+ severity: 'info',
451
+ message: `Magic number ${value} used directly in logic. Extract to a named constant.`,
452
+ line,
453
+ column: node.getStartLinePos(),
454
+ snippet: getSnippet(node, file),
455
+ });
456
+ }
457
+ return issues;
458
+ }
459
+ /**
460
+ * Comment contradiction: comments that restate exactly what the code does.
461
+ * Classic AI pattern — documents the obvious instead of the why.
462
+ * Detects: "// increment counter" above counter++, "// return x" above return x, etc.
463
+ */
464
+ function detectCommentContradiction(file) {
465
+ const issues = [];
466
+ const lines = file.getFullText().split('\n');
467
+ // Patterns: comment that is a near-literal restatement of the next line
468
+ const trivialCommentPatterns = [
469
+ // "// return ..." above a return statement
470
+ { comment: /\/\/\s*return\b/i, code: /^\s*return\b/ },
471
+ // "// increment ..." or "// increase ..." above x++ or x += 1
472
+ { comment: /\/\/\s*(increment|increase|add\s+1|plus\s+1)\b/i, code: /\+\+|(\+= ?1)\b/ },
473
+ // "// decrement ..." above x-- or x -= 1
474
+ { comment: /\/\/\s*(decrement|decrease|subtract\s+1|minus\s+1)\b/i, code: /--|(-= ?1)\b/ },
475
+ // "// log ..." above console.log
476
+ { comment: /\/\/\s*log\b/i, code: /console\.(log|warn|error)/ },
477
+ // "// set ... to ..." or "// assign ..." above assignment
478
+ { comment: /\/\/\s*(set|assign)\b/i, code: /^\s*\w[\w.[\]]*\s*=(?!=)/ },
479
+ // "// call ..." above a function call
480
+ { comment: /\/\/\s*call\b/i, code: /^\s*\w[\w.]*\(/ },
481
+ // "// declare ..." or "// define ..." or "// create ..." above const/let/var
482
+ { comment: /\/\/\s*(declare|define|create|initialize)\b/i, code: /^\s*(const|let|var)\b/ },
483
+ // "// check if ..." above an if statement
484
+ { comment: /\/\/\s*check\s+if\b/i, code: /^\s*if\s*\(/ },
485
+ // "// loop ..." or "// iterate ..." above for/while
486
+ { comment: /\/\/\s*(loop|iterate|for each|foreach)\b/i, code: /^\s*(for|while)\b/ },
487
+ // "// import ..." above an import
488
+ { comment: /\/\/\s*import\b/i, code: /^\s*import\b/ },
489
+ ];
490
+ for (let i = 0; i < lines.length - 1; i++) {
491
+ const commentLine = lines[i].trim();
492
+ const nextLine = lines[i + 1];
493
+ for (const { comment, code } of trivialCommentPatterns) {
494
+ if (comment.test(commentLine) && code.test(nextLine)) {
495
+ if (hasIgnoreComment(file, i + 1))
496
+ continue;
497
+ issues.push({
498
+ rule: 'comment-contradiction',
499
+ severity: 'warning',
500
+ message: `Comment restates what the code already says. AI documents the obvious instead of the why.`,
501
+ line: i + 1,
502
+ column: 1,
503
+ snippet: `${commentLine.slice(0, 60)}\n${nextLine.trim().slice(0, 60)}`,
504
+ });
505
+ break; // one issue per comment line max
506
+ }
507
+ }
508
+ }
509
+ return issues;
510
+ }
511
+ // ---------------------------------------------------------------------------
512
+ // Score
513
+ // ---------------------------------------------------------------------------
214
514
  function calculateScore(issues) {
215
515
  let raw = 0;
216
516
  for (const issue of issues) {
@@ -218,6 +518,9 @@ function calculateScore(issues) {
218
518
  }
219
519
  return Math.min(100, raw);
220
520
  }
521
+ // ---------------------------------------------------------------------------
522
+ // Public API
523
+ // ---------------------------------------------------------------------------
221
524
  export function analyzeFile(file) {
222
525
  if (isFileIgnored(file)) {
223
526
  return {
@@ -235,6 +538,15 @@ export function analyzeFile(file) {
235
538
  ...detectAnyAbuse(file),
236
539
  ...detectCatchSwallow(file),
237
540
  ...detectMissingReturnTypes(file),
541
+ // Phase 1: complexity
542
+ ...detectHighComplexity(file),
543
+ ...detectDeepNesting(file),
544
+ ...detectTooManyParams(file),
545
+ ...detectHighCoupling(file),
546
+ ...detectPromiseStyleMix(file),
547
+ // Stubs now implemented
548
+ ...detectMagicNumbers(file),
549
+ ...detectCommentContradiction(file),
238
550
  ];
239
551
  return {
240
552
  path: file.getFilePath(),
@@ -242,7 +554,7 @@ export function analyzeFile(file) {
242
554
  score: calculateScore(issues),
243
555
  };
244
556
  }
245
- export function analyzeProject(targetPath) {
557
+ export function analyzeProject(targetPath, config) {
246
558
  const project = new Project({
247
559
  skipAddingFilesFromTsConfig: true,
248
560
  compilerOptions: { allowJs: true },
@@ -260,6 +572,322 @@ export function analyzeProject(targetPath) {
260
572
  `!${targetPath}/**/*.test.*`,
261
573
  `!${targetPath}/**/*.spec.*`,
262
574
  ]);
263
- return project.getSourceFiles().map(analyzeFile);
575
+ const sourceFiles = project.getSourceFiles();
576
+ // Phase 1: per-file analysis
577
+ const reports = sourceFiles.map(analyzeFile);
578
+ const reportByPath = new Map();
579
+ for (const r of reports)
580
+ reportByPath.set(r.path, r);
581
+ // Phase 2: cross-file analysis — build import graph first
582
+ const allImportedPaths = new Set(); // absolute paths of files that are imported
583
+ const allImportedNames = new Map(); // file path → set of imported names
584
+ const allLiteralImports = new Set(); // raw module specifiers (for unused-dependency)
585
+ const importGraph = new Map(); // Phase 3: filePath → Set of imported filePaths
586
+ for (const sf of sourceFiles) {
587
+ const sfPath = sf.getFilePath();
588
+ for (const decl of sf.getImportDeclarations()) {
589
+ const moduleSpecifier = decl.getModuleSpecifierValue();
590
+ allLiteralImports.add(moduleSpecifier);
591
+ // Resolve to absolute path for dead-file / unused-export
592
+ const resolved = decl.getModuleSpecifierSourceFile();
593
+ if (resolved) {
594
+ const resolvedPath = resolved.getFilePath();
595
+ allImportedPaths.add(resolvedPath);
596
+ // Phase 3: populate directed import graph
597
+ if (!importGraph.has(sfPath))
598
+ importGraph.set(sfPath, new Set());
599
+ importGraph.get(sfPath).add(resolvedPath);
600
+ // Collect named imports { A, B } and default imports
601
+ const named = decl.getNamedImports().map(n => n.getName());
602
+ const def = decl.getDefaultImport()?.getText();
603
+ const ns = decl.getNamespaceImport()?.getText();
604
+ if (!allImportedNames.has(resolvedPath)) {
605
+ allImportedNames.set(resolvedPath, new Set());
606
+ }
607
+ const nameSet = allImportedNames.get(resolvedPath);
608
+ for (const n of named)
609
+ nameSet.add(n);
610
+ if (def)
611
+ nameSet.add('default');
612
+ if (ns)
613
+ nameSet.add('*'); // namespace import — counts all exports as used
614
+ }
615
+ }
616
+ // Also register re-exports: export { X, Y } from './module'
617
+ // These count as "using" X and Y from the source module
618
+ for (const exportDecl of sf.getExportDeclarations()) {
619
+ const reExportedModule = exportDecl.getModuleSpecifierSourceFile();
620
+ if (!reExportedModule)
621
+ continue;
622
+ const reExportedPath = reExportedModule.getFilePath();
623
+ allImportedPaths.add(reExportedPath);
624
+ if (!allImportedNames.has(reExportedPath)) {
625
+ allImportedNames.set(reExportedPath, new Set());
626
+ }
627
+ const nameSet = allImportedNames.get(reExportedPath);
628
+ const namedExports = exportDecl.getNamedExports();
629
+ if (namedExports.length === 0) {
630
+ // export * from './module' — namespace re-export, all names used
631
+ nameSet.add('*');
632
+ }
633
+ else {
634
+ for (const ne of namedExports)
635
+ nameSet.add(ne.getName());
636
+ }
637
+ }
638
+ }
639
+ // Detect unused-export and dead-file per source file
640
+ for (const sf of sourceFiles) {
641
+ const sfPath = sf.getFilePath();
642
+ const report = reportByPath.get(sfPath);
643
+ if (!report)
644
+ continue;
645
+ // dead-file: file is never imported by anyone
646
+ // Exclude entry-point candidates: index.ts, main.ts, cli.ts, app.ts, bin files
647
+ const basename = path.basename(sfPath);
648
+ const isBinFile = sfPath.replace(/\\/g, '/').includes('/bin/');
649
+ const isEntryPoint = /^(index|main|cli|app)\.(ts|tsx|js|jsx)$/.test(basename) || isBinFile;
650
+ if (!isEntryPoint && !allImportedPaths.has(sfPath)) {
651
+ const issue = {
652
+ rule: 'dead-file',
653
+ severity: RULE_WEIGHTS['dead-file'].severity,
654
+ message: 'File is never imported — may be dead code',
655
+ line: 1,
656
+ column: 1,
657
+ snippet: basename,
658
+ };
659
+ report.issues.push(issue);
660
+ report.score = calculateScore(report.issues);
661
+ }
662
+ // unused-export: named exports not imported anywhere
663
+ // Skip barrel files (index.ts) — their entire surface is the public API
664
+ const isBarrel = /^index\.(ts|tsx|js|jsx)$/.test(basename);
665
+ const importedNamesForFile = allImportedNames.get(sfPath);
666
+ const hasNamespaceImport = importedNamesForFile?.has('*') ?? false;
667
+ if (!isBarrel && !hasNamespaceImport) {
668
+ for (const exportDecl of sf.getExportDeclarations()) {
669
+ for (const namedExport of exportDecl.getNamedExports()) {
670
+ const name = namedExport.getName();
671
+ if (!importedNamesForFile?.has(name)) {
672
+ const line = namedExport.getStartLineNumber();
673
+ const issue = {
674
+ rule: 'unused-export',
675
+ severity: RULE_WEIGHTS['unused-export'].severity,
676
+ message: `'${name}' is exported but never imported`,
677
+ line,
678
+ column: 1,
679
+ snippet: namedExport.getText().slice(0, 80),
680
+ };
681
+ report.issues.push(issue);
682
+ report.score = calculateScore(report.issues);
683
+ }
684
+ }
685
+ }
686
+ // Also check inline export declarations (export function foo, export const bar)
687
+ for (const exportSymbol of sf.getExportedDeclarations()) {
688
+ const [exportName, declarations] = [exportSymbol[0], exportSymbol[1]];
689
+ if (exportName === 'default')
690
+ continue;
691
+ if (importedNamesForFile?.has(exportName))
692
+ continue;
693
+ for (const decl of declarations) {
694
+ // Skip if this is a re-export from another file
695
+ if (decl.getSourceFile().getFilePath() !== sfPath)
696
+ continue;
697
+ const line = decl.getStartLineNumber();
698
+ const issue = {
699
+ rule: 'unused-export',
700
+ severity: RULE_WEIGHTS['unused-export'].severity,
701
+ message: `'${exportName}' is exported but never imported`,
702
+ line,
703
+ column: 1,
704
+ snippet: decl.getText().split('\n')[0].slice(0, 80),
705
+ };
706
+ report.issues.push(issue);
707
+ report.score = calculateScore(report.issues);
708
+ break; // one issue per export name is enough
709
+ }
710
+ }
711
+ }
712
+ }
713
+ // Detect unused-dependency: packages in package.json never imported
714
+ const pkgPath = path.join(targetPath, 'package.json');
715
+ if (fs.existsSync(pkgPath)) {
716
+ let pkg;
717
+ try {
718
+ pkg = JSON.parse(fs.readFileSync(pkgPath, 'utf-8'));
719
+ }
720
+ catch {
721
+ pkg = {};
722
+ }
723
+ const deps = {
724
+ ...(pkg.dependencies ?? {}),
725
+ };
726
+ const unusedDeps = [];
727
+ for (const depName of Object.keys(deps)) {
728
+ // Skip type-only packages (@types/*)
729
+ if (depName.startsWith('@types/'))
730
+ continue;
731
+ // A dependency is "used" if any import specifier starts with the package name
732
+ // (handles sub-paths like 'lodash/merge', 'date-fns/format', etc.)
733
+ const isUsed = [...allLiteralImports].some(imp => imp === depName || imp.startsWith(depName + '/'));
734
+ if (!isUsed)
735
+ unusedDeps.push(depName);
736
+ }
737
+ if (unusedDeps.length > 0) {
738
+ const pkgIssues = unusedDeps.map(dep => ({
739
+ rule: 'unused-dependency',
740
+ severity: RULE_WEIGHTS['unused-dependency'].severity,
741
+ message: `'${dep}' is in package.json but never imported`,
742
+ line: 1,
743
+ column: 1,
744
+ snippet: `"${dep}"`,
745
+ }));
746
+ reports.push({
747
+ path: pkgPath,
748
+ issues: pkgIssues,
749
+ score: calculateScore(pkgIssues),
750
+ });
751
+ }
752
+ }
753
+ // Phase 3: circular-dependency — DFS cycle detection
754
+ function findCycles(graph) {
755
+ const visited = new Set();
756
+ const inStack = new Set();
757
+ const cycles = [];
758
+ function dfs(node, stack) {
759
+ visited.add(node);
760
+ inStack.add(node);
761
+ stack.push(node);
762
+ for (const neighbor of graph.get(node) ?? []) {
763
+ if (!visited.has(neighbor)) {
764
+ dfs(neighbor, stack);
765
+ }
766
+ else if (inStack.has(neighbor)) {
767
+ // Found a cycle — extract the cycle portion from the stack
768
+ const cycleStart = stack.indexOf(neighbor);
769
+ cycles.push(stack.slice(cycleStart));
770
+ }
771
+ }
772
+ stack.pop();
773
+ inStack.delete(node);
774
+ }
775
+ for (const node of graph.keys()) {
776
+ if (!visited.has(node)) {
777
+ dfs(node, []);
778
+ }
779
+ }
780
+ return cycles;
781
+ }
782
+ const cycles = findCycles(importGraph);
783
+ // De-duplicate: each unique cycle (regardless of starting node) reported once per file
784
+ const reportedCycleKeys = new Set();
785
+ for (const cycle of cycles) {
786
+ const cycleKey = [...cycle].sort().join('|');
787
+ if (reportedCycleKeys.has(cycleKey))
788
+ continue;
789
+ reportedCycleKeys.add(cycleKey);
790
+ // Report on the first file in the cycle
791
+ const firstFile = cycle[0];
792
+ const report = reportByPath.get(firstFile);
793
+ if (!report)
794
+ continue;
795
+ const cycleDisplay = cycle
796
+ .map(p => path.basename(p))
797
+ .concat(path.basename(cycle[0])) // close the loop visually: A → B → C → A
798
+ .join(' → ');
799
+ const issue = {
800
+ rule: 'circular-dependency',
801
+ severity: RULE_WEIGHTS['circular-dependency'].severity,
802
+ message: `Circular dependency detected: ${cycleDisplay}`,
803
+ line: 1,
804
+ column: 1,
805
+ snippet: cycleDisplay,
806
+ };
807
+ report.issues.push(issue);
808
+ report.score = calculateScore(report.issues);
809
+ }
810
+ // ── Phase 3b: layer-violation ──────────────────────────────────────────
811
+ if (config?.layers && config.layers.length > 0) {
812
+ const { layers } = config;
813
+ function getLayer(filePath) {
814
+ const rel = filePath.replace(/\\/g, '/');
815
+ return layers.find(layer => layer.patterns.some(pattern => {
816
+ const regexStr = pattern
817
+ .replace(/\\/g, '/')
818
+ .replace(/[.+^${}()|[\]]/g, '\\$&')
819
+ .replace(/\*\*/g, '###DOUBLESTAR###')
820
+ .replace(/\*/g, '[^/]*')
821
+ .replace(/###DOUBLESTAR###/g, '.*');
822
+ return new RegExp(`^${regexStr}`).test(rel);
823
+ }));
824
+ }
825
+ for (const [filePath, imports] of importGraph.entries()) {
826
+ const fileLayer = getLayer(filePath);
827
+ if (!fileLayer)
828
+ continue;
829
+ for (const importedPath of imports) {
830
+ const importedLayer = getLayer(importedPath);
831
+ if (!importedLayer)
832
+ continue;
833
+ if (importedLayer.name === fileLayer.name)
834
+ continue;
835
+ if (!fileLayer.canImportFrom.includes(importedLayer.name)) {
836
+ const report = reportByPath.get(filePath);
837
+ if (report) {
838
+ const weight = RULE_WEIGHTS['layer-violation']?.weight ?? 5;
839
+ report.issues.push({
840
+ rule: 'layer-violation',
841
+ severity: 'error',
842
+ message: `Layer '${fileLayer.name}' must not import from layer '${importedLayer.name}'`,
843
+ line: 1,
844
+ column: 1,
845
+ snippet: `import from '${path.relative(targetPath, importedPath).replace(/\\/g, '/')}'`,
846
+ });
847
+ report.score = Math.min(100, report.score + weight);
848
+ }
849
+ }
850
+ }
851
+ }
852
+ }
853
+ // ── Phase 3c: cross-boundary-import ────────────────────────────────────
854
+ if (config?.modules && config.modules.length > 0) {
855
+ const { modules } = config;
856
+ function getModule(filePath) {
857
+ const rel = filePath.replace(/\\/g, '/');
858
+ return modules.find(m => rel.startsWith(m.root.replace(/\\/g, '/')));
859
+ }
860
+ for (const [filePath, imports] of importGraph.entries()) {
861
+ const fileModule = getModule(filePath);
862
+ if (!fileModule)
863
+ continue;
864
+ for (const importedPath of imports) {
865
+ const importedModule = getModule(importedPath);
866
+ if (!importedModule)
867
+ continue;
868
+ if (importedModule.name === fileModule.name)
869
+ continue;
870
+ const allowedImports = fileModule.allowedExternalImports ?? [];
871
+ const relImported = importedPath.replace(/\\/g, '/');
872
+ const isAllowed = allowedImports.some(allowed => relImported.startsWith(allowed.replace(/\\/g, '/')));
873
+ if (!isAllowed) {
874
+ const report = reportByPath.get(filePath);
875
+ if (report) {
876
+ const weight = RULE_WEIGHTS['cross-boundary-import']?.weight ?? 5;
877
+ report.issues.push({
878
+ rule: 'cross-boundary-import',
879
+ severity: 'warning',
880
+ message: `Module '${fileModule.name}' must not import from module '${importedModule.name}'`,
881
+ line: 1,
882
+ column: 1,
883
+ snippet: `import from '${path.relative(targetPath, importedPath).replace(/\\/g, '/')}'`,
884
+ });
885
+ report.score = Math.min(100, report.score + weight);
886
+ }
887
+ }
888
+ }
889
+ }
890
+ }
891
+ return reports;
264
892
  }
265
893
  //# sourceMappingURL=analyzer.js.map