@angular-modernizer/plugin-solid 1.1.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.
@@ -3,31 +3,40 @@ Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.ISPViolationRule = void 0;
4
4
  const ts_morph_1 = require("ts-morph");
5
5
  /**
6
- * ISP Violation Rule (`solid:isp-violation`) - detects Interface Segregation
7
- * Principle violations.
6
+ * ISP Violation Rule (`solid:isp-violation`) - reports interfaces that declare
7
+ * more methods than one client is likely to need.
8
8
  *
9
- * Detection patterns (`violationType` in the metadata):
10
- * - `too-many-methods`: interfaces with more than 5 methods
11
- * - `mixed-concerns`: interfaces whose members mix concerns (UI, data,
12
- * business logic) by name keywords
13
- * - `too-many-interfaces`: classes implementing more than 3 interfaces
14
- * - `unused-interface-methods`: classes that implement an interface but
15
- * declare no methods
9
+ * One finding per interface (`violationType: 'too-many-methods'`, severity
10
+ * warning, at the interface) when it declares more than 5 methods. Methods
11
+ * are the interface's own method signatures counted by name (overloads once)
12
+ * plus properties whose type is a plain function (`onSave: () => void`, also
13
+ * optional and through a type alias). Callable types with properties of their
14
+ * own (signals such as `title: Signal<string>`), data properties, call and
15
+ * index signatures and members inherited through `extends` are not counted.
16
+ *
17
+ * Skipped: interfaces inside `declare global` or `declare module` blocks and
18
+ * interfaces that merge with a declaration in a `.d.ts` file (a top-level
19
+ * `interface Window` in a script file): they augment a type the project does
20
+ * not own. Classes are not examined; how many interfaces a class implements
21
+ * says nothing about the size of any of them.
16
22
  *
17
23
  * @example
18
24
  * ```typescript
19
- * // Violation: interface forces implementations to define unrelated methods
20
- * interface IWorker {
25
+ * // Reported: 6 methods
26
+ * interface Worker {
21
27
  * work(): void;
22
- * eat(): void; // Irrelevant for robots
23
- * sleep(): void; // Irrelevant for robots
28
+ * eat(): void;
29
+ * sleep(): void;
30
+ * commute(): void;
31
+ * report(): void;
32
+ * train(): void;
24
33
  * }
25
34
  * ```
26
35
  */
27
36
  class ISPViolationRule {
28
37
  id = 'solid:isp-violation';
29
38
  name = 'Interface Segregation Principle Violation';
30
- description = 'Detects interfaces that are too large or have mixed responsibilities';
39
+ description = 'Detects interfaces that declare more than 5 methods (overloads once, function-typed properties included)';
31
40
  severity = 'warning';
32
41
  category = 'solid-violation';
33
42
  tags = [
@@ -37,208 +46,80 @@ class ISPViolationRule {
37
46
  'segregation',
38
47
  'architecture',
39
48
  ];
40
- /**
41
- * Maximum number of methods allowed in an interface.
42
- */
49
+ /** Methods an interface may declare before it is reported. */
43
50
  maxMethodsInInterface = 5;
44
- /**
45
- * Maximum number of interfaces a class can implement.
46
- */
47
- maxInterfacesPerClass = 3;
48
- /**
49
- * Keywords that indicate different concerns.
50
- */
51
- concernKeywords = {
52
- ui: [
53
- 'render',
54
- 'display',
55
- 'show',
56
- 'hide',
57
- 'click',
58
- 'event',
59
- 'component',
60
- 'view',
61
- ],
62
- data: [
63
- 'save',
64
- 'load',
65
- 'fetch',
66
- 'query',
67
- 'store',
68
- 'persist',
69
- 'cache',
70
- 'repository',
71
- ],
72
- business: [
73
- 'calculate',
74
- 'validate',
75
- 'process',
76
- 'transform',
77
- 'convert',
78
- 'rule',
79
- 'logic',
80
- ],
81
- lifecycle: ['init', 'destroy', 'create', 'setup', 'cleanup', 'initialize'],
82
- };
83
51
  async analyze(context) {
84
- const violations = [];
85
52
  const sourceFile = context.sourceFile;
86
- // Find all interfaces in the file
87
- const interfaces = sourceFile.getDescendantsOfKind(ts_morph_1.SyntaxKind.InterfaceDeclaration);
88
- for (const interfaceDecl of interfaces) {
89
- const interfaceViolations = this.analyzeInterface(interfaceDecl, sourceFile.getFilePath());
90
- violations.push(...interfaceViolations);
91
- }
92
- // Find classes that implement interfaces they don't fully use
93
- const classes = sourceFile.getDescendantsOfKind(ts_morph_1.SyntaxKind.ClassDeclaration);
94
- for (const classDecl of classes) {
95
- const classViolations = this.analyzeClassInterfaceUsage(classDecl, sourceFile.getFilePath());
96
- violations.push(...classViolations);
53
+ const filePath = sourceFile.getFilePath();
54
+ const results = sourceFile
55
+ .getDescendantsOfKind(ts_morph_1.SyntaxKind.InterfaceDeclaration)
56
+ .filter((interfaceDecl) => !this.isAugmentation(interfaceDecl))
57
+ .flatMap((interfaceDecl) => this.checkInterface(interfaceDecl, filePath));
58
+ return Promise.resolve(results);
59
+ }
60
+ /** One finding when the interface declares more than the allowed methods. */
61
+ checkInterface(interfaceDecl, filePath) {
62
+ const methodNames = this.methodNames(interfaceDecl);
63
+ const methodCount = methodNames.length;
64
+ if (methodCount <= this.maxMethodsInInterface) {
65
+ return [];
97
66
  }
98
- return Promise.resolve(violations);
67
+ const interfaceName = interfaceDecl.getName();
68
+ return [
69
+ {
70
+ ruleId: this.id,
71
+ severity: 'warning',
72
+ message: `Interface '${interfaceName}' declares ${methodCount} methods, more than 5 (overloads counted once, function-typed properties included). Every implementation must provide all of them and every client depends on all of them.`,
73
+ filePath,
74
+ line: interfaceDecl.getStartLineNumber(),
75
+ column: interfaceDecl.getStart() - interfaceDecl.getStartLinePos(),
76
+ suggestedFix: `Split '${interfaceName}' by the clients that use each group of methods`,
77
+ metadata: {
78
+ interfaceName,
79
+ methodCount,
80
+ methodNames,
81
+ maxAllowed: this.maxMethodsInInterface,
82
+ violationType: 'too-many-methods',
83
+ },
84
+ },
85
+ ];
99
86
  }
100
- /**
101
- * Analyze an interface for ISP violations.
102
- */
103
- analyzeInterface(interfaceDecl, filePath) {
104
- const violations = [];
105
- try {
106
- const interfaceName = interfaceDecl.getName();
107
- const methods = interfaceDecl.getMethods();
108
- const properties = interfaceDecl.getProperties();
109
- // Check if interface has too many methods
110
- if (methods.length > this.maxMethodsInInterface) {
111
- const startLine = interfaceDecl.getStartLineNumber();
112
- const startColumn = interfaceDecl.getStart() - interfaceDecl.getStartLinePos();
113
- violations.push({
114
- ruleId: this.id,
115
- message: `Interface '${interfaceName}' has ${methods.length} methods, exceeding the recommended maximum of ${this.maxMethodsInInterface}. Consider splitting into smaller, focused interfaces.`,
116
- filePath,
117
- line: startLine,
118
- column: startColumn,
119
- suggestedFix: `Split '${interfaceName}' into smaller interfaces based on single responsibilities`,
120
- metadata: {
121
- interfaceName,
122
- methodCount: methods.length,
123
- maxAllowed: this.maxMethodsInInterface,
124
- violationType: 'too-many-methods',
125
- },
126
- });
127
- }
128
- // Check if interface mixes different concerns
129
- const concernAnalysis = this.analyzeInterfaceConcerns(methods, properties);
130
- if (concernAnalysis.mixedConcerns) {
131
- const startLine = interfaceDecl.getStartLineNumber();
132
- const startColumn = interfaceDecl.getStart() - interfaceDecl.getStartLinePos();
133
- violations.push({
134
- ruleId: this.id,
135
- message: `Interface '${interfaceName}' mixes multiple concerns: ${concernAnalysis.concerns.join(', ')}. Consider segregating into focused interfaces.`,
136
- filePath,
137
- line: startLine,
138
- column: startColumn,
139
- suggestedFix: `Create separate interfaces for each concern: ${concernAnalysis.concerns.map((c) => `${interfaceName}${c.charAt(0).toUpperCase() + c.slice(1)}`).join(', ')}`,
140
- metadata: {
141
- interfaceName,
142
- concerns: concernAnalysis.concerns,
143
- violationType: 'mixed-concerns',
144
- },
145
- });
146
- }
87
+ /** Distinct names of method signatures and callable property signatures. */
88
+ methodNames(interfaceDecl) {
89
+ const names = new Set();
90
+ for (const method of interfaceDecl.getMethods()) {
91
+ names.add(method.getName());
147
92
  }
148
- catch (_error) {
149
- // Continue with other interfaces
93
+ for (const property of interfaceDecl.getProperties()) {
94
+ if (this.isCallableProperty(property)) {
95
+ names.add(property.getName());
96
+ }
150
97
  }
151
- return violations;
98
+ return [...names];
152
99
  }
153
100
  /**
154
- * Analyze if a class implements interfaces it doesn't fully use.
101
+ * True when the property's type (without `undefined`) has call signatures
102
+ * and no properties of its own: a plain function, not a callable value
103
+ * with state such as a signal.
155
104
  */
156
- analyzeClassInterfaceUsage(classDecl, filePath) {
157
- const violations = [];
158
- try {
159
- const className = classDecl.getName();
160
- const implementedInterfaces = classDecl.getImplements();
161
- // Check if class implements too many interfaces
162
- if (implementedInterfaces.length > this.maxInterfacesPerClass) {
163
- const startLine = classDecl.getStartLineNumber();
164
- const startColumn = classDecl.getStart() - classDecl.getStartLinePos();
165
- violations.push({
166
- ruleId: this.id,
167
- message: `Class '${className}' implements ${implementedInterfaces.length} interfaces, exceeding the recommended maximum of ${this.maxInterfacesPerClass}. Consider segregating interfaces or using composition.`,
168
- filePath,
169
- line: startLine,
170
- column: startColumn,
171
- suggestedFix: `Split '${className}' into smaller classes or use composition instead of implementing multiple interfaces`,
172
- metadata: {
173
- className,
174
- interfaceCount: implementedInterfaces.length,
175
- maxAllowed: this.maxInterfacesPerClass,
176
- violationType: 'too-many-interfaces',
177
- },
178
- });
179
- }
180
- for (const impl of implementedInterfaces) {
181
- const interfaceType = impl.getType();
182
- const interfaceSymbol = interfaceType.getSymbol();
183
- if (interfaceSymbol) {
184
- // This is a simplified check - in a real implementation,
185
- // we'd analyze which methods are actually used vs declared
186
- const interfaceName = interfaceSymbol.getName();
187
- // For now, just check if the class has any methods at all
188
- // A more sophisticated analysis would check method usage
189
- const classMethods = classDecl.getMethods();
190
- if (classMethods.length === 0) {
191
- const startLine = classDecl.getStartLineNumber();
192
- const startColumn = classDecl.getStart() - classDecl.getStartLinePos();
193
- violations.push({
194
- ruleId: this.id,
195
- message: `Class '${className}' implements interface '${interfaceName}' but may not use all its methods. Consider implementing only the methods you need.`,
196
- filePath,
197
- line: startLine,
198
- column: startColumn,
199
- suggestedFix: `Implement only the interface methods that '${className}' actually needs`,
200
- metadata: {
201
- className,
202
- interfaceName,
203
- violationType: 'unused-interface-methods',
204
- },
205
- });
206
- }
207
- }
208
- }
209
- }
210
- catch (_error) {
211
- // Continue with other classes
212
- }
213
- return violations;
105
+ isCallableProperty(property) {
106
+ const type = property.getType().getNonNullableType();
107
+ return type.getCallSignatures().length > 0 && type.getProperties().length === 0;
214
108
  }
215
109
  /**
216
- * Analyze if an interface mixes different concerns.
110
+ * True for interfaces in `declare global` / `declare module` blocks and for
111
+ * interfaces that merge with a declaration in a `.d.ts` file.
217
112
  */
218
- analyzeInterfaceConcerns(methods, properties) {
219
- const concerns = new Set();
220
- // Analyze method names for concerns
221
- for (const method of methods) {
222
- const methodName = method.getName().toLowerCase();
223
- for (const [concern, keywords] of Object.entries(this.concernKeywords)) {
224
- if (keywords.some((keyword) => methodName.includes(keyword))) {
225
- concerns.add(concern);
226
- }
227
- }
228
- }
229
- // Analyze property names for concerns
230
- for (const property of properties) {
231
- const propertyName = property.getName().toLowerCase();
232
- for (const [concern, keywords] of Object.entries(this.concernKeywords)) {
233
- if (keywords.some((keyword) => propertyName.includes(keyword))) {
234
- concerns.add(concern);
235
- }
236
- }
113
+ isAugmentation(interfaceDecl) {
114
+ const inDeclareBlock = interfaceDecl
115
+ .getAncestors()
116
+ .some((ancestor) => ts_morph_1.Node.isModuleDeclaration(ancestor) && ancestor.hasDeclareKeyword());
117
+ if (inDeclareBlock) {
118
+ return true;
237
119
  }
238
- return {
239
- mixedConcerns: concerns.size > 1,
240
- concerns: Array.from(concerns),
241
- };
120
+ const declarations = interfaceDecl.getSymbol()?.getDeclarations() ?? [];
121
+ return declarations.some((declaration) => declaration !== interfaceDecl &&
122
+ declaration.getSourceFile().isDeclarationFile());
242
123
  }
243
124
  }
244
125
  exports.ISPViolationRule = ISPViolationRule;
@@ -1,51 +1,27 @@
1
1
  import type { AnalysisRule, AnalysisContext, AnalysisResult } from '@angular-modernizer/plugin-system';
2
2
  /**
3
- * LSP Violation Rule (`solid:lsp-violation`) - detects Liskov Substitution
4
- * Principle violations that break substitutability.
3
+ * Former Liskov Substitution checks (missing interface members, missing
4
+ * abstract methods, `not implemented` throws, `instanceof` checks). Reports
5
+ * nothing: a class that misses a required member of an implemented interface
6
+ * or an abstract method of its base does not compile (TS2420, TS2515), so on
7
+ * code that builds those checks could only fire on members they failed to see
8
+ * (inherited, optional, constructor parameter properties, arrow properties).
9
+ * An `instanceof` check alone (`error instanceof HttpErrorResponse`) shows no
10
+ * subtype that breaks its base's contract.
5
11
  *
6
- * Detection patterns (`violationType` in the metadata):
7
- * - `missing-interface-method`, `missing-interface-property`: members of an
8
- * implemented interface that the class does not declare (Angular internal
9
- * members starting with `ɵ` are ignored)
10
- * - `missing-abstract-method`: abstract methods of the base class that are
11
- * not implemented
12
- * - `throws-not-implemented`: implementations of abstract methods whose
13
- * first `throw` mentions `NotImplemented` or `not implemented`
14
- * - `instanceof-check`, `excessive-instanceof-checks`: `instanceof` checks in
15
- * methods (3 or more in one method count as excessive)
12
+ * The id stays registered so configurations naming it keep loading; ConfigLoader
13
+ * warns that `rules['solid:lsp-violation']` has no effect.
16
14
  *
17
- * @example
18
- * ```typescript
19
- * // Violation: derived class weakens base contract
20
- * class Bird { fly(): void {} }
21
- * class Penguin extends Bird {
22
- * fly(): void { throw new Error('Penguins cannot fly'); }
23
- * }
24
- * ```
15
+ * @deprecated Reports nothing; removed in 3.0. The TypeScript compiler reports
16
+ * missing interface members and abstract methods.
25
17
  */
26
18
  export declare class LSPViolationRule implements AnalysisRule {
27
19
  readonly id = "solid:lsp-violation";
28
- readonly name = "Liskov Substitution Principle Violation";
29
- readonly description = "Detects classes that violate the Liskov Substitution Principle";
20
+ readonly name = "Liskov Substitution Principle Violation (deprecated)";
21
+ readonly description = "Deprecated, reports nothing: missing interface members and abstract methods are compile errors";
30
22
  readonly severity = "warning";
31
23
  readonly category = "solid-violation";
32
24
  readonly tags: string[];
33
- analyze(context: AnalysisContext): Promise<AnalysisResult[]>;
34
- /**
35
- * Analyze a class for LSP violations.
36
- */
37
- private analyzeClass;
38
- /**
39
- * Check interface implementation compliance.
40
- */
41
- private checkInterfaceImplementation;
42
- /**
43
- * Check abstract method implementation compliance.
44
- */
45
- private checkAbstractMethodImplementation;
46
- /**
47
- * Check for inheritance-based violations like instanceof checks.
48
- */
49
- private checkInheritanceBasedViolations;
25
+ analyze(_context: AnalysisContext): Promise<AnalysisResult[]>;
50
26
  }
51
27
  //# sourceMappingURL=lsp-violation.rule.d.ts.map