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