@angular-modernizer/plugin-system 0.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.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Christian Weiss<CWOIDA>
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,551 @@
1
+ # @angular-modernizer/plugin-system
2
+
3
+ Plugin contracts and context-based dependency injection for the Angular Modernization Platform.
4
+
5
+ ## Overview
6
+
7
+ The `@angular-modernizer/plugin-system` package defines the interfaces and context types that enable the API-driven plugin architecture. It provides the context objects and dependency injection patterns that keep plugins stateless and composable.
8
+
9
+ This package has no runtime dependencies — it contains pure TypeScript interfaces only.
10
+
11
+ ## Architecture
12
+
13
+ The plugin system uses a context-driven pattern where all dependencies are passed through context objects rather than constructor injection:
14
+
15
+ ```typescript
16
+ // Constructor injection — tight coupling, avoid this
17
+ class OldStylePlugin {
18
+ constructor(
19
+ private api: PublicApi,
20
+ private project: Project,
21
+ ) {}
22
+ analyze() {
23
+ /* uses this.api, this.project */
24
+ }
25
+ }
26
+
27
+ // Context injection — loose coupling, use this
28
+ class CorrectPlugin {
29
+ constructor() {} // Stateless
30
+
31
+ analyze(context: AnalysisContext) {
32
+ const { api, project, sourceFile } = context;
33
+ }
34
+ }
35
+ ```
36
+
37
+ ## Core Interfaces
38
+
39
+ ### Plugin Interface
40
+
41
+ The contract all plugins must implement:
42
+
43
+ ```typescript
44
+ interface Plugin {
45
+ readonly name: string;
46
+ readonly version: string;
47
+ readonly description?: string;
48
+ readonly author?: string;
49
+
50
+ initialize(kernel: IKernel): Promise<void>;
51
+ getAnalysisRules(): AnalysisRule[];
52
+ getTransformRules(): TransformRule[];
53
+ getValidationRules(): ValidationRule[];
54
+ }
55
+ ```
56
+
57
+ `IKernel` is intentionally minimal — it only exposes `getProjectRoot()`. Plugins that need project-level access must defer that work until `analyze()` or `transform()` is called, where they receive the full context.
58
+
59
+ ### Rule Interfaces
60
+
61
+ #### AnalysisRule
62
+
63
+ Analyzes codebases and generates violation reports.
64
+
65
+ ```typescript
66
+ interface AnalysisRule {
67
+ readonly id: string;
68
+ readonly name: string;
69
+ readonly description: string;
70
+
71
+ analyze(context: AnalysisContext): Promise<AnalysisResult>;
72
+ }
73
+
74
+ interface AnalysisResult {
75
+ ruleId: string;
76
+ violations: Violation[];
77
+ metadata?: Record<string, unknown>;
78
+ suggestions?: Suggestion[];
79
+ }
80
+
81
+ interface Violation {
82
+ id: string;
83
+ severity: 'low' | 'medium' | 'high' | 'critical';
84
+ message: string;
85
+ location: SourceLocation;
86
+ category: string;
87
+ ruleId: string;
88
+ autoFix?: AutoFix;
89
+ }
90
+
91
+ interface SourceLocation {
92
+ filePath: string;
93
+ startLine: number;
94
+ startColumn: number;
95
+ endLine?: number;
96
+ endColumn?: number;
97
+ }
98
+ ```
99
+
100
+ #### TransformRule
101
+
102
+ Modifies code automatically. Implementations must be idempotent, atomic, and reversible.
103
+
104
+ ```typescript
105
+ interface TransformRule {
106
+ readonly id: string;
107
+ readonly name: string;
108
+ readonly description: string;
109
+
110
+ canTransform(context: TransformContext): Promise<boolean>;
111
+ transform(context: TransformContext): Promise<TransformResult>;
112
+ }
113
+
114
+ interface TransformResult {
115
+ ruleId: string;
116
+ modified: boolean;
117
+ message?: string;
118
+ changes?: Change[];
119
+ warnings?: string[];
120
+ errors?: string[];
121
+ }
122
+
123
+ interface Change {
124
+ type: 'add' | 'remove' | 'modify';
125
+ description: string;
126
+ location: SourceLocation;
127
+ before?: string;
128
+ after?: string;
129
+ }
130
+ ```
131
+
132
+ #### ValidationRule
133
+
134
+ Validates transformations and code quality.
135
+
136
+ ```typescript
137
+ interface ValidationRule {
138
+ readonly id: string;
139
+ readonly name: string;
140
+ readonly description: string;
141
+
142
+ validate(context: ValidationContext): Promise<ValidationResult>;
143
+ }
144
+
145
+ interface ValidationResult {
146
+ ruleId: string;
147
+ valid: boolean;
148
+ errors: ValidationError[];
149
+ warnings: ValidationWarning[];
150
+ metrics?: Record<string, number>;
151
+ }
152
+ ```
153
+
154
+ ## Context Objects
155
+
156
+ Context objects provide scoped access to dependencies. Always construct them via `ContextFactory` — never by hand.
157
+
158
+ ### AnalysisContext
159
+
160
+ Read-only access for analysis operations.
161
+
162
+ ```typescript
163
+ interface AnalysisContext {
164
+ readonly sourceFile: SourceFile;
165
+ readonly project: Project;
166
+ readonly api: PublicApi;
167
+ readonly config: Record<string, unknown>;
168
+ readonly filePath: string;
169
+ readonly ruleConfig?: Record<string, unknown>;
170
+ }
171
+ ```
172
+
173
+ ### TransformContext
174
+
175
+ Read-write access for transformation operations. Same structure as `AnalysisContext` but implies write permissions. Also includes a `dryRun` flag.
176
+
177
+ ```typescript
178
+ interface TransformContext {
179
+ readonly sourceFile: SourceFile;
180
+ readonly project: Project;
181
+ readonly api: PublicApi;
182
+ readonly config: Record<string, unknown>;
183
+ readonly filePath: string;
184
+ readonly dryRun?: boolean;
185
+ readonly ruleConfig?: Record<string, unknown>;
186
+ }
187
+ ```
188
+
189
+ ### ValidationContext
190
+
191
+ Access for validation operations after transformation.
192
+
193
+ ```typescript
194
+ interface ValidationContext {
195
+ readonly sourceFile: SourceFile;
196
+ readonly project: Project;
197
+ readonly api: PublicApi;
198
+ readonly config: Record<string, unknown>;
199
+ readonly previousResult?: TransformResult;
200
+ }
201
+ ```
202
+
203
+ ## Context Factory
204
+
205
+ The `ContextFactory` creates properly typed context objects. Always use it — never construct context objects directly.
206
+
207
+ ```typescript
208
+ class ContextFactory {
209
+ static createAnalysisContext(params: AnalysisContextParams): AnalysisContext;
210
+ static createTransformContext(params: TransformContextParams): TransformContext;
211
+ static createValidationContext(params: ValidationContextParams): ValidationContext;
212
+ }
213
+
214
+ interface AnalysisContextParams {
215
+ sourceFile: SourceFile;
216
+ project: Project;
217
+ api: PublicApi;
218
+ config?: Record<string, unknown>;
219
+ ruleConfig?: Record<string, unknown>;
220
+ }
221
+ ```
222
+
223
+ `AnalysisContext` requires all five fields (`sourceFile`, `project`, `api`, `config`, `filePath`). Tests that pass only `{ sourceFile }` may compile under ts-jest's lenient inline tsconfig but will fail in `pnpm run type-check`.
224
+
225
+ ## Usage Examples
226
+
227
+ ### Creating a Basic Plugin
228
+
229
+ ```typescript
230
+ import {
231
+ type Plugin,
232
+ type AnalysisRule,
233
+ type TransformRule,
234
+ } from '@angular-modernizer/plugin-system';
235
+
236
+ class MyPlugin implements Plugin {
237
+ readonly name = '@my-org/plugin-custom';
238
+ readonly version = '1.0.0';
239
+ readonly description = 'Custom analysis and transformation rules';
240
+
241
+ async initialize(kernel: IKernel): Promise<void> {
242
+ // Optional initialization
243
+ }
244
+
245
+ getAnalysisRules(): AnalysisRule[] {
246
+ return [new MyAnalysisRule()];
247
+ }
248
+
249
+ getTransformRules(): TransformRule[] {
250
+ return [new MyTransformRule()];
251
+ }
252
+
253
+ getValidationRules(): ValidationRule[] {
254
+ return [];
255
+ }
256
+ }
257
+ ```
258
+
259
+ ### Implementing an Analysis Rule
260
+
261
+ ```typescript
262
+ import {
263
+ type AnalysisRule,
264
+ type AnalysisContext,
265
+ } from '@angular-modernizer/plugin-system';
266
+
267
+ class DirectInstantiationRule implements AnalysisRule {
268
+ readonly id = 'direct-instantiation';
269
+ readonly name = 'Direct Service Instantiation';
270
+ readonly description = 'Detects direct instantiation of services (DIP violation)';
271
+
272
+ async analyze(context: AnalysisContext): Promise<AnalysisResult> {
273
+ const { sourceFile, api } = context;
274
+ const violations: Violation[] = [];
275
+
276
+ sourceFile.forEachDescendant((node) => {
277
+ if (ts.isNewExpression(node)) {
278
+ const className = node.expression.getText();
279
+
280
+ if (this.isServiceClass(className)) {
281
+ violations.push({
282
+ id: `direct-instantiation-${violations.length}`,
283
+ severity: 'high',
284
+ message: `Direct instantiation of ${className} violates Dependency Inversion Principle`,
285
+ location: this.getLocation(node),
286
+ category: 'solid-violation',
287
+ ruleId: this.id,
288
+ });
289
+ }
290
+ }
291
+ });
292
+
293
+ return {
294
+ ruleId: this.id,
295
+ violations,
296
+ metadata: {
297
+ totalViolations: violations.length,
298
+ analyzedLines: sourceFile.getLineCount(),
299
+ },
300
+ };
301
+ }
302
+
303
+ private isServiceClass(className: string): boolean {
304
+ return className.endsWith('Service') || className.endsWith('Repository');
305
+ }
306
+ }
307
+ ```
308
+
309
+ ### Implementing a Transform Rule
310
+
311
+ ```typescript
312
+ import {
313
+ type TransformRule,
314
+ type TransformContext,
315
+ } from '@angular-modernizer/plugin-system';
316
+
317
+ class ConstructorToInjectRule implements TransformRule {
318
+ readonly id = 'constructor-to-inject';
319
+ readonly name = 'Constructor to inject() Migration';
320
+ readonly description = 'Convert Angular constructor injection to inject() function';
321
+
322
+ async canTransform(context: TransformContext): Promise<boolean> {
323
+ const text = context.sourceFile.getText();
324
+ return text.includes('constructor(') && text.includes('standalone: true');
325
+ }
326
+
327
+ async transform(context: TransformContext): Promise<TransformResult> {
328
+ const { sourceFile, api } = context;
329
+
330
+ try {
331
+ const constructorMatch = this.findConstructor(sourceFile);
332
+ if (!constructorMatch) {
333
+ return { ruleId: this.id, modified: false, message: 'No constructor found' };
334
+ }
335
+
336
+ const injectStatements = this.generateInjectStatements(constructorMatch);
337
+ this.replaceConstructor(sourceFile, constructorMatch, injectStatements);
338
+
339
+ api.transformation.importManager.addImport(sourceFile, 'inject', '@angular/core');
340
+
341
+ return {
342
+ ruleId: this.id,
343
+ modified: true,
344
+ message: 'Successfully converted constructor to inject()',
345
+ changes: [
346
+ {
347
+ type: 'modify',
348
+ description: 'Replaced constructor with inject() statements',
349
+ location: this.getLocation(constructorMatch.node),
350
+ },
351
+ ],
352
+ };
353
+ } catch (error) {
354
+ return {
355
+ ruleId: this.id,
356
+ modified: false,
357
+ errors: [`Transformation failed: ${String(error)}`],
358
+ };
359
+ }
360
+ }
361
+ }
362
+ ```
363
+
364
+ ### Using Context Factory
365
+
366
+ ```typescript
367
+ import { ContextFactory } from '@angular-modernizer/plugin-system';
368
+ import { createPublicApi } from '@angular-modernizer/api';
369
+
370
+ const analysisContext = ContextFactory.createAnalysisContext({
371
+ sourceFile,
372
+ project,
373
+ api: createPublicApi(),
374
+ config: {
375
+ includeAutoFixes: true,
376
+ },
377
+ ruleConfig: {
378
+ serviceSuffixes: ['Service', 'Repository', 'Store'],
379
+ },
380
+ });
381
+
382
+ const transformContext = ContextFactory.createTransformContext({
383
+ sourceFile,
384
+ project,
385
+ api: createPublicApi(),
386
+ config: {
387
+ preserveExistingImports: false,
388
+ },
389
+ });
390
+ ```
391
+
392
+ ## Design Principles
393
+
394
+ ### Context-Driven Dependency Injection
395
+
396
+ All dependencies are injected via context objects:
397
+
398
+ ```typescript
399
+ // Correct: context injection
400
+ class MyRule implements AnalysisRule {
401
+ analyze(context: AnalysisContext) {
402
+ const { api, project, sourceFile } = context;
403
+ }
404
+ }
405
+
406
+ // Wrong: constructor injection
407
+ class MyRule implements AnalysisRule {
408
+ constructor(private api: PublicApi) {}
409
+ analyze(context: AnalysisContext) { /* uses this.api */ }
410
+ }
411
+ ```
412
+
413
+ ### Stateless Rules
414
+
415
+ Rules must not hold internal state between invocations:
416
+
417
+ ```typescript
418
+ // Correct: stateless
419
+ class MyRule implements AnalysisRule {
420
+ analyze(context: AnalysisContext): Promise<AnalysisResult> {
421
+ // Same context always produces same result
422
+ }
423
+ }
424
+
425
+ // Wrong: stateful
426
+ class MyRule implements AnalysisRule {
427
+ private analyzedFiles = new Set<string>(); // Do not do this
428
+ }
429
+ ```
430
+
431
+ ### Immutable Contexts
432
+
433
+ Context objects must not be mutated:
434
+
435
+ ```typescript
436
+ // Correct
437
+ function analyze(context: AnalysisContext) {
438
+ const { sourceFile, api } = context;
439
+ }
440
+
441
+ // Wrong
442
+ function analyze(context: AnalysisContext) {
443
+ context.config.additionalSetting = true; // Do not do this
444
+ }
445
+ ```
446
+
447
+ ### Rule ID Format
448
+
449
+ Rule IDs must follow `plugin-name:rule-name` format (e.g., `angular:component-wrapper-instantiation`, `solid:srp-single-responsibility-violation`). The prefix must match the plugin's registered name.
450
+
451
+ ### context.api is the Only Allowed AST Access Path
452
+
453
+ Plugins must not manipulate the ts-morph AST directly. All analysis and transformation must go through `context.api`. Direct `sourceFile.getClasses()` calls bypass the API's caching and abstraction layers.
454
+
455
+ ## Package Structure
456
+
457
+ ```
458
+ packages/plugin-system/
459
+ src/
460
+ interfaces/
461
+ plugin.ts
462
+ rules.ts
463
+ contexts.ts
464
+ context-factory.ts
465
+ index.ts
466
+ types.ts
467
+ __tests__/
468
+ interfaces/
469
+ plugin.test.ts
470
+ rules.test.ts
471
+ contexts.test.ts
472
+ context-factory.test.ts
473
+ integration.test.ts
474
+ package.json
475
+ tsconfig.json
476
+ jest.config.js
477
+ README.md
478
+ ```
479
+
480
+ ## Testing
481
+
482
+ The plugin-system package provides testing utilities:
483
+
484
+ ```typescript
485
+ import {
486
+ createMockAnalysisContext,
487
+ createMockTransformContext,
488
+ } from '@angular-modernizer/plugin-system';
489
+
490
+ describe('MyAnalysisRule', () => {
491
+ let rule: MyAnalysisRule;
492
+ let context: AnalysisContext;
493
+
494
+ beforeEach(() => {
495
+ rule = new MyAnalysisRule();
496
+ context = createMockAnalysisContext({
497
+ sourceFile: mockSourceFile,
498
+ config: { customSetting: true },
499
+ });
500
+ });
501
+
502
+ it('should detect violations', async () => {
503
+ const result = await rule.analyze(context);
504
+ expect(result.violations).toHaveLength(1);
505
+ });
506
+ });
507
+ ```
508
+
509
+ ## Best Practices
510
+
511
+ ### Rule Development
512
+
513
+ 1. Keep rules focused — one rule, one responsibility
514
+ 2. Use descriptive IDs — `dip-violation-direct-instantiation` not `rule1`
515
+ 3. Provide auto-fixes when possible
516
+ 4. Handle errors gracefully — do not throw on malformed code
517
+ 5. Write comprehensive tests covering edge cases
518
+
519
+ ### Plugin Development
520
+
521
+ 1. Group related rules — one plugin per domain (SOLID, standalone, etc.)
522
+ 2. Use semantic versioning for API compatibility
523
+ 3. Initialize efficiently — defer I/O until `analyze()` or `transform()`
524
+
525
+ ### Context Usage
526
+
527
+ 1. Destructure contexts: `const { api, sourceFile } = context;`
528
+ 2. Use `ruleConfig` for rule-specific settings
529
+ 3. Validate required context properties
530
+ 4. Return meaningful results including metadata and suggestions
531
+
532
+ ## Contributing
533
+
534
+ 1. Maintain backward compatibility — do not break existing interfaces
535
+ 2. Add comprehensive types — strong typing for all interfaces
536
+ 3. Write integration tests — test rule composition and context usage
537
+ 4. Document with examples — show real usage patterns
538
+ 5. Consider extensibility — design for future enhancements
539
+
540
+ ### Adding New Rule Types
541
+
542
+ 1. Define the interface following existing patterns
543
+ 2. Add to `Plugin` interface: `getNewRuleType(): NewRuleType[]`
544
+ 3. Create context type: `NewRuleContext`
545
+ 4. Add factory method: `ContextFactory.createNewRuleContext()`
546
+ 5. Update documentation with examples
547
+
548
+ ## See Also
549
+
550
+ - [packages/api/README.md](../api/README.md) - Public API tools
551
+ - [packages/core/README.md](../core/README.md) - Kernel infrastructure