kempo-server 3.0.10 → 3.0.12
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/CHANGELOG.md +12 -0
- package/README.md +106 -0
- package/dist/templating/index.js +1 -1
- package/docs/templating.html +38 -1
- package/docs-src/templating.page.html +38 -1
- package/package.json +1 -1
- package/src/templating/index.js +24 -10
- package/tests/renderExternalPage.node-test.js +219 -0
- package/tests/renderPageToString.node-test.js +178 -0
package/CHANGELOG.md
CHANGED
|
@@ -2,6 +2,18 @@
|
|
|
2
2
|
|
|
3
3
|
All notable changes to `kempo-server` are documented in this file.
|
|
4
4
|
|
|
5
|
+
## [3.0.12] - 2026-04-17
|
|
6
|
+
|
|
7
|
+
### Added
|
|
8
|
+
- **`renderExternalPage(pageFilePath, rootDir, resolveDir, globals, state, maxDepth)`** exported from `kempo-server/templating`. Identical pipeline to `renderPage` but decouples the page file's physical location from where templates and fragments are resolved. `resolveDir` (a path within `rootDir`) drives template/fragment walk-up and `pathToRoot` calculation, allowing page files that live outside `rootDir` (e.g. in extension packages) to use the host project's templates. Internally `renderPage` now delegates to a shared `renderPageCore` with no change to its public signature or behavior.
|
|
9
|
+
|
|
10
|
+
## [3.0.11] - 2026-04-16
|
|
11
|
+
|
|
12
|
+
### Added
|
|
13
|
+
|
|
14
|
+
- **`renderPageToString(pagePath, vars, rootDir)`** exported from `kempo-server/templating`. Runs the full templating pipeline (template resolution, fragment injection, global content, `<if>`, `<foreach>`, `{{vars}}`) against a `.page.html` file and returns the final HTML string. Intended for programmatic use such as rendering emails.
|
|
15
|
+
---
|
|
16
|
+
|
|
5
17
|
## [3.0.0] - 2026-04-09
|
|
6
18
|
|
|
7
19
|
### Breaking Changes
|
package/README.md
CHANGED
|
@@ -315,6 +315,112 @@ export default async function(request, response) {
|
|
|
315
315
|
}
|
|
316
316
|
```
|
|
317
317
|
|
|
318
|
+
## Programmatic HTML Rendering
|
|
319
|
+
|
|
320
|
+
Use `renderPageToString` to run the full templating pipeline outside of an HTTP request — ideal for rendering emails, generating HTML to pass to a PDF library, or any other programmatic use case.
|
|
321
|
+
|
|
322
|
+
```javascript
|
|
323
|
+
import { renderPageToString } from 'kempo-server/templating';
|
|
324
|
+
|
|
325
|
+
const html = await renderPageToString(pagePath, vars, rootDir);
|
|
326
|
+
```
|
|
327
|
+
|
|
328
|
+
**Parameters:**
|
|
329
|
+
|
|
330
|
+
| Parameter | Type | Description |
|
|
331
|
+
|-----------|------|-------------|
|
|
332
|
+
| `pagePath` | `string` | Absolute path to a `.page.html` file |
|
|
333
|
+
| `vars` | `object` | Data available as `{{varName}}` in templates, fragments, and `<if>` conditions |
|
|
334
|
+
| `rootDir` | `string` | *(optional)* Root for template/fragment/global search. Defaults to the directory of `pagePath` |
|
|
335
|
+
|
|
336
|
+
The same pipeline that runs for web requests is used: template resolution, fragment injection, global content push, `<if>` conditionals, `<foreach>` loops, and `{{var}}` interpolation.
|
|
337
|
+
|
|
338
|
+
**Email example:**
|
|
339
|
+
|
|
340
|
+
```
|
|
341
|
+
emails/
|
|
342
|
+
├─ email.template.html ← shared header/footer for all emails
|
|
343
|
+
├─ signature.fragment.html ← reusable fragment
|
|
344
|
+
├─ promo-banner.global.html ← pushed into every email automatically
|
|
345
|
+
├─ welcome.page.html
|
|
346
|
+
├─ password-reset.page.html
|
|
347
|
+
└─ order-confirmation.page.html
|
|
348
|
+
```
|
|
349
|
+
|
|
350
|
+
```javascript
|
|
351
|
+
// email.template.html
|
|
352
|
+
<html>
|
|
353
|
+
<body>
|
|
354
|
+
<location name="body" />
|
|
355
|
+
<fragment name="signature" />
|
|
356
|
+
<location name="promo" />
|
|
357
|
+
</body>
|
|
358
|
+
</html>
|
|
359
|
+
```
|
|
360
|
+
|
|
361
|
+
```javascript
|
|
362
|
+
// welcome.page.html
|
|
363
|
+
<page template="email">
|
|
364
|
+
<content location="body">
|
|
365
|
+
<h1>Welcome, {{userName}}!</h1>
|
|
366
|
+
</content>
|
|
367
|
+
</page>
|
|
368
|
+
```
|
|
369
|
+
|
|
370
|
+
```javascript
|
|
371
|
+
import { renderPageToString } from 'kempo-server/templating';
|
|
372
|
+
import path from 'path';
|
|
373
|
+
|
|
374
|
+
const emailsDir = path.resolve('./emails');
|
|
375
|
+
const html = await renderPageToString(
|
|
376
|
+
path.join(emailsDir, 'welcome.page.html'),
|
|
377
|
+
{ userName: 'Alice' },
|
|
378
|
+
emailsDir
|
|
379
|
+
);
|
|
380
|
+
// html is the fully rendered email string — ready to send
|
|
381
|
+
```
|
|
382
|
+
|
|
383
|
+
**Note:** `vars` are merged as `state` in the pipeline, meaning `<page>` tag attributes take highest priority, followed by `vars`, then `globals`. Built-in vars (`{{year}}`, `{{date}}`, `{{datetime}}`, `{{timestamp}}`) are always available.
|
|
384
|
+
|
|
385
|
+
## Rendering Pages from External Packages
|
|
386
|
+
|
|
387
|
+
Use `renderExternalPage` when a page file lives outside `rootDir` — for example, in a plugin or extension package — but should be rendered using the host project's templates, fragments, and globals.
|
|
388
|
+
|
|
389
|
+
```javascript
|
|
390
|
+
import { renderExternalPage } from 'kempo-server/templating';
|
|
391
|
+
|
|
392
|
+
const html = await renderExternalPage(pageFilePath, rootDir, resolveDir, globals, state, maxDepth);
|
|
393
|
+
```
|
|
394
|
+
|
|
395
|
+
**Parameters:**
|
|
396
|
+
|
|
397
|
+
| Parameter | Type | Description |
|
|
398
|
+
|-----------|------|-------------|
|
|
399
|
+
| `pageFilePath` | `string` | Absolute path to the `.page.html` file. May live outside `rootDir`. Used only to read content. |
|
|
400
|
+
| `rootDir` | `string` | Ceiling for template/fragment walk-up. `*.global.html` files are scanned from here. |
|
|
401
|
+
| `resolveDir` | `string` | Directory **within** `rootDir` where template and fragment walk-up starts. `pathToRoot` is calculated from here. |
|
|
402
|
+
| `globals` | `object` | Global variables available to all pages |
|
|
403
|
+
| `state` | `object` | Per-render variables |
|
|
404
|
+
| `maxDepth` | `number` | Max fragment nesting depth (default `10`) |
|
|
405
|
+
|
|
406
|
+
The behavior is identical to `renderPage` called on a hypothetical page file physically located at `resolveDir/<filename>.page.html`. The only difference is that the page content is read from `pageFilePath` regardless of where it lives on disk.
|
|
407
|
+
|
|
408
|
+
**Example — extension package rendering into host templates:**
|
|
409
|
+
|
|
410
|
+
```javascript
|
|
411
|
+
import { renderExternalPage } from 'kempo-server/templating';
|
|
412
|
+
import path from 'path';
|
|
413
|
+
|
|
414
|
+
// Page lives in the extension package, but uses the host app's templates
|
|
415
|
+
const html = await renderExternalPage(
|
|
416
|
+
path.resolve('./node_modules/my-extension/admin/dashboard.page.html'),
|
|
417
|
+
path.resolve('./public'), // rootDir — host project root
|
|
418
|
+
path.resolve('./public/admin'), // resolveDir — treat it as if it lives here
|
|
419
|
+
globals,
|
|
420
|
+
state
|
|
421
|
+
);
|
|
422
|
+
```
|
|
423
|
+
|
|
318
424
|
## Programmatic File Rescan
|
|
319
425
|
|
|
320
426
|
When files are added or removed at runtime (e.g., by a CMS generating static pages), you can trigger a file rescan without restarting the server:
|
package/dist/templating/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{readFile,writeFile,mkdir,readdir}from"fs/promises";import path from"path";import{extractAttrs,extractContentBlocks,mergeContentBlocks,replaceLocations,resolveVars,resolveIfs,resolveForeach,resolveFragmentTags}from"./parse.js";import{readFileSync,statSync}from"fs";const findFileUpSync=(filename,startDir,rootDir)=>{let dir=startDir;const root=path.resolve(rootDir);for(;;){const candidate=path.join(dir,filename);try{return statSync(candidate),candidate}catch(e){}if(path.resolve(dir)===root)return null;const parent=path.dirname(dir);if(parent===dir)return null;dir=parent}},loadVersion=rootDir=>{try{return JSON.parse(readFileSync(path.join(rootDir,"package.json"),"utf8")).version||""}catch(e){return""}},walkGlobals=async dir=>{const entries=await readdir(dir,{withFileTypes:!0}),results=[];for(const entry of entries){const full=path.join(dir,entry.name);entry.isDirectory()?results.push(...await walkGlobals(full)):entry.name.endsWith(".global.html")&&results.push(full)}return results},loadGlobalContent=async rootDir=>{const files=await walkGlobals(rootDir),maps=await Promise.all(files.map(async f=>extractContentBlocks(await readFile(f,"utf8"))));return mergeContentBlocks(...maps)},
|
|
1
|
+
import{readFile,writeFile,mkdir,readdir}from"fs/promises";import path from"path";import{extractAttrs,extractContentBlocks,mergeContentBlocks,replaceLocations,resolveVars,resolveIfs,resolveForeach,resolveFragmentTags}from"./parse.js";import{readFileSync,statSync}from"fs";const findFileUpSync=(filename,startDir,rootDir)=>{let dir=startDir;const root=path.resolve(rootDir);for(;;){const candidate=path.join(dir,filename);try{return statSync(candidate),candidate}catch(e){}if(path.resolve(dir)===root)return null;const parent=path.dirname(dir);if(parent===dir)return null;dir=parent}},loadVersion=rootDir=>{try{return JSON.parse(readFileSync(path.join(rootDir,"package.json"),"utf8")).version||""}catch(e){return""}},walkGlobals=async dir=>{const entries=await readdir(dir,{withFileTypes:!0}),results=[];for(const entry of entries){const full=path.join(dir,entry.name);entry.isDirectory()?results.push(...await walkGlobals(full)):entry.name.endsWith(".global.html")&&results.push(full)}return results},loadGlobalContent=async rootDir=>{const files=await walkGlobals(rootDir),maps=await Promise.all(files.map(async f=>extractContentBlocks(await readFile(f,"utf8"))));return mergeContentBlocks(...maps)},renderPageCore=async(pageFilePath,rootDir,resolveDir,globals={},state={},maxDepth=10,preloadedGlobalContent=null)=>{const pageContent=await readFile(pageFilePath,"utf8"),pageTagMatch=pageContent.match(/^[\s\S]*?<page((?:[^>"']|"[^"]*"|'[^']*')*)>/);if(!pageTagMatch)throw new Error(`Invalid page file: missing <page> root element in ${pageFilePath}`);const pageAttrs=extractAttrs(pageTagMatch[1]),templateName=pageAttrs.template||"default";delete pageAttrs.template;let templateFile=findFileUpSync(`${templateName}.template.html`,resolveDir,rootDir);if(templateFile||"default"===templateName||(templateFile=findFileUpSync("default.template.html",resolveDir,rootDir)),!templateFile)throw new Error(`Template not found: ${templateName}.template.html or default.template.html (searched from ${resolveDir} to ${rootDir})`);const globalContent=preloadedGlobalContent??await loadGlobalContent(rootDir),rawPageBlocks=extractContentBlocks(pageContent),pageBlocks={};for(const[name,entries]of Object.entries(rawPageBlocks))pageBlocks[name]=entries.map(e=>({...e,html:replaceLocations(e.html,globalContent)}));const contentBlocks=mergeContentBlocks(pageBlocks,globalContent);let templateHtml=readFileSync(templateFile,"utf8");templateHtml=resolveFragmentTags(templateHtml,name=>{const filePath=findFileUpSync(name+".fragment.html",resolveDir,rootDir);return filePath?readFileSync(filePath,"utf8"):null},0,maxDepth),templateHtml=replaceLocations(templateHtml,contentBlocks);const rel=path.relative(rootDir,resolveDir),depth=rel?rel.split(path.sep).length:0,now=new Date,vars={pathToRoot:depth>0?"../".repeat(depth):"./",year:String(now.getFullYear()),date:now.toISOString().slice(0,10),datetime:now.toISOString(),timestamp:String(Date.now()),version:loadVersion(rootDir),env:process.env.NODE_ENV||"",...globals,...state,...pageAttrs};for(const[key,val]of Object.entries(vars))"function"==typeof val&&(vars[key]=val());return templateHtml=resolveIfs(templateHtml,vars),templateHtml=resolveForeach(templateHtml,vars),templateHtml=resolveVars(templateHtml,vars),templateHtml},renderPage=(pageFilePath,rootDir,globals={},state={},maxDepth=10,preloadedGlobalContent=null)=>renderPageCore(pageFilePath,rootDir,path.dirname(pageFilePath),globals,state,maxDepth,preloadedGlobalContent),renderExternalPage=(pageFilePath,rootDir,resolveDir,globals={},state={},maxDepth=10)=>renderPageCore(pageFilePath,rootDir,resolveDir,globals,state,maxDepth,null),walkPages=async dir=>{const entries=await readdir(dir,{withFileTypes:!0}),results=[];for(const entry of entries){const full=path.join(dir,entry.name);entry.isDirectory()?results.push(...await walkPages(full)):entry.name.endsWith(".page.html")&&results.push(full)}return results},renderDir=async(inputDir,outputDir,globals={},state={},maxDepth=10)=>{const[pages,globalContent]=await Promise.all([walkPages(inputDir),loadGlobalContent(inputDir)]);let count=0;for(const page of pages){const outRel=path.relative(inputDir,page).replace(/\.page\.html$/,".html"),outPath=path.join(outputDir,outRel);await mkdir(path.dirname(outPath),{recursive:!0});const html=await renderPage(page,inputDir,globals,state,maxDepth,globalContent);await writeFile(outPath,html,"utf8"),count++}return count},renderPageToString=(pagePath,vars={},rootDir=path.dirname(pagePath))=>renderPage(pagePath,rootDir,{},vars);export{renderPage,renderDir,renderPageToString,renderExternalPage};
|
package/docs/templating.html
CHANGED
|
@@ -318,7 +318,44 @@
|
|
|
318
318
|
<p>The CLI automatically loads <code>.config.js</code> or <code>.config.json</code> from the input directory for globals, state, and maxFragmentDepth settings.</p>
|
|
319
319
|
|
|
320
320
|
<h3>Programmatic API</h3>
|
|
321
|
-
<pre><code class="hljs javascript"><span class="hljs-keyword">import</span> { renderDir, renderPage } <span class="hljs-keyword">from</span> <span class="hljs-string">'kempo-server/templating'</span>;<br /><br /><span class="hljs-comment">// Render all pages in a directory</span><br /><span class="hljs-keyword">const</span> count = <span class="hljs-keyword">await</span> renderDir(<span class="hljs-string">'./src'</span>, <span class="hljs-string">'./dist'</span>, globals, state, maxDepth);<br /><br /><span class="hljs-comment">// Render a single page</span><br /><span class="hljs-keyword">const</span> html = <span class="hljs-keyword">await</span> renderPage(<span class="hljs-string">'./src/about.page.html'</span>, <span class="hljs-string">'./src'</span>, globals, state, maxDepth);</code></pre>
|
|
321
|
+
<pre><code class="hljs javascript"><span class="hljs-keyword">import</span> { renderDir, renderPage, renderPageToString, renderExternalPage } <span class="hljs-keyword">from</span> <span class="hljs-string">'kempo-server/templating'</span>;<br /><br /><span class="hljs-comment">// Render all pages in a directory</span><br /><span class="hljs-keyword">const</span> count = <span class="hljs-keyword">await</span> renderDir(<span class="hljs-string">'./src'</span>, <span class="hljs-string">'./dist'</span>, globals, state, maxDepth);<br /><br /><span class="hljs-comment">// Render a single page</span><br /><span class="hljs-keyword">const</span> html = <span class="hljs-keyword">await</span> renderPage(<span class="hljs-string">'./src/about.page.html'</span>, <span class="hljs-string">'./src'</span>, globals, state, maxDepth);<br /><br /><span class="hljs-comment">// Render a page to a string (e.g. for sending emails)</span><br /><span class="hljs-keyword">const</span> emailHtml = <span class="hljs-keyword">await</span> renderPageToString(pagePath, vars, rootDir);<br /><br /><span class="hljs-comment">// Render a page file that lives outside rootDir</span><br /><span class="hljs-keyword">const</span> extHtml = <span class="hljs-keyword">await</span> renderExternalPage(pageFilePath, rootDir, resolveDir, globals, state, maxDepth);</code></pre>
|
|
322
|
+
|
|
323
|
+
<h3 id="render-page-to-string">renderPageToString</h3>
|
|
324
|
+
<p>Runs the full templating pipeline against a <code>.page.html</code> file and returns the final HTML string — no HTTP request needed. Template resolution, fragment injection, global content, <code><if></code>, <code><foreach></code>, and <code>{{vars}}</code> all work identically to a normal web render. Ideal for sending emails, generating PDFs, or any other programmatic rendering.</p>
|
|
325
|
+
<div class="table-wrapper mb">
|
|
326
|
+
<table>
|
|
327
|
+
<thead>
|
|
328
|
+
<tr><th>Parameter</th><th>Type</th><th>Default</th><th>Description</th></tr>
|
|
329
|
+
</thead>
|
|
330
|
+
<tbody>
|
|
331
|
+
<tr><td><code>pagePath</code></td><td><code>string</code></td><td><em>required</em></td><td>Absolute path to a <code>.page.html</code> file</td></tr>
|
|
332
|
+
<tr><td><code>vars</code></td><td><code>object</code></td><td><code>{}</code></td><td>Data available as <code>{{varName}}</code> in templates, fragments, and conditions</td></tr>
|
|
333
|
+
<tr><td><code>rootDir</code></td><td><code>string</code></td><td>Directory of <code>pagePath</code></td><td>Root for template, fragment, and global file search</td></tr>
|
|
334
|
+
</tbody>
|
|
335
|
+
</table>
|
|
336
|
+
</div>
|
|
337
|
+
<p>A common use case is sending templated emails. Create a dedicated email directory with a shared template, per-email pages, reusable fragments, and optional global content:</p>
|
|
338
|
+
<pre><code class="hljs javascript"><span class="hljs-keyword">import</span> { renderPageToString } <span class="hljs-keyword">from</span> <span class="hljs-string">'kempo-server/templating'</span>;<br /><span class="hljs-keyword">import</span> path <span class="hljs-keyword">from</span> <span class="hljs-string">'path'</span>;<br /><br /><span class="hljs-keyword">const</span> emailsDir = path.resolve(<span class="hljs-string">'./emails'</span>);<br /><span class="hljs-keyword">const</span> html = <span class="hljs-keyword">await</span> renderPageToString(<br /> path.join(emailsDir, <span class="hljs-string">'welcome.page.html'</span>),<br /> { userName: <span class="hljs-string">'Alice'</span>, orderId: <span class="hljs-string">'1234'</span> }<br />);</code></pre>
|
|
339
|
+
<p>Built-in vars (<code>2026</code>, <code>2026-04-17</code>, <code>2026-04-17T16:44:17.587Z</code>, <code>1776444257587</code>) are always available. Note that <code><page></code> tag attributes take highest priority and override <code>vars</code> with the same key.</p>
|
|
340
|
+
|
|
341
|
+
<h3 id="render-external-page">renderExternalPage</h3>
|
|
342
|
+
<p>Identical pipeline to <code>renderPage</code>, but decouples the page file's physical location from where templates and fragments are resolved. Use this when a page file lives outside <code>rootDir</code> — for example, in a plugin or extension package — but should be rendered using the host project's templates, fragments, and globals.</p>
|
|
343
|
+
<div class="table-wrapper mb">
|
|
344
|
+
<table>
|
|
345
|
+
<thead>
|
|
346
|
+
<tr><th>Parameter</th><th>Type</th><th>Default</th><th>Description</th></tr>
|
|
347
|
+
</thead>
|
|
348
|
+
<tbody>
|
|
349
|
+
<tr><td><code>pageFilePath</code></td><td><code>string</code></td><td><em>required</em></td><td>Absolute path to the <code>.page.html</code> file. May live outside <code>rootDir</code>. Used only to read content.</td></tr>
|
|
350
|
+
<tr><td><code>rootDir</code></td><td><code>string</code></td><td><em>required</em></td><td>Ceiling for template/fragment walk-up. <code>*.global.html</code> files are scanned from here.</td></tr>
|
|
351
|
+
<tr><td><code>resolveDir</code></td><td><code>string</code></td><td><em>required</em></td><td>Directory within <code>rootDir</code> where template and fragment walk-up starts. <code>pathToRoot</code> is calculated from here.</td></tr>
|
|
352
|
+
<tr><td><code>globals</code></td><td><code>object</code></td><td><code>{}</code></td><td>Global variables available to all pages</td></tr>
|
|
353
|
+
<tr><td><code>state</code></td><td><code>object</code></td><td><code>{}</code></td><td>Per-render variables</td></tr>
|
|
354
|
+
<tr><td><code>maxDepth</code></td><td><code>number</code></td><td><code>10</code></td><td>Maximum fragment nesting depth</td></tr>
|
|
355
|
+
</tbody>
|
|
356
|
+
</table>
|
|
357
|
+
</div>
|
|
358
|
+
<pre><code class="hljs javascript"><span class="hljs-keyword">import</span> { renderExternalPage } <span class="hljs-keyword">from</span> <span class="hljs-string">'kempo-server/templating'</span>;<br /><span class="hljs-keyword">import</span> path <span class="hljs-keyword">from</span> <span class="hljs-string">'path'</span>;<br /><br /><span class="hljs-comment">// Page lives in an extension package, rendered with the host app's templates</span><br /><span class="hljs-keyword">const</span> html = <span class="hljs-keyword">await</span> renderExternalPage(<br /> path.resolve(<span class="hljs-string">'./node_modules/my-ext/admin/dashboard.page.html'</span>),<br /> path.resolve(<span class="hljs-string">'./public'</span>), <span class="hljs-comment">// rootDir</span><br /> path.resolve(<span class="hljs-string">'./public/admin'</span>), <span class="hljs-comment">// resolveDir</span><br /> globals,<br /> state<br />);</code></pre>
|
|
322
359
|
|
|
323
360
|
<h2 id="ssr">Server-Side Rendering</h2>
|
|
324
361
|
<p>Pages can also be rendered on each request instead of pre-built. This is useful during development so you can see changes without rebuilding.</p>
|
|
@@ -218,7 +218,44 @@
|
|
|
218
218
|
<p>The CLI automatically loads <code>.config.js</code> or <code>.config.json</code> from the input directory for globals, state, and maxFragmentDepth settings.</p>
|
|
219
219
|
|
|
220
220
|
<h3>Programmatic API</h3>
|
|
221
|
-
<pre><code class="hljs javascript"><span class="hljs-keyword">import</span> { renderDir, renderPage } <span class="hljs-keyword">from</span> <span class="hljs-string">'kempo-server/templating'</span>;<br /><br /><span class="hljs-comment">// Render all pages in a directory</span><br /><span class="hljs-keyword">const</span> count = <span class="hljs-keyword">await</span> renderDir(<span class="hljs-string">'./src'</span>, <span class="hljs-string">'./dist'</span>, globals, state, maxDepth);<br /><br /><span class="hljs-comment">// Render a single page</span><br /><span class="hljs-keyword">const</span> html = <span class="hljs-keyword">await</span> renderPage(<span class="hljs-string">'./src/about.page.html'</span>, <span class="hljs-string">'./src'</span>, globals, state, maxDepth);</code></pre>
|
|
221
|
+
<pre><code class="hljs javascript"><span class="hljs-keyword">import</span> { renderDir, renderPage, renderPageToString, renderExternalPage } <span class="hljs-keyword">from</span> <span class="hljs-string">'kempo-server/templating'</span>;<br /><br /><span class="hljs-comment">// Render all pages in a directory</span><br /><span class="hljs-keyword">const</span> count = <span class="hljs-keyword">await</span> renderDir(<span class="hljs-string">'./src'</span>, <span class="hljs-string">'./dist'</span>, globals, state, maxDepth);<br /><br /><span class="hljs-comment">// Render a single page</span><br /><span class="hljs-keyword">const</span> html = <span class="hljs-keyword">await</span> renderPage(<span class="hljs-string">'./src/about.page.html'</span>, <span class="hljs-string">'./src'</span>, globals, state, maxDepth);<br /><br /><span class="hljs-comment">// Render a page to a string (e.g. for sending emails)</span><br /><span class="hljs-keyword">const</span> emailHtml = <span class="hljs-keyword">await</span> renderPageToString(pagePath, vars, rootDir);<br /><br /><span class="hljs-comment">// Render a page file that lives outside rootDir</span><br /><span class="hljs-keyword">const</span> extHtml = <span class="hljs-keyword">await</span> renderExternalPage(pageFilePath, rootDir, resolveDir, globals, state, maxDepth);</code></pre>
|
|
222
|
+
|
|
223
|
+
<h3 id="render-page-to-string">renderPageToString</h3>
|
|
224
|
+
<p>Runs the full templating pipeline against a <code>.page.html</code> file and returns the final HTML string — no HTTP request needed. Template resolution, fragment injection, global content, <code><if></code>, <code><foreach></code>, and <code>{{vars}}</code> all work identically to a normal web render. Ideal for sending emails, generating PDFs, or any other programmatic rendering.</p>
|
|
225
|
+
<div class="table-wrapper mb">
|
|
226
|
+
<table>
|
|
227
|
+
<thead>
|
|
228
|
+
<tr><th>Parameter</th><th>Type</th><th>Default</th><th>Description</th></tr>
|
|
229
|
+
</thead>
|
|
230
|
+
<tbody>
|
|
231
|
+
<tr><td><code>pagePath</code></td><td><code>string</code></td><td><em>required</em></td><td>Absolute path to a <code>.page.html</code> file</td></tr>
|
|
232
|
+
<tr><td><code>vars</code></td><td><code>object</code></td><td><code>{}</code></td><td>Data available as <code>{{varName}}</code> in templates, fragments, and conditions</td></tr>
|
|
233
|
+
<tr><td><code>rootDir</code></td><td><code>string</code></td><td>Directory of <code>pagePath</code></td><td>Root for template, fragment, and global file search</td></tr>
|
|
234
|
+
</tbody>
|
|
235
|
+
</table>
|
|
236
|
+
</div>
|
|
237
|
+
<p>A common use case is sending templated emails. Create a dedicated email directory with a shared template, per-email pages, reusable fragments, and optional global content:</p>
|
|
238
|
+
<pre><code class="hljs javascript"><span class="hljs-keyword">import</span> { renderPageToString } <span class="hljs-keyword">from</span> <span class="hljs-string">'kempo-server/templating'</span>;<br /><span class="hljs-keyword">import</span> path <span class="hljs-keyword">from</span> <span class="hljs-string">'path'</span>;<br /><br /><span class="hljs-keyword">const</span> emailsDir = path.resolve(<span class="hljs-string">'./emails'</span>);<br /><span class="hljs-keyword">const</span> html = <span class="hljs-keyword">await</span> renderPageToString(<br /> path.join(emailsDir, <span class="hljs-string">'welcome.page.html'</span>),<br /> { userName: <span class="hljs-string">'Alice'</span>, orderId: <span class="hljs-string">'1234'</span> }<br />);</code></pre>
|
|
239
|
+
<p>Built-in vars (<code>{{year}}</code>, <code>{{date}}</code>, <code>{{datetime}}</code>, <code>{{timestamp}}</code>) are always available. Note that <code><page></code> tag attributes take highest priority and override <code>vars</code> with the same key.</p>
|
|
240
|
+
|
|
241
|
+
<h3 id="render-external-page">renderExternalPage</h3>
|
|
242
|
+
<p>Identical pipeline to <code>renderPage</code>, but decouples the page file's physical location from where templates and fragments are resolved. Use this when a page file lives outside <code>rootDir</code> — for example, in a plugin or extension package — but should be rendered using the host project's templates, fragments, and globals.</p>
|
|
243
|
+
<div class="table-wrapper mb">
|
|
244
|
+
<table>
|
|
245
|
+
<thead>
|
|
246
|
+
<tr><th>Parameter</th><th>Type</th><th>Default</th><th>Description</th></tr>
|
|
247
|
+
</thead>
|
|
248
|
+
<tbody>
|
|
249
|
+
<tr><td><code>pageFilePath</code></td><td><code>string</code></td><td><em>required</em></td><td>Absolute path to the <code>.page.html</code> file. May live outside <code>rootDir</code>. Used only to read content.</td></tr>
|
|
250
|
+
<tr><td><code>rootDir</code></td><td><code>string</code></td><td><em>required</em></td><td>Ceiling for template/fragment walk-up. <code>*.global.html</code> files are scanned from here.</td></tr>
|
|
251
|
+
<tr><td><code>resolveDir</code></td><td><code>string</code></td><td><em>required</em></td><td>Directory within <code>rootDir</code> where template and fragment walk-up starts. <code>pathToRoot</code> is calculated from here.</td></tr>
|
|
252
|
+
<tr><td><code>globals</code></td><td><code>object</code></td><td><code>{}</code></td><td>Global variables available to all pages</td></tr>
|
|
253
|
+
<tr><td><code>state</code></td><td><code>object</code></td><td><code>{}</code></td><td>Per-render variables</td></tr>
|
|
254
|
+
<tr><td><code>maxDepth</code></td><td><code>number</code></td><td><code>10</code></td><td>Maximum fragment nesting depth</td></tr>
|
|
255
|
+
</tbody>
|
|
256
|
+
</table>
|
|
257
|
+
</div>
|
|
258
|
+
<pre><code class="hljs javascript"><span class="hljs-keyword">import</span> { renderExternalPage } <span class="hljs-keyword">from</span> <span class="hljs-string">'kempo-server/templating'</span>;<br /><span class="hljs-keyword">import</span> path <span class="hljs-keyword">from</span> <span class="hljs-string">'path'</span>;<br /><br /><span class="hljs-comment">// Page lives in an extension package, rendered with the host app's templates</span><br /><span class="hljs-keyword">const</span> html = <span class="hljs-keyword">await</span> renderExternalPage(<br /> path.resolve(<span class="hljs-string">'./node_modules/my-ext/admin/dashboard.page.html'</span>),<br /> path.resolve(<span class="hljs-string">'./public'</span>), <span class="hljs-comment">// rootDir</span><br /> path.resolve(<span class="hljs-string">'./public/admin'</span>), <span class="hljs-comment">// resolveDir</span><br /> globals,<br /> state<br />);</code></pre>
|
|
222
259
|
|
|
223
260
|
<h2 id="ssr">Server-Side Rendering</h2>
|
|
224
261
|
<p>Pages can also be rendered on each request instead of pre-built. This is useful during development so you can see changes without rebuilding.</p>
|
package/package.json
CHANGED
package/src/templating/index.js
CHANGED
|
@@ -63,9 +63,9 @@ const loadGlobalContent = async rootDir => {
|
|
|
63
63
|
};
|
|
64
64
|
|
|
65
65
|
/*
|
|
66
|
-
Render a Single Page
|
|
66
|
+
Render a Single Page (internal — accepts explicit resolveDir)
|
|
67
67
|
*/
|
|
68
|
-
const
|
|
68
|
+
const renderPageCore = async (pageFilePath, rootDir, resolveDir, globals = {}, state = {}, maxDepth = 10, preloadedGlobalContent = null) => {
|
|
69
69
|
const pageContent = await readFile(pageFilePath, 'utf8');
|
|
70
70
|
const pageTagMatch = pageContent.match(/^[\s\S]*?<page((?:[^>"']|"[^"]*"|'[^']*')*)>/);
|
|
71
71
|
if(!pageTagMatch) throw new Error(`Invalid page file: missing <page> root element in ${pageFilePath}`);
|
|
@@ -73,15 +73,14 @@ const renderPage = async (pageFilePath, rootDir, globals = {}, state = {}, maxDe
|
|
|
73
73
|
const templateName = pageAttrs.template || 'default';
|
|
74
74
|
delete pageAttrs.template;
|
|
75
75
|
|
|
76
|
-
|
|
77
|
-
let templateFile = findFileUpSync(`${templateName}.template.html`, pageDir, rootDir);
|
|
76
|
+
let templateFile = findFileUpSync(`${templateName}.template.html`, resolveDir, rootDir);
|
|
78
77
|
|
|
79
78
|
// If the specified template is not found, fall back to default.template.html
|
|
80
|
-
if
|
|
81
|
-
templateFile = findFileUpSync('default.template.html',
|
|
79
|
+
if(!templateFile && templateName !== 'default'){
|
|
80
|
+
templateFile = findFileUpSync('default.template.html', resolveDir, rootDir);
|
|
82
81
|
}
|
|
83
82
|
|
|
84
|
-
if(!templateFile) throw new Error(`Template not found: ${templateName}.template.html or default.template.html (searched from ${
|
|
83
|
+
if(!templateFile) throw new Error(`Template not found: ${templateName}.template.html or default.template.html (searched from ${resolveDir} to ${rootDir})`);
|
|
85
84
|
|
|
86
85
|
const globalContent = preloadedGlobalContent ?? await loadGlobalContent(rootDir);
|
|
87
86
|
const rawPageBlocks = extractContentBlocks(pageContent);
|
|
@@ -96,7 +95,7 @@ const renderPage = async (pageFilePath, rootDir, globals = {}, state = {}, maxDe
|
|
|
96
95
|
let templateHtml = readFileSync(templateFile, 'utf8');
|
|
97
96
|
|
|
98
97
|
const findFragmentFile = name => {
|
|
99
|
-
const filePath = findFileUpSync(name + '.fragment.html',
|
|
98
|
+
const filePath = findFileUpSync(name + '.fragment.html', resolveDir, rootDir);
|
|
100
99
|
if(!filePath) return null;
|
|
101
100
|
return readFileSync(filePath, 'utf8');
|
|
102
101
|
};
|
|
@@ -104,7 +103,7 @@ const renderPage = async (pageFilePath, rootDir, globals = {}, state = {}, maxDe
|
|
|
104
103
|
templateHtml = resolveFragmentTags(templateHtml, findFragmentFile, 0, maxDepth);
|
|
105
104
|
templateHtml = replaceLocations(templateHtml, contentBlocks);
|
|
106
105
|
|
|
107
|
-
const rel = path.relative(rootDir,
|
|
106
|
+
const rel = path.relative(rootDir, resolveDir);
|
|
108
107
|
const depth = rel ? rel.split(path.sep).length : 0;
|
|
109
108
|
const now = new Date();
|
|
110
109
|
|
|
@@ -133,6 +132,18 @@ const renderPage = async (pageFilePath, rootDir, globals = {}, state = {}, maxDe
|
|
|
133
132
|
return templateHtml;
|
|
134
133
|
};
|
|
135
134
|
|
|
135
|
+
/*
|
|
136
|
+
Render a Single Page
|
|
137
|
+
*/
|
|
138
|
+
const renderPage = (pageFilePath, rootDir, globals = {}, state = {}, maxDepth = 10, preloadedGlobalContent = null) =>
|
|
139
|
+
renderPageCore(pageFilePath, rootDir, path.dirname(pageFilePath), globals, state, maxDepth, preloadedGlobalContent);
|
|
140
|
+
|
|
141
|
+
/*
|
|
142
|
+
Render a Page File That Lives Outside rootDir
|
|
143
|
+
*/
|
|
144
|
+
const renderExternalPage = (pageFilePath, rootDir, resolveDir, globals = {}, state = {}, maxDepth = 10) =>
|
|
145
|
+
renderPageCore(pageFilePath, rootDir, resolveDir, globals, state, maxDepth, null);
|
|
146
|
+
|
|
136
147
|
/*
|
|
137
148
|
Recursively Walk Directory for *.page.html
|
|
138
149
|
*/
|
|
@@ -168,4 +179,7 @@ const renderDir = async (inputDir, outputDir, globals = {}, state = {}, maxDepth
|
|
|
168
179
|
return count;
|
|
169
180
|
};
|
|
170
181
|
|
|
171
|
-
|
|
182
|
+
const renderPageToString = (pagePath, vars = {}, rootDir = path.dirname(pagePath)) =>
|
|
183
|
+
renderPage(pagePath, rootDir, {}, vars);
|
|
184
|
+
|
|
185
|
+
export { renderPage, renderDir, renderPageToString, renderExternalPage };
|
|
@@ -0,0 +1,219 @@
|
|
|
1
|
+
import { renderExternalPage } from '../src/templating/index.js';
|
|
2
|
+
import { writeFile, mkdir } from 'fs/promises';
|
|
3
|
+
import path from 'path';
|
|
4
|
+
import { withTempDir } from './utils/temp-dir.js';
|
|
5
|
+
|
|
6
|
+
const setupFiles = async (dir, files) => {
|
|
7
|
+
for(const [rel, content] of Object.entries(files)){
|
|
8
|
+
const full = path.join(dir, rel);
|
|
9
|
+
await mkdir(path.dirname(full), {recursive: true});
|
|
10
|
+
await writeFile(full, content, 'utf8');
|
|
11
|
+
}
|
|
12
|
+
};
|
|
13
|
+
|
|
14
|
+
export default {
|
|
15
|
+
'renderExternalPage renders page outside rootDir using rootDir templates': async ({pass, fail}) => {
|
|
16
|
+
await withTempDir(async rootDir => {
|
|
17
|
+
await withTempDir(async externalDir => {
|
|
18
|
+
await setupFiles(rootDir, {
|
|
19
|
+
'default.template.html': '<html><body><location name="main" /></body></html>'
|
|
20
|
+
});
|
|
21
|
+
await setupFiles(externalDir, {
|
|
22
|
+
'admin.page.html': '<page><content location="main"><h1>Admin</h1></content></page>'
|
|
23
|
+
});
|
|
24
|
+
const html = await renderExternalPage(
|
|
25
|
+
path.join(externalDir, 'admin.page.html'),
|
|
26
|
+
rootDir,
|
|
27
|
+
rootDir
|
|
28
|
+
);
|
|
29
|
+
if(!html.includes('<h1>Admin</h1>')) return fail(`page content missing: ${html}`);
|
|
30
|
+
if(!html.includes('<html>')) return fail(`template not used: ${html}`);
|
|
31
|
+
pass();
|
|
32
|
+
});
|
|
33
|
+
});
|
|
34
|
+
},
|
|
35
|
+
|
|
36
|
+
'renderExternalPage resolveDir controls template walk-up': async ({pass, fail}) => {
|
|
37
|
+
await withTempDir(async rootDir => {
|
|
38
|
+
await withTempDir(async externalDir => {
|
|
39
|
+
// template is only in rootDir/admin/ — resolveDir points there
|
|
40
|
+
await setupFiles(rootDir, {
|
|
41
|
+
'admin/admin.template.html': '<admin><location name="body" /></admin>'
|
|
42
|
+
});
|
|
43
|
+
await setupFiles(externalDir, {
|
|
44
|
+
'page.page.html': '<page template="admin"><content location="body">content</content></page>'
|
|
45
|
+
});
|
|
46
|
+
const html = await renderExternalPage(
|
|
47
|
+
path.join(externalDir, 'page.page.html'),
|
|
48
|
+
rootDir,
|
|
49
|
+
path.join(rootDir, 'admin')
|
|
50
|
+
);
|
|
51
|
+
if(!html.includes('<admin>')) return fail(`admin template not resolved: ${html}`);
|
|
52
|
+
if(!html.includes('content')) return fail(`body missing: ${html}`);
|
|
53
|
+
pass();
|
|
54
|
+
});
|
|
55
|
+
});
|
|
56
|
+
},
|
|
57
|
+
|
|
58
|
+
'renderExternalPage resolveDir controls fragment resolution': async ({pass, fail}) => {
|
|
59
|
+
await withTempDir(async rootDir => {
|
|
60
|
+
await withTempDir(async externalDir => {
|
|
61
|
+
await setupFiles(rootDir, {
|
|
62
|
+
'default.template.html': '<fragment name="sig" /><location name="main" />',
|
|
63
|
+
'sig.fragment.html': '<p>Signature</p>'
|
|
64
|
+
});
|
|
65
|
+
await setupFiles(externalDir, {
|
|
66
|
+
'page.page.html': '<page><content location="main">body</content></page>'
|
|
67
|
+
});
|
|
68
|
+
const html = await renderExternalPage(
|
|
69
|
+
path.join(externalDir, 'page.page.html'),
|
|
70
|
+
rootDir,
|
|
71
|
+
rootDir
|
|
72
|
+
);
|
|
73
|
+
if(!html.includes('<p>Signature</p>')) return fail(`fragment missing: ${html}`);
|
|
74
|
+
pass();
|
|
75
|
+
});
|
|
76
|
+
});
|
|
77
|
+
},
|
|
78
|
+
|
|
79
|
+
'renderExternalPage pathToRoot reflects resolveDir depth not page file location': async ({pass, fail}) => {
|
|
80
|
+
await withTempDir(async rootDir => {
|
|
81
|
+
await withTempDir(async externalDir => {
|
|
82
|
+
await setupFiles(rootDir, {
|
|
83
|
+
'default.template.html': '{{pathToRoot}}<location name="main" />'
|
|
84
|
+
});
|
|
85
|
+
await setupFiles(externalDir, {
|
|
86
|
+
// page lives outside rootDir — its actual location is irrelevant
|
|
87
|
+
'deep/nested/page.page.html': '<page><content location="main">x</content></page>'
|
|
88
|
+
});
|
|
89
|
+
// resolveDir is rootDir/section/ — depth 1
|
|
90
|
+
await mkdir(path.join(rootDir, 'section'), {recursive: true});
|
|
91
|
+
const html = await renderExternalPage(
|
|
92
|
+
path.join(externalDir, 'deep', 'nested', 'page.page.html'),
|
|
93
|
+
rootDir,
|
|
94
|
+
path.join(rootDir, 'section')
|
|
95
|
+
);
|
|
96
|
+
if(!html.includes('../')) return fail(`pathToRoot should reflect resolveDir depth: ${html}`);
|
|
97
|
+
// rootDir itself gives depth 0 — resolveDir one level deep gives '../'
|
|
98
|
+
pass();
|
|
99
|
+
});
|
|
100
|
+
});
|
|
101
|
+
},
|
|
102
|
+
|
|
103
|
+
'renderExternalPage uses global content from rootDir': async ({pass, fail}) => {
|
|
104
|
+
await withTempDir(async rootDir => {
|
|
105
|
+
await withTempDir(async externalDir => {
|
|
106
|
+
await setupFiles(rootDir, {
|
|
107
|
+
'default.template.html': '<location name="banner" /><location name="main" />',
|
|
108
|
+
'site.global.html': '<content location="banner"><b>Global Banner</b></content>'
|
|
109
|
+
});
|
|
110
|
+
await setupFiles(externalDir, {
|
|
111
|
+
'page.page.html': '<page><content location="main">body</content></page>'
|
|
112
|
+
});
|
|
113
|
+
const html = await renderExternalPage(
|
|
114
|
+
path.join(externalDir, 'page.page.html'),
|
|
115
|
+
rootDir,
|
|
116
|
+
rootDir
|
|
117
|
+
);
|
|
118
|
+
if(!html.includes('<b>Global Banner</b>')) return fail(`global missing: ${html}`);
|
|
119
|
+
pass();
|
|
120
|
+
});
|
|
121
|
+
});
|
|
122
|
+
},
|
|
123
|
+
|
|
124
|
+
'renderExternalPage interpolates vars': async ({pass, fail}) => {
|
|
125
|
+
await withTempDir(async rootDir => {
|
|
126
|
+
await withTempDir(async externalDir => {
|
|
127
|
+
await setupFiles(rootDir, {
|
|
128
|
+
'default.template.html': '<location name="main" />'
|
|
129
|
+
});
|
|
130
|
+
await setupFiles(externalDir, {
|
|
131
|
+
'page.page.html': '<page><content location="main">Hello {{name}}</content></page>'
|
|
132
|
+
});
|
|
133
|
+
const html = await renderExternalPage(
|
|
134
|
+
path.join(externalDir, 'page.page.html'),
|
|
135
|
+
rootDir,
|
|
136
|
+
rootDir,
|
|
137
|
+
{},
|
|
138
|
+
{name: 'World'}
|
|
139
|
+
);
|
|
140
|
+
if(!html.includes('Hello World')) return fail(`var not interpolated: ${html}`);
|
|
141
|
+
pass();
|
|
142
|
+
});
|
|
143
|
+
});
|
|
144
|
+
},
|
|
145
|
+
|
|
146
|
+
'renderExternalPage processes if conditionals': async ({pass, fail}) => {
|
|
147
|
+
await withTempDir(async rootDir => {
|
|
148
|
+
await withTempDir(async externalDir => {
|
|
149
|
+
await setupFiles(rootDir, {
|
|
150
|
+
'default.template.html': '<location name="main" />'
|
|
151
|
+
});
|
|
152
|
+
await setupFiles(externalDir, {
|
|
153
|
+
'page.page.html': '<page><content location="main"><if condition="show">visible</if></content></page>'
|
|
154
|
+
});
|
|
155
|
+
const shown = await renderExternalPage(
|
|
156
|
+
path.join(externalDir, 'page.page.html'),
|
|
157
|
+
rootDir,
|
|
158
|
+
rootDir,
|
|
159
|
+
{},
|
|
160
|
+
{show: true}
|
|
161
|
+
);
|
|
162
|
+
if(!shown.includes('visible')) return fail(`should show: ${shown}`);
|
|
163
|
+
const hidden = await renderExternalPage(
|
|
164
|
+
path.join(externalDir, 'page.page.html'),
|
|
165
|
+
rootDir,
|
|
166
|
+
rootDir,
|
|
167
|
+
{},
|
|
168
|
+
{show: false}
|
|
169
|
+
);
|
|
170
|
+
if(hidden.includes('visible')) return fail(`should hide: ${hidden}`);
|
|
171
|
+
pass();
|
|
172
|
+
});
|
|
173
|
+
});
|
|
174
|
+
},
|
|
175
|
+
|
|
176
|
+
'renderExternalPage throws on missing template': async ({pass, fail}) => {
|
|
177
|
+
await withTempDir(async rootDir => {
|
|
178
|
+
await withTempDir(async externalDir => {
|
|
179
|
+
await setupFiles(externalDir, {
|
|
180
|
+
'page.page.html': '<page template="missing"><content location="main">x</content></page>'
|
|
181
|
+
});
|
|
182
|
+
try {
|
|
183
|
+
await renderExternalPage(
|
|
184
|
+
path.join(externalDir, 'page.page.html'),
|
|
185
|
+
rootDir,
|
|
186
|
+
rootDir
|
|
187
|
+
);
|
|
188
|
+
fail('should have thrown');
|
|
189
|
+
} catch(e){
|
|
190
|
+
if(!e.message.includes('Template not found')) return fail(`wrong error: ${e.message}`);
|
|
191
|
+
pass();
|
|
192
|
+
}
|
|
193
|
+
});
|
|
194
|
+
});
|
|
195
|
+
},
|
|
196
|
+
|
|
197
|
+
'renderExternalPage identical output to renderPage for page inside rootDir': async ({pass, fail}) => {
|
|
198
|
+
await withTempDir(async rootDir => {
|
|
199
|
+
await withTempDir(async externalDir => {
|
|
200
|
+
const template = '<html><body><location name="main" /></body></html>';
|
|
201
|
+
const pageContent = '<page><content location="main"><p>same</p></content></page>';
|
|
202
|
+
await setupFiles(rootDir, {'default.template.html': template});
|
|
203
|
+
await setupFiles(externalDir, {'page.page.html': pageContent});
|
|
204
|
+
// Copy page content into rootDir so renderPage can serve as reference
|
|
205
|
+
await setupFiles(rootDir, {'page.page.html': pageContent});
|
|
206
|
+
|
|
207
|
+
const { renderPage } = await import('../src/templating/index.js');
|
|
208
|
+
const reference = await renderPage(path.join(rootDir, 'page.page.html'), rootDir);
|
|
209
|
+
const result = await renderExternalPage(
|
|
210
|
+
path.join(externalDir, 'page.page.html'),
|
|
211
|
+
rootDir,
|
|
212
|
+
rootDir
|
|
213
|
+
);
|
|
214
|
+
if(result !== reference) return fail(`output differs:\nexpected: ${reference}\ngot: ${result}`);
|
|
215
|
+
pass();
|
|
216
|
+
});
|
|
217
|
+
});
|
|
218
|
+
}
|
|
219
|
+
};
|
|
@@ -0,0 +1,178 @@
|
|
|
1
|
+
import { renderPageToString } from '../src/templating/index.js';
|
|
2
|
+
import { writeFile, mkdir } from 'fs/promises';
|
|
3
|
+
import path from 'path';
|
|
4
|
+
import { withTempDir } from './utils/temp-dir.js';
|
|
5
|
+
|
|
6
|
+
const setupFiles = async (dir, files) => {
|
|
7
|
+
for(const [rel, content] of Object.entries(files)){
|
|
8
|
+
const full = path.join(dir, rel);
|
|
9
|
+
await mkdir(path.dirname(full), {recursive: true});
|
|
10
|
+
await writeFile(full, content, 'utf8');
|
|
11
|
+
}
|
|
12
|
+
};
|
|
13
|
+
|
|
14
|
+
export default {
|
|
15
|
+
'renderPageToString returns html string': async ({pass, fail}) => {
|
|
16
|
+
await withTempDir(async dir => {
|
|
17
|
+
await setupFiles(dir, {
|
|
18
|
+
'default.template.html': '<html><body><location name="main" /></body></html>',
|
|
19
|
+
'index.page.html': '<page><content location="main"><h1>Hello</h1></content></page>'
|
|
20
|
+
});
|
|
21
|
+
const html = await renderPageToString(path.join(dir, 'index.page.html'));
|
|
22
|
+
if(typeof html !== 'string') return fail(`expected string, got ${typeof html}`);
|
|
23
|
+
if(!html.includes('<h1>Hello</h1>')) return fail(`missing content: ${html}`);
|
|
24
|
+
if(!html.includes('<html>')) return fail(`missing template: ${html}`);
|
|
25
|
+
pass();
|
|
26
|
+
});
|
|
27
|
+
},
|
|
28
|
+
|
|
29
|
+
'renderPageToString interpolates vars': async ({pass, fail}) => {
|
|
30
|
+
await withTempDir(async dir => {
|
|
31
|
+
await setupFiles(dir, {
|
|
32
|
+
'default.template.html': '<location name="main" />',
|
|
33
|
+
'welcome.page.html': '<page><content location="main">Hello {{userName}}</content></page>'
|
|
34
|
+
});
|
|
35
|
+
const html = await renderPageToString(path.join(dir, 'welcome.page.html'), {userName: 'Alice'});
|
|
36
|
+
if(!html.includes('Hello Alice')) return fail(`var not interpolated: ${html}`);
|
|
37
|
+
pass();
|
|
38
|
+
});
|
|
39
|
+
},
|
|
40
|
+
|
|
41
|
+
'renderPageToString uses named template': async ({pass, fail}) => {
|
|
42
|
+
await withTempDir(async dir => {
|
|
43
|
+
await setupFiles(dir, {
|
|
44
|
+
'email.template.html': '<email><location name="body" /></email>',
|
|
45
|
+
'welcome.page.html': '<page template="email"><content location="body">Welcome!</content></page>'
|
|
46
|
+
});
|
|
47
|
+
const html = await renderPageToString(path.join(dir, 'welcome.page.html'));
|
|
48
|
+
if(!html.includes('<email>')) return fail(`email template not used: ${html}`);
|
|
49
|
+
if(!html.includes('Welcome!')) return fail(`content missing: ${html}`);
|
|
50
|
+
pass();
|
|
51
|
+
});
|
|
52
|
+
},
|
|
53
|
+
|
|
54
|
+
'renderPageToString injects fragments': async ({pass, fail}) => {
|
|
55
|
+
await withTempDir(async dir => {
|
|
56
|
+
await setupFiles(dir, {
|
|
57
|
+
'email.template.html': '<fragment name="signature" /><location name="body" />',
|
|
58
|
+
'signature.fragment.html': '<p>Best regards, Acme Corp</p>',
|
|
59
|
+
'welcome.page.html': '<page template="email"><content location="body">Hi there</content></page>'
|
|
60
|
+
});
|
|
61
|
+
const html = await renderPageToString(path.join(dir, 'welcome.page.html'));
|
|
62
|
+
if(!html.includes('Best regards, Acme Corp')) return fail(`fragment missing: ${html}`);
|
|
63
|
+
if(!html.includes('Hi there')) return fail(`body missing: ${html}`);
|
|
64
|
+
pass();
|
|
65
|
+
});
|
|
66
|
+
},
|
|
67
|
+
|
|
68
|
+
'renderPageToString uses global content': async ({pass, fail}) => {
|
|
69
|
+
await withTempDir(async dir => {
|
|
70
|
+
await setupFiles(dir, {
|
|
71
|
+
'email.template.html': '<location name="promo" /><location name="body" />',
|
|
72
|
+
'promo.global.html': '<content location="promo"><b>Summer Sale!</b></content>',
|
|
73
|
+
'welcome.page.html': '<page template="email"><content location="body">Welcome</content></page>'
|
|
74
|
+
});
|
|
75
|
+
const html = await renderPageToString(path.join(dir, 'welcome.page.html'));
|
|
76
|
+
if(!html.includes('<b>Summer Sale!</b>')) return fail(`global promo missing: ${html}`);
|
|
77
|
+
if(!html.includes('Welcome')) return fail(`body missing: ${html}`);
|
|
78
|
+
pass();
|
|
79
|
+
});
|
|
80
|
+
},
|
|
81
|
+
|
|
82
|
+
'renderPageToString processes if conditionals': async ({pass, fail}) => {
|
|
83
|
+
await withTempDir(async dir => {
|
|
84
|
+
await setupFiles(dir, {
|
|
85
|
+
'default.template.html': '<location name="main" />',
|
|
86
|
+
'reset.page.html': '<page><content location="main"><if condition="resetLink">Click {{resetLink}}</if></content></page>'
|
|
87
|
+
});
|
|
88
|
+
const withLink = await renderPageToString(path.join(dir, 'reset.page.html'), {resetLink: 'https://example.com/reset'});
|
|
89
|
+
if(!withLink.includes('Click https://example.com/reset')) return fail(`link not rendered: ${withLink}`);
|
|
90
|
+
const withoutLink = await renderPageToString(path.join(dir, 'reset.page.html'), {});
|
|
91
|
+
if(withoutLink.includes('Click')) return fail(`should be hidden: ${withoutLink}`);
|
|
92
|
+
pass();
|
|
93
|
+
});
|
|
94
|
+
},
|
|
95
|
+
|
|
96
|
+
'renderPageToString processes foreach loops': async ({pass, fail}) => {
|
|
97
|
+
await withTempDir(async dir => {
|
|
98
|
+
await setupFiles(dir, {
|
|
99
|
+
'default.template.html': '<location name="main" />',
|
|
100
|
+
'order.page.html': '<page><content location="main"><foreach in="items" as="item"><li>{{item}}</li></foreach></content></page>'
|
|
101
|
+
});
|
|
102
|
+
const html = await renderPageToString(path.join(dir, 'order.page.html'), {items: ['Widget', 'Gadget']});
|
|
103
|
+
if(!html.includes('<li>Widget</li>')) return fail(`Widget missing: ${html}`);
|
|
104
|
+
if(!html.includes('<li>Gadget</li>')) return fail(`Gadget missing: ${html}`);
|
|
105
|
+
pass();
|
|
106
|
+
});
|
|
107
|
+
},
|
|
108
|
+
|
|
109
|
+
'renderPageToString accepts explicit rootDir': async ({pass, fail}) => {
|
|
110
|
+
await withTempDir(async dir => {
|
|
111
|
+
await setupFiles(dir, {
|
|
112
|
+
'email.template.html': '<location name="body" />',
|
|
113
|
+
'emails/welcome.page.html': '<page template="email"><content location="body">Hi</content></page>'
|
|
114
|
+
});
|
|
115
|
+
const pagePath = path.join(dir, 'emails', 'welcome.page.html');
|
|
116
|
+
const html = await renderPageToString(pagePath, {}, dir);
|
|
117
|
+
if(!html.includes('Hi')) return fail(`content missing with explicit rootDir: ${html}`);
|
|
118
|
+
pass();
|
|
119
|
+
});
|
|
120
|
+
},
|
|
121
|
+
|
|
122
|
+
'renderPageToString page attributes override vars': async ({pass, fail}) => {
|
|
123
|
+
await withTempDir(async dir => {
|
|
124
|
+
await setupFiles(dir, {
|
|
125
|
+
'default.template.html': '<title>{{title}}</title><location name="main" />',
|
|
126
|
+
'welcome.page.html': '<page title="Page Title"><content location="main">x</content></page>'
|
|
127
|
+
});
|
|
128
|
+
// page attributes take highest priority — they override vars with same key
|
|
129
|
+
const html = await renderPageToString(path.join(dir, 'welcome.page.html'), {title: 'Var Title'});
|
|
130
|
+
if(!html.includes('<title>Page Title</title>')) return fail(`page attr should win: ${html}`);
|
|
131
|
+
pass();
|
|
132
|
+
});
|
|
133
|
+
},
|
|
134
|
+
|
|
135
|
+
'renderPageToString throws on missing template': async ({pass, fail}) => {
|
|
136
|
+
await withTempDir(async dir => {
|
|
137
|
+
await setupFiles(dir, {
|
|
138
|
+
'welcome.page.html': '<page template="email"><content location="body">hi</content></page>'
|
|
139
|
+
});
|
|
140
|
+
try {
|
|
141
|
+
await renderPageToString(path.join(dir, 'welcome.page.html'));
|
|
142
|
+
fail('should have thrown');
|
|
143
|
+
} catch(e){
|
|
144
|
+
if(!e.message.includes('Template not found')) return fail(`wrong error: ${e.message}`);
|
|
145
|
+
pass();
|
|
146
|
+
}
|
|
147
|
+
});
|
|
148
|
+
},
|
|
149
|
+
|
|
150
|
+
'renderPageToString includes built-in year var': async ({pass, fail}) => {
|
|
151
|
+
await withTempDir(async dir => {
|
|
152
|
+
await setupFiles(dir, {
|
|
153
|
+
'default.template.html': '{{year}}<location name="main" />',
|
|
154
|
+
'index.page.html': '<page><content location="main">x</content></page>'
|
|
155
|
+
});
|
|
156
|
+
const html = await renderPageToString(path.join(dir, 'index.page.html'));
|
|
157
|
+
if(!html.includes(String(new Date().getFullYear()))) return fail(`year missing: ${html}`);
|
|
158
|
+
pass();
|
|
159
|
+
});
|
|
160
|
+
},
|
|
161
|
+
|
|
162
|
+
'renderPageToString shared template across multiple pages': async ({pass, fail}) => {
|
|
163
|
+
await withTempDir(async dir => {
|
|
164
|
+
await setupFiles(dir, {
|
|
165
|
+
'email.template.html': '<html><body><location name="body" /></body></html>',
|
|
166
|
+
'welcome.page.html': '<page template="email"><content location="body">Welcome email</content></page>',
|
|
167
|
+
'reset.page.html': '<page template="email"><content location="body">Reset email</content></page>'
|
|
168
|
+
});
|
|
169
|
+
const [welcome, reset] = await Promise.all([
|
|
170
|
+
renderPageToString(path.join(dir, 'welcome.page.html')),
|
|
171
|
+
renderPageToString(path.join(dir, 'reset.page.html'))
|
|
172
|
+
]);
|
|
173
|
+
if(!welcome.includes('<html>') || !welcome.includes('Welcome email')) return fail(`welcome wrong: ${welcome}`);
|
|
174
|
+
if(!reset.includes('<html>') || !reset.includes('Reset email')) return fail(`reset wrong: ${reset}`);
|
|
175
|
+
pass();
|
|
176
|
+
});
|
|
177
|
+
}
|
|
178
|
+
};
|