@aiready/context-analyzer 0.22.4 → 0.22.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,1304 @@
1
+ import {
2
+ calculateImportDepthFromEdges,
3
+ detectGraphCycles,
4
+ getTransitiveDependenciesFromEdges
5
+ } from "./chunk-64U3PNO3.mjs";
6
+ import {
7
+ calculateEnhancedCohesion,
8
+ calculateFragmentation
9
+ } from "./chunk-EMYD7NS6.mjs";
10
+
11
+ // src/orchestrator.ts
12
+ import { scanFiles, readFileContent } from "@aiready/core";
13
+
14
+ // src/issue-analyzer.ts
15
+ import { Severity, isBuildArtifact } from "@aiready/core";
16
+ function analyzeIssues(params) {
17
+ const {
18
+ file,
19
+ importDepth,
20
+ contextBudget,
21
+ cohesionScore,
22
+ fragmentationScore,
23
+ maxDepth,
24
+ maxContextBudget,
25
+ minCohesion,
26
+ maxFragmentation,
27
+ circularDeps
28
+ } = params;
29
+ const issues = [];
30
+ const recommendations = [];
31
+ let severity = Severity.Info;
32
+ let potentialSavings = 0;
33
+ if (circularDeps.length > 0) {
34
+ severity = Severity.Critical;
35
+ issues.push(`Part of ${circularDeps.length} circular dependency chain(s)`);
36
+ recommendations.push(
37
+ "Break circular dependencies by extracting interfaces or using dependency injection"
38
+ );
39
+ potentialSavings += contextBudget * 0.2;
40
+ }
41
+ if (importDepth > maxDepth * 1.5) {
42
+ severity = Severity.Critical;
43
+ issues.push(`Import depth ${importDepth} exceeds limit by 50%`);
44
+ recommendations.push("Flatten dependency tree or use facade pattern");
45
+ potentialSavings += contextBudget * 0.3;
46
+ } else if (importDepth > maxDepth) {
47
+ if (severity !== Severity.Critical) severity = Severity.Major;
48
+ issues.push(
49
+ `Import depth ${importDepth} exceeds recommended maximum ${maxDepth}`
50
+ );
51
+ recommendations.push("Consider reducing dependency depth");
52
+ potentialSavings += contextBudget * 0.15;
53
+ }
54
+ if (contextBudget > maxContextBudget * 1.5) {
55
+ severity = Severity.Critical;
56
+ issues.push(
57
+ `Context budget ${contextBudget.toLocaleString()} tokens is 50% over limit`
58
+ );
59
+ recommendations.push(
60
+ "Split into smaller modules or reduce dependency tree"
61
+ );
62
+ potentialSavings += contextBudget * 0.4;
63
+ } else if (contextBudget > maxContextBudget) {
64
+ if (severity !== Severity.Critical) severity = Severity.Major;
65
+ issues.push(
66
+ `Context budget ${contextBudget.toLocaleString()} exceeds ${maxContextBudget.toLocaleString()}`
67
+ );
68
+ recommendations.push("Reduce file size or dependencies");
69
+ potentialSavings += contextBudget * 0.2;
70
+ }
71
+ if (cohesionScore < minCohesion * 0.5) {
72
+ if (severity !== Severity.Critical) severity = Severity.Major;
73
+ issues.push(
74
+ `Very low cohesion (${(cohesionScore * 100).toFixed(0)}%) - mixed concerns`
75
+ );
76
+ recommendations.push(
77
+ "Split file by domain - separate unrelated functionality"
78
+ );
79
+ potentialSavings += contextBudget * 0.25;
80
+ } else if (cohesionScore < minCohesion) {
81
+ if (severity === Severity.Info) severity = Severity.Minor;
82
+ issues.push(`Low cohesion (${(cohesionScore * 100).toFixed(0)}%)`);
83
+ recommendations.push("Consider grouping related exports together");
84
+ potentialSavings += contextBudget * 0.1;
85
+ }
86
+ if (fragmentationScore > maxFragmentation) {
87
+ if (severity === Severity.Info || severity === Severity.Minor)
88
+ severity = Severity.Minor;
89
+ issues.push(
90
+ `High fragmentation (${(fragmentationScore * 100).toFixed(0)}%) - scattered implementation`
91
+ );
92
+ recommendations.push("Consolidate with related files in same domain");
93
+ potentialSavings += contextBudget * 0.3;
94
+ }
95
+ if (isBuildArtifact(file)) {
96
+ issues.push("Detected build artifact (bundled/output file)");
97
+ recommendations.push("Exclude build outputs from analysis");
98
+ severity = Severity.Info;
99
+ potentialSavings = 0;
100
+ }
101
+ return {
102
+ severity,
103
+ issues,
104
+ recommendations,
105
+ potentialSavings: Math.floor(potentialSavings)
106
+ };
107
+ }
108
+
109
+ // src/graph-builder.ts
110
+ import { estimateTokens, parseFileExports as parseFileExports2 } from "@aiready/core";
111
+
112
+ // src/utils/string-utils.ts
113
+ function singularize(word) {
114
+ const irregulars = {
115
+ people: "person",
116
+ children: "child",
117
+ men: "man",
118
+ women: "woman"
119
+ };
120
+ if (irregulars[word]) return irregulars[word];
121
+ if (word.endsWith("ies")) return word.slice(0, -3) + "y";
122
+ if (word.endsWith("ses")) return word.slice(0, -2);
123
+ if (word.endsWith("s") && word.length > 3) return word.slice(0, -1);
124
+ return word;
125
+ }
126
+
127
+ // src/semantic/co-usage.ts
128
+ function buildCoUsageMatrix(graph) {
129
+ const coUsageMatrix = /* @__PURE__ */ new Map();
130
+ for (const [, node] of graph.nodes) {
131
+ const imports = node.imports;
132
+ for (let i = 0; i < imports.length; i++) {
133
+ const fileA = imports[i];
134
+ if (!coUsageMatrix.has(fileA)) coUsageMatrix.set(fileA, /* @__PURE__ */ new Map());
135
+ for (let j = i + 1; j < imports.length; j++) {
136
+ const fileB = imports[j];
137
+ const fileAUsage = coUsageMatrix.get(fileA);
138
+ fileAUsage.set(fileB, (fileAUsage.get(fileB) || 0) + 1);
139
+ if (!coUsageMatrix.has(fileB)) coUsageMatrix.set(fileB, /* @__PURE__ */ new Map());
140
+ const fileBUsage = coUsageMatrix.get(fileB);
141
+ fileBUsage.set(fileA, (fileBUsage.get(fileA) || 0) + 1);
142
+ }
143
+ }
144
+ }
145
+ return coUsageMatrix;
146
+ }
147
+ function findSemanticClusters(coUsageMatrix, minCoUsage = 3) {
148
+ const clusters = /* @__PURE__ */ new Map();
149
+ const visited = /* @__PURE__ */ new Set();
150
+ for (const [file, coUsages] of coUsageMatrix) {
151
+ if (visited.has(file)) continue;
152
+ const cluster = [file];
153
+ visited.add(file);
154
+ for (const [relatedFile, count] of coUsages) {
155
+ if (count >= minCoUsage && !visited.has(relatedFile)) {
156
+ cluster.push(relatedFile);
157
+ visited.add(relatedFile);
158
+ }
159
+ }
160
+ if (cluster.length > 1) clusters.set(file, cluster);
161
+ }
162
+ return clusters;
163
+ }
164
+ function getCoUsageData(file, coUsageMatrix) {
165
+ return {
166
+ file,
167
+ coImportedWith: coUsageMatrix.get(file) || /* @__PURE__ */ new Map(),
168
+ sharedImporters: []
169
+ };
170
+ }
171
+
172
+ // src/semantic/type-graph.ts
173
+ function buildTypeGraph(graph) {
174
+ const typeGraph = /* @__PURE__ */ new Map();
175
+ for (const [file, node] of graph.nodes) {
176
+ for (const exp of node.exports) {
177
+ if (exp.typeReferences) {
178
+ for (const typeRef of exp.typeReferences) {
179
+ if (!typeGraph.has(typeRef)) typeGraph.set(typeRef, /* @__PURE__ */ new Set());
180
+ typeGraph.get(typeRef).add(file);
181
+ }
182
+ }
183
+ }
184
+ }
185
+ return typeGraph;
186
+ }
187
+
188
+ // src/semantic/domain-inference.ts
189
+ function calculateDomainConfidence(signals) {
190
+ const weights = {
191
+ coUsage: 0.35,
192
+ typeReference: 0.3,
193
+ exportName: 0.15,
194
+ importPath: 0.1,
195
+ folderStructure: 0.1
196
+ };
197
+ let confidence = 0;
198
+ if (signals.coUsage) confidence += weights.coUsage;
199
+ if (signals.typeReference) confidence += weights.typeReference;
200
+ if (signals.exportName) confidence += weights.exportName;
201
+ if (signals.importPath) confidence += weights.importPath;
202
+ if (signals.folderStructure) confidence += weights.folderStructure;
203
+ return confidence;
204
+ }
205
+ function inferDomainFromSemantics(file, exportName, graph, coUsageMatrix, typeGraph, exportTypeRefs) {
206
+ const domainSignals = /* @__PURE__ */ new Map();
207
+ const coUsages = coUsageMatrix.get(file) || /* @__PURE__ */ new Map();
208
+ const strongCoUsages = Array.from(coUsages.entries()).filter(([, count]) => count >= 3).map(([coFile]) => coFile);
209
+ for (const coFile of strongCoUsages) {
210
+ const coNode = graph.nodes.get(coFile);
211
+ if (coNode) {
212
+ for (const exp of coNode.exports) {
213
+ const expAny = exp;
214
+ if (expAny.inferredDomain && expAny.inferredDomain !== "unknown") {
215
+ const domain = expAny.inferredDomain;
216
+ if (!domainSignals.has(domain)) {
217
+ domainSignals.set(domain, {
218
+ coUsage: false,
219
+ typeReference: false,
220
+ exportName: false,
221
+ importPath: false,
222
+ folderStructure: false
223
+ });
224
+ }
225
+ domainSignals.get(domain).coUsage = true;
226
+ }
227
+ }
228
+ }
229
+ }
230
+ if (exportTypeRefs) {
231
+ for (const typeRef of exportTypeRefs) {
232
+ const filesWithType = typeGraph.get(typeRef);
233
+ if (filesWithType) {
234
+ for (const typeFile of filesWithType) {
235
+ if (typeFile === file) continue;
236
+ const typeNode = graph.nodes.get(typeFile);
237
+ if (typeNode) {
238
+ for (const exp of typeNode.exports) {
239
+ const expAny = exp;
240
+ if (expAny.inferredDomain && expAny.inferredDomain !== "unknown") {
241
+ const domain = expAny.inferredDomain;
242
+ if (!domainSignals.has(domain)) {
243
+ domainSignals.set(domain, {
244
+ coUsage: false,
245
+ typeReference: false,
246
+ exportName: false,
247
+ importPath: false,
248
+ folderStructure: false
249
+ });
250
+ }
251
+ domainSignals.get(domain).typeReference = true;
252
+ }
253
+ }
254
+ }
255
+ }
256
+ }
257
+ }
258
+ }
259
+ const assignments = [];
260
+ for (const [domain, signals] of domainSignals) {
261
+ const confidence = calculateDomainConfidence(signals);
262
+ if (confidence >= 0.3) assignments.push({ domain, confidence, signals });
263
+ }
264
+ assignments.sort((a, b) => b.confidence - a.confidence);
265
+ return assignments;
266
+ }
267
+ function extractExports(content, filePath, domainOptions, fileImports) {
268
+ const exports = [];
269
+ const patterns = [
270
+ /export\s+function\s+(\w+)/g,
271
+ /export\s+class\s+(\w+)/g,
272
+ /export\s+const\s+(\w+)/g,
273
+ /export\s+type\s+(\w+)/g,
274
+ /export\s+interface\s+(\w+)/g,
275
+ /export\s+default/g
276
+ ];
277
+ const types = [
278
+ "function",
279
+ "class",
280
+ "const",
281
+ "type",
282
+ "interface",
283
+ "default"
284
+ ];
285
+ patterns.forEach((pattern, index) => {
286
+ let match;
287
+ while ((match = pattern.exec(content)) !== null) {
288
+ const name = match[1] || "default";
289
+ const type = types[index];
290
+ const inferredDomain = inferDomain(
291
+ name,
292
+ filePath,
293
+ domainOptions,
294
+ fileImports
295
+ );
296
+ exports.push({ name, type, inferredDomain });
297
+ }
298
+ });
299
+ return exports;
300
+ }
301
+ function inferDomain(name, filePath, domainOptions, fileImports) {
302
+ const lower = name.toLowerCase();
303
+ const tokens = Array.from(
304
+ new Set(
305
+ lower.replace(/([a-z0-9])([A-Z])/g, "$1 $2").replace(/[^a-z0-9]+/gi, " ").split(" ").filter(Boolean)
306
+ )
307
+ );
308
+ const defaultKeywords = [
309
+ "authentication",
310
+ "authorization",
311
+ "payment",
312
+ "invoice",
313
+ "customer",
314
+ "product",
315
+ "order",
316
+ "cart",
317
+ "user",
318
+ "admin",
319
+ "repository",
320
+ "controller",
321
+ "service",
322
+ "config",
323
+ "model",
324
+ "view",
325
+ "auth"
326
+ ];
327
+ const domainKeywords = domainOptions?.domainKeywords?.length ? [...domainOptions.domainKeywords, ...defaultKeywords] : defaultKeywords;
328
+ for (const keyword of domainKeywords) {
329
+ if (tokens.includes(keyword)) return keyword;
330
+ }
331
+ for (const keyword of domainKeywords) {
332
+ if (lower.includes(keyword)) return keyword;
333
+ }
334
+ if (fileImports) {
335
+ for (const importPath of fileImports) {
336
+ const segments = importPath.split("/");
337
+ for (const segment of segments) {
338
+ const segLower = segment.toLowerCase();
339
+ const singularSegment = singularize(segLower);
340
+ for (const keyword of domainKeywords) {
341
+ if (singularSegment === keyword || segLower === keyword || segLower.includes(keyword))
342
+ return keyword;
343
+ }
344
+ }
345
+ }
346
+ }
347
+ if (filePath) {
348
+ const segments = filePath.split("/");
349
+ for (const segment of segments) {
350
+ const segLower = segment.toLowerCase();
351
+ const singularSegment = singularize(segLower);
352
+ for (const keyword of domainKeywords) {
353
+ if (singularSegment === keyword || segLower === keyword) return keyword;
354
+ }
355
+ }
356
+ }
357
+ return "unknown";
358
+ }
359
+
360
+ // src/ast-utils.ts
361
+ import { parseFileExports, isTestFile } from "@aiready/core";
362
+ async function extractExportsWithAST(content, filePath, domainOptions, fileImports) {
363
+ try {
364
+ const { exports: astExports } = await parseFileExports(content, filePath);
365
+ if (astExports.length === 0 && !isTestFile(filePath)) {
366
+ return extractExports(content, filePath, domainOptions, fileImports);
367
+ }
368
+ return astExports.map((exp) => ({
369
+ name: exp.name,
370
+ type: exp.type,
371
+ inferredDomain: inferDomain(
372
+ exp.name,
373
+ filePath,
374
+ domainOptions,
375
+ fileImports
376
+ ),
377
+ imports: exp.imports,
378
+ dependencies: exp.dependencies,
379
+ typeReferences: exp.typeReferences
380
+ }));
381
+ } catch {
382
+ return extractExports(content, filePath, domainOptions, fileImports);
383
+ }
384
+ }
385
+
386
+ // src/graph-builder.ts
387
+ import { join, dirname, normalize } from "path";
388
+ function resolveImport(source, importingFile, allFiles) {
389
+ if (!source.startsWith(".") && !source.startsWith("/")) {
390
+ if (source.startsWith("@aiready/")) {
391
+ const pkgName = source.split("/")[1];
392
+ const possiblePaths = [
393
+ // Standard src/index.ts entry point for our packages
394
+ join("packages", pkgName, "src", "index.ts"),
395
+ join("packages", pkgName, "src", "index.tsx"),
396
+ // Support for sub-exports if needed (e.g. @aiready/core/client)
397
+ join(
398
+ "packages",
399
+ pkgName,
400
+ "src",
401
+ `${source.split("/").slice(2).join("/") || "index"}.ts`
402
+ )
403
+ ];
404
+ for (const p of possiblePaths) {
405
+ const absolutePkgPath = Array.from(allFiles).find(
406
+ (f) => f.endsWith(normalize(p))
407
+ );
408
+ if (absolutePkgPath) return absolutePkgPath;
409
+ }
410
+ }
411
+ if (allFiles.has(source)) return source;
412
+ return null;
413
+ }
414
+ const dir = dirname(importingFile);
415
+ const absolutePath = normalize(join(dir, source));
416
+ if (allFiles.has(absolutePath)) return absolutePath;
417
+ const extensions = [".ts", ".tsx", ".js", ".jsx"];
418
+ for (const ext of extensions) {
419
+ const withExt = absolutePath + ext;
420
+ if (allFiles.has(withExt)) return withExt;
421
+ }
422
+ for (const ext of extensions) {
423
+ const indexFile = normalize(join(absolutePath, `index${ext}`));
424
+ if (allFiles.has(indexFile)) return indexFile;
425
+ }
426
+ return null;
427
+ }
428
+ function extractDomainKeywordsFromPaths(files) {
429
+ const folderNames = /* @__PURE__ */ new Set();
430
+ for (const { file } of files) {
431
+ const segments = file.split("/");
432
+ const skipFolders = /* @__PURE__ */ new Set([
433
+ "src",
434
+ "lib",
435
+ "dist",
436
+ "build",
437
+ "node_modules",
438
+ "test",
439
+ "tests",
440
+ "__tests__",
441
+ "spec",
442
+ "e2e",
443
+ "scripts",
444
+ "components",
445
+ "utils",
446
+ "helpers",
447
+ "util",
448
+ "helper",
449
+ "api",
450
+ "apis"
451
+ ]);
452
+ for (const segment of segments) {
453
+ const normalized = segment.toLowerCase();
454
+ if (normalized && !skipFolders.has(normalized) && !normalized.includes(".")) {
455
+ folderNames.add(singularize(normalized));
456
+ }
457
+ }
458
+ }
459
+ return Array.from(folderNames);
460
+ }
461
+ async function buildDependencyGraph(files, options) {
462
+ const nodes = /* @__PURE__ */ new Map();
463
+ const edges = /* @__PURE__ */ new Map();
464
+ const autoDetectedKeywords = options?.domainKeywords ?? extractDomainKeywordsFromPaths(files);
465
+ const allFilePaths = new Set(files.map((f) => f.file));
466
+ for (const { file, content } of files) {
467
+ const { imports: astImports } = await parseFileExports2(content, file);
468
+ const resolvedImports = astImports.map((i) => resolveImport(i.source, file, allFilePaths)).filter((path) => path !== null);
469
+ const importSources = astImports.map((i) => i.source);
470
+ const exports = await extractExportsWithAST(
471
+ content,
472
+ file,
473
+ { domainKeywords: autoDetectedKeywords },
474
+ importSources
475
+ );
476
+ const tokenCost = estimateTokens(content);
477
+ const linesOfCode = content.split("\n").length;
478
+ nodes.set(file, {
479
+ file,
480
+ imports: importSources,
481
+ exports,
482
+ tokenCost,
483
+ linesOfCode
484
+ });
485
+ edges.set(file, new Set(resolvedImports));
486
+ }
487
+ const graph = { nodes, edges };
488
+ const coUsageMatrix = buildCoUsageMatrix(graph);
489
+ const typeGraph = buildTypeGraph(graph);
490
+ graph.coUsageMatrix = coUsageMatrix;
491
+ graph.typeGraph = typeGraph;
492
+ for (const [file, node] of nodes) {
493
+ for (const exp of node.exports) {
494
+ const semanticAssignments = inferDomainFromSemantics(
495
+ file,
496
+ exp.name,
497
+ graph,
498
+ coUsageMatrix,
499
+ typeGraph,
500
+ exp.typeReferences
501
+ );
502
+ const expAny = exp;
503
+ expAny.domains = semanticAssignments;
504
+ if (semanticAssignments.length > 0) {
505
+ expAny.inferredDomain = semanticAssignments[0].domain;
506
+ }
507
+ }
508
+ }
509
+ return graph;
510
+ }
511
+ function calculateImportDepth(file, graph, visited = /* @__PURE__ */ new Set(), depth = 0) {
512
+ return calculateImportDepthFromEdges(file, graph.edges, visited, depth);
513
+ }
514
+ function getTransitiveDependencies(file, graph, visited = /* @__PURE__ */ new Set()) {
515
+ return getTransitiveDependenciesFromEdges(file, graph.edges, visited);
516
+ }
517
+ function calculateContextBudget(file, graph) {
518
+ const node = graph.nodes.get(file);
519
+ if (!node) return 0;
520
+ let totalTokens = node.tokenCost;
521
+ const deps = getTransitiveDependencies(file, graph);
522
+ for (const dep of deps) {
523
+ const depNode = graph.nodes.get(dep);
524
+ if (depNode) {
525
+ totalTokens += depNode.tokenCost;
526
+ }
527
+ }
528
+ return totalTokens;
529
+ }
530
+ function detectCircularDependencies(graph) {
531
+ return detectGraphCycles(graph.edges);
532
+ }
533
+
534
+ // src/classify/classification-patterns.ts
535
+ var BARREL_EXPORT_MIN_EXPORTS = 5;
536
+ var BARREL_EXPORT_TOKEN_LIMIT = 1e3;
537
+ var HANDLER_NAME_PATTERNS = [
538
+ "handler",
539
+ ".handler.",
540
+ "-handler.",
541
+ "lambda",
542
+ ".lambda.",
543
+ "-lambda."
544
+ ];
545
+ var SERVICE_NAME_PATTERNS = [
546
+ "service",
547
+ ".service.",
548
+ "-service.",
549
+ "_service."
550
+ ];
551
+ var EMAIL_NAME_PATTERNS = [
552
+ "-email-",
553
+ ".email.",
554
+ "_email_",
555
+ "-template",
556
+ ".template.",
557
+ "_template",
558
+ "-mail.",
559
+ ".mail."
560
+ ];
561
+ var PARSER_NAME_PATTERNS = [
562
+ "parser",
563
+ ".parser.",
564
+ "-parser.",
565
+ "_parser.",
566
+ "transform",
567
+ "converter",
568
+ "mapper",
569
+ "serializer"
570
+ ];
571
+ var SESSION_NAME_PATTERNS = ["session", "state", "context", "store"];
572
+ var NEXTJS_METADATA_EXPORTS = [
573
+ "metadata",
574
+ "generatemetadata",
575
+ "faqjsonld",
576
+ "jsonld",
577
+ "icon"
578
+ ];
579
+ var CONFIG_NAME_PATTERNS = [
580
+ ".config.",
581
+ "tsconfig",
582
+ "jest.config",
583
+ "package.json",
584
+ "aiready.json",
585
+ "next.config",
586
+ "sst.config"
587
+ ];
588
+
589
+ // src/classify/file-classifiers.ts
590
+ function isBoilerplateBarrel(node) {
591
+ const { exports, tokenCost } = node;
592
+ if (!exports || exports.length === 0) return false;
593
+ const isPurelyReexports = exports.every((exp) => !!exp.source);
594
+ if (!isPurelyReexports) return false;
595
+ if (tokenCost > 500) return false;
596
+ const sources = new Set(exports.map((exp) => exp.source));
597
+ const isSingleSourcePassThrough = sources.size === 1;
598
+ const isMeaninglessAggregation = sources.size > 0 && sources.size < 3;
599
+ return isSingleSourcePassThrough || isMeaninglessAggregation;
600
+ }
601
+ function isBarrelExport(node) {
602
+ if (isBoilerplateBarrel(node)) return false;
603
+ const { file, exports } = node;
604
+ const fileName = file.split("/").pop()?.toLowerCase();
605
+ const isIndexFile = fileName === "index.ts" || fileName === "index.js";
606
+ const isSmallAndManyExports = node.tokenCost < BARREL_EXPORT_TOKEN_LIMIT && (exports || []).length > BARREL_EXPORT_MIN_EXPORTS;
607
+ const isReexportPattern = (exports || []).length >= BARREL_EXPORT_MIN_EXPORTS && (exports || []).every(
608
+ (exp) => ["const", "function", "type", "interface"].includes(exp.type)
609
+ );
610
+ return !!isIndexFile || !!isSmallAndManyExports || !!isReexportPattern;
611
+ }
612
+ function isTypeDefinition(node) {
613
+ const { file } = node;
614
+ if (file.endsWith(".d.ts")) return true;
615
+ const nodeExports = node.exports || [];
616
+ const hasExports = nodeExports.length > 0;
617
+ const areAllTypes = hasExports && nodeExports.every(
618
+ (exp) => exp.type === "type" || exp.type === "interface"
619
+ );
620
+ const isTypePath = /\/(types|interfaces|models)\//i.test(file);
621
+ return !!areAllTypes || isTypePath && hasExports;
622
+ }
623
+ function isUtilityModule(node) {
624
+ const { file } = node;
625
+ const isUtilPath = /\/(utils|helpers|util|helper)\//i.test(file);
626
+ const fileName = file.split("/").pop()?.toLowerCase() || "";
627
+ const isUtilName = /(utils\.|helpers\.|util\.|helper\.)/i.test(fileName);
628
+ return isUtilPath || isUtilName;
629
+ }
630
+ function isLambdaHandler(node) {
631
+ const { file, exports } = node;
632
+ const fileName = file.split("/").pop()?.toLowerCase() || "";
633
+ const isHandlerName = HANDLER_NAME_PATTERNS.some(
634
+ (pattern) => fileName.includes(pattern)
635
+ );
636
+ const isHandlerPath = /\/(handlers|lambdas|lambda|functions)\//i.test(file);
637
+ const hasHandlerExport = (exports || []).some(
638
+ (exp) => ["handler", "main", "lambdahandler"].includes(exp.name.toLowerCase()) || exp.name.toLowerCase().endsWith("handler")
639
+ );
640
+ return isHandlerName || isHandlerPath || hasHandlerExport;
641
+ }
642
+ function isServiceFile(node) {
643
+ const { file, exports } = node;
644
+ const fileName = file.split("/").pop()?.toLowerCase() || "";
645
+ const isServiceName = SERVICE_NAME_PATTERNS.some(
646
+ (pattern) => fileName.includes(pattern)
647
+ );
648
+ const isServicePath = file.toLowerCase().includes("/services/");
649
+ const hasServiceNamedExport = (exports || []).some(
650
+ (exp) => exp.name.toLowerCase().includes("service")
651
+ );
652
+ const hasClassExport = (exports || []).some(
653
+ (exp) => exp.type === "class"
654
+ );
655
+ return isServiceName || isServicePath || hasServiceNamedExport && hasClassExport;
656
+ }
657
+ function isEmailTemplate(node) {
658
+ const { file, exports } = node;
659
+ const fileName = file.split("/").pop()?.toLowerCase() || "";
660
+ const isEmailName = EMAIL_NAME_PATTERNS.some(
661
+ (pattern) => fileName.includes(pattern)
662
+ );
663
+ const isEmailPath = /\/(emails|mail|notifications)\//i.test(file);
664
+ const hasTemplateFunction = (exports || []).some(
665
+ (exp) => exp.type === "function" && (exp.name.toLowerCase().startsWith("render") || exp.name.toLowerCase().startsWith("generate"))
666
+ );
667
+ return isEmailPath || isEmailName || hasTemplateFunction;
668
+ }
669
+ function isParserFile(node) {
670
+ const { file, exports } = node;
671
+ const fileName = file.split("/").pop()?.toLowerCase() || "";
672
+ const isParserName = PARSER_NAME_PATTERNS.some(
673
+ (pattern) => fileName.includes(pattern)
674
+ );
675
+ const isParserPath = /\/(parsers|transformers)\//i.test(file);
676
+ const hasParseFunction = (exports || []).some(
677
+ (exp) => exp.type === "function" && (exp.name.toLowerCase().startsWith("parse") || exp.name.toLowerCase().startsWith("transform"))
678
+ );
679
+ return isParserName || isParserPath || hasParseFunction;
680
+ }
681
+ function isSessionFile(node) {
682
+ const { file, exports } = node;
683
+ const fileName = file.split("/").pop()?.toLowerCase() || "";
684
+ const isSessionName = SESSION_NAME_PATTERNS.some(
685
+ (pattern) => fileName.includes(pattern)
686
+ );
687
+ const isSessionPath = /\/(sessions|state)\//i.test(file);
688
+ const hasSessionExport = (exports || []).some(
689
+ (exp) => ["session", "state", "store"].some(
690
+ (pattern) => exp.name.toLowerCase().includes(pattern)
691
+ )
692
+ );
693
+ return isSessionName || isSessionPath || hasSessionExport;
694
+ }
695
+ function isNextJsPage(node) {
696
+ const { file, exports } = node;
697
+ const lowerPath = file.toLowerCase();
698
+ const fileName = file.split("/").pop()?.toLowerCase() || "";
699
+ const isInAppDir = lowerPath.includes("/app/") || lowerPath.startsWith("app/");
700
+ if (!isInAppDir || fileName !== "page.tsx" && fileName !== "page.ts")
701
+ return false;
702
+ const hasDefaultExport = (exports || []).some(
703
+ (exp) => exp.type === "default"
704
+ );
705
+ const hasNextJsExport = (exports || []).some(
706
+ (exp) => NEXTJS_METADATA_EXPORTS.includes(exp.name.toLowerCase())
707
+ );
708
+ return hasDefaultExport || hasNextJsExport;
709
+ }
710
+ function isConfigFile(node) {
711
+ const { file, exports } = node;
712
+ const lowerPath = file.toLowerCase();
713
+ const fileName = file.split("/").pop()?.toLowerCase() || "";
714
+ const isConfigName = CONFIG_NAME_PATTERNS.some(
715
+ (pattern) => fileName.includes(pattern)
716
+ );
717
+ const isConfigPath = /\/(config|settings|schemas)\//i.test(lowerPath);
718
+ const hasSchemaExport = (exports || []).some(
719
+ (exp) => ["schema", "config", "setting"].some(
720
+ (pattern) => exp.name.toLowerCase().includes(pattern)
721
+ )
722
+ );
723
+ return isConfigName || isConfigPath || hasSchemaExport;
724
+ }
725
+ function isHubAndSpokeFile(node) {
726
+ const { file } = node;
727
+ return /\/packages\/[a-zA-Z0-9-]+\/src\//.test(file);
728
+ }
729
+
730
+ // src/classifier.ts
731
+ var Classification = {
732
+ BARREL: "barrel-export",
733
+ BOILERPLATE: "boilerplate-barrel",
734
+ TYPE_DEFINITION: "type-definition",
735
+ NEXTJS_PAGE: "nextjs-page",
736
+ LAMBDA_HANDLER: "lambda-handler",
737
+ SERVICE: "service-file",
738
+ EMAIL_TEMPLATE: "email-template",
739
+ PARSER: "parser-file",
740
+ COHESIVE_MODULE: "cohesive-module",
741
+ UTILITY_MODULE: "utility-module",
742
+ SPOKE_MODULE: "spoke-module",
743
+ MIXED_CONCERNS: "mixed-concerns",
744
+ UNKNOWN: "unknown"
745
+ };
746
+ function classifyFile(node, cohesionScore = 1, domains = []) {
747
+ if (isBoilerplateBarrel(node)) {
748
+ return Classification.BOILERPLATE;
749
+ }
750
+ if (isBarrelExport(node)) {
751
+ return Classification.BARREL;
752
+ }
753
+ if (isTypeDefinition(node)) {
754
+ return Classification.TYPE_DEFINITION;
755
+ }
756
+ if (isNextJsPage(node)) {
757
+ return Classification.NEXTJS_PAGE;
758
+ }
759
+ if (isLambdaHandler(node)) {
760
+ return Classification.LAMBDA_HANDLER;
761
+ }
762
+ if (isServiceFile(node)) {
763
+ return Classification.SERVICE;
764
+ }
765
+ if (isEmailTemplate(node)) {
766
+ return Classification.EMAIL_TEMPLATE;
767
+ }
768
+ if (isParserFile(node)) {
769
+ return Classification.PARSER;
770
+ }
771
+ if (isSessionFile(node)) {
772
+ if (cohesionScore >= 0.25 && domains.length <= 1)
773
+ return Classification.COHESIVE_MODULE;
774
+ return Classification.UTILITY_MODULE;
775
+ }
776
+ if (isUtilityModule(node)) {
777
+ return Classification.UTILITY_MODULE;
778
+ }
779
+ if (isConfigFile(node)) {
780
+ return Classification.COHESIVE_MODULE;
781
+ }
782
+ if (isHubAndSpokeFile(node)) {
783
+ return Classification.SPOKE_MODULE;
784
+ }
785
+ if (domains.length <= 1 && domains[0] !== "unknown") {
786
+ return Classification.COHESIVE_MODULE;
787
+ }
788
+ if (domains.length > 1 && cohesionScore < 0.4) {
789
+ return Classification.MIXED_CONCERNS;
790
+ }
791
+ if (cohesionScore >= 0.7) {
792
+ return Classification.COHESIVE_MODULE;
793
+ }
794
+ return Classification.UNKNOWN;
795
+ }
796
+ function adjustCohesionForClassification(baseCohesion, classification, node) {
797
+ switch (classification) {
798
+ case Classification.BOILERPLATE:
799
+ return 0.2;
800
+ // Redundant indirection is low cohesion (architectural theater)
801
+ case Classification.BARREL:
802
+ return 1;
803
+ case Classification.TYPE_DEFINITION:
804
+ return 1;
805
+ case Classification.NEXTJS_PAGE:
806
+ return 1;
807
+ case Classification.UTILITY_MODULE: {
808
+ if (node && hasRelatedExportNames(
809
+ (node.exports || []).map((e) => e.name.toLowerCase())
810
+ )) {
811
+ return Math.max(0.8, Math.min(1, baseCohesion + 0.45));
812
+ }
813
+ return Math.max(0.75, Math.min(1, baseCohesion + 0.35));
814
+ }
815
+ case Classification.SERVICE:
816
+ return Math.max(0.72, Math.min(1, baseCohesion + 0.3));
817
+ case Classification.LAMBDA_HANDLER:
818
+ return Math.max(0.75, Math.min(1, baseCohesion + 0.35));
819
+ case Classification.EMAIL_TEMPLATE:
820
+ return Math.max(0.72, Math.min(1, baseCohesion + 0.3));
821
+ case Classification.PARSER:
822
+ return Math.max(0.7, Math.min(1, baseCohesion + 0.3));
823
+ case Classification.SPOKE_MODULE:
824
+ return Math.max(baseCohesion, 0.6);
825
+ case Classification.COHESIVE_MODULE:
826
+ return Math.max(baseCohesion, 0.7);
827
+ case Classification.MIXED_CONCERNS:
828
+ return baseCohesion;
829
+ default:
830
+ return Math.min(1, baseCohesion + 0.1);
831
+ }
832
+ }
833
+ function hasRelatedExportNames(exportNames) {
834
+ if (exportNames.length < 2) return true;
835
+ const stems = /* @__PURE__ */ new Set();
836
+ const domains = /* @__PURE__ */ new Set();
837
+ const verbs = [
838
+ "get",
839
+ "set",
840
+ "create",
841
+ "update",
842
+ "delete",
843
+ "fetch",
844
+ "save",
845
+ "load",
846
+ "parse",
847
+ "format",
848
+ "validate"
849
+ ];
850
+ const domainPatterns = [
851
+ "user",
852
+ "order",
853
+ "product",
854
+ "session",
855
+ "email",
856
+ "file",
857
+ "db",
858
+ "api",
859
+ "config"
860
+ ];
861
+ for (const name of exportNames) {
862
+ for (const verb of verbs) {
863
+ if (name.startsWith(verb) && name.length > verb.length) {
864
+ stems.add(name.slice(verb.length).toLowerCase());
865
+ }
866
+ }
867
+ for (const domain of domainPatterns) {
868
+ if (name.includes(domain)) domains.add(domain);
869
+ }
870
+ }
871
+ if (stems.size === 1 || domains.size === 1) return true;
872
+ return false;
873
+ }
874
+ function adjustFragmentationForClassification(baseFragmentation, classification) {
875
+ switch (classification) {
876
+ case Classification.BOILERPLATE:
877
+ return baseFragmentation * 1.5;
878
+ // Redundant barrels increase fragmentation
879
+ case Classification.BARREL:
880
+ return 0;
881
+ case Classification.TYPE_DEFINITION:
882
+ return 0;
883
+ case Classification.UTILITY_MODULE:
884
+ case Classification.SERVICE:
885
+ case Classification.LAMBDA_HANDLER:
886
+ case Classification.EMAIL_TEMPLATE:
887
+ case Classification.PARSER:
888
+ case Classification.NEXTJS_PAGE:
889
+ return baseFragmentation * 0.2;
890
+ case Classification.SPOKE_MODULE:
891
+ return baseFragmentation * 0.15;
892
+ // Heavily discount intentional monorepo separation
893
+ case Classification.COHESIVE_MODULE:
894
+ return baseFragmentation * 0.3;
895
+ case Classification.MIXED_CONCERNS:
896
+ return baseFragmentation;
897
+ default:
898
+ return baseFragmentation * 0.7;
899
+ }
900
+ }
901
+
902
+ // src/cluster-detector.ts
903
+ function detectModuleClusters(graph, options) {
904
+ const domainMap = /* @__PURE__ */ new Map();
905
+ for (const [file, node] of graph.nodes.entries()) {
906
+ const primaryDomain = node.exports[0]?.inferredDomain || "unknown";
907
+ if (!domainMap.has(primaryDomain)) {
908
+ domainMap.set(primaryDomain, []);
909
+ }
910
+ domainMap.get(primaryDomain).push(file);
911
+ }
912
+ const clusters = [];
913
+ const generateSuggestedStructure = (files, tokens, fragmentation) => {
914
+ const targetFiles = Math.max(1, Math.ceil(tokens / 1e4));
915
+ const plan = [];
916
+ if (fragmentation > 0.5) {
917
+ plan.push(
918
+ `Consolidate ${files.length} files scattered across multiple directories into ${targetFiles} core module(s)`
919
+ );
920
+ }
921
+ if (tokens > 2e4) {
922
+ plan.push(
923
+ `Domain logic is very large (${Math.round(tokens / 1e3)}k tokens). Ensure clear sub-domain boundaries.`
924
+ );
925
+ }
926
+ return { targetFiles, consolidationPlan: plan };
927
+ };
928
+ for (const [domain, files] of domainMap.entries()) {
929
+ if (files.length < 2 || domain === "unknown") continue;
930
+ const totalTokens = files.reduce((sum, file) => {
931
+ const node = graph.nodes.get(file);
932
+ return sum + (node?.tokenCost || 0);
933
+ }, 0);
934
+ let sharedImportRatio = 0;
935
+ if (files.length >= 2) {
936
+ const allImportSets = files.map(
937
+ (f) => new Set(graph.nodes.get(f)?.imports || [])
938
+ );
939
+ let intersection = new Set(allImportSets[0]);
940
+ const union = new Set(allImportSets[0]);
941
+ for (let i = 1; i < allImportSets.length; i++) {
942
+ const nextSet = allImportSets[i];
943
+ intersection = new Set([...intersection].filter((x) => nextSet.has(x)));
944
+ for (const x of nextSet) union.add(x);
945
+ }
946
+ sharedImportRatio = union.size > 0 ? intersection.size / union.size : 0;
947
+ }
948
+ const rawFragmentation = calculateFragmentation(files, domain, {
949
+ ...options,
950
+ sharedImportRatio
951
+ });
952
+ let totalCohesion = 0;
953
+ let totalAdjustedFragmentation = 0;
954
+ files.forEach((f) => {
955
+ const node = graph.nodes.get(f);
956
+ if (node) {
957
+ const cohesion = calculateEnhancedCohesion(node.exports);
958
+ totalCohesion += cohesion;
959
+ const classification = classifyFile(node, cohesion);
960
+ totalAdjustedFragmentation += adjustFragmentationForClassification(
961
+ rawFragmentation,
962
+ classification
963
+ );
964
+ }
965
+ });
966
+ const avgCohesion = totalCohesion / files.length;
967
+ const fragmentationScore = totalAdjustedFragmentation / files.length;
968
+ clusters.push({
969
+ domain,
970
+ files,
971
+ totalTokens,
972
+ fragmentationScore,
973
+ avgCohesion,
974
+ suggestedStructure: generateSuggestedStructure(
975
+ files,
976
+ totalTokens,
977
+ fragmentationScore
978
+ )
979
+ });
980
+ }
981
+ return clusters;
982
+ }
983
+
984
+ // src/remediation.ts
985
+ function getClassificationRecommendations(classification, file, issues) {
986
+ switch (classification) {
987
+ case "boilerplate-barrel":
988
+ return [
989
+ "Redundant indirection detected (architectural theater)",
990
+ "Remove this pass-through barrel export to reduce cognitive load",
991
+ "Consider combining into meaningful domain exports if necessary"
992
+ ];
993
+ case "barrel-export":
994
+ return [
995
+ "Barrel export file detected - multiple domains are expected here",
996
+ "Consider if this barrel export improves or hinders discoverability"
997
+ ];
998
+ case "type-definition":
999
+ return [
1000
+ "Type definition file - centralized types improve consistency",
1001
+ "Consider splitting if file becomes too large (>500 lines)"
1002
+ ];
1003
+ case "cohesive-module":
1004
+ return [
1005
+ "Module has good cohesion despite its size",
1006
+ "Consider documenting the module boundaries for AI assistants"
1007
+ ];
1008
+ case "utility-module":
1009
+ return [
1010
+ "Utility module detected - multiple domains are acceptable here",
1011
+ "Consider grouping related utilities by prefix or domain for better discoverability"
1012
+ ];
1013
+ case "service-file":
1014
+ return [
1015
+ "Service file detected - orchestration of multiple dependencies is expected",
1016
+ "Consider documenting service boundaries and dependencies"
1017
+ ];
1018
+ case "lambda-handler":
1019
+ return [
1020
+ "Lambda handler detected - coordination of services is expected",
1021
+ "Ensure handler has clear single responsibility"
1022
+ ];
1023
+ case "email-template":
1024
+ return [
1025
+ "Email template detected - references multiple domains for rendering",
1026
+ "Template structure is cohesive by design"
1027
+ ];
1028
+ case "parser-file":
1029
+ return [
1030
+ "Parser/transformer file detected - handles multiple data sources",
1031
+ "Consider documenting input/output schemas"
1032
+ ];
1033
+ case "nextjs-page":
1034
+ return [
1035
+ "Next.js App Router page detected - metadata/JSON-LD/component pattern is cohesive",
1036
+ "Multiple exports (metadata, faqJsonLd, default) serve single page purpose"
1037
+ ];
1038
+ case "spoke-module":
1039
+ return [
1040
+ "Spoke module detected - intentional monorepo separation is good for modularity",
1041
+ "Ensure this spoke only exports what is necessary for the hub or other spokes"
1042
+ ];
1043
+ case "mixed-concerns":
1044
+ return [
1045
+ "Consider splitting this file by domain",
1046
+ "Identify independent responsibilities and extract them",
1047
+ "Review import dependencies to understand coupling"
1048
+ ];
1049
+ default:
1050
+ return issues;
1051
+ }
1052
+ }
1053
+ function getGeneralRecommendations(metrics, thresholds) {
1054
+ const recommendations = [];
1055
+ const issues = [];
1056
+ let severity = "info";
1057
+ if (metrics.contextBudget > thresholds.maxContextBudget) {
1058
+ issues.push(
1059
+ `High context budget: ${Math.round(metrics.contextBudget / 1e3)}k tokens`
1060
+ );
1061
+ recommendations.push(
1062
+ "Reduce dependencies or split the file to lower context window requirements"
1063
+ );
1064
+ severity = "major";
1065
+ }
1066
+ if (metrics.importDepth > thresholds.maxDepth) {
1067
+ issues.push(`Deep import chain: ${metrics.importDepth} levels`);
1068
+ recommendations.push("Flatten the dependency graph by reducing nesting");
1069
+ if (severity !== "critical") severity = "major";
1070
+ }
1071
+ if (metrics.circularDeps.length > 0) {
1072
+ issues.push(
1073
+ `Circular dependencies detected: ${metrics.circularDeps.length}`
1074
+ );
1075
+ recommendations.push(
1076
+ "Refactor to remove circular imports (use dependency injection or interfaces)"
1077
+ );
1078
+ severity = "critical";
1079
+ }
1080
+ if (metrics.cohesionScore < thresholds.minCohesion) {
1081
+ issues.push(`Low cohesion score: ${metrics.cohesionScore.toFixed(2)}`);
1082
+ recommendations.push(
1083
+ "Extract unrelated exports into separate domain-specific modules"
1084
+ );
1085
+ if (severity === "info") severity = "minor";
1086
+ }
1087
+ if (metrics.fragmentationScore > thresholds.maxFragmentation) {
1088
+ issues.push(
1089
+ `High domain fragmentation: ${metrics.fragmentationScore.toFixed(2)}`
1090
+ );
1091
+ recommendations.push(
1092
+ "Consolidate domain-related files into fewer directories"
1093
+ );
1094
+ if (severity === "info") severity = "minor";
1095
+ }
1096
+ return {
1097
+ recommendations,
1098
+ issues,
1099
+ severity
1100
+ };
1101
+ }
1102
+
1103
+ // src/orchestrator.ts
1104
+ function mapNodeToResult(node, graph, clusters, allCircularDeps, options) {
1105
+ const file = node.file;
1106
+ const tokenCost = node.tokenCost;
1107
+ const importDepth = calculateImportDepth(file, graph);
1108
+ const transitiveDeps = getTransitiveDependencies(file, graph);
1109
+ const contextBudget = calculateContextBudget(file, graph);
1110
+ const circularDeps = allCircularDeps.filter((cycle) => cycle.includes(file));
1111
+ const cluster = clusters.find((c) => c.files.includes(file));
1112
+ const rawFragmentationScore = cluster ? cluster.fragmentationScore : 0;
1113
+ const rawCohesionScore = calculateEnhancedCohesion(
1114
+ node.exports,
1115
+ file,
1116
+ options
1117
+ );
1118
+ const fileClassification = classifyFile(node, rawCohesionScore);
1119
+ const cohesionScore = adjustCohesionForClassification(
1120
+ rawCohesionScore,
1121
+ fileClassification
1122
+ );
1123
+ const fragmentationScore = adjustFragmentationForClassification(
1124
+ rawFragmentationScore,
1125
+ fileClassification
1126
+ );
1127
+ const { severity, issues, recommendations, potentialSavings } = analyzeIssues(
1128
+ {
1129
+ file,
1130
+ importDepth,
1131
+ contextBudget,
1132
+ cohesionScore,
1133
+ fragmentationScore,
1134
+ maxDepth: options.maxDepth,
1135
+ maxContextBudget: options.maxContextBudget,
1136
+ minCohesion: options.minCohesion,
1137
+ maxFragmentation: options.maxFragmentation,
1138
+ circularDeps
1139
+ }
1140
+ );
1141
+ const classRecs = getClassificationRecommendations(
1142
+ fileClassification,
1143
+ file,
1144
+ issues
1145
+ );
1146
+ const allRecommendations = Array.from(
1147
+ /* @__PURE__ */ new Set([...recommendations, ...classRecs])
1148
+ );
1149
+ return {
1150
+ file,
1151
+ tokenCost,
1152
+ linesOfCode: node.linesOfCode,
1153
+ importDepth,
1154
+ dependencyCount: transitiveDeps.length,
1155
+ dependencyList: transitiveDeps,
1156
+ circularDeps,
1157
+ cohesionScore,
1158
+ domains: Array.from(
1159
+ new Set(
1160
+ node.exports.flatMap(
1161
+ (e) => e.domains?.map((d) => d.domain) || []
1162
+ )
1163
+ )
1164
+ ),
1165
+ exportCount: node.exports.length,
1166
+ contextBudget,
1167
+ fragmentationScore,
1168
+ relatedFiles: cluster ? cluster.files : [],
1169
+ fileClassification,
1170
+ severity,
1171
+ issues,
1172
+ recommendations: allRecommendations,
1173
+ potentialSavings
1174
+ };
1175
+ }
1176
+ function calculateCohesion(exports, filePath, options) {
1177
+ return calculateEnhancedCohesion(exports, filePath, options);
1178
+ }
1179
+ async function analyzeContext(options) {
1180
+ const {
1181
+ maxDepth = 5,
1182
+ maxContextBudget = 25e3,
1183
+ minCohesion = 0.6,
1184
+ maxFragmentation = 0.5,
1185
+ includeNodeModules = false,
1186
+ ...scanOptions
1187
+ } = options;
1188
+ const files = await scanFiles({
1189
+ ...scanOptions,
1190
+ exclude: includeNodeModules && scanOptions.exclude ? scanOptions.exclude.filter(
1191
+ (pattern) => pattern !== "**/node_modules/**"
1192
+ ) : scanOptions.exclude
1193
+ });
1194
+ const pythonFiles = files.filter((f) => f.toLowerCase().endsWith(".py"));
1195
+ const fileContents = await Promise.all(
1196
+ files.map(async (file) => ({
1197
+ file,
1198
+ content: await readFileContent(file)
1199
+ }))
1200
+ );
1201
+ const graph = await buildDependencyGraph(
1202
+ fileContents.filter((f) => !f.file.toLowerCase().endsWith(".py"))
1203
+ );
1204
+ let pythonResults = [];
1205
+ if (pythonFiles.length > 0) {
1206
+ const { analyzePythonContext } = await import("./python-context-BWDC4E5Z.mjs");
1207
+ const pythonMetrics = await analyzePythonContext(
1208
+ pythonFiles,
1209
+ scanOptions.rootDir || options.rootDir || "."
1210
+ );
1211
+ pythonResults = pythonMetrics.map((metric) => {
1212
+ const { severity, issues, recommendations, potentialSavings } = analyzeIssues({
1213
+ file: metric.file,
1214
+ importDepth: metric.importDepth,
1215
+ contextBudget: metric.contextBudget,
1216
+ cohesionScore: metric.cohesion,
1217
+ fragmentationScore: 0,
1218
+ maxDepth,
1219
+ maxContextBudget,
1220
+ minCohesion,
1221
+ maxFragmentation,
1222
+ circularDeps: []
1223
+ });
1224
+ return {
1225
+ file: metric.file,
1226
+ tokenCost: 0,
1227
+ linesOfCode: 0,
1228
+ importDepth: metric.importDepth,
1229
+ dependencyCount: 0,
1230
+ dependencyList: [],
1231
+ circularDeps: [],
1232
+ cohesionScore: metric.cohesion,
1233
+ domains: [],
1234
+ exportCount: 0,
1235
+ contextBudget: metric.contextBudget,
1236
+ fragmentationScore: 0,
1237
+ relatedFiles: [],
1238
+ fileClassification: "unknown",
1239
+ severity,
1240
+ issues,
1241
+ recommendations,
1242
+ potentialSavings
1243
+ };
1244
+ });
1245
+ }
1246
+ const clusters = detectModuleClusters(graph);
1247
+ const allCircularDeps = detectCircularDependencies(graph);
1248
+ const results = Array.from(graph.nodes.values()).map(
1249
+ (node) => mapNodeToResult(node, graph, clusters, allCircularDeps, {
1250
+ maxDepth,
1251
+ maxContextBudget,
1252
+ minCohesion,
1253
+ maxFragmentation
1254
+ })
1255
+ );
1256
+ return [...results, ...pythonResults];
1257
+ }
1258
+
1259
+ export {
1260
+ buildCoUsageMatrix,
1261
+ findSemanticClusters,
1262
+ getCoUsageData,
1263
+ buildTypeGraph,
1264
+ calculateDomainConfidence,
1265
+ inferDomainFromSemantics,
1266
+ extractExports,
1267
+ inferDomain,
1268
+ extractDomainKeywordsFromPaths,
1269
+ buildDependencyGraph,
1270
+ calculateImportDepth,
1271
+ getTransitiveDependencies,
1272
+ calculateContextBudget,
1273
+ detectCircularDependencies,
1274
+ BARREL_EXPORT_MIN_EXPORTS,
1275
+ BARREL_EXPORT_TOKEN_LIMIT,
1276
+ HANDLER_NAME_PATTERNS,
1277
+ SERVICE_NAME_PATTERNS,
1278
+ EMAIL_NAME_PATTERNS,
1279
+ PARSER_NAME_PATTERNS,
1280
+ SESSION_NAME_PATTERNS,
1281
+ NEXTJS_METADATA_EXPORTS,
1282
+ CONFIG_NAME_PATTERNS,
1283
+ isBoilerplateBarrel,
1284
+ isBarrelExport,
1285
+ isTypeDefinition,
1286
+ isUtilityModule,
1287
+ isLambdaHandler,
1288
+ isServiceFile,
1289
+ isEmailTemplate,
1290
+ isParserFile,
1291
+ isSessionFile,
1292
+ isNextJsPage,
1293
+ isConfigFile,
1294
+ isHubAndSpokeFile,
1295
+ Classification,
1296
+ classifyFile,
1297
+ adjustCohesionForClassification,
1298
+ adjustFragmentationForClassification,
1299
+ detectModuleClusters,
1300
+ getClassificationRecommendations,
1301
+ getGeneralRecommendations,
1302
+ calculateCohesion,
1303
+ analyzeContext
1304
+ };