npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2025 – Pkg Stats / Ryan Hefner

@bernierllc/email-template-engine

v1.0.2

Published

Email template processing engine with compilation, rendering, and text generation

Readme

@bernierllc/email-template-engine

Email template processing engine providing template compilation, variable substitution, base template composition, text version generation, and validation.

Installation

npm install @bernierllc/email-template-engine

Features

  • Handlebars Template Compilation - Compile and render templates with variable substitution
  • Base Template Composition - Combine header, content, and footer into complete emails
  • Variable Extraction - Automatically extract and analyze template variables
  • Text Version Generation - Convert HTML to plain text for email clients
  • Template Validation - Syntax checking and error detection
  • Custom Helpers - Extend with custom Handlebars helpers
  • TypeScript Support - Full type definitions included
  • Zero Dependencies on @bernierllc - Pure core package

Usage

Basic Template Rendering

import { EmailTemplateEngine } from '@bernierllc/email-template-engine';

const engine = new EmailTemplateEngine();

// Simple variable substitution
const result = engine.render(
  '<p>Hello {{name}}!</p>',
  { name: 'John' }
);

console.log(result.data); // '<p>Hello John!</p>'

Building Complete Email Templates

import { buildEmailTemplate } from '@bernierllc/email-template-engine';

const result = await buildEmailTemplate(
  {
    headerHtml: '<html><body><header>Company Logo</header>',
    footerHtml: '<footer>&copy; 2025 Company</footer></body></html>',
  },
  '<h1>{{title}}</h1><p>{{message}}</p>',
  {
    title: 'Welcome',
    message: 'Thank you for joining!',
  }
);

console.log(result.data?.html);  // Complete HTML email
console.log(result.data?.text);  // Plain text version

Variable Extraction

import { extractTemplateVariables } from '@bernierllc/email-template-engine';

const template = '<h1>{{title}}</h1><p>{{user.name}}</p>';
const result = extractTemplateVariables(template);

console.log(result.data);
// [
//   { name: 'title', path: 'title', type: 'string', occurrenceCount: 1, ... },
//   { name: 'user', path: 'user.name', type: 'object', occurrenceCount: 1, ... }
// ]

Template Validation

import { validateEmailTemplate } from '@bernierllc/email-template-engine';

const result = validateEmailTemplate('<p>{{name}}</p>');

if (!result.data?.isValid) {
  console.error('Validation errors:', result.data?.errors);
}

HTML to Text Conversion

import { generateTextFromHtml } from '@bernierllc/email-template-engine';

const result = generateTextFromHtml(
  '<h1>Welcome</h1><p>Check out our <a href="https://example.com">website</a></p>'
);

console.log(result.data);
// WELCOME
//
// Check out our website [https://example.com]

API Reference

EmailTemplateEngine

Main class for template processing.

Methods

compile(template: string, options?: CompilationOptions): TemplateResult<HandlebarsTemplateDelegate>

Compile a Handlebars template into a reusable function.

Options:

  • strict - Throw on undefined variables (default: false)
  • noEscape - Disable HTML escaping (default: false)
  • helpers - Custom Handlebars helpers
  • partials - Template partials
render(template: string, data: Record<string, unknown>, options?: CompilationOptions): TemplateResult<string>

Compile and render template with data in one step.

buildCompleteTemplate(baseTemplate: BaseTemplate, content: string, variables?: Record<string, unknown>): Promise<TemplateResult<BuiltTemplate>>

Build complete email by combining header, content, and footer.

Returns:

  • html - Complete rendered HTML
  • text - Plain text version
  • variables - Extracted template variables
  • metadata - Build metrics (time, variable count, content length)
generateTextVersion(html: string, options?: TextGenerationOptions): TemplateResult<string>

Convert HTML to plain text.

Options:

  • wordwrap - Wrap at N characters (default: 80)
  • preserveNewlines - Keep line breaks (default: true)
  • uppercaseHeadings - Uppercase headings (default: true)
extractVariables(template: string): TemplateResult<TemplateVariable[]>

Extract all variables from template.

validateTemplate(template: string): TemplateResult<TemplateValidationResult>

Validate template syntax and structure.

Convenience Functions

All methods are available as standalone functions:

import {
  compileTemplate,
  renderTemplate,
  buildEmailTemplate,
  generateTextFromHtml,
  extractTemplateVariables,
  validateEmailTemplate,
} from '@bernierllc/email-template-engine';

Default Helpers

Built-in Handlebars helpers included:

  • formatDate - Format date objects
  • uppercase - Convert string to uppercase
  • lowercase - Convert string to lowercase
const result = engine.render(
  '<p>{{uppercase name}}</p>',
  { name: 'john' }
);
// <p>JOHN</p>

Custom Helpers

Add your own Handlebars helpers:

const engine = new EmailTemplateEngine();

const result = engine.render(
  '<p>Price: {{currency amount}}</p>',
  { amount: 99.5 },
  {
    helpers: {
      currency: (value: number) => `$${value.toFixed(2)}`,
    },
  }
);
// <p>Price: $99.50</p>

Error Handling

All methods return a TemplateResult<T> object:

const result = engine.render(template, data);

if (!result.success) {
  console.error('Template error:', result.error);
  return;
}

// Safe to use result.data
console.log(result.data);

Examples

Welcome Email

const engine = new EmailTemplateEngine();

const welcomeTemplate = `
  <h1>Welcome to {{companyName}}</h1>
  <p>Hi {{userName}},</p>
  <p>Your account email: {{email}}</p>
  <a href="{{verificationLink}}">Verify Account</a>
`;

const result = await engine.buildCompleteTemplate(
  {
    headerHtml: '<html><body style="font-family: Arial;">',
    footerHtml: '<footer>&copy; 2025 Company</footer></body></html>',
  },
  welcomeTemplate,
  {
    companyName: 'ACME Corp',
    userName: 'John Doe',
    email: '[email protected]',
    verificationLink: 'https://example.com/verify/abc123',
  }
);

Order Confirmation

const orderTemplate = `
  <h1>Order Confirmation</h1>
  <p>Order #{{orderNumber}}</p>
  <p>Total: ${{total}}</p>
  <ul>
    {{#each items}}
      <li>{{this.name}} - ${{this.price}}</li>
    {{/each}}
  </ul>
`;

const result = await buildEmailTemplate(
  baseTemplate,
  orderTemplate,
  {
    orderNumber: '12345',
    total: '99.99',
    items: [
      { name: 'Product A', price: '49.99' },
      { name: 'Product B', price: '50.00' },
    ],
  }
);

Integration Status

  • Logger: Optional - Logs compilation errors and validation warnings when provided
  • Docs-Suite: Ready - Complete API documentation with examples
  • NeverHub: Optional - Publishes template processing events when available

Logger Integration

import { EmailTemplateEngine } from '@bernierllc/email-template-engine';
import { Logger } from '@bernierllc/logger';

const logger = new Logger({ service: 'email-template-engine' });
const engine = new EmailTemplateEngine({ logger });

// Logger automatically logs:
// - Template compilation errors
// - Variable extraction issues
// - Text generation failures

Performance

  • Template compilation: <10ms for typical email templates (5KB)
  • Complete template building: <50ms including text generation
  • Variable extraction: <5ms for templates with 50+ variables
  • Compilation cache available for repeated use

TypeScript Support

Full TypeScript definitions included:

import type {
  BaseTemplate,
  BuiltTemplate,
  CompilationOptions,
  TemplateResult,
  TemplateValidationResult,
  TemplateVariable,
  TextGenerationOptions,
} from '@bernierllc/email-template-engine';

See Also

License

Copyright (c) 2025 Bernier LLC. All rights reserved.

This package is licensed under a limited-use license. See LICENSE file for details.