All files / core/engine template-renderer.service.ts

97.22% Statements 35/36
84% Branches 21/25
100% Functions 4/4
97.05% Lines 33/34

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 715x 5x     5x         17x 17x 15x   2x                 15x 15x 15x 15x 15x   15x 905x 905x   905x 71x 53x 53x   834x 18x 18x 816x 18x 18x     798x     905x     15x 14x     15x 67x     67x           67x          
import { Injectable } from '@nestjs/common';
import { render } from 'ejs';
 
@Injectable()
export class TemplateRendererService {
  render(
    templateContent: string,
    context: Record<string, unknown>
  ): string[] {
    try {
      const rendered = render(templateContent, context);
      return this.splitIntoArgs(rendered);
    } catch (error) {
      throw new Error(
        `Template rendering failed: ${
          error instanceof Error ? error.message : String(error)
        }. Template: ${templateContent.substring(0, 100)}...`
      );
    }
  }
 
  private splitIntoArgs(rendered: string): string[] {
    const args: string[] = [];
    let currentArg = '';
    let inQuotes = false;
    let quoteChar = '';
    let i = 0;
 
    while (i < rendered.length) {
      const char = rendered[i];
      const isWhitespace = /\s/.test(char);
 
      if (!inQuotes && isWhitespace) {
        if (currentArg.trim()) {
          args.push(currentArg.trim());
          currentArg = '';
        }
      } else if (!inQuotes && (char === '"' || char === '\'')) {
        inQuotes = true;
        quoteChar = char;
      } else if (inQuotes && char === quoteChar) {
        inQuotes = false;
        quoteChar = '';
        // Don't include the closing quote in the arg
      } else {
        currentArg += char;
      }
 
      i++;
    }
 
    if (currentArg.trim()) {
      args.push(currentArg.trim());
    }
 
    return args
      .filter((arg) => arg.length > 0)
      .map((arg) => {
        // Remove surrounding quotes if present
        Iif (
          (arg.startsWith('"') && arg.endsWith('"')) ||
          (arg.startsWith('\'') && arg.endsWith('\''))
        ) {
          return arg.slice(1, -1);
        }
        return arg;
      });
  }
}