kempo-server 3.0.11 → 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 CHANGED
@@ -2,12 +2,16 @@
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
+
5
10
  ## [3.0.11] - 2026-04-16
6
11
 
7
12
  ### Added
8
13
 
9
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.
10
-
11
15
  ---
12
16
 
13
17
  ## [3.0.0] - 2026-04-09
package/README.md CHANGED
@@ -382,6 +382,45 @@ const html = await renderPageToString(
382
382
 
383
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
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
+
385
424
  ## Programmatic File Rescan
386
425
 
387
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:
@@ -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)},renderPage=async(pageFilePath,rootDir,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;const pageDir=path.dirname(pageFilePath);let templateFile=findFileUpSync(`${templateName}.template.html`,pageDir,rootDir);if(templateFile||"default"===templateName||(templateFile=findFileUpSync("default.template.html",pageDir,rootDir)),!templateFile)throw new Error(`Template not found: ${templateName}.template.html or default.template.html (searched from ${pageDir} 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",pageDir,rootDir);return filePath?readFileSync(filePath,"utf8"):null},0,maxDepth),templateHtml=replaceLocations(templateHtml,contentBlocks);const rel=path.relative(rootDir,path.dirname(pageFilePath)),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},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};
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};
@@ -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>&lt;if&gt;</code>, <code>&lt;foreach&gt;</code>, and <code>&#123;&#123;vars&#125;&#125;</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>&#123;&#123;varName&#125;&#125;</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>&lt;page&gt;</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>&lt;if&gt;</code>, <code>&lt;foreach&gt;</code>, and <code>&#123;&#123;vars&#125;&#125;</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>&#123;&#123;varName&#125;&#125;</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>&lt;page&gt;</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
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "kempo-server",
3
3
  "type": "module",
4
- "version": "3.0.11",
4
+ "version": "3.0.12",
5
5
  "description": "A lightweight, zero-dependency, file based routing server.",
6
6
  "exports": {
7
7
  "./rescan": "./dist/rescan.js",
@@ -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 renderPage = async (pageFilePath, rootDir, globals = {}, state = {}, maxDepth = 10, preloadedGlobalContent = null) => {
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
- const pageDir = path.dirname(pageFilePath);
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 (!templateFile && templateName !== 'default') {
81
- templateFile = findFileUpSync('default.template.html', pageDir, rootDir);
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 ${pageDir} to ${rootDir})`);
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', pageDir, rootDir);
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, path.dirname(pageFilePath));
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
  */
@@ -171,4 +182,4 @@ const renderDir = async (inputDir, outputDir, globals = {}, state = {}, maxDepth
171
182
  const renderPageToString = (pagePath, vars = {}, rootDir = path.dirname(pagePath)) =>
172
183
  renderPage(pagePath, rootDir, {}, vars);
173
184
 
174
- export { renderPage, renderDir, renderPageToString };
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
+ };