# Transformation Orchestrators

This directory contains the orchestrator classes that implement the core logic for Angular code transformations. Following the "thin rule, thick orchestrator" pattern, these orchestrators handle the complex AST manipulation and code generation while the rules provide the high-level coordination.

## Overview

Each orchestrator implements a specific transformation type and provides methods for:

- **Analysis**: Detecting transformation opportunities in source code
- **Validation**: Ensuring transformations are safe and beneficial
- **Code Generation**: Creating the transformed code with proper syntax
- **Integration**: Coordinating with the broader transformation pipeline

## Orchestrators

### 1. ConstructorToInjectOrchestrator

**File:** `constructor-to-inject-orchestrator.ts`  
**Purpose:** Converts Angular constructor dependency injection to modern `inject()` function calls

**Key Methods:**

- `analyzeConstructor()` - Detects constructor parameters and injection patterns
- `generateInjectStatements()` - Creates `inject()` calls with proper imports
- `updateConstructor()` - Removes old constructor or converts to parameterless

**Transformation Example:**

```typescript
// Before
constructor(private userService: UserService) {}

// After
private userService = inject(UserService);
```

---

### 2. DependencyInjectionMigrationOrchestrator

**File:** `dependency-injection-migration-orchestrator.ts`  
**Purpose:** Modernizes legacy Angular DI patterns including string tokens and ReflectiveInjector

**Key Methods:**

- `analyzeInjectionTokens()` - Detects string-based `@Inject()` usage
- `analyzeReflectiveInjector()` - Finds legacy injector patterns
- `generateInjectionTokens()` - Creates `InjectionToken` constants
- `migrateInjectorUsage()` - Converts to modern `Injector.create()`

**Transformation Example:**

```typescript
// Before
@Injectable()
export class ApiService {
  constructor(@Inject('API_URL') private apiUrl: string) {}
}

// After
export const API_URL = new InjectionToken<string>('API_URL');

@Injectable()
export class ApiService {
  private apiUrl = inject(API_URL);
}
```

---

### 3. FacadePatternOrchestrator

**File:** `facade-pattern-orchestrator.ts`  
**Purpose:** Extracts business logic from bloated components into dedicated facade services

**Key Methods:**

- `analyzeComponentComplexity()` - Evaluates component method count and complexity
- `analyzeServiceDependencies()` - Detects services used by extracted methods
- `generateFacadeServiceContent()` - Creates the facade service with proper DI
- `updateComponentToUseFacade()` - Modifies component to use facade injection
- `removeMigratedServicesFromComponent()` - Cleans up unused service dependencies

**Transformation Example:**

```typescript
// Before (bloated component)
@Component({...})
export class UserListComponent {
  constructor(private userService: UserService, private router: Router) {}

  loadUsers() {
    return this.userService.getUsers().pipe(
      map(users => users.filter(u => u.active))
    );
  }

  navigateToUser(userId: string) {
    this.router.navigate(['/user', userId]);
  }
}

// After (clean component + facade)
@Injectable()
export class UserListFacade {
  private userService = inject(UserService);
  private router = inject(Router);

  loadUsers() {
    return this.userService.getUsers().pipe(
      map(users => users.filter(u => u.active))
    );
  }

  navigateToUser(userId: string) {
    this.router.navigate(['/user', userId]);
  }
}

@Component({...})
export class UserListComponent {
  private facade = inject(UserListFacade);

  loadUsers() {
    return this.facade.loadUsers();
  }

  navigateToUser(userId: string) {
    this.facade.navigateToUser(userId);
  }
}
```

---

### 4. FormModernizationOrchestrator

**File:** `form-modernization-orchestrator.ts`  
**Purpose:** Modernizes Angular forms from template-driven to reactive patterns

**Key Methods:**

- `analyzeFormTemplates()` - Detects template-driven form patterns
- `analyzeFormComponents()` - Evaluates component form logic
- `generateReactiveFormSetup()` - Creates FormBuilder-based reactive forms
- `migrateTemplateValidation()` - Converts template validators to reactive validators

**Transformation Example:**

```typescript
// Before (template-driven)
@Component({
  template: `
    <form #userForm="ngForm">
      <input [(ngModel)]="user.name" required />
      <input [(ngModel)]="user.email" email />
    </form>
  `,
})
export class UserFormComponent {
  user = { name: '', email: '' };
}

// After (reactive)
@Component({
  template: `
    <form [formGroup]="userForm">
      <input formControlName="name" />
      <input formControlName="email" />
    </form>
  `,
})
export class UserFormComponent {
  userForm = this.fb.group({
    name: ['', Validators.required],
    email: ['', [Validators.required, Validators.email]],
  });

  constructor(private fb: FormBuilder) {}
}
```

---

### 5. InterfaceExtractionOrchestrator

**File:** `interface-extraction-orchestrator.ts`  
**Purpose:** Extracts inline type literals into named interfaces for better code organization

**Key Methods:**

- `analyzeTypeLiterals()` - Finds complex inline type definitions
- `generateInterfaceDeclarations()` - Creates interface declarations with unique names
- `updatePropertyTypes()` - Replaces inline types with interface references
- `handleNestedTypes()` - Manages complex nested type structures

**Transformation Example:**

```typescript
// Before
@Component({...})
export class UserCardComponent {
  @Input() user: {
    id: number;
    name: string;
    profile: {
      avatar: string;
      bio?: string;
    };
  };
}

// After
interface UserProfile {
  avatar: string;
  bio?: string;
}

interface User {
  id: number;
  name: string;
  profile: UserProfile;
}

@Component({...})
export class UserCardComponent {
  @Input() user: User;
}
```

---

### 6. ConstructorInjectionTransformOrchestrator

**File:** `constructor-injection-transform-orchestrator.ts`  
**Purpose:** Converts manual service instantiation (`new Service()`) to proper `inject(Service)` calls

**Key Methods:**

- `analyzeManualInstantiation()` - Detects `new Service()` patterns in constructors and methods
- `validateServiceClasses()` - Checks if instantiated classes match service patterns
- `generateInjectCalls()` - Creates `inject(Service)` calls with proper imports
- `removeManualInstantiation()` - Cleans up constructor assignments and method calls

**Transformation Example:**

```typescript
// Before
@Component({...})
export class UserComponent {
  constructor() {
    this.httpClient = new HttpClient();
    this.userService = new UserService();
  }

  private httpClient: HttpClient;
  private userService: UserService;
}

// After
@Component({...})
export class UserComponent {
  private httpClient = inject(HttpClient);
  private userService = inject(UserService);
}
```

---

### 7. ComponentInputsInterfaceExtractionOrchestrator

**File:** `component-inputs-interface-extraction-orchestrator.ts`  
**Purpose:** Extracts component input properties into dedicated interfaces for better type safety

**Key Methods:**

- `analyzeComponentInputs()` - Finds all `@Input()` properties in components
- `generateInputInterface()` - Creates interface declarations for input properties
- `updateComponentProperties()` - Replaces individual input types with interface references
- `handleOptionalInputs()` - Manages optional vs required input properties

**Transformation Example:**

```typescript
// Before
@Component({...})
export class UserCardComponent {
  @Input() userId: number;
  @Input() userName: string;
  @Input() isActive: boolean;
  @Input() avatarUrl?: string;
}

// After
interface UserCardInputs {
  userId: number;
  userName: string;
  isActive: boolean;
  avatarUrl?: string;
}

@Component({...})
export class UserCardComponent {
  @Input() inputs: UserCardInputs;
}
```

---

### 8. ServiceInjectionCleanupOrchestrator

**File:** `service-injection-cleanup-orchestrator.ts`  
**Purpose:** Converts pseudo-services (classes with manual instantiation) to proper Angular services

**Key Methods:**

- `findManualServiceInstantiations()` - Detects manual service instantiation patterns
- `isManualServiceInstantiation()` - Validates complex expressions like `new Service() || null`
- `convertToInjectCalls()` - Transforms property initializers to `inject()` calls
- `ensureInjectImport()` - Adds `inject` import from `@angular/core`
- `removeEmptyConstructors()` - Cleans up constructors after transformation

**Transformation Example:**

```typescript
// Before
@Component({...})
export class DataComponent {
  private http = new HttpClient();
  private router: Router = new Router();

  constructor() {
    this.http = new HttpClient();
  }
}

// After
@Component({...})
export class DataComponent {
  private http = inject(HttpClient);
  private router = inject(Router);
}
```

## Additional Orchestrators

The following orchestrators exist but are not fully documented above:

| File | Purpose |
|-|-|
| `any-to-interface.orchestrator.ts` | Replaces `any`-typed params/props with generated interfaces |
| `container-presentational-orchestrator.ts` | Separates mixed-responsibility components into container + presentational |
| `core-shared-modules-orchestrator.ts` | Refactors core/shared NgModule structure |
| `dto-object-literal.orchestrator.ts` | Converts DTO object literals to typed class instances |
| `interface-duplication-transform.orchestrator.ts` | Merges duplicate interface families |
| `library-extraction/` | 7-phase pipeline for extracting Angular artifacts to a new library |
| `missing-output-transform.orchestrator.ts` | Adds missing `@Output` EventEmitter declarations |
| `promise-cleanup-transform.orchestrator.ts` | Removes `.toPromise()` and wrapping Promise anti-patterns |
| `promise-component-transform.orchestrator.ts` | Converts async component methods to reactive patterns |
| `promise-service-transform.orchestrator.ts` | Converts async service methods to `Observable`-based API |
| `sequential-await-transform.orchestrator.ts` | Replaces sequential `await` calls with `forkJoin` |
| `service-bag-transform.orchestrator.ts` | Splits service bags into focused services by responsibility |
| `static-class-transform.orchestrator.ts` | Converts static-only classes to module-level functions/constants |
| `static-extract-transform.orchestrator.ts` | Extracts static members from mixed classes |
| `subscription-transform.orchestrator.ts` | Replaces manual unsubscribe with `takeUntilDestroyed()` |
| `type-safety-transform.orchestrator.ts` | Adds missing return types and replaces `any` with typed alternatives |

## Architecture Pattern

All orchestrators follow the **"thin rule, thick orchestrator"** pattern:

- **Rules** (in `../rules/`): Provide high-level coordination, configuration, and validation
- **Orchestrators** (this directory): Handle complex AST manipulation and code generation
- **API Integration**: Use `DependencyAnalyzer`, `TemplateAnalyzer`, and other APIs for analysis
- **Context-Based DI**: Receive dependencies through context objects, not constructors

## Usage in Rules

```typescript
export class FacadePatternRule implements TransformRule {
  async transform(context: TransformContext): Promise<TransformResult> {
    const orchestrator = new FacadePatternOrchestrator();

    // Use orchestrator for complex logic
    const analysis = await orchestrator.analyzeComponentComplexity(context);
    if (!analysis.shouldTransform) {
      return { modified: false };
    }

    const facadeContent = orchestrator.generateFacadeServiceContent(context);
    const updatedComponent = orchestrator.updateComponentToUseFacade(context);

    return {
      modified: true,
      content: updatedComponent,
      additionalFiles: [{ path: facadePath, content: facadeContent }],
    };
  }
}
```

## Testing

Each orchestrator has comprehensive unit tests in `../../__tests__/transform-rules/` that validate:

- Correct AST analysis and pattern detection
- Proper code generation with syntax validation
- Edge cases and error handling
- Integration with the transformation pipeline

## Dependencies

Orchestrators use:

- **ts-morph**: For TypeScript AST manipulation
- **Public API**: `DependencyAnalyzer`, `TemplateAnalyzer`, `SymbolLocator`
- **Plugin Context**: `TransformContext` with project and configuration access
- **Utility Functions**: Type checking, import management, code formatting

## Contributing

When adding new orchestrators:

1. Follow the existing naming convention: `{transformation-type}-orchestrator.ts`
2. Implement the orchestrator interface with analysis and generation methods
3. Add comprehensive unit tests with real-world fixtures
4. Update this README with the new orchestrator documentation
5. Ensure integration with the corresponding transformation rule
