@angular-modernizer/plugin-solid 0.1.0
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.
- package/LICENSE +21 -0
- package/README.md +835 -0
- package/dist/index.d.ts +21 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +37 -0
- package/dist/index.js.map +1 -0
- package/dist/orchestrators/god-switch-transform-orchestrator.d.ts +350 -0
- package/dist/orchestrators/god-switch-transform-orchestrator.d.ts.map +1 -0
- package/dist/orchestrators/god-switch-transform-orchestrator.js +1165 -0
- package/dist/orchestrators/god-switch-transform-orchestrator.js.map +1 -0
- package/dist/orchestrators/service-dip-violation-transform.orchestrator.d.ts +72 -0
- package/dist/orchestrators/service-dip-violation-transform.orchestrator.d.ts.map +1 -0
- package/dist/orchestrators/service-dip-violation-transform.orchestrator.js +243 -0
- package/dist/orchestrators/service-dip-violation-transform.orchestrator.js.map +1 -0
- package/dist/rules/dip-violation.rule.d.ts +54 -0
- package/dist/rules/dip-violation.rule.d.ts.map +1 -0
- package/dist/rules/dip-violation.rule.js +156 -0
- package/dist/rules/dip-violation.rule.js.map +1 -0
- package/dist/rules/god-switch-analysis.rule.d.ts +73 -0
- package/dist/rules/god-switch-analysis.rule.d.ts.map +1 -0
- package/dist/rules/god-switch-analysis.rule.js +174 -0
- package/dist/rules/god-switch-analysis.rule.js.map +1 -0
- package/dist/rules/isp-violation.rule.d.ts +62 -0
- package/dist/rules/isp-violation.rule.d.ts.map +1 -0
- package/dist/rules/isp-violation.rule.js +250 -0
- package/dist/rules/isp-violation.rule.js.map +1 -0
- package/dist/rules/lsp-violation.rule.d.ts +57 -0
- package/dist/rules/lsp-violation.rule.d.ts.map +1 -0
- package/dist/rules/lsp-violation.rule.js +321 -0
- package/dist/rules/lsp-violation.rule.js.map +1 -0
- package/dist/rules/ocp-violation.rule.d.ts +69 -0
- package/dist/rules/ocp-violation.rule.d.ts.map +1 -0
- package/dist/rules/ocp-violation.rule.js +204 -0
- package/dist/rules/ocp-violation.rule.js.map +1 -0
- package/dist/rules/service-dip-violation.analysis.rule.d.ts +85 -0
- package/dist/rules/service-dip-violation.analysis.rule.d.ts.map +1 -0
- package/dist/rules/service-dip-violation.analysis.rule.js +217 -0
- package/dist/rules/service-dip-violation.analysis.rule.js.map +1 -0
- package/dist/rules/srp-violation.rule.d.ts +71 -0
- package/dist/rules/srp-violation.rule.d.ts.map +1 -0
- package/dist/rules/srp-violation.rule.js +307 -0
- package/dist/rules/srp-violation.rule.js.map +1 -0
- package/dist/solid-plugin.d.ts +82 -0
- package/dist/solid-plugin.d.ts.map +1 -0
- package/dist/solid-plugin.js +115 -0
- package/dist/solid-plugin.js.map +1 -0
- package/dist/transform-rules/god-switch-transform.rule.d.ts +128 -0
- package/dist/transform-rules/god-switch-transform.rule.d.ts.map +1 -0
- package/dist/transform-rules/god-switch-transform.rule.js +167 -0
- package/dist/transform-rules/god-switch-transform.rule.js.map +1 -0
- package/dist/transform-rules/service-dip-violation.transform.rule.d.ts +75 -0
- package/dist/transform-rules/service-dip-violation.transform.rule.d.ts.map +1 -0
- package/dist/transform-rules/service-dip-violation.transform.rule.js +115 -0
- package/dist/transform-rules/service-dip-violation.transform.rule.js.map +1 -0
- package/package.json +59 -0
- package/src/index.ts +30 -0
- package/src/orchestrators/god-switch-transform-orchestrator.ts +1562 -0
- package/src/orchestrators/service-dip-violation-transform.orchestrator.ts +331 -0
- package/src/rules/dip-violation.rule.ts +194 -0
- package/src/rules/god-switch-analysis.rule.ts +209 -0
- package/src/rules/isp-violation.rule.ts +315 -0
- package/src/rules/lsp-violation.rule.ts +393 -0
- package/src/rules/ocp-violation.rule.ts +264 -0
- package/src/rules/service-dip-violation.analysis.rule.ts +285 -0
- package/src/rules/srp-violation.rule.ts +366 -0
- package/src/solid-plugin.ts +127 -0
- package/src/transform-rules/god-switch-transform.rule.ts +189 -0
- package/src/transform-rules/service-dip-violation.transform.rule.ts +134 -0
package/README.md
ADDED
|
@@ -0,0 +1,835 @@
|
|
|
1
|
+
# @angular-modernizer/plugin-solid
|
|
2
|
+
|
|
3
|
+
SOLID principle violation detection and architectural analysis for Angular codebases.
|
|
4
|
+
|
|
5
|
+
## Overview
|
|
6
|
+
|
|
7
|
+
The `@angular-modernizer/plugin-solid` package provides analysis rules for detecting violations of SOLID principles and other architectural issues. This plugin powers the `scan-solid` tool in the MCP server.
|
|
8
|
+
|
|
9
|
+
## SOLID Principles Coverage
|
|
10
|
+
|
|
11
|
+
### Single Responsibility Principle (SRP)
|
|
12
|
+
|
|
13
|
+
Detects classes that have too many responsibilities by examining class sizes, method counts, and coupling metrics. Also detects single methods that mix 4 or more concern categories across 20 or more lines.
|
|
14
|
+
|
|
15
|
+
### Open/Closed Principle (OCP)
|
|
16
|
+
|
|
17
|
+
Identifies code that requires modification to extend behavior, including switch statements and if-else chains that grow with each new case.
|
|
18
|
+
|
|
19
|
+
### Liskov Substitution Principle (LSP)
|
|
20
|
+
|
|
21
|
+
Finds inheritance hierarchies where subclasses break substitutability by overriding behavior in incompatible ways.
|
|
22
|
+
|
|
23
|
+
### Interface Segregation Principle (ISP)
|
|
24
|
+
|
|
25
|
+
Detects fat interfaces that force unnecessary dependencies on implementing classes.
|
|
26
|
+
|
|
27
|
+
### Dependency Inversion Principle (DIP)
|
|
28
|
+
|
|
29
|
+
Finds direct instantiation and tight coupling violations, including `new` expressions for services and concrete constructor dependencies.
|
|
30
|
+
|
|
31
|
+
## Analysis Rules
|
|
32
|
+
|
|
33
|
+
### SRPSingleResponsibilityViolationRule
|
|
34
|
+
|
|
35
|
+
**Rule ID:** `solid:srp-single-responsibility-violation`
|
|
36
|
+
**Severity:** Warning
|
|
37
|
+
|
|
38
|
+
Detects classes with more than 15 public methods or mixed responsibility categories across 3 or more distinct concern domains. Also detects single methods that mix 4 or more concern categories across 20 or more lines.
|
|
39
|
+
|
|
40
|
+
---
|
|
41
|
+
|
|
42
|
+
### DIPViolationRule
|
|
43
|
+
|
|
44
|
+
**Rule ID:** `solid:dip-violation-direct-instantiation`
|
|
45
|
+
**Severity:** High
|
|
46
|
+
|
|
47
|
+
Detects direct instantiation of services and the service locator anti-pattern.
|
|
48
|
+
|
|
49
|
+
Detection patterns:
|
|
50
|
+
- `new MyService()` in constructors or methods
|
|
51
|
+
- `new MyRepository()` in component methods
|
|
52
|
+
- Direct instantiation of classes ending with "Service", "Repository", "Store"
|
|
53
|
+
- `injector.get()` service locator calls
|
|
54
|
+
|
|
55
|
+
**Before:**
|
|
56
|
+
|
|
57
|
+
```typescript
|
|
58
|
+
// Direct instantiation
|
|
59
|
+
@Component({...})
|
|
60
|
+
export class UserComponent {
|
|
61
|
+
private userService = new UserService(); // DIP violation
|
|
62
|
+
private httpClient = new HttpClient(); // DIP violation
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
// Service locator
|
|
66
|
+
constructor(private injector: Injector) {
|
|
67
|
+
this.service = injector.get(UserService); // DIP violation
|
|
68
|
+
}
|
|
69
|
+
```
|
|
70
|
+
|
|
71
|
+
**After:**
|
|
72
|
+
|
|
73
|
+
```typescript
|
|
74
|
+
@Component({...})
|
|
75
|
+
export class UserComponent {
|
|
76
|
+
private userService = inject(UserService);
|
|
77
|
+
private httpClient = inject(HttpClient);
|
|
78
|
+
}
|
|
79
|
+
```
|
|
80
|
+
|
|
81
|
+
**Analysis Result:**
|
|
82
|
+
|
|
83
|
+
```json
|
|
84
|
+
{
|
|
85
|
+
"ruleId": "solid:dip-violation-direct-instantiation",
|
|
86
|
+
"violations": [
|
|
87
|
+
{
|
|
88
|
+
"id": "dip-violation-1",
|
|
89
|
+
"severity": "high",
|
|
90
|
+
"message": "Direct instantiation of UserService violates Dependency Inversion Principle",
|
|
91
|
+
"location": {
|
|
92
|
+
"filePath": "src/app/user.component.ts",
|
|
93
|
+
"startLine": 5,
|
|
94
|
+
"startColumn": 25
|
|
95
|
+
},
|
|
96
|
+
"category": "solid-violation",
|
|
97
|
+
"autoFix": {
|
|
98
|
+
"type": "inject-conversion",
|
|
99
|
+
"description": "Convert to dependency injection using inject()"
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
]
|
|
103
|
+
}
|
|
104
|
+
```
|
|
105
|
+
|
|
106
|
+
---
|
|
107
|
+
|
|
108
|
+
### DIPConcreteDependencyRule
|
|
109
|
+
|
|
110
|
+
**Rule ID:** `solid:dip-violation-concrete-dependency`
|
|
111
|
+
**Severity:** Warning
|
|
112
|
+
|
|
113
|
+
Detects constructor parameters that inject concrete `@Injectable` classes rather than interfaces. Has a transform counterpart (`ServiceDipViolationTransformOrchestrator`) in this plugin that creates an `I{ClassName}` interface and `InjectionToken` in the service file, and updates the consuming file with an `@Inject` decorator.
|
|
114
|
+
|
|
115
|
+
---
|
|
116
|
+
|
|
117
|
+
### GodSwitchAnalysisRule
|
|
118
|
+
|
|
119
|
+
**Rule ID:** `solid:god-switch`
|
|
120
|
+
**Severity:** Warning
|
|
121
|
+
|
|
122
|
+
Detects switch statements with too many cases (default threshold: 10), classified by switch type.
|
|
123
|
+
|
|
124
|
+
Detection patterns:
|
|
125
|
+
- Switch statements exceeding the configurable threshold
|
|
126
|
+
- Classification by switch type: type-based, status-based, action-based, event-based, command-based, state-based, kind-based, category-based
|
|
127
|
+
- Confidence scoring for violations (0.7 to 1.0)
|
|
128
|
+
|
|
129
|
+
**Before:**
|
|
130
|
+
|
|
131
|
+
```typescript
|
|
132
|
+
// God Switch with 15 cases
|
|
133
|
+
export class OrderProcessor {
|
|
134
|
+
processOrder(status: string): void {
|
|
135
|
+
switch (status) {
|
|
136
|
+
case 'pending': break;
|
|
137
|
+
case 'processing': break;
|
|
138
|
+
case 'shipped': break;
|
|
139
|
+
case 'delivered': break;
|
|
140
|
+
case 'cancelled': break;
|
|
141
|
+
case 'refunded': break;
|
|
142
|
+
case 'returned': break;
|
|
143
|
+
case 'failed': break;
|
|
144
|
+
case 'on-hold': break;
|
|
145
|
+
case 'completed': break;
|
|
146
|
+
case 'archived': break;
|
|
147
|
+
case 'disputed': break;
|
|
148
|
+
case 'escalated': break;
|
|
149
|
+
case 'resolved': break;
|
|
150
|
+
case 'closed': break;
|
|
151
|
+
default: break;
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
```
|
|
156
|
+
|
|
157
|
+
**After (Factory Pattern):**
|
|
158
|
+
|
|
159
|
+
```typescript
|
|
160
|
+
interface OrderStatusStrategy {
|
|
161
|
+
execute(): void;
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
class PendingStrategy implements OrderStatusStrategy {
|
|
165
|
+
execute(): void { /* ... */ }
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
class ProcessingStrategy implements OrderStatusStrategy {
|
|
169
|
+
execute(): void { /* ... */ }
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
// ... more strategy classes
|
|
173
|
+
|
|
174
|
+
class OrderStatusFactory {
|
|
175
|
+
private strategies = new Map<string, OrderStatusStrategy>([
|
|
176
|
+
['pending', new PendingStrategy()],
|
|
177
|
+
['processing', new ProcessingStrategy()],
|
|
178
|
+
// ... more strategies
|
|
179
|
+
]);
|
|
180
|
+
|
|
181
|
+
createStrategy(status: string): OrderStatusStrategy {
|
|
182
|
+
return this.strategies.get(status) ?? new DefaultStrategy();
|
|
183
|
+
}
|
|
184
|
+
}
|
|
185
|
+
```
|
|
186
|
+
|
|
187
|
+
**Analysis Result:**
|
|
188
|
+
|
|
189
|
+
```json
|
|
190
|
+
{
|
|
191
|
+
"ruleId": "solid:god-switch",
|
|
192
|
+
"message": "God Switch detected: 15 cases (status-based). Consider Factory Pattern.",
|
|
193
|
+
"filePath": "src/app/order-processor.ts",
|
|
194
|
+
"line": 3,
|
|
195
|
+
"column": 4,
|
|
196
|
+
"suggestedFix": "Refactor to Factory Pattern with strategy objects for each case type",
|
|
197
|
+
"metadata": {
|
|
198
|
+
"caseCount": 15,
|
|
199
|
+
"switchType": "status-based",
|
|
200
|
+
"switchExpression": "status",
|
|
201
|
+
"hasDefault": true,
|
|
202
|
+
"confidence": 0.9,
|
|
203
|
+
"caseLabels": ["pending", "processing", "shipped", "..."],
|
|
204
|
+
"violationType": "god-switch",
|
|
205
|
+
"principle": "Open/Closed Principle"
|
|
206
|
+
}
|
|
207
|
+
}
|
|
208
|
+
```
|
|
209
|
+
|
|
210
|
+
**Configuration:**
|
|
211
|
+
|
|
212
|
+
```typescript
|
|
213
|
+
interface GodSwitchConfig {
|
|
214
|
+
/**
|
|
215
|
+
* Maximum allowed case clauses before violation
|
|
216
|
+
* Default: 10
|
|
217
|
+
*/
|
|
218
|
+
maxCases?: number;
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
// Usage
|
|
222
|
+
const context = ContextFactory.createAnalysisContext({
|
|
223
|
+
sourceFile,
|
|
224
|
+
project,
|
|
225
|
+
api: createPublicApi(),
|
|
226
|
+
config: {
|
|
227
|
+
solid: {
|
|
228
|
+
godSwitch: {
|
|
229
|
+
maxCases: 15, // Custom threshold
|
|
230
|
+
},
|
|
231
|
+
},
|
|
232
|
+
},
|
|
233
|
+
});
|
|
234
|
+
```
|
|
235
|
+
|
|
236
|
+
---
|
|
237
|
+
|
|
238
|
+
### ImportDirectionViolationRule
|
|
239
|
+
|
|
240
|
+
**Rule ID:** `solid:import-direction-violation`
|
|
241
|
+
**Severity:** Error
|
|
242
|
+
|
|
243
|
+
Detects imports that violate the configured layer direction rules. Requires `layers` configuration in `.angular-modernizer.json`. Silently skips violations when layer detection returns null for either file to avoid noise from unrecognized paths.
|
|
244
|
+
|
|
245
|
+
---
|
|
246
|
+
|
|
247
|
+
### OCPViolationRule
|
|
248
|
+
|
|
249
|
+
**Rule ID:** `solid:ocp-violation`
|
|
250
|
+
**Severity:** Warning
|
|
251
|
+
|
|
252
|
+
Detects classes that require modification to extend behavior, including type-checking patterns (instanceof chains, type switches) and hardcoded branching on type identifiers.
|
|
253
|
+
|
|
254
|
+
---
|
|
255
|
+
|
|
256
|
+
### LSPViolationRule
|
|
257
|
+
|
|
258
|
+
**Rule ID:** `solid:lsp-violation`
|
|
259
|
+
**Severity:** Warning
|
|
260
|
+
|
|
261
|
+
Detects subclasses that break Liskov Substitution by overriding methods in ways that violate the base class contract.
|
|
262
|
+
|
|
263
|
+
---
|
|
264
|
+
|
|
265
|
+
### GodSwitchTransformRule
|
|
266
|
+
|
|
267
|
+
**Rule ID:** `solid:god-switch-transform`
|
|
268
|
+
**Transformation Type:** `god-switch-transform`
|
|
269
|
+
|
|
270
|
+
Transforms God Switches into Factory Pattern implementations.
|
|
271
|
+
|
|
272
|
+
Transformation steps:
|
|
273
|
+
1. Detect switch statements exceeding the threshold
|
|
274
|
+
2. Extract metadata: case logic, parameters, return types, mutations
|
|
275
|
+
3. Generate strategy interface for polymorphic dispatch
|
|
276
|
+
4. Generate one strategy class per case with extracted logic
|
|
277
|
+
5. Generate factory class with strategy map and factory method
|
|
278
|
+
6. Replace switch statement with factory call
|
|
279
|
+
7. Update imports for generated code
|
|
280
|
+
|
|
281
|
+
**Before:**
|
|
282
|
+
|
|
283
|
+
```typescript
|
|
284
|
+
export class PaymentProcessor {
|
|
285
|
+
processPayment(method: string, amount: number): string {
|
|
286
|
+
let result = '';
|
|
287
|
+
switch (method) {
|
|
288
|
+
case 'credit-card':
|
|
289
|
+
result = `Processing credit card payment of ${amount}`;
|
|
290
|
+
break;
|
|
291
|
+
case 'debit-card':
|
|
292
|
+
result = `Processing debit card payment of ${amount}`;
|
|
293
|
+
break;
|
|
294
|
+
case 'paypal':
|
|
295
|
+
result = `Processing PayPal payment of ${amount}`;
|
|
296
|
+
break;
|
|
297
|
+
case 'bank-transfer':
|
|
298
|
+
result = `Processing bank transfer of ${amount}`;
|
|
299
|
+
break;
|
|
300
|
+
case 'crypto':
|
|
301
|
+
result = `Processing crypto payment of ${amount}`;
|
|
302
|
+
break;
|
|
303
|
+
// ... 10+ more cases
|
|
304
|
+
default:
|
|
305
|
+
result = 'Unknown payment method';
|
|
306
|
+
break;
|
|
307
|
+
}
|
|
308
|
+
return result;
|
|
309
|
+
}
|
|
310
|
+
}
|
|
311
|
+
```
|
|
312
|
+
|
|
313
|
+
**After:**
|
|
314
|
+
|
|
315
|
+
```typescript
|
|
316
|
+
interface MethodStrategy {
|
|
317
|
+
execute(amount: number): string;
|
|
318
|
+
}
|
|
319
|
+
|
|
320
|
+
class CreditCardStrategy implements MethodStrategy {
|
|
321
|
+
execute(amount: number): string {
|
|
322
|
+
return `Processing credit card payment of ${amount}`;
|
|
323
|
+
}
|
|
324
|
+
}
|
|
325
|
+
|
|
326
|
+
class DebitCardStrategy implements MethodStrategy {
|
|
327
|
+
execute(amount: number): string {
|
|
328
|
+
return `Processing debit card payment of ${amount}`;
|
|
329
|
+
}
|
|
330
|
+
}
|
|
331
|
+
|
|
332
|
+
// ... more strategy classes
|
|
333
|
+
|
|
334
|
+
class MethodFactory {
|
|
335
|
+
private strategies = new Map<string, MethodStrategy>([
|
|
336
|
+
['credit-card', new CreditCardStrategy()],
|
|
337
|
+
['debit-card', new DebitCardStrategy()],
|
|
338
|
+
['paypal', new PaypalStrategy()],
|
|
339
|
+
// ... more strategies
|
|
340
|
+
]);
|
|
341
|
+
|
|
342
|
+
createStrategy(method: string): MethodStrategy {
|
|
343
|
+
return this.strategies.get(method) ?? new DefaultStrategy();
|
|
344
|
+
}
|
|
345
|
+
}
|
|
346
|
+
|
|
347
|
+
export class PaymentProcessor {
|
|
348
|
+
private factory = new MethodFactory();
|
|
349
|
+
|
|
350
|
+
processPayment(method: string, amount: number): string {
|
|
351
|
+
const strategy = this.factory.createStrategy(method);
|
|
352
|
+
return strategy.execute(amount);
|
|
353
|
+
}
|
|
354
|
+
}
|
|
355
|
+
```
|
|
356
|
+
|
|
357
|
+
**Configuration:**
|
|
358
|
+
|
|
359
|
+
```typescript
|
|
360
|
+
interface GodSwitchTransformConfig {
|
|
361
|
+
/**
|
|
362
|
+
* Minimum case count to trigger transformation
|
|
363
|
+
* Default: 10
|
|
364
|
+
*/
|
|
365
|
+
minCaseCount?: number;
|
|
366
|
+
|
|
367
|
+
/**
|
|
368
|
+
* Generate strategy interface
|
|
369
|
+
* Default: true
|
|
370
|
+
*/
|
|
371
|
+
generateInterfaces?: boolean;
|
|
372
|
+
|
|
373
|
+
/**
|
|
374
|
+
* Generate factory class
|
|
375
|
+
* Default: true
|
|
376
|
+
*/
|
|
377
|
+
generateFactory?: boolean;
|
|
378
|
+
|
|
379
|
+
/**
|
|
380
|
+
* Strategy class naming pattern
|
|
381
|
+
* Placeholders: {CaseValue}, {SwitchExpression}
|
|
382
|
+
* Default: "{CaseValue}Strategy"
|
|
383
|
+
*/
|
|
384
|
+
strategyNamingPattern?: string;
|
|
385
|
+
|
|
386
|
+
/**
|
|
387
|
+
* Factory class naming pattern
|
|
388
|
+
* Default: "{SwitchExpression}Factory"
|
|
389
|
+
*/
|
|
390
|
+
factoryNamingPattern?: string;
|
|
391
|
+
}
|
|
392
|
+
|
|
393
|
+
// Usage via MCP tool
|
|
394
|
+
const result = await transformCode({
|
|
395
|
+
filePath: 'src/app/payment-processor.ts',
|
|
396
|
+
transformationType: 'god-switch-transform',
|
|
397
|
+
config: {
|
|
398
|
+
'@angular-modernizer/plugin-solid': {
|
|
399
|
+
transformationType: 'god-switch-transform',
|
|
400
|
+
godSwitch: {
|
|
401
|
+
minCaseCount: 10,
|
|
402
|
+
generateInterfaces: true,
|
|
403
|
+
generateFactory: true,
|
|
404
|
+
strategyNamingPattern: '{CaseValue}Strategy',
|
|
405
|
+
factoryNamingPattern: '{SwitchExpression}Factory',
|
|
406
|
+
},
|
|
407
|
+
},
|
|
408
|
+
},
|
|
409
|
+
});
|
|
410
|
+
```
|
|
411
|
+
|
|
412
|
+
Transformation guarantees:
|
|
413
|
+
- Idempotent: safe to run multiple times, skips already-transformed switches
|
|
414
|
+
- Atomic: all-or-nothing semantics with automatic rollback on failure
|
|
415
|
+
- Mutation handling: preserves variable mutations across case boundaries
|
|
416
|
+
- Fallthrough support: groups fallthrough cases into a single strategy
|
|
417
|
+
- Type safety: generates TypeScript interfaces and typed factory methods
|
|
418
|
+
|
|
419
|
+
---
|
|
420
|
+
|
|
421
|
+
## Factory Pattern Comparison
|
|
422
|
+
|
|
423
|
+
| Aspect | God Switch | Factory Pattern |
|
|
424
|
+
|-|-|-|
|
|
425
|
+
| Extensibility | Modify switch for new cases | Add new strategy class |
|
|
426
|
+
| Testability | Test entire switch | Test strategies independently |
|
|
427
|
+
| Maintainability | Large, complex switch | Small, focused classes |
|
|
428
|
+
| OCP Compliance | Violates OCP | Follows OCP |
|
|
429
|
+
| Code Reuse | Duplicate logic | Reusable strategies |
|
|
430
|
+
| Type Safety | String-based cases | Interface-based polymorphism |
|
|
431
|
+
|
|
432
|
+
---
|
|
433
|
+
|
|
434
|
+
## Usage Examples
|
|
435
|
+
|
|
436
|
+
### Basic SOLID Analysis
|
|
437
|
+
|
|
438
|
+
```typescript
|
|
439
|
+
import { Kernel, RealFileSystemAdapter } from '@angular-modernizer/core';
|
|
440
|
+
import { SolidPlugin } from '@angular-modernizer/plugin-solid';
|
|
441
|
+
|
|
442
|
+
const kernel = new Kernel({
|
|
443
|
+
tsConfigPath: './tsconfig.json',
|
|
444
|
+
fileSystem: new RealFileSystemAdapter(),
|
|
445
|
+
plugins: [new SolidPlugin()],
|
|
446
|
+
});
|
|
447
|
+
|
|
448
|
+
await kernel.initialize();
|
|
449
|
+
|
|
450
|
+
// Get SOLID analysis rules
|
|
451
|
+
const plugin = kernel.getPlugin('@angular-modernizer/plugin-solid');
|
|
452
|
+
const rules = plugin.getAnalysisRules();
|
|
453
|
+
const dipRule = rules.find(
|
|
454
|
+
(r) => r.id === 'solid:dip-violation-direct-instantiation',
|
|
455
|
+
);
|
|
456
|
+
|
|
457
|
+
// Analyze a file
|
|
458
|
+
const project = kernel.getProject();
|
|
459
|
+
const sourceFile = project.addSourceFileAtPath('src/app/user.component.ts');
|
|
460
|
+
|
|
461
|
+
const context = ContextFactory.createAnalysisContext({
|
|
462
|
+
sourceFile,
|
|
463
|
+
project,
|
|
464
|
+
api: createPublicApi(),
|
|
465
|
+
config: {},
|
|
466
|
+
});
|
|
467
|
+
|
|
468
|
+
const result = await dipRule.analyze(context);
|
|
469
|
+
|
|
470
|
+
console.log('DIP Violations found:', result.violations.length);
|
|
471
|
+
result.violations.forEach((v) => {
|
|
472
|
+
console.log(`- ${v.message} at line ${v.location.startLine}`);
|
|
473
|
+
});
|
|
474
|
+
```
|
|
475
|
+
|
|
476
|
+
### Detection + Transformation (God Switch)
|
|
477
|
+
|
|
478
|
+
```typescript
|
|
479
|
+
// Get both analysis and transform rules
|
|
480
|
+
const analysisRule = plugin
|
|
481
|
+
.getAnalysisRules()
|
|
482
|
+
.find((r) => r.id === 'solid:god-switch');
|
|
483
|
+
const transformRule = plugin
|
|
484
|
+
.getTransformRules()
|
|
485
|
+
.find((r) => r.id === 'solid:god-switch-transform');
|
|
486
|
+
|
|
487
|
+
// 1. Detect violations
|
|
488
|
+
const analysisContext = ContextFactory.createAnalysisContext({
|
|
489
|
+
sourceFile,
|
|
490
|
+
project,
|
|
491
|
+
api: createPublicApi(project),
|
|
492
|
+
config: {},
|
|
493
|
+
});
|
|
494
|
+
|
|
495
|
+
const violations = await analysisRule.analyze(analysisContext);
|
|
496
|
+
|
|
497
|
+
if (violations.length > 0) {
|
|
498
|
+
console.log(`Found ${violations.length} God Switches, transforming...`);
|
|
499
|
+
|
|
500
|
+
// 2. Transform violations
|
|
501
|
+
const transformContext = ContextFactory.createTransformContext({
|
|
502
|
+
sourceFile,
|
|
503
|
+
project,
|
|
504
|
+
api: createPublicApi(project),
|
|
505
|
+
config: {
|
|
506
|
+
'@angular-modernizer/plugin-solid': {
|
|
507
|
+
transformationType: 'god-switch-transform',
|
|
508
|
+
godSwitch: {
|
|
509
|
+
minCaseCount: 10,
|
|
510
|
+
generateInterfaces: true,
|
|
511
|
+
generateFactory: true,
|
|
512
|
+
},
|
|
513
|
+
},
|
|
514
|
+
},
|
|
515
|
+
});
|
|
516
|
+
|
|
517
|
+
const result = await transformRule.transform(transformContext);
|
|
518
|
+
|
|
519
|
+
if (result.modified) {
|
|
520
|
+
await sourceFile.save();
|
|
521
|
+
}
|
|
522
|
+
}
|
|
523
|
+
```
|
|
524
|
+
|
|
525
|
+
### MCP Tool Integration
|
|
526
|
+
|
|
527
|
+
```typescript
|
|
528
|
+
// MCP tool usage (handled by adapter-mcp)
|
|
529
|
+
const violations = await callTool("scan-solid", {
|
|
530
|
+
rootPath: "/path/to/project",
|
|
531
|
+
rules: ["solid:dip-violation-direct-instantiation"],
|
|
532
|
+
includeAutoFixes: true
|
|
533
|
+
});
|
|
534
|
+
```
|
|
535
|
+
|
|
536
|
+
### Batch Analysis
|
|
537
|
+
|
|
538
|
+
```typescript
|
|
539
|
+
import { glob } from 'glob';
|
|
540
|
+
|
|
541
|
+
const files = await glob('src/**/*.{ts,tsx}', {
|
|
542
|
+
ignore: ['**/node_modules/**', '**/dist/**'],
|
|
543
|
+
});
|
|
544
|
+
|
|
545
|
+
const allViolations: Violation[] = [];
|
|
546
|
+
|
|
547
|
+
for (const filePath of files) {
|
|
548
|
+
const sourceFile = project.addSourceFileAtPath(filePath);
|
|
549
|
+
const context = ContextFactory.createAnalysisContext({
|
|
550
|
+
sourceFile,
|
|
551
|
+
project,
|
|
552
|
+
api: createPublicApi(),
|
|
553
|
+
});
|
|
554
|
+
|
|
555
|
+
for (const rule of rules) {
|
|
556
|
+
const result = await rule.analyze(context);
|
|
557
|
+
allViolations.push(...result.violations);
|
|
558
|
+
}
|
|
559
|
+
}
|
|
560
|
+
|
|
561
|
+
// Group by severity
|
|
562
|
+
const bySeverity = allViolations.reduce(
|
|
563
|
+
(acc, v) => {
|
|
564
|
+
acc[v.severity] = (acc[v.severity] || 0) + 1;
|
|
565
|
+
return acc;
|
|
566
|
+
},
|
|
567
|
+
{} as Record<string, number>,
|
|
568
|
+
);
|
|
569
|
+
|
|
570
|
+
console.log('SOLID Analysis Summary:');
|
|
571
|
+
console.log('High:', bySeverity.high || 0);
|
|
572
|
+
console.log('Medium:', bySeverity.medium || 0);
|
|
573
|
+
console.log('Low:', bySeverity.low || 0);
|
|
574
|
+
```
|
|
575
|
+
|
|
576
|
+
---
|
|
577
|
+
|
|
578
|
+
## Configuration Options
|
|
579
|
+
|
|
580
|
+
### DIP Violation Config
|
|
581
|
+
|
|
582
|
+
```typescript
|
|
583
|
+
interface DIPViolationConfig {
|
|
584
|
+
/**
|
|
585
|
+
* Service class suffixes to detect
|
|
586
|
+
* Default: ['Service', 'Repository', 'Store', 'Manager']
|
|
587
|
+
*/
|
|
588
|
+
serviceSuffixes?: string[];
|
|
589
|
+
|
|
590
|
+
/**
|
|
591
|
+
* Exclude patterns for files/directories
|
|
592
|
+
* Default: ['**/node_modules/**', '**/dist/**']
|
|
593
|
+
*/
|
|
594
|
+
excludePatterns?: string[];
|
|
595
|
+
|
|
596
|
+
/**
|
|
597
|
+
* Include auto-fix suggestions
|
|
598
|
+
* Default: true
|
|
599
|
+
*/
|
|
600
|
+
includeAutoFixes?: boolean;
|
|
601
|
+
|
|
602
|
+
/**
|
|
603
|
+
* Custom service detection patterns
|
|
604
|
+
*/
|
|
605
|
+
customPatterns?: RegExp[];
|
|
606
|
+
}
|
|
607
|
+
```
|
|
608
|
+
|
|
609
|
+
### Example Configuration
|
|
610
|
+
|
|
611
|
+
```typescript
|
|
612
|
+
const context = ContextFactory.createAnalysisContext({
|
|
613
|
+
sourceFile,
|
|
614
|
+
project,
|
|
615
|
+
api: createPublicApi(),
|
|
616
|
+
config: {
|
|
617
|
+
serviceSuffixes: ['Service', 'Repository', 'Store', 'Api'],
|
|
618
|
+
excludePatterns: ['**/generated/**', '**/vendor/**'],
|
|
619
|
+
includeAutoFixes: true,
|
|
620
|
+
customPatterns: [/.*Client$/, /.*Provider$/],
|
|
621
|
+
},
|
|
622
|
+
});
|
|
623
|
+
```
|
|
624
|
+
|
|
625
|
+
---
|
|
626
|
+
|
|
627
|
+
## Package Structure
|
|
628
|
+
|
|
629
|
+
```
|
|
630
|
+
packages/plugin-solid/
|
|
631
|
+
src/
|
|
632
|
+
rules/
|
|
633
|
+
dip-violation.rule.ts
|
|
634
|
+
srp-single-responsibility-violation.rule.ts
|
|
635
|
+
god-switch-analysis.rule.ts
|
|
636
|
+
ocp-violation.rule.ts
|
|
637
|
+
lsp-violation.rule.ts
|
|
638
|
+
import-direction-violation.rule.ts
|
|
639
|
+
dip-violation-concrete-dependency.rule.ts
|
|
640
|
+
orchestrators/
|
|
641
|
+
god-switch-transform-orchestrator.ts
|
|
642
|
+
service-dip-violation-transform.orchestrator.ts
|
|
643
|
+
transform-rules/
|
|
644
|
+
god-switch-transform.rule.ts
|
|
645
|
+
solid-plugin.ts
|
|
646
|
+
index.ts
|
|
647
|
+
types.ts
|
|
648
|
+
__tests__/
|
|
649
|
+
rules/
|
|
650
|
+
dip-violation.rule.test.ts
|
|
651
|
+
god-switch-analysis.rule.test.ts
|
|
652
|
+
(and more)
|
|
653
|
+
orchestrators/
|
|
654
|
+
god-switch-transform-orchestrator.test.ts
|
|
655
|
+
god-switch-mutation-preservation.test.ts
|
|
656
|
+
transform-rules/
|
|
657
|
+
god-switch-transform.rule.test.ts
|
|
658
|
+
solid-plugin.test.ts
|
|
659
|
+
package.json
|
|
660
|
+
tsconfig.json
|
|
661
|
+
jest.config.js
|
|
662
|
+
README.md
|
|
663
|
+
```
|
|
664
|
+
|
|
665
|
+
---
|
|
666
|
+
|
|
667
|
+
## Testing
|
|
668
|
+
|
|
669
|
+
```bash
|
|
670
|
+
# Run SOLID plugin tests
|
|
671
|
+
pnpm test --filter @angular-modernizer/plugin-solid
|
|
672
|
+
|
|
673
|
+
# Run with coverage
|
|
674
|
+
pnpm test --filter @angular-modernizer/plugin-solid --coverage
|
|
675
|
+
```
|
|
676
|
+
|
|
677
|
+
### Test Examples
|
|
678
|
+
|
|
679
|
+
```typescript
|
|
680
|
+
describe('DIPViolationRule', () => {
|
|
681
|
+
let rule: DIPViolationRule;
|
|
682
|
+
|
|
683
|
+
beforeEach(() => {
|
|
684
|
+
rule = new DIPViolationRule();
|
|
685
|
+
});
|
|
686
|
+
|
|
687
|
+
it('should detect direct service instantiation', async () => {
|
|
688
|
+
const sourceFile = project.createSourceFile(
|
|
689
|
+
'test.component.ts',
|
|
690
|
+
`
|
|
691
|
+
@Component({})
|
|
692
|
+
export class TestComponent {
|
|
693
|
+
private service = new UserService(); // Violation
|
|
694
|
+
private repo = new UserRepository(); // Violation
|
|
695
|
+
}
|
|
696
|
+
`,
|
|
697
|
+
);
|
|
698
|
+
|
|
699
|
+
const context = ContextFactory.createAnalysisContext({
|
|
700
|
+
sourceFile,
|
|
701
|
+
project,
|
|
702
|
+
api: createPublicApi(),
|
|
703
|
+
});
|
|
704
|
+
|
|
705
|
+
const result = await rule.analyze(context);
|
|
706
|
+
|
|
707
|
+
expect(result.violations).toHaveLength(2);
|
|
708
|
+
expect(result.violations[0].message).toContain('UserService');
|
|
709
|
+
expect(result.violations[1].message).toContain('UserRepository');
|
|
710
|
+
});
|
|
711
|
+
|
|
712
|
+
it('should not flag dependency injection', async () => {
|
|
713
|
+
const sourceFile = project.createSourceFile(
|
|
714
|
+
'test.component.ts',
|
|
715
|
+
`
|
|
716
|
+
@Component({})
|
|
717
|
+
export class TestComponent {
|
|
718
|
+
private service = inject(UserService); // OK
|
|
719
|
+
private repo = inject(UserRepository); // OK
|
|
720
|
+
}
|
|
721
|
+
`,
|
|
722
|
+
);
|
|
723
|
+
|
|
724
|
+
const context = ContextFactory.createAnalysisContext({
|
|
725
|
+
sourceFile,
|
|
726
|
+
project,
|
|
727
|
+
api: createPublicApi(),
|
|
728
|
+
});
|
|
729
|
+
|
|
730
|
+
const result = await rule.analyze(context);
|
|
731
|
+
|
|
732
|
+
expect(result.violations).toHaveLength(0);
|
|
733
|
+
});
|
|
734
|
+
});
|
|
735
|
+
```
|
|
736
|
+
|
|
737
|
+
---
|
|
738
|
+
|
|
739
|
+
## Dependencies
|
|
740
|
+
|
|
741
|
+
- `@angular-modernizer/api` - Public API with analysis tools
|
|
742
|
+
- `@angular-modernizer/core` - Kernel and infrastructure
|
|
743
|
+
- `@angular-modernizer/plugin-system` - Plugin contracts and contexts
|
|
744
|
+
|
|
745
|
+
---
|
|
746
|
+
|
|
747
|
+
## SOLID Principle Reference
|
|
748
|
+
|
|
749
|
+
### Dependency Inversion Principle (DIP)
|
|
750
|
+
|
|
751
|
+
High-level modules should not depend on low-level modules. Both should depend on abstractions.
|
|
752
|
+
|
|
753
|
+
Common violations:
|
|
754
|
+
- Direct instantiation of services (`new MyService()`)
|
|
755
|
+
- Missing interfaces for services
|
|
756
|
+
- Tight coupling between high-level and low-level modules
|
|
757
|
+
|
|
758
|
+
Best practices:
|
|
759
|
+
- Use dependency injection
|
|
760
|
+
- Program to interfaces, not implementations
|
|
761
|
+
- Create abstractions for volatile dependencies
|
|
762
|
+
|
|
763
|
+
### Single Responsibility Principle (SRP)
|
|
764
|
+
|
|
765
|
+
A class should have only one reason to change. One responsibility per class.
|
|
766
|
+
|
|
767
|
+
### Open/Closed Principle (OCP)
|
|
768
|
+
|
|
769
|
+
Open for extension, closed for modification. Use polymorphism instead of conditionals.
|
|
770
|
+
|
|
771
|
+
### Liskov Substitution Principle (LSP)
|
|
772
|
+
|
|
773
|
+
Subtypes must be substitutable for their base types. Inheritance should preserve behavior.
|
|
774
|
+
|
|
775
|
+
### Interface Segregation Principle (ISP)
|
|
776
|
+
|
|
777
|
+
Clients should not be forced to depend on interfaces they don't use. Prefer small, focused interfaces.
|
|
778
|
+
|
|
779
|
+
---
|
|
780
|
+
|
|
781
|
+
## Contributing
|
|
782
|
+
|
|
783
|
+
When adding new SOLID analysis rules:
|
|
784
|
+
|
|
785
|
+
1. Focus on one principle - each rule should address one SOLID principle
|
|
786
|
+
2. Use PublicApi tools - leverage existing analysis infrastructure
|
|
787
|
+
3. Include auto-fixes when possible
|
|
788
|
+
4. Write comprehensive tests covering various violation scenarios
|
|
789
|
+
5. Document with before/after examples
|
|
790
|
+
|
|
791
|
+
### Adding a New SOLID Rule
|
|
792
|
+
|
|
793
|
+
```typescript
|
|
794
|
+
// 1. Implement the rule
|
|
795
|
+
class MySolidRule implements AnalysisRule {
|
|
796
|
+
readonly id = 'solid:my-solid-rule';
|
|
797
|
+
readonly name = 'My SOLID Rule';
|
|
798
|
+
readonly description = 'Detects violations of a specific SOLID principle';
|
|
799
|
+
|
|
800
|
+
async analyze(context: AnalysisContext): Promise<AnalysisResult> {
|
|
801
|
+
const { api, sourceFile } = context;
|
|
802
|
+
const violations: Violation[] = [];
|
|
803
|
+
|
|
804
|
+
// Use PublicApi for analysis
|
|
805
|
+
// Detect violations and create Violation objects
|
|
806
|
+
|
|
807
|
+
return {
|
|
808
|
+
ruleId: this.id,
|
|
809
|
+
violations,
|
|
810
|
+
metadata: {
|
|
811
|
+
totalViolations: violations.length,
|
|
812
|
+
},
|
|
813
|
+
};
|
|
814
|
+
}
|
|
815
|
+
}
|
|
816
|
+
|
|
817
|
+
// 2. Add to plugin
|
|
818
|
+
class SolidPlugin implements Plugin {
|
|
819
|
+
getAnalysisRules(): AnalysisRule[] {
|
|
820
|
+
return [
|
|
821
|
+
new DIPViolationRule(),
|
|
822
|
+
new MySolidRule(), // Add here
|
|
823
|
+
];
|
|
824
|
+
}
|
|
825
|
+
}
|
|
826
|
+
```
|
|
827
|
+
|
|
828
|
+
---
|
|
829
|
+
|
|
830
|
+
## See Also
|
|
831
|
+
|
|
832
|
+
- [README.md](../../README.md) - Project overview
|
|
833
|
+
- [DEVELOPMENT_GUIDE.md](../../DEVELOPMENT_GUIDE.md) - Architecture details
|
|
834
|
+
- [packages/api/README.md](../api/README.md) - Public API tools
|
|
835
|
+
- [packages/plugin-analyzer/README.md](../plugin-analyzer/README.md) - Project analysis rules
|