@aiready/pattern-detect 0.17.13 → 0.17.15

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,404 @@
1
+ // src/context-rules.ts
2
+ import {
3
+ IssueType,
4
+ getSeverityLabel,
5
+ filterBySeverity,
6
+ Severity as Severity5
7
+ } from "@aiready/core";
8
+
9
+ // src/rules/categories/test-rules.ts
10
+ import { Severity } from "@aiready/core";
11
+ var TEST_RULES = [
12
+ // Test Fixtures - Intentional duplication for test isolation
13
+ {
14
+ name: "test-fixtures",
15
+ detect: (file, code) => {
16
+ const isTestFile = file.includes(".test.") || file.includes(".spec.") || file.includes("__tests__") || file.includes("/test/") || file.includes("/tests/");
17
+ const hasTestFixtures = code.includes("beforeAll") || code.includes("afterAll") || code.includes("beforeEach") || code.includes("afterEach") || code.includes("setUp") || code.includes("tearDown");
18
+ return isTestFile && hasTestFixtures;
19
+ },
20
+ severity: Severity.Info,
21
+ reason: "Test fixture duplication is intentional for test isolation",
22
+ suggestion: "Consider if shared test setup would improve maintainability without coupling tests"
23
+ },
24
+ // E2E/Integration Test Page Objects - Test independence
25
+ {
26
+ name: "e2e-page-objects",
27
+ detect: (file, code) => {
28
+ const isE2ETest = file.includes("e2e/") || file.includes("/e2e/") || file.includes(".e2e.") || file.includes("/playwright/") || file.includes("playwright/") || file.includes("/cypress/") || file.includes("cypress/") || file.includes("/integration/") || file.includes("integration/");
29
+ const hasPageObjectPatterns = code.includes("page.") || code.includes("await page") || code.includes("locator") || code.includes("getBy") || code.includes("selector") || code.includes("click(") || code.includes("fill(");
30
+ return isE2ETest && hasPageObjectPatterns;
31
+ },
32
+ severity: Severity.Info,
33
+ reason: "E2E test duplication ensures test independence and reduces coupling",
34
+ suggestion: "Consider page object pattern only if duplication causes maintenance issues"
35
+ },
36
+ // Mock Data - Test data intentionally duplicated
37
+ {
38
+ name: "mock-data",
39
+ detect: (file, code) => {
40
+ const isMockFile = file.includes("/mocks/") || file.includes("/__mocks__/") || file.includes("/fixtures/") || file.includes(".mock.") || file.includes(".fixture.");
41
+ const hasMockData = code.includes("mock") || code.includes("Mock") || code.includes("fixture") || code.includes("stub") || code.includes("export const");
42
+ return isMockFile && hasMockData;
43
+ },
44
+ severity: Severity.Info,
45
+ reason: "Mock data duplication is expected for comprehensive test coverage",
46
+ suggestion: "Consider shared factories only for complex mock generation"
47
+ }
48
+ ];
49
+
50
+ // src/rules/categories/web-rules.ts
51
+ import { Severity as Severity2 } from "@aiready/core";
52
+ var WEB_RULES = [
53
+ // Email/Document Templates - Often intentionally similar for consistency
54
+ {
55
+ name: "templates",
56
+ detect: (file, code) => {
57
+ const isTemplate = file.includes("/templates/") || file.includes("-template") || file.includes("/email-templates/") || file.includes("/emails/");
58
+ const hasTemplateContent = (code.includes("return") || code.includes("export")) && (code.includes("html") || code.includes("subject") || code.includes("body"));
59
+ return isTemplate && hasTemplateContent;
60
+ },
61
+ severity: Severity2.Info,
62
+ reason: "Template duplication may be intentional for maintainability and branding consistency",
63
+ suggestion: "Extract shared structure only if templates become hard to maintain"
64
+ },
65
+ // Common UI Event Handlers - Very specific patterns only
66
+ {
67
+ name: "common-ui-handlers",
68
+ detect: (file, code) => {
69
+ const isUIFile = file.includes("/components/") || file.includes(".tsx") || file.includes(".jsx") || file.includes("/hooks/");
70
+ const hasCommonHandler = code.includes("handleClickOutside") && code.includes("dropdownRef.current") && code.includes("!dropdownRef.current.contains") || code.includes("handleEscape") && code.includes("event.key") && code.includes("=== 'Escape'") || code.includes("handleClickInside") && code.includes("event.stopPropagation");
71
+ return isUIFile && hasCommonHandler;
72
+ },
73
+ severity: Severity2.Info,
74
+ reason: "Common UI event handlers are boilerplate patterns that repeat across components",
75
+ suggestion: "Consider extracting to shared hooks (useClickOutside, useEscapeKey) only if causing maintenance issues"
76
+ },
77
+ // Next.js Route Handler Patterns - Boilerplate API route patterns
78
+ {
79
+ name: "nextjs-route-handlers",
80
+ detect: (file, code) => {
81
+ const isRouteFile = file.includes("/api/") && (file.endsWith("/route.ts") || file.endsWith("/route.js"));
82
+ const hasRoutePattern = code.includes("export async function POST") || code.includes("export async function GET") || code.includes("export async function PUT") || code.includes("export async function DELETE") || code.includes("NextResponse.json") || code.includes("NextRequest");
83
+ return isRouteFile && hasRoutePattern;
84
+ },
85
+ severity: Severity2.Info,
86
+ reason: "Next.js route handlers follow standard patterns and are intentionally similar across endpoints",
87
+ suggestion: "Route handler duplication is acceptable for API endpoint boilerplate"
88
+ }
89
+ ];
90
+
91
+ // src/rules/categories/infra-rules.ts
92
+ import { Severity as Severity3 } from "@aiready/core";
93
+ var INFRA_RULES = [
94
+ // Configuration Files - Often necessarily similar by design
95
+ {
96
+ name: "config-files",
97
+ detect: (file) => {
98
+ return file.endsWith(".config.ts") || file.endsWith(".config.js") || file.includes("jest.config") || file.includes("vite.config") || file.includes("webpack.config") || file.includes("rollup.config") || file.includes("tsconfig");
99
+ },
100
+ severity: Severity3.Info,
101
+ reason: "Configuration files often have similar structure by design",
102
+ suggestion: "Consider shared config base only if configurations become hard to maintain"
103
+ },
104
+ // Migration Scripts - One-off scripts that are similar by nature
105
+ {
106
+ name: "migration-scripts",
107
+ detect: (file) => {
108
+ return file.includes("/migrations/") || file.includes("/migrate/") || file.includes(".migration.");
109
+ },
110
+ severity: Severity3.Info,
111
+ reason: "Migration scripts are typically one-off and intentionally similar",
112
+ suggestion: "Duplication is acceptable for migration scripts"
113
+ },
114
+ // Tool Implementations - Structural Boilerplate
115
+ {
116
+ name: "tool-implementations",
117
+ detect: (file, code) => {
118
+ const isToolFile = file.includes("/tools/") || file.endsWith(".tool.ts") || code.includes("toolDefinitions");
119
+ const hasToolStructure = code.includes("execute") && (code.includes("try") || code.includes("catch"));
120
+ return isToolFile && hasToolStructure;
121
+ },
122
+ severity: Severity3.Info,
123
+ reason: "Tool implementations share structural boilerplate but have distinct business logic",
124
+ suggestion: "Tool duplication is acceptable for boilerplate interface wrappers"
125
+ },
126
+ // CLI Command Definitions - Commander.js boilerplate patterns
127
+ {
128
+ name: "cli-command-definitions",
129
+ detect: (file, code) => {
130
+ const basename = file.split("/").pop() || "";
131
+ const isCliFile = file.includes("/commands/") || file.includes("/cli/") || file.endsWith(".command.ts") || basename === "cli.ts" || basename === "cli.js" || basename === "cli.tsx" || basename === "cli-action.ts";
132
+ const hasCommandPattern = (code.includes(".command(") || code.includes("defineCommand")) && (code.includes(".description(") || code.includes(".option(")) && (code.includes(".action(") || code.includes("async"));
133
+ return isCliFile && hasCommandPattern;
134
+ },
135
+ severity: Severity3.Info,
136
+ reason: "CLI command definitions follow standard Commander.js patterns and are intentionally similar",
137
+ suggestion: "Command boilerplate duplication is acceptable for CLI interfaces"
138
+ },
139
+ // DynamoDB Single-Table Design - Standard single-table patterns with prefixed keys
140
+ {
141
+ name: "dynamodb-single-table",
142
+ detect: (file, code) => {
143
+ const hasDynamoDBPattern = code.includes("docClient") || code.includes("dynamodb") || code.includes("DynamoDB") || code.includes("queryItems") || code.includes("putItem") || code.includes("getItem") || code.includes("updateItem") || code.includes("deleteItem");
144
+ const hasKeyPrefix = code.includes("userId:") && code.includes("#") || code.includes("pk:") && code.includes("#") || code.includes("Key:") && code.includes("#") || /[A-Z]+#/.test(code);
145
+ const hasSingleTablePattern = code.includes("KeyConditionExpression") || code.includes("pk =") || code.includes("sk =") || code.includes("userId") && code.includes("timestamp");
146
+ return hasDynamoDBPattern && (hasKeyPrefix || hasSingleTablePattern);
147
+ },
148
+ severity: Severity3.Info,
149
+ reason: "DynamoDB single-table design with prefixed keys is a standard pattern for efficient data access",
150
+ suggestion: "Single-table query patterns are intentionally similar and should not be refactored"
151
+ },
152
+ // CLI Main Function Boilerplate - Standard argument parsing patterns
153
+ {
154
+ name: "cli-main-boilerplate",
155
+ detect: (file, code) => {
156
+ const basename = file.split("/").pop() || "";
157
+ const isCliFile = file.includes("/cli/") || file.includes("/commands/") || basename.startsWith("cli") || basename.endsWith(".cli.ts") || basename.endsWith(".cli.js");
158
+ const hasMainFunction = code.includes("function main()") || code.includes("async function main()") || code.includes("const main =") || code.includes("main()");
159
+ const hasArgParsing = code.includes("process.argv") || code.includes("yargs") || code.includes("commander") || code.includes("minimist") || code.includes(".parse(") || code.includes("args") && code.includes("._");
160
+ return isCliFile && hasMainFunction && hasArgParsing;
161
+ },
162
+ severity: Severity3.Info,
163
+ reason: "CLI main functions with argument parsing follow standard boilerplate patterns",
164
+ suggestion: "CLI argument parsing boilerplate is acceptable and should not be flagged as duplication"
165
+ }
166
+ ];
167
+
168
+ // src/rules/categories/logic-rules.ts
169
+ import { Severity as Severity4 } from "@aiready/core";
170
+ var LOGIC_RULES = [
171
+ // Enum Semantic Difference - Different enum names indicate different semantic meanings
172
+ {
173
+ name: "enum-semantic-difference",
174
+ detect: (file, code) => {
175
+ const enumRegex = /(?:export\s+)?(?:const\s+)?enum\s+([A-Z][a-zA-Z0-9]*)/g;
176
+ const enums = [];
177
+ let match;
178
+ while ((match = enumRegex.exec(code)) !== null) {
179
+ enums.push(match[1]);
180
+ }
181
+ return enums.length > 0;
182
+ },
183
+ severity: Severity4.Info,
184
+ reason: "Enums with different names represent different semantic domain concepts, even if they share similar values",
185
+ suggestion: "Different enums (e.g., EscalationPriority vs HealthSeverity) serve different purposes and should not be merged"
186
+ },
187
+ // Enum Value Similarity - Common enum values like LOW, MEDIUM, HIGH are standard
188
+ {
189
+ name: "enum-value-similarity",
190
+ detect: (file, code) => {
191
+ const hasCommonEnumValues = (code.includes("LOW = 'low'") || code.includes("LOW = 0") || code.includes("LOW = 'LOW'")) && (code.includes("HIGH = 'high'") || code.includes("HIGH = 2") || code.includes("HIGH = 'HIGH'")) && (code.includes("MEDIUM = 'medium'") || code.includes("MEDIUM = 1") || code.includes("MEDIUM = 'MEDIUM'"));
192
+ const isEnumDefinition = /(?:export\s+)?(?:const\s+)?enum\s+/.test(code) || code.includes("enum ") && code.includes("{") && code.includes("}");
193
+ return hasCommonEnumValues && isEnumDefinition;
194
+ },
195
+ severity: Severity4.Info,
196
+ reason: "Common enum values (LOW, MEDIUM, HIGH, CRITICAL) are standard patterns used across different domain enums",
197
+ suggestion: "Enum value similarity is expected for severity/priority enums and should not be flagged as duplication"
198
+ },
199
+ // Re-export / Barrel files - Intentional API surface consolidation
200
+ {
201
+ name: "re-export-files",
202
+ detect: (file, code) => {
203
+ const isIndexFile = file.endsWith("/index.ts") || file.endsWith("/index.js") || file.endsWith("/index.tsx") || file.endsWith("/index.jsx");
204
+ const lines = code.split("\n").filter((l) => l.trim());
205
+ if (lines.length === 0) return false;
206
+ const reExportLines = lines.filter(
207
+ (l) => /^export\s+(\{[^}]+\}|\*)\s+from\s+/.test(l.trim()) || /^export\s+\*\s+as\s+\w+\s+from\s+/.test(l.trim())
208
+ ).length;
209
+ return isIndexFile && reExportLines > 0 && reExportLines / lines.length > 0.5;
210
+ },
211
+ severity: Severity4.Info,
212
+ reason: "Barrel/index files intentionally re-export for API surface consolidation",
213
+ suggestion: "Re-exports in barrel files are expected and not true duplication"
214
+ },
215
+ // Type Definitions - Duplication for type safety and module independence
216
+ {
217
+ name: "type-definitions",
218
+ detect: (file, code) => {
219
+ const isTypeFile = file.endsWith(".d.ts") || file.includes("/types/");
220
+ const hasOnlyTypeDefinitions = (code.includes("interface ") || code.includes("type ") || code.includes("enum ")) && !code.includes("function ") && !code.includes("class ") && !code.includes("const ") && !code.includes("let ") && !code.includes("export default");
221
+ const isInterfaceOnlySnippet = code.trim().startsWith("interface ") && code.includes("{") && code.includes("}") && !code.includes("function ") && !code.includes("const ") && !code.includes("return ");
222
+ return isTypeFile && hasOnlyTypeDefinitions || isInterfaceOnlySnippet;
223
+ },
224
+ severity: Severity4.Info,
225
+ reason: "Type/interface definitions are intentionally duplicated for module independence",
226
+ suggestion: "Extract to shared types package only if causing maintenance burden"
227
+ },
228
+ // Cross-Package Type Definitions - Different packages may have similar types
229
+ {
230
+ name: "cross-package-types",
231
+ detect: (file, code) => {
232
+ const hasTypeDefinition = code.includes("interface ") || code.includes("type ") || code.includes("enum ");
233
+ const isPackageOrApp = file.includes("/packages/") || file.includes("/apps/") || file.includes("/core/");
234
+ const packageMatch = file.match(/\/(packages|apps|core)\/([^/]+)\//);
235
+ const hasPackageStructure = packageMatch !== null;
236
+ return hasTypeDefinition && isPackageOrApp && hasPackageStructure;
237
+ },
238
+ severity: Severity4.Info,
239
+ reason: "Types in different packages/modules are often intentionally similar for module independence",
240
+ suggestion: "Cross-package type duplication is acceptable for decoupled module architecture"
241
+ },
242
+ // Utility Functions - Small helpers in dedicated utility files
243
+ {
244
+ name: "utility-functions",
245
+ detect: (file, code) => {
246
+ const isUtilFile = file.endsWith(".util.ts") || file.endsWith(".helper.ts") || file.endsWith(".utils.ts");
247
+ const hasUtilPattern = code.includes("function format") || code.includes("function parse") || code.includes("function sanitize") || code.includes("function normalize") || code.includes("function convert");
248
+ return isUtilFile && hasUtilPattern;
249
+ },
250
+ severity: Severity4.Info,
251
+ reason: "Utility functions in dedicated utility files may be intentionally similar",
252
+ suggestion: "Consider extracting to shared utilities only if causing significant duplication"
253
+ },
254
+ // React/Vue Hooks - Standard patterns
255
+ {
256
+ name: "shared-hooks",
257
+ detect: (file, code) => {
258
+ const isHookFile = file.includes("/hooks/") || file.endsWith(".hook.ts") || file.endsWith(".hook.tsx");
259
+ const hasHookPattern = code.includes("function use") || code.includes("export function use") || code.includes("const use") || code.includes("export const use");
260
+ return isHookFile && hasHookPattern;
261
+ },
262
+ severity: Severity4.Info,
263
+ reason: "Hooks follow standard patterns and are often intentionally similar across components",
264
+ suggestion: "Consider extracting common hook logic only if hooks become complex"
265
+ },
266
+ // Score/Rating Helper Functions - Common threshold patterns
267
+ {
268
+ name: "score-helpers",
269
+ detect: (file, code) => {
270
+ const isHelperFile = file.includes("/utils/") || file.includes("/helpers/") || file.endsWith(".util.ts");
271
+ const hasScorePattern = (code.includes("if (score >=") || code.includes("if (score >")) && code.includes("return") && code.includes("'") && code.split("if (score").length >= 3;
272
+ return isHelperFile && hasScorePattern;
273
+ },
274
+ severity: Severity4.Info,
275
+ reason: "Score/rating helper functions use common threshold patterns that are intentionally similar",
276
+ suggestion: "Score formatting duplication is acceptable for consistent UI display"
277
+ },
278
+ // D3/Canvas Event Handlers - Standard visualization patterns
279
+ {
280
+ name: "visualization-handlers",
281
+ detect: (file, code) => {
282
+ const isVizFile = file.includes("/visualizer/") || file.includes("/charts/") || file.includes("GraphCanvas") || file.includes("ForceDirected");
283
+ const hasVizPattern = (code.includes("dragstarted") || code.includes("dragged") || code.includes("dragended")) && (code.includes("simulation") || code.includes("d3.") || code.includes("alphaTarget"));
284
+ return isVizFile && hasVizPattern;
285
+ },
286
+ severity: Severity4.Info,
287
+ reason: "D3/visualization event handlers follow standard patterns and are intentionally similar",
288
+ suggestion: "Visualization boilerplate duplication is acceptable for interactive charts"
289
+ },
290
+ // Icon/Switch Statement Helpers - Common enum-to-value patterns
291
+ {
292
+ name: "switch-helpers",
293
+ detect: (file, code) => {
294
+ const hasSwitchPattern = code.includes("switch (") && code.includes("case '") && code.includes("return") && code.split("case ").length >= 4;
295
+ const hasIconPattern = code.includes("getIcon") || code.includes("getColor") || code.includes("getLabel") || code.includes("getRating");
296
+ return hasSwitchPattern && hasIconPattern;
297
+ },
298
+ severity: Severity4.Info,
299
+ reason: "Switch statement helpers for enum-to-value mapping are inherently similar",
300
+ suggestion: "Switch duplication is acceptable for mapping enums to display values"
301
+ },
302
+ // Common API/Utility Functions - Legitimate duplication across modules
303
+ {
304
+ name: "common-api-functions",
305
+ detect: (file, code) => {
306
+ const isApiFile = file.includes("/api/") || file.includes("/lib/") || file.includes("/utils/") || file.endsWith(".ts");
307
+ const hasCommonApiPattern = code.includes("getStripe") && code.includes("process.env.STRIPE_SECRET_KEY") || code.includes("getUserByEmail") && code.includes("queryItems") || code.includes("updateUser") && code.includes("buildUpdateExpression") || code.includes("listUserRepositories") && code.includes("queryItems") || code.includes("listTeamRepositories") && code.includes("queryItems") || code.includes("getRemediation") && code.includes("queryItems") || code.includes("formatBreakdownKey") && code.includes(".replace(/([A-Z])/g") || code.includes("queryItems") && code.includes("KeyConditionExpression") || code.includes("putItem") && code.includes("createdAt") || code.includes("updateItem") && code.includes("buildUpdateExpression");
308
+ return isApiFile && hasCommonApiPattern;
309
+ },
310
+ severity: Severity4.Info,
311
+ reason: "Common API/utility functions are legitimately duplicated across modules for clarity and independence",
312
+ suggestion: "Consider extracting to shared utilities only if causing significant duplication"
313
+ },
314
+ // Validation Functions - Inherently similar patterns
315
+ {
316
+ name: "validation-functions",
317
+ detect: (file, code) => {
318
+ const hasValidationPattern = code.includes("isValid") || code.includes("validate") || code.includes("checkValid") || code.includes("isEmail") || code.includes("isPhone") || code.includes("isUrl") || code.includes("isNumeric") || code.includes("isAlpha") || code.includes("isAlphanumeric") || code.includes("isEmpty") || code.includes("isNotEmpty") || code.includes("isRequired") || code.includes("isOptional");
319
+ return hasValidationPattern;
320
+ },
321
+ severity: Severity4.Info,
322
+ reason: "Validation functions are inherently similar and often intentionally duplicated for domain clarity",
323
+ suggestion: "Consider extracting to shared validators only if validation logic becomes complex"
324
+ },
325
+ // Singleton Getter Pattern - Standard singleton initialization pattern
326
+ {
327
+ name: "singleton-getter",
328
+ detect: (file, code) => {
329
+ const hasSingletonGetter = /(?:export\s+)?(?:async\s+)?function\s+get[A-Z][a-zA-Z0-9]*\s*\(/.test(code) || /(?:export\s+)?const\s+get[A-Z][a-zA-Z0-9]*\s*=\s*(?:async\s+)?\(\)\s*=>/.test(code);
330
+ const hasSingletonPattern = code.includes("if (!") && code.includes("instance") && code.includes(" = ") || code.includes("if (!_") && code.includes(" = new ") || code.includes("if (") && code.includes(" === null") && code.includes(" = new ");
331
+ return hasSingletonGetter && hasSingletonPattern;
332
+ },
333
+ severity: Severity4.Info,
334
+ reason: "Singleton getter functions follow standard initialization pattern and are intentionally similar",
335
+ suggestion: "Singleton getters are boilerplate and acceptable duplication for lazy initialization"
336
+ }
337
+ ];
338
+
339
+ // src/context-rules.ts
340
+ var CONTEXT_RULES = [
341
+ ...TEST_RULES,
342
+ ...WEB_RULES,
343
+ ...INFRA_RULES,
344
+ ...LOGIC_RULES
345
+ ];
346
+ function calculateSeverity(file1, file2, code, similarity, linesOfCode) {
347
+ for (const rule of CONTEXT_RULES) {
348
+ if (rule.detect(file1, code) || rule.detect(file2, code)) {
349
+ return {
350
+ severity: rule.severity,
351
+ reason: rule.reason,
352
+ suggestion: rule.suggestion,
353
+ matchedRule: rule.name
354
+ };
355
+ }
356
+ }
357
+ if (similarity >= 0.95 && linesOfCode >= 30) {
358
+ return {
359
+ severity: Severity5.Critical,
360
+ reason: "Large nearly-identical code blocks waste tokens and create maintenance burden",
361
+ suggestion: "Extract to shared utility module immediately"
362
+ };
363
+ } else if (similarity >= 0.95 && linesOfCode >= 15) {
364
+ return {
365
+ severity: Severity5.Major,
366
+ reason: "Nearly identical code should be consolidated",
367
+ suggestion: "Move to shared utility file"
368
+ };
369
+ } else if (similarity >= 0.85) {
370
+ return {
371
+ severity: Severity5.Major,
372
+ reason: "High similarity indicates significant duplication",
373
+ suggestion: "Extract common logic to shared function"
374
+ };
375
+ } else if (similarity >= 0.7) {
376
+ return {
377
+ severity: Severity5.Minor,
378
+ reason: "Moderate similarity detected",
379
+ suggestion: "Consider extracting shared patterns if code evolves together"
380
+ };
381
+ } else {
382
+ return {
383
+ severity: Severity5.Minor,
384
+ reason: "Minor similarity detected",
385
+ suggestion: "Monitor but refactoring may not be worthwhile"
386
+ };
387
+ }
388
+ }
389
+ function getSeverityThreshold(severity) {
390
+ const thresholds = {
391
+ [Severity5.Critical]: 0.95,
392
+ [Severity5.Major]: 0.85,
393
+ [Severity5.Minor]: 0.5,
394
+ [Severity5.Info]: 0
395
+ };
396
+ return thresholds[severity] || 0;
397
+ }
398
+
399
+ export {
400
+ getSeverityLabel,
401
+ filterBySeverity,
402
+ calculateSeverity,
403
+ getSeverityThreshold
404
+ };