@angular-modernizer/plugin-solid 0.2.0 → 1.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/dist/orchestrators/service-dip-violation-transform.orchestrator.d.ts +1 -1
- package/dist/orchestrators/service-dip-violation-transform.orchestrator.js +1 -1
- package/dist/rules/service-dip-violation.analysis.rule.d.ts +6 -6
- package/dist/rules/service-dip-violation.analysis.rule.js +6 -6
- package/package.json +19 -9
- package/dist/index.d.ts.map +0 -1
- package/dist/index.js.map +0 -1
- package/dist/orchestrators/god-switch-transform-orchestrator.d.ts.map +0 -1
- package/dist/orchestrators/god-switch-transform-orchestrator.js.map +0 -1
- package/dist/orchestrators/service-dip-violation-transform.orchestrator.d.ts.map +0 -1
- package/dist/orchestrators/service-dip-violation-transform.orchestrator.js.map +0 -1
- package/dist/rules/dip-violation.rule.d.ts.map +0 -1
- package/dist/rules/dip-violation.rule.js.map +0 -1
- package/dist/rules/god-switch-analysis.rule.d.ts.map +0 -1
- package/dist/rules/god-switch-analysis.rule.js.map +0 -1
- package/dist/rules/isp-violation.rule.d.ts.map +0 -1
- package/dist/rules/isp-violation.rule.js.map +0 -1
- package/dist/rules/lsp-violation.rule.d.ts.map +0 -1
- package/dist/rules/lsp-violation.rule.js.map +0 -1
- package/dist/rules/ocp-violation.rule.d.ts.map +0 -1
- package/dist/rules/ocp-violation.rule.js.map +0 -1
- package/dist/rules/service-dip-violation.analysis.rule.d.ts.map +0 -1
- package/dist/rules/service-dip-violation.analysis.rule.js.map +0 -1
- package/dist/rules/srp-violation.rule.d.ts.map +0 -1
- package/dist/rules/srp-violation.rule.js.map +0 -1
- package/dist/solid-plugin.d.ts.map +0 -1
- package/dist/solid-plugin.js.map +0 -1
- package/dist/transform-rules/god-switch-transform.rule.d.ts.map +0 -1
- package/dist/transform-rules/god-switch-transform.rule.js.map +0 -1
- package/dist/transform-rules/service-dip-violation.transform.rule.d.ts.map +0 -1
- package/dist/transform-rules/service-dip-violation.transform.rule.js.map +0 -1
- package/src/index.ts +0 -30
- package/src/orchestrators/god-switch-transform-orchestrator.ts +0 -1562
- package/src/orchestrators/service-dip-violation-transform.orchestrator.ts +0 -331
- package/src/rules/dip-violation.rule.ts +0 -194
- package/src/rules/god-switch-analysis.rule.ts +0 -209
- package/src/rules/isp-violation.rule.ts +0 -315
- package/src/rules/lsp-violation.rule.ts +0 -393
- package/src/rules/ocp-violation.rule.ts +0 -264
- package/src/rules/service-dip-violation.analysis.rule.ts +0 -285
- package/src/rules/srp-violation.rule.ts +0 -533
- package/src/solid-plugin.ts +0 -127
- package/src/transform-rules/god-switch-transform.rule.ts +0 -189
- package/src/transform-rules/service-dip-violation.transform.rule.ts +0 -134
|
@@ -1,331 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* @angular-modernizer/plugin-solid - Service DIP Violation Transform Orchestrator
|
|
3
|
-
*
|
|
4
|
-
* Transforms concrete constructor injection into interface-based injection:
|
|
5
|
-
*
|
|
6
|
-
* BEFORE:
|
|
7
|
-
* constructor(private svc: OrderService) {}
|
|
8
|
-
*
|
|
9
|
-
* AFTER (in consuming file):
|
|
10
|
-
* constructor(@Inject(ORDER_SERVICE_TOKEN) private svc: IOrderService) {}
|
|
11
|
-
*
|
|
12
|
-
* AFTER (in injected service file):
|
|
13
|
-
* export interface IOrderService { methodA(): void; ... }
|
|
14
|
-
* export const ORDER_SERVICE_TOKEN = new InjectionToken<IOrderService>('order-service');
|
|
15
|
-
*
|
|
16
|
-
* Philosophy: "Thin Rule, Thick Orchestrator"
|
|
17
|
-
* - Stateless — no constructor dependencies
|
|
18
|
-
* - All operations via ts-morph AST (direct, not via context.api.transformation.importManager)
|
|
19
|
-
* - Idempotent: skips params already decorated with @Inject
|
|
20
|
-
* - Multi-file: modifies both consuming file and injected service file
|
|
21
|
-
*/
|
|
22
|
-
|
|
23
|
-
import type { TransformContext } from '@angular-modernizer/plugin-system';
|
|
24
|
-
import type { PublicApi } from '@angular-modernizer/api';
|
|
25
|
-
import {
|
|
26
|
-
Node,
|
|
27
|
-
type ClassDeclaration,
|
|
28
|
-
type ParameterDeclaration,
|
|
29
|
-
type SourceFile,
|
|
30
|
-
} from 'ts-morph';
|
|
31
|
-
import { dirname, relative } from 'node:path';
|
|
32
|
-
|
|
33
|
-
export interface ServiceDipTransformResult {
|
|
34
|
-
changeCount: number;
|
|
35
|
-
transformedParams: {
|
|
36
|
-
injectingClass: string;
|
|
37
|
-
parameterName: string;
|
|
38
|
-
interfaceName: string;
|
|
39
|
-
tokenName: string;
|
|
40
|
-
}[];
|
|
41
|
-
errors: string[];
|
|
42
|
-
}
|
|
43
|
-
|
|
44
|
-
/**
|
|
45
|
-
* Orchestrator for DIP violation transformation.
|
|
46
|
-
*
|
|
47
|
-
* For each constructor parameter that injects a concrete `` class:
|
|
48
|
-
* 1. Derives interface name (`I${ClassName}`) and token name (`CLASS_NAME_TOKEN`)
|
|
49
|
-
* 2. Inserts the interface + InjectionToken into the injected service file
|
|
50
|
-
* 3. Replaces the parameter type with the interface name
|
|
51
|
-
* 4. Adds `@Inject(TOKEN)` to the parameter
|
|
52
|
-
* 5. Ensures all required imports are present in both files
|
|
53
|
-
*/
|
|
54
|
-
export class ServiceDipViolationTransformOrchestrator {
|
|
55
|
-
run(context: TransformContext<PublicApi>): ServiceDipTransformResult {
|
|
56
|
-
const { sourceFile } = context;
|
|
57
|
-
const result: ServiceDipTransformResult = {
|
|
58
|
-
changeCount: 0,
|
|
59
|
-
transformedParams: [],
|
|
60
|
-
errors: [],
|
|
61
|
-
};
|
|
62
|
-
|
|
63
|
-
// Skip declaration files
|
|
64
|
-
if (sourceFile.getFilePath().endsWith('.d.ts')) {
|
|
65
|
-
return result;
|
|
66
|
-
}
|
|
67
|
-
|
|
68
|
-
for (const classDecl of sourceFile.getClasses()) {
|
|
69
|
-
if (!this.hasInjectableDecorator(classDecl)) {
|
|
70
|
-
continue;
|
|
71
|
-
}
|
|
72
|
-
|
|
73
|
-
const ctor = classDecl.getConstructors()[0];
|
|
74
|
-
if (!ctor) {
|
|
75
|
-
continue;
|
|
76
|
-
}
|
|
77
|
-
|
|
78
|
-
for (const param of ctor.getParameters()) {
|
|
79
|
-
try {
|
|
80
|
-
const transformed = this.transformParam(param, classDecl, sourceFile);
|
|
81
|
-
if (transformed) {
|
|
82
|
-
result.changeCount++;
|
|
83
|
-
result.transformedParams.push(transformed);
|
|
84
|
-
}
|
|
85
|
-
} catch (err) {
|
|
86
|
-
const msg = err instanceof Error ? err.message : String(err);
|
|
87
|
-
result.errors.push(
|
|
88
|
-
`${classDecl.getName() ?? '?'}.${param.getName()}: ${msg}`,
|
|
89
|
-
);
|
|
90
|
-
}
|
|
91
|
-
}
|
|
92
|
-
}
|
|
93
|
-
|
|
94
|
-
return result;
|
|
95
|
-
}
|
|
96
|
-
|
|
97
|
-
// ---------------------------------------------------------------------------
|
|
98
|
-
// Core: per-parameter transformation
|
|
99
|
-
// ---------------------------------------------------------------------------
|
|
100
|
-
|
|
101
|
-
private transformParam(
|
|
102
|
-
param: ParameterDeclaration,
|
|
103
|
-
injectingClass: ClassDeclaration,
|
|
104
|
-
consumingFile: SourceFile,
|
|
105
|
-
): {
|
|
106
|
-
injectingClass: string;
|
|
107
|
-
parameterName: string;
|
|
108
|
-
interfaceName: string;
|
|
109
|
-
tokenName: string;
|
|
110
|
-
} | null {
|
|
111
|
-
// Idempotency: already has @Inject → skip
|
|
112
|
-
if (param.getDecorators().some((d) => d.getName() === 'Inject')) {
|
|
113
|
-
return null;
|
|
114
|
-
}
|
|
115
|
-
|
|
116
|
-
const injectedDecl = this.resolveServiceDeclaration(param);
|
|
117
|
-
if (!injectedDecl || !this.hasInjectableDecorator(injectedDecl)) {
|
|
118
|
-
return null;
|
|
119
|
-
}
|
|
120
|
-
|
|
121
|
-
const injectedClassName = injectedDecl.getName();
|
|
122
|
-
if (!injectedClassName) {
|
|
123
|
-
return null;
|
|
124
|
-
}
|
|
125
|
-
|
|
126
|
-
const interfaceName = `I${injectedClassName}`;
|
|
127
|
-
const tokenName = this.buildTokenName(injectedClassName);
|
|
128
|
-
const injectedSourceFile = injectedDecl.getSourceFile();
|
|
129
|
-
|
|
130
|
-
// 1. Insert interface + token into injected service file (if not already there)
|
|
131
|
-
if (!injectedSourceFile.getInterface(interfaceName)) {
|
|
132
|
-
const methods = this.extractPublicMethodSignatures(injectedDecl);
|
|
133
|
-
this.insertInterfaceAndToken(
|
|
134
|
-
injectedSourceFile,
|
|
135
|
-
interfaceName,
|
|
136
|
-
tokenName,
|
|
137
|
-
methods,
|
|
138
|
-
);
|
|
139
|
-
this.ensureNamedImport(
|
|
140
|
-
injectedSourceFile,
|
|
141
|
-
'@angular/core',
|
|
142
|
-
'InjectionToken',
|
|
143
|
-
);
|
|
144
|
-
}
|
|
145
|
-
|
|
146
|
-
// 2. Replace parameter type in consuming file
|
|
147
|
-
param.setType(interfaceName);
|
|
148
|
-
|
|
149
|
-
// 3. Add @Inject(TOKEN) decorator to the parameter
|
|
150
|
-
param.addDecorator({ name: 'Inject', arguments: [tokenName] });
|
|
151
|
-
|
|
152
|
-
// 4. Ensure imports in consuming file
|
|
153
|
-
const relativePath = this.calculateRelativePath(
|
|
154
|
-
consumingFile.getFilePath(),
|
|
155
|
-
injectedSourceFile.getFilePath(),
|
|
156
|
-
);
|
|
157
|
-
this.ensureNamedImport(consumingFile, relativePath, interfaceName);
|
|
158
|
-
this.ensureNamedImport(consumingFile, relativePath, tokenName);
|
|
159
|
-
this.ensureNamedImport(consumingFile, '@angular/core', 'Inject');
|
|
160
|
-
|
|
161
|
-
return {
|
|
162
|
-
injectingClass: injectingClass.getName() ?? 'Unknown',
|
|
163
|
-
parameterName: param.getName(),
|
|
164
|
-
interfaceName,
|
|
165
|
-
tokenName,
|
|
166
|
-
};
|
|
167
|
-
}
|
|
168
|
-
|
|
169
|
-
// ---------------------------------------------------------------------------
|
|
170
|
-
// Interface + Token insertion
|
|
171
|
-
// ---------------------------------------------------------------------------
|
|
172
|
-
|
|
173
|
-
private insertInterfaceAndToken(
|
|
174
|
-
sf: SourceFile,
|
|
175
|
-
interfaceName: string,
|
|
176
|
-
tokenName: string,
|
|
177
|
-
methodSignatures: string[],
|
|
178
|
-
): void {
|
|
179
|
-
const insertIndex = this.findInsertionIndex(sf);
|
|
180
|
-
|
|
181
|
-
const methodBlock =
|
|
182
|
-
methodSignatures.length > 0
|
|
183
|
-
? `{\n${methodSignatures.map((s) => ` ${s}`).join('\n')}\n}`
|
|
184
|
-
: '{}';
|
|
185
|
-
|
|
186
|
-
const kebabName = this.toKebabCase(interfaceName.slice(1)); // strip leading 'I'
|
|
187
|
-
|
|
188
|
-
sf.insertStatements(insertIndex, [
|
|
189
|
-
`export interface ${interfaceName} ${methodBlock}`,
|
|
190
|
-
`export const ${tokenName} = new InjectionToken<${interfaceName}>('${kebabName}');`,
|
|
191
|
-
]);
|
|
192
|
-
}
|
|
193
|
-
|
|
194
|
-
/**
|
|
195
|
-
* Finds the statement index right after all top-level imports.
|
|
196
|
-
* Inserts interface + token before any class/function declarations.
|
|
197
|
-
*/
|
|
198
|
-
private findInsertionIndex(sf: SourceFile): number {
|
|
199
|
-
const stmts = sf.getStatements();
|
|
200
|
-
let lastImportIndex = -1;
|
|
201
|
-
for (let i = 0; i < stmts.length; i++) {
|
|
202
|
-
if (Node.isImportDeclaration(stmts[i])) {
|
|
203
|
-
lastImportIndex = i;
|
|
204
|
-
}
|
|
205
|
-
}
|
|
206
|
-
return lastImportIndex + 1;
|
|
207
|
-
}
|
|
208
|
-
|
|
209
|
-
// ---------------------------------------------------------------------------
|
|
210
|
-
// Public method signature extraction
|
|
211
|
-
// ---------------------------------------------------------------------------
|
|
212
|
-
|
|
213
|
-
private extractPublicMethodSignatures(classDecl: ClassDeclaration): string[] {
|
|
214
|
-
const signatures: string[] = [];
|
|
215
|
-
|
|
216
|
-
for (const method of classDecl.getMethods()) {
|
|
217
|
-
// Skip private / protected / static
|
|
218
|
-
const mods = method.getModifiers().map((m) => m.getText());
|
|
219
|
-
if (
|
|
220
|
-
mods.includes('private') ||
|
|
221
|
-
mods.includes('protected') ||
|
|
222
|
-
mods.includes('static')
|
|
223
|
-
) {
|
|
224
|
-
continue;
|
|
225
|
-
}
|
|
226
|
-
|
|
227
|
-
const name = method.getName();
|
|
228
|
-
const params = method
|
|
229
|
-
.getParameters()
|
|
230
|
-
.map((p) => {
|
|
231
|
-
const typeText = p.getTypeNode()?.getText() ?? 'unknown';
|
|
232
|
-
return `${p.getName()}: ${typeText}`;
|
|
233
|
-
})
|
|
234
|
-
.join(', ');
|
|
235
|
-
const returnType = method.getReturnTypeNode()?.getText() ?? 'void';
|
|
236
|
-
|
|
237
|
-
signatures.push(`${name}(${params}): ${returnType};`);
|
|
238
|
-
}
|
|
239
|
-
|
|
240
|
-
return signatures;
|
|
241
|
-
}
|
|
242
|
-
|
|
243
|
-
// ---------------------------------------------------------------------------
|
|
244
|
-
// Import management (direct ts-morph, no importManager mock needed)
|
|
245
|
-
// ---------------------------------------------------------------------------
|
|
246
|
-
|
|
247
|
-
private ensureNamedImport(
|
|
248
|
-
sf: SourceFile,
|
|
249
|
-
moduleSpecifier: string,
|
|
250
|
-
namedExport: string,
|
|
251
|
-
): void {
|
|
252
|
-
const existing = sf.getImportDeclaration(
|
|
253
|
-
(d) => d.getModuleSpecifierValue() === moduleSpecifier,
|
|
254
|
-
);
|
|
255
|
-
if (existing) {
|
|
256
|
-
const alreadyImported = existing
|
|
257
|
-
.getNamedImports()
|
|
258
|
-
.some((ni) => ni.getName() === namedExport);
|
|
259
|
-
if (!alreadyImported) {
|
|
260
|
-
existing.addNamedImport(namedExport);
|
|
261
|
-
}
|
|
262
|
-
} else {
|
|
263
|
-
sf.addImportDeclaration({ moduleSpecifier, namedImports: [namedExport] });
|
|
264
|
-
}
|
|
265
|
-
}
|
|
266
|
-
|
|
267
|
-
// ---------------------------------------------------------------------------
|
|
268
|
-
// Helpers
|
|
269
|
-
// ---------------------------------------------------------------------------
|
|
270
|
-
|
|
271
|
-
private resolveServiceDeclaration(
|
|
272
|
-
param: ParameterDeclaration,
|
|
273
|
-
): ClassDeclaration | null {
|
|
274
|
-
try {
|
|
275
|
-
const declarations = param.getType().getSymbol()?.getDeclarations();
|
|
276
|
-
if (!declarations || declarations.length === 0) {
|
|
277
|
-
return null;
|
|
278
|
-
}
|
|
279
|
-
for (const decl of declarations) {
|
|
280
|
-
if (Node.isClassDeclaration(decl)) {
|
|
281
|
-
return decl;
|
|
282
|
-
}
|
|
283
|
-
}
|
|
284
|
-
return null;
|
|
285
|
-
} catch {
|
|
286
|
-
return null;
|
|
287
|
-
}
|
|
288
|
-
}
|
|
289
|
-
|
|
290
|
-
private hasInjectableDecorator(classDecl: ClassDeclaration): boolean {
|
|
291
|
-
return classDecl.getDecorators().some((d) => d.getName() === 'Injectable');
|
|
292
|
-
}
|
|
293
|
-
|
|
294
|
-
/**
|
|
295
|
-
* Converts `OrderService` → `ORDER_SERVICE_TOKEN`.
|
|
296
|
-
* Uses word-boundary splitting to handle consecutive capitals (e.g. `HTTPClient` → `HTTP_CLIENT_TOKEN`).
|
|
297
|
-
*/
|
|
298
|
-
buildTokenName(className: string): string {
|
|
299
|
-
return (
|
|
300
|
-
className
|
|
301
|
-
.replaceAll(/([a-z])([A-Z])/g, '$1_$2')
|
|
302
|
-
.replaceAll(/([A-Z]+)([A-Z][a-z])/g, '$1_$2')
|
|
303
|
-
.toUpperCase() + '_TOKEN'
|
|
304
|
-
);
|
|
305
|
-
}
|
|
306
|
-
|
|
307
|
-
/**
|
|
308
|
-
* Converts `IOrderService` → `order-service` (kebab-case, strips leading I).
|
|
309
|
-
*/
|
|
310
|
-
private toKebabCase(str: string): string {
|
|
311
|
-
return str
|
|
312
|
-
.replace(/([a-z])([A-Z])/g, '$1-$2')
|
|
313
|
-
.replace(/([A-Z]+)([A-Z][a-z])/g, '$1-$2')
|
|
314
|
-
.toLowerCase();
|
|
315
|
-
}
|
|
316
|
-
|
|
317
|
-
/**
|
|
318
|
-
* Computes the relative module specifier from `fromPath` to `toPath`.
|
|
319
|
-
* Strips the `.ts` extension to produce a valid import path.
|
|
320
|
-
*/
|
|
321
|
-
calculateRelativePath(fromPath: string, toPath: string): string {
|
|
322
|
-
const fromDir = dirname(fromPath);
|
|
323
|
-
let rel = relative(fromDir, toPath)
|
|
324
|
-
.replace(/\.ts$/, '')
|
|
325
|
-
.replaceAll('\\', '/');
|
|
326
|
-
if (!rel.startsWith('.')) {
|
|
327
|
-
rel = './' + rel;
|
|
328
|
-
}
|
|
329
|
-
return rel;
|
|
330
|
-
}
|
|
331
|
-
}
|
|
@@ -1,194 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* @angular-modernizer/plugin-solid - DIP Violation Rule
|
|
3
|
-
*
|
|
4
|
-
* Detects direct instantiation of services (Dependency Inversion Principle violation).
|
|
5
|
-
*
|
|
6
|
-
* Detection Patterns:
|
|
7
|
-
* - new MyService() in constructors or methods
|
|
8
|
-
* - Direct instantiation of classes matching service patterns (Service, Repository, Store, etc.)
|
|
9
|
-
*
|
|
10
|
-
* This rule helps enforce proper dependency injection patterns in Angular applications.
|
|
11
|
-
*
|
|
12
|
-
* NOTE: This rule uses pattern matching for service detection since it analyzes NewExpressions
|
|
13
|
-
* rather than ClassDeclarations. For class-level service detection, use ServiceDetector.
|
|
14
|
-
*
|
|
15
|
-
* @example
|
|
16
|
-
* // Violation: direct instantiation bypasses Angular DI
|
|
17
|
-
* class OrderService {
|
|
18
|
-
* private userService = new UserService(); // DIP violation
|
|
19
|
-
* }
|
|
20
|
-
*/
|
|
21
|
-
|
|
22
|
-
import { SyntaxKind, type NewExpression, type SourceFile } from 'ts-morph';
|
|
23
|
-
import type {
|
|
24
|
-
AnalysisRule,
|
|
25
|
-
AnalysisContext,
|
|
26
|
-
AnalysisResult,
|
|
27
|
-
} from '@angular-modernizer/plugin-system';
|
|
28
|
-
|
|
29
|
-
/**
|
|
30
|
-
* DIP Violation Rule - detects direct service instantiation.
|
|
31
|
-
*
|
|
32
|
-
* This rule implements the Dependency Inversion Principle by detecting
|
|
33
|
-
* direct instantiation of services, which should be injected instead.
|
|
34
|
-
*/
|
|
35
|
-
export class DIPViolationRule implements AnalysisRule {
|
|
36
|
-
public readonly id = 'solid:dip-violation-direct-instantiation';
|
|
37
|
-
public readonly name = 'Dependency Inversion Principle Violation';
|
|
38
|
-
public readonly description =
|
|
39
|
-
'Detects direct instantiation of services that should be injected';
|
|
40
|
-
public readonly severity = 'warning';
|
|
41
|
-
public readonly category = 'solid-violation';
|
|
42
|
-
public readonly tags = [
|
|
43
|
-
'solid',
|
|
44
|
-
'dip',
|
|
45
|
-
'dependency-injection',
|
|
46
|
-
'architecture',
|
|
47
|
-
];
|
|
48
|
-
|
|
49
|
-
/**
|
|
50
|
-
* Service class suffixes to detect.
|
|
51
|
-
* Aligned with ServicePatternRecognizer patterns for consistency.
|
|
52
|
-
*/
|
|
53
|
-
private readonly defaultServiceSuffixes = [
|
|
54
|
-
'Service',
|
|
55
|
-
'Repository',
|
|
56
|
-
'Store',
|
|
57
|
-
'Manager',
|
|
58
|
-
'Api',
|
|
59
|
-
'Client',
|
|
60
|
-
'Provider',
|
|
61
|
-
'Facade',
|
|
62
|
-
'Helper',
|
|
63
|
-
'Util',
|
|
64
|
-
'Utils',
|
|
65
|
-
];
|
|
66
|
-
|
|
67
|
-
async analyze(context: AnalysisContext): Promise<AnalysisResult[]> {
|
|
68
|
-
const violations: AnalysisResult[] = [];
|
|
69
|
-
const sourceFile = context.sourceFile;
|
|
70
|
-
|
|
71
|
-
// Find all 'new' expressions in the file
|
|
72
|
-
const newExpressions = sourceFile.getDescendantsOfKind(
|
|
73
|
-
SyntaxKind.NewExpression,
|
|
74
|
-
);
|
|
75
|
-
|
|
76
|
-
for (const newExpr of newExpressions) {
|
|
77
|
-
const violation = this.checkNewExpression(
|
|
78
|
-
newExpr,
|
|
79
|
-
sourceFile.getFilePath(),
|
|
80
|
-
);
|
|
81
|
-
if (violation) {
|
|
82
|
-
violations.push(violation);
|
|
83
|
-
}
|
|
84
|
-
}
|
|
85
|
-
|
|
86
|
-
// Check for service locator pattern (Cat 6)
|
|
87
|
-
violations.push(
|
|
88
|
-
...this.analyzeServiceLocator(sourceFile, sourceFile.getFilePath()),
|
|
89
|
-
);
|
|
90
|
-
|
|
91
|
-
return Promise.resolve(violations);
|
|
92
|
-
}
|
|
93
|
-
|
|
94
|
-
/**
|
|
95
|
-
* Check if a new expression violates DIP.
|
|
96
|
-
*/
|
|
97
|
-
private checkNewExpression(
|
|
98
|
-
newExpr: NewExpression,
|
|
99
|
-
filePath: string,
|
|
100
|
-
): AnalysisResult | null {
|
|
101
|
-
try {
|
|
102
|
-
// Get the type being instantiated
|
|
103
|
-
const expression = newExpr.getExpression();
|
|
104
|
-
const typeName = expression.getText();
|
|
105
|
-
|
|
106
|
-
// Check if it's a service class (ends with service suffixes)
|
|
107
|
-
if (this.isServiceClass(typeName)) {
|
|
108
|
-
const startLine = newExpr.getStartLineNumber();
|
|
109
|
-
const startColumn = newExpr.getStart() - newExpr.getStartLinePos();
|
|
110
|
-
|
|
111
|
-
return {
|
|
112
|
-
ruleId: this.id,
|
|
113
|
-
message: `Direct instantiation of ${typeName} violates Dependency Inversion Principle. Use dependency injection instead.`,
|
|
114
|
-
filePath,
|
|
115
|
-
line: startLine,
|
|
116
|
-
column: startColumn,
|
|
117
|
-
suggestedFix: `Replace 'new ${typeName}()' with 'inject(${typeName})' or constructor injection`,
|
|
118
|
-
metadata: {
|
|
119
|
-
instantiatedType: typeName,
|
|
120
|
-
violationType: 'direct-instantiation',
|
|
121
|
-
principle: 'DIP',
|
|
122
|
-
},
|
|
123
|
-
};
|
|
124
|
-
}
|
|
125
|
-
|
|
126
|
-
return null;
|
|
127
|
-
} catch (_error) {
|
|
128
|
-
// If we can't analyze the expression, skip it
|
|
129
|
-
return null;
|
|
130
|
-
}
|
|
131
|
-
}
|
|
132
|
-
|
|
133
|
-
/**
|
|
134
|
-
* Detect service locator pattern: `injector.get(SomeService)` bypasses Angular DI.
|
|
135
|
-
*/
|
|
136
|
-
private analyzeServiceLocator(
|
|
137
|
-
sourceFile: SourceFile,
|
|
138
|
-
filePath: string,
|
|
139
|
-
): AnalysisResult[] {
|
|
140
|
-
const violations: AnalysisResult[] = [];
|
|
141
|
-
|
|
142
|
-
const callExpressions = sourceFile.getDescendantsOfKind(
|
|
143
|
-
SyntaxKind.CallExpression,
|
|
144
|
-
);
|
|
145
|
-
|
|
146
|
-
for (const call of callExpressions) {
|
|
147
|
-
const expression = call.getExpression();
|
|
148
|
-
if (!expression.isKind(SyntaxKind.PropertyAccessExpression)) {
|
|
149
|
-
continue;
|
|
150
|
-
}
|
|
151
|
-
|
|
152
|
-
const propAccess = expression;
|
|
153
|
-
// Must be a .get() call
|
|
154
|
-
if (propAccess.getName() !== 'get') {
|
|
155
|
-
continue;
|
|
156
|
-
}
|
|
157
|
-
|
|
158
|
-
// Receiver must match /injector/i
|
|
159
|
-
const receiver = propAccess.getExpression().getText();
|
|
160
|
-
if (!/injector/i.test(receiver)) {
|
|
161
|
-
continue;
|
|
162
|
-
}
|
|
163
|
-
|
|
164
|
-
violations.push({
|
|
165
|
-
ruleId: this.id,
|
|
166
|
-
message: `Service locator pattern: ${receiver}.get() bypasses Angular DI and makes testing difficult. Inject dependencies directly.`,
|
|
167
|
-
filePath,
|
|
168
|
-
line: call.getStartLineNumber(),
|
|
169
|
-
column: call.getStart() - call.getStartLinePos(),
|
|
170
|
-
suggestedFix: `Replace '${receiver}.get(SomeService)' with 'inject(SomeService)' or add the dependency to the constructor.`,
|
|
171
|
-
metadata: {
|
|
172
|
-
violationType: 'service-locator-pattern',
|
|
173
|
-
principle: 'DIP',
|
|
174
|
-
receiver,
|
|
175
|
-
},
|
|
176
|
-
});
|
|
177
|
-
}
|
|
178
|
-
|
|
179
|
-
return violations;
|
|
180
|
-
}
|
|
181
|
-
|
|
182
|
-
/**
|
|
183
|
-
* Check if a class name represents a service that should be injected.
|
|
184
|
-
*/
|
|
185
|
-
private isServiceClass(className: string): boolean {
|
|
186
|
-
// Remove any generic type parameters
|
|
187
|
-
const baseName = className.split('<')[0];
|
|
188
|
-
|
|
189
|
-
// Check against default service suffixes
|
|
190
|
-
return this.defaultServiceSuffixes.some(
|
|
191
|
-
(suffix) => baseName?.endsWith(suffix) ?? false,
|
|
192
|
-
);
|
|
193
|
-
}
|
|
194
|
-
}
|