npm package: @js-utility/template-engine
Description: A lightweight and flexible JavaScript template engine for rendering dynamic content, supporting both CommonJS and ES modules.
Author: Pradip Sabhadiya
Latest version: 0.0.1005

# Transform Engine

A lightweight, flexible string transformation engine for JavaScript and TypeScript. Transform Engine enables dynamic string interpolation, inline expressions, and powerful formatting with a clean, customizable syntax.

If this package has been helpful to you, your support goes a long way in helping maintain it, improve its features, and build more open-source tools like it.
[Buy Me a Coffee ☕](https://buymeacoffee.com/pradip_sabhadiya)

---

## ✨ Features

- **Inline Expressions:** Use `{{ ... }}` to embed dynamic expressions directly in your strings.
- **Built-in Methods:** Perform calculations, string manipulations, and more with a rich set of built-in methods.
- **Chained Formatters:** Pipe results through formatters for advanced formatting.
- **Customizable & Extensible:** Easily extend with your own methods and formatters (API coming soon).
- **Zero Dependencies:** Lightweight and fast, suitable for any project.
- **AI Generated, well formatted & well tested:** Unit tested with automation testing and verified by humans. It is type safe, null safe.

---

## 📦 Installation

```bash
npm install @js-utility/template-engine
```

---

## 🚀 Usage

```ts
import { TransformEngine } from '@js-utility/template-engine';

const input = 'Total: {{ sum:10:20 | currency "US":2 }}';

const output = TransformEngine(input, {});

console.log(output); // Total: $30.00
```

---

## 🧠 Syntax

Each placeholder follows this pattern:

```
{{ method:param1:param2 | formatter:param1:param2 }}
```

- **method:** The function to execute (e.g., `sum`, `row.name`)
- **params:** (Optional) Arguments to the method (numbers, strings, variables), separated by colons (:)
- **formatter:** (Optional) Pipe output through a formatter (e.g., `currency`, `capitalize`)
- **formatParams:** (Optional) Arguments to the formatter (numbers, strings, variables), separated by colons (:)

**Examples:**

```text
{{ sum:2:3 }}                       => 5
{{ row.name | capitalize }}         => John doe
{{ row.amount | currency 'US':2 }}  => $1,234.57
{{ sum:10:20 | number 'US':1 }}     => 30.0
{{ 0.25 | percentage 2 }}           => 25.00%
```

---

## 📘 API

| Function | Description |
|----------|-------------|
| **TransformEngine(text: string, context?: object, options?: object): string** | Transforms the input string by evaluating all placeholders. |

### Parameters

| Name     | Type    | Description                                      |
|----------|---------|--------------------------------------------------|
| text     | string  | The input string containing placeholders.         |
| context  | object  | (Optional) Data object for expression resolution. |
| options  | object  | (Optional) Reference Resolution Parameter, that supports context format to key value pair for references. It is default to off. |

**Returns:**  
`string` — The transformed string with all placeholders evaluated.

---

## 🛠️ Built-in Methods

| Method    | Description                |
|-----------|---------------------------|
| sum       | Adds all arguments         |
| subtract  | Subtracts numbers          |
| avg       | Returns average            |
| min       | Minimum value              |
| max       | Maximum value              |
| count     | Counts number of items     |
| multiply  | Multiplies all numbers     |
| divide    | Divides numbers            |
| concat    | Concatenates strings       |
| mod       | Modulo                     |
| pow       | Exponentiation             |
| abs       | Absolute value             |
| floor     | Rounds down                |
| ceil      | Rounds up                  |
| sqrt      | Square root                |
| log       | Natural logarithm          |
| echo      | Returns the first argument |
| length    | Length of string or array  |
| size      | Alias of length            |

---

## 🎨 Built-in Formatters

| Formatter   | Description                                                                 |
|-------------|-----------------------------------------------------------------------------|
| upper       | Converts to uppercase                                                       |
| lower       | Converts to lowercase                                                       |
| round       | Rounds to nearest integer                                                   |
| number      | Formats number with fraction points (e.g., `number 'US':1:2`)               |
| date        | Formats as date                                                             |
| currency    | Formats as currency (e.g., `currency "US":0:2` for country and decimals)    |
| percentage  | Formats as percent (e.g., `percentage 0:2` for decimals)         	        |
| json        | Converts to JSON string                                                     |
| capitalize  | Capitalizes the first letter                                                |
| trim        | Trims whitespace                                                            |
| length      | Gets length of string or array                                              |
| camel       | Converts to camelCase                                                       |
| snake       | Converts to snake_case                                                      |
| strip       | Removes non-alphanumerics                                                   |
| prefix      | Adds a prefix (e.g., `prefix:"ID-"`)                                        |
| suffix      | Adds a suffix                                                               |
| repeat      | Repeats a string (e.g., `repeat:3`)                                         |
| title       | Converts to Title Case                                                      |

**Note:**  
- `currency` and `number` use the same parameter structure:  
  `formatter alpha_2_country_code:min_fraction:max_fraction`  
  - `alpha_2_country_code`: e.g., `"US"`  
  - `min_fraction` (optional): Minimum Number of decimal places. default to '0'
  - `max_fraction` (optional): Maximum Number of decimal places. default to 'min_fraction'

---

## 🧩 Placeholder Regex

```ts
const PLACEHOLDER_REGEX = /\{\{\s*([^\s|}]+)(?:\s+([^|}]*?))?(?:\s*\|\s*([^\s|}]+)(?:\s+([^}]*?))?)?\s*\}\}/g;
```

- Supports: `{{ method args | formatter params }}`
- Flexible whitespace and quoted string arguments (`"..."`, `'...'`)

---

## 📚 Examples

```ts
TransformEngine('Hello {{ row.name | capitalize }}!', { row: { name: 'sarah' } });
// => Hello Sarah!

TransformEngine('Price: {{ sum 10:15 | currency "US":2 }}');
// => Price: $25.00

TransformEngine('{{ echo "hello world" | upper }}');
// => HELLO WORLD

TransformEngine('Value: {{ sum 1520.856:864.69 | currency "US":1 }}');
// => Value: $2,385.5

TransformEngine('Percent: {{ 0.8320 | percentage 1 }}');
// => Percent: 83.2%
```

---
## 📘 TypeScript Support
This package is built with full TypeScript support. All functions are type-safe, and type definitions are bundled, so you get autocomplete, inline documentation, and compile-time safety out of the box, no need to install `@types`.


---
## 🧪 Testing
This package is thoroughly tested using Jest, with a focus on correctness, edge cases, and null-safety.


---
## 🤝 Contributing
This project is maintained privately. While direct contributions (e.g., pull requests or code changes) are not open to the public, **feedback, suggestions, and issue reports are always welcome.**

If you notice any bugs, edge cases, or have ideas for improvement, feel free to reach out or open an issue (if access is available). Your input helps make the package more robust and useful for everyone!


---
## 💖 Support / Donate

If you find this package useful, consider supporting its development. Your support helps maintain the project, improve documentation, and add new features.

Support as through :

- [Buy Me a Coffee ☕](https://buymeacoffee.com/pradip_sabhadiya)
- [GitHub](https://github.com/sponsors/AIWebBuilder)

---
## 💬 Support & Feedback

Have ideas, suggestions, or found a bug? I'd love to hear from you!

- **Feedback**: Whether it’s a feature request or an edge case you'd like handled, your input helps improve the package.
- **Issues**: If you run into a bug or unexpected behavior, feel free to open an issue (if the repo is accessible).
- **Reach Out**: You can also reach out directly for feedback or discussion via email or the contact details in the repository.

Your feedback helps shape better tools for everyone using this package.