@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,25 +3,32 @@ Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.GodSwitchAnalysisRule = void 0;
4
4
  const ts_morph_1 = require("ts-morph");
5
5
  /**
6
- * God Switch Analysis Rule (`solid:god-switch`) - detects switch statements
7
- * with too many cases (Open/Closed Principle violation).
6
+ * God Switch Analysis Rule (`solid:god-switch`) - reports switch statements
7
+ * that dispatch to too many different behaviors (Open/Closed Principle).
8
8
  *
9
- * Reports every switch statement with more case clauses (excluding
10
- * `default`) than the threshold. The threshold is read from
11
- * `context.config.solid.godSwitch.maxCases` (default: 10). Each result
12
- * carries the case count, a classification of the switch expression
13
- * (`switchType`) and a confidence score. Recommended refactorings: factory
14
- * with strategy objects, polymorphism, strategy or command pattern;
15
- * {@link GodSwitchTransformRule} applies the factory variant.
9
+ * Clauses are counted by body: labels that fall through without statements
10
+ * form one clause with the next label that has statements, and `default`
11
+ * counts like a case clause when it has a body. A clause is a lookup when
12
+ * its body, ignoring `break` and unwrapping blocks, is a single `return` or
13
+ * a single assignment expression statement whose value contains no call or
14
+ * `new` expression or is one call whose arguments are all constants
15
+ * (literals, enum members, `const` variables; `translate.instant('KEY')`);
16
+ * a clause whose body is only `break` is not counted. One
17
+ * finding per switch (severity warning, at the switch) when the number of
18
+ * non-lookup clauses is above the threshold, read from
19
+ * `rules['solid:god-switch'].maxCases` of `.angular-modernizer.json`
20
+ * (`context.config['solid:god-switch'].maxCases`, default: 10). Switches
21
+ * are checked everywhere in the file. A pure value mapping is never
22
+ * reported; {@link GodSwitchTransformRule} applies a factory refactoring.
16
23
  *
17
24
  * @example
18
25
  * ```typescript
19
- * // Violation: switch with too many cases exceeds threshold
26
+ * // Reported: 11 clauses that call a handler
20
27
  * function handleAction(action: string) {
21
28
  * switch (action) {
22
29
  * case 'create': return onCreate();
23
30
  * case 'read': return onRead();
24
- * // 9+ additional cases - "God Switch" pattern
31
+ * // 9 more clauses that call a handler
25
32
  * }
26
33
  * }
27
34
  * ```
@@ -29,7 +36,7 @@ const ts_morph_1 = require("ts-morph");
29
36
  class GodSwitchAnalysisRule {
30
37
  id = 'solid:god-switch';
31
38
  name = 'God Switch Detection';
32
- description = 'Detects switch statements with too many cases that violate OCP (configurable threshold, default: 10)';
39
+ description = 'Detects switch statements with too many clauses that do more than return or assign a value (configurable threshold, default: 10)';
33
40
  severity = 'warning';
34
41
  category = 'solid-violation';
35
42
  tags = [
@@ -40,121 +47,151 @@ class GodSwitchAnalysisRule {
40
47
  'refactoring',
41
48
  ];
42
49
  async analyze(context) {
43
- const violations = [];
44
- const sourceFile = context.sourceFile;
45
- // Read maxSwitchCases from configuration, defaulting to 10
46
- const solidConfig = context.config['solid'];
47
- const maxSwitchCases = solidConfig?.godSwitch?.maxCases ?? 10;
48
- // Find all switch statements in the file
49
- const switchStatements = sourceFile.getDescendantsOfKind(ts_morph_1.SyntaxKind.SwitchStatement);
50
- for (const switchStmt of switchStatements) {
51
- const violation = this.analyzeSwitchStatement(switchStmt, context.filePath, maxSwitchCases);
52
- if (violation !== null) {
53
- violations.push(violation);
54
- }
50
+ // rules['solid:god-switch'].maxCases of .angular-modernizer.json, default 10
51
+ const ruleConfig = context.config[this.id];
52
+ const maxCases = ruleConfig?.maxCases ?? 10;
53
+ const results = context.sourceFile
54
+ .getDescendantsOfKind(ts_morph_1.SyntaxKind.SwitchStatement)
55
+ .flatMap((switchStmt) => this.checkSwitch(switchStmt, context.filePath, maxCases));
56
+ return Promise.resolve(results);
57
+ }
58
+ checkSwitch(switchStmt, filePath, maxCases) {
59
+ const clauses = switchStmt.getClauses();
60
+ const counts = this.countClauses(switchStmt);
61
+ if (counts.nonLookupClauseCount <= maxCases) {
62
+ return [];
55
63
  }
56
- return violations;
64
+ const switchExpression = switchStmt.getExpression().getText();
65
+ const caseLabels = clauses.flatMap((clause) => ts_morph_1.Node.isCaseClause(clause)
66
+ ? [clause.getExpression().getText().replaceAll(/^['"]|['"]$/g, '')]
67
+ : []);
68
+ const hasDefault = clauses.some((clause) => ts_morph_1.Node.isDefaultClause(clause));
69
+ return [
70
+ {
71
+ ruleId: this.id,
72
+ severity: 'warning',
73
+ message: `Switch on '${switchExpression}' has ${counts.nonLookupClauseCount} clauses that do more than return or assign a value (threshold: ${maxCases}).`,
74
+ filePath,
75
+ line: switchStmt.getStartLineNumber(),
76
+ column: switchStmt.getStart() - switchStmt.getStartLinePos(),
77
+ suggestedFix: 'Move the behavior of each clause into a handler map or into polymorphic classes so a new case does not edit this switch.',
78
+ metadata: {
79
+ ...counts,
80
+ maxCases,
81
+ switchExpression,
82
+ hasDefault,
83
+ caseLabels,
84
+ violationType: 'god-switch',
85
+ principle: 'Open/Closed Principle',
86
+ },
87
+ },
88
+ ];
57
89
  }
58
90
  /**
59
- * Analyze a switch statement for God Switch pattern.
60
- *
61
- * @param switchStmt - The switch statement to analyze
62
- * @param filePath - Path to the file containing the switch statement
63
- * @param maxSwitchCases - Maximum allowed case clauses (configurable threshold)
91
+ * Counts clauses with a body of their own; grouped labels without
92
+ * statements belong to the next clause with statements.
64
93
  */
65
- analyzeSwitchStatement(switchStmt, filePath, maxSwitchCases) {
66
- const caseBlock = switchStmt.getCaseBlock();
67
- const clauses = caseBlock.getClauses();
68
- // Filter to get only case clauses (exclude default)
69
- const caseClauses = clauses.filter((c) => c.getKind() === ts_morph_1.SyntaxKind.CaseClause);
70
- const caseCount = caseClauses.length;
71
- // Check if case count exceeds threshold
72
- if (caseCount <= maxSwitchCases) {
73
- return null;
74
- }
75
- // Get switch expression for classification
76
- const expression = switchStmt.getExpression();
77
- const expressionText = expression.getText();
78
- const switchType = this.analyzeSwitchType(expressionText);
79
- // Check for default clause
80
- const hasDefault = clauses.some((c) => c.getKind() === ts_morph_1.SyntaxKind.DefaultClause);
81
- // Extract case labels for metadata
82
- const caseLabels = caseClauses.map((c) => {
83
- const caseClause = c.asKind(ts_morph_1.SyntaxKind.CaseClause);
84
- if (caseClause) {
85
- const expr = caseClause.getExpression();
86
- // Strip quotes from string literals for cleaner metadata
87
- const text = expr.getText();
88
- return text.replaceAll(/^['"]|['"]$/g, '');
94
+ countClauses(switchStmt) {
95
+ let clauseCount = 0;
96
+ let lookupClauseCount = 0;
97
+ for (const clause of switchStmt.getClauses()) {
98
+ const body = this.withoutBreaks(clause.getStatements());
99
+ if (body.length === 0) {
100
+ continue;
101
+ }
102
+ clauseCount++;
103
+ if (this.isLookup(body)) {
104
+ lookupClauseCount++;
89
105
  }
90
- return 'unknown';
91
- });
92
- // Build violation result
106
+ }
93
107
  return {
94
- ruleId: this.id,
95
- message: `God Switch detected: ${caseCount} cases (${switchType}). Consider Factory Pattern.`,
96
- filePath,
97
- line: switchStmt.getStartLineNumber(),
98
- column: switchStmt.getStart() - switchStmt.getStartLinePos(),
99
- suggestedFix: 'Refactor to Factory Pattern with strategy objects for each case type',
100
- metadata: {
101
- caseCount,
102
- switchType,
103
- switchExpression: expressionText,
104
- hasDefault,
105
- confidence: 0.9,
106
- caseLabels,
107
- violationType: 'god-switch',
108
- principle: 'Open/Closed Principle',
109
- },
108
+ clauseCount,
109
+ lookupClauseCount,
110
+ nonLookupClauseCount: clauseCount - lookupClauseCount,
110
111
  };
111
112
  }
113
+ /** Statements without `break`, with a single block unwrapped. */
114
+ withoutBreaks(statements) {
115
+ const rest = statements.filter((stmt) => !ts_morph_1.Node.isBreakStatement(stmt));
116
+ const [only] = rest;
117
+ if (rest.length === 1 && ts_morph_1.Node.isBlock(only)) {
118
+ return this.withoutBreaks(only.getStatements());
119
+ }
120
+ return rest;
121
+ }
112
122
  /**
113
- * Classify the switch type based on the expression pattern.
114
- *
115
- * Classification helps guide appropriate refactoring strategies:
116
- * - type-based: Use inheritance/polymorphism
117
- * - status-based: Use State Pattern
118
- * - action-based: Use Command Pattern
119
- * - event-based: Use Observer Pattern
120
- * - command-based: Use Command Pattern
121
- * - state-based: Use State Pattern
122
- * - kind-based: Use Factory Pattern
123
- * - category-based: Use Strategy Pattern
124
- * - discriminated-union: Use type-safe discriminated unions
125
- *
126
- * Note: Order matters! Check more specific patterns (event, command) before generic ones (type).
123
+ * True when the body is one `return` or one assignment expression
124
+ * statement whose value has no call or `new` expression in it, or is one
125
+ * call with constant arguments.
127
126
  */
128
- analyzeSwitchType(expression) {
129
- // Pattern matching on switch expression text
130
- // Check specific patterns first to avoid false matches
131
- if (/event/i.test(expression)) {
132
- return 'event-based';
127
+ isLookup(body) {
128
+ if (body.length !== 1) {
129
+ return false;
133
130
  }
134
- if (/command/i.test(expression)) {
135
- return 'command-based';
131
+ const [stmt] = body;
132
+ if (ts_morph_1.Node.isReturnStatement(stmt)) {
133
+ const value = stmt.getExpression();
134
+ return value === undefined || this.isLookupValue(value);
136
135
  }
137
- if (/status/i.test(expression)) {
138
- return 'status-based';
136
+ if (!ts_morph_1.Node.isExpressionStatement(stmt)) {
137
+ return false;
139
138
  }
140
- if (/action/i.test(expression)) {
141
- return 'action-based';
139
+ const expr = stmt.getExpression();
140
+ if (!ts_morph_1.Node.isBinaryExpression(expr)) {
141
+ return false;
142
142
  }
143
- if (/state/i.test(expression)) {
144
- return 'state-based';
143
+ const operator = expr.getOperatorToken().getKind();
144
+ const isAssignment = operator >= ts_morph_1.SyntaxKind.FirstAssignment &&
145
+ operator <= ts_morph_1.SyntaxKind.LastAssignment;
146
+ return isAssignment && this.isLookupValue(expr.getRight());
147
+ }
148
+ /**
149
+ * A value without a call or `new` expression, or a single call whose
150
+ * arguments (at least one) are all constants: `translate.instant('KEY')`
151
+ * is a key lookup, `this.compute()` and `handle(input)` are not.
152
+ */
153
+ isLookupValue(value) {
154
+ if (!this.containsCall(value)) {
155
+ return true;
145
156
  }
146
- if (/kind/i.test(expression)) {
147
- return 'kind-based';
157
+ const call = this.unwrap(value);
158
+ if (!ts_morph_1.Node.isCallExpression(call) || this.containsCall(call.getExpression())) {
159
+ return false;
148
160
  }
149
- if (/category/i.test(expression)) {
150
- return 'category-based';
161
+ const args = call.getArguments();
162
+ return args.length > 0 && args.every((arg) => this.isConstant(arg));
163
+ }
164
+ /**
165
+ * A string, number, boolean or `null` literal, a template without
166
+ * substitutions, or a reference to an enum member or a `const` variable.
167
+ */
168
+ isConstant(node) {
169
+ const kind = node.getKind();
170
+ if (ts_morph_1.Node.isStringLiteral(node) ||
171
+ ts_morph_1.Node.isNoSubstitutionTemplateLiteral(node) ||
172
+ ts_morph_1.Node.isNumericLiteral(node) ||
173
+ kind === ts_morph_1.SyntaxKind.TrueKeyword ||
174
+ kind === ts_morph_1.SyntaxKind.FalseKeyword ||
175
+ kind === ts_morph_1.SyntaxKind.NullKeyword) {
176
+ return true;
151
177
  }
152
- // Check generic pattern last
153
- if (/type/i.test(expression)) {
154
- return 'type-based';
178
+ if (!ts_morph_1.Node.isIdentifier(node) && !ts_morph_1.Node.isPropertyAccessExpression(node)) {
179
+ return false;
155
180
  }
156
- // Default classification
157
- return 'discriminated-union';
181
+ const declarations = node.getSymbol()?.getDeclarations() ?? [];
182
+ return (declarations.length > 0 &&
183
+ declarations.every((decl) => ts_morph_1.Node.isEnumMember(decl) ||
184
+ (ts_morph_1.Node.isVariableDeclaration(decl) &&
185
+ decl.getVariableStatement()?.getDeclarationKind() === ts_morph_1.VariableDeclarationKind.Const)));
186
+ }
187
+ /** Strips parentheses. */
188
+ unwrap(node) {
189
+ return ts_morph_1.Node.isParenthesizedExpression(node) ? this.unwrap(node.getExpression()) : node;
190
+ }
191
+ /** True when the node is or contains a call or `new` expression. */
192
+ containsCall(node) {
193
+ const isCall = (child) => ts_morph_1.Node.isCallExpression(child) || ts_morph_1.Node.isNewExpression(child);
194
+ return isCall(node) || node.getFirstDescendant(isCall) !== undefined;
158
195
  }
159
196
  }
160
197
  exports.GodSwitchAnalysisRule = GodSwitchAnalysisRule;
@@ -1,57 +1,59 @@
1
1
  import type { AnalysisRule, AnalysisContext, AnalysisResult } from '@angular-modernizer/plugin-system';
2
2
  /**
3
- * ISP Violation Rule (`solid:isp-violation`) - detects Interface Segregation
4
- * Principle violations.
3
+ * ISP Violation Rule (`solid:isp-violation`) - reports interfaces that declare
4
+ * more methods than one client is likely to need.
5
5
  *
6
- * Detection patterns (`violationType` in the metadata):
7
- * - `too-many-methods`: interfaces with more than 5 methods
8
- * - `mixed-concerns`: interfaces whose members mix concerns (UI, data,
9
- * business logic) by name keywords
10
- * - `too-many-interfaces`: classes implementing more than 3 interfaces
11
- * - `unused-interface-methods`: classes that implement an interface but
12
- * declare no methods
6
+ * One finding per interface (`violationType: 'too-many-methods'`, severity
7
+ * warning, at the interface) when it declares more than 5 methods. Methods
8
+ * are the interface's own method signatures counted by name (overloads once)
9
+ * plus properties whose type is a plain function (`onSave: () => void`, also
10
+ * optional and through a type alias). Callable types with properties of their
11
+ * own (signals such as `title: Signal<string>`), data properties, call and
12
+ * index signatures and members inherited through `extends` are not counted.
13
+ *
14
+ * Skipped: interfaces inside `declare global` or `declare module` blocks and
15
+ * interfaces that merge with a declaration in a `.d.ts` file (a top-level
16
+ * `interface Window` in a script file): they augment a type the project does
17
+ * not own. Classes are not examined; how many interfaces a class implements
18
+ * says nothing about the size of any of them.
13
19
  *
14
20
  * @example
15
21
  * ```typescript
16
- * // Violation: interface forces implementations to define unrelated methods
17
- * interface IWorker {
22
+ * // Reported: 6 methods
23
+ * interface Worker {
18
24
  * work(): void;
19
- * eat(): void; // Irrelevant for robots
20
- * sleep(): void; // Irrelevant for robots
25
+ * eat(): void;
26
+ * sleep(): void;
27
+ * commute(): void;
28
+ * report(): void;
29
+ * train(): void;
21
30
  * }
22
31
  * ```
23
32
  */
24
33
  export declare class ISPViolationRule implements AnalysisRule {
25
34
  readonly id = "solid:isp-violation";
26
35
  readonly name = "Interface Segregation Principle Violation";
27
- readonly description = "Detects interfaces that are too large or have mixed responsibilities";
36
+ readonly description = "Detects interfaces that declare more than 5 methods (overloads once, function-typed properties included)";
28
37
  readonly severity = "warning";
29
38
  readonly category = "solid-violation";
30
39
  readonly tags: string[];
31
- /**
32
- * Maximum number of methods allowed in an interface.
33
- */
40
+ /** Methods an interface may declare before it is reported. */
34
41
  private readonly maxMethodsInInterface;
35
- /**
36
- * Maximum number of interfaces a class can implement.
37
- */
38
- private readonly maxInterfacesPerClass;
39
- /**
40
- * Keywords that indicate different concerns.
41
- */
42
- private readonly concernKeywords;
43
42
  analyze(context: AnalysisContext): Promise<AnalysisResult[]>;
43
+ /** One finding when the interface declares more than the allowed methods. */
44
+ private checkInterface;
45
+ /** Distinct names of method signatures and callable property signatures. */
46
+ private methodNames;
44
47
  /**
45
- * Analyze an interface for ISP violations.
46
- */
47
- private analyzeInterface;
48
- /**
49
- * Analyze if a class implements interfaces it doesn't fully use.
48
+ * True when the property's type (without `undefined`) has call signatures
49
+ * and no properties of its own: a plain function, not a callable value
50
+ * with state such as a signal.
50
51
  */
51
- private analyzeClassInterfaceUsage;
52
+ private isCallableProperty;
52
53
  /**
53
- * Analyze if an interface mixes different concerns.
54
+ * True for interfaces in `declare global` / `declare module` blocks and for
55
+ * interfaces that merge with a declaration in a `.d.ts` file.
54
56
  */
55
- private analyzeInterfaceConcerns;
57
+ private isAugmentation;
56
58
  }
57
59
  //# sourceMappingURL=isp-violation.rule.d.ts.map