@angular-modernizer/plugin-solid 1.2.0 → 2.0.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/CHANGELOG.md +270 -0
- package/README.md +103 -99
- package/dist/index.d.ts +5 -3
- package/dist/index.js +4 -2
- package/dist/rules/dip-violation.rule.d.ts +30 -31
- package/dist/rules/dip-violation.rule.js +246 -112
- package/dist/rules/god-switch-analysis.rule.d.ts +44 -33
- package/dist/rules/god-switch-analysis.rule.js +146 -109
- package/dist/rules/isp-violation.rule.d.ts +35 -33
- package/dist/rules/isp-violation.rule.js +83 -202
- package/dist/rules/lsp-violation.rule.d.ts +15 -39
- package/dist/rules/lsp-violation.rule.js +17 -300
- package/dist/rules/ocp-violation.rule.d.ts +52 -36
- package/dist/rules/ocp-violation.rule.js +227 -145
- package/dist/rules/service-dip-violation.analysis.rule.d.ts +32 -56
- package/dist/rules/service-dip-violation.analysis.rule.js +21 -192
- package/dist/rules/srp-violation.rule.d.ts +36 -71
- package/dist/rules/srp-violation.rule.js +78 -384
- package/dist/solid-plugin.d.ts +13 -8
- package/dist/solid-plugin.js +17 -11
- package/package.json +7 -6
package/README.md
CHANGED
|
@@ -10,32 +10,38 @@ The `@angular-modernizer/plugin-solid` package provides analysis rules for detec
|
|
|
10
10
|
|
|
11
11
|
### Single Responsibility Principle (SRP)
|
|
12
12
|
|
|
13
|
-
|
|
13
|
+
Reports classes that are too large: more than 15 instance methods, Angular lifecycle hooks, accessors and function-valued properties not counted. Components and static-only classes are skipped. The rule makes no claim about responsibilities: it reads neither member names nor method bodies.
|
|
14
14
|
|
|
15
15
|
### Open/Closed Principle (OCP)
|
|
16
16
|
|
|
17
|
-
|
|
17
|
+
Reports if-else chains that dispatch on one value in more than 4 conditions, and (`solid:god-switch`) switches with more than 10 clauses that do more than return or assign a value. Both grow with each new case.
|
|
18
18
|
|
|
19
19
|
### Liskov Substitution Principle (LSP)
|
|
20
20
|
|
|
21
|
-
|
|
21
|
+
`solid:lsp-violation` is deprecated and reports nothing: a missing interface member or abstract method is a compile error, and an `instanceof` check alone shows no broken substitution. The id stays registered so configurations load; ConfigLoader warns when it is configured.
|
|
22
22
|
|
|
23
23
|
### Interface Segregation Principle (ISP)
|
|
24
24
|
|
|
25
|
-
|
|
25
|
+
Reports interfaces that declare more than 5 methods (overloads once, function-typed properties included).
|
|
26
26
|
|
|
27
27
|
### Dependency Inversion Principle (DIP)
|
|
28
28
|
|
|
29
|
-
|
|
29
|
+
Reports `@Injectable` classes of the project created with `new` and `Injector.get()` lookups inside class members: both bypass Angular DI. `solid:service-dip-violation` (concrete constructor injection) is deprecated and reports nothing; injections against the layer direction are imports that `architecture:layer-boundary-violation` reports.
|
|
30
30
|
|
|
31
31
|
## Analysis Rules
|
|
32
32
|
|
|
33
|
-
###
|
|
33
|
+
### SingleResponsibilityRule
|
|
34
34
|
|
|
35
35
|
**Rule ID:** `solid:srp-single-responsibility-violation`
|
|
36
36
|
**Severity:** Warning
|
|
37
37
|
|
|
38
|
-
|
|
38
|
+
One finding per class (`violationType: 'too-many-methods'`, at the class) when the class has more than 15 instance methods. Counted: method declarations that are not static (public, protected, private, `#` and abstract alike), an overloaded method once. Not counted: the Angular lifecycle hooks `ngOnInit`, `ngOnDestroy`, `ngOnChanges`, `ngDoCheck`, `ngAfterViewInit`, `ngAfterViewChecked`, `ngAfterContentInit` and `ngAfterContentChecked` (by exact name), get/set accessors and properties, also arrow-function and function-expression properties and signal fields such as `input()`, `output()`, `model()`, `computed()` and `effect()`.
|
|
39
|
+
|
|
40
|
+
Skipped: components (`@Component` and the decorators of `parser.componentDecorators`; `architecture:component-complexity` reports component size) and static-only classes. Directives, pipes, services and plain classes are counted.
|
|
41
|
+
|
|
42
|
+
Message: `Class 'UserService' has 16 instance methods without lifecycle hooks (threshold: 15).` Metadata: `className`, `methodCount`, `threshold`, `violationType`, `principle`.
|
|
43
|
+
|
|
44
|
+
Member names and method bodies are not read: the former checks for responsibility keywords in member names (`mixed-responsibilities`) and in method bodies (`single-method-multi-concern`) are removed. Responsibilities of services are reported by `architecture:service-bag`.
|
|
39
45
|
|
|
40
46
|
---
|
|
41
47
|
|
|
@@ -44,38 +50,45 @@ Detects classes with more than 15 public methods or mixed responsibility categor
|
|
|
44
50
|
**Rule ID:** `solid:dip-violation-direct-instantiation`
|
|
45
51
|
**Severity:** Warning
|
|
46
52
|
|
|
47
|
-
|
|
53
|
+
One warning per finding (`result.severity`). Violation types (`violationType` in the metadata):
|
|
48
54
|
|
|
49
|
-
|
|
50
|
-
- `
|
|
51
|
-
- `new MyRepository()` in component methods
|
|
52
|
-
- Direct instantiation of classes ending with `Service`, `Repository`, `Store`, `Manager`, `Api`, `Client`, `Provider`, `Facade`, `Helper`, `Util` or `Utils`
|
|
53
|
-
- `injector.get()` service locator calls
|
|
55
|
+
- `direct-instantiation`: `new X()` where `X` resolves by symbol to a class declared in the project (not in a `.d.ts` file or `node_modules`) with an `Injectable` decorator from `@angular/core` (named, aliased or namespace import). Library classes (`new HttpClient(handler)`, third-party clients) and undecorated helpers or models are not reported, whatever their name. Metadata: `instantiatedType` (class name without qualifier or type arguments).
|
|
56
|
+
- `service-locator-pattern`: `.get(...)` on a receiver whose type is Angular's `Injector` (type checker), any receiver expression: `this.injector`, a parameter, `inject(Injector)`. A `Map` or other receiver only named like an injector is not reported. Metadata: `receiver`, `token`.
|
|
54
57
|
|
|
55
|
-
|
|
58
|
+
Both are reported only inside class members (methods, constructors, accessors, property initializers). Not reported: a function that is the value of a `useFactory` property, a function passed to `provideAppInitializer`, `provideEnvironmentInitializer` or `providePlatformInitializer`, decorators and functions outside classes, since these build providers.
|
|
59
|
+
|
|
60
|
+
`suggestedFix` proposes `inject(X)` when the project uses Angular 14 or later (api `angularMajorVersion`, installed `@angular/core` first, else the declared range) and the call site is an injection context (an instance field initializer or the constructor body, not a nested callback); otherwise a constructor parameter. Metadata also carries `principle: 'DIP'`, `injectionContext` and `angularMajorVersion`.
|
|
61
|
+
|
|
62
|
+
**Reported:**
|
|
56
63
|
|
|
57
64
|
```typescript
|
|
58
|
-
|
|
65
|
+
@Injectable({ providedIn: 'root' })
|
|
66
|
+
export class UserService {}
|
|
67
|
+
|
|
59
68
|
@Component({...})
|
|
60
69
|
export class UserComponent {
|
|
61
|
-
private userService = new UserService();
|
|
62
|
-
|
|
63
|
-
}
|
|
70
|
+
private userService = new UserService(); // direct-instantiation, fix: inject(UserService)
|
|
71
|
+
|
|
72
|
+
constructor(private injector: Injector) {}
|
|
64
73
|
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
74
|
+
load() {
|
|
75
|
+
return this.injector.get(UserService); // service-locator-pattern, fix: constructor parameter
|
|
76
|
+
}
|
|
68
77
|
}
|
|
69
78
|
```
|
|
70
79
|
|
|
71
|
-
**
|
|
80
|
+
**Not reported:**
|
|
72
81
|
|
|
73
82
|
```typescript
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
83
|
+
export class ApiFactory {
|
|
84
|
+
create(handler: HttpHandler) {
|
|
85
|
+
return new HttpClient(handler); // library class
|
|
86
|
+
}
|
|
78
87
|
}
|
|
88
|
+
|
|
89
|
+
export const PROVIDERS = [
|
|
90
|
+
{ provide: UserStore, useFactory: (injector: Injector) => injector.get(UserService), deps: [Injector] },
|
|
91
|
+
];
|
|
79
92
|
```
|
|
80
93
|
|
|
81
94
|
**Analysis Result:**
|
|
@@ -83,23 +96,19 @@ export class UserComponent {
|
|
|
83
96
|
```json
|
|
84
97
|
{
|
|
85
98
|
"ruleId": "solid:dip-violation-direct-instantiation",
|
|
86
|
-
"
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
"description": "Convert to dependency injection using inject()"
|
|
100
|
-
}
|
|
101
|
-
}
|
|
102
|
-
]
|
|
99
|
+
"severity": "warning",
|
|
100
|
+
"message": "new UserService() creates an @Injectable class outside Angular DI (Dependency Inversion Principle): its own dependencies are not injected, providers and test doubles for UserService are bypassed.",
|
|
101
|
+
"filePath": "/src/app/user.component.ts",
|
|
102
|
+
"line": 6,
|
|
103
|
+
"column": 2,
|
|
104
|
+
"suggestedFix": "Replace 'new UserService()' with 'inject(UserService)'.",
|
|
105
|
+
"metadata": {
|
|
106
|
+
"instantiatedType": "UserService",
|
|
107
|
+
"violationType": "direct-instantiation",
|
|
108
|
+
"principle": "DIP",
|
|
109
|
+
"injectionContext": true,
|
|
110
|
+
"angularMajorVersion": 21
|
|
111
|
+
}
|
|
103
112
|
}
|
|
104
113
|
```
|
|
105
114
|
|
|
@@ -108,9 +117,9 @@ export class UserComponent {
|
|
|
108
117
|
### ServiceDipViolationRule
|
|
109
118
|
|
|
110
119
|
**Rule ID:** `solid:service-dip-violation`
|
|
111
|
-
**
|
|
120
|
+
**Status:** Deprecated, reports nothing (removed in 3.0)
|
|
112
121
|
|
|
113
|
-
|
|
122
|
+
Injecting a concrete `@Injectable` class is Angular's normal DI and no defect. The only harmful shape, an injection against the layer direction, is always an import upwards, which `architecture:layer-boundary-violation` reports for the configured `layers` / `layersSource` (and suppresses with its `suppressionComments` markers). The id stays registered so configurations load; ConfigLoader warns when `rules['solid:service-dip-violation']` is set. The transform `ServiceDipViolationTransformRule` detects its targets itself and is not affected.
|
|
114
123
|
|
|
115
124
|
---
|
|
116
125
|
|
|
@@ -119,35 +128,24 @@ Detects constructor parameters of `@Injectable` classes that inject concrete `@I
|
|
|
119
128
|
**Rule ID:** `solid:god-switch`
|
|
120
129
|
**Severity:** Warning
|
|
121
130
|
|
|
122
|
-
|
|
131
|
+
Reports a switch statement with more than 10 non-lookup clauses (threshold `maxCases`, default 10), one warning per switch at the switch. Switches are checked everywhere in the file.
|
|
123
132
|
|
|
124
|
-
|
|
125
|
-
-
|
|
126
|
-
-
|
|
127
|
-
-
|
|
133
|
+
How clauses are counted:
|
|
134
|
+
- A clause is a label with a body of its own: labels that fall through without statements form one clause with the next label that has statements. `default` counts like a case clause when it has a body.
|
|
135
|
+
- A clause is a lookup when its body, ignoring `break` and unwrapping blocks, is a single `return` or a single assignment expression statement and contains no call or `new` expression (`return 'x'`, `return row.active ? row.on : row.off`, `this.label = 'x'`), or whose value is one call with only constant arguments: literals, enum members and `const` variables (`return translate.instant('HEADER.NAME')`). `return this.compute()` and `return handle(input)` are no lookups. Lookups are not counted, so a value mapping is never reported. `return this.compute()` is no lookup.
|
|
136
|
+
- A clause whose body is only `break` does nothing and is not counted.
|
|
128
137
|
|
|
129
138
|
**Before:**
|
|
130
139
|
|
|
131
140
|
```typescript
|
|
132
|
-
//
|
|
141
|
+
// 11 clauses that each call a handler
|
|
133
142
|
export class OrderProcessor {
|
|
134
143
|
processOrder(status: string): void {
|
|
135
144
|
switch (status) {
|
|
136
|
-
case 'pending': break;
|
|
137
|
-
case 'processing': break;
|
|
138
|
-
case 'shipped': break;
|
|
139
|
-
|
|
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;
|
|
145
|
+
case 'pending': this.reserveStock(); break;
|
|
146
|
+
case 'processing': this.startPicking(); break;
|
|
147
|
+
case 'shipped': this.notifyCarrier(); break;
|
|
148
|
+
// ... 8 more clauses that call a handler
|
|
151
149
|
default: break;
|
|
152
150
|
}
|
|
153
151
|
}
|
|
@@ -189,17 +187,19 @@ class OrderStatusFactory {
|
|
|
189
187
|
```json
|
|
190
188
|
{
|
|
191
189
|
"ruleId": "solid:god-switch",
|
|
192
|
-
"
|
|
190
|
+
"severity": "warning",
|
|
191
|
+
"message": "Switch on 'status' has 11 clauses that do more than return or assign a value (threshold: 10).",
|
|
193
192
|
"filePath": "src/app/order-processor.ts",
|
|
194
193
|
"line": 3,
|
|
195
194
|
"column": 4,
|
|
196
|
-
"suggestedFix": "
|
|
195
|
+
"suggestedFix": "Move the behavior of each clause into a handler map or into polymorphic classes so a new case does not edit this switch.",
|
|
197
196
|
"metadata": {
|
|
198
|
-
"
|
|
199
|
-
"
|
|
197
|
+
"clauseCount": 11,
|
|
198
|
+
"lookupClauseCount": 0,
|
|
199
|
+
"nonLookupClauseCount": 11,
|
|
200
|
+
"maxCases": 10,
|
|
200
201
|
"switchExpression": "status",
|
|
201
202
|
"hasDefault": true,
|
|
202
|
-
"confidence": 0.9,
|
|
203
203
|
"caseLabels": ["pending", "processing", "shipped", "..."],
|
|
204
204
|
"violationType": "god-switch",
|
|
205
205
|
"principle": "Open/Closed Principle"
|
|
@@ -212,7 +212,7 @@ class OrderStatusFactory {
|
|
|
212
212
|
```typescript
|
|
213
213
|
interface GodSwitchConfig {
|
|
214
214
|
/**
|
|
215
|
-
* Maximum allowed
|
|
215
|
+
* Maximum allowed non-lookup clauses before violation
|
|
216
216
|
* Default: 10
|
|
217
217
|
*/
|
|
218
218
|
maxCases?: number;
|
|
@@ -224,10 +224,9 @@ const context = ContextFactory.createAnalysisContext({
|
|
|
224
224
|
project,
|
|
225
225
|
api: createPublicApi(),
|
|
226
226
|
config: {
|
|
227
|
-
solid:
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
},
|
|
227
|
+
// rules['solid:god-switch'] of .angular-modernizer.json
|
|
228
|
+
'solid:god-switch': {
|
|
229
|
+
maxCases: 15, // Custom threshold
|
|
231
230
|
},
|
|
232
231
|
},
|
|
233
232
|
});
|
|
@@ -240,9 +239,9 @@ const context = ContextFactory.createAnalysisContext({
|
|
|
240
239
|
**Rule ID:** `solid:isp-violation`
|
|
241
240
|
**Severity:** Warning
|
|
242
241
|
|
|
243
|
-
|
|
242
|
+
Reports an interface that declares more than 5 methods, one warning at the interface. Methods are the interface's own method signatures counted by name (overloads once) plus properties whose type is a plain function (`onSave: () => void`, also optional or through a type alias). Callable types with properties of their own (signals such as `title: Signal<string>`), data properties, call and index signatures and members inherited through `extends` are not counted. Interfaces in `declare global` or `declare module` blocks and interfaces that merge with a declaration in a `.d.ts` file (a script-level `interface Window`) are skipped. Classes are not examined: how many interfaces a class implements is not reported.
|
|
244
243
|
|
|
245
|
-
`solid:import-direction-violation` and `solid:
|
|
244
|
+
`solid:import-direction-violation`, `solid:circular-dependency` and `solid:god-object-violation` use the `solid:` prefix but belong to `@angular-modernizer/plugin-architecture`.
|
|
246
245
|
|
|
247
246
|
---
|
|
248
247
|
|
|
@@ -251,16 +250,18 @@ Detects interfaces with more than 5 methods, interfaces whose members mix concer
|
|
|
251
250
|
**Rule ID:** `solid:ocp-violation`
|
|
252
251
|
**Severity:** Warning
|
|
253
252
|
|
|
254
|
-
|
|
253
|
+
Reports an if-else chain with more than 4 conditions (the `if` plus its `else if` links; a final plain `else` is not counted) when every condition compares the same discriminant with `===` or `==`, also joined by `||` (`kind === 'a' || kind === 'b'`). The discriminant is a variable, parameter, property access chain such as `this.state.kind` or element access with a reference or literal key such as `values[key]`; two references match when they resolve to the same symbols and keys, so `a.kind` and `b.kind` are different discriminants. One warning per chain at its first `if`; the message names the enclosing function or method, the discriminant and the number of conditions and suggests a lookup map or polymorphism.
|
|
254
|
+
|
|
255
|
+
Chains are checked in the whole file: methods, constructors, nested classes (each chain once) and functions outside classes. Switch statements are reported by `solid:god-switch`; parameter counts are not reported (no Open/Closed claim; ESLint `max-params` covers them).
|
|
255
256
|
|
|
256
257
|
---
|
|
257
258
|
|
|
258
259
|
### LSPViolationRule
|
|
259
260
|
|
|
260
261
|
**Rule ID:** `solid:lsp-violation`
|
|
261
|
-
**
|
|
262
|
+
**Status:** Deprecated, reports nothing (removed in 3.0)
|
|
262
263
|
|
|
263
|
-
|
|
264
|
+
A class that misses a required member of an implemented interface or an abstract method of its base does not compile (TS2420, TS2515), so on code that builds these checks could only report members they did not see (inherited, optional, constructor parameter properties, arrow properties). An `instanceof` check alone (`error instanceof HttpErrorResponse`) shows no subtype that breaks its base's contract. The rule stays registered so configurations naming it load; ConfigLoader warns that `rules['solid:lsp-violation']` has no effect.
|
|
264
265
|
|
|
265
266
|
---
|
|
266
267
|
|
|
@@ -425,7 +426,7 @@ Transformation guarantees:
|
|
|
425
426
|
**Rule ID:** `solid:service-dip-violation-transform`
|
|
426
427
|
**Transformation Type:** `service-dip-violation-transform`
|
|
427
428
|
|
|
428
|
-
|
|
429
|
+
Reads no findings (the analysis rule `solid:service-dip-violation` is deprecated and reports nothing): for each constructor parameter of an `@Injectable` class that injects a concrete `@Injectable` class, it adds an `I{ClassName}` interface (public method signatures) and a `{CLASS_NAME}_TOKEN` `InjectionToken` to the injected service file, changes the parameter type to the interface, adds `@Inject(TOKEN)` and the needed imports. Parameters that already have `@Inject` are skipped; an existing interface is not created again.
|
|
429
430
|
|
|
430
431
|
---
|
|
431
432
|
|
|
@@ -476,11 +477,11 @@ const context = ContextFactory.createAnalysisContext({
|
|
|
476
477
|
config: {},
|
|
477
478
|
});
|
|
478
479
|
|
|
479
|
-
const
|
|
480
|
+
const results = await dipRule.analyze(context);
|
|
480
481
|
|
|
481
|
-
console.log('DIP Violations found:',
|
|
482
|
-
|
|
483
|
-
console.log(`- ${v.message} at line ${v.
|
|
482
|
+
console.log('DIP Violations found:', results.length);
|
|
483
|
+
results.forEach((v) => {
|
|
484
|
+
console.log(`- ${v.message} at line ${v.line}`);
|
|
484
485
|
});
|
|
485
486
|
```
|
|
486
487
|
|
|
@@ -592,9 +593,8 @@ Most rules use fixed thresholds. Configurable are:
|
|
|
592
593
|
|
|
593
594
|
| Rule | Option | Default | Source |
|
|
594
595
|
|-|-|-|-|
|
|
595
|
-
| `solid:god-switch` | `
|
|
596
|
+
| `solid:god-switch` | `maxCases` (non-lookup clauses) | `10` | `rules['solid:god-switch']` of `.angular-modernizer.json` (`context.config['solid:god-switch']`) |
|
|
596
597
|
| `solid:god-switch-transform` | `godSwitch.minCaseCount`, `generateInterfaces`, `generateFactory`, `strategyNamingPattern`, `factoryNamingPattern` | `10`, `true`, `true`, `'{CaseValue}Strategy'`, `'{SwitchExpression}Factory'` | `context.config` |
|
|
597
|
-
| `solid:service-dip-violation` | `crossLayerOnly` | `false` | `ServiceDipViolationRule` constructor |
|
|
598
598
|
|
|
599
599
|
### Example Configuration
|
|
600
600
|
|
|
@@ -604,7 +604,8 @@ const context = ContextFactory.createAnalysisContext({
|
|
|
604
604
|
project,
|
|
605
605
|
api: createPublicApi(project),
|
|
606
606
|
config: {
|
|
607
|
-
solid:
|
|
607
|
+
// rules['solid:god-switch'] of .angular-modernizer.json
|
|
608
|
+
'solid:god-switch': { maxCases: 15 },
|
|
608
609
|
},
|
|
609
610
|
});
|
|
610
611
|
```
|
|
@@ -675,6 +676,10 @@ describe('DIPViolationRule', () => {
|
|
|
675
676
|
const sourceFile = project.createSourceFile(
|
|
676
677
|
'test.component.ts',
|
|
677
678
|
`
|
|
679
|
+
import { Component, Injectable } from '@angular/core';
|
|
680
|
+
@Injectable() export class UserService {}
|
|
681
|
+
@Injectable() export class UserRepository {}
|
|
682
|
+
|
|
678
683
|
@Component({})
|
|
679
684
|
export class TestComponent {
|
|
680
685
|
private service = new UserService(); // Violation
|
|
@@ -689,11 +694,11 @@ describe('DIPViolationRule', () => {
|
|
|
689
694
|
api: createPublicApi(),
|
|
690
695
|
});
|
|
691
696
|
|
|
692
|
-
const
|
|
697
|
+
const results = await rule.analyze(context);
|
|
693
698
|
|
|
694
|
-
expect(
|
|
695
|
-
expect(
|
|
696
|
-
expect(
|
|
699
|
+
expect(results).toHaveLength(2);
|
|
700
|
+
expect(results[0].message).toContain('UserService');
|
|
701
|
+
expect(results[1].message).toContain('UserRepository');
|
|
697
702
|
});
|
|
698
703
|
|
|
699
704
|
it('should not flag dependency injection', async () => {
|
|
@@ -714,9 +719,9 @@ describe('DIPViolationRule', () => {
|
|
|
714
719
|
api: createPublicApi(),
|
|
715
720
|
});
|
|
716
721
|
|
|
717
|
-
const
|
|
722
|
+
const results = await rule.analyze(context);
|
|
718
723
|
|
|
719
|
-
expect(
|
|
724
|
+
expect(results).toHaveLength(0);
|
|
720
725
|
});
|
|
721
726
|
});
|
|
722
727
|
```
|
|
@@ -737,10 +742,9 @@ describe('DIPViolationRule', () => {
|
|
|
737
742
|
|
|
738
743
|
High-level modules should not depend on low-level modules. Both should depend on abstractions.
|
|
739
744
|
|
|
740
|
-
|
|
741
|
-
- Direct instantiation of
|
|
742
|
-
-
|
|
743
|
-
- Tight coupling between high-level and low-level modules
|
|
745
|
+
Reported by `solid:dip-violation-direct-instantiation`:
|
|
746
|
+
- Direct instantiation of project `@Injectable` classes (`new MyService()`)
|
|
747
|
+
- `Injector.get()` lookups inside class members
|
|
744
748
|
|
|
745
749
|
Best practices:
|
|
746
750
|
- Use dependency injection
|
package/dist/index.d.ts
CHANGED
|
@@ -2,10 +2,12 @@
|
|
|
2
2
|
* SOLID principles plugin for the Angular Modernizer.
|
|
3
3
|
*
|
|
4
4
|
* {@link SolidPlugin} registers seven analysis rules and two transform rules:
|
|
5
|
-
* - {@link DIPViolationRule}
|
|
5
|
+
* - {@link DIPViolationRule}: Dependency Inversion
|
|
6
|
+
* - {@link ServiceDipViolationRule}: concrete service injection (deprecated,
|
|
7
|
+
* reports nothing)
|
|
6
8
|
* - {@link SingleResponsibilityRule}: Single Responsibility
|
|
7
9
|
* - {@link OCPViolationRule}, {@link GodSwitchAnalysisRule}: Open/Closed
|
|
8
|
-
* - {@link LSPViolationRule}: Liskov Substitution
|
|
10
|
+
* - {@link LSPViolationRule}: Liskov Substitution (deprecated, reports nothing)
|
|
9
11
|
* - {@link ISPViolationRule}: Interface Segregation
|
|
10
12
|
* - {@link GodSwitchTransformRule}: replaces a large switch with a factory and
|
|
11
13
|
* strategy classes ({@link GodSwitchTransformOrchestrator})
|
|
@@ -17,7 +19,7 @@
|
|
|
17
19
|
*/
|
|
18
20
|
export { SolidPlugin } from './solid-plugin.js';
|
|
19
21
|
export { DIPViolationRule } from './rules/dip-violation.rule.js';
|
|
20
|
-
export { SingleResponsibilityRule } from './rules/srp-violation.rule.js';
|
|
22
|
+
export { SingleResponsibilityRule, type SingleResponsibilityRuleOptions, } from './rules/srp-violation.rule.js';
|
|
21
23
|
export { LSPViolationRule } from './rules/lsp-violation.rule.js';
|
|
22
24
|
export { OCPViolationRule } from './rules/ocp-violation.rule.js';
|
|
23
25
|
export { ISPViolationRule } from './rules/isp-violation.rule.js';
|
package/dist/index.js
CHANGED
|
@@ -3,10 +3,12 @@
|
|
|
3
3
|
* SOLID principles plugin for the Angular Modernizer.
|
|
4
4
|
*
|
|
5
5
|
* {@link SolidPlugin} registers seven analysis rules and two transform rules:
|
|
6
|
-
* - {@link DIPViolationRule}
|
|
6
|
+
* - {@link DIPViolationRule}: Dependency Inversion
|
|
7
|
+
* - {@link ServiceDipViolationRule}: concrete service injection (deprecated,
|
|
8
|
+
* reports nothing)
|
|
7
9
|
* - {@link SingleResponsibilityRule}: Single Responsibility
|
|
8
10
|
* - {@link OCPViolationRule}, {@link GodSwitchAnalysisRule}: Open/Closed
|
|
9
|
-
* - {@link LSPViolationRule}: Liskov Substitution
|
|
11
|
+
* - {@link LSPViolationRule}: Liskov Substitution (deprecated, reports nothing)
|
|
10
12
|
* - {@link ISPViolationRule}: Interface Segregation
|
|
11
13
|
* - {@link GodSwitchTransformRule}: replaces a large switch with a factory and
|
|
12
14
|
* strategy classes ({@link GodSwitchTransformOrchestrator})
|
|
@@ -1,51 +1,50 @@
|
|
|
1
1
|
import type { AnalysisRule, AnalysisContext, AnalysisResult } from '@angular-modernizer/plugin-system';
|
|
2
2
|
/**
|
|
3
|
-
* DIP Violation Rule (`solid:dip-violation-direct-instantiation`) -
|
|
4
|
-
*
|
|
3
|
+
* DIP Violation Rule (`solid:dip-violation-direct-instantiation`) - reports
|
|
4
|
+
* dependencies a class creates or looks up itself instead of declaring them
|
|
5
|
+
* for Angular DI. Severity warning per finding.
|
|
5
6
|
*
|
|
6
|
-
*
|
|
7
|
-
* - `new X()`
|
|
8
|
-
* (
|
|
9
|
-
*
|
|
10
|
-
*
|
|
11
|
-
* -
|
|
12
|
-
*
|
|
7
|
+
* Violation types (`violationType` in the metadata):
|
|
8
|
+
* - `direct-instantiation`: `new X()` where `X` resolves by symbol to a class
|
|
9
|
+
* declared in the project (not in a `.d.ts` file) that has an `Injectable`
|
|
10
|
+
* decorator from `@angular/core`. Library classes (`new HttpClient(handler)`)
|
|
11
|
+
* and undecorated helpers or models are not reported, whatever their name.
|
|
12
|
+
* - `service-locator-pattern`: `.get(...)` on a receiver whose type is
|
|
13
|
+
* Angular's `Injector` (type checker), any receiver expression
|
|
14
|
+
* (`this.injector`, a parameter, `inject(Injector)`).
|
|
13
15
|
*
|
|
14
|
-
*
|
|
15
|
-
*
|
|
16
|
+
* Both are reported only inside class members (methods, constructors,
|
|
17
|
+
* accessors, property initializers), not inside a `useFactory` function, a
|
|
18
|
+
* function passed to `provideAppInitializer`, `provideEnvironmentInitializer`
|
|
19
|
+
* or `providePlatformInitializer`, a decorator or any function outside a class:
|
|
20
|
+
* these build providers and are DI configuration.
|
|
21
|
+
*
|
|
22
|
+
* `suggestedFix` proposes `inject(X)` when the project uses Angular 14 or later
|
|
23
|
+
* (api `angularMajorVersion`) and the call site is an injection context (an
|
|
24
|
+
* instance field initializer or the constructor body, not a nested function);
|
|
25
|
+
* otherwise a constructor parameter. Metadata: `violationType`, `principle`,
|
|
26
|
+
* `instantiatedType` or `receiver` and `token`, `injectionContext`,
|
|
27
|
+
* `angularMajorVersion`.
|
|
16
28
|
*
|
|
17
29
|
* @example
|
|
18
30
|
* ```typescript
|
|
19
|
-
*
|
|
20
|
-
* class
|
|
21
|
-
*
|
|
31
|
+
* @Injectable({ providedIn: 'root' })
|
|
32
|
+
* export class UserService {}
|
|
33
|
+
*
|
|
34
|
+
* export class OrderComponent {
|
|
35
|
+
* private users = new UserService(); // reported: bypasses Angular DI
|
|
22
36
|
* }
|
|
23
37
|
* ```
|
|
24
38
|
*/
|
|
25
39
|
export declare class DIPViolationRule implements AnalysisRule {
|
|
26
40
|
readonly id = "solid:dip-violation-direct-instantiation";
|
|
27
41
|
readonly name = "Dependency Inversion Principle Violation";
|
|
28
|
-
readonly description = "Detects
|
|
42
|
+
readonly description = "Detects @Injectable classes created with new and Injector.get() lookups inside class members";
|
|
29
43
|
readonly severity = "warning";
|
|
30
44
|
readonly category = "solid-violation";
|
|
31
45
|
readonly tags: string[];
|
|
32
|
-
/**
|
|
33
|
-
* Service class suffixes to detect.
|
|
34
|
-
* Aligned with ServicePatternRecognizer patterns for consistency.
|
|
35
|
-
*/
|
|
36
|
-
private readonly defaultServiceSuffixes;
|
|
37
46
|
analyze(context: AnalysisContext): Promise<AnalysisResult[]>;
|
|
38
|
-
/**
|
|
39
|
-
* Check if a new expression violates DIP.
|
|
40
|
-
*/
|
|
41
47
|
private checkNewExpression;
|
|
42
|
-
|
|
43
|
-
* Detect service locator pattern: `injector.get(SomeService)` bypasses Angular DI.
|
|
44
|
-
*/
|
|
45
|
-
private analyzeServiceLocator;
|
|
46
|
-
/**
|
|
47
|
-
* Check if a class name represents a service that should be injected.
|
|
48
|
-
*/
|
|
49
|
-
private isServiceClass;
|
|
48
|
+
private checkInjectorGet;
|
|
50
49
|
}
|
|
51
50
|
//# sourceMappingURL=dip-violation.rule.d.ts.map
|