lite-template 0.0.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.gitattributes +2 -0
- package/.github/workflows/publish.yml +32 -0
- package/LICENSE +21 -0
- package/README.md +116 -0
- package/dist/index.d.ts +14 -0
- package/dist/index.js +72 -0
- package/package.json +43 -0
- package/src/index.ts +79 -0
- package/tsconfig.json +14 -0
package/.gitattributes
ADDED
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
name: Publish to NPM
|
|
2
|
+
on:
|
|
3
|
+
release:
|
|
4
|
+
types: [published]
|
|
5
|
+
workflow_dispatch:
|
|
6
|
+
|
|
7
|
+
permissions:
|
|
8
|
+
contents: read
|
|
9
|
+
id-token: write
|
|
10
|
+
|
|
11
|
+
jobs:
|
|
12
|
+
publish:
|
|
13
|
+
runs-on: ubuntu-latest
|
|
14
|
+
steps:
|
|
15
|
+
- uses: actions/checkout@v6
|
|
16
|
+
|
|
17
|
+
- name: Setup Node.js
|
|
18
|
+
uses: actions/setup-node@v6
|
|
19
|
+
with:
|
|
20
|
+
node-version: '22'
|
|
21
|
+
registry-url: 'https://registry.npmjs.org'
|
|
22
|
+
|
|
23
|
+
- name: Install dependencies
|
|
24
|
+
run: npm install
|
|
25
|
+
|
|
26
|
+
- name: Build package
|
|
27
|
+
run: npm run build
|
|
28
|
+
|
|
29
|
+
- name: Publish to npm
|
|
30
|
+
run: npm publish --access public
|
|
31
|
+
env:
|
|
32
|
+
NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
|
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2025-present docmd.io
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
ADDED
|
@@ -0,0 +1,116 @@
|
|
|
1
|
+
# lite-template
|
|
2
|
+
|
|
3
|
+
**High-Performance, Async-Safe JavaScript Template Engine.**
|
|
4
|
+
|
|
5
|
+
`lite-template` is a modern, ultra-lightweight template engine designed for the needs of today's asynchronous web applications. It serves as a drop-in replacement for the aging, sync-heavy legacy of **EJS**, while introducing native, first-class support for `async/await` throughout the entire template lifecycle.
|
|
6
|
+
|
|
7
|
+
## Technical Specifications
|
|
8
|
+
|
|
9
|
+
- **Runtime**: Node.js (v18+), Browser (Modern), Cloudflare Workers.
|
|
10
|
+
- **Language**: Core engine logic written in TypeScript.
|
|
11
|
+
- **Compiler**: Direct-to-string AsyncFunction compilation.
|
|
12
|
+
- **Distribution**: Native ESM (CommonJS not supported).
|
|
13
|
+
|
|
14
|
+
## The Architecture: Async-First Compilation
|
|
15
|
+
|
|
16
|
+
Most legacy engines (like `EJS`) were built in the pre-Promise era of Node.js. They execute template logic synchronously, which can block the event loop in high-throughput environments or when templates require database/API interaction.
|
|
17
|
+
|
|
18
|
+
`lite-tpl` compiles logic directly into native, V8-optimized **`AsyncFunction`** objects. This enables seamless, non-blocking template execution that leverages existing JavaScript primitives for maximum efficiency.
|
|
19
|
+
|
|
20
|
+
### Technical Limitations (Design Philosophy)
|
|
21
|
+
|
|
22
|
+
To prioritize performance and maintain its minimalist footprint (<10KB), `lite-template` purposefully omits several non-core EJS features:
|
|
23
|
+
|
|
24
|
+
1. **Strictly Logic-Driven**: Unlike EJS, it does not include a complex built-in caching layer. Reusable templates should be pre-compiled using `compile()` at the application level.
|
|
25
|
+
2. **Explicit Scope**: Uses the `with` block for performance. Variables must be defined within the provided `data` object to be accessible; it does not automatically pull from global scope.
|
|
26
|
+
3. **No Layout System**: Does not include a proprietary EJS `<%- layout() %>` system. Layout/Include handling is left to the developer via standard async calls (e.g., `<%- await include(...) %>`).
|
|
27
|
+
4. **No Middleware Integration**: This is a pure string-to-HTML engine—no native Express.js view-engine integration is included out of the box.
|
|
28
|
+
5. **ESM Only**: Built exclusively for modern ESM toolchains.
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
* **Async Native Engine**: Supports `await` natively within any `<% ... %>` or `<%= ... %>` block without messy workarounds.
|
|
32
|
+
* **Optimal Performance**: Compiles template strings directly into optimized JavaScript function strings, skipping the AST-processing overhead of heavier engines.
|
|
33
|
+
* **Predictable Scoping**: Leverages the JavaScript `with` scope for safe, predictable, and performant variable resolution.
|
|
34
|
+
* **Micro Footprint**: Under 10KB. Eliminates the hundreds of cascading dependencies common in larger engines.
|
|
35
|
+
* **Modern Compatibility**: Built for standard **EJS syntax** but engineered for the modern ES Module ecosystem.
|
|
36
|
+
|
|
37
|
+
## Installation
|
|
38
|
+
|
|
39
|
+
```bash
|
|
40
|
+
npm install lite-template
|
|
41
|
+
```
|
|
42
|
+
|
|
43
|
+
## Comparisons
|
|
44
|
+
|
|
45
|
+
| Feature | EJS | lite-template |
|
|
46
|
+
| :--- | :--- | :--- |
|
|
47
|
+
| **Logic** | Sync-First | **Async-Native** |
|
|
48
|
+
| **Parsing** | Bulky AST | **Direct-to-Function** |
|
|
49
|
+
| **Weight (approx)** | ~50KB | **<10KB** |
|
|
50
|
+
| **Dependencies** | Multiple (jake, async, etc.) | **Zero** |
|
|
51
|
+
|
|
52
|
+
## Quick Start
|
|
53
|
+
|
|
54
|
+
### Basic Rendering
|
|
55
|
+
|
|
56
|
+
```javascript
|
|
57
|
+
import { render } from 'lite-tpl';
|
|
58
|
+
|
|
59
|
+
const template = `<h2>Hello, <%= name %></h2>`;
|
|
60
|
+
const html = await render(template, { name: "System" });
|
|
61
|
+
```
|
|
62
|
+
|
|
63
|
+
### Advanced Loops and Logic
|
|
64
|
+
|
|
65
|
+
```javascript
|
|
66
|
+
const template = `
|
|
67
|
+
<div class="user-list">
|
|
68
|
+
<% users.forEach(user => { %>
|
|
69
|
+
<div class="user-card"><%= user.name %></div>
|
|
70
|
+
<% }); %>
|
|
71
|
+
</div>
|
|
72
|
+
`;
|
|
73
|
+
|
|
74
|
+
const html = await render(template, {
|
|
75
|
+
users: [{ name: "Alice" }, { name: "Bob" }]
|
|
76
|
+
});
|
|
77
|
+
```
|
|
78
|
+
|
|
79
|
+
### First-Class Async/Await
|
|
80
|
+
|
|
81
|
+
```javascript
|
|
82
|
+
const template = `
|
|
83
|
+
<div class="profile">
|
|
84
|
+
<h2>User Details</h2>
|
|
85
|
+
<p>Age: <%= await getUserAge(id) %></p>
|
|
86
|
+
</div>
|
|
87
|
+
`;
|
|
88
|
+
|
|
89
|
+
const html = await render(template, {
|
|
90
|
+
id: 101,
|
|
91
|
+
getUserAge: async (id) => `Verified Age for User #${id}`
|
|
92
|
+
});
|
|
93
|
+
```
|
|
94
|
+
|
|
95
|
+
## API Reference
|
|
96
|
+
|
|
97
|
+
### `render(template, data)`
|
|
98
|
+
|
|
99
|
+
**Arguments:**
|
|
100
|
+
- `template` (string): The raw template string to compile and evaluate.
|
|
101
|
+
- `data` (object): The variable context to be accessible within the template.
|
|
102
|
+
|
|
103
|
+
**Returns:**
|
|
104
|
+
- `Promise<string>`: The final rendered output.
|
|
105
|
+
|
|
106
|
+
### `compile(template)`
|
|
107
|
+
|
|
108
|
+
**Arguments:**
|
|
109
|
+
- `template` (string): The raw template string.
|
|
110
|
+
|
|
111
|
+
**Returns:**
|
|
112
|
+
- `(data) => Promise<string>`: A reusable, high-performance async render function.
|
|
113
|
+
|
|
114
|
+
## License
|
|
115
|
+
|
|
116
|
+
MIT - Developed under the docmd ecosystem by [Ghazi](https://mgks.dev).
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Compiles an EJS-style template string into an async function.
|
|
3
|
+
* Supports: <% js %>, <%= escaped %>, <%- unescaped %>
|
|
4
|
+
*/
|
|
5
|
+
export declare function compile(template: any): (data: any) => any;
|
|
6
|
+
/**
|
|
7
|
+
* Convenience method to render template directly.
|
|
8
|
+
*/
|
|
9
|
+
export declare function render(template: any, data?: {}, options?: {}): Promise<any>;
|
|
10
|
+
declare const _default: {
|
|
11
|
+
render: typeof render;
|
|
12
|
+
compile: typeof compile;
|
|
13
|
+
};
|
|
14
|
+
export default _default;
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
const AsyncFunction = Object.getPrototypeOf(async function () { }).constructor;
|
|
2
|
+
function escapeHtml(str) {
|
|
3
|
+
return String(str)
|
|
4
|
+
.replace(/&/g, '&')
|
|
5
|
+
.replace(/</g, '<')
|
|
6
|
+
.replace(/>/g, '>')
|
|
7
|
+
.replace(/"/g, '"')
|
|
8
|
+
.replace(/'/g, ''');
|
|
9
|
+
}
|
|
10
|
+
/**
|
|
11
|
+
* Compiles an EJS-style template string into an async function.
|
|
12
|
+
* Supports: <% js %>, <%= escaped %>, <%- unescaped %>
|
|
13
|
+
*/
|
|
14
|
+
export function compile(template) {
|
|
15
|
+
let code = "";
|
|
16
|
+
const regex = /<%(=|-|_|#)?([\s\S]+?)([-_])?%>/g;
|
|
17
|
+
let cursor = 0;
|
|
18
|
+
let match;
|
|
19
|
+
while ((match = regex.exec(template)) !== null) {
|
|
20
|
+
const textBefore = template.slice(cursor, match.index);
|
|
21
|
+
if (textBefore) {
|
|
22
|
+
code += `__out += \`${textBefore.replace(/\\/g, "\\\\").replace(/`/g, "\\`").replace(/\$/g, "\\$")}\`;\n`;
|
|
23
|
+
}
|
|
24
|
+
const type = match[1];
|
|
25
|
+
let script = match[2].trim();
|
|
26
|
+
if (type === '#') {
|
|
27
|
+
// It's a comment, completely ignore it.
|
|
28
|
+
}
|
|
29
|
+
else if (type === '=') {
|
|
30
|
+
// Escape HTML output
|
|
31
|
+
code += `__out += escapeHtml(typeof (${script}) !== 'undefined' ? (${script}) : '');\n`;
|
|
32
|
+
}
|
|
33
|
+
else if (type === '-') {
|
|
34
|
+
// Raw HTML output
|
|
35
|
+
code += `__out += String(typeof (${script}) !== 'undefined' ? (${script}) : '');\n`;
|
|
36
|
+
}
|
|
37
|
+
else {
|
|
38
|
+
// Literal JS code execution
|
|
39
|
+
code += `${script}\n`;
|
|
40
|
+
}
|
|
41
|
+
cursor = match.index + match[0].length;
|
|
42
|
+
}
|
|
43
|
+
const textAfter = template.slice(cursor);
|
|
44
|
+
if (textAfter) {
|
|
45
|
+
code += `__out += \`${textAfter.replace(/\\/g, "\\\\").replace(/`/g, "\\`").replace(/\$/g, "\\$")}\`;\n`;
|
|
46
|
+
}
|
|
47
|
+
const wrappedCode = `let __out = '';\nwith(__data || {}) {\n${code}\nreturn __out;\n}`;
|
|
48
|
+
let fn;
|
|
49
|
+
try {
|
|
50
|
+
fn = new AsyncFunction("__data", "escapeHtml", wrappedCode);
|
|
51
|
+
}
|
|
52
|
+
catch (e) {
|
|
53
|
+
console.error("COMPILATION ERROR CODE:\n" + wrappedCode.split('\\n').map((l, i) => `${i + 1}: ${l}`).join('\\n'));
|
|
54
|
+
throw e;
|
|
55
|
+
}
|
|
56
|
+
return function (data) {
|
|
57
|
+
return fn(data, escapeHtml);
|
|
58
|
+
};
|
|
59
|
+
}
|
|
60
|
+
/**
|
|
61
|
+
* Convenience method to render template directly.
|
|
62
|
+
*/
|
|
63
|
+
export async function render(template, data = {}, options = {}) {
|
|
64
|
+
// Allow caching if 'filename' or 'id' is passed usually, but here we just compile and run.
|
|
65
|
+
const fn = compile(template);
|
|
66
|
+
// Add locals pseudo-property common in EJS contexts
|
|
67
|
+
return await fn({ locals: data, ...data });
|
|
68
|
+
}
|
|
69
|
+
export default {
|
|
70
|
+
render,
|
|
71
|
+
compile
|
|
72
|
+
};
|
package/package.json
ADDED
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "lite-template",
|
|
3
|
+
"version": "0.0.1",
|
|
4
|
+
"description": "Ultra lightweight, zero-dependency async template engine compatible with basic EJS syntax.",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"main": "dist/index.js",
|
|
7
|
+
"types": "dist/index.d.ts",
|
|
8
|
+
"scripts": {
|
|
9
|
+
"build": "tsc"
|
|
10
|
+
},
|
|
11
|
+
"devDependencies": {
|
|
12
|
+
"typescript": "^5.0.0"
|
|
13
|
+
},
|
|
14
|
+
"keywords": [
|
|
15
|
+
"ejs",
|
|
16
|
+
"template",
|
|
17
|
+
"engine",
|
|
18
|
+
"micro",
|
|
19
|
+
"lite",
|
|
20
|
+
"async",
|
|
21
|
+
"minimal",
|
|
22
|
+
"lightweight",
|
|
23
|
+
"typescript",
|
|
24
|
+
"javascript",
|
|
25
|
+
"nodejs",
|
|
26
|
+
"docmd"
|
|
27
|
+
],
|
|
28
|
+
"author": {
|
|
29
|
+
"name": "Ghazi",
|
|
30
|
+
"url": "https://mgks.dev"
|
|
31
|
+
},
|
|
32
|
+
"repository": {
|
|
33
|
+
"type": "git",
|
|
34
|
+
"url": "git+https://github.com/docmd-io/docmd.git",
|
|
35
|
+
"directory": "lite-template"
|
|
36
|
+
},
|
|
37
|
+
"bugs": {
|
|
38
|
+
"url": "https://github.com/docmd-io/docmd/issues"
|
|
39
|
+
},
|
|
40
|
+
"homepage": "https://docmd.io",
|
|
41
|
+
"funding": "https://github.com/sponsors/mgks",
|
|
42
|
+
"license": "MIT"
|
|
43
|
+
}
|
package/src/index.ts
ADDED
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
const AsyncFunction = Object.getPrototypeOf(async function(){}).constructor;
|
|
2
|
+
|
|
3
|
+
function escapeHtml(str) {
|
|
4
|
+
return String(str)
|
|
5
|
+
.replace(/&/g, '&')
|
|
6
|
+
.replace(/</g, '<')
|
|
7
|
+
.replace(/>/g, '>')
|
|
8
|
+
.replace(/"/g, '"')
|
|
9
|
+
.replace(/'/g, ''');
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
/**
|
|
13
|
+
* Compiles an EJS-style template string into an async function.
|
|
14
|
+
* Supports: <% js %>, <%= escaped %>, <%- unescaped %>
|
|
15
|
+
*/
|
|
16
|
+
export function compile(template) {
|
|
17
|
+
let code = "";
|
|
18
|
+
const regex = /<%(=|-|_|#)?([\s\S]+?)([-_])?%>/g;
|
|
19
|
+
let cursor = 0;
|
|
20
|
+
let match;
|
|
21
|
+
|
|
22
|
+
while ((match = regex.exec(template)) !== null) {
|
|
23
|
+
const textBefore = template.slice(cursor, match.index);
|
|
24
|
+
if (textBefore) {
|
|
25
|
+
code += `__out += \`${textBefore.replace(/\\/g, "\\\\").replace(/`/g, "\\`").replace(/\$/g, "\\$")}\`;\n`;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
const type = match[1];
|
|
29
|
+
let script = match[2].trim();
|
|
30
|
+
|
|
31
|
+
if (type === '#') {
|
|
32
|
+
// It's a comment, completely ignore it.
|
|
33
|
+
} else if (type === '=') {
|
|
34
|
+
// Escape HTML output
|
|
35
|
+
code += `__out += escapeHtml(typeof (${script}) !== 'undefined' ? (${script}) : '');\n`;
|
|
36
|
+
} else if (type === '-') {
|
|
37
|
+
// Raw HTML output
|
|
38
|
+
code += `__out += String(typeof (${script}) !== 'undefined' ? (${script}) : '');\n`;
|
|
39
|
+
} else {
|
|
40
|
+
// Literal JS code execution
|
|
41
|
+
code += `${script}\n`;
|
|
42
|
+
}
|
|
43
|
+
cursor = match.index + match[0].length;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
const textAfter = template.slice(cursor);
|
|
47
|
+
if (textAfter) {
|
|
48
|
+
code += `__out += \`${textAfter.replace(/\\/g, "\\\\").replace(/`/g, "\\`").replace(/\$/g, "\\$")}\`;\n`;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
const wrappedCode = `let __out = '';\nwith(__data || {}) {\n${code}\nreturn __out;\n}`;
|
|
52
|
+
|
|
53
|
+
let fn;
|
|
54
|
+
try {
|
|
55
|
+
fn = new AsyncFunction("__data", "escapeHtml", wrappedCode);
|
|
56
|
+
} catch (e) {
|
|
57
|
+
console.error("COMPILATION ERROR CODE:\n" + wrappedCode.split('\\n').map((l, i) => `${i+1}: ${l}`).join('\\n'));
|
|
58
|
+
throw e;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
return function(data) {
|
|
62
|
+
return fn(data, escapeHtml);
|
|
63
|
+
};
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/**
|
|
67
|
+
* Convenience method to render template directly.
|
|
68
|
+
*/
|
|
69
|
+
export async function render(template, data = {}, options = {}) {
|
|
70
|
+
// Allow caching if 'filename' or 'id' is passed usually, but here we just compile and run.
|
|
71
|
+
const fn = compile(template);
|
|
72
|
+
// Add locals pseudo-property common in EJS contexts
|
|
73
|
+
return await fn({ locals: data, ...data });
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
export default {
|
|
77
|
+
render,
|
|
78
|
+
compile
|
|
79
|
+
};
|
package/tsconfig.json
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
{
|
|
2
|
+
"compilerOptions": {
|
|
3
|
+
"target": "ES2022",
|
|
4
|
+
"module": "Node16",
|
|
5
|
+
"moduleResolution": "node16",
|
|
6
|
+
"strict": false,
|
|
7
|
+
"declaration": true,
|
|
8
|
+
"outDir": "dist",
|
|
9
|
+
"esModuleInterop": true,
|
|
10
|
+
"forceConsistentCasingInFileNames": true,
|
|
11
|
+
"skipLibCheck": true
|
|
12
|
+
},
|
|
13
|
+
"include": ["src/**/*"]
|
|
14
|
+
}
|