@angular-modernizer/plugin-solid 1.2.0 → 2.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.
@@ -2,33 +2,68 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.DIPViolationRule = void 0;
4
4
  const ts_morph_1 = require("ts-morph");
5
+ const api_1 = require("@angular-modernizer/api");
6
+ /** Module that exports `Injectable`, `Injector` and `inject`. */
7
+ const ANGULAR_CORE = '@angular/core';
8
+ /** First Angular major with `inject()` in field initializers and constructors. */
9
+ const INJECT_FUNCTION_MAJOR = 14;
10
+ /** `@angular/core` functions whose function argument runs as an initializer, not as a class member. */
11
+ const INITIALIZER_FUNCTIONS = new Set([
12
+ 'provideAppInitializer',
13
+ 'provideEnvironmentInitializer',
14
+ 'providePlatformInitializer',
15
+ ]);
16
+ /** `@angular/core` decorators that make Angular DI create the class. */
17
+ const DI_DECORATORS = ['Injectable', 'Component', 'Directive', 'Pipe', 'NgModule'];
5
18
  /**
6
- * DIP Violation Rule (`solid:dip-violation-direct-instantiation`) - detects
7
- * direct service instantiation (Dependency Inversion Principle violation).
19
+ * DIP Violation Rule (`solid:dip-violation-direct-instantiation`) - reports
20
+ * dependencies a class creates or looks up itself instead of declaring them
21
+ * for Angular DI. Severity warning per finding, except
22
+ * `service-locator-outside-di` (info).
8
23
  *
9
- * Detection patterns:
10
- * - `new X()` anywhere in the file where `X` ends with a service suffix
11
- * (`Service`, `Repository`, `Store`, `Manager`, `Api`, `Client`, `Provider`,
12
- * `Facade`, `Helper`, `Util`, `Utils`); metadata `violationType:
13
- * 'direct-instantiation'`
14
- * - Service locator calls `<receiver>.get(...)` where the receiver matches
15
- * `/injector/i`; metadata `violationType: 'service-locator-pattern'`
24
+ * Violation types (`violationType` in the metadata):
25
+ * - `direct-instantiation`: `new X()` where `X` resolves by symbol to a class
26
+ * declared in the project (not in a `.d.ts` file) that has an `Injectable`
27
+ * decorator from `@angular/core`. Library classes (`new HttpClient(handler)`)
28
+ * and undecorated helpers or models are not reported, whatever their name.
29
+ * - `service-locator-pattern`: `.get(...)` on a receiver whose type is
30
+ * Angular's `Injector` (type checker), any receiver expression
31
+ * (`this.injector`, a parameter, `inject(Injector)`).
32
+ * - `service-locator-outside-di` (severity info): the same `.get(...)` lookup
33
+ * outside an injection context in a class with no `Injectable`, `Component`,
34
+ * `Directive`, `Pipe` or `NgModule` decorator from `@angular/core`, such as
35
+ * a handler created with `new`. The hidden dependency is real, but
36
+ * `inject()` is not possible there: `suggestedFix` proposes a constructor
37
+ * parameter filled by the code that creates the class.
16
38
  *
17
- * Service detection matches names because the rule looks at `new`
18
- * expressions, not class declarations.
39
+ * Both are reported only inside class members (methods, constructors,
40
+ * accessors, property initializers), not inside a `useFactory` function, a
41
+ * function passed to `provideAppInitializer`, `provideEnvironmentInitializer`
42
+ * or `providePlatformInitializer`, a decorator or any function outside a class:
43
+ * these build providers and are DI configuration.
44
+ *
45
+ * `suggestedFix` proposes `inject(X)` when the project uses Angular 14 or later
46
+ * (api `angularMajorVersion`) and the call site is an injection context (an
47
+ * instance field initializer or the constructor body, not a nested function);
48
+ * otherwise a constructor parameter (for `service-locator-outside-di` one
49
+ * filled by the creator of the class). Metadata: `violationType`, `principle`,
50
+ * `instantiatedType` or `receiver` and `token`, `injectionContext`,
51
+ * `angularMajorVersion`.
19
52
  *
20
53
  * @example
21
54
  * ```typescript
22
- * // Violation: direct instantiation bypasses Angular DI
23
- * class OrderService {
24
- * private userService = new UserService(); // DIP violation
55
+ * @Injectable({ providedIn: 'root' })
56
+ * export class UserService {}
57
+ *
58
+ * export class OrderComponent {
59
+ * private users = new UserService(); // reported: bypasses Angular DI
25
60
  * }
26
61
  * ```
27
62
  */
28
63
  class DIPViolationRule {
29
64
  id = 'solid:dip-violation-direct-instantiation';
30
65
  name = 'Dependency Inversion Principle Violation';
31
- description = 'Detects direct instantiation of services that should be injected';
66
+ description = 'Detects @Injectable classes created with new and Injector.get() lookups inside class members (info outside Angular DI)';
32
67
  severity = 'warning';
33
68
  category = 'solid-violation';
34
69
  tags = [
@@ -37,117 +72,265 @@ class DIPViolationRule {
37
72
  'dependency-injection',
38
73
  'architecture',
39
74
  ];
40
- /**
41
- * Service class suffixes to detect.
42
- * Aligned with ServicePatternRecognizer patterns for consistency.
43
- */
44
- defaultServiceSuffixes = [
45
- 'Service',
46
- 'Repository',
47
- 'Store',
48
- 'Manager',
49
- 'Api',
50
- 'Client',
51
- 'Provider',
52
- 'Facade',
53
- 'Helper',
54
- 'Util',
55
- 'Utils',
56
- ];
57
- async analyze(context) {
58
- const violations = [];
75
+ analyze(context) {
59
76
  const sourceFile = context.sourceFile;
60
- // Find all 'new' expressions in the file
61
- const newExpressions = sourceFile.getDescendantsOfKind(ts_morph_1.SyntaxKind.NewExpression);
62
- for (const newExpr of newExpressions) {
63
- const violation = this.checkNewExpression(newExpr, sourceFile.getFilePath());
77
+ const violations = [];
78
+ let major = null;
79
+ const version = () => {
80
+ if (major === null) {
81
+ major = (0, api_1.angularMajorVersion)(sourceFile.getProject(), sourceFile.getFilePath());
82
+ }
83
+ return major;
84
+ };
85
+ for (const newExpr of sourceFile.getDescendantsOfKind(ts_morph_1.SyntaxKind.NewExpression)) {
86
+ const violation = this.checkNewExpression(newExpr, sourceFile, version);
87
+ if (violation) {
88
+ violations.push(violation);
89
+ }
90
+ }
91
+ for (const call of sourceFile.getDescendantsOfKind(ts_morph_1.SyntaxKind.CallExpression)) {
92
+ const violation = this.checkInjectorGet(call, sourceFile, version);
64
93
  if (violation) {
65
94
  violations.push(violation);
66
95
  }
67
96
  }
68
- // Check for service locator pattern (Cat 6)
69
- violations.push(...this.analyzeServiceLocator(sourceFile, sourceFile.getFilePath()));
70
97
  return Promise.resolve(violations);
71
98
  }
72
- /**
73
- * Check if a new expression violates DIP.
74
- */
75
- checkNewExpression(newExpr, filePath) {
76
- try {
77
- // Get the type being instantiated
78
- const expression = newExpr.getExpression();
79
- const typeName = expression.getText();
80
- // Check if it's a service class (ends with service suffixes)
81
- if (this.isServiceClass(typeName)) {
82
- const startLine = newExpr.getStartLineNumber();
83
- const startColumn = newExpr.getStart() - newExpr.getStartLinePos();
84
- return {
85
- ruleId: this.id,
86
- message: `Direct instantiation of ${typeName} violates Dependency Inversion Principle. Use dependency injection instead.`,
87
- filePath,
88
- line: startLine,
89
- column: startColumn,
90
- suggestedFix: `Replace 'new ${typeName}()' with 'inject(${typeName})' or constructor injection`,
91
- metadata: {
92
- instantiatedType: typeName,
93
- violationType: 'direct-instantiation',
94
- principle: 'DIP',
95
- },
96
- };
97
- }
99
+ checkNewExpression(newExpr, sourceFile, version) {
100
+ const cls = injectableProjectClass(newExpr.getExpression());
101
+ if (cls === undefined || !isInClassMember(newExpr)) {
98
102
  return null;
99
103
  }
100
- catch (_error) {
101
- // If we can't analyze the expression, skip it
104
+ const typeName = cls.getName() ?? 'class';
105
+ const major = version();
106
+ const injectionContext = isInjectionContext(newExpr);
107
+ return {
108
+ ruleId: this.id,
109
+ severity: 'warning',
110
+ message: `new ${typeName}() creates an @Injectable class outside Angular DI (Dependency Inversion Principle): its own dependencies are not injected, providers and test doubles for ${typeName} are bypassed.`,
111
+ filePath: sourceFile.getFilePath(),
112
+ line: newExpr.getStartLineNumber(),
113
+ column: newExpr.getStart() - newExpr.getStartLinePos(),
114
+ suggestedFix: injectionAdvice(typeName, `new ${typeName}()`, major, injectionContext),
115
+ metadata: {
116
+ instantiatedType: typeName,
117
+ violationType: 'direct-instantiation',
118
+ principle: 'DIP',
119
+ injectionContext,
120
+ angularMajorVersion: major,
121
+ },
122
+ };
123
+ }
124
+ checkInjectorGet(call, sourceFile, version) {
125
+ const callee = call.getExpression();
126
+ if (!ts_morph_1.Node.isPropertyAccessExpression(callee) || callee.getName() !== 'get') {
102
127
  return null;
103
128
  }
104
- }
105
- /**
106
- * Detect service locator pattern: `injector.get(SomeService)` bypasses Angular DI.
107
- */
108
- analyzeServiceLocator(sourceFile, filePath) {
109
- const violations = [];
110
- const callExpressions = sourceFile.getDescendantsOfKind(ts_morph_1.SyntaxKind.CallExpression);
111
- for (const call of callExpressions) {
112
- const expression = call.getExpression();
113
- if (!expression.isKind(ts_morph_1.SyntaxKind.PropertyAccessExpression)) {
114
- continue;
115
- }
116
- const propAccess = expression;
117
- // Must be a .get() call
118
- if (propAccess.getName() !== 'get') {
119
- continue;
120
- }
121
- // Receiver must match /injector/i
122
- const receiver = propAccess.getExpression().getText();
123
- if (!/injector/i.test(receiver)) {
124
- continue;
125
- }
126
- violations.push({
129
+ const receiverNode = callee.getExpression();
130
+ if (!isAngularInjectorType(receiverNode) || !isInClassMember(call)) {
131
+ return null;
132
+ }
133
+ const receiver = receiverNode.getText();
134
+ const token = call.getArguments()[0]?.getText() ?? 'token';
135
+ const major = version();
136
+ const injectionContext = isInjectionContext(call);
137
+ const plainClass = injectionContext ? undefined : classOutsideDi(call);
138
+ if (plainClass !== undefined) {
139
+ return {
127
140
  ruleId: this.id,
128
- message: `Service locator pattern: ${receiver}.get() bypasses Angular DI and makes testing difficult. Inject dependencies directly.`,
129
- filePath,
141
+ severity: 'info',
142
+ message: `Service locator outside Angular DI: ${receiver}.get(${token}) looks up ${token} at runtime in ${plainClass}, a class that Angular DI does not create, so inject() is not available there; the class's dependencies are hidden from its signature.`,
143
+ filePath: sourceFile.getFilePath(),
130
144
  line: call.getStartLineNumber(),
131
145
  column: call.getStart() - call.getStartLinePos(),
132
- suggestedFix: `Replace '${receiver}.get(SomeService)' with 'inject(SomeService)' or add the dependency to the constructor.`,
146
+ suggestedFix: `Declare ${token} as a constructor parameter of ${plainClass}, pass it in from the code that creates ${plainClass}, and use it instead of '${receiver}.get(${token})'.`,
133
147
  metadata: {
134
- violationType: 'service-locator-pattern',
148
+ violationType: 'service-locator-outside-di',
135
149
  principle: 'DIP',
136
150
  receiver,
151
+ token,
152
+ injectionContext,
153
+ angularMajorVersion: major,
137
154
  },
138
- });
155
+ };
139
156
  }
140
- return violations;
141
- }
142
- /**
143
- * Check if a class name represents a service that should be injected.
144
- */
145
- isServiceClass(className) {
146
- // Remove any generic type parameters
147
- const baseName = className.split('<')[0];
148
- // Check against default service suffixes
149
- return this.defaultServiceSuffixes.some((suffix) => baseName?.endsWith(suffix) ?? false);
157
+ return {
158
+ ruleId: this.id,
159
+ severity: 'warning',
160
+ message: `Service locator: ${receiver}.get(${token}) looks up ${token} at runtime instead of declaring it as a dependency (Dependency Inversion Principle); the class's dependencies are hidden from its signature.`,
161
+ filePath: sourceFile.getFilePath(),
162
+ line: call.getStartLineNumber(),
163
+ column: call.getStart() - call.getStartLinePos(),
164
+ suggestedFix: injectionAdvice(token, `${receiver}.get(${token})`, major, injectionContext),
165
+ metadata: {
166
+ violationType: 'service-locator-pattern',
167
+ principle: 'DIP',
168
+ receiver,
169
+ token,
170
+ injectionContext,
171
+ angularMajorVersion: major,
172
+ },
173
+ };
150
174
  }
151
175
  }
152
176
  exports.DIPViolationRule = DIPViolationRule;
177
+ /** Fix text: `inject(X)` from Angular 14 in an injection context, else a constructor parameter. */
178
+ function injectionAdvice(dependency, current, major, injectionContext) {
179
+ if (injectionContext && (major ?? 0) >= INJECT_FUNCTION_MAJOR) {
180
+ return `Replace '${current}' with 'inject(${dependency})'.`;
181
+ }
182
+ return `Declare ${dependency} as a constructor parameter and use it instead of '${current}'.`;
183
+ }
184
+ /** The project class decorated with `@Injectable` from `@angular/core` that `expression` names, if any. */
185
+ function injectableProjectClass(expression) {
186
+ const symbol = expression.getSymbol();
187
+ const target = symbol?.isAlias() ? symbol.getAliasedSymbol() : symbol;
188
+ for (const declaration of target?.getDeclarations() ?? []) {
189
+ if (ts_morph_1.Node.isClassDeclaration(declaration) &&
190
+ !declaration.getSourceFile().isDeclarationFile() &&
191
+ !declaration.getSourceFile().isInNodeModules() &&
192
+ hasAngularInjectable(declaration)) {
193
+ return declaration;
194
+ }
195
+ }
196
+ return undefined;
197
+ }
198
+ /** `true` when the class has an `Injectable` decorator that resolves to `@angular/core`. */
199
+ function hasAngularInjectable(cls) {
200
+ return cls.getDecorators().some((decorator) => {
201
+ const call = decorator.getCallExpression();
202
+ const name = call ? call.getExpression() : decorator.getExpression();
203
+ return isAngularCoreReference(name, 'Injectable');
204
+ });
205
+ }
206
+ /**
207
+ * Name of the class around `node` when it has no `@angular/core` decorator
208
+ * that makes Angular DI create it (`Injectable`, `Component`, `Directive`,
209
+ * `Pipe`, `NgModule`); `undefined` for a DI-created class or no class.
210
+ */
211
+ function classOutsideDi(node) {
212
+ const cls = node.getFirstAncestor((ancestor) => ts_morph_1.Node.isClassDeclaration(ancestor) || ts_morph_1.Node.isClassExpression(ancestor));
213
+ if (!ts_morph_1.Node.isClassDeclaration(cls) && !ts_morph_1.Node.isClassExpression(cls)) {
214
+ return undefined;
215
+ }
216
+ const createdByDi = cls.getDecorators().some((decorator) => {
217
+ const call = decorator.getCallExpression();
218
+ const name = call ? call.getExpression() : decorator.getExpression();
219
+ return DI_DECORATORS.some((exported) => isAngularCoreReference(name, exported));
220
+ });
221
+ return createdByDi ? undefined : (cls.getName() ?? 'class');
222
+ }
223
+ /** `true` when the type of `receiver` is the `Injector` class of `@angular/core`. */
224
+ function isAngularInjectorType(receiver) {
225
+ const type = receiver.getType();
226
+ const symbol = type.getSymbol() ?? type.getAliasSymbol();
227
+ if (symbol?.getName() !== 'Injector') {
228
+ return false;
229
+ }
230
+ return symbol.getDeclarations().some((declaration) => isInAngularCore(declaration));
231
+ }
232
+ /**
233
+ * `true` when `name` (an identifier or `ns.member`) refers to the export
234
+ * `exported` of `@angular/core`: named or aliased import, namespace import, or
235
+ * a symbol declared in the package.
236
+ */
237
+ function isAngularCoreReference(name, exported) {
238
+ if (ts_morph_1.Node.isIdentifier(name)) {
239
+ return isAngularCoreExport(name, exported);
240
+ }
241
+ if (!ts_morph_1.Node.isPropertyAccessExpression(name) || name.getName() !== exported) {
242
+ return false;
243
+ }
244
+ const namespace = name.getExpression();
245
+ return ts_morph_1.Node.isIdentifier(namespace) && isAngularCoreNamespace(namespace);
246
+ }
247
+ /** `true` when the identifier's symbol is the export `exported` of `@angular/core`. */
248
+ function isAngularCoreExport(identifier, exported) {
249
+ const symbol = identifier.getSymbol();
250
+ if (symbol === undefined) {
251
+ return false;
252
+ }
253
+ const imported = symbol
254
+ .getDeclarations()
255
+ .some((declaration) => ts_morph_1.Node.isImportSpecifier(declaration) &&
256
+ declaration.getName() === exported &&
257
+ declaration.getImportDeclaration().getModuleSpecifierValue() === ANGULAR_CORE);
258
+ if (imported) {
259
+ return true;
260
+ }
261
+ const target = symbol.isAlias() ? symbol.getAliasedSymbol() : undefined;
262
+ return (target?.getName() === exported &&
263
+ target.getDeclarations().some((declaration) => isInAngularCore(declaration)));
264
+ }
265
+ /** `true` when the identifier is a namespace import of `@angular/core`. */
266
+ function isAngularCoreNamespace(identifier) {
267
+ return (identifier.getSymbol()?.getDeclarations() ?? []).some((declaration) => ts_morph_1.Node.isNamespaceImport(declaration) &&
268
+ declaration
269
+ .getFirstAncestorByKind(ts_morph_1.SyntaxKind.ImportDeclaration)
270
+ ?.getModuleSpecifierValue() === ANGULAR_CORE);
271
+ }
272
+ /** `true` for a declaration inside the `@angular/core` package. */
273
+ function isInAngularCore(declaration) {
274
+ return declaration
275
+ .getSourceFile()
276
+ .getFilePath()
277
+ .includes(`/node_modules/${ANGULAR_CORE}/`);
278
+ }
279
+ /** `true` for a function that builds a provider: a `useFactory` value or an argument of an Angular initializer function. */
280
+ function isProviderFactory(fn) {
281
+ const parent = fn.getParent();
282
+ if (ts_morph_1.Node.isPropertyAssignment(parent) && parent.getName() === 'useFactory') {
283
+ return true;
284
+ }
285
+ if (!ts_morph_1.Node.isCallExpression(parent) || !parent.getArguments().includes(fn)) {
286
+ return false;
287
+ }
288
+ const callee = parent.getExpression();
289
+ return [...INITIALIZER_FUNCTIONS].some((name) => isAngularCoreReference(callee, name));
290
+ }
291
+ /**
292
+ * `true` when `node` is inside a member of a class (method, constructor,
293
+ * accessor, property initializer) and inside no provider factory between it
294
+ * and that member. Decorators and functions outside classes are not members.
295
+ */
296
+ function isInClassMember(node) {
297
+ for (let current = node.getParent(); current !== undefined; current = current.getParent()) {
298
+ if (ts_morph_1.Node.isDecorator(current) || ts_morph_1.Node.isSourceFile(current)) {
299
+ return false;
300
+ }
301
+ if (ts_morph_1.Node.isFunctionLikeDeclaration(current) && isProviderFactory(current)) {
302
+ return false;
303
+ }
304
+ if (ts_morph_1.Node.isMethodDeclaration(current) ||
305
+ ts_morph_1.Node.isConstructorDeclaration(current) ||
306
+ ts_morph_1.Node.isGetAccessorDeclaration(current) ||
307
+ ts_morph_1.Node.isSetAccessorDeclaration(current) ||
308
+ ts_morph_1.Node.isPropertyDeclaration(current) ||
309
+ ts_morph_1.Node.isClassStaticBlockDeclaration(current)) {
310
+ return ts_morph_1.Node.isClassDeclaration(current.getParent()) || ts_morph_1.Node.isClassExpression(current.getParent());
311
+ }
312
+ }
313
+ return false;
314
+ }
315
+ /**
316
+ * `true` when `node` runs in Angular's injection context: directly in an
317
+ * instance field initializer or the constructor body, with no function in
318
+ * between (a callback runs later, outside the context), of a class that
319
+ * Angular DI creates (see `classOutsideDi`). A class created with `new` has
320
+ * no injection context.
321
+ */
322
+ function isInjectionContext(node) {
323
+ for (let current = node.getParent(); current !== undefined; current = current.getParent()) {
324
+ if (ts_morph_1.Node.isConstructorDeclaration(current)) {
325
+ return classOutsideDi(current) === undefined;
326
+ }
327
+ if (ts_morph_1.Node.isPropertyDeclaration(current)) {
328
+ return !current.isStatic() && classOutsideDi(current) === undefined;
329
+ }
330
+ if (ts_morph_1.Node.isFunctionLikeDeclaration(current) || ts_morph_1.Node.isClassStaticBlockDeclaration(current)) {
331
+ return false;
332
+ }
333
+ }
334
+ return false;
335
+ }
153
336
  //# sourceMappingURL=dip-violation.rule.js.map
@@ -1,24 +1,31 @@
1
1
  import type { AnalysisRule, AnalysisContext, AnalysisResult } from '@angular-modernizer/plugin-system';
2
2
  /**
3
- * God Switch Analysis Rule (`solid:god-switch`) - detects switch statements
4
- * with too many cases (Open/Closed Principle violation).
3
+ * God Switch Analysis Rule (`solid:god-switch`) - reports switch statements
4
+ * that dispatch to too many different behaviors (Open/Closed Principle).
5
5
  *
6
- * Reports every switch statement with more case clauses (excluding
7
- * `default`) than the threshold. The threshold is read from
8
- * `context.config.solid.godSwitch.maxCases` (default: 10). Each result
9
- * carries the case count, a classification of the switch expression
10
- * (`switchType`) and a confidence score. Recommended refactorings: factory
11
- * with strategy objects, polymorphism, strategy or command pattern;
12
- * {@link GodSwitchTransformRule} applies the factory variant.
6
+ * Clauses are counted by body: labels that fall through without statements
7
+ * form one clause with the next label that has statements, and `default`
8
+ * counts like a case clause when it has a body. A clause is a lookup when
9
+ * its body, ignoring `break` and unwrapping blocks, is a single `return` or
10
+ * a single assignment expression statement whose value contains no call or
11
+ * `new` expression or is one call whose arguments are all constants
12
+ * (literals, enum members, `const` variables; `translate.instant('KEY')`);
13
+ * a clause whose body is only `break` is not counted. One
14
+ * finding per switch (severity warning, at the switch) when the number of
15
+ * non-lookup clauses is above the threshold, read from
16
+ * `rules['solid:god-switch'].maxCases` of `.angular-modernizer.json`
17
+ * (`context.config['solid:god-switch'].maxCases`, default: 10). Switches
18
+ * are checked everywhere in the file. A pure value mapping is never
19
+ * reported; {@link GodSwitchTransformRule} applies a factory refactoring.
13
20
  *
14
21
  * @example
15
22
  * ```typescript
16
- * // Violation: switch with too many cases exceeds threshold
23
+ * // Reported: 11 clauses that call a handler
17
24
  * function handleAction(action: string) {
18
25
  * switch (action) {
19
26
  * case 'create': return onCreate();
20
27
  * case 'read': return onRead();
21
- * // 9+ additional cases - "God Switch" pattern
28
+ * // 9 more clauses that call a handler
22
29
  * }
23
30
  * }
24
31
  * ```
@@ -26,35 +33,39 @@ import type { AnalysisRule, AnalysisContext, AnalysisResult } from '@angular-mod
26
33
  export declare class GodSwitchAnalysisRule implements AnalysisRule {
27
34
  readonly id = "solid:god-switch";
28
35
  readonly name = "God Switch Detection";
29
- readonly description = "Detects switch statements with too many cases that violate OCP (configurable threshold, default: 10)";
36
+ readonly description = "Detects switch statements with too many clauses that do more than return or assign a value (configurable threshold, default: 10)";
30
37
  readonly severity = "warning";
31
38
  readonly category = "solid-violation";
32
39
  readonly tags: string[];
33
40
  analyze(context: AnalysisContext): Promise<AnalysisResult[]>;
41
+ private checkSwitch;
34
42
  /**
35
- * Analyze a switch statement for God Switch pattern.
36
- *
37
- * @param switchStmt - The switch statement to analyze
38
- * @param filePath - Path to the file containing the switch statement
39
- * @param maxSwitchCases - Maximum allowed case clauses (configurable threshold)
43
+ * Counts clauses with a body of their own; grouped labels without
44
+ * statements belong to the next clause with statements.
40
45
  */
41
- private analyzeSwitchStatement;
46
+ private countClauses;
47
+ /** Statements without `break`, with a single block unwrapped. */
48
+ private withoutBreaks;
42
49
  /**
43
- * Classify the switch type based on the expression pattern.
44
- *
45
- * Classification helps guide appropriate refactoring strategies:
46
- * - type-based: Use inheritance/polymorphism
47
- * - status-based: Use State Pattern
48
- * - action-based: Use Command Pattern
49
- * - event-based: Use Observer Pattern
50
- * - command-based: Use Command Pattern
51
- * - state-based: Use State Pattern
52
- * - kind-based: Use Factory Pattern
53
- * - category-based: Use Strategy Pattern
54
- * - discriminated-union: Use type-safe discriminated unions
55
- *
56
- * Note: Order matters! Check more specific patterns (event, command) before generic ones (type).
50
+ * True when the body is one `return` or one assignment expression
51
+ * statement whose value has no call or `new` expression in it, or is one
52
+ * call with constant arguments.
57
53
  */
58
- private analyzeSwitchType;
54
+ private isLookup;
55
+ /**
56
+ * A value without a call or `new` expression, or a single call whose
57
+ * arguments (at least one) are all constants: `translate.instant('KEY')`
58
+ * is a key lookup, `this.compute()` and `handle(input)` are not.
59
+ */
60
+ private isLookupValue;
61
+ /**
62
+ * A string, number, boolean or `null` literal, a template without
63
+ * substitutions, or a reference to an enum member or a `const` variable.
64
+ */
65
+ private isConstant;
66
+ /** Strips parentheses. */
67
+ private unwrap;
68
+ /** True when the node is or contains a call or `new` expression. */
69
+ private containsCall;
59
70
  }
60
71
  //# sourceMappingURL=god-switch-analysis.rule.d.ts.map