@aiready/pattern-detect 0.16.18 → 0.16.20

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 (49) hide show
  1. package/dist/analyzer-entry-BVz-HnZd.d.mts +119 -0
  2. package/dist/analyzer-entry-BwuoiCNm.d.ts +119 -0
  3. package/dist/analyzer-entry.d.mts +3 -0
  4. package/dist/analyzer-entry.d.ts +3 -0
  5. package/dist/analyzer-entry.js +693 -0
  6. package/dist/analyzer-entry.mjs +12 -0
  7. package/dist/chunk-65UQ5J2J.mjs +64 -0
  8. package/dist/chunk-6JTVOBJX.mjs +64 -0
  9. package/dist/chunk-BKRPSTT2.mjs +64 -0
  10. package/dist/chunk-CMWW24HW.mjs +259 -0
  11. package/dist/chunk-DNZS4ESD.mjs +391 -0
  12. package/dist/chunk-GLKAGFKX.mjs +391 -0
  13. package/dist/chunk-GREN7X5H.mjs +143 -0
  14. package/dist/chunk-I6ETJC7L.mjs +179 -0
  15. package/dist/chunk-JBUZ6YHE.mjs +391 -0
  16. package/dist/chunk-KWMNN3TG.mjs +391 -0
  17. package/dist/chunk-LYKRYBSM.mjs +64 -0
  18. package/dist/chunk-MHU3CL4R.mjs +64 -0
  19. package/dist/chunk-RS73WLNI.mjs +251 -0
  20. package/dist/chunk-SVCSIZ2A.mjs +259 -0
  21. package/dist/chunk-THF4RW63.mjs +254 -0
  22. package/dist/chunk-UB3CGOQ7.mjs +64 -0
  23. package/dist/chunk-VGMM3L3O.mjs +143 -0
  24. package/dist/chunk-WBBO35SC.mjs +112 -0
  25. package/dist/chunk-WMOGJFME.mjs +391 -0
  26. package/dist/chunk-XNPID6FU.mjs +391 -0
  27. package/dist/cli.js +62 -219
  28. package/dist/cli.mjs +72 -97
  29. package/dist/context-rules-entry-y2uJSngh.d.mts +60 -0
  30. package/dist/context-rules-entry-y2uJSngh.d.ts +60 -0
  31. package/dist/context-rules-entry.d.mts +2 -0
  32. package/dist/context-rules-entry.d.ts +2 -0
  33. package/dist/context-rules-entry.js +207 -0
  34. package/dist/context-rules-entry.mjs +12 -0
  35. package/dist/detector-entry.d.mts +14 -0
  36. package/dist/detector-entry.d.ts +14 -0
  37. package/dist/detector-entry.js +301 -0
  38. package/dist/detector-entry.mjs +7 -0
  39. package/dist/index.d.mts +7 -235
  40. package/dist/index.d.ts +7 -235
  41. package/dist/index.js +9 -126
  42. package/dist/index.mjs +17 -9
  43. package/dist/scoring-entry.d.mts +23 -0
  44. package/dist/scoring-entry.d.ts +23 -0
  45. package/dist/scoring-entry.js +133 -0
  46. package/dist/scoring-entry.mjs +6 -0
  47. package/dist/types-DU2mmhwb.d.mts +36 -0
  48. package/dist/types-DU2mmhwb.d.ts +36 -0
  49. package/package.json +24 -4
@@ -0,0 +1,7 @@
1
+ import {
2
+ detectDuplicatePatterns
3
+ } from "./chunk-VGMM3L3O.mjs";
4
+ import "./chunk-I6ETJC7L.mjs";
5
+ export {
6
+ detectDuplicatePatterns
7
+ };
package/dist/index.d.mts CHANGED
@@ -1,242 +1,14 @@
1
- import { ToolProvider, Severity, FileContent, ScanOptions, AnalysisResult, CostConfig, ToolScoringOutput } from '@aiready/core';
1
+ import { ToolProvider } from '@aiready/core';
2
2
  export { Severity } from '@aiready/core';
3
+ export { D as DuplicateGroup, P as PatternDetectOptions, a as PatternSummary, R as RefactorCluster, b as analyzePatterns, c as createRefactorClusters, f as filterClustersByImpact, g as generateSummary, d as getSmartDefaults, e as groupDuplicatesByFilePair } from './analyzer-entry-BVz-HnZd.mjs';
4
+ export { detectDuplicatePatterns } from './detector-entry.mjs';
5
+ export { calculatePatternScore } from './scoring-entry.mjs';
6
+ export { C as CONTEXT_RULES, a as ContextRule, c as calculateSeverity, f as filterBySeverity, g as getSeverityLabel, b as getSeverityThreshold } from './context-rules-entry-y2uJSngh.mjs';
7
+ export { D as DuplicatePattern, P as PatternType } from './types-DU2mmhwb.mjs';
3
8
 
4
9
  /**
5
10
  * Pattern Detection Tool Provider
6
11
  */
7
12
  declare const PatternDetectProvider: ToolProvider;
8
13
 
9
- type PatternType = 'api-handler' | 'validator' | 'utility' | 'class-method' | 'component' | 'function' | 'unknown';
10
- interface DuplicatePattern {
11
- file1: string;
12
- line1: number;
13
- endLine1: number;
14
- file2: string;
15
- line2: number;
16
- endLine2: number;
17
- code1: string;
18
- code2: string;
19
- similarity: number;
20
- confidence: number;
21
- patternType: PatternType;
22
- tokenCost: number;
23
- severity: Severity;
24
- reason?: string;
25
- suggestion?: string;
26
- matchedRule?: string;
27
- }
28
- interface DetectionOptions {
29
- minSimilarity: number;
30
- minLines: number;
31
- batchSize: number;
32
- approx: boolean;
33
- minSharedTokens: number;
34
- maxCandidatesPerBlock: number;
35
- streamResults: boolean;
36
- excludePatterns?: string[];
37
- confidenceThreshold?: number;
38
- ignoreWhitelist?: string[];
39
- onProgress?: (processed: number, total: number, message: string) => void;
40
- }
41
-
42
- /**
43
- * Detect duplicate patterns across files
44
- *
45
- * @param fileContents - Array of file contents to analyze.
46
- * @param options - Configuration for duplicate detection (thresholds, progress, etc).
47
- * @returns Promise resolving to an array of detected duplicate patterns sorted by similarity.
48
- */
49
- declare function detectDuplicatePatterns(fileContents: FileContent[], options: DetectionOptions): Promise<DuplicatePattern[]>;
50
-
51
- interface DuplicateGroup {
52
- filePair: string;
53
- severity: Severity;
54
- occurrences: number;
55
- totalTokenCost: number;
56
- averageSimilarity: number;
57
- patternTypes: Set<PatternType>;
58
- lineRanges: Array<{
59
- file1: {
60
- start: number;
61
- end: number;
62
- };
63
- file2: {
64
- start: number;
65
- end: number;
66
- };
67
- }>;
68
- }
69
- interface RefactorCluster {
70
- id: string;
71
- name: string;
72
- files: string[];
73
- severity: Severity;
74
- duplicateCount: number;
75
- totalTokenCost: number;
76
- averageSimilarity: number;
77
- reason?: string;
78
- suggestion?: string;
79
- }
80
- /**
81
- * Group raw duplicates by file pairs to reduce noise
82
- */
83
- declare function groupDuplicatesByFilePair(duplicates: DuplicatePattern[]): DuplicateGroup[];
84
- /**
85
- * Create clusters of highly related files (refactor targets)
86
- * Uses a simple connected components algorithm
87
- * @param duplicates - Array of duplicate patterns to cluster
88
- * @returns Array of refactor clusters
89
- */
90
- declare function createRefactorClusters(duplicates: DuplicatePattern[]): RefactorCluster[];
91
- /**
92
- * Filter clusters by impact threshold
93
- * @param clusters - Array of refactor clusters to filter
94
- * @param minTokenCost - Minimum token cost threshold (default: 1000)
95
- * @param minFiles - Minimum number of files in cluster (default: 3)
96
- * @returns Filtered array of refactor clusters
97
- */
98
- declare function filterClustersByImpact(clusters: RefactorCluster[], minTokenCost?: number, minFiles?: number): RefactorCluster[];
99
-
100
- interface PatternDetectOptions extends ScanOptions {
101
- minSimilarity?: number;
102
- minLines?: number;
103
- batchSize?: number;
104
- approx?: boolean;
105
- minSharedTokens?: number;
106
- maxCandidatesPerBlock?: number;
107
- streamResults?: boolean;
108
- severity?: string;
109
- includeTests?: boolean;
110
- useSmartDefaults?: boolean;
111
- groupByFilePair?: boolean;
112
- createClusters?: boolean;
113
- minClusterTokenCost?: number;
114
- minClusterFiles?: number;
115
- excludePatterns?: string[];
116
- confidenceThreshold?: number;
117
- ignoreWhitelist?: string[];
118
- onProgress?: (processed: number, total: number, message: string) => void;
119
- }
120
- interface PatternSummary {
121
- totalPatterns: number;
122
- totalTokenCost: number;
123
- patternsByType: Record<PatternType, number>;
124
- topDuplicates: Array<{
125
- files: Array<{
126
- path: string;
127
- startLine: number;
128
- endLine: number;
129
- }>;
130
- similarity: number;
131
- patternType: PatternType;
132
- tokenCost: number;
133
- }>;
134
- }
135
- /**
136
- * Determine smart defaults based on repository size estimation.
137
- *
138
- * @param directory - The directory to analyze for size.
139
- * @param userOptions - User-provided option overrides.
140
- * @returns Promise resolving to optimal detection options.
141
- */
142
- declare function getSmartDefaults(directory: string, userOptions: Partial<PatternDetectOptions>): Promise<PatternDetectOptions>;
143
- /**
144
- * Main entry point for pattern detection analysis.
145
- *
146
- * @param options - Configuration including rootDir and detection parameters.
147
- * @returns Promise resolving to the comprehensive pattern detect report.
148
- * @lastUpdated 2026-03-18
149
- */
150
- declare function analyzePatterns(options: PatternDetectOptions): Promise<{
151
- results: AnalysisResult[];
152
- duplicates: DuplicatePattern[];
153
- files: string[];
154
- groups?: DuplicateGroup[];
155
- clusters?: RefactorCluster[];
156
- config: PatternDetectOptions;
157
- }>;
158
- /**
159
- * Generate a summary of pattern detection results.
160
- *
161
- * @param results - Array of file-level analysis results.
162
- * @returns Consolidated pattern summary object.
163
- */
164
- declare function generateSummary(results: AnalysisResult[]): PatternSummary;
165
-
166
- /**
167
- * Calculate AI Readiness Score for pattern duplication (0-100)
168
- *
169
- * Based on:
170
- * - Number of duplicates per file
171
- * - Token waste per file
172
- * - High-impact duplicates (>1000 tokens or >70% similarity)
173
- *
174
- * Includes business value metrics:
175
- * - Estimated monthly cost of token waste
176
- * - Estimated developer hours to fix
177
- *
178
- * @param duplicates - Array of detected duplicate patterns.
179
- * @param totalFilesAnalyzed - Total count of files scanned.
180
- * @param costConfig - Optional configuration for business value calculations.
181
- * @returns Standardized scoring output for pattern detection.
182
- */
183
- declare function calculatePatternScore(duplicates: DuplicatePattern[], totalFilesAnalyzed: number, costConfig?: Partial<CostConfig>): ToolScoringOutput;
184
-
185
- /**
186
- * Context-aware severity detection for duplicate patterns
187
- * Identifies intentional duplication patterns and adjusts severity accordingly
188
- */
189
- interface ContextRule {
190
- name: string;
191
- detect: (file: string, code: string) => boolean;
192
- severity: Severity;
193
- reason: string;
194
- suggestion?: string;
195
- }
196
- /**
197
- * Context rules for detecting intentional or acceptable duplication patterns
198
- * Rules are checked in order - first match wins
199
- */
200
- declare const CONTEXT_RULES: ContextRule[];
201
- /**
202
- * Calculate severity based on context rules and code characteristics
203
- *
204
- * @param file1 - First file path in the duplicate pair.
205
- * @param file2 - Second file path in the duplicate pair.
206
- * @param code - Snippet of the duplicated code.
207
- * @param similarity - The calculated similarity score (0-1).
208
- * @param linesOfCode - Number of lines in the duplicated block.
209
- * @returns An object containing the severity level and reasoning.
210
- */
211
- declare function calculateSeverity(file1: string, file2: string, code: string, similarity: number, linesOfCode: number): {
212
- severity: Severity;
213
- reason?: string;
214
- suggestion?: string;
215
- matchedRule?: string;
216
- };
217
- /**
218
- * Get a human-readable severity label with emoji
219
- *
220
- * @param severity - The severity level to label.
221
- * @returns Formatted label string for UI display.
222
- */
223
- declare function getSeverityLabel(severity: Severity): string;
224
- /**
225
- * Filter duplicates by minimum severity threshold
226
- *
227
- * @param duplicates - List of items with a severity property.
228
- * @param minSeverity - Minimum threshold for inclusion.
229
- * @returns Filtered list of items.
230
- */
231
- declare function filterBySeverity<T extends {
232
- severity: Severity;
233
- }>(duplicates: T[], minSeverity: Severity): T[];
234
- /**
235
- * Get numerical similarity threshold associated with a severity level
236
- *
237
- * @param severity - The severity level to look up.
238
- * @returns Minimum similarity value for this severity.
239
- */
240
- declare function getSeverityThreshold(severity: Severity): number;
241
-
242
- export { CONTEXT_RULES, type ContextRule, type DuplicateGroup, type DuplicatePattern, type PatternDetectOptions, PatternDetectProvider, type PatternSummary, type PatternType, type RefactorCluster, analyzePatterns, calculatePatternScore, calculateSeverity, createRefactorClusters, detectDuplicatePatterns, filterBySeverity, filterClustersByImpact, generateSummary, getSeverityLabel, getSeverityThreshold, getSmartDefaults, groupDuplicatesByFilePair };
14
+ export { PatternDetectProvider };
package/dist/index.d.ts CHANGED
@@ -1,242 +1,14 @@
1
- import { ToolProvider, Severity, FileContent, ScanOptions, AnalysisResult, CostConfig, ToolScoringOutput } from '@aiready/core';
1
+ import { ToolProvider } from '@aiready/core';
2
2
  export { Severity } from '@aiready/core';
3
+ export { D as DuplicateGroup, P as PatternDetectOptions, a as PatternSummary, R as RefactorCluster, b as analyzePatterns, c as createRefactorClusters, f as filterClustersByImpact, g as generateSummary, d as getSmartDefaults, e as groupDuplicatesByFilePair } from './analyzer-entry-BwuoiCNm.js';
4
+ export { detectDuplicatePatterns } from './detector-entry.js';
5
+ export { calculatePatternScore } from './scoring-entry.js';
6
+ export { C as CONTEXT_RULES, a as ContextRule, c as calculateSeverity, f as filterBySeverity, g as getSeverityLabel, b as getSeverityThreshold } from './context-rules-entry-y2uJSngh.js';
7
+ export { D as DuplicatePattern, P as PatternType } from './types-DU2mmhwb.js';
3
8
 
4
9
  /**
5
10
  * Pattern Detection Tool Provider
6
11
  */
7
12
  declare const PatternDetectProvider: ToolProvider;
8
13
 
9
- type PatternType = 'api-handler' | 'validator' | 'utility' | 'class-method' | 'component' | 'function' | 'unknown';
10
- interface DuplicatePattern {
11
- file1: string;
12
- line1: number;
13
- endLine1: number;
14
- file2: string;
15
- line2: number;
16
- endLine2: number;
17
- code1: string;
18
- code2: string;
19
- similarity: number;
20
- confidence: number;
21
- patternType: PatternType;
22
- tokenCost: number;
23
- severity: Severity;
24
- reason?: string;
25
- suggestion?: string;
26
- matchedRule?: string;
27
- }
28
- interface DetectionOptions {
29
- minSimilarity: number;
30
- minLines: number;
31
- batchSize: number;
32
- approx: boolean;
33
- minSharedTokens: number;
34
- maxCandidatesPerBlock: number;
35
- streamResults: boolean;
36
- excludePatterns?: string[];
37
- confidenceThreshold?: number;
38
- ignoreWhitelist?: string[];
39
- onProgress?: (processed: number, total: number, message: string) => void;
40
- }
41
-
42
- /**
43
- * Detect duplicate patterns across files
44
- *
45
- * @param fileContents - Array of file contents to analyze.
46
- * @param options - Configuration for duplicate detection (thresholds, progress, etc).
47
- * @returns Promise resolving to an array of detected duplicate patterns sorted by similarity.
48
- */
49
- declare function detectDuplicatePatterns(fileContents: FileContent[], options: DetectionOptions): Promise<DuplicatePattern[]>;
50
-
51
- interface DuplicateGroup {
52
- filePair: string;
53
- severity: Severity;
54
- occurrences: number;
55
- totalTokenCost: number;
56
- averageSimilarity: number;
57
- patternTypes: Set<PatternType>;
58
- lineRanges: Array<{
59
- file1: {
60
- start: number;
61
- end: number;
62
- };
63
- file2: {
64
- start: number;
65
- end: number;
66
- };
67
- }>;
68
- }
69
- interface RefactorCluster {
70
- id: string;
71
- name: string;
72
- files: string[];
73
- severity: Severity;
74
- duplicateCount: number;
75
- totalTokenCost: number;
76
- averageSimilarity: number;
77
- reason?: string;
78
- suggestion?: string;
79
- }
80
- /**
81
- * Group raw duplicates by file pairs to reduce noise
82
- */
83
- declare function groupDuplicatesByFilePair(duplicates: DuplicatePattern[]): DuplicateGroup[];
84
- /**
85
- * Create clusters of highly related files (refactor targets)
86
- * Uses a simple connected components algorithm
87
- * @param duplicates - Array of duplicate patterns to cluster
88
- * @returns Array of refactor clusters
89
- */
90
- declare function createRefactorClusters(duplicates: DuplicatePattern[]): RefactorCluster[];
91
- /**
92
- * Filter clusters by impact threshold
93
- * @param clusters - Array of refactor clusters to filter
94
- * @param minTokenCost - Minimum token cost threshold (default: 1000)
95
- * @param minFiles - Minimum number of files in cluster (default: 3)
96
- * @returns Filtered array of refactor clusters
97
- */
98
- declare function filterClustersByImpact(clusters: RefactorCluster[], minTokenCost?: number, minFiles?: number): RefactorCluster[];
99
-
100
- interface PatternDetectOptions extends ScanOptions {
101
- minSimilarity?: number;
102
- minLines?: number;
103
- batchSize?: number;
104
- approx?: boolean;
105
- minSharedTokens?: number;
106
- maxCandidatesPerBlock?: number;
107
- streamResults?: boolean;
108
- severity?: string;
109
- includeTests?: boolean;
110
- useSmartDefaults?: boolean;
111
- groupByFilePair?: boolean;
112
- createClusters?: boolean;
113
- minClusterTokenCost?: number;
114
- minClusterFiles?: number;
115
- excludePatterns?: string[];
116
- confidenceThreshold?: number;
117
- ignoreWhitelist?: string[];
118
- onProgress?: (processed: number, total: number, message: string) => void;
119
- }
120
- interface PatternSummary {
121
- totalPatterns: number;
122
- totalTokenCost: number;
123
- patternsByType: Record<PatternType, number>;
124
- topDuplicates: Array<{
125
- files: Array<{
126
- path: string;
127
- startLine: number;
128
- endLine: number;
129
- }>;
130
- similarity: number;
131
- patternType: PatternType;
132
- tokenCost: number;
133
- }>;
134
- }
135
- /**
136
- * Determine smart defaults based on repository size estimation.
137
- *
138
- * @param directory - The directory to analyze for size.
139
- * @param userOptions - User-provided option overrides.
140
- * @returns Promise resolving to optimal detection options.
141
- */
142
- declare function getSmartDefaults(directory: string, userOptions: Partial<PatternDetectOptions>): Promise<PatternDetectOptions>;
143
- /**
144
- * Main entry point for pattern detection analysis.
145
- *
146
- * @param options - Configuration including rootDir and detection parameters.
147
- * @returns Promise resolving to the comprehensive pattern detect report.
148
- * @lastUpdated 2026-03-18
149
- */
150
- declare function analyzePatterns(options: PatternDetectOptions): Promise<{
151
- results: AnalysisResult[];
152
- duplicates: DuplicatePattern[];
153
- files: string[];
154
- groups?: DuplicateGroup[];
155
- clusters?: RefactorCluster[];
156
- config: PatternDetectOptions;
157
- }>;
158
- /**
159
- * Generate a summary of pattern detection results.
160
- *
161
- * @param results - Array of file-level analysis results.
162
- * @returns Consolidated pattern summary object.
163
- */
164
- declare function generateSummary(results: AnalysisResult[]): PatternSummary;
165
-
166
- /**
167
- * Calculate AI Readiness Score for pattern duplication (0-100)
168
- *
169
- * Based on:
170
- * - Number of duplicates per file
171
- * - Token waste per file
172
- * - High-impact duplicates (>1000 tokens or >70% similarity)
173
- *
174
- * Includes business value metrics:
175
- * - Estimated monthly cost of token waste
176
- * - Estimated developer hours to fix
177
- *
178
- * @param duplicates - Array of detected duplicate patterns.
179
- * @param totalFilesAnalyzed - Total count of files scanned.
180
- * @param costConfig - Optional configuration for business value calculations.
181
- * @returns Standardized scoring output for pattern detection.
182
- */
183
- declare function calculatePatternScore(duplicates: DuplicatePattern[], totalFilesAnalyzed: number, costConfig?: Partial<CostConfig>): ToolScoringOutput;
184
-
185
- /**
186
- * Context-aware severity detection for duplicate patterns
187
- * Identifies intentional duplication patterns and adjusts severity accordingly
188
- */
189
- interface ContextRule {
190
- name: string;
191
- detect: (file: string, code: string) => boolean;
192
- severity: Severity;
193
- reason: string;
194
- suggestion?: string;
195
- }
196
- /**
197
- * Context rules for detecting intentional or acceptable duplication patterns
198
- * Rules are checked in order - first match wins
199
- */
200
- declare const CONTEXT_RULES: ContextRule[];
201
- /**
202
- * Calculate severity based on context rules and code characteristics
203
- *
204
- * @param file1 - First file path in the duplicate pair.
205
- * @param file2 - Second file path in the duplicate pair.
206
- * @param code - Snippet of the duplicated code.
207
- * @param similarity - The calculated similarity score (0-1).
208
- * @param linesOfCode - Number of lines in the duplicated block.
209
- * @returns An object containing the severity level and reasoning.
210
- */
211
- declare function calculateSeverity(file1: string, file2: string, code: string, similarity: number, linesOfCode: number): {
212
- severity: Severity;
213
- reason?: string;
214
- suggestion?: string;
215
- matchedRule?: string;
216
- };
217
- /**
218
- * Get a human-readable severity label with emoji
219
- *
220
- * @param severity - The severity level to label.
221
- * @returns Formatted label string for UI display.
222
- */
223
- declare function getSeverityLabel(severity: Severity): string;
224
- /**
225
- * Filter duplicates by minimum severity threshold
226
- *
227
- * @param duplicates - List of items with a severity property.
228
- * @param minSeverity - Minimum threshold for inclusion.
229
- * @returns Filtered list of items.
230
- */
231
- declare function filterBySeverity<T extends {
232
- severity: Severity;
233
- }>(duplicates: T[], minSeverity: Severity): T[];
234
- /**
235
- * Get numerical similarity threshold associated with a severity level
236
- *
237
- * @param severity - The severity level to look up.
238
- * @returns Minimum similarity value for this severity.
239
- */
240
- declare function getSeverityThreshold(severity: Severity): number;
241
-
242
- export { CONTEXT_RULES, type ContextRule, type DuplicateGroup, type DuplicatePattern, type PatternDetectOptions, PatternDetectProvider, type PatternSummary, type PatternType, type RefactorCluster, analyzePatterns, calculatePatternScore, calculateSeverity, createRefactorClusters, detectDuplicatePatterns, filterBySeverity, filterClustersByImpact, generateSummary, getSeverityLabel, getSeverityThreshold, getSmartDefaults, groupDuplicatesByFilePair };
14
+ export { PatternDetectProvider };
package/dist/index.js CHANGED
@@ -230,144 +230,27 @@ function getSeverityThreshold(severity) {
230
230
  return thresholds[severity] || 0;
231
231
  }
232
232
 
233
- // src/detector.ts
233
+ // src/core/normalizer.ts
234
234
  function normalizeCode(code, isPython = false) {
235
+ if (!code) return "";
235
236
  let normalized = code;
236
237
  if (isPython) {
237
238
  normalized = normalized.replace(/#.*/g, "");
238
239
  } else {
239
- normalized = normalized.replace(/\/\/.*/g, "").replace(/\/\*[\s\S]*?\*\//g, "");
240
+ normalized = normalized.replace(/\/\/.*$/gm, "").replace(/\/\*[\s\S]*?\*\//g, "");
240
241
  }
241
- return normalized.replace(/['"`]/g, '"').replace(/\s+/g, " ").trim().toLowerCase();
242
+ return normalized.replace(/"[^"]*"/g, '"STR"').replace(/'[^']*'/g, "'STR'").replace(/`[^`]*`/g, "`STR`").replace(/\b\d+\b/g, "NUM").replace(/\s+/g, " ").trim().toLowerCase();
242
243
  }
244
+
245
+ // src/detector.ts
243
246
  function extractBlocks(file, content) {
244
- const isPython = file.toLowerCase().endsWith(".py");
245
- if (isPython) {
246
- return extractBlocksPython(file, content);
247
- }
248
- const blocks = [];
249
- const lines = content.split("\n");
250
- const blockRegex = /^\s*(?:export\s+)?(?:async\s+)?(?:public\s+|private\s+|protected\s+|internal\s+|static\s+|readonly\s+|virtual\s+|abstract\s+|override\s+)*(function|class|interface|type|enum|record|struct|void|func|[a-zA-Z0-9_<>[]]+)\s+([a-zA-Z0-9_]+)(?:\s*\(|(?:\s+extends|\s+implements|\s+where)?\s*\{)|^\s*(?:export\s+)?const\s+([a-zA-Z0-9_]+)\s*=\s*[a-zA-Z0-9_.]+\.object\(|^\s*(app\.(?:get|post|put|delete|patch|use))\(/gm;
251
- let match;
252
- while ((match = blockRegex.exec(content)) !== null) {
253
- const startLine = content.substring(0, match.index).split("\n").length;
254
- let type;
255
- let name;
256
- if (match[1]) {
257
- type = match[1];
258
- name = match[2];
259
- } else if (match[3]) {
260
- type = "const";
261
- name = match[3];
262
- } else {
263
- type = "handler";
264
- name = match[4];
265
- }
266
- let endLine = -1;
267
- let openBraces = 0;
268
- let foundStart = false;
269
- for (let i = match.index; i < content.length; i++) {
270
- if (content[i] === "{") {
271
- openBraces++;
272
- foundStart = true;
273
- } else if (content[i] === "}") {
274
- openBraces--;
275
- }
276
- if (foundStart && openBraces === 0) {
277
- endLine = content.substring(0, i + 1).split("\n").length;
278
- break;
279
- }
280
- }
281
- if (endLine === -1) {
282
- const remaining = content.slice(match.index);
283
- const nextLineMatch = remaining.indexOf("\n");
284
- if (nextLineMatch !== -1) {
285
- endLine = startLine;
286
- } else {
287
- endLine = lines.length;
288
- }
289
- }
290
- endLine = Math.max(startLine, endLine);
291
- const blockCode = lines.slice(startLine - 1, endLine).join("\n");
292
- const tokens = (0, import_core2.estimateTokens)(blockCode);
293
- blocks.push({
294
- file,
295
- startLine,
296
- endLine,
297
- code: blockCode,
298
- tokens,
299
- patternType: inferPatternType(type, name)
300
- });
301
- }
302
- return blocks;
303
- }
304
- function extractBlocksPython(file, content) {
305
- const blocks = [];
306
- const lines = content.split("\n");
307
- const blockRegex = /^\s*(?:async\s+)?(def|class)\s+([a-zA-Z0-9_]+)/gm;
308
- let match;
309
- while ((match = blockRegex.exec(content)) !== null) {
310
- const startLinePos = content.substring(0, match.index).split("\n").length;
311
- const startLineIdx = startLinePos - 1;
312
- const initialIndent = lines[startLineIdx].search(/\S/);
313
- let endLineIdx = startLineIdx;
314
- for (let i = startLineIdx + 1; i < lines.length; i++) {
315
- const line = lines[i];
316
- if (line.trim().length === 0) {
317
- endLineIdx = i;
318
- continue;
319
- }
320
- const currentIndent = line.search(/\S/);
321
- if (currentIndent <= initialIndent) {
322
- break;
323
- }
324
- endLineIdx = i;
325
- }
326
- while (endLineIdx > startLineIdx && lines[endLineIdx].trim().length === 0) {
327
- endLineIdx--;
328
- }
329
- const blockCode = lines.slice(startLineIdx, endLineIdx + 1).join("\n");
330
- const tokens = (0, import_core2.estimateTokens)(blockCode);
331
- blocks.push({
332
- file,
333
- startLine: startLinePos,
334
- endLine: endLineIdx + 1,
335
- code: blockCode,
336
- tokens,
337
- patternType: inferPatternType(match[1], match[2])
338
- });
339
- }
340
- return blocks;
341
- }
342
- function inferPatternType(keyword, name) {
343
- const n = name.toLowerCase();
344
- if (keyword === "handler" || n.includes("handler") || n.includes("controller") || n.startsWith("app.")) {
345
- return "api-handler";
346
- }
347
- if (n.includes("validate") || n.includes("schema")) return "validator";
348
- if (n.includes("util") || n.includes("helper")) return "utility";
349
- if (keyword === "class") return "class-method";
350
- if (n.match(/^[A-Z]/)) return "component";
351
- if (keyword === "function") return "function";
352
- return "unknown";
247
+ return (0, import_core2.extractCodeBlocks)(file, content);
353
248
  }
354
249
  function calculateSimilarity(a, b) {
355
- if (a === b) return 1;
356
- const tokensA = a.split(/[^a-zA-Z0-9]+/).filter((t) => t.length > 0);
357
- const tokensB = b.split(/[^a-zA-Z0-9]+/).filter((t) => t.length > 0);
358
- if (tokensA.length === 0 || tokensB.length === 0) return 0;
359
- const setA = new Set(tokensA);
360
- const setB = new Set(tokensB);
361
- const intersection = new Set([...setA].filter((x) => setB.has(x)));
362
- const union = /* @__PURE__ */ new Set([...setA, ...setB]);
363
- return intersection.size / union.size;
250
+ return (0, import_core2.calculateStringSimilarity)(a, b);
364
251
  }
365
252
  function calculateConfidence(similarity, tokens, lines) {
366
- let confidence = similarity;
367
- if (lines > 20) confidence += 0.05;
368
- if (tokens > 200) confidence += 0.05;
369
- if (lines < 5) confidence -= 0.1;
370
- return Math.max(0, Math.min(1, confidence));
253
+ return (0, import_core2.calculateHeuristicConfidence)(similarity, tokens, lines);
371
254
  }
372
255
  async function detectDuplicatePatterns(fileContents, options) {
373
256
  const {
package/dist/index.mjs CHANGED
@@ -1,20 +1,28 @@
1
1
  import {
2
- CONTEXT_RULES,
3
2
  PatternDetectProvider,
4
- Severity,
3
+ Severity
4
+ } from "./chunk-6JTVOBJX.mjs";
5
+ import {
5
6
  analyzePatterns,
6
- calculatePatternScore,
7
- calculateSeverity,
8
7
  createRefactorClusters,
9
- detectDuplicatePatterns,
10
- filterBySeverity,
11
8
  filterClustersByImpact,
12
9
  generateSummary,
13
- getSeverityLabel,
14
- getSeverityThreshold,
15
10
  getSmartDefaults,
16
11
  groupDuplicatesByFilePair
17
- } from "./chunk-BUBQ3W6W.mjs";
12
+ } from "./chunk-DNZS4ESD.mjs";
13
+ import {
14
+ detectDuplicatePatterns
15
+ } from "./chunk-VGMM3L3O.mjs";
16
+ import {
17
+ CONTEXT_RULES,
18
+ calculateSeverity,
19
+ filterBySeverity,
20
+ getSeverityLabel,
21
+ getSeverityThreshold
22
+ } from "./chunk-I6ETJC7L.mjs";
23
+ import {
24
+ calculatePatternScore
25
+ } from "./chunk-WBBO35SC.mjs";
18
26
  export {
19
27
  CONTEXT_RULES,
20
28
  PatternDetectProvider,