@aiready/context-analyzer 0.22.9 → 0.22.12

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.
Files changed (302) hide show
  1. package/.turbo/turbo-build.log +33 -32
  2. package/.turbo/turbo-format-check.log +1 -1
  3. package/.turbo/turbo-lint.log +8 -0
  4. package/dist/chunk-HD4Y3GYL.mjs +124 -0
  5. package/dist/{chunk-M2EGQ36M.mjs → chunk-ISWPFG2C.mjs} +43 -98
  6. package/dist/{chunk-BQCISA2F.mjs → chunk-QW6ULRML.mjs} +32 -6
  7. package/dist/{chunk-WHB7QI7N.mjs → chunk-T733LS62.mjs} +23 -4
  8. package/dist/{cli-action-CXIHOVAC.mjs → cli-action-FV4G4OB6.mjs} +3 -3
  9. package/dist/{cli-action-3CWN7PBE.mjs → cli-action-HYSWE7F4.mjs} +3 -3
  10. package/dist/{cli-action-MLFCIW2O.mjs → cli-action-VIQZSWSP.mjs} +3 -3
  11. package/dist/{cli-action-E7UGP4KE.mjs → cli-action-W7TESWAV.mjs} +6 -8
  12. package/dist/cli.js +236 -191
  13. package/dist/cli.mjs +1 -1
  14. package/dist/console-report-AP4JYNQY.mjs +74 -0
  15. package/dist/html-report-ULELSIYG.mjs +73 -0
  16. package/dist/index.d.mts +69 -337
  17. package/dist/index.d.ts +69 -337
  18. package/dist/index.js +90 -452
  19. package/dist/index.mjs +9 -157
  20. package/dist/interactive-setup-JGFBFI3M.mjs +75 -0
  21. package/dist/{orchestrator-3ERQS3NW.mjs → orchestrator-QNE2E4TE.mjs} +2 -2
  22. package/dist/summary-GQRWW3A2.mjs +7 -0
  23. package/dist/summary-JTBS7CPM.mjs +7 -0
  24. package/dist/summary-TZFB6ZFM.mjs +7 -0
  25. package/package.json +2 -2
  26. package/src/__tests__/file-classification.fixtures.ts +57 -0
  27. package/src/__tests__/file-classification.test.ts +24 -929
  28. package/src/__tests__/provider.test.ts +6 -72
  29. package/src/classifier.ts +42 -42
  30. package/src/cli-action.ts +11 -6
  31. package/src/index.ts +30 -27
  32. package/src/provider.ts +1 -1
  33. package/src/summary.ts +65 -10
  34. package/dist/__tests__/analyzer.test.d.ts +0 -2
  35. package/dist/__tests__/analyzer.test.d.ts.map +0 -1
  36. package/dist/__tests__/analyzer.test.js +0 -198
  37. package/dist/__tests__/analyzer.test.js.map +0 -1
  38. package/dist/__tests__/auto-detection.test.d.ts +0 -2
  39. package/dist/__tests__/auto-detection.test.d.ts.map +0 -1
  40. package/dist/__tests__/auto-detection.test.js +0 -132
  41. package/dist/__tests__/auto-detection.test.js.map +0 -1
  42. package/dist/__tests__/cluster-detector.test.d.ts +0 -2
  43. package/dist/__tests__/cluster-detector.test.d.ts.map +0 -1
  44. package/dist/__tests__/cluster-detector.test.js +0 -121
  45. package/dist/__tests__/cluster-detector.test.js.map +0 -1
  46. package/dist/__tests__/contract.test.d.ts +0 -2
  47. package/dist/__tests__/contract.test.d.ts.map +0 -1
  48. package/dist/__tests__/contract.test.js +0 -59
  49. package/dist/__tests__/contract.test.js.map +0 -1
  50. package/dist/__tests__/enhanced-cohesion.test.d.ts +0 -2
  51. package/dist/__tests__/enhanced-cohesion.test.d.ts.map +0 -1
  52. package/dist/__tests__/enhanced-cohesion.test.js +0 -119
  53. package/dist/__tests__/enhanced-cohesion.test.js.map +0 -1
  54. package/dist/__tests__/file-classification.test.d.ts +0 -2
  55. package/dist/__tests__/file-classification.test.d.ts.map +0 -1
  56. package/dist/__tests__/file-classification.test.js +0 -749
  57. package/dist/__tests__/file-classification.test.js.map +0 -1
  58. package/dist/__tests__/fragmentation-advanced.test.d.ts +0 -2
  59. package/dist/__tests__/fragmentation-advanced.test.d.ts.map +0 -1
  60. package/dist/__tests__/fragmentation-advanced.test.js +0 -44
  61. package/dist/__tests__/fragmentation-advanced.test.js.map +0 -1
  62. package/dist/__tests__/fragmentation-coupling.test.d.ts +0 -2
  63. package/dist/__tests__/fragmentation-coupling.test.d.ts.map +0 -1
  64. package/dist/__tests__/fragmentation-coupling.test.js +0 -52
  65. package/dist/__tests__/fragmentation-coupling.test.js.map +0 -1
  66. package/dist/__tests__/fragmentation-log.test.d.ts +0 -2
  67. package/dist/__tests__/fragmentation-log.test.d.ts.map +0 -1
  68. package/dist/__tests__/fragmentation-log.test.js +0 -29
  69. package/dist/__tests__/fragmentation-log.test.js.map +0 -1
  70. package/dist/__tests__/provider.test.d.ts +0 -2
  71. package/dist/__tests__/provider.test.d.ts.map +0 -1
  72. package/dist/__tests__/provider.test.js +0 -72
  73. package/dist/__tests__/provider.test.js.map +0 -1
  74. package/dist/__tests__/remediation.test.d.ts +0 -2
  75. package/dist/__tests__/remediation.test.d.ts.map +0 -1
  76. package/dist/__tests__/remediation.test.js +0 -61
  77. package/dist/__tests__/remediation.test.js.map +0 -1
  78. package/dist/__tests__/scoring.test.d.ts +0 -2
  79. package/dist/__tests__/scoring.test.d.ts.map +0 -1
  80. package/dist/__tests__/scoring.test.js +0 -298
  81. package/dist/__tests__/scoring.test.js.map +0 -1
  82. package/dist/__tests__/structural-cohesion.test.d.ts +0 -2
  83. package/dist/__tests__/structural-cohesion.test.d.ts.map +0 -1
  84. package/dist/__tests__/structural-cohesion.test.js +0 -35
  85. package/dist/__tests__/structural-cohesion.test.js.map +0 -1
  86. package/dist/analyzer.d.ts +0 -37
  87. package/dist/analyzer.d.ts.map +0 -1
  88. package/dist/analyzer.js +0 -283
  89. package/dist/analyzer.js.map +0 -1
  90. package/dist/analyzers/python-context.d.ts +0 -38
  91. package/dist/analyzers/python-context.d.ts.map +0 -1
  92. package/dist/analyzers/python-context.js +0 -234
  93. package/dist/analyzers/python-context.js.map +0 -1
  94. package/dist/ast-utils.d.ts +0 -16
  95. package/dist/ast-utils.d.ts.map +0 -1
  96. package/dist/ast-utils.js +0 -81
  97. package/dist/ast-utils.js.map +0 -1
  98. package/dist/chunk-22ZO4EKZ.mjs +0 -1297
  99. package/dist/chunk-2HE27YEV.mjs +0 -1739
  100. package/dist/chunk-45P4RDYP.mjs +0 -607
  101. package/dist/chunk-474DEGWW.mjs +0 -1792
  102. package/dist/chunk-4SYIJ7CU.mjs +0 -1538
  103. package/dist/chunk-4U4LDWGF.mjs +0 -360
  104. package/dist/chunk-4XQVYYPC.mjs +0 -1470
  105. package/dist/chunk-5CLU3HYU.mjs +0 -1475
  106. package/dist/chunk-5K73Q3OQ.mjs +0 -1520
  107. package/dist/chunk-5N5DCJOV.mjs +0 -583
  108. package/dist/chunk-6AVS4KTM.mjs +0 -1536
  109. package/dist/chunk-6FQYIG6I.mjs +0 -1298
  110. package/dist/chunk-6I4552YB.mjs +0 -1467
  111. package/dist/chunk-6LPITDKG.mjs +0 -1539
  112. package/dist/chunk-72QC5QUS.mjs +0 -549
  113. package/dist/chunk-736QSHJP.mjs +0 -1807
  114. package/dist/chunk-7LUSCLGR.mjs +0 -2058
  115. package/dist/chunk-7VK3XTSH.mjs +0 -1756
  116. package/dist/chunk-7ZEJGWLN.mjs +0 -1363
  117. package/dist/chunk-AECWO7NQ.mjs +0 -1539
  118. package/dist/chunk-AEK3MZC5.mjs +0 -709
  119. package/dist/chunk-AJC3FR6G.mjs +0 -1509
  120. package/dist/chunk-AMPK6SWS.mjs +0 -1754
  121. package/dist/chunk-BA7QGUHN.mjs +0 -1722
  122. package/dist/chunk-BCEZGRXI.mjs +0 -1297
  123. package/dist/chunk-BD4NWUVG.mjs +0 -1242
  124. package/dist/chunk-BEZPBI5C.mjs +0 -1829
  125. package/dist/chunk-BHCRDEE4.mjs +0 -1745
  126. package/dist/chunk-BW463GQB.mjs +0 -1767
  127. package/dist/chunk-CAX2MOUZ.mjs +0 -1801
  128. package/dist/chunk-CBWM3EK5.mjs +0 -1854
  129. package/dist/chunk-CCBNKQYB.mjs +0 -1812
  130. package/dist/chunk-CDIVYADN.mjs +0 -2110
  131. package/dist/chunk-CVGIDSMN.mjs +0 -1522
  132. package/dist/chunk-D25B5LZR.mjs +0 -1739
  133. package/dist/chunk-D3SIHB2V.mjs +0 -2118
  134. package/dist/chunk-DD7UVNE3.mjs +0 -678
  135. package/dist/chunk-DMRZMS2U.mjs +0 -964
  136. package/dist/chunk-DXG5NIYL.mjs +0 -1527
  137. package/dist/chunk-EBXG2Q5Y.mjs +0 -2059
  138. package/dist/chunk-EH3PMNZQ.mjs +0 -569
  139. package/dist/chunk-EMYD7NS6.mjs +0 -137
  140. package/dist/chunk-EVX2W2BK.mjs +0 -1896
  141. package/dist/chunk-EWFR366Y.mjs +0 -1740
  142. package/dist/chunk-EX7HCWAO.mjs +0 -625
  143. package/dist/chunk-FNPSK3CG.mjs +0 -1760
  144. package/dist/chunk-FO6YT6RG.mjs +0 -1751
  145. package/dist/chunk-FYI56A5M.mjs +0 -1892
  146. package/dist/chunk-G3CCJCBI.mjs +0 -1521
  147. package/dist/chunk-G7PO3DNK.mjs +0 -1072
  148. package/dist/chunk-GFADGYXZ.mjs +0 -1752
  149. package/dist/chunk-GTRIBVS6.mjs +0 -1467
  150. package/dist/chunk-GXTGOLZT.mjs +0 -92
  151. package/dist/chunk-H4HWBQU6.mjs +0 -1530
  152. package/dist/chunk-HDFXSEFW.mjs +0 -605
  153. package/dist/chunk-HOUDVRG2.mjs +0 -1422
  154. package/dist/chunk-HQNHM2X7.mjs +0 -997
  155. package/dist/chunk-I54HL4FZ.mjs +0 -781
  156. package/dist/chunk-I77HFFZU.mjs +0 -1876
  157. package/dist/chunk-IKRP7ECY.mjs +0 -1754
  158. package/dist/chunk-ILMLGJGI.mjs +0 -1295
  159. package/dist/chunk-IPIE5TXJ.mjs +0 -1741
  160. package/dist/chunk-IRWCPDWD.mjs +0 -779
  161. package/dist/chunk-J3MUOWHC.mjs +0 -1747
  162. package/dist/chunk-J5TA3AZU.mjs +0 -1795
  163. package/dist/chunk-JH535NPP.mjs +0 -1619
  164. package/dist/chunk-JUHHOSHG.mjs +0 -1808
  165. package/dist/chunk-JZ2SE4DB.mjs +0 -1116
  166. package/dist/chunk-K2WFOBAZ.mjs +0 -1821
  167. package/dist/chunk-K6U64EL3.mjs +0 -517
  168. package/dist/chunk-KDUUZQBK.mjs +0 -1692
  169. package/dist/chunk-KGFWKSGJ.mjs +0 -1442
  170. package/dist/chunk-KGVMS4R5.mjs +0 -1750
  171. package/dist/chunk-KWIS5FQP.mjs +0 -1739
  172. package/dist/chunk-KYSZF5N6.mjs +0 -1876
  173. package/dist/chunk-LERPI33Y.mjs +0 -2060
  174. package/dist/chunk-M64RHH4D.mjs +0 -1896
  175. package/dist/chunk-MBE4AQP5.mjs +0 -1362
  176. package/dist/chunk-MR7WXHIE.mjs +0 -1833
  177. package/dist/chunk-MZP3G7TF.mjs +0 -2118
  178. package/dist/chunk-N2GQWNFG.mjs +0 -1527
  179. package/dist/chunk-N6XBOOVA.mjs +0 -564
  180. package/dist/chunk-NJUW6VED.mjs +0 -610
  181. package/dist/chunk-NOHK5DLU.mjs +0 -2173
  182. package/dist/chunk-NQA3F2HJ.mjs +0 -1532
  183. package/dist/chunk-NXXQ2U73.mjs +0 -1467
  184. package/dist/chunk-OP4G6GLN.mjs +0 -1876
  185. package/dist/chunk-ORLC5Y4J.mjs +0 -1787
  186. package/dist/chunk-OTCQL7DY.mjs +0 -2045
  187. package/dist/chunk-OUYSZZ7X.mjs +0 -1846
  188. package/dist/chunk-OZE3FVZT.mjs +0 -1089
  189. package/dist/chunk-P3T3H27S.mjs +0 -1895
  190. package/dist/chunk-P5YV5WIX.mjs +0 -1803
  191. package/dist/chunk-P74BO725.mjs +0 -1296
  192. package/dist/chunk-PDN74MG3.mjs +0 -1834
  193. package/dist/chunk-PJD4VCIH.mjs +0 -1722
  194. package/dist/chunk-PVVCCE6W.mjs +0 -755
  195. package/dist/chunk-PVVMK56C.mjs +0 -1793
  196. package/dist/chunk-Q2GDZ2FZ.mjs +0 -1794
  197. package/dist/chunk-QDGPR3L6.mjs +0 -1518
  198. package/dist/chunk-RQCIJO5Z.mjs +0 -1116
  199. package/dist/chunk-RRB2C34Q.mjs +0 -1738
  200. package/dist/chunk-RYIB5CWD.mjs +0 -781
  201. package/dist/chunk-S6OPP4L5.mjs +0 -1791
  202. package/dist/chunk-SAVOSPM3.mjs +0 -1522
  203. package/dist/chunk-SFK6XTJE.mjs +0 -2110
  204. package/dist/chunk-SIX4KMF2.mjs +0 -1468
  205. package/dist/chunk-SPAM2YJE.mjs +0 -1537
  206. package/dist/chunk-T6ZCOPPI.mjs +0 -538
  207. package/dist/chunk-TPF75CNP.mjs +0 -581
  208. package/dist/chunk-TWWPY7FD.mjs +0 -1754
  209. package/dist/chunk-U5R2FTCR.mjs +0 -1803
  210. package/dist/chunk-UG7OPVHB.mjs +0 -1521
  211. package/dist/chunk-UMZTAWDA.mjs +0 -1812
  212. package/dist/chunk-UU4HZ7ZT.mjs +0 -1849
  213. package/dist/chunk-UXC6QUZ7.mjs +0 -1801
  214. package/dist/chunk-VBWXHKGD.mjs +0 -1895
  215. package/dist/chunk-VIJTZPBI.mjs +0 -1470
  216. package/dist/chunk-VLV6MXPL.mjs +0 -1750
  217. package/dist/chunk-VTALAPQZ.mjs +0 -1241
  218. package/dist/chunk-W2KNBN6W.mjs +0 -1849
  219. package/dist/chunk-W37E7MW5.mjs +0 -1403
  220. package/dist/chunk-W76FEISE.mjs +0 -1538
  221. package/dist/chunk-WCFQYXQA.mjs +0 -1532
  222. package/dist/chunk-WKOZOHOU.mjs +0 -2060
  223. package/dist/chunk-WTQJNY4U.mjs +0 -1785
  224. package/dist/chunk-XBFM2Z4O.mjs +0 -1792
  225. package/dist/chunk-XIXAWCMS.mjs +0 -1760
  226. package/dist/chunk-XTAXUNQN.mjs +0 -1742
  227. package/dist/chunk-XY77XABG.mjs +0 -1545
  228. package/dist/chunk-XZ645X5U.mjs +0 -1425
  229. package/dist/chunk-Y6FXYEAI.mjs +0 -10
  230. package/dist/chunk-YCGDIGOG.mjs +0 -1467
  231. package/dist/chunk-YYB6NZE3.mjs +0 -1869
  232. package/dist/chunk-Z5WY6A4P.mjs +0 -1754
  233. package/dist/chunk-ZAMFWKIB.mjs +0 -1842
  234. package/dist/classifier.d.ts +0 -114
  235. package/dist/classifier.d.ts.map +0 -1
  236. package/dist/classifier.js +0 -439
  237. package/dist/classifier.js.map +0 -1
  238. package/dist/cli-action-SA7SCYNV.mjs +0 -95
  239. package/dist/cli-action-VCXBZGZP.mjs +0 -95
  240. package/dist/cli-action-YAJOJCXJ.mjs +0 -95
  241. package/dist/cli.d.ts.map +0 -1
  242. package/dist/cli.js.map +0 -1
  243. package/dist/cluster-detector.d.ts +0 -8
  244. package/dist/cluster-detector.d.ts.map +0 -1
  245. package/dist/cluster-detector.js +0 -70
  246. package/dist/cluster-detector.js.map +0 -1
  247. package/dist/defaults.d.ts +0 -7
  248. package/dist/defaults.d.ts.map +0 -1
  249. package/dist/defaults.js +0 -54
  250. package/dist/defaults.js.map +0 -1
  251. package/dist/graph-builder.d.ts +0 -33
  252. package/dist/graph-builder.d.ts.map +0 -1
  253. package/dist/graph-builder.js +0 -225
  254. package/dist/graph-builder.js.map +0 -1
  255. package/dist/index.d.ts.map +0 -1
  256. package/dist/index.js.map +0 -1
  257. package/dist/metrics.d.ts +0 -34
  258. package/dist/metrics.d.ts.map +0 -1
  259. package/dist/metrics.js +0 -170
  260. package/dist/metrics.js.map +0 -1
  261. package/dist/orchestrator-3L3NAZYP.mjs +0 -10
  262. package/dist/orchestrator-5AL3XBPZ.mjs +0 -10
  263. package/dist/orchestrator-KMAKMHTD.mjs +0 -10
  264. package/dist/orchestrator-MONOZHVW.mjs +0 -10
  265. package/dist/orchestrator-R6MZT4Z2.mjs +0 -10
  266. package/dist/orchestrator-ZR7JSKWI.mjs +0 -10
  267. package/dist/provider.d.ts +0 -6
  268. package/dist/provider.d.ts.map +0 -1
  269. package/dist/provider.js +0 -48
  270. package/dist/provider.js.map +0 -1
  271. package/dist/python-context-3GZKN3LR.mjs +0 -162
  272. package/dist/python-context-GOH747QU.mjs +0 -202
  273. package/dist/python-context-O2EN3M6Z.mjs +0 -162
  274. package/dist/python-context-PAETRLDY.mjs +0 -185
  275. package/dist/python-context-TBI5FVFY.mjs +0 -203
  276. package/dist/python-context-UOPTQH44.mjs +0 -192
  277. package/dist/remediation.d.ts +0 -25
  278. package/dist/remediation.d.ts.map +0 -1
  279. package/dist/remediation.js +0 -98
  280. package/dist/remediation.js.map +0 -1
  281. package/dist/scoring.d.ts +0 -9
  282. package/dist/scoring.d.ts.map +0 -1
  283. package/dist/scoring.js +0 -142
  284. package/dist/scoring.js.map +0 -1
  285. package/dist/semantic-analysis.d.ts +0 -33
  286. package/dist/semantic-analysis.d.ts.map +0 -1
  287. package/dist/semantic-analysis.js +0 -303
  288. package/dist/semantic-analysis.js.map +0 -1
  289. package/dist/summary-7PZVW72O.mjs +0 -7
  290. package/dist/summary-LKUCJAIS.mjs +0 -7
  291. package/dist/summary.d.ts +0 -6
  292. package/dist/summary.d.ts.map +0 -1
  293. package/dist/summary.js +0 -92
  294. package/dist/summary.js.map +0 -1
  295. package/dist/types.d.ts +0 -124
  296. package/dist/types.d.ts.map +0 -1
  297. package/dist/types.js +0 -2
  298. package/dist/types.js.map +0 -1
  299. package/dist/utils/output-formatter.d.ts +0 -14
  300. package/dist/utils/output-formatter.d.ts.map +0 -1
  301. package/dist/utils/output-formatter.js +0 -338
  302. package/dist/utils/output-formatter.js.map +0 -1
@@ -1,1801 +0,0 @@
1
- import {
2
- calculateImportDepthFromEdges,
3
- detectGraphCycles,
4
- getTransitiveDependenciesFromEdges
5
- } from "./chunk-64U3PNO3.mjs";
6
-
7
- // src/utils/string-utils.ts
8
- function singularize(word) {
9
- const irregulars = {
10
- people: "person",
11
- children: "child",
12
- men: "man",
13
- women: "woman"
14
- };
15
- if (irregulars[word]) return irregulars[word];
16
- if (word.endsWith("ies")) return word.slice(0, -3) + "y";
17
- if (word.endsWith("ses")) return word.slice(0, -2);
18
- if (word.endsWith("s") && word.length > 3) return word.slice(0, -1);
19
- return word;
20
- }
21
-
22
- // src/semantic-analysis.ts
23
- function buildCoUsageMatrix(graph) {
24
- const coUsageMatrix = /* @__PURE__ */ new Map();
25
- for (const [, node] of graph.nodes) {
26
- const imports = node.imports;
27
- for (let i = 0; i < imports.length; i++) {
28
- const fileA = imports[i];
29
- if (!coUsageMatrix.has(fileA)) coUsageMatrix.set(fileA, /* @__PURE__ */ new Map());
30
- for (let j = i + 1; j < imports.length; j++) {
31
- const fileB = imports[j];
32
- const fileAUsage = coUsageMatrix.get(fileA);
33
- fileAUsage.set(fileB, (fileAUsage.get(fileB) || 0) + 1);
34
- if (!coUsageMatrix.has(fileB)) coUsageMatrix.set(fileB, /* @__PURE__ */ new Map());
35
- const fileBUsage = coUsageMatrix.get(fileB);
36
- fileBUsage.set(fileA, (fileBUsage.get(fileA) || 0) + 1);
37
- }
38
- }
39
- }
40
- return coUsageMatrix;
41
- }
42
- function buildTypeGraph(graph) {
43
- const typeGraph = /* @__PURE__ */ new Map();
44
- for (const [file, node] of graph.nodes) {
45
- for (const exp of node.exports) {
46
- if (exp.typeReferences) {
47
- for (const typeRef of exp.typeReferences) {
48
- if (!typeGraph.has(typeRef)) typeGraph.set(typeRef, /* @__PURE__ */ new Set());
49
- typeGraph.get(typeRef).add(file);
50
- }
51
- }
52
- }
53
- }
54
- return typeGraph;
55
- }
56
- function findSemanticClusters(coUsageMatrix, minCoUsage = 3) {
57
- const clusters = /* @__PURE__ */ new Map();
58
- const visited = /* @__PURE__ */ new Set();
59
- for (const [file, coUsages] of coUsageMatrix) {
60
- if (visited.has(file)) continue;
61
- const cluster = [file];
62
- visited.add(file);
63
- for (const [relatedFile, count] of coUsages) {
64
- if (count >= minCoUsage && !visited.has(relatedFile)) {
65
- cluster.push(relatedFile);
66
- visited.add(relatedFile);
67
- }
68
- }
69
- if (cluster.length > 1) clusters.set(file, cluster);
70
- }
71
- return clusters;
72
- }
73
- function inferDomainFromSemantics(file, exportName, graph, coUsageMatrix, typeGraph, exportTypeRefs) {
74
- const domainSignals = /* @__PURE__ */ new Map();
75
- const coUsages = coUsageMatrix.get(file) || /* @__PURE__ */ new Map();
76
- const strongCoUsages = Array.from(coUsages.entries()).filter(([, count]) => count >= 3).map(([coFile]) => coFile);
77
- for (const coFile of strongCoUsages) {
78
- const coNode = graph.nodes.get(coFile);
79
- if (coNode) {
80
- for (const exp of coNode.exports) {
81
- if (exp.inferredDomain && exp.inferredDomain !== "unknown") {
82
- const domain = exp.inferredDomain;
83
- if (!domainSignals.has(domain)) {
84
- domainSignals.set(domain, {
85
- coUsage: false,
86
- typeReference: false,
87
- exportName: false,
88
- importPath: false,
89
- folderStructure: false
90
- });
91
- }
92
- domainSignals.get(domain).coUsage = true;
93
- }
94
- }
95
- }
96
- }
97
- if (exportTypeRefs) {
98
- for (const typeRef of exportTypeRefs) {
99
- const filesWithType = typeGraph.get(typeRef);
100
- if (filesWithType) {
101
- for (const typeFile of filesWithType) {
102
- if (typeFile === file) continue;
103
- const typeNode = graph.nodes.get(typeFile);
104
- if (typeNode) {
105
- for (const exp of typeNode.exports) {
106
- if (exp.inferredDomain && exp.inferredDomain !== "unknown") {
107
- const domain = exp.inferredDomain;
108
- if (!domainSignals.has(domain)) {
109
- domainSignals.set(domain, {
110
- coUsage: false,
111
- typeReference: false,
112
- exportName: false,
113
- importPath: false,
114
- folderStructure: false
115
- });
116
- }
117
- domainSignals.get(domain).typeReference = true;
118
- }
119
- }
120
- }
121
- }
122
- }
123
- }
124
- }
125
- const assignments = [];
126
- for (const [domain, signals] of domainSignals) {
127
- const confidence = calculateDomainConfidence(signals);
128
- if (confidence >= 0.3) assignments.push({ domain, confidence, signals });
129
- }
130
- assignments.sort((a, b) => b.confidence - a.confidence);
131
- return assignments;
132
- }
133
- function calculateDomainConfidence(signals) {
134
- const weights = {
135
- coUsage: 0.35,
136
- typeReference: 0.3,
137
- exportName: 0.15,
138
- importPath: 0.1,
139
- folderStructure: 0.1
140
- };
141
- let confidence = 0;
142
- if (signals.coUsage) confidence += weights.coUsage;
143
- if (signals.typeReference) confidence += weights.typeReference;
144
- if (signals.exportName) confidence += weights.exportName;
145
- if (signals.importPath) confidence += weights.importPath;
146
- if (signals.folderStructure) confidence += weights.folderStructure;
147
- return confidence;
148
- }
149
- function extractExports(content, filePath, domainOptions, fileImports) {
150
- const exports = [];
151
- const patterns = [
152
- /export\s+function\s+(\w+)/g,
153
- /export\s+class\s+(\w+)/g,
154
- /export\s+const\s+(\w+)/g,
155
- /export\s+type\s+(\w+)/g,
156
- /export\s+interface\s+(\w+)/g,
157
- /export\s+default/g
158
- ];
159
- const types = [
160
- "function",
161
- "class",
162
- "const",
163
- "type",
164
- "interface",
165
- "default"
166
- ];
167
- patterns.forEach((pattern, index) => {
168
- let match;
169
- while ((match = pattern.exec(content)) !== null) {
170
- const name = match[1] || "default";
171
- const type = types[index];
172
- const inferredDomain = inferDomain(
173
- name,
174
- filePath,
175
- domainOptions,
176
- fileImports
177
- );
178
- exports.push({ name, type, inferredDomain });
179
- }
180
- });
181
- return exports;
182
- }
183
- function inferDomain(name, filePath, domainOptions, fileImports) {
184
- const lower = name.toLowerCase();
185
- const tokens = Array.from(
186
- new Set(
187
- lower.replace(/([a-z0-9])([A-Z])/g, "$1 $2").replace(/[^a-z0-9]+/gi, " ").split(" ").filter(Boolean)
188
- )
189
- );
190
- const defaultKeywords = [
191
- "authentication",
192
- "authorization",
193
- "payment",
194
- "invoice",
195
- "customer",
196
- "product",
197
- "order",
198
- "cart",
199
- "user",
200
- "admin",
201
- "repository",
202
- "controller",
203
- "service",
204
- "config",
205
- "model",
206
- "view",
207
- "auth"
208
- ];
209
- const domainKeywords = domainOptions?.domainKeywords?.length ? [...domainOptions.domainKeywords, ...defaultKeywords] : defaultKeywords;
210
- for (const keyword of domainKeywords) {
211
- if (tokens.includes(keyword)) return keyword;
212
- }
213
- for (const keyword of domainKeywords) {
214
- if (lower.includes(keyword)) return keyword;
215
- }
216
- if (fileImports) {
217
- for (const importPath of fileImports) {
218
- const segments = importPath.split("/");
219
- for (const segment of segments) {
220
- const segLower = segment.toLowerCase();
221
- const singularSegment = singularize(segLower);
222
- for (const keyword of domainKeywords) {
223
- if (singularSegment === keyword || segLower === keyword || segLower.includes(keyword))
224
- return keyword;
225
- }
226
- }
227
- }
228
- }
229
- if (filePath) {
230
- const segments = filePath.split("/");
231
- for (const segment of segments) {
232
- const segLower = segment.toLowerCase();
233
- const singularSegment = singularize(segLower);
234
- for (const keyword of domainKeywords) {
235
- if (singularSegment === keyword || segLower === keyword) return keyword;
236
- }
237
- }
238
- }
239
- return "unknown";
240
- }
241
- function getCoUsageData(file, coUsageMatrix) {
242
- return {
243
- file,
244
- coImportedWith: coUsageMatrix.get(file) || /* @__PURE__ */ new Map(),
245
- sharedImporters: []
246
- };
247
- }
248
- function findConsolidationCandidates(graph, coUsageMatrix, typeGraph, minCoUsage = 5, minSharedTypes = 2) {
249
- const candidates = [];
250
- for (const [fileA, coUsages] of coUsageMatrix) {
251
- const nodeA = graph.nodes.get(fileA);
252
- if (!nodeA) continue;
253
- for (const [fileB, count] of coUsages) {
254
- if (fileB <= fileA || count < minCoUsage) continue;
255
- const nodeB = graph.nodes.get(fileB);
256
- if (!nodeB) continue;
257
- const typesA = new Set(
258
- nodeA.exports.flatMap((e) => e.typeReferences || [])
259
- );
260
- const typesB = new Set(
261
- nodeB.exports.flatMap((e) => e.typeReferences || [])
262
- );
263
- const sharedTypes = Array.from(typesA).filter((t) => typesB.has(t));
264
- if (sharedTypes.length >= minSharedTypes || count >= minCoUsage * 2) {
265
- candidates.push({
266
- files: [fileA, fileB],
267
- reason: `High co-usage (${count}x)`,
268
- strength: count / 10
269
- });
270
- }
271
- }
272
- }
273
- return candidates.sort((a, b) => b.strength - a.strength);
274
- }
275
-
276
- // src/metrics.ts
277
- import { calculateImportSimilarity } from "@aiready/core";
278
-
279
- // src/ast-utils.ts
280
- import { parseFileExports } from "@aiready/core";
281
- function extractExportsWithAST(content, filePath, domainOptions, fileImports) {
282
- try {
283
- const { exports: astExports } = parseFileExports(content, filePath);
284
- if (astExports.length === 0 && !isTestFile(filePath)) {
285
- return extractExports(content, filePath, domainOptions, fileImports);
286
- }
287
- return astExports.map((exp) => ({
288
- name: exp.name,
289
- type: exp.type,
290
- inferredDomain: inferDomain(
291
- exp.name,
292
- filePath,
293
- domainOptions,
294
- fileImports
295
- ),
296
- imports: exp.imports,
297
- dependencies: exp.dependencies,
298
- typeReferences: exp.typeReferences
299
- }));
300
- } catch {
301
- return extractExports(content, filePath, domainOptions, fileImports);
302
- }
303
- }
304
- function isTestFile(filePath) {
305
- const lower = filePath.toLowerCase();
306
- return lower.includes(".test.") || lower.includes(".spec.") || lower.includes("/__tests__/") || lower.includes("/tests/") || lower.includes("/test/") || lower.includes("test-") || lower.includes("-test") || lower.includes("/__mocks__/") || lower.includes("/mocks/") || lower.includes("/fixtures/") || lower.includes(".mock.") || lower.includes(".fixture.") || lower.includes("/test-utils/");
307
- }
308
-
309
- // src/metrics.ts
310
- function calculateEnhancedCohesion(exports, filePath, options) {
311
- if (exports.length <= 1) return 1;
312
- if (filePath && isTestFile(filePath)) return 1;
313
- const domains = exports.map((e) => e.inferredDomain || "unknown");
314
- const domainCounts = /* @__PURE__ */ new Map();
315
- for (const domain of domains)
316
- domainCounts.set(domain, (domainCounts.get(domain) || 0) + 1);
317
- if (domainCounts.size === 1 && domains[0] !== "unknown") {
318
- if (!options?.weights) return 1;
319
- }
320
- const probs = Array.from(domainCounts.values()).map(
321
- (count) => count / exports.length
322
- );
323
- let domainEntropy = 0;
324
- for (const prob of probs) {
325
- if (prob > 0) domainEntropy -= prob * Math.log2(prob);
326
- }
327
- const maxEntropy = Math.log2(Math.max(2, domainCounts.size));
328
- const domainScore = 1 - domainEntropy / maxEntropy;
329
- let importScoreTotal = 0;
330
- let pairsWithData = 0;
331
- let anyImportData = false;
332
- for (let i = 0; i < exports.length; i++) {
333
- for (let j = i + 1; j < exports.length; j++) {
334
- const exp1Imports = exports[i].imports;
335
- const exp2Imports = exports[j].imports;
336
- if (exp1Imports || exp2Imports) {
337
- anyImportData = true;
338
- const sim = calculateImportSimilarity(
339
- { ...exports[i], imports: exp1Imports || [] },
340
- { ...exports[j], imports: exp2Imports || [] }
341
- );
342
- importScoreTotal += sim;
343
- pairsWithData++;
344
- }
345
- }
346
- }
347
- const avgImportScore = pairsWithData > 0 ? importScoreTotal / pairsWithData : 0;
348
- let score = anyImportData ? domainScore * 0.4 + avgImportScore * 0.6 : domainScore;
349
- if (anyImportData && score === 0 && domainScore === 0) {
350
- score = 0.1;
351
- }
352
- let structuralScore = 0;
353
- for (const exp of exports) {
354
- if (exp.dependencies && exp.dependencies.length > 0) {
355
- structuralScore += 1;
356
- }
357
- }
358
- if (structuralScore > 0) {
359
- score = Math.min(1, score + 0.1);
360
- }
361
- if (!options?.weights && !anyImportData && domainCounts.size === 1) return 1;
362
- return score;
363
- }
364
- function calculateStructuralCohesionFromCoUsage(file, coUsageMatrix) {
365
- if (!coUsageMatrix) return 1;
366
- const coUsages = coUsageMatrix.get(file);
367
- if (!coUsages || coUsages.size === 0) return 1;
368
- let total = 0;
369
- for (const count of coUsages.values()) total += count;
370
- if (total === 0) return 1;
371
- const probs = [];
372
- for (const count of coUsages.values()) {
373
- if (count > 0) probs.push(count / total);
374
- }
375
- if (probs.length <= 1) return 1;
376
- let entropy = 0;
377
- for (const prob of probs) {
378
- entropy -= prob * Math.log2(prob);
379
- }
380
- const maxEntropy = Math.log2(probs.length);
381
- return maxEntropy > 0 ? 1 - entropy / maxEntropy : 1;
382
- }
383
- function calculateFragmentation(files, domain, options) {
384
- if (files.length <= 1) return 0;
385
- const directories = new Set(
386
- files.map((file) => file.split("/").slice(0, -1).join("/"))
387
- );
388
- const uniqueDirs = directories.size;
389
- let score = options?.useLogScale ? uniqueDirs <= 1 ? 0 : Math.log(uniqueDirs) / Math.log(options.logBase || Math.E) / (Math.log(files.length) / Math.log(options.logBase || Math.E)) : (uniqueDirs - 1) / (files.length - 1);
390
- if (options?.sharedImportRatio && options.sharedImportRatio > 0.5) {
391
- const discount = (options.sharedImportRatio - 0.5) * 0.4;
392
- score = score * (1 - discount);
393
- }
394
- return score;
395
- }
396
- function calculatePathEntropy(files) {
397
- if (!files || files.length === 0) return 0;
398
- const dirCounts = /* @__PURE__ */ new Map();
399
- for (const file of files) {
400
- const dir = file.split("/").slice(0, -1).join("/") || ".";
401
- dirCounts.set(dir, (dirCounts.get(dir) || 0) + 1);
402
- }
403
- const counts = Array.from(dirCounts.values());
404
- if (counts.length <= 1) return 0;
405
- const total = counts.reduce((sum, value) => sum + value, 0);
406
- let entropy = 0;
407
- for (const count of counts) {
408
- const prob = count / total;
409
- entropy -= prob * Math.log2(prob);
410
- }
411
- const maxEntropy = Math.log2(counts.length);
412
- return maxEntropy > 0 ? entropy / maxEntropy : 0;
413
- }
414
- function calculateDirectoryDistance(files) {
415
- if (!files || files.length <= 1) return 0;
416
- const pathSegments = (pathStr) => pathStr.split("/").filter(Boolean);
417
- const commonAncestorDepth = (pathA, pathB) => {
418
- const minLen = Math.min(pathA.length, pathB.length);
419
- let i = 0;
420
- while (i < minLen && pathA[i] === pathB[i]) i++;
421
- return i;
422
- };
423
- let totalNormalized = 0;
424
- let comparisons = 0;
425
- for (let i = 0; i < files.length; i++) {
426
- for (let j = i + 1; j < files.length; j++) {
427
- const segA = pathSegments(files[i]);
428
- const segB = pathSegments(files[j]);
429
- const shared = commonAncestorDepth(segA, segB);
430
- const maxDepth = Math.max(segA.length, segB.length);
431
- totalNormalized += 1 - (maxDepth > 0 ? shared / maxDepth : 0);
432
- comparisons++;
433
- }
434
- }
435
- return comparisons > 0 ? totalNormalized / comparisons : 0;
436
- }
437
-
438
- // src/graph-builder.ts
439
- import { estimateTokens, parseFileExports as parseFileExports2 } from "@aiready/core";
440
- import { join, dirname, normalize } from "path";
441
- function resolveImport(source, importingFile, allFiles) {
442
- if (!source.startsWith(".") && !source.startsWith("/")) {
443
- if (allFiles.has(source)) return source;
444
- return null;
445
- }
446
- const dir = dirname(importingFile);
447
- const absolutePath = normalize(join(dir, source));
448
- if (allFiles.has(absolutePath)) return absolutePath;
449
- const extensions = [".ts", ".tsx", ".js", ".jsx"];
450
- for (const ext of extensions) {
451
- const withExt = absolutePath + ext;
452
- if (allFiles.has(withExt)) return withExt;
453
- }
454
- for (const ext of extensions) {
455
- const indexFile = normalize(join(absolutePath, `index${ext}`));
456
- if (allFiles.has(indexFile)) return indexFile;
457
- }
458
- return null;
459
- }
460
- function extractDomainKeywordsFromPaths(files) {
461
- const folderNames = /* @__PURE__ */ new Set();
462
- for (const { file } of files) {
463
- const segments = file.split("/");
464
- const skipFolders = /* @__PURE__ */ new Set([
465
- "src",
466
- "lib",
467
- "dist",
468
- "build",
469
- "node_modules",
470
- "test",
471
- "tests",
472
- "__tests__",
473
- "spec",
474
- "e2e",
475
- "scripts",
476
- "components",
477
- "utils",
478
- "helpers",
479
- "util",
480
- "helper",
481
- "api",
482
- "apis"
483
- ]);
484
- for (const segment of segments) {
485
- const normalized = segment.toLowerCase();
486
- if (normalized && !skipFolders.has(normalized) && !normalized.includes(".")) {
487
- folderNames.add(singularize(normalized));
488
- }
489
- }
490
- }
491
- return Array.from(folderNames);
492
- }
493
- function buildDependencyGraph(files, options) {
494
- const nodes = /* @__PURE__ */ new Map();
495
- const edges = /* @__PURE__ */ new Map();
496
- const autoDetectedKeywords = options?.domainKeywords ?? extractDomainKeywordsFromPaths(files);
497
- const allFilePaths = new Set(files.map((f) => f.file));
498
- for (const { file, content } of files) {
499
- const { imports: astImports } = parseFileExports2(content, file);
500
- const resolvedImports = astImports.map((i) => resolveImport(i.source, file, allFilePaths)).filter((path) => path !== null);
501
- const importSources = astImports.map((i) => i.source);
502
- const exports = extractExportsWithAST(
503
- content,
504
- file,
505
- { domainKeywords: autoDetectedKeywords },
506
- importSources
507
- );
508
- const tokenCost = estimateTokens(content);
509
- const linesOfCode = content.split("\n").length;
510
- nodes.set(file, {
511
- file,
512
- imports: importSources,
513
- exports,
514
- tokenCost,
515
- linesOfCode
516
- });
517
- edges.set(file, new Set(resolvedImports));
518
- }
519
- const graph = { nodes, edges };
520
- const coUsageMatrix = buildCoUsageMatrix(graph);
521
- const typeGraph = buildTypeGraph(graph);
522
- graph.coUsageMatrix = coUsageMatrix;
523
- graph.typeGraph = typeGraph;
524
- for (const [file, node] of nodes) {
525
- for (const exp of node.exports) {
526
- const semanticAssignments = inferDomainFromSemantics(
527
- file,
528
- exp.name,
529
- graph,
530
- coUsageMatrix,
531
- typeGraph,
532
- exp.typeReferences
533
- );
534
- exp.domains = semanticAssignments;
535
- if (semanticAssignments.length > 0) {
536
- exp.inferredDomain = semanticAssignments[0].domain;
537
- }
538
- }
539
- }
540
- return graph;
541
- }
542
- function calculateImportDepth(file, graph, visited = /* @__PURE__ */ new Set(), depth = 0) {
543
- return calculateImportDepthFromEdges(file, graph.edges, visited, depth);
544
- }
545
- function getTransitiveDependencies(file, graph, visited = /* @__PURE__ */ new Set()) {
546
- return getTransitiveDependenciesFromEdges(file, graph.edges, visited);
547
- }
548
- function calculateContextBudget(file, graph) {
549
- const node = graph.nodes.get(file);
550
- if (!node) return 0;
551
- let totalTokens = node.tokenCost;
552
- const deps = getTransitiveDependencies(file, graph);
553
- for (const dep of deps) {
554
- const depNode = graph.nodes.get(dep);
555
- if (depNode) {
556
- totalTokens += depNode.tokenCost;
557
- }
558
- }
559
- return totalTokens;
560
- }
561
- function detectCircularDependencies(graph) {
562
- return detectGraphCycles(graph.edges);
563
- }
564
-
565
- // src/heuristics.ts
566
- var BARREL_EXPORT_MIN_EXPORTS = 5;
567
- var BARREL_EXPORT_TOKEN_LIMIT = 1e3;
568
- var HANDLER_NAME_PATTERNS = [
569
- "handler",
570
- ".handler.",
571
- "-handler.",
572
- "lambda",
573
- ".lambda.",
574
- "-lambda."
575
- ];
576
- var SERVICE_NAME_PATTERNS = [
577
- "service",
578
- ".service.",
579
- "-service.",
580
- "_service."
581
- ];
582
- var EMAIL_NAME_PATTERNS = [
583
- "-email-",
584
- ".email.",
585
- "_email_",
586
- "-template",
587
- ".template.",
588
- "_template",
589
- "-mail.",
590
- ".mail."
591
- ];
592
- var PARSER_NAME_PATTERNS = [
593
- "parser",
594
- ".parser.",
595
- "-parser.",
596
- "_parser.",
597
- "transform",
598
- "converter",
599
- "mapper",
600
- "serializer"
601
- ];
602
- var SESSION_NAME_PATTERNS = ["session", "state", "context", "store"];
603
- var NEXTJS_METADATA_EXPORTS = [
604
- "metadata",
605
- "generatemetadata",
606
- "faqjsonld",
607
- "jsonld",
608
- "icon"
609
- ];
610
- var CONFIG_NAME_PATTERNS = [
611
- ".config.",
612
- "tsconfig",
613
- "jest.config",
614
- "package.json",
615
- "aiready.json",
616
- "next.config",
617
- "sst.config"
618
- ];
619
- function isBarrelExport(node) {
620
- const { file, exports } = node;
621
- const fileName = file.split("/").pop()?.toLowerCase();
622
- const isIndexFile = fileName === "index.ts" || fileName === "index.js";
623
- const isSmallAndManyExports = node.tokenCost < BARREL_EXPORT_TOKEN_LIMIT && (exports || []).length > BARREL_EXPORT_MIN_EXPORTS;
624
- const isReexportPattern = (exports || []).length >= BARREL_EXPORT_MIN_EXPORTS && (exports || []).every(
625
- (exp) => ["const", "function", "type", "interface"].includes(exp.type)
626
- );
627
- return !!isIndexFile || !!isSmallAndManyExports || !!isReexportPattern;
628
- }
629
- function isTypeDefinition(node) {
630
- const { file } = node;
631
- if (file.endsWith(".d.ts")) return true;
632
- const nodeExports = node.exports || [];
633
- const hasExports = nodeExports.length > 0;
634
- const areAllTypes = hasExports && nodeExports.every(
635
- (exp) => exp.type === "type" || exp.type === "interface"
636
- );
637
- const isTypePath = /\/(types|interfaces|models)\//i.test(file);
638
- return !!areAllTypes || isTypePath && hasExports;
639
- }
640
- function isUtilityModule(node) {
641
- const { file } = node;
642
- const isUtilPath = /\/(utils|helpers|util|helper)\//i.test(file);
643
- const fileName = file.split("/").pop()?.toLowerCase() || "";
644
- const isUtilName = /(utils\.|helpers\.|util\.|helper\.)/i.test(fileName);
645
- return isUtilPath || isUtilName;
646
- }
647
- function isLambdaHandler(node) {
648
- const { file, exports } = node;
649
- const fileName = file.split("/").pop()?.toLowerCase() || "";
650
- const isHandlerName = HANDLER_NAME_PATTERNS.some(
651
- (pattern) => fileName.includes(pattern)
652
- );
653
- const isHandlerPath = /\/(handlers|lambdas|lambda|functions)\//i.test(file);
654
- const hasHandlerExport = (exports || []).some(
655
- (exp) => ["handler", "main", "lambdahandler"].includes(exp.name.toLowerCase()) || exp.name.toLowerCase().endsWith("handler")
656
- );
657
- return isHandlerName || isHandlerPath || hasHandlerExport;
658
- }
659
- function isServiceFile(node) {
660
- const { file, exports } = node;
661
- const fileName = file.split("/").pop()?.toLowerCase() || "";
662
- const isServiceName = SERVICE_NAME_PATTERNS.some(
663
- (pattern) => fileName.includes(pattern)
664
- );
665
- const isServicePath = file.toLowerCase().includes("/services/");
666
- const hasServiceNamedExport = (exports || []).some(
667
- (exp) => exp.name.toLowerCase().includes("service")
668
- );
669
- const hasClassExport = (exports || []).some(
670
- (exp) => exp.type === "class"
671
- );
672
- return isServiceName || isServicePath || hasServiceNamedExport && hasClassExport;
673
- }
674
- function isEmailTemplate(node) {
675
- const { file, exports } = node;
676
- const fileName = file.split("/").pop()?.toLowerCase() || "";
677
- const isEmailName = EMAIL_NAME_PATTERNS.some(
678
- (pattern) => fileName.includes(pattern)
679
- );
680
- const isEmailPath = /\/(emails|mail|notifications)\//i.test(file);
681
- const hasTemplateFunction = (exports || []).some(
682
- (exp) => exp.type === "function" && (exp.name.toLowerCase().startsWith("render") || exp.name.toLowerCase().startsWith("generate"))
683
- );
684
- return isEmailPath || isEmailName || hasTemplateFunction;
685
- }
686
- function isParserFile(node) {
687
- const { file, exports } = node;
688
- const fileName = file.split("/").pop()?.toLowerCase() || "";
689
- const isParserName = PARSER_NAME_PATTERNS.some(
690
- (pattern) => fileName.includes(pattern)
691
- );
692
- const isParserPath = /\/(parsers|transformers)\//i.test(file);
693
- const hasParseFunction = (exports || []).some(
694
- (exp) => exp.type === "function" && (exp.name.toLowerCase().startsWith("parse") || exp.name.toLowerCase().startsWith("transform"))
695
- );
696
- return isParserName || isParserPath || hasParseFunction;
697
- }
698
- function isSessionFile(node) {
699
- const { file, exports } = node;
700
- const fileName = file.split("/").pop()?.toLowerCase() || "";
701
- const isSessionName = SESSION_NAME_PATTERNS.some(
702
- (pattern) => fileName.includes(pattern)
703
- );
704
- const isSessionPath = /\/(sessions|state)\//i.test(file);
705
- const hasSessionExport = (exports || []).some(
706
- (exp) => ["session", "state", "store"].some(
707
- (pattern) => exp.name.toLowerCase().includes(pattern)
708
- )
709
- );
710
- return isSessionName || isSessionPath || hasSessionExport;
711
- }
712
- function isNextJsPage(node) {
713
- const { file, exports } = node;
714
- const lowerPath = file.toLowerCase();
715
- const fileName = file.split("/").pop()?.toLowerCase() || "";
716
- const isInAppDir = lowerPath.includes("/app/") || lowerPath.startsWith("app/");
717
- if (!isInAppDir || fileName !== "page.tsx" && fileName !== "page.ts")
718
- return false;
719
- const hasDefaultExport = (exports || []).some(
720
- (exp) => exp.type === "default"
721
- );
722
- const hasNextJsExport = (exports || []).some(
723
- (exp) => NEXTJS_METADATA_EXPORTS.includes(exp.name.toLowerCase())
724
- );
725
- return hasDefaultExport || hasNextJsExport;
726
- }
727
- function isConfigFile(node) {
728
- const { file, exports } = node;
729
- const lowerPath = file.toLowerCase();
730
- const fileName = file.split("/").pop()?.toLowerCase() || "";
731
- const isConfigName = CONFIG_NAME_PATTERNS.some(
732
- (pattern) => fileName.includes(pattern)
733
- );
734
- const isConfigPath = /\/(config|settings|schemas)\//i.test(lowerPath);
735
- const hasSchemaExport = (exports || []).some(
736
- (exp) => ["schema", "config", "setting"].some(
737
- (pattern) => exp.name.toLowerCase().includes(pattern)
738
- )
739
- );
740
- return isConfigName || isConfigPath || hasSchemaExport;
741
- }
742
- function isHubAndSpokeFile(node) {
743
- const { file } = node;
744
- return /\/packages\/[a-zA-Z0-9-]+\/src\//.test(file);
745
- }
746
-
747
- // src/classifier.ts
748
- var Classification = {
749
- BARREL: "barrel-export",
750
- TYPE_DEFINITION: "type-definition",
751
- NEXTJS_PAGE: "nextjs-page",
752
- LAMBDA_HANDLER: "lambda-handler",
753
- SERVICE: "service-file",
754
- EMAIL_TEMPLATE: "email-template",
755
- PARSER: "parser-file",
756
- COHESIVE_MODULE: "cohesive-module",
757
- UTILITY_MODULE: "utility-module",
758
- SPOKE_MODULE: "spoke-module",
759
- MIXED_CONCERNS: "mixed-concerns",
760
- UNKNOWN: "unknown"
761
- };
762
- function classifyFile(node, cohesionScore = 1, domains = []) {
763
- if (isBarrelExport(node)) {
764
- return Classification.BARREL;
765
- }
766
- if (isTypeDefinition(node)) {
767
- return Classification.TYPE_DEFINITION;
768
- }
769
- if (isNextJsPage(node)) {
770
- return Classification.NEXTJS_PAGE;
771
- }
772
- if (isLambdaHandler(node)) {
773
- return Classification.LAMBDA_HANDLER;
774
- }
775
- if (isServiceFile(node)) {
776
- return Classification.SERVICE;
777
- }
778
- if (isEmailTemplate(node)) {
779
- return Classification.EMAIL_TEMPLATE;
780
- }
781
- if (isParserFile(node)) {
782
- return Classification.PARSER;
783
- }
784
- if (isSessionFile(node)) {
785
- if (cohesionScore >= 0.25 && domains.length <= 1)
786
- return Classification.COHESIVE_MODULE;
787
- return Classification.UTILITY_MODULE;
788
- }
789
- if (isUtilityModule(node)) {
790
- return Classification.UTILITY_MODULE;
791
- }
792
- if (isConfigFile(node)) {
793
- return Classification.COHESIVE_MODULE;
794
- }
795
- if (isHubAndSpokeFile(node)) {
796
- return Classification.SPOKE_MODULE;
797
- }
798
- if (domains.length <= 1 && domains[0] !== "unknown") {
799
- return Classification.COHESIVE_MODULE;
800
- }
801
- if (domains.length > 1 && cohesionScore < 0.4) {
802
- return Classification.MIXED_CONCERNS;
803
- }
804
- if (cohesionScore >= 0.7) {
805
- return Classification.COHESIVE_MODULE;
806
- }
807
- return Classification.UNKNOWN;
808
- }
809
- function adjustCohesionForClassification(baseCohesion, classification, node) {
810
- switch (classification) {
811
- case Classification.BARREL:
812
- return 1;
813
- case Classification.TYPE_DEFINITION:
814
- return 1;
815
- case Classification.NEXTJS_PAGE:
816
- return 1;
817
- case Classification.UTILITY_MODULE: {
818
- if (node && hasRelatedExportNames(
819
- (node.exports || []).map((e) => e.name.toLowerCase())
820
- )) {
821
- return Math.max(0.8, Math.min(1, baseCohesion + 0.45));
822
- }
823
- return Math.max(0.75, Math.min(1, baseCohesion + 0.35));
824
- }
825
- case Classification.SERVICE:
826
- return Math.max(0.72, Math.min(1, baseCohesion + 0.3));
827
- case Classification.LAMBDA_HANDLER:
828
- return Math.max(0.75, Math.min(1, baseCohesion + 0.35));
829
- case Classification.EMAIL_TEMPLATE:
830
- return Math.max(0.72, Math.min(1, baseCohesion + 0.3));
831
- case Classification.PARSER:
832
- return Math.max(0.7, Math.min(1, baseCohesion + 0.3));
833
- case Classification.SPOKE_MODULE:
834
- return Math.max(baseCohesion, 0.6);
835
- case Classification.COHESIVE_MODULE:
836
- return Math.max(baseCohesion, 0.7);
837
- case Classification.MIXED_CONCERNS:
838
- return baseCohesion;
839
- default:
840
- return Math.min(1, baseCohesion + 0.1);
841
- }
842
- }
843
- function hasRelatedExportNames(exportNames) {
844
- if (exportNames.length < 2) return true;
845
- const stems = /* @__PURE__ */ new Set();
846
- const domains = /* @__PURE__ */ new Set();
847
- const verbs = [
848
- "get",
849
- "set",
850
- "create",
851
- "update",
852
- "delete",
853
- "fetch",
854
- "save",
855
- "load",
856
- "parse",
857
- "format",
858
- "validate"
859
- ];
860
- const domainPatterns = [
861
- "user",
862
- "order",
863
- "product",
864
- "session",
865
- "email",
866
- "file",
867
- "db",
868
- "api",
869
- "config"
870
- ];
871
- for (const name of exportNames) {
872
- for (const verb of verbs) {
873
- if (name.startsWith(verb) && name.length > verb.length) {
874
- stems.add(name.slice(verb.length).toLowerCase());
875
- }
876
- }
877
- for (const domain of domainPatterns) {
878
- if (name.includes(domain)) domains.add(domain);
879
- }
880
- }
881
- if (stems.size === 1 || domains.size === 1) return true;
882
- return false;
883
- }
884
- function adjustFragmentationForClassification(baseFragmentation, classification) {
885
- switch (classification) {
886
- case Classification.BARREL:
887
- return 0;
888
- case Classification.TYPE_DEFINITION:
889
- return 0;
890
- case Classification.UTILITY_MODULE:
891
- case Classification.SERVICE:
892
- case Classification.LAMBDA_HANDLER:
893
- case Classification.EMAIL_TEMPLATE:
894
- case Classification.PARSER:
895
- case Classification.NEXTJS_PAGE:
896
- return baseFragmentation * 0.2;
897
- case Classification.SPOKE_MODULE:
898
- return baseFragmentation * 0.15;
899
- // Heavily discount intentional monorepo separation
900
- case Classification.COHESIVE_MODULE:
901
- return baseFragmentation * 0.3;
902
- case Classification.MIXED_CONCERNS:
903
- return baseFragmentation;
904
- default:
905
- return baseFragmentation * 0.7;
906
- }
907
- }
908
-
909
- // src/cluster-detector.ts
910
- function detectModuleClusters(graph, options) {
911
- const domainMap = /* @__PURE__ */ new Map();
912
- for (const [file, node] of graph.nodes.entries()) {
913
- const primaryDomain = node.exports[0]?.inferredDomain || "unknown";
914
- if (!domainMap.has(primaryDomain)) {
915
- domainMap.set(primaryDomain, []);
916
- }
917
- domainMap.get(primaryDomain).push(file);
918
- }
919
- const clusters = [];
920
- const generateSuggestedStructure = (files, tokens, fragmentation) => {
921
- const targetFiles = Math.max(1, Math.ceil(tokens / 1e4));
922
- const plan = [];
923
- if (fragmentation > 0.5) {
924
- plan.push(
925
- `Consolidate ${files.length} files scattered across multiple directories into ${targetFiles} core module(s)`
926
- );
927
- }
928
- if (tokens > 2e4) {
929
- plan.push(
930
- `Domain logic is very large (${Math.round(tokens / 1e3)}k tokens). Ensure clear sub-domain boundaries.`
931
- );
932
- }
933
- return { targetFiles, consolidationPlan: plan };
934
- };
935
- for (const [domain, files] of domainMap.entries()) {
936
- if (files.length < 2 || domain === "unknown") continue;
937
- const totalTokens = files.reduce((sum, file) => {
938
- const node = graph.nodes.get(file);
939
- return sum + (node?.tokenCost || 0);
940
- }, 0);
941
- let sharedImportRatio = 0;
942
- if (files.length >= 2) {
943
- const allImportSets = files.map(
944
- (f) => new Set(graph.nodes.get(f)?.imports || [])
945
- );
946
- let intersection = new Set(allImportSets[0]);
947
- const union = new Set(allImportSets[0]);
948
- for (let i = 1; i < allImportSets.length; i++) {
949
- const nextSet = allImportSets[i];
950
- intersection = new Set([...intersection].filter((x) => nextSet.has(x)));
951
- for (const x of nextSet) union.add(x);
952
- }
953
- sharedImportRatio = union.size > 0 ? intersection.size / union.size : 0;
954
- }
955
- const rawFragmentation = calculateFragmentation(files, domain, {
956
- ...options,
957
- sharedImportRatio
958
- });
959
- let totalCohesion = 0;
960
- let totalAdjustedFragmentation = 0;
961
- files.forEach((f) => {
962
- const node = graph.nodes.get(f);
963
- if (node) {
964
- const cohesion = calculateEnhancedCohesion(node.exports);
965
- totalCohesion += cohesion;
966
- const classification = classifyFile(node, cohesion);
967
- totalAdjustedFragmentation += adjustFragmentationForClassification(
968
- rawFragmentation,
969
- classification
970
- );
971
- }
972
- });
973
- const avgCohesion = totalCohesion / files.length;
974
- const fragmentationScore = totalAdjustedFragmentation / files.length;
975
- clusters.push({
976
- domain,
977
- files,
978
- totalTokens,
979
- fragmentationScore,
980
- avgCohesion,
981
- suggestedStructure: generateSuggestedStructure(
982
- files,
983
- totalTokens,
984
- fragmentationScore
985
- )
986
- });
987
- }
988
- return clusters;
989
- }
990
-
991
- // src/remediation.ts
992
- function getClassificationRecommendations(classification, file, issues) {
993
- switch (classification) {
994
- case "barrel-export":
995
- return [
996
- "Barrel export file detected - multiple domains are expected here",
997
- "Consider if this barrel export improves or hinders discoverability"
998
- ];
999
- case "type-definition":
1000
- return [
1001
- "Type definition file - centralized types improve consistency",
1002
- "Consider splitting if file becomes too large (>500 lines)"
1003
- ];
1004
- case "cohesive-module":
1005
- return [
1006
- "Module has good cohesion despite its size",
1007
- "Consider documenting the module boundaries for AI assistants"
1008
- ];
1009
- case "utility-module":
1010
- return [
1011
- "Utility module detected - multiple domains are acceptable here",
1012
- "Consider grouping related utilities by prefix or domain for better discoverability"
1013
- ];
1014
- case "service-file":
1015
- return [
1016
- "Service file detected - orchestration of multiple dependencies is expected",
1017
- "Consider documenting service boundaries and dependencies"
1018
- ];
1019
- case "lambda-handler":
1020
- return [
1021
- "Lambda handler detected - coordination of services is expected",
1022
- "Ensure handler has clear single responsibility"
1023
- ];
1024
- case "email-template":
1025
- return [
1026
- "Email template detected - references multiple domains for rendering",
1027
- "Template structure is cohesive by design"
1028
- ];
1029
- case "parser-file":
1030
- return [
1031
- "Parser/transformer file detected - handles multiple data sources",
1032
- "Consider documenting input/output schemas"
1033
- ];
1034
- case "nextjs-page":
1035
- return [
1036
- "Next.js App Router page detected - metadata/JSON-LD/component pattern is cohesive",
1037
- "Multiple exports (metadata, faqJsonLd, default) serve single page purpose"
1038
- ];
1039
- case "spoke-module":
1040
- return [
1041
- "Spoke module detected - intentional monorepo separation is good for modularity",
1042
- "Ensure this spoke only exports what is necessary for the hub or other spokes"
1043
- ];
1044
- case "mixed-concerns":
1045
- return [
1046
- "Consider splitting this file by domain",
1047
- "Identify independent responsibilities and extract them",
1048
- "Review import dependencies to understand coupling"
1049
- ];
1050
- default:
1051
- return issues;
1052
- }
1053
- }
1054
- function getGeneralRecommendations(metrics, thresholds) {
1055
- const recommendations = [];
1056
- const issues = [];
1057
- let severity = "info";
1058
- if (metrics.contextBudget > thresholds.maxContextBudget) {
1059
- issues.push(
1060
- `High context budget: ${Math.round(metrics.contextBudget / 1e3)}k tokens`
1061
- );
1062
- recommendations.push(
1063
- "Reduce dependencies or split the file to lower context window requirements"
1064
- );
1065
- severity = "major";
1066
- }
1067
- if (metrics.importDepth > thresholds.maxDepth) {
1068
- issues.push(`Deep import chain: ${metrics.importDepth} levels`);
1069
- recommendations.push("Flatten the dependency graph by reducing nesting");
1070
- if (severity !== "critical") severity = "major";
1071
- }
1072
- if (metrics.circularDeps.length > 0) {
1073
- issues.push(
1074
- `Circular dependencies detected: ${metrics.circularDeps.length}`
1075
- );
1076
- recommendations.push(
1077
- "Refactor to remove circular imports (use dependency injection or interfaces)"
1078
- );
1079
- severity = "critical";
1080
- }
1081
- if (metrics.cohesionScore < thresholds.minCohesion) {
1082
- issues.push(`Low cohesion score: ${metrics.cohesionScore.toFixed(2)}`);
1083
- recommendations.push(
1084
- "Extract unrelated exports into separate domain-specific modules"
1085
- );
1086
- if (severity === "info") severity = "minor";
1087
- }
1088
- if (metrics.fragmentationScore > thresholds.maxFragmentation) {
1089
- issues.push(
1090
- `High domain fragmentation: ${metrics.fragmentationScore.toFixed(2)}`
1091
- );
1092
- recommendations.push(
1093
- "Consolidate domain-related files into fewer directories"
1094
- );
1095
- if (severity === "info") severity = "minor";
1096
- }
1097
- return { recommendations, issues, severity };
1098
- }
1099
-
1100
- // src/orchestrator.ts
1101
- import { scanFiles, readFileContent } from "@aiready/core";
1102
-
1103
- // src/issue-analyzer.ts
1104
- import { Severity } from "@aiready/core";
1105
- function analyzeIssues(params) {
1106
- const {
1107
- file,
1108
- importDepth,
1109
- contextBudget,
1110
- cohesionScore,
1111
- fragmentationScore,
1112
- maxDepth,
1113
- maxContextBudget,
1114
- minCohesion,
1115
- maxFragmentation,
1116
- circularDeps
1117
- } = params;
1118
- const issues = [];
1119
- const recommendations = [];
1120
- let severity = Severity.Info;
1121
- let potentialSavings = 0;
1122
- if (circularDeps.length > 0) {
1123
- severity = Severity.Critical;
1124
- issues.push(`Part of ${circularDeps.length} circular dependency chain(s)`);
1125
- recommendations.push(
1126
- "Break circular dependencies by extracting interfaces or using dependency injection"
1127
- );
1128
- potentialSavings += contextBudget * 0.2;
1129
- }
1130
- if (importDepth > maxDepth * 1.5) {
1131
- severity = Severity.Critical;
1132
- issues.push(`Import depth ${importDepth} exceeds limit by 50%`);
1133
- recommendations.push("Flatten dependency tree or use facade pattern");
1134
- potentialSavings += contextBudget * 0.3;
1135
- } else if (importDepth > maxDepth) {
1136
- if (severity !== Severity.Critical) severity = Severity.Major;
1137
- issues.push(
1138
- `Import depth ${importDepth} exceeds recommended maximum ${maxDepth}`
1139
- );
1140
- recommendations.push("Consider reducing dependency depth");
1141
- potentialSavings += contextBudget * 0.15;
1142
- }
1143
- if (contextBudget > maxContextBudget * 1.5) {
1144
- severity = Severity.Critical;
1145
- issues.push(
1146
- `Context budget ${contextBudget.toLocaleString()} tokens is 50% over limit`
1147
- );
1148
- recommendations.push(
1149
- "Split into smaller modules or reduce dependency tree"
1150
- );
1151
- potentialSavings += contextBudget * 0.4;
1152
- } else if (contextBudget > maxContextBudget) {
1153
- if (severity !== Severity.Critical) severity = Severity.Major;
1154
- issues.push(
1155
- `Context budget ${contextBudget.toLocaleString()} exceeds ${maxContextBudget.toLocaleString()}`
1156
- );
1157
- recommendations.push("Reduce file size or dependencies");
1158
- potentialSavings += contextBudget * 0.2;
1159
- }
1160
- if (cohesionScore < minCohesion * 0.5) {
1161
- if (severity !== Severity.Critical) severity = Severity.Major;
1162
- issues.push(
1163
- `Very low cohesion (${(cohesionScore * 100).toFixed(0)}%) - mixed concerns`
1164
- );
1165
- recommendations.push(
1166
- "Split file by domain - separate unrelated functionality"
1167
- );
1168
- potentialSavings += contextBudget * 0.25;
1169
- } else if (cohesionScore < minCohesion) {
1170
- if (severity === Severity.Info) severity = Severity.Minor;
1171
- issues.push(`Low cohesion (${(cohesionScore * 100).toFixed(0)}%)`);
1172
- recommendations.push("Consider grouping related exports together");
1173
- potentialSavings += contextBudget * 0.1;
1174
- }
1175
- if (fragmentationScore > maxFragmentation) {
1176
- if (severity === Severity.Info || severity === Severity.Minor)
1177
- severity = Severity.Minor;
1178
- issues.push(
1179
- `High fragmentation (${(fragmentationScore * 100).toFixed(0)}%) - scattered implementation`
1180
- );
1181
- recommendations.push("Consolidate with related files in same domain");
1182
- potentialSavings += contextBudget * 0.3;
1183
- }
1184
- if (issues.length === 0) {
1185
- issues.push("No significant issues detected");
1186
- recommendations.push("File is well-structured for AI context usage");
1187
- }
1188
- if (isBuildArtifact(file)) {
1189
- issues.push("Detected build artifact (bundled/output file)");
1190
- recommendations.push("Exclude build outputs from analysis");
1191
- severity = Severity.Info;
1192
- potentialSavings = 0;
1193
- }
1194
- return {
1195
- severity,
1196
- issues,
1197
- recommendations,
1198
- potentialSavings: Math.floor(potentialSavings)
1199
- };
1200
- }
1201
- function isBuildArtifact(filePath) {
1202
- const lower = filePath.toLowerCase();
1203
- return lower.includes("/node_modules/") || lower.includes("/dist/") || lower.includes("/build/") || lower.includes("/out/") || lower.includes("/.next/");
1204
- }
1205
-
1206
- // src/mapper.ts
1207
- function mapNodeToResult(node, graph, clusters, allCircularDeps, options) {
1208
- const file = node.file;
1209
- const tokenCost = node.tokenCost;
1210
- const importDepth = calculateImportDepth(file, graph);
1211
- const transitiveDeps = getTransitiveDependencies(file, graph);
1212
- const contextBudget = calculateContextBudget(file, graph);
1213
- const circularDeps = allCircularDeps.filter(
1214
- (cycle) => cycle.includes(file)
1215
- );
1216
- const cluster = clusters.find((c) => c.files.includes(file));
1217
- const rawFragmentationScore = cluster ? cluster.fragmentationScore : 0;
1218
- const rawCohesionScore = calculateEnhancedCohesion(
1219
- node.exports,
1220
- file,
1221
- options
1222
- );
1223
- const fileClassification = classifyFile(node, rawCohesionScore);
1224
- const cohesionScore = adjustCohesionForClassification(
1225
- rawCohesionScore,
1226
- fileClassification
1227
- );
1228
- const fragmentationScore = adjustFragmentationForClassification(
1229
- rawFragmentationScore,
1230
- fileClassification
1231
- );
1232
- const { severity, issues, recommendations, potentialSavings } = analyzeIssues({
1233
- file,
1234
- importDepth,
1235
- contextBudget,
1236
- cohesionScore,
1237
- fragmentationScore,
1238
- maxDepth: options.maxDepth,
1239
- maxContextBudget: options.maxContextBudget,
1240
- minCohesion: options.minCohesion,
1241
- maxFragmentation: options.maxFragmentation,
1242
- circularDeps
1243
- });
1244
- const classRecs = getClassificationRecommendations(
1245
- fileClassification,
1246
- file,
1247
- issues
1248
- );
1249
- const allRecommendations = Array.from(
1250
- /* @__PURE__ */ new Set([...recommendations, ...classRecs])
1251
- );
1252
- return {
1253
- file,
1254
- tokenCost,
1255
- linesOfCode: node.linesOfCode,
1256
- importDepth,
1257
- dependencyCount: transitiveDeps.length,
1258
- dependencyList: transitiveDeps,
1259
- circularDeps,
1260
- cohesionScore,
1261
- domains: Array.from(
1262
- new Set(
1263
- node.exports.flatMap((e) => e.domains?.map((d) => d.domain) || [])
1264
- )
1265
- ),
1266
- exportCount: node.exports.length,
1267
- contextBudget,
1268
- fragmentationScore,
1269
- relatedFiles: cluster ? cluster.files : [],
1270
- fileClassification,
1271
- severity,
1272
- issues,
1273
- recommendations: allRecommendations,
1274
- potentialSavings
1275
- };
1276
- }
1277
-
1278
- // src/orchestrator.ts
1279
- function calculateCohesion(exports, filePath, options) {
1280
- return calculateEnhancedCohesion(exports, filePath, options);
1281
- }
1282
- async function analyzeContext(options) {
1283
- const {
1284
- maxDepth = 5,
1285
- maxContextBudget = 25e3,
1286
- minCohesion = 0.6,
1287
- maxFragmentation = 0.5,
1288
- includeNodeModules = false,
1289
- ...scanOptions
1290
- } = options;
1291
- const files = await scanFiles({
1292
- ...scanOptions,
1293
- exclude: includeNodeModules && scanOptions.exclude ? scanOptions.exclude.filter(
1294
- (pattern) => pattern !== "**/node_modules/**"
1295
- ) : scanOptions.exclude
1296
- });
1297
- const pythonFiles = files.filter((f) => f.toLowerCase().endsWith(".py"));
1298
- const fileContents = await Promise.all(
1299
- files.map(async (file) => ({
1300
- file,
1301
- content: await readFileContent(file)
1302
- }))
1303
- );
1304
- const graph = buildDependencyGraph(
1305
- fileContents.filter((f) => !f.file.toLowerCase().endsWith(".py"))
1306
- );
1307
- let pythonResults = [];
1308
- if (pythonFiles.length > 0) {
1309
- const { analyzePythonContext } = await import("./python-context-3GZKN3LR.mjs");
1310
- const pythonMetrics = await analyzePythonContext(
1311
- pythonFiles,
1312
- scanOptions.rootDir || options.rootDir || "."
1313
- );
1314
- pythonResults = pythonMetrics.map((metric) => {
1315
- const { severity, issues, recommendations, potentialSavings } = analyzeIssues({
1316
- file: metric.file,
1317
- importDepth: metric.importDepth,
1318
- contextBudget: metric.contextBudget,
1319
- cohesionScore: metric.cohesion,
1320
- fragmentationScore: 0,
1321
- maxDepth,
1322
- maxContextBudget,
1323
- minCohesion,
1324
- maxFragmentation,
1325
- circularDeps: []
1326
- });
1327
- return {
1328
- file: metric.file,
1329
- tokenCost: 0,
1330
- linesOfCode: 0,
1331
- importDepth: metric.importDepth,
1332
- dependencyCount: 0,
1333
- dependencyList: [],
1334
- circularDeps: [],
1335
- cohesionScore: metric.cohesion,
1336
- domains: [],
1337
- exportCount: 0,
1338
- contextBudget: metric.contextBudget,
1339
- fragmentationScore: 0,
1340
- relatedFiles: [],
1341
- fileClassification: "unknown",
1342
- severity,
1343
- issues,
1344
- recommendations,
1345
- potentialSavings
1346
- };
1347
- });
1348
- }
1349
- const clusters = detectModuleClusters(graph);
1350
- const allCircularDeps = detectCircularDependencies(graph);
1351
- const results = Array.from(graph.nodes.values()).map(
1352
- (node) => mapNodeToResult(node, graph, clusters, allCircularDeps, {
1353
- maxDepth,
1354
- maxContextBudget,
1355
- minCohesion,
1356
- maxFragmentation
1357
- })
1358
- );
1359
- return [...results, ...pythonResults];
1360
- }
1361
-
1362
- // src/summary.ts
1363
- import { GLOBAL_SCAN_OPTIONS } from "@aiready/core";
1364
- function generateSummary(results, options = {}) {
1365
- const config = options ? Object.fromEntries(
1366
- Object.entries(options).filter(
1367
- ([key]) => !GLOBAL_SCAN_OPTIONS.includes(key) || key === "rootDir"
1368
- )
1369
- ) : {};
1370
- const totalFiles = results.length;
1371
- const totalTokens = results.reduce((sum, r) => sum + r.tokenCost, 0);
1372
- const avgContextBudget = totalFiles > 0 ? results.reduce((sum, r) => sum + r.contextBudget, 0) / totalFiles : 0;
1373
- const deepFiles = results.filter((r) => r.importDepth > 5).map((r) => ({ file: r.file, depth: r.importDepth }));
1374
- const maxImportDepth = Math.max(0, ...results.map((r) => r.importDepth));
1375
- const moduleMap = /* @__PURE__ */ new Map();
1376
- results.forEach((r) => {
1377
- const parts = r.file.split("/");
1378
- let domain = "root";
1379
- if (parts.length > 2) {
1380
- domain = parts.slice(0, 2).join("/");
1381
- }
1382
- if (!moduleMap.has(domain)) moduleMap.set(domain, []);
1383
- moduleMap.get(domain).push(r);
1384
- });
1385
- const fragmentedModules = [];
1386
- moduleMap.forEach((files, domain) => {
1387
- const clusterTokens = files.reduce((sum, f) => sum + f.tokenCost, 0);
1388
- const filePaths = files.map((f) => f.file);
1389
- const avgEntropy = calculatePathEntropy(filePaths);
1390
- const fragmentationScore = Math.min(1, avgEntropy * (files.length / 10));
1391
- if (fragmentationScore > 0.4) {
1392
- fragmentedModules.push({
1393
- domain,
1394
- files: filePaths,
1395
- fragmentationScore,
1396
- totalTokens: clusterTokens,
1397
- avgCohesion: files.reduce((sum, f) => sum + f.cohesionScore, 0) / files.length,
1398
- suggestedStructure: {
1399
- targetFiles: Math.ceil(files.length / 2),
1400
- consolidationPlan: [
1401
- `Consolidate ${files.length} files in ${domain} into fewer modules`
1402
- ]
1403
- }
1404
- });
1405
- }
1406
- });
1407
- fragmentedModules.sort((a, b) => b.fragmentationScore - a.fragmentationScore);
1408
- const avgFragmentation = fragmentedModules.length > 0 ? fragmentedModules.reduce((sum, m) => sum + m.fragmentationScore, 0) / fragmentedModules.length : 0;
1409
- const avgCohesion = results.reduce((sum, r) => sum + r.cohesionScore, 0) / (totalFiles || 1);
1410
- const lowCohesionFiles = results.filter((r) => r.cohesionScore < 0.4).map((r) => ({ file: r.file, score: r.cohesionScore }));
1411
- const criticalIssues = results.filter(
1412
- (r) => r.severity === "critical"
1413
- ).length;
1414
- const majorIssues = results.filter((r) => r.severity === "major").length;
1415
- const minorIssues = results.filter((r) => r.severity === "minor").length;
1416
- const totalPotentialSavings = results.reduce(
1417
- (sum, r) => sum + (r.potentialSavings || 0),
1418
- 0
1419
- );
1420
- const topExpensiveFiles = [...results].sort((a, b) => b.contextBudget - a.contextBudget).slice(0, 10).map((r) => ({
1421
- file: r.file,
1422
- contextBudget: r.contextBudget,
1423
- severity: r.severity
1424
- }));
1425
- return {
1426
- totalFiles,
1427
- totalTokens,
1428
- avgContextBudget,
1429
- maxContextBudget: Math.max(0, ...results.map((r) => r.contextBudget)),
1430
- avgImportDepth: results.reduce((sum, r) => sum + r.importDepth, 0) / (totalFiles || 1),
1431
- maxImportDepth,
1432
- deepFiles,
1433
- avgFragmentation,
1434
- fragmentedModules,
1435
- avgCohesion,
1436
- lowCohesionFiles,
1437
- criticalIssues,
1438
- majorIssues,
1439
- minorIssues,
1440
- totalPotentialSavings,
1441
- topExpensiveFiles,
1442
- config
1443
- };
1444
- }
1445
-
1446
- // src/utils/output-formatter.ts
1447
- import chalk from "chalk";
1448
- import { existsSync, readFileSync } from "fs";
1449
- import { join as join2 } from "path";
1450
- import prompts from "prompts";
1451
- function displayConsoleReport(summary, results, maxResults = 10) {
1452
- const divider = "\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500";
1453
- const totalIssues = summary.criticalIssues + summary.majorIssues + summary.minorIssues;
1454
- console.log(chalk.bold("\u{1F4CA} Context Analysis Summary:\n"));
1455
- console.log(` \u2022 Total Files: ${chalk.cyan(summary.totalFiles)}`);
1456
- console.log(
1457
- ` \u2022 Total Tokens: ${chalk.cyan(summary.totalTokens.toLocaleString())}`
1458
- );
1459
- console.log(
1460
- ` \u2022 Avg Budget: ${chalk.cyan(summary.avgContextBudget.toFixed(0))} tokens`
1461
- );
1462
- console.log(
1463
- ` \u2022 Potential Saving: ${chalk.green(summary.totalPotentialSavings.toLocaleString())} tokens`
1464
- );
1465
- console.log();
1466
- if (totalIssues > 0) {
1467
- console.log(chalk.bold("\u26A0\uFE0F Issues Detected:\n"));
1468
- console.log(` \u2022 ${chalk.red("\u{1F534} Critical:")} ${summary.criticalIssues}`);
1469
- console.log(` \u2022 ${chalk.yellow("\u{1F7E1} Major:")} ${summary.majorIssues}`);
1470
- console.log(` \u2022 ${chalk.blue("\u{1F535} Minor:")} ${summary.minorIssues}`);
1471
- console.log();
1472
- } else {
1473
- console.log(chalk.green("\u2705 No significant context issues detected!\n"));
1474
- }
1475
- if (summary.fragmentedModules.length > 0) {
1476
- console.log(chalk.bold("\u{1F9E9} Top Fragmented Modules:\n"));
1477
- summary.fragmentedModules.slice(0, maxResults).forEach((mod) => {
1478
- const scoreColor = mod.fragmentationScore > 0.7 ? chalk.red : mod.fragmentationScore > 0.4 ? chalk.yellow : chalk.green;
1479
- console.log(
1480
- ` ${scoreColor("\u25A0")} ${chalk.white(mod.domain)} ${chalk.dim(`(${mod.files.length} files, ${(mod.fragmentationScore * 100).toFixed(0)}% frag)`)}`
1481
- );
1482
- });
1483
- console.log();
1484
- }
1485
- if (summary.topExpensiveFiles.length > 0) {
1486
- console.log(chalk.bold("\u{1F4B8} Most Expensive Files (Context Budget):\n"));
1487
- summary.topExpensiveFiles.slice(0, maxResults).forEach((item) => {
1488
- const fileName = item.file.split("/").slice(-2).join("/");
1489
- const severityColor = item.severity === "critical" ? chalk.red : item.severity === "major" ? chalk.yellow : chalk.blue;
1490
- console.log(
1491
- ` ${severityColor("\u25CF")} ${chalk.white(fileName)} ${chalk.dim(`- ${item.contextBudget.toLocaleString()} tokens`)}`
1492
- );
1493
- });
1494
- console.log();
1495
- }
1496
- if (totalIssues > 0) {
1497
- console.log(chalk.bold("\u{1F4A1} Top Recommendations:\n"));
1498
- const topFiles = results.filter((r) => r.severity === "critical" || r.severity === "major").slice(0, 3);
1499
- topFiles.forEach((result, index) => {
1500
- const fileName = result.file.split("/").slice(-2).join("/");
1501
- console.log(chalk.cyan(` ${index + 1}. ${fileName}`));
1502
- result.recommendations.slice(0, 2).forEach((rec) => {
1503
- console.log(chalk.dim(` \u2022 ${rec}`));
1504
- });
1505
- });
1506
- console.log();
1507
- }
1508
- console.log(chalk.cyan(divider));
1509
- console.log(
1510
- chalk.dim(
1511
- "\n\u2B50 Like aiready? Star us on GitHub: https://github.com/caopengau/aiready-context-analyzer"
1512
- )
1513
- );
1514
- console.log(
1515
- chalk.dim(
1516
- "\u{1F41B} Found a bug? Report it: https://github.com/caopengau/aiready-context-analyzer/issues\n"
1517
- )
1518
- );
1519
- }
1520
- function generateHTMLReport(summary, results) {
1521
- const totalIssues = summary.criticalIssues + summary.majorIssues + summary.minorIssues;
1522
- void results;
1523
- return `<!DOCTYPE html>
1524
- <html lang="en">
1525
- <head>
1526
- <meta charset="UTF-8">
1527
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
1528
- <title>aiready Context Analysis Report</title>
1529
- <style>
1530
- body {
1531
- font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
1532
- line-height: 1.6;
1533
- color: #333;
1534
- max-width: 1200px;
1535
- margin: 0 auto;
1536
- padding: 20px;
1537
- background-color: #f5f5f5;
1538
- }
1539
- h1, h2, h3 { color: #2c3e50; }
1540
- .header {
1541
- background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
1542
- color: white;
1543
- padding: 30px;
1544
- border-radius: 8px;
1545
- margin-bottom: 30px;
1546
- }
1547
- .summary {
1548
- display: grid;
1549
- grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
1550
- gap: 20px;
1551
- margin-bottom: 30px;
1552
- }
1553
- .card {
1554
- background: white;
1555
- padding: 20px;
1556
- border-radius: 8px;
1557
- box-shadow: 0 2px 4px rgba(0,0,0,0.1);
1558
- }
1559
- .metric {
1560
- font-size: 2em;
1561
- font-weight: bold;
1562
- color: #667eea;
1563
- }
1564
- .label {
1565
- color: #666;
1566
- font-size: 0.9em;
1567
- margin-top: 5px;
1568
- }
1569
- .issue-critical { color: #e74c3c; }
1570
- .issue-major { color: #f39c12; }
1571
- .issue-minor { color: #3498db; }
1572
- table {
1573
- width: 100%;
1574
- border-collapse: collapse;
1575
- background: white;
1576
- border-radius: 8px;
1577
- overflow: hidden;
1578
- box-shadow: 0 2px 4px rgba(0,0,0,0.1);
1579
- }
1580
- th, td {
1581
- padding: 12px;
1582
- text-align: left;
1583
- border-bottom: 1px solid #eee;
1584
- }
1585
- th {
1586
- background-color: #667eea;
1587
- color: white;
1588
- font-weight: 600;
1589
- }
1590
- tr:hover { background-color: #f8f9fa; }
1591
- .footer {
1592
- text-align: center;
1593
- margin-top: 40px;
1594
- padding: 20px;
1595
- color: #666;
1596
- font-size: 0.9em;
1597
- }
1598
- </style>
1599
- </head>
1600
- <body>
1601
- <div class="header">
1602
- <h1>\u{1F50D} AIReady Context Analysis Report</h1>
1603
- <p>Generated on ${(/* @__PURE__ */ new Date()).toLocaleString()}</p>
1604
- </div>
1605
-
1606
- <div class="summary">
1607
- <div class="card">
1608
- <div class="metric">${summary.totalFiles}</div>
1609
- <div class="label">Files Analyzed</div>
1610
- </div>
1611
- <div class="card">
1612
- <div class="metric">${summary.totalTokens.toLocaleString()}</div>
1613
- <div class="label">Total Tokens</div>
1614
- </div>
1615
- <div class="card">
1616
- <div class="metric">${summary.avgContextBudget.toFixed(0)}</div>
1617
- <div class="label">Avg Context Budget</div>
1618
- </div>
1619
- <div class="card">
1620
- <div class="metric ${totalIssues > 0 ? "issue-major" : ""}">${totalIssues}</div>
1621
- <div class="label">Total Issues</div>
1622
- </div>
1623
- </div>
1624
-
1625
- ${totalIssues > 0 ? `
1626
- <div class="card" style="margin-bottom: 30px;">
1627
- <h2>\u26A0\uFE0F Issues Summary</h2>
1628
- <p>
1629
- <span class="issue-critical">\u{1F534} Critical: ${summary.criticalIssues}</span> &nbsp;
1630
- <span class="issue-major">\u{1F7E1} Major: ${summary.majorIssues}</span> &nbsp;
1631
- <span class="issue-minor">\u{1F535} Minor: ${summary.minorIssues}</span>
1632
- </p>
1633
- <p><strong>Potential Savings:</strong> ${summary.totalPotentialSavings.toLocaleString()} tokens</p>
1634
- </div>
1635
- ` : ""}
1636
-
1637
- ${summary.fragmentedModules.length > 0 ? `
1638
- <div class="card" style="margin-bottom: 30px;">
1639
- <h2>\u{1F9E9} Fragmented Modules</h2>
1640
- <table>
1641
- <thead>
1642
- <tr>
1643
- <th>Domain</th>
1644
- <th>Files</th>
1645
- <th>Fragmentation</th>
1646
- <th>Token Cost</th>
1647
- </tr>
1648
- </thead>
1649
- <tbody>
1650
- ${summary.fragmentedModules.map(
1651
- (m) => `
1652
- <tr>
1653
- <td>${m.domain}</td>
1654
- <td>${m.files.length}</td>
1655
- <td>${(m.fragmentationScore * 100).toFixed(0)}%</td>
1656
- <td>${m.totalTokens.toLocaleString()}</td>
1657
- </tr>
1658
- `
1659
- ).join("")}
1660
- </tbody>
1661
- </table>
1662
- </div>
1663
- ` : ""}
1664
-
1665
- ${summary.topExpensiveFiles.length > 0 ? `
1666
- <div class="card" style="margin-bottom: 30px;">
1667
- <h2>\u{1F4B8} Most Expensive Files</h2>
1668
- <table>
1669
- <thead>
1670
- <tr>
1671
- <th>File</th>
1672
- <th>Context Budget</th>
1673
- <th>Severity</th>
1674
- </tr>
1675
- </thead>
1676
- <tbody>
1677
- ${summary.topExpensiveFiles.map(
1678
- (f) => `
1679
- <tr>
1680
- <td>${f.file}</td>
1681
- <td>${f.contextBudget.toLocaleString()} tokens</td>
1682
- <td class="issue-${f.severity}">${f.severity.toUpperCase()}</td>
1683
- </tr>
1684
- `
1685
- ).join("")}
1686
- </tbody>
1687
- </table>
1688
- </div>
1689
- ` : ""}
1690
-
1691
- <div class="footer">
1692
- <p>Generated by <strong>@aiready/context-analyzer</strong></p>
1693
- <p>Like AIReady? <a href="https://github.com/caopengau/aiready-context-analyzer">Star us on GitHub</a></p>
1694
- <p>Found a bug? <a href="https://github.com/caopengau/aiready-context-analyzer/issues">Report it here</a></p>
1695
- </div>
1696
- </body>
1697
- </html>`;
1698
- }
1699
- async function runInteractiveSetup(directory, current) {
1700
- console.log(chalk.yellow("\u{1F9ED} Interactive mode: let\u2019s tailor the analysis."));
1701
- const pkgPath = join2(directory, "package.json");
1702
- let deps = {};
1703
- if (existsSync(pkgPath)) {
1704
- try {
1705
- const pkg = JSON.parse(readFileSync(pkgPath, "utf-8"));
1706
- deps = { ...pkg.dependencies || {}, ...pkg.devDependencies || {} };
1707
- } catch (e) {
1708
- void e;
1709
- }
1710
- }
1711
- const hasNextJs = existsSync(join2(directory, ".next")) || !!deps["next"];
1712
- const hasCDK = existsSync(join2(directory, "cdk.out")) || !!deps["aws-cdk-lib"] || Object.keys(deps).some((d) => d.startsWith("@aws-cdk/"));
1713
- const recommendedExcludes = new Set(current.exclude || []);
1714
- if (hasNextJs && !Array.from(recommendedExcludes).some((p) => p.includes(".next"))) {
1715
- recommendedExcludes.add("**/.next/**");
1716
- }
1717
- if (hasCDK && !Array.from(recommendedExcludes).some((p) => p.includes("cdk.out"))) {
1718
- recommendedExcludes.add("**/cdk.out/**");
1719
- }
1720
- const { applyExcludes } = await prompts({
1721
- type: "toggle",
1722
- name: "applyExcludes",
1723
- message: `Detected ${hasNextJs ? "Next.js " : ""}${hasCDK ? "AWS CDK " : ""}frameworks. Apply recommended excludes?`,
1724
- initial: true,
1725
- active: "yes",
1726
- inactive: "no"
1727
- });
1728
- const nextOptions = { ...current };
1729
- if (applyExcludes) {
1730
- nextOptions.exclude = Array.from(recommendedExcludes);
1731
- }
1732
- const { focusArea } = await prompts({
1733
- type: "select",
1734
- name: "focusArea",
1735
- message: "Which areas to focus?",
1736
- choices: [
1737
- { title: "Frontend (web app)", value: "frontend" },
1738
- { title: "Backend (API/infra)", value: "backend" },
1739
- { title: "Both", value: "both" }
1740
- ],
1741
- initial: 2
1742
- });
1743
- if (focusArea === "frontend") {
1744
- nextOptions.include = ["**/*.{ts,tsx,js,jsx}"];
1745
- nextOptions.exclude = Array.from(
1746
- /* @__PURE__ */ new Set([
1747
- ...nextOptions.exclude || [],
1748
- "**/cdk.out/**",
1749
- "**/infra/**",
1750
- "**/server/**",
1751
- "**/backend/**"
1752
- ])
1753
- );
1754
- } else if (focusArea === "backend") {
1755
- nextOptions.include = [
1756
- "**/api/**",
1757
- "**/server/**",
1758
- "**/backend/**",
1759
- "**/infra/**",
1760
- "**/*.{ts,js,py,java}"
1761
- ];
1762
- }
1763
- console.log(chalk.green("\u2713 Interactive configuration applied."));
1764
- return nextOptions;
1765
- }
1766
-
1767
- export {
1768
- buildCoUsageMatrix,
1769
- buildTypeGraph,
1770
- findSemanticClusters,
1771
- inferDomainFromSemantics,
1772
- calculateDomainConfidence,
1773
- extractExports,
1774
- inferDomain,
1775
- getCoUsageData,
1776
- findConsolidationCandidates,
1777
- calculateEnhancedCohesion,
1778
- calculateStructuralCohesionFromCoUsage,
1779
- calculateFragmentation,
1780
- calculatePathEntropy,
1781
- calculateDirectoryDistance,
1782
- extractDomainKeywordsFromPaths,
1783
- buildDependencyGraph,
1784
- calculateImportDepth,
1785
- getTransitiveDependencies,
1786
- calculateContextBudget,
1787
- detectCircularDependencies,
1788
- Classification,
1789
- classifyFile,
1790
- adjustCohesionForClassification,
1791
- adjustFragmentationForClassification,
1792
- detectModuleClusters,
1793
- getClassificationRecommendations,
1794
- getGeneralRecommendations,
1795
- calculateCohesion,
1796
- analyzeContext,
1797
- generateSummary,
1798
- displayConsoleReport,
1799
- generateHTMLReport,
1800
- runInteractiveSetup
1801
- };