Angular Modernizer
    Preparing search index...

    Enhanced Parser Strategy - ts-morph with preprocessing for complex projects.

    This parser is optimized for projects with custom patterns that standard ts-morph cannot handle directly. It provides preprocessing to:

    • Resolve custom path aliases (@shared/, @domain/, etc.)
    • Filter false positive syntax errors from external decorators
    • Handle complex constructor patterns

    Compatibility:

    • Projects with external decorators (e.g., @PageComponent)
    • Projects with custom path aliases (@shared/, @domain/)
    • Projects with complex constructor patterns
    • Standard Angular CLI projects (with overhead)
    • Projects requiring Babel parser (fallback to CustomParserStrategy)

    Reliability:

    • 0.8 base reliability (moderate)
    • -0.1 penalty for external decorators
    • -0.05 penalty for path aliases
    • -0.05 penalty for complex constructors
    • Minimum: 0.6 (still reliable for most transformations)

    Performance Characteristics:

    • Parse time: <5ms baseline + <1ms path resolution + <1ms false positive filtering
    • Total overhead: <10% vs StandardParserStrategy
    • Memory usage: ~50MB (single Project instance)
    • Preprocessing: Cached for performance
    const parser = new EnhancedParserStrategy(project);

    // Check if parser can handle project
    const context: ProjectContext = {
    projectRoot: '/path/to/project',
    hasCustomDecorators: true,
    hasPathAliases: true,
    hasComplexConstructors: false,
    angularVersion: '17.0.0'
    };

    if (parser.canHandle(context)) {
    const reliability = parser.getReliability(context); // 0.65
    const ast = await parser.parse('src/app/app.component.ts', fileContent);
    const result = await parser.transform(ast, [standaloneRule]);
    }
    const parser = new EnhancedParserStrategy(project, {
    preserveAliases: true, // Keep @shared/* as-is
    verboseLogging: true, // Log preprocessing stats
    tsconfigPath: './tsconfig.app.json',
    baseDir: '/path/to/project/src'
    });

    Implements

    Index

    Constructors

    • Initialize the Enhanced Parser Strategy.

      Uses SharedProjectManager's singleton Project by default for standalone usage. Accepts optional Project parameter for Kernel integration (backward compatible).

      Parameters

      • Optionalproject: Project

        Optional ts-morph Project instance (defaults to SharedProjectManager)

      • Optionalconfig: EnhancedParserStrategyConfig

        Configuration options for enhanced parser

      Returns EnhancedParserStrategy

      const parser = new EnhancedParserStrategy(undefined, {
      preserveAliases: false,
      verboseLogging: true
      });
      // Parser uses SharedProjectManager singleton (50MB shared)
      const project = new Project({ tsConfigFilePath: './tsconfig.json' });
      const parser = new EnhancedParserStrategy(project, {
      preserveAliases: false
      });
      // Parser uses Kernel's Project instance

    Properties

    name: "enhanced" = 'enhanced'

    Parser name identifier.

    Used for logging, metrics, and parser selection.

    Methods

    • Check if this parser can handle the given project context.

      The enhanced parser handles projects with:

      • External decorators (custom decorators like @PageComponent)
      • Custom path aliases (@shared/, @domain/, etc.)
      • Complex constructor patterns

      Decision Logic:

      • Returns true if project has any custom patterns
      • Returns false if project is standard Angular CLI (use StandardParser instead)

      Performance: <1ms (simple boolean checks)

      Parameters

      Returns boolean

      true if parser can handle this project, false otherwise

      const context: ProjectContext = {
      projectRoot: '/app',
      hasCustomDecorators: true,
      hasPathAliases: false,
      hasComplexConstructors: false,
      angularVersion: '16.0.0'
      };
      parser.canHandle(context); // true
      const context: ProjectContext = {
      projectRoot: '/app',
      hasCustomDecorators: false,
      hasPathAliases: false,
      hasComplexConstructors: false,
      angularVersion: '17.0.0'
      };
      parser.canHandle(context); // false (use StandardParser)
    • Get preprocessing statistics for monitoring and debugging.

      Returns cumulative statistics about preprocessing operations:

      • Files processed
      • Path aliases resolved
      • False positives filtered
      • Average preprocessing time

      Returns {
          avgPreprocessingTime: number;
          falsePositivesFiltered: number;
          filesProcessed: number;
          pathAliasesResolved: number;
      }

      Preprocessing statistics object

      • avgPreprocessingTime: number

        Average preprocessing time per file in milliseconds (0 without files).

      • falsePositivesFiltered: number

        Syntax errors removed as false positives.

      • filesProcessed: number

        Files parsed since the last reset.

      • pathAliasesResolved: number

        Path aliases resolved across those files.

      const stats = parser.getPreprocessingStats();
      console.info(`Processed ${stats.filesProcessed} files`);
      console.info(`Resolved ${stats.pathAliasesResolved} path aliases`);
      console.info(`Filtered ${stats.falsePositivesFiltered} false positives`);
      console.info(`Avg time: ${stats.avgPreprocessingTime}ms per file`);
    • Calculate reliability score for this parser on the given project.

      The enhanced parser provides moderate reliability (0.6-0.8) based on project complexity. More complex projects have lower reliability scores.

      Reliability Calculation:

      • Base reliability: 0.8 (moderate confidence)
      • External decorators: -0.1 penalty (parser may not recognize all decorators)
      • Path aliases: -0.05 penalty (resolution may fail for dynamic aliases)
      • Complex constructors: -0.05 penalty (may miss some edge cases)
      • Minimum: 0.6 (still reliable enough for most transformations)

      Performance: <1ms (simple arithmetic)

      Parameters

      Returns number

      Reliability score between 0.6 and 0.8

      const context: ProjectContext = {
      projectRoot: '/app',
      hasCustomDecorators: false,
      hasPathAliases: true,
      hasComplexConstructors: false,
      angularVersion: '17.0.0'
      };
      parser.getReliability(context); // 0.75 (0.8 - 0.05)
      const context: ProjectContext = {
      projectRoot: '/app',
      hasCustomDecorators: true,
      hasPathAliases: true,
      hasComplexConstructors: true,
      angularVersion: '16.0.0'
      };
      parser.getReliability(context); // 0.6 (0.8 - 0.1 - 0.05 - 0.05)
    • Parse a file and return an Abstract Syntax Tree with preprocessing.

      This method implements the preprocessing pipeline:

      1. Path Alias Resolution: Resolve @shared/, @domain/, etc. to relative paths
      2. ts-morph Parsing: Parse preprocessed content with TypeScript compiler
      3. False Positive Filtering: Remove false positive syntax errors

      Preprocessing Steps:

      • Path aliases resolved before parsing (prevents "Cannot find module" errors)
      • False positives filtered after parsing (removes incorrect syntax errors)
      • External decorators detected and logged

      Error Handling:

      • Returns errors in AST.errors array (after filtering)
      • Never throws unless catastrophic failure
      • Preprocessing errors logged but don't block parsing

      Performance:

      • Parse time: <5ms baseline (ts-morph)
      • Path resolution: <1ms (cached)
      • False positive filtering: <1ms
      • Total: <7ms per file (<10% overhead vs standard)

      Parameters

      • file: string

        File path (used for error reporting and relative path calculation)

      • content: string

        File content to parse

      Returns Promise<ParserAST>

      Promise resolving to AST with SourceFile, diagnostics, and preprocessing metadata

      const content = `
      import { SharedModule } from '@shared/modules';
      import { PageComponent } from '@shared/decorators/page';

      @PageComponent({ id: 'user-component' })
      @Component({ selector: 'app-user', template: '' })
      export class UserComponent {}
      `;
      const ast = await parser.parse('src/app/user.component.ts', content);
      console.info(`Path aliases resolved: ${ast.pathAliasesResolved}`); // 2
      console.info(`False positives filtered: ${ast.falsePositivesFiltered}`); // 1
      console.info(`Errors: ${ast.errors.length}`); // 0
      const content = `
      import { Component } from '@angular/core';
      @Component({ selector: 'app-user' }) // Missing closing brace
      export class UserComponent {
      `;
      const ast = await parser.parse('user.component.ts', content);
      console.info(`Errors: ${ast.errors.length}`); // 1+ (genuine syntax error)
      ast.errors.forEach(err => console.error(`Line ${err.line}: ${err.message}`));
    • Reset preprocessing statistics.

      Useful for benchmarking or isolating statistics for specific operations.

      Returns void

      parser.resetPreprocessingStats();
      // Process files...
      const stats = parser.getPreprocessingStats();
      // Stats now only reflect operations since reset
    • Apply transformation rules to an AST.

      This method executes transformation rules on the parsed AST and returns the transformation result with metadata. Path aliases are preserved or resolved based on configuration.

      Transformation Process:

      1. Create transform context with sourceFile and project
      2. Execute each rule's transform() method
      3. Aggregate results (modified, changeCount)
      4. Detect syntax errors after transformation
      5. Return result with metadata (including preprocessing stats)

      Alias Handling:

      • If preserveAliases is true: Aliases are never resolved (preprocessing skipped)
      • If preserveAliases is false: Aliases are resolved before parsing (default)
      • No explicit "restore" needed - aliases are either preserved from start or resolved

      Error Handling:

      • Never throws errors
      • Returns result with modified=false on failure
      • Syntax errors after transformation reported in metadata

      Performance:

      • Transform time: <1s per file (typical)
      • No post-transformation preprocessing (aliases handled during parse)

      Parameters

      Returns Promise<ParserTransformResult>

      Promise resolving to transformation result

      const ast = await parser.parse('component.ts', content);
      const rules = [standaloneRule];
      const result = await parser.transform(ast, rules);

      if (result.modified) {
      console.info(`Applied ${rules.length} rules`);
      console.info(`Changed ${result.changeCount} lines`);
      console.info(`Parser: ${result.metadata?.parserStrategy}`);
      console.info(`False positives filtered: ${result.metadata?.falsePositivesFiltered}`);
      console.info(`Output: ${ast.sourceFile.getFullText()}`);
      }
      const result = await parser.transform(ast, rules);
      if (!result.modified && result.metadata?.syntaxErrors?.length) {
      console.error('Transformation introduced syntax errors:');
      result.metadata.syntaxErrors.forEach(err => console.error(` - ${err}`));
      }