@aiready/pattern-detect 0.17.8 → 0.17.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 (190) hide show
  1. package/dist/analyzer-entry/index.d.mts +1 -1
  2. package/dist/analyzer-entry/index.d.ts +1 -1
  3. package/dist/analyzer-entry/index.js +370 -135
  4. package/dist/analyzer-entry/index.mjs +4 -3
  5. package/dist/chunk-2P7BQHGR.mjs +306 -0
  6. package/dist/{chunk-VGMM3L3O.mjs → chunk-3EORD7DC.mjs} +1 -1
  7. package/dist/{chunk-GREN7X5H.mjs → chunk-4PVPQMRT.mjs} +2 -2
  8. package/dist/{chunk-RS73WLNI.mjs → chunk-6VDL7TAS.mjs} +5 -113
  9. package/dist/chunk-AQIP4JGM.mjs +283 -0
  10. package/dist/{chunk-JBUZ6YHE.mjs → chunk-B4NLWKPZ.mjs} +85 -9
  11. package/dist/chunk-IPBGVPUX.mjs +143 -0
  12. package/dist/chunk-LUUJOUK5.mjs +283 -0
  13. package/dist/chunk-P3BOCGVV.mjs +498 -0
  14. package/dist/{scoring-entry.js → chunk-PHJE6A3J.mjs} +20 -37
  15. package/dist/chunk-PQXOORR4.mjs +234 -0
  16. package/dist/{chunk-GLKAGFKX.mjs → chunk-RDR75DVI.mjs} +85 -9
  17. package/dist/chunk-SXVLRPMF.mjs +143 -0
  18. package/dist/{chunk-DNZS4ESD.mjs → chunk-SY7RX5YQ.mjs} +85 -9
  19. package/dist/{context-rules-entry.js → chunk-TIBF7KST.mjs} +81 -78
  20. package/dist/chunk-WYYSQX5M.mjs +467 -0
  21. package/dist/{chunk-I6ETJC7L.mjs → chunk-X553BOMI.mjs} +56 -26
  22. package/dist/{chunk-K7BO57OO.mjs → chunk-Y6OB7K34.mjs} +80 -4
  23. package/dist/chunk-YLVV6YZ5.mjs +143 -0
  24. package/dist/chunk-ZUWPFVJV.mjs +115 -0
  25. package/dist/chunk-ZZMONVPE.mjs +467 -0
  26. package/dist/cli.js +402 -167
  27. package/dist/cli.mjs +4 -3
  28. package/dist/context-rules-entry/index.d.mts +35 -1
  29. package/dist/context-rules-entry/index.d.ts +35 -1
  30. package/dist/context-rules-entry/index.js +194 -48
  31. package/dist/context-rules-entry/index.mjs +1 -1
  32. package/dist/detector-entry/index.js +192 -46
  33. package/dist/detector-entry/index.mjs +2 -2
  34. package/dist/{analyzer-entry-BVz-HnZd.d.mts → index-B-pnXpgn.d.mts} +10 -1
  35. package/dist/{index-BwuoiCNm.d.ts → index-CWgYOKaK.d.ts} +35 -16
  36. package/dist/{index-BVz-HnZd.d.mts → index-Dl4BrGIT.d.mts} +35 -16
  37. package/dist/{analyzer-entry-BwuoiCNm.d.ts → index-DqS2e0kK.d.ts} +10 -1
  38. package/dist/index.d.mts +5 -6
  39. package/dist/index.d.ts +5 -6
  40. package/dist/index.js +467 -214
  41. package/dist/index.mjs +37 -22
  42. package/dist/scoring-entry/index.js +7 -3
  43. package/dist/scoring-entry/index.mjs +1 -1
  44. package/package.json +2 -2
  45. package/dist/analyzer-entry.d.mts +0 -100
  46. package/dist/analyzer-entry.d.ts +0 -100
  47. package/dist/analyzer-entry.js +0 -693
  48. package/dist/analyzer-entry.mjs +0 -12
  49. package/dist/chunk-262N2JB7.mjs +0 -497
  50. package/dist/chunk-2R7HOR5H.mjs +0 -777
  51. package/dist/chunk-3D7RVGHM.mjs +0 -64
  52. package/dist/chunk-3LS3E6MO.mjs +0 -508
  53. package/dist/chunk-3VRQYFW3.mjs +0 -782
  54. package/dist/chunk-3WK24ZOX.mjs +0 -860
  55. package/dist/chunk-3YYN6ZXN.mjs +0 -1038
  56. package/dist/chunk-4BPRGZRG.mjs +0 -1041
  57. package/dist/chunk-4UHDGB7U.mjs +0 -920
  58. package/dist/chunk-5LYDB7DY.mjs +0 -771
  59. package/dist/chunk-65G3HXLQ.mjs +0 -497
  60. package/dist/chunk-65UQ5J2J.mjs +0 -64
  61. package/dist/chunk-6JTVOBJX.mjs +0 -64
  62. package/dist/chunk-6OEHUI5J.mjs +0 -1045
  63. package/dist/chunk-6YUGU4P4.mjs +0 -914
  64. package/dist/chunk-7EJGNGXM.mjs +0 -771
  65. package/dist/chunk-7O2DUBSN.mjs +0 -1058
  66. package/dist/chunk-7S4AUL5S.mjs +0 -911
  67. package/dist/chunk-A76JUWER.mjs +0 -786
  68. package/dist/chunk-AJZUNNFH.mjs +0 -817
  69. package/dist/chunk-AXHGYYYZ.mjs +0 -404
  70. package/dist/chunk-BKRPSTT2.mjs +0 -64
  71. package/dist/chunk-BUBQ3W6W.mjs +0 -980
  72. package/dist/chunk-CCHM2VLK.mjs +0 -1051
  73. package/dist/chunk-CHFK6EBT.mjs +0 -419
  74. package/dist/chunk-CMT3MWWO.mjs +0 -948
  75. package/dist/chunk-CMWW24HW.mjs +0 -259
  76. package/dist/chunk-CTDBJP25.mjs +0 -1043
  77. package/dist/chunk-DGAKXYIP.mjs +0 -1041
  78. package/dist/chunk-DQSLTL7J.mjs +0 -788
  79. package/dist/chunk-DR5W7S3Z.mjs +0 -968
  80. package/dist/chunk-EFUKPMBE.mjs +0 -950
  81. package/dist/chunk-EVBFDILL.mjs +0 -927
  82. package/dist/chunk-EXORBAXR.mjs +0 -887
  83. package/dist/chunk-EZT3NZGB.mjs +0 -1057
  84. package/dist/chunk-FWUKMJEQ.mjs +0 -1133
  85. package/dist/chunk-GSJFORRO.mjs +0 -504
  86. package/dist/chunk-H4ADJYOG.mjs +0 -925
  87. package/dist/chunk-H5FB2USZ.mjs +0 -762
  88. package/dist/chunk-H73HEG7M.mjs +0 -670
  89. package/dist/chunk-HOS5Z2NC.mjs +0 -669
  90. package/dist/chunk-HXHQOQB5.mjs +0 -508
  91. package/dist/chunk-INEOYHUM.mjs +0 -911
  92. package/dist/chunk-INJ4SBTV.mjs +0 -754
  93. package/dist/chunk-J5CW6NYY.mjs +0 -64
  94. package/dist/chunk-JAFZCZAP.mjs +0 -776
  95. package/dist/chunk-JKVKOXYR.mjs +0 -407
  96. package/dist/chunk-JTHW7EYW.mjs +0 -1041
  97. package/dist/chunk-JWR3AHKO.mjs +0 -788
  98. package/dist/chunk-KC2CQMG2.mjs +0 -858
  99. package/dist/chunk-KDWGWBP5.mjs +0 -832
  100. package/dist/chunk-KPEK5REL.mjs +0 -919
  101. package/dist/chunk-KT6O2IAE.mjs +0 -861
  102. package/dist/chunk-KWMNN3TG.mjs +0 -391
  103. package/dist/chunk-LUA5FXSZ.mjs +0 -771
  104. package/dist/chunk-LYKRYBSM.mjs +0 -64
  105. package/dist/chunk-M4PQMW34.mjs +0 -480
  106. package/dist/chunk-MH6LBXZF.mjs +0 -816
  107. package/dist/chunk-MHU3CL4R.mjs +0 -64
  108. package/dist/chunk-MJWBS6SM.mjs +0 -1058
  109. package/dist/chunk-OFGMDX66.mjs +0 -402
  110. package/dist/chunk-P7B6Z4I2.mjs +0 -1043
  111. package/dist/chunk-PBCXSG7E.mjs +0 -658
  112. package/dist/chunk-PEEHSFDR.mjs +0 -1058
  113. package/dist/chunk-PSVG2NLH.mjs +0 -966
  114. package/dist/chunk-PWNQ6JZW.mjs +0 -508
  115. package/dist/chunk-QE4E3F7C.mjs +0 -410
  116. package/dist/chunk-QEP76HGK.mjs +0 -1039
  117. package/dist/chunk-QX2BQJEO.mjs +0 -1058
  118. package/dist/chunk-R2S73CVG.mjs +0 -503
  119. package/dist/chunk-RMGDSNLE.mjs +0 -770
  120. package/dist/chunk-S2KQFII2.mjs +0 -491
  121. package/dist/chunk-SLDK5PQK.mjs +0 -1129
  122. package/dist/chunk-SNSDVGWW.mjs +0 -783
  123. package/dist/chunk-SUUZMLPS.mjs +0 -391
  124. package/dist/chunk-SVCSIZ2A.mjs +0 -259
  125. package/dist/chunk-T2C6WS73.mjs +0 -670
  126. package/dist/chunk-TCG2G32F.mjs +0 -911
  127. package/dist/chunk-TGBZP7SB.mjs +0 -773
  128. package/dist/chunk-THF4RW63.mjs +0 -254
  129. package/dist/chunk-TJKDLVLN.mjs +0 -503
  130. package/dist/chunk-TXWPOVYU.mjs +0 -402
  131. package/dist/chunk-UB3CGOQ7.mjs +0 -64
  132. package/dist/chunk-UKIKN27B.mjs +0 -950
  133. package/dist/chunk-V5DP4FP6.mjs +0 -876
  134. package/dist/chunk-VRMXVYDZ.mjs +0 -419
  135. package/dist/chunk-WACZ5LFH.mjs +0 -1055
  136. package/dist/chunk-WC7CBAA7.mjs +0 -1058
  137. package/dist/chunk-WKBCNITM.mjs +0 -1072
  138. package/dist/chunk-WMOGJFME.mjs +0 -391
  139. package/dist/chunk-X4GR2N2M.mjs +0 -947
  140. package/dist/chunk-XCWY2DQY.mjs +0 -788
  141. package/dist/chunk-XJD35DS6.mjs +0 -1058
  142. package/dist/chunk-XNPID6FU.mjs +0 -391
  143. package/dist/chunk-XUUVS54V.mjs +0 -776
  144. package/dist/chunk-YCGV65F5.mjs +0 -508
  145. package/dist/chunk-YJYDBFT3.mjs +0 -780
  146. package/dist/chunk-YP3HEDQW.mjs +0 -859
  147. package/dist/chunk-YSDOUNJJ.mjs +0 -1142
  148. package/dist/chunk-Z6GBFFOV.mjs +0 -1040
  149. package/dist/cli.d.ts.map +0 -1
  150. package/dist/cli.js.map +0 -1
  151. package/dist/context-rules-entry-y2uJSngh.d.mts +0 -60
  152. package/dist/context-rules-entry-y2uJSngh.d.ts +0 -60
  153. package/dist/context-rules-entry.d.mts +0 -55
  154. package/dist/context-rules-entry.d.ts +0 -55
  155. package/dist/context-rules-entry.mjs +0 -12
  156. package/dist/context-rules.d.ts +0 -41
  157. package/dist/context-rules.d.ts.map +0 -1
  158. package/dist/context-rules.js +0 -225
  159. package/dist/context-rules.js.map +0 -1
  160. package/dist/detector-entry.d.mts +0 -14
  161. package/dist/detector-entry.d.ts +0 -14
  162. package/dist/detector-entry.js +0 -301
  163. package/dist/detector-entry.mjs +0 -7
  164. package/dist/detector.d.ts +0 -40
  165. package/dist/detector.d.ts.map +0 -1
  166. package/dist/detector.js +0 -385
  167. package/dist/detector.js.map +0 -1
  168. package/dist/extractors/python-extractor.d.ts +0 -19
  169. package/dist/extractors/python-extractor.d.ts.map +0 -1
  170. package/dist/extractors/python-extractor.js +0 -164
  171. package/dist/extractors/python-extractor.js.map +0 -1
  172. package/dist/grouping.d.ts +0 -54
  173. package/dist/grouping.d.ts.map +0 -1
  174. package/dist/grouping.js +0 -347
  175. package/dist/grouping.js.map +0 -1
  176. package/dist/index-y2uJSngh.d.mts +0 -60
  177. package/dist/index-y2uJSngh.d.ts +0 -60
  178. package/dist/index.d.ts.map +0 -1
  179. package/dist/index.js.map +0 -1
  180. package/dist/python-extractor-BGKGX6BK.mjs +0 -131
  181. package/dist/python-extractor-ELAKYK2W.mjs +0 -140
  182. package/dist/scoring-entry.d.mts +0 -23
  183. package/dist/scoring-entry.d.ts +0 -23
  184. package/dist/scoring-entry.mjs +0 -6
  185. package/dist/scoring.d.ts +0 -12
  186. package/dist/scoring.d.ts.map +0 -1
  187. package/dist/scoring.js +0 -116
  188. package/dist/scoring.js.map +0 -1
  189. package/dist/types-C4lmb2Yh.d.mts +0 -36
  190. package/dist/types-C4lmb2Yh.d.ts +0 -36
@@ -1,407 +0,0 @@
1
- // src/index.ts
2
- import { scanFiles, readFileContent } from "@aiready/core";
3
-
4
- // src/detector.ts
5
- import { estimateTokens } from "@aiready/core";
6
- function categorizePattern(code) {
7
- const lower = code.toLowerCase();
8
- if (lower.includes("request") && lower.includes("response") || lower.includes("router.") || lower.includes("app.get") || lower.includes("app.post") || lower.includes("express") || lower.includes("ctx.body")) {
9
- return "api-handler";
10
- }
11
- if (lower.includes("validate") || lower.includes("schema") || lower.includes("zod") || lower.includes("yup") || lower.includes("if") && lower.includes("throw")) {
12
- return "validator";
13
- }
14
- if (lower.includes("return (") || lower.includes("jsx") || lower.includes("component") || lower.includes("props")) {
15
- return "component";
16
- }
17
- if (lower.includes("class ") || lower.includes("this.")) {
18
- return "class-method";
19
- }
20
- if (lower.includes("return ") && !lower.includes("this") && !lower.includes("new ")) {
21
- return "utility";
22
- }
23
- if (lower.includes("function") || lower.includes("=>")) {
24
- return "function";
25
- }
26
- return "unknown";
27
- }
28
- function extractCodeBlocks(content, minLines) {
29
- const lines = content.split("\n");
30
- const blocks = [];
31
- let currentBlock = [];
32
- let blockStart = 0;
33
- let braceDepth = 0;
34
- let inFunction = false;
35
- for (let i = 0; i < lines.length; i++) {
36
- const line = lines[i];
37
- const trimmed = line.trim();
38
- if (!inFunction && (trimmed.includes("function ") || trimmed.includes("=>") || trimmed.includes("async ") || /^(export\s+)?(async\s+)?function\s+/.test(trimmed) || /^(export\s+)?const\s+\w+\s*=\s*(async\s*)?\(/.test(trimmed))) {
39
- inFunction = true;
40
- blockStart = i;
41
- }
42
- for (const char of line) {
43
- if (char === "{") braceDepth++;
44
- if (char === "}") braceDepth--;
45
- }
46
- if (inFunction) {
47
- currentBlock.push(line);
48
- }
49
- if (inFunction && braceDepth === 0 && currentBlock.length >= minLines) {
50
- const blockContent = currentBlock.join("\n");
51
- const linesOfCode = currentBlock.filter(
52
- (l) => l.trim() && !l.trim().startsWith("//")
53
- ).length;
54
- blocks.push({
55
- content: blockContent,
56
- startLine: blockStart + 1,
57
- endLine: i + 1,
58
- patternType: categorizePattern(blockContent),
59
- linesOfCode
60
- });
61
- currentBlock = [];
62
- inFunction = false;
63
- } else if (inFunction && braceDepth === 0) {
64
- currentBlock = [];
65
- inFunction = false;
66
- }
67
- }
68
- return blocks;
69
- }
70
- function normalizeCode(code) {
71
- return code.replace(/\/\/.*$/gm, "").replace(/\/\*[\s\S]*?\*\//g, "").replace(/"[^"]*"/g, '"STR"').replace(/'[^']*'/g, "'STR'").replace(/`[^`]*`/g, "`STR`").replace(/\b\d+\b/g, "NUM").replace(/\s+/g, " ").trim();
72
- }
73
- function jaccardSimilarity(tokens1, tokens2) {
74
- const set1 = new Set(tokens1);
75
- const set2 = new Set(tokens2);
76
- let intersection = 0;
77
- for (const token of set1) {
78
- if (set2.has(token)) intersection++;
79
- }
80
- const union = set1.size + set2.size - intersection;
81
- return union === 0 ? 0 : intersection / union;
82
- }
83
- async function detectDuplicatePatterns(files, options) {
84
- const {
85
- minSimilarity,
86
- minLines,
87
- batchSize = 100,
88
- approx = true,
89
- minSharedTokens = 8,
90
- maxCandidatesPerBlock = 100,
91
- streamResults = false
92
- } = options;
93
- const duplicates = [];
94
- const maxComparisons = approx ? Infinity : 5e5;
95
- const allBlocks = files.flatMap(
96
- (file) => extractCodeBlocks(file.content, minLines).map((block) => ({
97
- content: block.content,
98
- startLine: block.startLine,
99
- endLine: block.endLine,
100
- file: file.file,
101
- normalized: normalizeCode(block.content),
102
- patternType: block.patternType,
103
- tokenCost: estimateTokens(block.content),
104
- linesOfCode: block.linesOfCode
105
- }))
106
- );
107
- console.log(`Extracted ${allBlocks.length} code blocks for analysis`);
108
- if (!approx && allBlocks.length > 500) {
109
- console.log(`\u26A0\uFE0F Using --no-approx mode with ${allBlocks.length} blocks may be slow (O(B\xB2) complexity).`);
110
- console.log(` Consider using approximate mode (default) for better performance.`);
111
- }
112
- const stopwords = /* @__PURE__ */ new Set([
113
- "return",
114
- "const",
115
- "let",
116
- "var",
117
- "function",
118
- "class",
119
- "new",
120
- "if",
121
- "else",
122
- "for",
123
- "while",
124
- "async",
125
- "await",
126
- "try",
127
- "catch",
128
- "switch",
129
- "case",
130
- "default",
131
- "import",
132
- "export",
133
- "from",
134
- "true",
135
- "false",
136
- "null",
137
- "undefined",
138
- "this"
139
- ]);
140
- const tokenize = (norm) => norm.split(/[\s(){}\[\];,\.]+/).filter((t) => t && t.length >= 3 && !stopwords.has(t.toLowerCase()));
141
- const blockTokens = allBlocks.map((b) => tokenize(b.normalized));
142
- const invertedIndex = /* @__PURE__ */ new Map();
143
- if (approx) {
144
- for (let i = 0; i < blockTokens.length; i++) {
145
- for (const tok of blockTokens[i]) {
146
- let arr = invertedIndex.get(tok);
147
- if (!arr) {
148
- arr = [];
149
- invertedIndex.set(tok, arr);
150
- }
151
- arr.push(i);
152
- }
153
- }
154
- }
155
- const totalComparisons = approx ? void 0 : allBlocks.length * (allBlocks.length - 1) / 2;
156
- if (totalComparisons !== void 0) {
157
- console.log(`Processing ${totalComparisons.toLocaleString()} comparisons in batches...`);
158
- } else {
159
- console.log(`Using approximate candidate selection to reduce comparisons...`);
160
- }
161
- let comparisonsProcessed = 0;
162
- let comparisonsBudgetExhausted = false;
163
- const startTime = Date.now();
164
- for (let i = 0; i < allBlocks.length; i++) {
165
- if (maxComparisons && comparisonsProcessed >= maxComparisons) {
166
- comparisonsBudgetExhausted = true;
167
- break;
168
- }
169
- if (i % batchSize === 0 && i > 0) {
170
- const elapsed = ((Date.now() - startTime) / 1e3).toFixed(1);
171
- const duplicatesFound = duplicates.length;
172
- if (totalComparisons !== void 0) {
173
- const progress = (comparisonsProcessed / totalComparisons * 100).toFixed(1);
174
- const remaining = totalComparisons - comparisonsProcessed;
175
- const rate = comparisonsProcessed / parseFloat(elapsed);
176
- const eta = remaining > 0 ? (remaining / rate).toFixed(0) : 0;
177
- console.log(` ${progress}% (${comparisonsProcessed.toLocaleString()}/${totalComparisons.toLocaleString()} comparisons, ${elapsed}s elapsed, ~${eta}s remaining, ${duplicatesFound} duplicates)`);
178
- } else {
179
- console.log(` Processed ${i.toLocaleString()}/${allBlocks.length} blocks (${elapsed}s elapsed, ${duplicatesFound} duplicates)`);
180
- }
181
- await new Promise((resolve) => setImmediate(resolve));
182
- }
183
- const block1 = allBlocks[i];
184
- let candidates = null;
185
- if (approx) {
186
- const counts = /* @__PURE__ */ new Map();
187
- for (const tok of blockTokens[i]) {
188
- const ids = invertedIndex.get(tok);
189
- if (!ids) continue;
190
- for (const j of ids) {
191
- if (j <= i) continue;
192
- if (allBlocks[j].file === block1.file) continue;
193
- counts.set(j, (counts.get(j) || 0) + 1);
194
- }
195
- }
196
- candidates = Array.from(counts.entries()).filter(([, shared]) => shared >= minSharedTokens).sort((a, b) => b[1] - a[1]).slice(0, maxCandidatesPerBlock).map(([j, shared]) => ({ j, shared }));
197
- }
198
- if (approx && candidates) {
199
- for (const { j } of candidates) {
200
- if (!approx && maxComparisons !== Infinity && comparisonsProcessed >= maxComparisons) {
201
- console.log(`\u26A0\uFE0F Comparison safety limit reached (${maxComparisons.toLocaleString()} comparisons in --no-approx mode).`);
202
- console.log(` This prevents excessive runtime on large repos. Consider using approximate mode (default) or --min-lines to reduce blocks.`);
203
- break;
204
- }
205
- comparisonsProcessed++;
206
- const block2 = allBlocks[j];
207
- const similarity = jaccardSimilarity(blockTokens[i], blockTokens[j]);
208
- if (similarity >= minSimilarity) {
209
- const duplicate = {
210
- file1: block1.file,
211
- file2: block2.file,
212
- line1: block1.startLine,
213
- line2: block2.startLine,
214
- endLine1: block1.endLine,
215
- endLine2: block2.endLine,
216
- similarity,
217
- snippet: block1.content.split("\n").slice(0, 5).join("\n") + "\n...",
218
- patternType: block1.patternType,
219
- tokenCost: block1.tokenCost + block2.tokenCost,
220
- linesOfCode: block1.linesOfCode
221
- };
222
- duplicates.push(duplicate);
223
- if (streamResults) {
224
- console.log(`
225
- \u2705 Found: ${duplicate.patternType} ${Math.round(similarity * 100)}% similar`);
226
- console.log(` ${duplicate.file1}:${duplicate.line1}-${duplicate.endLine1} \u21D4 ${duplicate.file2}:${duplicate.line2}-${duplicate.endLine2}`);
227
- console.log(` Token cost: ${duplicate.tokenCost.toLocaleString()}`);
228
- }
229
- }
230
- }
231
- } else {
232
- for (let j = i + 1; j < allBlocks.length; j++) {
233
- if (maxComparisons && comparisonsProcessed >= maxComparisons) break;
234
- comparisonsProcessed++;
235
- const block2 = allBlocks[j];
236
- if (block1.file === block2.file) continue;
237
- const similarity = jaccardSimilarity(blockTokens[i], blockTokens[j]);
238
- if (similarity >= minSimilarity) {
239
- const duplicate = {
240
- file1: block1.file,
241
- file2: block2.file,
242
- line1: block1.startLine,
243
- line2: block2.startLine,
244
- endLine1: block1.endLine,
245
- endLine2: block2.endLine,
246
- similarity,
247
- snippet: block1.content.split("\n").slice(0, 5).join("\n") + "\n...",
248
- patternType: block1.patternType,
249
- tokenCost: block1.tokenCost + block2.tokenCost,
250
- linesOfCode: block1.linesOfCode
251
- };
252
- duplicates.push(duplicate);
253
- if (streamResults) {
254
- console.log(`
255
- \u2705 Found: ${duplicate.patternType} ${Math.round(similarity * 100)}% similar`);
256
- console.log(` ${duplicate.file1}:${duplicate.line1}-${duplicate.endLine1} \u21D4 ${duplicate.file2}:${duplicate.line2}-${duplicate.endLine2}`);
257
- console.log(` Token cost: ${duplicate.tokenCost.toLocaleString()}`);
258
- }
259
- }
260
- }
261
- }
262
- }
263
- if (comparisonsBudgetExhausted) {
264
- console.log(`\u26A0\uFE0F Comparison budget exhausted (${maxComparisons.toLocaleString()} comparisons). Use --max-comparisons to increase.`);
265
- }
266
- return duplicates.sort(
267
- (a, b) => b.similarity - a.similarity || b.tokenCost - a.tokenCost
268
- );
269
- }
270
-
271
- // src/index.ts
272
- function getRefactoringSuggestion(patternType, similarity) {
273
- const baseMessages = {
274
- "api-handler": "Extract common middleware or create a base handler class",
275
- validator: "Consolidate validation logic into shared schema validators (Zod/Yup)",
276
- utility: "Move to a shared utilities file and reuse across modules",
277
- "class-method": "Consider inheritance or composition to share behavior",
278
- component: "Extract shared logic into a custom hook or HOC",
279
- function: "Extract into a shared helper function",
280
- unknown: "Extract common logic into a reusable module"
281
- };
282
- const urgency = similarity > 0.95 ? " (CRITICAL: Nearly identical code)" : similarity > 0.9 ? " (HIGH: Very similar, refactor soon)" : "";
283
- return baseMessages[patternType] + urgency;
284
- }
285
- async function analyzePatterns(options) {
286
- const {
287
- minSimilarity = 0.4,
288
- // Jaccard similarity default (40% threshold)
289
- minLines = 5,
290
- batchSize = 100,
291
- approx = true,
292
- minSharedTokens = 8,
293
- maxCandidatesPerBlock = 100,
294
- streamResults = false,
295
- ...scanOptions
296
- } = options;
297
- const files = await scanFiles(scanOptions);
298
- const results = [];
299
- const fileContents = await Promise.all(
300
- files.map(async (file) => ({
301
- file,
302
- content: await readFileContent(file)
303
- }))
304
- );
305
- const duplicates = await detectDuplicatePatterns(fileContents, {
306
- minSimilarity,
307
- minLines,
308
- batchSize,
309
- approx,
310
- minSharedTokens,
311
- maxCandidatesPerBlock,
312
- streamResults
313
- });
314
- for (const file of files) {
315
- const fileDuplicates = duplicates.filter(
316
- (dup) => dup.file1 === file || dup.file2 === file
317
- );
318
- const issues = fileDuplicates.map((dup) => {
319
- const otherFile = dup.file1 === file ? dup.file2 : dup.file1;
320
- const severity = dup.similarity > 0.95 ? "critical" : dup.similarity > 0.9 ? "major" : "minor";
321
- return {
322
- type: "duplicate-pattern",
323
- severity,
324
- message: `${dup.patternType} pattern ${Math.round(dup.similarity * 100)}% similar to ${otherFile} (${dup.tokenCost} tokens wasted)`,
325
- location: {
326
- file,
327
- line: dup.file1 === file ? dup.line1 : dup.line2
328
- },
329
- suggestion: getRefactoringSuggestion(dup.patternType, dup.similarity)
330
- };
331
- });
332
- const totalTokenCost = fileDuplicates.reduce(
333
- (sum, dup) => sum + dup.tokenCost,
334
- 0
335
- );
336
- results.push({
337
- fileName: file,
338
- issues,
339
- metrics: {
340
- tokenCost: totalTokenCost,
341
- consistencyScore: Math.max(0, 1 - fileDuplicates.length * 0.1)
342
- }
343
- });
344
- }
345
- return results;
346
- }
347
- function generateSummary(results) {
348
- const allIssues = results.flatMap((r) => r.issues);
349
- const totalTokenCost = results.reduce(
350
- (sum, r) => sum + (r.metrics.tokenCost || 0),
351
- 0
352
- );
353
- const patternsByType = {
354
- "api-handler": 0,
355
- validator: 0,
356
- utility: 0,
357
- "class-method": 0,
358
- component: 0,
359
- function: 0,
360
- unknown: 0
361
- };
362
- allIssues.forEach((issue) => {
363
- const match = issue.message.match(/^(\S+(?:-\S+)*) pattern/);
364
- if (match) {
365
- const type = match[1];
366
- patternsByType[type] = (patternsByType[type] || 0) + 1;
367
- }
368
- });
369
- const topDuplicates = allIssues.slice(0, 10).map((issue) => {
370
- const similarityMatch = issue.message.match(/(\d+)% similar/);
371
- const tokenMatch = issue.message.match(/\((\d+) tokens/);
372
- const typeMatch = issue.message.match(/^(\S+(?:-\S+)*) pattern/);
373
- const fileMatch = issue.message.match(/similar to (.+?) \(/);
374
- return {
375
- files: [
376
- {
377
- path: issue.location.file,
378
- startLine: issue.location.line,
379
- endLine: 0
380
- // Not available from Issue
381
- },
382
- {
383
- path: fileMatch?.[1] || "unknown",
384
- startLine: 0,
385
- // Not available from Issue
386
- endLine: 0
387
- // Not available from Issue
388
- }
389
- ],
390
- similarity: similarityMatch ? parseInt(similarityMatch[1]) / 100 : 0,
391
- patternType: typeMatch?.[1] || "unknown",
392
- tokenCost: tokenMatch ? parseInt(tokenMatch[1]) : 0
393
- };
394
- });
395
- return {
396
- totalPatterns: allIssues.length,
397
- totalTokenCost,
398
- patternsByType,
399
- topDuplicates
400
- };
401
- }
402
-
403
- export {
404
- detectDuplicatePatterns,
405
- analyzePatterns,
406
- generateSummary
407
- };