All files / slidev template-processor.ts

100% Statements 35/35
100% Branches 18/18
100% Functions 4/4
100% Lines 35/35

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 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128                                          1x         27x   37x     37x     37x 37x 46x 42x     4x         33x 2x       31x 2x     29x                           1x 20x 20x     20x 28x     20x                                 1x       13x 13x   13x 18x 18x   18x 22x 17x   5x 5x         18x 2x 2x         13x          
/**
 * Replace placeholders in a template string with values from a data object.
 * Supports nested JSON data using dot notation (e.g., {{user.name}}).
 *
 * @param template - The template string containing placeholders in {{key}} format
 * @param data - The data object with values to replace placeholders
 * @returns The processed template with placeholders replaced
 *
 * @example
 * // Simple replacement
 * replaceTemplatePlaceholders("Hello {{name}}", { name: "World" });
 * // Returns: "Hello World"
 *
 * @example
 * // Nested data replacement
 * replaceTemplatePlaceholders(
 *   "{{user.name}} is {{user.age}} years old",
 *   { user: { name: "Alice", age: 30 } }
 * );
 * // Returns: "Alice is 30 years old"
 */
export function replaceTemplatePlaceholders(
  template: string,
  data: Record<string, any>
): string {
  // Replace placeholders with support for nested paths (e.g., {{user.name}})
  return template.replace(/\{\{([^}]+)\}\}/g, (match, path) => {
    // Trim whitespace from the path
    const trimmedPath = path.trim();
 
    // Split the path by dots for nested access
    const keys = trimmedPath.split('.');
 
    // Traverse the data object to get the value
    let value: any = data;
    for (const key of keys) {
      if (value && typeof value === 'object' && key in value) {
        value = value[key];
      } else {
        // If path doesn't exist, return original placeholder
        return match;
      }
    }
 
    // Convert value to string, handling various types
    if (value === null || value === undefined) {
      return match; // Return original placeholder if value is null/undefined
    }
 
    // Handle arrays and objects by converting to JSON
    if (typeof value === 'object') {
      return JSON.stringify(value);
    }
 
    return String(value);
  });
}
 
/**
 * Extract all placeholder keys from a template string
 *
 * @param template - The template string to analyze
 * @returns Array of unique placeholder keys found in the template
 *
 * @example
 * extractPlaceholders("Hello {{name}}, you have {{count}} messages");
 * // Returns: ["name", "count"]
 */
export function extractPlaceholders(template: string): string[] {
  const placeholders = new Set<string>();
  const regex = /\{\{([^}]+)\}\}/g;
  let match;
 
  while ((match = regex.exec(template)) !== null) {
    placeholders.add(match[1].trim());
  }
 
  return Array.from(placeholders);
}
 
/**
 * Validate that all required placeholders are present in the data object
 *
 * @param template - The template string to validate
 * @param data - The data object to check against
 * @returns Object with isValid flag and array of missing placeholders
 *
 * @example
 * validatePlaceholders("Hello {{name}}", { name: "World" });
 * // Returns: { isValid: true, missing: [] }
 *
 * validatePlaceholders("Hello {{name}}", {});
 * // Returns: { isValid: false, missing: ["name"] }
 */
export function validatePlaceholders(
  template: string,
  data: Record<string, any>
): { isValid: boolean; missing: string[] } {
  const placeholders = extractPlaceholders(template);
  const missing: string[] = [];
 
  for (const placeholder of placeholders) {
    const keys = placeholder.split('.');
    let value: any = data;
 
    for (const key of keys) {
      if (value && typeof value === 'object' && key in value) {
        value = value[key];
      } else {
        missing.push(placeholder);
        break;
      }
    }
 
    // Check if final value is null/undefined
    if (value === null || value === undefined) {
      if (!missing.includes(placeholder)) {
        missing.push(placeholder);
      }
    }
  }
 
  return {
    isValid: missing.length === 0,
    missing
  };
}