@angular-modernizer/plugin-solid 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.
Files changed (68) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +835 -0
  3. package/dist/index.d.ts +21 -0
  4. package/dist/index.d.ts.map +1 -0
  5. package/dist/index.js +37 -0
  6. package/dist/index.js.map +1 -0
  7. package/dist/orchestrators/god-switch-transform-orchestrator.d.ts +350 -0
  8. package/dist/orchestrators/god-switch-transform-orchestrator.d.ts.map +1 -0
  9. package/dist/orchestrators/god-switch-transform-orchestrator.js +1165 -0
  10. package/dist/orchestrators/god-switch-transform-orchestrator.js.map +1 -0
  11. package/dist/orchestrators/service-dip-violation-transform.orchestrator.d.ts +72 -0
  12. package/dist/orchestrators/service-dip-violation-transform.orchestrator.d.ts.map +1 -0
  13. package/dist/orchestrators/service-dip-violation-transform.orchestrator.js +243 -0
  14. package/dist/orchestrators/service-dip-violation-transform.orchestrator.js.map +1 -0
  15. package/dist/rules/dip-violation.rule.d.ts +54 -0
  16. package/dist/rules/dip-violation.rule.d.ts.map +1 -0
  17. package/dist/rules/dip-violation.rule.js +156 -0
  18. package/dist/rules/dip-violation.rule.js.map +1 -0
  19. package/dist/rules/god-switch-analysis.rule.d.ts +73 -0
  20. package/dist/rules/god-switch-analysis.rule.d.ts.map +1 -0
  21. package/dist/rules/god-switch-analysis.rule.js +174 -0
  22. package/dist/rules/god-switch-analysis.rule.js.map +1 -0
  23. package/dist/rules/isp-violation.rule.d.ts +62 -0
  24. package/dist/rules/isp-violation.rule.d.ts.map +1 -0
  25. package/dist/rules/isp-violation.rule.js +250 -0
  26. package/dist/rules/isp-violation.rule.js.map +1 -0
  27. package/dist/rules/lsp-violation.rule.d.ts +57 -0
  28. package/dist/rules/lsp-violation.rule.d.ts.map +1 -0
  29. package/dist/rules/lsp-violation.rule.js +321 -0
  30. package/dist/rules/lsp-violation.rule.js.map +1 -0
  31. package/dist/rules/ocp-violation.rule.d.ts +69 -0
  32. package/dist/rules/ocp-violation.rule.d.ts.map +1 -0
  33. package/dist/rules/ocp-violation.rule.js +204 -0
  34. package/dist/rules/ocp-violation.rule.js.map +1 -0
  35. package/dist/rules/service-dip-violation.analysis.rule.d.ts +85 -0
  36. package/dist/rules/service-dip-violation.analysis.rule.d.ts.map +1 -0
  37. package/dist/rules/service-dip-violation.analysis.rule.js +217 -0
  38. package/dist/rules/service-dip-violation.analysis.rule.js.map +1 -0
  39. package/dist/rules/srp-violation.rule.d.ts +71 -0
  40. package/dist/rules/srp-violation.rule.d.ts.map +1 -0
  41. package/dist/rules/srp-violation.rule.js +307 -0
  42. package/dist/rules/srp-violation.rule.js.map +1 -0
  43. package/dist/solid-plugin.d.ts +82 -0
  44. package/dist/solid-plugin.d.ts.map +1 -0
  45. package/dist/solid-plugin.js +115 -0
  46. package/dist/solid-plugin.js.map +1 -0
  47. package/dist/transform-rules/god-switch-transform.rule.d.ts +128 -0
  48. package/dist/transform-rules/god-switch-transform.rule.d.ts.map +1 -0
  49. package/dist/transform-rules/god-switch-transform.rule.js +167 -0
  50. package/dist/transform-rules/god-switch-transform.rule.js.map +1 -0
  51. package/dist/transform-rules/service-dip-violation.transform.rule.d.ts +75 -0
  52. package/dist/transform-rules/service-dip-violation.transform.rule.d.ts.map +1 -0
  53. package/dist/transform-rules/service-dip-violation.transform.rule.js +115 -0
  54. package/dist/transform-rules/service-dip-violation.transform.rule.js.map +1 -0
  55. package/package.json +59 -0
  56. package/src/index.ts +30 -0
  57. package/src/orchestrators/god-switch-transform-orchestrator.ts +1562 -0
  58. package/src/orchestrators/service-dip-violation-transform.orchestrator.ts +331 -0
  59. package/src/rules/dip-violation.rule.ts +194 -0
  60. package/src/rules/god-switch-analysis.rule.ts +209 -0
  61. package/src/rules/isp-violation.rule.ts +315 -0
  62. package/src/rules/lsp-violation.rule.ts +393 -0
  63. package/src/rules/ocp-violation.rule.ts +264 -0
  64. package/src/rules/service-dip-violation.analysis.rule.ts +285 -0
  65. package/src/rules/srp-violation.rule.ts +366 -0
  66. package/src/solid-plugin.ts +127 -0
  67. package/src/transform-rules/god-switch-transform.rule.ts +189 -0
  68. package/src/transform-rules/service-dip-violation.transform.rule.ts +134 -0
@@ -0,0 +1,1562 @@
1
+ /**
2
+ * @angular-modernizer/plugin-solid - God Switch Transform Orchestrator
3
+ *
4
+ * The central "brain" of the God Switch transformation plugin.
5
+ * Transforms large switch statements into maintainable Factory Pattern implementations.
6
+ *
7
+ * Philosophy: "API-Driven Orchestration"
8
+ * - Receives all capabilities via TransformContext
9
+ * - Uses ts-morph for all AST operations
10
+ * - Stateless - no constructor dependencies
11
+ * - Pure business logic, no low-level manipulation
12
+ */
13
+
14
+ import type { TransformContext } from '@angular-modernizer/plugin-system';
15
+ import type { PublicApi } from '@angular-modernizer/api';
16
+ import type {
17
+ SourceFile,
18
+ SwitchStatement,
19
+ CaseClause,
20
+ DefaultClause,
21
+ Node,
22
+ Statement,
23
+ ReturnStatement,
24
+ BinaryExpression,
25
+ PrefixUnaryExpression,
26
+ PostfixUnaryExpression,
27
+ } from 'ts-morph';
28
+ import { SyntaxKind } from 'ts-morph';
29
+
30
+ /**
31
+ * Configuration options for God Switch transformation.
32
+ */
33
+ export interface GodSwitchTransformConfig {
34
+ /**
35
+ * Whether to generate strategy interfaces.
36
+ * Default: true
37
+ */
38
+ generateInterfaces?: boolean;
39
+
40
+ /**
41
+ * Whether to generate factory classes.
42
+ * Default: true
43
+ */
44
+ generateFactory?: boolean;
45
+
46
+ /**
47
+ * Naming pattern for strategy classes.
48
+ * Template variables: {CaseValue}, {SwitchExpression}
49
+ * Default: '{CaseValue}Strategy'
50
+ */
51
+ strategyNamingPattern?: string;
52
+
53
+ /**
54
+ * Naming pattern for factory classes.
55
+ * Template variables: {SwitchExpression}
56
+ * Default: '{SwitchExpression}Factory'
57
+ */
58
+ factoryNamingPattern?: string;
59
+
60
+ /**
61
+ * Minimum case count to trigger transformation.
62
+ * Should match the analysis rule threshold.
63
+ * Default: 10
64
+ */
65
+ minCaseCount?: number;
66
+ }
67
+
68
+ /**
69
+ * Metadata extracted from a switch statement.
70
+ */
71
+ interface SwitchMetadata {
72
+ expression: string;
73
+ expressionType: string;
74
+ returnType: string;
75
+ parameters: ParameterInfo[];
76
+ cases: CaseMetadata[];
77
+ hasDefault: boolean;
78
+ defaultClause?: DefaultClause;
79
+ }
80
+
81
+ /**
82
+ * Metadata for a single case clause.
83
+ */
84
+ interface CaseMetadata {
85
+ caseValue: string;
86
+ sanitizedValue: string;
87
+ statements: Statement[];
88
+ capturedVariables: string[];
89
+ mutatedVariables: string[];
90
+ hasReturn: boolean;
91
+ hasBreak: boolean;
92
+ isFallthrough: boolean;
93
+ returnType: string; // Return type for this specific case
94
+ }
95
+
96
+ /**
97
+ * Parameter information for strategy execute method.
98
+ */
99
+ interface ParameterInfo {
100
+ name: string;
101
+ type: string;
102
+ isMutable?: boolean;
103
+ }
104
+
105
+ /**
106
+ * God Switch Transform Orchestrator
107
+ *
108
+ * @remarks
109
+ * The central orchestrator for transforming God Switch patterns into Factory Pattern.
110
+ * This class analyzes large switch statements and refactors them into maintainable
111
+ * strategy-based implementations using the Factory Pattern.
112
+ *
113
+ * ## Architecture Pattern
114
+ *
115
+ * This orchestrator follows three core principles:
116
+ * 1. **Stateless Design** - No constructor dependencies
117
+ * 2. **Context-Driven** - All capabilities injected via {@link TransformContext}
118
+ * 3. **API-First** - Uses ts-morph for all AST operations
119
+ *
120
+ * ## Transformation Workflow
121
+ *
122
+ * The orchestrator performs the following transformations:
123
+ * 1. Find all God Switch violations in the source file
124
+ * 2. Extract switch metadata (expression, cases, return type)
125
+ * 3. Generate strategy interface with execute() method
126
+ * 4. Generate strategy classes (one per case)
127
+ * 5. Generate factory class with strategy instantiation
128
+ * 6. Replace switch statement with factory call
129
+ * 7. Update imports as needed
130
+ *
131
+ * ## Example Usage
132
+ *
133
+ * ```typescript
134
+ * const orchestrator = new GodSwitchTransformOrchestrator();
135
+ * const context = ContextFactory.createTransformContext({
136
+ * sourceFile,
137
+ * project,
138
+ * api,
139
+ * config: { minCaseCount: 10 }
140
+ * });
141
+ * orchestrator.run(context);
142
+ * ```
143
+ *
144
+ * @see {@link TransformContext} for context structure
145
+ * @see {@link GodSwitchTransformConfig} for configuration options
146
+ *
147
+ * @public
148
+ */
149
+ export class GodSwitchTransformOrchestrator {
150
+ /**
151
+ * Creates a new GodSwitchTransformOrchestrator instance.
152
+ *
153
+ * @remarks
154
+ * The constructor is intentionally stateless. All dependencies are provided
155
+ * through the {@link TransformContext} passed to the {@link run} method.
156
+ * This enables testing, composition, and prevents tight coupling.
157
+ *
158
+ * @public
159
+ */
160
+ constructor() {
161
+ // Intentionally empty - follows the new architecture pattern
162
+ }
163
+
164
+ /**
165
+ * Executes the God Switch transformation on a single source file.
166
+ *
167
+ * @remarks
168
+ * This method is the main entry point for the orchestrator. It receives all
169
+ * necessary dependencies (project, API, config) through the context parameter,
170
+ * analyzes switch statements, and transforms them into Factory Pattern.
171
+ *
172
+ * The method operates on one source file at a time and is safe to call
173
+ * multiple times. It will:
174
+ * - Find all God Switch violations (switches exceeding case threshold)
175
+ * - Extract metadata from each switch statement
176
+ * - Generate strategy interface, classes, and factory
177
+ * - Replace switch with factory call
178
+ * - Update imports
179
+ *
180
+ * ## Transformation Behavior
181
+ *
182
+ * **Switch Analysis**:
183
+ * - Identifies switch statements exceeding configured case threshold
184
+ * - Extracts case labels, logic, and return values
185
+ * - Analyzes captured variables from outer scope
186
+ *
187
+ * **Code Generation**:
188
+ * - Creates IStrategy interface with execute() method signature
189
+ * - Generates one strategy class per case implementing IStrategy
190
+ * - Creates factory class with strategy instantiation mapping
191
+ *
192
+ * **Code Replacement**:
193
+ * - Replaces switch statement with factory instantiation and execute call
194
+ * - Preserves original switch in comment for reference
195
+ * - Updates imports for new classes
196
+ *
197
+ * ## Safety Guarantees
198
+ *
199
+ * **Idempotency**: Checks if factory/strategies already exist before generating
200
+ * **Atomicity**: Uses try-catch with rollback on error
201
+ * **Reversibility**: Preserves original switch in comments with transformation metadata
202
+ *
203
+ * @param context - The transformation context containing:
204
+ * - `sourceFile`: The TypeScript source file to analyze
205
+ * - `project`: The ts-morph Project for cross-file operations
206
+ * - `api`: The PublicApi with analysis and transformation tools
207
+ * - `config`: User-provided configuration options
208
+ *
209
+ * @example
210
+ * ```typescript
211
+ * // Basic usage
212
+ * orchestrator.run(context);
213
+ *
214
+ * // With custom configuration
215
+ * const context = ContextFactory.createTransformContext({
216
+ * sourceFile,
217
+ * project,
218
+ * api,
219
+ * config: {
220
+ * '@angular-modernizer/plugin-solid': {
221
+ * godSwitch: {
222
+ * minCaseCount: 15,
223
+ * generateInterfaces: true,
224
+ * strategyNamingPattern: '{CaseValue}Handler'
225
+ * }
226
+ * }
227
+ * }
228
+ * });
229
+ * orchestrator.run(context);
230
+ * ```
231
+ *
232
+ * @see {@link TransformContext} for context structure
233
+ * @see {@link GodSwitchTransformConfig} for configuration options
234
+ *
235
+ * @public
236
+ */
237
+ run(context: TransformContext<PublicApi>): void {
238
+ const { sourceFile, config } = context;
239
+
240
+ // Get plugin-specific configuration
241
+ const pluginConfig = config['@angular-modernizer/plugin-solid'] as
242
+ | Record<string, unknown>
243
+ | undefined;
244
+ const godSwitchConfig = this.getGodSwitchConfig(pluginConfig ?? {});
245
+
246
+ // Capture original source for rollback
247
+ const originalText = sourceFile.getFullText();
248
+
249
+ try {
250
+ // Find all God Switch violations
251
+ const godSwitches = this.findGodSwitches(
252
+ sourceFile,
253
+ godSwitchConfig.minCaseCount,
254
+ );
255
+
256
+ if (godSwitches.length === 0) {
257
+ // No violations to transform
258
+ return;
259
+ }
260
+
261
+ // Extract all metadata BEFORE any AST modifications
262
+ // This prevents node invalidation issues when transforming multiple switches
263
+ interface SwitchTransformData {
264
+ originalSwitchText: string;
265
+ isInReturnStatement: boolean;
266
+ metadata: SwitchMetadata;
267
+ interfaceCode: string | null;
268
+ strategyClasses: string[];
269
+ factoryClass: string | null;
270
+ replacementText: string;
271
+ }
272
+
273
+ const transformDataList: SwitchTransformData[] = [];
274
+
275
+ for (const switchStmt of godSwitches) {
276
+ // Check idempotency - skip if already transformed
277
+ if (this.isAlreadyTransformed(switchStmt)) {
278
+ continue;
279
+ }
280
+
281
+ // Capture original switch text and context
282
+ const originalSwitchText = switchStmt.getText();
283
+ const parentNode = switchStmt.getParent();
284
+ const isInReturnStatement =
285
+ parentNode.getKind() === SyntaxKind.ReturnStatement;
286
+
287
+ // Extract switch metadata
288
+ const metadata = this.extractSwitchMetadata(switchStmt);
289
+
290
+ // Generate code
291
+ const interfaceCode = godSwitchConfig.generateInterfaces
292
+ ? this.generateStrategyInterface(
293
+ switchStmt,
294
+ metadata,
295
+ godSwitchConfig,
296
+ )
297
+ : null;
298
+
299
+ const { classes: strategyClasses, caseToStrategyMap } =
300
+ this.generateStrategyClasses(
301
+ metadata.cases,
302
+ metadata,
303
+ godSwitchConfig,
304
+ );
305
+
306
+ const factoryClass = godSwitchConfig.generateFactory
307
+ ? this.generateFactoryClass(
308
+ metadata,
309
+ godSwitchConfig,
310
+ caseToStrategyMap,
311
+ )
312
+ : null;
313
+
314
+ // Generate replacement text
315
+ const replacementText = this.generateReplacementText(
316
+ metadata,
317
+ godSwitchConfig,
318
+ originalSwitchText,
319
+ isInReturnStatement,
320
+ );
321
+
322
+ transformDataList.push({
323
+ originalSwitchText,
324
+ isInReturnStatement,
325
+ metadata,
326
+ interfaceCode,
327
+ strategyClasses,
328
+ factoryClass,
329
+ replacementText,
330
+ });
331
+ }
332
+
333
+ // Apply all transformations
334
+ // Process in reverse order to avoid position shifts affecting earlier switches
335
+ for (let i = transformDataList.length - 1; i >= 0; i--) {
336
+ const data = transformDataList[i];
337
+ if (!data) {
338
+ continue;
339
+ }
340
+
341
+ // Insert generated code
342
+ this.insertGeneratedCode(
343
+ sourceFile,
344
+ data.interfaceCode,
345
+ data.strategyClasses,
346
+ data.factoryClass,
347
+ );
348
+
349
+ // Replace switch with factory call
350
+ this.applySwitchReplacement(
351
+ sourceFile,
352
+ data.originalSwitchText,
353
+ data.replacementText,
354
+ data.isInReturnStatement,
355
+ );
356
+ }
357
+
358
+ // Update imports once at the end
359
+ this.updateImports(sourceFile, context.api);
360
+ } catch (error) {
361
+ // Rollback on error (atomicity guarantee)
362
+ sourceFile.replaceWithText(originalText);
363
+ throw error;
364
+ }
365
+ }
366
+
367
+ /**
368
+ * Find all switch statements that exceed the case threshold.
369
+ *
370
+ * @param sourceFile - The source file to analyze
371
+ * @param minCaseCount - Minimum case count to be considered a God Switch
372
+ * @returns Array of switch statements exceeding threshold
373
+ */
374
+ private findGodSwitches(
375
+ sourceFile: SourceFile,
376
+ minCaseCount: number,
377
+ ): SwitchStatement[] {
378
+ const allSwitches = sourceFile.getDescendantsOfKind(
379
+ SyntaxKind.SwitchStatement,
380
+ );
381
+
382
+ return allSwitches.filter((switchStmt) => {
383
+ const caseBlock = switchStmt.getCaseBlock();
384
+ const caseClauses = caseBlock
385
+ .getClauses()
386
+ .filter((c) => c.getKind() === SyntaxKind.CaseClause);
387
+
388
+ return caseClauses.length > minCaseCount;
389
+ });
390
+ }
391
+
392
+ /**
393
+ * Check if a switch statement has already been transformed.
394
+ *
395
+ * @param switchStmt - The switch statement to check
396
+ * @returns True if already transformed, false otherwise
397
+ */
398
+ private isAlreadyTransformed(switchStmt: SwitchStatement): boolean {
399
+ // Check if the switch is immediately preceded by a comment indicating transformation
400
+ const parent = switchStmt.getParent();
401
+ const fullText = parent.getFullText();
402
+ const switchPos = switchStmt.getStart();
403
+ const textBeforeSwitch = fullText.substring(0, switchPos);
404
+
405
+ return textBeforeSwitch.includes(
406
+ '// TRANSFORMED: God Switch to Factory Pattern',
407
+ );
408
+ }
409
+
410
+ /**
411
+ * Extract comprehensive metadata from a switch statement.
412
+ *
413
+ * @param switchStmt - The switch statement to analyze
414
+ * @returns Complete switch metadata for code generation
415
+ */
416
+ private extractSwitchMetadata(switchStmt: SwitchStatement): SwitchMetadata {
417
+ const expression = switchStmt.getExpression();
418
+ const expressionText = expression.getText();
419
+ const expressionType = expression.getType().getText();
420
+
421
+ // Get the function containing the switch
422
+ const containingFunc =
423
+ switchStmt.getFirstAncestorByKind(SyntaxKind.FunctionDeclaration) ??
424
+ switchStmt.getFirstAncestorByKind(SyntaxKind.MethodDeclaration);
425
+
426
+ // Extract cases
427
+ const caseBlock = switchStmt.getCaseBlock();
428
+ const clauses = caseBlock.getClauses();
429
+
430
+ const cases: CaseMetadata[] = [];
431
+ let defaultClause: DefaultClause | undefined;
432
+
433
+ for (let i = 0; i < clauses.length; i++) {
434
+ const clause = clauses[i];
435
+ if (!clause) {
436
+ continue;
437
+ }
438
+
439
+ if (clause.getKind() === SyntaxKind.DefaultClause) {
440
+ defaultClause = clause as DefaultClause;
441
+ continue;
442
+ }
443
+
444
+ const caseClause = clause as CaseClause;
445
+ const caseMetadata = this.analyzeCaseLogic(caseClause, containingFunc);
446
+
447
+ // Check for fall-through (no break/return and followed by another case)
448
+ if (
449
+ i < clauses.length - 1 &&
450
+ !caseMetadata.hasBreak &&
451
+ !caseMetadata.hasReturn
452
+ ) {
453
+ caseMetadata.isFallthrough = true;
454
+ }
455
+
456
+ cases.push(caseMetadata);
457
+ }
458
+
459
+ // Determine return type
460
+ const returnType = this.extractReturnType(switchStmt);
461
+
462
+ // Extract parameters (function parameters + captured variables)
463
+ const parameters = this.extractParameters(switchStmt, cases);
464
+
465
+ return {
466
+ expression: expressionText,
467
+ expressionType,
468
+ returnType,
469
+ parameters,
470
+ cases,
471
+ hasDefault: defaultClause !== undefined,
472
+ defaultClause,
473
+ };
474
+ }
475
+
476
+ /**
477
+ * Analyze a case clause to extract logic and metadata.
478
+ *
479
+ * @param caseClause - The case clause to analyze
480
+ * @param containingFunc - The containing function or method
481
+ * @returns Case metadata including statements and control flow
482
+ */
483
+ private analyzeCaseLogic(
484
+ caseClause: CaseClause,
485
+ containingFunc: Node | undefined,
486
+ ): CaseMetadata {
487
+ const caseExpression = caseClause.getExpression();
488
+ const caseValue = caseExpression.getText();
489
+ const sanitizedValue = this.sanitizeCaseValue(caseValue);
490
+
491
+ const statements = caseClause.getStatements();
492
+ const hasReturn = statements.some(
493
+ (stmt) => stmt.getKind() === SyntaxKind.ReturnStatement,
494
+ );
495
+ const hasBreak = statements.some(
496
+ (stmt) => stmt.getKind() === SyntaxKind.BreakStatement,
497
+ );
498
+
499
+ // Extract return type for this specific case
500
+ let returnType = 'void';
501
+ const returnStmt = statements.find(
502
+ (stmt) => stmt.getKind() === SyntaxKind.ReturnStatement,
503
+ );
504
+ if (returnStmt) {
505
+ const returnExpression = (returnStmt as ReturnStatement).getExpression();
506
+ if (returnExpression) {
507
+ returnType = returnExpression.getType().getText();
508
+ }
509
+ }
510
+
511
+ // Analyze captured variables (variables used but not declared in case)
512
+ // Pass the containing function/block as parent scope, not the switch statement
513
+ const capturedVariables = containingFunc
514
+ ? this.identifyCapturedVariables(caseClause, containingFunc)
515
+ : [];
516
+
517
+ // Analyze mutated variables (captured variables that are assigned/modified)
518
+ const mutatedVariables = this.identifyMutatedVariables(
519
+ caseClause,
520
+ capturedVariables,
521
+ );
522
+
523
+ return {
524
+ caseValue,
525
+ sanitizedValue,
526
+ statements,
527
+ capturedVariables,
528
+ mutatedVariables,
529
+ hasReturn,
530
+ hasBreak,
531
+ isFallthrough: false, // Will be set by caller
532
+ returnType,
533
+ };
534
+ }
535
+
536
+ /**
537
+ * Identify variables captured from outer scope.
538
+ *
539
+ * @param caseClause - The case clause to analyze
540
+ * @param parentScope - The parent scope (e.g., function, block)
541
+ * @returns Array of captured variable names
542
+ */
543
+ private identifyCapturedVariables(
544
+ caseClause: CaseClause,
545
+ parentScope: Node,
546
+ ): string[] {
547
+ const captured = new Set<string>();
548
+
549
+ // Get all identifiers used in the case
550
+ const identifiers = caseClause.getDescendantsOfKind(SyntaxKind.Identifier);
551
+
552
+ // Get all variable declarations in the case
553
+ const localDeclarations = new Set(
554
+ caseClause
555
+ .getDescendantsOfKind(SyntaxKind.VariableDeclaration)
556
+ .map((decl) => decl.getName()),
557
+ );
558
+
559
+ for (const identifier of identifiers) {
560
+ const name = identifier.getText();
561
+
562
+ // Skip if locally declared
563
+ if (localDeclarations.has(name)) {
564
+ continue;
565
+ }
566
+
567
+ // Skip if it's a property access (e.g., this.foo)
568
+ const parent = identifier.getParent();
569
+ if (parent.getKind() === SyntaxKind.PropertyAccessExpression) {
570
+ continue;
571
+ }
572
+
573
+ // Check if declared in parent scope
574
+ const symbol = identifier.getSymbol();
575
+ if (symbol) {
576
+ const declarations = symbol.getDeclarations();
577
+ for (const decl of declarations) {
578
+ // If declaration is outside the case but inside parent scope, it's captured
579
+ if (
580
+ !caseClause.containsRange(decl.getPos(), decl.getEnd()) &&
581
+ parentScope.containsRange(decl.getPos(), decl.getEnd())
582
+ ) {
583
+ captured.add(name);
584
+ }
585
+ }
586
+ }
587
+ }
588
+
589
+ return Array.from(captured);
590
+ }
591
+
592
+ /**
593
+ * Identify captured variables that are mutated in the case clause.
594
+ * Detects assignments, increment/decrement operations on captured variables.
595
+ *
596
+ * @param caseClause - The case clause to analyze
597
+ * @param capturedVariables - Array of captured variable names
598
+ * @returns Array of mutated variable names
599
+ */
600
+ private identifyMutatedVariables(
601
+ caseClause: CaseClause,
602
+ capturedVariables: string[],
603
+ ): string[] {
604
+ const mutated = new Set<string>();
605
+ const capturedSet = new Set(capturedVariables);
606
+
607
+ // Walk the AST to find mutations
608
+ caseClause.forEachDescendant((node) => {
609
+ // Check for assignment expressions (a = b, a += b, etc.)
610
+ if (node.getKind() === SyntaxKind.BinaryExpression) {
611
+ const binExpr = node as BinaryExpression;
612
+ const operator = binExpr.getOperatorToken().getText();
613
+
614
+ // Check if it's an assignment operator
615
+ if (
616
+ operator === '=' ||
617
+ operator === '+=' ||
618
+ operator === '-=' ||
619
+ operator === '*=' ||
620
+ operator === '/=' ||
621
+ operator === '%=' ||
622
+ operator === '<<=' ||
623
+ operator === '>>=' ||
624
+ operator === '>>>=' ||
625
+ operator === '&=' ||
626
+ operator === '|=' ||
627
+ operator === '^='
628
+ ) {
629
+ const left = binExpr.getLeft();
630
+ if (left.getKind() === SyntaxKind.Identifier) {
631
+ const varName = left.getText();
632
+ if (capturedSet.has(varName)) {
633
+ mutated.add(varName);
634
+ }
635
+ }
636
+ }
637
+ }
638
+
639
+ // Check for prefix unary expressions (++a, --a)
640
+ if (node.getKind() === SyntaxKind.PrefixUnaryExpression) {
641
+ const prefixExpr = node as PrefixUnaryExpression;
642
+ const operator = prefixExpr.getOperatorToken();
643
+
644
+ if (
645
+ operator === SyntaxKind.PlusPlusToken ||
646
+ operator === SyntaxKind.MinusMinusToken
647
+ ) {
648
+ const operand = prefixExpr.getOperand();
649
+ if (operand.getKind() === SyntaxKind.Identifier) {
650
+ const varName = operand.getText();
651
+ if (capturedSet.has(varName)) {
652
+ mutated.add(varName);
653
+ }
654
+ }
655
+ }
656
+ }
657
+
658
+ // Check for postfix unary expressions (a++, a--)
659
+ if (node.getKind() === SyntaxKind.PostfixUnaryExpression) {
660
+ const postfixExpr = node as PostfixUnaryExpression;
661
+ // PostfixUnaryExpression always has ++ or -- operator
662
+ const operand = postfixExpr.getOperand();
663
+ if (operand.getKind() === SyntaxKind.Identifier) {
664
+ const varName = operand.getText();
665
+ if (capturedSet.has(varName)) {
666
+ mutated.add(varName);
667
+ }
668
+ }
669
+ }
670
+ });
671
+
672
+ return Array.from(mutated);
673
+ }
674
+
675
+ /**
676
+ * Extract return type from switch statement.
677
+ * Prioritizes function's declared return type over inferred literal types.
678
+ *
679
+ * @param switchStmt - The switch statement
680
+ * @returns Return type as string
681
+ */
682
+ private extractReturnType(switchStmt: SwitchStatement): string {
683
+ // ALWAYS try to get the function's declared return type first
684
+ // This prevents literal type inference (e.g., "0" instead of "number")
685
+ const func =
686
+ switchStmt.getFirstAncestorByKind(SyntaxKind.MethodDeclaration) ??
687
+ switchStmt.getFirstAncestorByKind(SyntaxKind.FunctionDeclaration);
688
+
689
+ if (func) {
690
+ const returnTypeNode = func.getReturnTypeNode();
691
+ if (returnTypeNode) {
692
+ return returnTypeNode.getText();
693
+ }
694
+ }
695
+
696
+ // Fallback: Check all case return statements for type inference
697
+ const caseBlock = switchStmt.getCaseBlock();
698
+ const returnStatements = caseBlock.getDescendantsOfKind(
699
+ SyntaxKind.ReturnStatement,
700
+ );
701
+
702
+ if (returnStatements.length > 0) {
703
+ const firstReturn = returnStatements[0];
704
+ if (firstReturn) {
705
+ const expression = firstReturn.getExpression();
706
+ if (expression) {
707
+ // Get widened type to avoid literal types
708
+ const type = expression.getType();
709
+ const baseType = type.getBaseTypeOfLiteralType();
710
+ return baseType.getText();
711
+ }
712
+ }
713
+ }
714
+
715
+ // Default to void
716
+ return 'void';
717
+ }
718
+
719
+ /**
720
+ * Extract parameters needed by strategy execute method.
721
+ * Merges function parameters with captured variables from cases.
722
+ *
723
+ * @param switchStmt - The switch statement
724
+ * @param cases - Array of case metadata with captured variables
725
+ * @returns Array of parameter information
726
+ */
727
+ private extractParameters(
728
+ switchStmt: SwitchStatement,
729
+ cases: CaseMetadata[],
730
+ ): ParameterInfo[] {
731
+ const parameterMap = new Map<string, ParameterInfo>();
732
+
733
+ // Get the function containing the switch
734
+ const containingFunc =
735
+ switchStmt.getFirstAncestorByKind(SyntaxKind.FunctionDeclaration) ??
736
+ switchStmt.getFirstAncestorByKind(SyntaxKind.MethodDeclaration);
737
+
738
+ if (!containingFunc) {
739
+ return [];
740
+ }
741
+
742
+ // Get all parameters from the containing function
743
+ const funcParams = containingFunc.getParameters();
744
+
745
+ // Get all identifiers used in switch cases
746
+ const caseBlock = switchStmt.getCaseBlock();
747
+ const usedIdentifiers = new Set<string>();
748
+
749
+ caseBlock.getDescendantsOfKind(SyntaxKind.Identifier).forEach((id) => {
750
+ usedIdentifiers.add(id.getText());
751
+ });
752
+
753
+ // Collect all mutated variables from all cases
754
+ const allMutatedVariables = new Set<string>();
755
+ for (const caseMetadata of cases) {
756
+ for (const varName of caseMetadata.mutatedVariables) {
757
+ allMutatedVariables.add(varName);
758
+ }
759
+ }
760
+
761
+ // Add function parameters that are used in switch cases
762
+ for (const param of funcParams) {
763
+ const paramName = param.getName();
764
+ if (usedIdentifiers.has(paramName)) {
765
+ parameterMap.set(paramName, {
766
+ name: paramName,
767
+ type: param.getType().getText(),
768
+ isMutable: allMutatedVariables.has(paramName),
769
+ });
770
+ }
771
+ }
772
+
773
+ // Collect all captured variables from all cases
774
+ const allCapturedVariables = new Set<string>();
775
+ for (const caseMetadata of cases) {
776
+ for (const varName of caseMetadata.capturedVariables) {
777
+ allCapturedVariables.add(varName);
778
+ }
779
+ }
780
+
781
+ // Add captured variables to parameters (if not already a function parameter)
782
+ for (const varName of allCapturedVariables) {
783
+ if (!parameterMap.has(varName)) {
784
+ // Find the variable declaration to get its type
785
+ const varDecls = containingFunc
786
+ .getDescendantsOfKind(SyntaxKind.VariableDeclaration)
787
+ .filter((decl) => decl.getName() === varName);
788
+
789
+ if (varDecls.length > 0) {
790
+ const varDecl = varDecls[0];
791
+ if (varDecl) {
792
+ parameterMap.set(varName, {
793
+ name: varName,
794
+ type: varDecl.getType().getText(),
795
+ isMutable: allMutatedVariables.has(varName),
796
+ });
797
+ }
798
+ } else {
799
+ // Fallback: try to infer type from usage
800
+ const identifiers = caseBlock
801
+ .getDescendantsOfKind(SyntaxKind.Identifier)
802
+ .filter((id) => id.getText() === varName);
803
+
804
+ if (identifiers.length > 0) {
805
+ const firstId = identifiers[0];
806
+ if (firstId) {
807
+ parameterMap.set(varName, {
808
+ name: varName,
809
+ type: firstId.getType().getText(),
810
+ isMutable: allMutatedVariables.has(varName),
811
+ });
812
+ }
813
+ }
814
+ }
815
+ }
816
+ }
817
+
818
+ return Array.from(parameterMap.values());
819
+ }
820
+
821
+ /**
822
+ * Generate strategy interface code.
823
+ *
824
+ * @param switchStmt - The switch statement
825
+ * @param metadata - Switch metadata
826
+ * @param config - Configuration options
827
+ * @returns Interface code as string
828
+ */
829
+ private generateStrategyInterface(
830
+ switchStmt: SwitchStatement,
831
+ metadata: SwitchMetadata,
832
+ config: GodSwitchTransformConfig,
833
+ ): string {
834
+ const expression = switchStmt.getExpression().getText();
835
+ const interfaceName = this.applyNamingPattern(
836
+ config.factoryNamingPattern!,
837
+ '',
838
+ expression,
839
+ ).replace('Factory', 'Strategy');
840
+
841
+ // Separate readonly and mutable parameters
842
+ const readonlyParams = metadata.parameters
843
+ .filter((p) => !p.isMutable)
844
+ .map((p) => `${p.name}: ${p.type}`)
845
+ .join(', ');
846
+
847
+ const mutableParams = metadata.parameters
848
+ .filter((p) => p.isMutable)
849
+ .map((p) => `${p.name}: ${p.type}`)
850
+ .join(', ');
851
+
852
+ // Determine return type
853
+ const hasMutations = metadata.parameters.some((p) => p.isMutable);
854
+ const mutableVarNames = metadata.parameters
855
+ .filter((p) => p.isMutable)
856
+ .map((p) => `'${p.name}'`)
857
+ .join(' | ');
858
+
859
+ let returnType: string;
860
+ if (hasMutations && metadata.returnType !== 'void') {
861
+ // Both return value and mutations
862
+ returnType = `{ result: ${metadata.returnType}; mutations: Partial<Record<${mutableVarNames}, any>> }`;
863
+ } else if (hasMutations) {
864
+ // Only mutations
865
+ returnType = `Partial<Record<${mutableVarNames}, any>>`;
866
+ } else {
867
+ // Only return value
868
+ returnType = metadata.returnType;
869
+ }
870
+
871
+ // Build parameter list
872
+ let paramList = '';
873
+ if (readonlyParams && mutableParams) {
874
+ paramList = `${readonlyParams}, ${mutableParams}`;
875
+ } else if (readonlyParams) {
876
+ paramList = readonlyParams;
877
+ } else if (mutableParams) {
878
+ paramList = mutableParams;
879
+ }
880
+
881
+ return `
882
+ /**
883
+ * Strategy interface for ${expression} switch statement.
884
+ * Generated by GodSwitchTransformOrchestrator.
885
+ */
886
+ interface I${interfaceName} {
887
+ execute(${paramList}): ${returnType};
888
+ }
889
+ `;
890
+ }
891
+
892
+ /**
893
+ * Generate strategy class implementations.
894
+ *
895
+ * @param cases - Array of case metadata
896
+ * @param metadata - Complete switch metadata
897
+ * @param config - Configuration options
898
+ * @returns Object containing strategy class code and case-to-strategy mapping
899
+ */
900
+ private generateStrategyClasses(
901
+ cases: CaseMetadata[],
902
+ metadata: SwitchMetadata,
903
+ config: GodSwitchTransformConfig,
904
+ ): { classes: string[]; caseToStrategyMap: Record<string, string> } {
905
+ const strategyClasses: string[] = [];
906
+ const caseToStrategyMap: Record<string, string> = {};
907
+ const interfaceName = this.applyNamingPattern(
908
+ config.factoryNamingPattern!,
909
+ '',
910
+ metadata.expression,
911
+ ).replace('Factory', 'Strategy');
912
+
913
+ // Conditional interface reference based on config
914
+ const interfaceRef = config.generateInterfaces
915
+ ? `I${interfaceName}`
916
+ : 'any';
917
+
918
+ // Group fall-through cases
919
+ const groupedCases: CaseMetadata[][] = [];
920
+ let currentGroup: CaseMetadata[] = [];
921
+
922
+ for (const caseMetadata of cases) {
923
+ currentGroup.push(caseMetadata);
924
+
925
+ if (!caseMetadata.isFallthrough) {
926
+ groupedCases.push([...currentGroup]);
927
+ currentGroup = [];
928
+ }
929
+ }
930
+
931
+ // Generate strategy for each case or case group
932
+ for (const caseGroup of groupedCases) {
933
+ const firstCase = caseGroup[0];
934
+ if (!firstCase) {
935
+ continue;
936
+ }
937
+
938
+ const className = this.applyNamingPattern(
939
+ config.strategyNamingPattern!,
940
+ firstCase.sanitizedValue,
941
+ metadata.expression,
942
+ );
943
+
944
+ // Map ALL cases in the group to the same strategy class
945
+ for (const caseMetadata of caseGroup) {
946
+ caseToStrategyMap[caseMetadata.caseValue] = className;
947
+ }
948
+
949
+ // Separate readonly and mutable parameters
950
+ const readonlyParams = metadata.parameters
951
+ .filter((p) => !p.isMutable)
952
+ .map((p) => `${p.name}: ${p.type}`)
953
+ .join(', ');
954
+
955
+ const mutableParams = metadata.parameters
956
+ .filter((p) => p.isMutable)
957
+ .map((p) => `${p.name}: ${p.type}`)
958
+ .join(', ');
959
+
960
+ let paramList = '';
961
+ if (readonlyParams && mutableParams) {
962
+ paramList = `${readonlyParams}, ${mutableParams}`;
963
+ } else if (readonlyParams) {
964
+ paramList = readonlyParams;
965
+ } else if (mutableParams) {
966
+ paramList = mutableParams;
967
+ }
968
+
969
+ // Extract case logic (remove break/return statements at the end)
970
+ const allStatements = caseGroup.flatMap((c) => c.statements);
971
+ const logic = allStatements
972
+ .filter(
973
+ (stmt) =>
974
+ stmt.getKind() !== SyntaxKind.BreakStatement &&
975
+ stmt.getKind() !== SyntaxKind.ReturnStatement,
976
+ )
977
+ .map((stmt) => stmt.getText())
978
+ .join('\n ');
979
+
980
+ // Check if there's a return statement
981
+ const returnStmt = allStatements.find(
982
+ (stmt) => stmt.getKind() === SyntaxKind.ReturnStatement,
983
+ );
984
+
985
+ const hasMutations = metadata.parameters.some((p) => p.isMutable);
986
+ const hasReturn = metadata.returnType !== 'void';
987
+
988
+ let executeBody = '';
989
+ if (hasMutations) {
990
+ // Track mutations
991
+ executeBody += ' ' + logic + '\n';
992
+
993
+ if (hasReturn && returnStmt) {
994
+ // Both return value and mutations
995
+ const returnValue =
996
+ (returnStmt as ReturnStatement).getExpression()?.getText() ??
997
+ 'undefined';
998
+ executeBody += ` const __result = ${returnValue};\n`;
999
+ executeBody += ' return {\n';
1000
+ executeBody += ` result: __result,\n`;
1001
+ executeBody += ' mutations: {\n';
1002
+
1003
+ const mutableVars = metadata.parameters.filter((p) => p.isMutable);
1004
+ for (const param of mutableVars) {
1005
+ executeBody += ` ${param.name},\n`;
1006
+ }
1007
+ executeBody += ' }\n';
1008
+ executeBody += ' };';
1009
+ } else {
1010
+ // Only mutations
1011
+ executeBody += ' return {\n';
1012
+
1013
+ const mutableVars = metadata.parameters.filter((p) => p.isMutable);
1014
+ for (const param of mutableVars) {
1015
+ executeBody += ` ${param.name},\n`;
1016
+ }
1017
+ executeBody += ' };';
1018
+ }
1019
+ } else {
1020
+ // No mutations - original behavior
1021
+ executeBody = ' ' + logic;
1022
+ if (returnStmt) {
1023
+ executeBody += '\n ' + returnStmt.getText();
1024
+ }
1025
+ }
1026
+
1027
+ // Determine return type from the first case in the group
1028
+ const caseReturnType = firstCase.returnType;
1029
+ const mutableVarNames = metadata.parameters
1030
+ .filter((p) => p.isMutable)
1031
+ .map((p) => `'${p.name}'`)
1032
+ .join(' | ');
1033
+
1034
+ let returnType: string;
1035
+ if (hasMutations && hasReturn) {
1036
+ returnType = `{ result: ${caseReturnType}; mutations: Partial<Record<${mutableVarNames}, any>> }`;
1037
+ } else if (hasMutations) {
1038
+ returnType = `Partial<Record<${mutableVarNames}, any>>`;
1039
+ } else {
1040
+ returnType = caseReturnType;
1041
+ }
1042
+
1043
+ const strategyClass = `
1044
+ /**
1045
+ * Strategy for case: ${caseGroup.map((c) => c.caseValue).join(', ')}
1046
+ * Generated by GodSwitchTransformOrchestrator.
1047
+ */
1048
+ class ${className}${config.generateInterfaces ? ` implements ${interfaceRef}` : ''} {
1049
+ execute(${paramList}): ${returnType} {
1050
+ ${executeBody}
1051
+ }
1052
+ }
1053
+ `;
1054
+
1055
+ strategyClasses.push(strategyClass);
1056
+ }
1057
+
1058
+ // Generate DefaultStrategy if hasDefault is true
1059
+ if (metadata.hasDefault && metadata.defaultClause) {
1060
+ const className = this.applyNamingPattern(
1061
+ config.strategyNamingPattern!,
1062
+ 'Default',
1063
+ metadata.expression,
1064
+ );
1065
+
1066
+ // Separate readonly and mutable parameters
1067
+ const readonlyParams = metadata.parameters
1068
+ .filter((p) => !p.isMutable)
1069
+ .map((p) => `${p.name}: ${p.type}`)
1070
+ .join(', ');
1071
+
1072
+ const mutableParams = metadata.parameters
1073
+ .filter((p) => p.isMutable)
1074
+ .map((p) => `${p.name}: ${p.type}`)
1075
+ .join(', ');
1076
+
1077
+ let paramList = '';
1078
+ if (readonlyParams && mutableParams) {
1079
+ paramList = `${readonlyParams}, ${mutableParams}`;
1080
+ } else if (readonlyParams) {
1081
+ paramList = readonlyParams;
1082
+ } else if (mutableParams) {
1083
+ paramList = mutableParams;
1084
+ }
1085
+
1086
+ const statements = metadata.defaultClause.getStatements();
1087
+ const logic = statements
1088
+ .filter(
1089
+ (stmt) =>
1090
+ stmt.getKind() !== SyntaxKind.BreakStatement &&
1091
+ stmt.getKind() !== SyntaxKind.ReturnStatement,
1092
+ )
1093
+ .map((stmt) => stmt.getText())
1094
+ .join('\n ');
1095
+
1096
+ const returnStmt = statements.find(
1097
+ (stmt) => stmt.getKind() === SyntaxKind.ReturnStatement,
1098
+ );
1099
+
1100
+ // Use the function's declared return type for consistency with the interface
1101
+ // Don't infer from the default clause (it might throw, return never, etc.)
1102
+ const defaultReturnType = metadata.returnType;
1103
+
1104
+ const hasMutations = metadata.parameters.some((p) => p.isMutable);
1105
+ const hasReturn = defaultReturnType !== 'void';
1106
+
1107
+ let executeBody = '';
1108
+ if (hasMutations) {
1109
+ // Track mutations
1110
+ executeBody += ' ' + logic + '\n';
1111
+
1112
+ if (hasReturn && returnStmt) {
1113
+ // Both return value and mutations
1114
+ const returnValue =
1115
+ (returnStmt as ReturnStatement).getExpression()?.getText() ??
1116
+ 'undefined';
1117
+ executeBody += ` const __result = ${returnValue};\n`;
1118
+ executeBody += ' return {\n';
1119
+ executeBody += ` result: __result,\n`;
1120
+ executeBody += ' mutations: {\n';
1121
+
1122
+ const mutableVars = metadata.parameters.filter((p) => p.isMutable);
1123
+ for (const param of mutableVars) {
1124
+ executeBody += ` ${param.name},\n`;
1125
+ }
1126
+ executeBody += ' }\n';
1127
+ executeBody += ' };';
1128
+ } else {
1129
+ // Only mutations
1130
+ executeBody += ' return {\n';
1131
+
1132
+ const mutableVars = metadata.parameters.filter((p) => p.isMutable);
1133
+ for (const param of mutableVars) {
1134
+ executeBody += ` ${param.name},\n`;
1135
+ }
1136
+ executeBody += ' };';
1137
+ }
1138
+ } else {
1139
+ // No mutations - original behavior
1140
+ executeBody = ' ' + logic;
1141
+ if (returnStmt) {
1142
+ executeBody += '\n ' + returnStmt.getText();
1143
+ }
1144
+ }
1145
+
1146
+ // Determine return type using the extracted default return type
1147
+ const mutableVarNames = metadata.parameters
1148
+ .filter((p) => p.isMutable)
1149
+ .map((p) => `'${p.name}'`)
1150
+ .join(' | ');
1151
+
1152
+ let returnType: string;
1153
+ if (hasMutations && hasReturn) {
1154
+ returnType = `{ result: ${defaultReturnType}; mutations: Partial<Record<${mutableVarNames}, any>> }`;
1155
+ } else if (hasMutations) {
1156
+ returnType = `Partial<Record<${mutableVarNames}, any>>`;
1157
+ } else {
1158
+ returnType = defaultReturnType;
1159
+ }
1160
+
1161
+ const defaultStrategyClass = `
1162
+ /**
1163
+ * Default strategy (fallback for unmatched keys).
1164
+ * Generated by GodSwitchTransformOrchestrator.
1165
+ */
1166
+ class ${className}${config.generateInterfaces ? ` implements ${interfaceRef}` : ''} {
1167
+ execute(${paramList}): ${returnType} {
1168
+ ${executeBody}
1169
+ }
1170
+ }
1171
+ `;
1172
+
1173
+ strategyClasses.push(defaultStrategyClass);
1174
+ }
1175
+
1176
+ return { classes: strategyClasses, caseToStrategyMap };
1177
+ }
1178
+
1179
+ /**
1180
+ * Generate factory class code.
1181
+ *
1182
+ * @param metadata - Switch metadata
1183
+ * @param config - Configuration options
1184
+ * @param caseToStrategyMap - Mapping from case values to strategy class names
1185
+ * @returns Factory class code as string
1186
+ */
1187
+ private generateFactoryClass(
1188
+ metadata: SwitchMetadata,
1189
+ config: GodSwitchTransformConfig,
1190
+ caseToStrategyMap: Record<string, string>,
1191
+ ): string {
1192
+ const factoryName = this.applyNamingPattern(
1193
+ config.factoryNamingPattern!,
1194
+ '',
1195
+ metadata.expression,
1196
+ );
1197
+
1198
+ const interfaceName = factoryName.replace('Factory', 'Strategy');
1199
+
1200
+ // Conditional interface reference based on config
1201
+ const interfaceRef = config.generateInterfaces
1202
+ ? `I${interfaceName}`
1203
+ : 'any';
1204
+
1205
+ // Use the shared caseToStrategyMap to generate mappings for ALL cases (including fall-through)
1206
+ const strategyMappings = Object.entries(caseToStrategyMap)
1207
+ .map(([caseValue, className]) => {
1208
+ return ` ${caseValue}: new ${className}()`;
1209
+ })
1210
+ .join(',\n');
1211
+
1212
+ // Generate default strategy instantiation if hasDefault is true
1213
+ const defaultStrategyField = metadata.hasDefault
1214
+ ? `\n private defaultStrategy: ${interfaceRef} = new ${this.applyNamingPattern(
1215
+ config.strategyNamingPattern!,
1216
+ 'Default',
1217
+ metadata.expression,
1218
+ )}();`
1219
+ : '';
1220
+
1221
+ // Generate create method with default fallback
1222
+ const createMethodBody = metadata.hasDefault
1223
+ ? `
1224
+ create(key: string): ${interfaceRef} {
1225
+ const strategy = this.strategies[key];
1226
+ return strategy ?? this.defaultStrategy;
1227
+ }`
1228
+ : `
1229
+ create(key: string): ${interfaceRef} {
1230
+ const strategy = this.strategies[key];
1231
+ if (!strategy) {
1232
+ throw new Error(\`Unknown strategy key: \${key}\`);
1233
+ }
1234
+ return strategy;
1235
+ }`;
1236
+
1237
+ return `
1238
+ /**
1239
+ * Factory for ${metadata.expression} strategies.
1240
+ * Generated by GodSwitchTransformOrchestrator.
1241
+ */
1242
+ class ${factoryName} {
1243
+ private strategies: Record<string, ${interfaceRef}> = {
1244
+ ${strategyMappings}
1245
+ };${defaultStrategyField}
1246
+ ${createMethodBody}
1247
+ }
1248
+ `;
1249
+ }
1250
+
1251
+ /**
1252
+ * Generate replacement text for switch statement.
1253
+ *
1254
+ * @param metadata - Switch metadata
1255
+ * @param config - Configuration options
1256
+ * @param originalSwitchText - Original switch text
1257
+ * @param isInReturnStatement - Whether the switch is in a return statement
1258
+ * @returns Replacement text
1259
+ */
1260
+ private generateReplacementText(
1261
+ metadata: SwitchMetadata,
1262
+ config: GodSwitchTransformConfig,
1263
+ originalSwitchText: string,
1264
+ isInReturnStatement: boolean,
1265
+ ): string {
1266
+ const factoryName = this.applyNamingPattern(
1267
+ config.factoryNamingPattern!,
1268
+ '',
1269
+ metadata.expression,
1270
+ );
1271
+
1272
+ const paramList = metadata.parameters.map((p) => p.name).join(', ');
1273
+ const hasMutations = metadata.parameters.some((p) => p.isMutable);
1274
+ const hasReturn = metadata.returnType !== 'void';
1275
+
1276
+ // Preserve original switch in comment
1277
+ const comment = `// TRANSFORMED: God Switch to Factory Pattern\n// Original switch preserved below:\n/*\n${originalSwitchText}\n*/\n`;
1278
+
1279
+ let replacement: string;
1280
+
1281
+ if (hasMutations && hasReturn) {
1282
+ // Both mutations and return value
1283
+ if (isInReturnStatement) {
1284
+ replacement = `${comment}const factory = new ${factoryName}();
1285
+ const strategy = factory.create(${metadata.expression});
1286
+ const { result: __result, mutations } = strategy.execute(${paramList});
1287
+ ${this.generateMutationApplication(metadata)}
1288
+ return __result;`;
1289
+ } else {
1290
+ replacement = `${comment}const factory = new ${factoryName}();
1291
+ const strategy = factory.create(${metadata.expression});
1292
+ const { result: __result, mutations } = strategy.execute(${paramList});
1293
+ ${this.generateMutationApplication(metadata)}`;
1294
+ }
1295
+ } else if (hasMutations) {
1296
+ // Only mutations, no return value
1297
+ replacement = `${comment}const factory = new ${factoryName}();
1298
+ const strategy = factory.create(${metadata.expression});
1299
+ const mutations = strategy.execute(${paramList});
1300
+ ${this.generateMutationApplication(metadata)}`;
1301
+ } else if (hasReturn) {
1302
+ // Only return value, no mutations (original behavior)
1303
+ if (isInReturnStatement) {
1304
+ replacement = `${comment}const factory = new ${factoryName}();
1305
+ const strategy = factory.create(${metadata.expression});
1306
+ return strategy.execute(${paramList});`;
1307
+ } else {
1308
+ replacement = `${comment}const factory = new ${factoryName}();
1309
+ const strategy = factory.create(${metadata.expression});
1310
+ const result = strategy.execute(${paramList});
1311
+ return result;`;
1312
+ }
1313
+ } else {
1314
+ // No return value, no mutations
1315
+ replacement = `${comment}const factory = new ${factoryName}();
1316
+ const strategy = factory.create(${metadata.expression});
1317
+ strategy.execute(${paramList});`;
1318
+ }
1319
+
1320
+ return replacement;
1321
+ }
1322
+
1323
+ /**
1324
+ * Generate mutation application code.
1325
+ * Applies mutations returned from strategy back to original variables.
1326
+ *
1327
+ * @param metadata - Switch metadata
1328
+ * @returns Mutation application code
1329
+ */
1330
+ private generateMutationApplication(metadata: SwitchMetadata): string {
1331
+ const mutableVars = metadata.parameters.filter((p) => p.isMutable);
1332
+
1333
+ if (mutableVars.length === 0) {
1334
+ return '';
1335
+ }
1336
+
1337
+ const assignments = mutableVars
1338
+ .map(
1339
+ (param) =>
1340
+ `if (mutations.${param.name} !== undefined) ${param.name} = mutations.${param.name};`,
1341
+ )
1342
+ .join('\n');
1343
+
1344
+ return assignments;
1345
+ }
1346
+
1347
+ /**
1348
+ * Apply switch replacement after AST has been modified.
1349
+ *
1350
+ * @param sourceFile - The source file
1351
+ * @param originalSwitchText - Original switch text to find
1352
+ * @param replacementText - Replacement text
1353
+ * @param isInReturnStatement - Whether to replace return statement
1354
+ */
1355
+ private applySwitchReplacement(
1356
+ sourceFile: SourceFile,
1357
+ originalSwitchText: string,
1358
+ replacementText: string,
1359
+ isInReturnStatement: boolean,
1360
+ ): void {
1361
+ // Find all switch statements in the file
1362
+ const switches = sourceFile.getDescendantsOfKind(
1363
+ SyntaxKind.SwitchStatement,
1364
+ );
1365
+
1366
+ for (const switchStmt of switches) {
1367
+ const currentText = switchStmt.getText();
1368
+
1369
+ // Match based on normalized text (remove whitespace differences)
1370
+ const normalizedOriginal = originalSwitchText.replaceAll(/\s+/g, ' ');
1371
+ const normalizedCurrent = currentText.replaceAll(/\s+/g, ' ');
1372
+
1373
+ if (normalizedCurrent === normalizedOriginal) {
1374
+ if (isInReturnStatement) {
1375
+ // Replace the entire return statement
1376
+ const parent = switchStmt.getParent();
1377
+ if (parent.getKind() === SyntaxKind.ReturnStatement) {
1378
+ parent.replaceWithText(replacementText);
1379
+ } else {
1380
+ switchStmt.replaceWithText(replacementText);
1381
+ }
1382
+ } else {
1383
+ switchStmt.replaceWithText(replacementText);
1384
+ }
1385
+ break; // Only replace the first match
1386
+ }
1387
+ }
1388
+ }
1389
+
1390
+ /**
1391
+ * Insert generated code into the source file.
1392
+ *
1393
+ * @param sourceFile - The source file
1394
+ * @param interfaceCode - Strategy interface code (null if not generated)
1395
+ * @param strategyClasses - Array of strategy class code
1396
+ * @param factoryClass - Factory class code (null if not generated)
1397
+ */
1398
+ private insertGeneratedCode(
1399
+ sourceFile: SourceFile,
1400
+ interfaceCode: string | null,
1401
+ strategyClasses: string[],
1402
+ factoryClass: string | null,
1403
+ ): void {
1404
+ // Find the last import statement
1405
+ const imports = sourceFile.getImportDeclarations();
1406
+ const lastImport = imports.at(-1);
1407
+
1408
+ // Build the code to insert
1409
+ let codeToInsert = '\n// ========================================\n';
1410
+ codeToInsert += '// Generated by GodSwitchTransformOrchestrator\n';
1411
+ codeToInsert += '// ========================================\n';
1412
+
1413
+ if (interfaceCode) {
1414
+ codeToInsert += interfaceCode;
1415
+ }
1416
+
1417
+ for (const strategyClass of strategyClasses) {
1418
+ codeToInsert += strategyClass;
1419
+ }
1420
+
1421
+ if (factoryClass) {
1422
+ codeToInsert += factoryClass;
1423
+ }
1424
+
1425
+ codeToInsert += '\n// ========================================\n\n';
1426
+
1427
+ // Insert after last import (or at beginning if no imports)
1428
+ if (lastImport) {
1429
+ lastImport.replaceWithText(lastImport.getText() + codeToInsert);
1430
+ } else {
1431
+ // Insert at the beginning of the file
1432
+ sourceFile.insertText(0, codeToInsert);
1433
+ }
1434
+ }
1435
+
1436
+ /**
1437
+ * Update imports as needed.
1438
+ *
1439
+ * @param sourceFile - The source file
1440
+ * @param api - The Public API
1441
+ */
1442
+ private updateImports(sourceFile: SourceFile, _api: PublicApi): void {
1443
+ // For now, no additional imports are needed
1444
+ // Strategy classes and factory are generated in the same file
1445
+
1446
+ // In the future, if we generate separate files, we would use:
1447
+ // api.transformation.importManager.addImport(...)
1448
+
1449
+ // Ensure imports are formatted correctly
1450
+ sourceFile.formatText();
1451
+ }
1452
+
1453
+ /**
1454
+ * Apply naming pattern template to generate class names.
1455
+ *
1456
+ * @param pattern - Naming pattern with template variables
1457
+ * @param caseValue - The case value (for strategies)
1458
+ * @param switchExpression - The switch expression
1459
+ * @returns Generated name
1460
+ */
1461
+ private applyNamingPattern(
1462
+ pattern: string,
1463
+ caseValue: string,
1464
+ switchExpression: string,
1465
+ ): string {
1466
+ let result = pattern;
1467
+
1468
+ // Replace {CaseValue} with PascalCase case value
1469
+ if (caseValue) {
1470
+ result = result.replace('{CaseValue}', this.toPascalCase(caseValue));
1471
+ }
1472
+
1473
+ // Replace {SwitchExpression} with PascalCase expression
1474
+ const expressionName =
1475
+ this.extractIdentifierFromExpression(switchExpression);
1476
+ result = result.replace(
1477
+ '{SwitchExpression}',
1478
+ this.toPascalCase(expressionName),
1479
+ );
1480
+
1481
+ return result;
1482
+ }
1483
+
1484
+ /**
1485
+ * Extract identifier from expression (e.g., "user.type" -> "UserType").
1486
+ *
1487
+ * @param expression - The switch expression
1488
+ * @returns Extracted identifier
1489
+ */
1490
+ private extractIdentifierFromExpression(expression: string): string {
1491
+ // Remove property access, function calls, etc.
1492
+ const cleaned = expression
1493
+ .replaceAll(/\(.*?\)/g, '') // Remove function calls
1494
+ .replaceAll(/\[.*?\]/g, '') // Remove array access
1495
+ .replaceAll(/\s+/g, ''); // Remove whitespace
1496
+
1497
+ // Split on dots and join
1498
+ return cleaned
1499
+ .split('.')
1500
+ .map((part) => this.toPascalCase(part))
1501
+ .join('');
1502
+ }
1503
+
1504
+ /**
1505
+ * Convert string to PascalCase.
1506
+ *
1507
+ * @param str - String to convert
1508
+ * @returns PascalCase string
1509
+ */
1510
+ private toPascalCase(str: string): string {
1511
+ return str
1512
+ .replaceAll(/[^a-zA-Z0-9]+/g, ' ') // Replace non-alphanumeric with spaces
1513
+ .split(' ')
1514
+ .filter((word) => word.length > 0)
1515
+ .map((word) => word.charAt(0).toUpperCase() + word.slice(1).toLowerCase())
1516
+ .join('');
1517
+ }
1518
+
1519
+ /**
1520
+ * Sanitize case value for use in identifiers.
1521
+ *
1522
+ * @param value - Case value to sanitize
1523
+ * @returns Sanitized value safe for identifiers
1524
+ */
1525
+ private sanitizeCaseValue(value: string): string {
1526
+ // Remove quotes from string literals
1527
+ let sanitized = value.replaceAll(/(?:^['"`])|(?:['"`]$)/g, '');
1528
+
1529
+ // Replace non-alphanumeric characters with underscores
1530
+ sanitized = sanitized.replaceAll(/[^a-zA-Z0-9]/g, '_');
1531
+
1532
+ // Ensure it doesn't start with a number
1533
+ if (/^\d/.test(sanitized)) {
1534
+ sanitized = '_' + sanitized;
1535
+ }
1536
+
1537
+ return sanitized;
1538
+ }
1539
+
1540
+ /**
1541
+ * Get God Switch configuration with defaults.
1542
+ *
1543
+ * @param config - Plugin configuration
1544
+ * @returns Complete configuration with defaults
1545
+ */
1546
+ private getGodSwitchConfig(
1547
+ config: Record<string, unknown>,
1548
+ ): Required<GodSwitchTransformConfig> {
1549
+ const godSwitchConfig = (config['godSwitch'] ??
1550
+ {}) as GodSwitchTransformConfig;
1551
+
1552
+ return {
1553
+ generateInterfaces: godSwitchConfig.generateInterfaces ?? true,
1554
+ generateFactory: godSwitchConfig.generateFactory ?? true,
1555
+ strategyNamingPattern:
1556
+ godSwitchConfig.strategyNamingPattern ?? '{CaseValue}Strategy',
1557
+ factoryNamingPattern:
1558
+ godSwitchConfig.factoryNamingPattern ?? '{SwitchExpression}Factory',
1559
+ minCaseCount: godSwitchConfig.minCaseCount ?? 10,
1560
+ };
1561
+ }
1562
+ }