kempo-server 3.0.11 → 3.1.0

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,21 @@
2
2
 
3
3
  All notable changes to `kempo-server` are documented in this file.
4
4
 
5
+ ## [3.1.0] - 2026-04-19
6
+
7
+ ### Added
8
+ - **`rootPath` injected into custom middleware config.** When the server loads custom middleware, it now merges `rootPath` (the absolute path to the server root directory) into the config object passed to each middleware factory. Previously middleware received only the raw `middleware` config section; now it receives `{ ...middlewareConfig, rootPath }`. This allows middleware to resolve files relative to the project root without hardcoding paths.
9
+
10
+ ## [3.0.12] - 2026-04-17
11
+
12
+ ### Added
13
+ - **`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.
14
+
5
15
  ## [3.0.11] - 2026-04-16
6
16
 
7
17
  ### Added
8
18
 
9
19
  - **`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
20
  ---
12
21
 
13
22
  ## [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:
package/dist/router.js CHANGED
@@ -1 +1 @@
1
- import path from"path";import{readFile,stat,readdir}from"fs/promises";import{pathToFileURL}from"url";import defaultConfig from"./defaultConfig.js";import getFiles from"./getFiles.js";import findFile from"./findFile.js";import serveFile from"./serveFile.js";import MiddlewareRunner from"./middlewareRunner.js";import ModuleCache from"./moduleCache.js";import createRequestWrapper,{readRawBody,parseBody}from"./requestWrapper.js";import createResponseWrapper from"./responseWrapper.js";import{corsMiddleware,compressionMiddleware,rateLimitMiddleware,securityMiddleware,loggingMiddleware}from"./builtinMiddleware.js";import{onRescan}from"./rescan.js";import{renderDir,renderPage}from"./templating/index.js";export default async(flags,log)=>{log("Initializing router",3);const rootPath=path.isAbsolute(flags.root)?flags.root:path.join(process.cwd(),flags.root);log(`Root path: ${rootPath}`,3);let config=defaultConfig;try{const configFileName=flags.config||".config.js",configPath=path.isAbsolute(configFileName)?configFileName:path.join(rootPath,configFileName);if(log(`Config file name: ${configFileName}`,3),log(`Config path: ${configPath}`,3),path.isAbsolute(configFileName))log("Config file name is absolute, skipping validation",4);else{const relativeConfigPath=path.relative(rootPath,configPath);if(log(`Relative config path: ${relativeConfigPath}`,4),log(`Starts with '..': ${relativeConfigPath.startsWith("..")}`,4),relativeConfigPath.startsWith("..")||path.isAbsolute(relativeConfigPath))throw log("Validation failed - throwing error",4),new Error(`Config file must be within the server root directory. Config path: ${configPath}, Root path: ${rootPath}`);log("Validation passed",4)}let userConfig;if(log(`Loading config from: ${configPath}`,3),configPath.endsWith(".js")){const configUrl=pathToFileURL(configPath).href+`?t=${Date.now()}`;userConfig=(await import(configUrl)).default}else{const configContent=await readFile(configPath,"utf8");userConfig=JSON.parse(configContent)}if(!userConfig)throw new Error("Config file is empty or has no default export");config={...defaultConfig,...userConfig,allowedMimes:{...defaultConfig.allowedMimes,...userConfig.allowedMimes||{}},middleware:{...defaultConfig.middleware,...userConfig.middleware||{}},customRoutes:{...defaultConfig.customRoutes,...userConfig.customRoutes||{}},cache:{...defaultConfig.cache,...userConfig.cache||{}},templating:{...defaultConfig.templating,...userConfig.templating||{}}},log("User config loaded and merged with defaults",3)}catch(e){if(e.message.includes("Config file must be within the server root directory"))throw e;const configFileName=flags.config||".config.js";if(configFileName.endsWith(".js"))try{const jsonFallback=configFileName.replace(/\.js$/,".json"),jsonPath=path.isAbsolute(jsonFallback)?jsonFallback:path.join(rootPath,jsonFallback);log(`Trying JSON fallback: ${jsonPath}`,3);const configContent=await readFile(jsonPath,"utf8"),userConfig=JSON.parse(configContent);config={...defaultConfig,...userConfig,allowedMimes:{...defaultConfig.allowedMimes,...userConfig.allowedMimes||{}},middleware:{...defaultConfig.middleware,...userConfig.middleware||{}},customRoutes:{...defaultConfig.customRoutes,...userConfig.customRoutes||{}},cache:{...defaultConfig.cache,...userConfig.cache||{}},templating:{...defaultConfig.templating,...userConfig.templating||{}}},log("User config loaded from JSON fallback",3)}catch(e2){log("Using default config (no config file found)",3)}else log("Using default config (no config file found)",3)}const dis=new Set(config.disallowedRegex);if(dis.add("^/\\..*"),dis.add("\\.config\\.js$"),dis.add("\\.config\\.json$"),dis.add("\\.git/"),config.disallowedRegex=[...dis],log(`Config loaded with ${config.disallowedRegex.length} disallowed patterns`,3),config.templating.preRender){const{globals:globals,state:state,maxFragmentDepth:maxFragmentDepth}=config.templating,count=await renderDir(rootPath,rootPath,globals,state,maxFragmentDepth);log(`Pre-rendered ${count} page(s)`,2);for(const[urlPattern,dirPath]of Object.entries(config.customRoutes||{})){const baseDirRaw=dirPath.includes("*")?dirPath.split("*")[0]:dirPath,resolvedBaseDir=(path.isAbsolute(baseDirRaw)?baseDirRaw:path.resolve(rootPath,baseDirRaw)).replace(/[/\\]+$/,"");try{if(!(await stat(resolvedBaseDir)).isDirectory())continue;const extraCount=await renderDir(resolvedBaseDir,resolvedBaseDir,globals,state,maxFragmentDepth);log(`Pre-rendered ${extraCount} page(s) from custom route: ${urlPattern}`,2)}catch{}}}let files=await getFiles(rootPath,config,log);log(`Initial scan found ${files.length} files`,2),onRescan(async done=>{try{files=await getFiles(rootPath,config,log),log(`Rescan found ${files.length} files`,2),done(null,files.length)}catch(error){log(`Rescan failed: ${error.message}`,1),done(error)}});const middlewareRunner=new MiddlewareRunner;if(config.middleware?.cors?.enabled&&(middlewareRunner.use(corsMiddleware(config.middleware.cors)),log("CORS middleware enabled",3)),config.middleware?.compression?.enabled&&(middlewareRunner.use(compressionMiddleware(config.middleware.compression)),log("Compression middleware enabled",3)),config.middleware?.rateLimit?.enabled&&(middlewareRunner.use(rateLimitMiddleware(config.middleware.rateLimit)),log("Rate limit middleware enabled",3)),config.middleware?.security?.enabled&&(middlewareRunner.use(securityMiddleware(config.middleware.security)),log("Security middleware enabled",3)),config.middleware?.logging?.enabled&&(middlewareRunner.use(loggingMiddleware(config.middleware.logging,log)),log("Logging middleware enabled",3)),config.middleware?.custom&&config.middleware.custom.length>0){log(`Loading ${config.middleware.custom.length} custom middleware files`,3);for(const middlewarePath of config.middleware.custom)try{const resolvedPath=path.isAbsolute(middlewarePath)?middlewarePath:path.resolve(rootPath,middlewarePath),middlewareUrl=pathToFileURL(resolvedPath).href+`?t=${Date.now()}`,customMiddleware=(await import(middlewareUrl)).default;"function"==typeof customMiddleware?(middlewareRunner.use(customMiddleware(config.middleware)),log(`Custom middleware loaded: ${middlewarePath}`,3)):log(`Custom middleware error: ${middlewarePath} does not export a default function`,1)}catch(error){log(`Custom middleware error for ${middlewarePath}: ${error.message}`,1)}}let moduleCache=null;config.cache?.enabled&&(moduleCache=new ModuleCache(config.cache),log(`Module cache initialized: ${config.cache.maxSize} max modules, ${config.cache.maxMemoryMB}MB limit, ${config.cache.ttlMs}ms TTL`,2));const customRoutes=new Map,wildcardRoutes=new Map;if(config.customRoutes&&Object.keys(config.customRoutes).length>0){log(`Processing ${Object.keys(config.customRoutes).length} custom routes`,3);for(const[urlPath,filePath]of Object.entries(config.customRoutes))if(urlPath.includes("*")){const resolvedPath=path.isAbsolute(filePath)?filePath:path.resolve(rootPath,filePath);wildcardRoutes.set(urlPath,resolvedPath),log(`Wildcard route mapped: ${urlPath} -> ${resolvedPath}`,3)}else{const resolvedPath=path.isAbsolute(filePath)?filePath:path.resolve(rootPath,filePath);customRoutes.set(urlPath,resolvedPath),log(`Custom route mapped: ${urlPath} -> ${resolvedPath}`,3)}}const matchWildcardRoute=(requestPath,pattern)=>{const regexPattern=(pattern.startsWith("/")?pattern:"/"+pattern).replace(/\*\*/g,"(.+)").replace(/\*/g,"([^/]+)");return new RegExp(`^${regexPattern}$`).exec(requestPath)},serveStaticCustomFile=async(filePath,res)=>{const fileExtension=path.extname(filePath).toLowerCase().slice(1),mimeConfig=config.allowedMimes[fileExtension];let mimeType,encoding;"string"==typeof mimeConfig?(mimeType=mimeConfig,encoding=mimeType.startsWith("text/")?"utf8":void 0):(mimeType=mimeConfig?.mime||"application/octet-stream",encoding="utf8"===mimeConfig?.encoding?"utf8":void 0);const fileContent=await readFile(filePath,encoding);log(`Serving custom file as ${mimeType} (${fileContent.length} bytes)`,2);const contentType="utf8"===encoding&&mimeType.startsWith("text/")?`${mimeType}; charset=utf-8`:mimeType;res.writeHead(200,{"Content-Type":contentType}),res.end(fileContent)},executeRouteModule=async(filePath,req,res,params={})=>{let module;if(moduleCache&&config.cache?.enabled){const fileStats=await stat(filePath);if(module=moduleCache.get(filePath,fileStats),!module){const fileUrl=pathToFileURL(filePath).href+`?t=${Date.now()}`;module=await import(fileUrl);const estimatedSizeKB=fileStats.size/1024;moduleCache.set(filePath,module,fileStats,estimatedSizeKB)}}else{const fileUrl=pathToFileURL(filePath).href+`?t=${Date.now()}`;module=await import(fileUrl)}if("function"!=typeof module.default)return log(`Route file does not export a function: ${filePath}`,0),res.writeHead(500,{"Content-Type":"text/plain"}),void res.end("Route file does not export a function");const enhancedReq=createRequestWrapper(req,params),enhancedRes=createResponseWrapper(res),rawBody=await readRawBody(req);enhancedReq._rawBody=rawBody,enhancedReq.body=parseBody(rawBody,req.headers["content-type"]),moduleCache&&(enhancedReq._kempoCache=moduleCache),await module.default(enhancedReq,enhancedRes)},walkDynamic=async(base,segments)=>{if(0===segments.length)return{filePath:base,params:{}};const[head,...rest]=segments;let entries;try{entries=await readdir(base,{withFileTypes:!0})}catch{return null}for(const entry of entries)if(entry.name===head)if(entry.isDirectory()){const result=await walkDynamic(path.join(base,head),rest);if(result)return result}else if(entry.isFile()&&0===rest.length)return{filePath:path.join(base,head),params:{}};for(const entry of entries){if(!entry.isDirectory()||!entry.name.startsWith("[")||!entry.name.endsWith("]"))continue;const paramName=entry.name.slice(1,-1),result=await walkDynamic(path.join(base,entry.name),rest);if(result)return{filePath:result.filePath,params:{[paramName]:head,...result.params}}}return null},serveResolvedPath=async(filePath,fileStat,params,req,res)=>{if(fileStat.isDirectory()){const methodUpper=req.method.toUpperCase(),candidates=[`${methodUpper}.js`,`${methodUpper}.html`,`${methodUpper}.page.html`,"index.js","index.html","index.page.html","index.htm","CATCH.js","CATCH.html","CATCH.page.html"];for(const candidate of candidates){const candidatePath=path.join(filePath,candidate);try{await stat(candidatePath)}catch{continue}if(candidate.endsWith(".page.html")){log(`Rendering page template: ${candidatePath}`,2);const{globals:globals,state:state,maxFragmentDepth:maxFragmentDepth}=config.templating,html=await renderPage(candidatePath,rootPath,globals,state,maxFragmentDepth);return res.writeHead(200,{"Content-Type":"text/html; charset=utf-8"}),res.end(html),!0}return config.routeFiles.includes(candidate)?(log(`Executing route file: ${candidatePath}`,2),await executeRouteModule(candidatePath,req,res,params),!0):(log(`Serving index file: ${candidatePath}`,2),await serveStaticCustomFile(candidatePath,res),!0)}return null}const fileName=path.basename(filePath);if(fileName.endsWith(".page.html")){log(`Rendering page template: ${filePath}`,2);const{globals:globals,state:state,maxFragmentDepth:maxFragmentDepth}=config.templating,html=await renderPage(filePath,rootPath,globals,state,maxFragmentDepth);return res.writeHead(200,{"Content-Type":"text/html; charset=utf-8"}),res.end(html),!0}return config.routeFiles.includes(fileName)?(log(`Executing route file: ${filePath}`,2),await executeRouteModule(filePath,req,res,params),!0):(await serveStaticCustomFile(filePath,res),!0)},serveCustomRoutePath=async(resolvedFilePath,req,res,customRootDir=null)=>{let fileStat;try{fileStat=await stat(resolvedFilePath);const result=await serveResolvedPath(resolvedFilePath,fileStat,{},req,res);if(result)return result}catch(e){if("ENOENT"!==e.code)throw e}if(!fileStat){let current=resolvedFilePath;const remaining=[];for(;current!==path.dirname(current);){remaining.unshift(path.basename(current)),current=path.dirname(current);try{if(!(await stat(current)).isDirectory())break;const result=await walkDynamic(current,remaining);if(!result)break;const resolvedStat=await stat(result.filePath),served=await serveResolvedPath(result.filePath,resolvedStat,result.params,req,res);if(served)return served;break}catch(e2){if("ENOENT"!==e2.code)throw e2}}}if(config.templating?.ssr&&customRootDir){const{globals:globals,state:state,maxFragmentDepth:maxFragmentDepth}=config.templating,base=resolvedFilePath.replace(/\.html$/,"").replace(/[\/\\]+$/,"");for(const pageFile of[base+".page.html",path.join(base,"index.page.html")])try{await stat(pageFile);const html=await renderPage(pageFile,customRootDir,globals,state,maxFragmentDepth);return res.writeHead(200,{"Content-Type":"text/html; charset=utf-8"}),res.end(html),log(`SSR rendered custom route: ${pageFile}`,2),!0}catch(e){log(`SSR custom route miss for ${pageFile}: ${e.message}`,3)}}return null},rescanAttempts=new Map,serveCatchFallback=async(requestPath,req,res)=>{const candidates=["CATCH.js","CATCH.html","CATCH.page.html"];let dir=path.join(rootPath,requestPath.startsWith("/")?requestPath.slice(1):requestPath);for(path.extname(dir)&&(dir=path.dirname(dir));dir.startsWith(rootPath);){for(const candidate of candidates){const candidatePath=path.join(dir,candidate);try{await stat(candidatePath)}catch{continue}if(log(`Serving catch fallback: ${candidatePath}`,2),"CATCH.page.html"===candidate){const{globals:globals,state:state,maxFragmentDepth:maxFragmentDepth}=config.templating,html=await renderPage(candidatePath,rootPath,globals,state,maxFragmentDepth);return res.writeHead(404,{"Content-Type":"text/html; charset=utf-8"}),res.end(html),!0}if("CATCH.js"===candidate)return await executeRouteModule(candidatePath,req,res),!0;const fileContent=await readFile(candidatePath,"utf8");return res.writeHead(404,{"Content-Type":"text/html; charset=utf-8"}),res.end(fileContent),!0}const parent=path.dirname(dir);if(parent===dir)break;dir=parent}return!1},dynamicNoRescanPaths=new Set,shouldSkipRescan=requestPath=>config.noRescanPaths.some(pattern=>new RegExp(pattern).test(requestPath))?(log(`Skipping rescan for configured pattern: ${requestPath}`,3),!0):!!dynamicNoRescanPaths.has(requestPath)&&(log(`Skipping rescan for dynamically blacklisted path: ${requestPath}`,3),!0),handler=async(req,res)=>{if(parseInt(req.headers["content-length"]||"0",10)>config.maxBodySize)return res.writeHead(413,{"Content-Type":"text/plain"}),void res.end("Payload Too Large");const rawBody=await new Promise((resolve,reject)=>{if(["GET","HEAD"].includes(req.method)&&!req.headers["content-length"])return resolve("");let body="",size=0;req.on("data",chunk=>{if(size+=chunk.length,size>config.maxBodySize)return req.destroy(),void reject(new Error("Payload Too Large"));body+=chunk.toString()}),req.on("end",()=>resolve(body)),req.on("error",reject)}).catch(err=>{if("Payload Too Large"===err.message)return res.writeHead(413,{"Content-Type":"text/plain"}),res.end("Payload Too Large"),null;throw err});if(null===rawBody)return;req._bufferedBody=rawBody;const enhancedRequest=createRequestWrapper(req,{}),enhancedResponse=createResponseWrapper(res);enhancedRequest._rawBody=rawBody,enhancedRequest.body=parseBody(rawBody,req.headers["content-type"]),await middlewareRunner.run(enhancedRequest,enhancedResponse,async()=>{const requestPath=enhancedRequest.url.split("?")[0];log(`${enhancedRequest.method} ${requestPath}`,4),log(`customRoutes keys: ${Array.from(customRoutes.keys()).join(", ")}`,4);const normalizePath=p=>{try{let np=decodeURIComponent(p);return np.startsWith("/")||(np="/"+np),np.length>1&&np.endsWith("/")&&(np=np.slice(0,-1)),np}catch(e){log(`Warning: Failed to decode URI component "${p}": ${e.message}`,1);let np=p;return np.startsWith("/")||(np="/"+np),np.length>1&&np.endsWith("/")&&(np=np.slice(0,-1)),np}},normalizedRequestPath=normalizePath(requestPath);log(`Normalized requestPath: ${normalizedRequestPath}`,4);let matchedKey=null;for(const key of customRoutes.keys())if(normalizePath(key)===normalizedRequestPath){matchedKey=key;break}if(matchedKey){const customFilePath=customRoutes.get(matchedKey);log(`Serving custom route: ${normalizedRequestPath} -> ${customFilePath}`,3);try{if(await serveCustomRoutePath(customFilePath,req,res,customFilePath))return;return log(`Custom route path not found: ${customFilePath}`,1),res.writeHead(404,{"Content-Type":"text/plain"}),void res.end("Custom route file not found")}catch(error){return log(`Error serving custom route ${normalizedRequestPath}: ${error.message}`,1),res.writeHead(500,{"Content-Type":"text/plain"}),void res.end("Internal Server Error")}}const wildcardMatch=(requestPath=>{for(const[pattern,filePath]of wildcardRoutes){const matches=matchWildcardRoute(requestPath,pattern);if(matches)return{filePath:filePath,matches:matches}}return null})(requestPath);if(wildcardMatch){const resolvedFilePath=((filePath,matches)=>{let resolvedPath=filePath,matchIndex=1;for(;resolvedPath.includes("**")&&matchIndex<matches.length;)resolvedPath=resolvedPath.replace("**",matches[matchIndex]),matchIndex++;for(;resolvedPath.includes("*")&&matchIndex<matches.length;)resolvedPath=resolvedPath.replace("*",matches[matchIndex]),matchIndex++;return path.isAbsolute(resolvedPath)?resolvedPath:path.resolve(rootPath,resolvedPath)})(wildcardMatch.filePath,wildcardMatch.matches);log(`Serving wildcard route: ${requestPath} -> ${resolvedFilePath}`,3);try{const customRootDir=wildcardMatch.filePath.split("*")[0].replace(/[\/\\]+$/,"");if(await serveCustomRoutePath(resolvedFilePath,req,res,customRootDir))return;log(`Wildcard route path not found: ${requestPath}`,2)}catch(error){return log(`Error serving wildcard route ${requestPath}: ${error.message}`,1),enhancedResponse.writeHead(500,{"Content-Type":"text/plain"}),void enhancedResponse.end("Internal Server Error")}}const served=await serveFile(files,rootPath,requestPath,req.method,config,req,res,log,moduleCache);if(!served&&config.maxRescanAttempts>0&&!shouldSkipRescan(requestPath)){log("File not found, rescanning directory...",1),files=await getFiles(rootPath,config,log),log(`Rescan found ${files.length} files`,2);if(await serveFile(files,rootPath,requestPath,req.method,config,req,res,log,moduleCache))rescanAttempts.delete(requestPath);else{if((requestPath=>{const newAttempts=(rescanAttempts.get(requestPath)||0)+1;rescanAttempts.set(requestPath,newAttempts),newAttempts>config.maxRescanAttempts&&(dynamicNoRescanPaths.add(requestPath),log(`Path ${requestPath} added to dynamic blacklist after ${newAttempts} failed attempts`,1)),log(`Rescan attempt ${newAttempts}/${config.maxRescanAttempts} for: ${requestPath}`,3)})(requestPath),log(`404 - File not found after rescan: ${requestPath}`,1),await serveCatchFallback(requestPath,req,res))return;enhancedResponse.writeHead(404,{"Content-Type":"text/plain"}),enhancedResponse.end("Not Found")}}else if(!served){if(shouldSkipRescan(requestPath)?log(`404 - Skipped rescan for: ${requestPath}`,2):log(`404 - File not found: ${requestPath}`,1),await serveCatchFallback(requestPath,req,res))return;enhancedResponse.writeHead(404,{"Content-Type":"text/plain"}),enhancedResponse.end("Not Found")}})};return handler.moduleCache=moduleCache,handler.getStats=()=>moduleCache?.getStats()||null,handler.logCacheStats=()=>moduleCache?.logStats(log),handler.clearCache=()=>moduleCache?.clear(),handler};
1
+ import path from"path";import{readFile,stat,readdir}from"fs/promises";import{pathToFileURL}from"url";import defaultConfig from"./defaultConfig.js";import getFiles from"./getFiles.js";import findFile from"./findFile.js";import serveFile from"./serveFile.js";import MiddlewareRunner from"./middlewareRunner.js";import ModuleCache from"./moduleCache.js";import createRequestWrapper,{readRawBody,parseBody}from"./requestWrapper.js";import createResponseWrapper from"./responseWrapper.js";import{corsMiddleware,compressionMiddleware,rateLimitMiddleware,securityMiddleware,loggingMiddleware}from"./builtinMiddleware.js";import{onRescan}from"./rescan.js";import{renderDir,renderExternalPage}from"./templating/index.js";export default async(flags,log)=>{log("Initializing router",3);const rootPath=path.isAbsolute(flags.root)?flags.root:path.join(process.cwd(),flags.root);log(`Root path: ${rootPath}`,3);let config=defaultConfig;try{const configFileName=flags.config||".config.js",configPath=path.isAbsolute(configFileName)?configFileName:path.join(rootPath,configFileName);if(log(`Config file name: ${configFileName}`,3),log(`Config path: ${configPath}`,3),path.isAbsolute(configFileName))log("Config file name is absolute, skipping validation",4);else{const relativeConfigPath=path.relative(rootPath,configPath);if(log(`Relative config path: ${relativeConfigPath}`,4),log(`Starts with '..': ${relativeConfigPath.startsWith("..")}`,4),relativeConfigPath.startsWith("..")||path.isAbsolute(relativeConfigPath))throw log("Validation failed - throwing error",4),new Error(`Config file must be within the server root directory. Config path: ${configPath}, Root path: ${rootPath}`);log("Validation passed",4)}let userConfig;if(log(`Loading config from: ${configPath}`,3),configPath.endsWith(".js")){const configUrl=pathToFileURL(configPath).href+`?t=${Date.now()}`;userConfig=(await import(configUrl)).default}else{const configContent=await readFile(configPath,"utf8");userConfig=JSON.parse(configContent)}if(!userConfig)throw new Error("Config file is empty or has no default export");config={...defaultConfig,...userConfig,allowedMimes:{...defaultConfig.allowedMimes,...userConfig.allowedMimes||{}},middleware:{...defaultConfig.middleware,...userConfig.middleware||{}},customRoutes:{...defaultConfig.customRoutes,...userConfig.customRoutes||{}},cache:{...defaultConfig.cache,...userConfig.cache||{}},templating:{...defaultConfig.templating,...userConfig.templating||{}}},log("User config loaded and merged with defaults",3)}catch(e){if(e.message.includes("Config file must be within the server root directory"))throw e;const configFileName=flags.config||".config.js";if(configFileName.endsWith(".js"))try{const jsonFallback=configFileName.replace(/\.js$/,".json"),jsonPath=path.isAbsolute(jsonFallback)?jsonFallback:path.join(rootPath,jsonFallback);log(`Trying JSON fallback: ${jsonPath}`,3);const configContent=await readFile(jsonPath,"utf8"),userConfig=JSON.parse(configContent);config={...defaultConfig,...userConfig,allowedMimes:{...defaultConfig.allowedMimes,...userConfig.allowedMimes||{}},middleware:{...defaultConfig.middleware,...userConfig.middleware||{}},customRoutes:{...defaultConfig.customRoutes,...userConfig.customRoutes||{}},cache:{...defaultConfig.cache,...userConfig.cache||{}},templating:{...defaultConfig.templating,...userConfig.templating||{}}},log("User config loaded from JSON fallback",3)}catch(e2){log("Using default config (no config file found)",3)}else log("Using default config (no config file found)",3)}const dis=new Set(config.disallowedRegex);if(dis.add("^/\\..*"),dis.add("\\.config\\.js$"),dis.add("\\.config\\.json$"),dis.add("\\.git/"),config.disallowedRegex=[...dis],log(`Config loaded with ${config.disallowedRegex.length} disallowed patterns`,3),config.templating.preRender){const{globals:globals,state:state,maxFragmentDepth:maxFragmentDepth}=config.templating,count=await renderDir(rootPath,rootPath,globals,state,maxFragmentDepth);log(`Pre-rendered ${count} page(s)`,2);for(const[urlPattern,dirPath]of Object.entries(config.customRoutes||{})){const baseDirRaw=dirPath.includes("*")?dirPath.split("*")[0]:dirPath,resolvedBaseDir=(path.isAbsolute(baseDirRaw)?baseDirRaw:path.resolve(rootPath,baseDirRaw)).replace(/[/\\]+$/,"");try{if(!(await stat(resolvedBaseDir)).isDirectory())continue;const extraCount=await renderDir(resolvedBaseDir,resolvedBaseDir,globals,state,maxFragmentDepth);log(`Pre-rendered ${extraCount} page(s) from custom route: ${urlPattern}`,2)}catch{}}}let files=await getFiles(rootPath,config,log);log(`Initial scan found ${files.length} files`,2),onRescan(async done=>{try{files=await getFiles(rootPath,config,log),log(`Rescan found ${files.length} files`,2),done(null,files.length)}catch(error){log(`Rescan failed: ${error.message}`,1),done(error)}});const middlewareRunner=new MiddlewareRunner;if(config.middleware?.cors?.enabled&&(middlewareRunner.use(corsMiddleware(config.middleware.cors)),log("CORS middleware enabled",3)),config.middleware?.compression?.enabled&&(middlewareRunner.use(compressionMiddleware(config.middleware.compression)),log("Compression middleware enabled",3)),config.middleware?.rateLimit?.enabled&&(middlewareRunner.use(rateLimitMiddleware(config.middleware.rateLimit)),log("Rate limit middleware enabled",3)),config.middleware?.security?.enabled&&(middlewareRunner.use(securityMiddleware(config.middleware.security)),log("Security middleware enabled",3)),config.middleware?.logging?.enabled&&(middlewareRunner.use(loggingMiddleware(config.middleware.logging,log)),log("Logging middleware enabled",3)),config.middleware?.custom&&config.middleware.custom.length>0){log(`Loading ${config.middleware.custom.length} custom middleware files`,3);for(const middlewarePath of config.middleware.custom)try{const resolvedPath=path.isAbsolute(middlewarePath)?middlewarePath:path.resolve(rootPath,middlewarePath),middlewareUrl=pathToFileURL(resolvedPath).href+`?t=${Date.now()}`,customMiddleware=(await import(middlewareUrl)).default;"function"==typeof customMiddleware?(middlewareRunner.use(customMiddleware({...config.middleware,rootPath:rootPath})),log(`Custom middleware loaded: ${middlewarePath}`,3)):log(`Custom middleware error: ${middlewarePath} does not export a default function`,1)}catch(error){log(`Custom middleware error for ${middlewarePath}: ${error.message}`,1)}}let moduleCache=null;config.cache?.enabled&&(moduleCache=new ModuleCache(config.cache),log(`Module cache initialized: ${config.cache.maxSize} max modules, ${config.cache.maxMemoryMB}MB limit, ${config.cache.ttlMs}ms TTL`,2));const customRoutes=new Map,wildcardRoutes=new Map;if(config.customRoutes&&Object.keys(config.customRoutes).length>0){log(`Processing ${Object.keys(config.customRoutes).length} custom routes`,3);for(const[urlPath,filePath]of Object.entries(config.customRoutes))if(urlPath.includes("*")){const resolvedPath=path.isAbsolute(filePath)?filePath:path.resolve(rootPath,filePath);wildcardRoutes.set(urlPath,resolvedPath),log(`Wildcard route mapped: ${urlPath} -> ${resolvedPath}`,3)}else{const resolvedPath=path.isAbsolute(filePath)?filePath:path.resolve(rootPath,filePath);customRoutes.set(urlPath,resolvedPath),log(`Custom route mapped: ${urlPath} -> ${resolvedPath}`,3)}}const matchWildcardRoute=(requestPath,pattern)=>{const regexPattern=(pattern.startsWith("/")?pattern:"/"+pattern).replace(/\*\*/g,"\0GLOBSTAR\0").replace(/\*/g,"([^/]+)").replace(/\x00GLOBSTAR\x00/g,"(.*)");return new RegExp(`^${regexPattern}$`).exec(requestPath)},serveStaticCustomFile=async(filePath,res)=>{const fileExtension=path.extname(filePath).toLowerCase().slice(1),mimeConfig=config.allowedMimes[fileExtension];let mimeType,encoding;"string"==typeof mimeConfig?(mimeType=mimeConfig,encoding=mimeType.startsWith("text/")?"utf8":void 0):(mimeType=mimeConfig?.mime||"application/octet-stream",encoding="utf8"===mimeConfig?.encoding?"utf8":void 0);const fileContent=await readFile(filePath,encoding);log(`Serving custom file as ${mimeType} (${fileContent.length} bytes)`,2);const contentType="utf8"===encoding&&mimeType.startsWith("text/")?`${mimeType}; charset=utf-8`:mimeType;res.writeHead(200,{"Content-Type":contentType}),res.end(fileContent)},executeRouteModule=async(filePath,req,res,params={})=>{let module;if(moduleCache&&config.cache?.enabled){const fileStats=await stat(filePath);if(module=moduleCache.get(filePath,fileStats),!module){const fileUrl=pathToFileURL(filePath).href+`?t=${Date.now()}`;module=await import(fileUrl);const estimatedSizeKB=fileStats.size/1024;moduleCache.set(filePath,module,fileStats,estimatedSizeKB)}}else{const fileUrl=pathToFileURL(filePath).href+`?t=${Date.now()}`;module=await import(fileUrl)}if("function"!=typeof module.default)return log(`Route file does not export a function: ${filePath}`,0),res.writeHead(500,{"Content-Type":"text/plain"}),void res.end("Route file does not export a function");const enhancedReq=createRequestWrapper(req,params),enhancedRes=createResponseWrapper(res),rawBody=await readRawBody(req);enhancedReq._rawBody=rawBody,enhancedReq.body=parseBody(rawBody,req.headers["content-type"]),moduleCache&&(enhancedReq._kempoCache=moduleCache),await module.default(enhancedReq,enhancedRes)},walkDynamic=async(base,segments)=>{if(0===segments.length)return{filePath:base,params:{}};const[head,...rest]=segments;let entries;try{entries=await readdir(base,{withFileTypes:!0})}catch{return null}for(const entry of entries)if(entry.name===head)if(entry.isDirectory()){const result=await walkDynamic(path.join(base,head),rest);if(result)return result}else if(entry.isFile()&&0===rest.length)return{filePath:path.join(base,head),params:{}};for(const entry of entries){if(!entry.isDirectory()||!entry.name.startsWith("[")||!entry.name.endsWith("]"))continue;const paramName=entry.name.slice(1,-1),result=await walkDynamic(path.join(base,entry.name),rest);if(result)return{filePath:result.filePath,params:{[paramName]:head,...result.params}}}return null},getResolveDir=(pageFilePath,reqUrl)=>{if(pageFilePath.startsWith(rootPath))return path.dirname(pageFilePath);const urlParts=reqUrl.split("?")[0].replace(/\/+$/,"").split("/").filter(Boolean),depth=urlParts.length;let fakeDir=rootPath;for(let i=0;i<depth;i++)fakeDir=path.join(fakeDir,urlParts[i]||"__scope__");return fakeDir},serveResolvedPath=async(filePath,fileStat,params,req,res)=>{if(fileStat.isDirectory()){const methodUpper=req.method.toUpperCase(),candidates=[`${methodUpper}.js`,`${methodUpper}.html`,`${methodUpper}.page.html`,"index.js","index.html","index.page.html","index.htm","CATCH.js","CATCH.html","CATCH.page.html"];for(const candidate of candidates){const candidatePath=path.join(filePath,candidate);try{await stat(candidatePath)}catch{continue}if(candidate.endsWith(".page.html")){log(`Rendering page template: ${candidatePath}`,2);const{globals:globals,state:state,maxFragmentDepth:maxFragmentDepth}=config.templating,resolveDir=getResolveDir(candidatePath,req.url),html=await renderExternalPage(candidatePath,rootPath,resolveDir,globals,state,maxFragmentDepth);return res.writeHead(200,{"Content-Type":"text/html; charset=utf-8"}),res.end(html),!0}return config.routeFiles.includes(candidate)?(log(`Executing route file: ${candidatePath}`,2),await executeRouteModule(candidatePath,req,res,params),!0):(log(`Serving index file: ${candidatePath}`,2),await serveStaticCustomFile(candidatePath,res),!0)}return null}const fileName=path.basename(filePath);if(fileName.endsWith(".page.html")){log(`Rendering page template: ${filePath}`,2);const{globals:globals,state:state,maxFragmentDepth:maxFragmentDepth}=config.templating,resolveDir=getResolveDir(filePath,req.url),html=await renderExternalPage(filePath,rootPath,resolveDir,globals,state,maxFragmentDepth);return res.writeHead(200,{"Content-Type":"text/html; charset=utf-8"}),res.end(html),!0}return config.routeFiles.includes(fileName)?(log(`Executing route file: ${filePath}`,2),await executeRouteModule(filePath,req,res,params),!0):(await serveStaticCustomFile(filePath,res),!0)},serveCustomRoutePath=async(resolvedFilePath,req,res,customRootDir=null)=>{let fileStat;try{fileStat=await stat(resolvedFilePath);const result=await serveResolvedPath(resolvedFilePath,fileStat,{},req,res);if(result)return result}catch(e){if("ENOENT"!==e.code)throw e}if(!fileStat){let current=resolvedFilePath;const remaining=[];for(;current!==path.dirname(current);){remaining.unshift(path.basename(current)),current=path.dirname(current);try{if(!(await stat(current)).isDirectory())break;const result=await walkDynamic(current,remaining);if(!result)break;const resolvedStat=await stat(result.filePath),served=await serveResolvedPath(result.filePath,resolvedStat,result.params,req,res);if(served)return served;break}catch(e2){if("ENOENT"!==e2.code)throw e2}}}if(config.templating?.ssr&&customRootDir){const{globals:globals,state:state,maxFragmentDepth:maxFragmentDepth}=config.templating,base=resolvedFilePath.replace(/\.html$/,"").replace(/[\/\\]+$/,"");for(const pageFile of[base+".page.html",path.join(base,"index.page.html")])try{await stat(pageFile);const resolveDir=getResolveDir(pageFile,req.url),html=await renderExternalPage(pageFile,rootPath,resolveDir,globals,state,maxFragmentDepth);return res.writeHead(200,{"Content-Type":"text/html; charset=utf-8"}),res.end(html),log(`SSR rendered custom route: ${pageFile}`,2),!0}catch(e){log(`SSR custom route miss for ${pageFile}: ${e.message}`,3)}}return null},rescanAttempts=new Map,serveCatchFallbackFrom=async(startDir,boundDir,req,res)=>{const candidates=["CATCH.js","CATCH.html","CATCH.page.html"];let dir=path.extname(startDir)?path.dirname(startDir):startDir;const bound=path.resolve(boundDir);for(;path.resolve(dir).startsWith(bound);){for(const candidate of candidates){const candidatePath=path.join(dir,candidate);try{await stat(candidatePath)}catch{continue}if(log(`Serving catch fallback: ${candidatePath}`,2),"CATCH.page.html"===candidate){const{globals:globals,state:state,maxFragmentDepth:maxFragmentDepth}=config.templating,resolveDir=getResolveDir(candidatePath,req.url),html=await renderExternalPage(candidatePath,rootPath,resolveDir,globals,state,maxFragmentDepth);return res.writeHead(404,{"Content-Type":"text/html; charset=utf-8"}),res.end(html),!0}if("CATCH.js"===candidate)return await executeRouteModule(candidatePath,req,res),!0;const fileContent=await readFile(candidatePath,"utf8");return res.writeHead(404,{"Content-Type":"text/html; charset=utf-8"}),res.end(fileContent),!0}const parent=path.dirname(dir);if(parent===dir)break;dir=parent}return!1},serveCatchFallback=(requestPath,req,res)=>{const startDir=path.join(rootPath,requestPath.startsWith("/")?requestPath.slice(1):requestPath);return serveCatchFallbackFrom(startDir,rootPath,req,res)},dynamicNoRescanPaths=new Set,shouldSkipRescan=requestPath=>config.noRescanPaths.some(pattern=>new RegExp(pattern).test(requestPath))?(log(`Skipping rescan for configured pattern: ${requestPath}`,3),!0):!!dynamicNoRescanPaths.has(requestPath)&&(log(`Skipping rescan for dynamically blacklisted path: ${requestPath}`,3),!0),handler=async(req,res)=>{if(parseInt(req.headers["content-length"]||"0",10)>config.maxBodySize)return res.writeHead(413,{"Content-Type":"text/plain"}),void res.end("Payload Too Large");const rawBody=await new Promise((resolve,reject)=>{if(["GET","HEAD"].includes(req.method)&&!req.headers["content-length"])return resolve("");let body="",size=0;req.on("data",chunk=>{if(size+=chunk.length,size>config.maxBodySize)return req.destroy(),void reject(new Error("Payload Too Large"));body+=chunk.toString()}),req.on("end",()=>resolve(body)),req.on("error",reject)}).catch(err=>{if("Payload Too Large"===err.message)return res.writeHead(413,{"Content-Type":"text/plain"}),res.end("Payload Too Large"),null;throw err});if(null===rawBody)return;req._bufferedBody=rawBody;const enhancedRequest=createRequestWrapper(req,{}),enhancedResponse=createResponseWrapper(res);enhancedRequest._rawBody=rawBody,enhancedRequest.body=parseBody(rawBody,req.headers["content-type"]),await middlewareRunner.run(enhancedRequest,enhancedResponse,async()=>{const requestPath=enhancedRequest.url.split("?")[0];log(`${enhancedRequest.method} ${requestPath}`,4),log(`customRoutes keys: ${Array.from(customRoutes.keys()).join(", ")}`,4);const normalizePath=p=>{try{let np=decodeURIComponent(p);return np.startsWith("/")||(np="/"+np),np.length>1&&np.endsWith("/")&&(np=np.slice(0,-1)),np}catch(e){log(`Warning: Failed to decode URI component "${p}": ${e.message}`,1);let np=p;return np.startsWith("/")||(np="/"+np),np.length>1&&np.endsWith("/")&&(np=np.slice(0,-1)),np}},normalizedRequestPath=normalizePath(requestPath);log(`Normalized requestPath: ${normalizedRequestPath}`,4);let matchedKey=null;for(const key of customRoutes.keys())if(normalizePath(key)===normalizedRequestPath){matchedKey=key;break}if(matchedKey){const customFilePath=customRoutes.get(matchedKey);log(`Serving custom route: ${normalizedRequestPath} -> ${customFilePath}`,3);try{if(await serveCustomRoutePath(customFilePath,req,res,customFilePath))return;return log(`Custom route path not found: ${customFilePath}`,1),res.writeHead(404,{"Content-Type":"text/plain"}),void res.end("Custom route file not found")}catch(error){return log(`Error serving custom route ${normalizedRequestPath}: ${error.message}`,1),res.writeHead(500,{"Content-Type":"text/plain"}),void res.end("Internal Server Error")}}const wildcardMatch=(requestPath=>{for(const[pattern,filePath]of wildcardRoutes){const matches=matchWildcardRoute(requestPath,pattern);if(matches)return{filePath:filePath,matches:matches}}return null})(requestPath);if(wildcardMatch){const resolvedFilePath=((filePath,matches)=>{let resolvedPath=filePath,matchIndex=1;for(;resolvedPath.includes("**")&&matchIndex<matches.length;)resolvedPath=resolvedPath.replace("**",matches[matchIndex]),matchIndex++;for(;resolvedPath.includes("*")&&matchIndex<matches.length;)resolvedPath=resolvedPath.replace("*",matches[matchIndex]),matchIndex++;return path.isAbsolute(resolvedPath)?resolvedPath:path.resolve(rootPath,resolvedPath)})(wildcardMatch.filePath,wildcardMatch.matches);log(`Serving wildcard route: ${requestPath} -> ${resolvedFilePath}`,3);try{const customRootDir=wildcardMatch.filePath.split("*")[0].replace(/[\/\\]+$/,"");if(await serveCustomRoutePath(resolvedFilePath,req,res,customRootDir))return;if(log(`Wildcard route path not found: ${requestPath}`,2),await serveCatchFallbackFrom(resolvedFilePath,customRootDir,req,res))return}catch(error){return log(`Error serving wildcard route ${requestPath}: ${error.message}`,1),enhancedResponse.writeHead(500,{"Content-Type":"text/plain"}),void enhancedResponse.end("Internal Server Error")}}const served=await serveFile(files,rootPath,requestPath,req.method,config,req,res,log,moduleCache);if(!served&&config.maxRescanAttempts>0&&!shouldSkipRescan(requestPath)){log("File not found, rescanning directory...",1),files=await getFiles(rootPath,config,log),log(`Rescan found ${files.length} files`,2);if(await serveFile(files,rootPath,requestPath,req.method,config,req,res,log,moduleCache))rescanAttempts.delete(requestPath);else{if((requestPath=>{const newAttempts=(rescanAttempts.get(requestPath)||0)+1;rescanAttempts.set(requestPath,newAttempts),newAttempts>config.maxRescanAttempts&&(dynamicNoRescanPaths.add(requestPath),log(`Path ${requestPath} added to dynamic blacklist after ${newAttempts} failed attempts`,1)),log(`Rescan attempt ${newAttempts}/${config.maxRescanAttempts} for: ${requestPath}`,3)})(requestPath),log(`404 - File not found after rescan: ${requestPath}`,1),await serveCatchFallback(requestPath,req,res))return;enhancedResponse.writeHead(404,{"Content-Type":"text/plain"}),enhancedResponse.end("Not Found")}}else if(!served){if(shouldSkipRescan(requestPath)?log(`404 - Skipped rescan for: ${requestPath}`,2):log(`404 - File not found: ${requestPath}`,1),await serveCatchFallback(requestPath,req,res))return;enhancedResponse.writeHead(404,{"Content-Type":"text/plain"}),enhancedResponse.end("Not Found")}})};return handler.moduleCache=moduleCache,handler.getStats=()=>moduleCache?.getStats()||null,handler.logCacheStats=()=>moduleCache?.logStats(log),handler.clearCache=()=>moduleCache?.clear(),handler};
@@ -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};
@@ -176,7 +176,7 @@
176
176
 
177
177
  <h3>Middleware Function Parameters</h3>
178
178
  <ul>
179
- <li><code>config</code> - Configuration object (can be used for middleware settings)</li>
179
+ <li><code>config</code> - The middleware config object, extended with <code>rootPath</code> (absolute path to the server root directory)</li>
180
180
  <li><code>req</code> - Request object (can be modified)</li>
181
181
  <li><code>res</code> - Response object (can be modified)</li>
182
182
  <li><code>next</code> - Function to call the next middleware or route handler</li>
@@ -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-19</code>, <code>2026-04-19T16:45:40.333Z</code>, <code>1776617140333</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>
@@ -76,7 +76,7 @@
76
76
 
77
77
  <h3>Middleware Function Parameters</h3>
78
78
  <ul>
79
- <li><code>config</code> - Configuration object (can be used for middleware settings)</li>
79
+ <li><code>config</code> - The middleware config object, extended with <code>rootPath</code> (absolute path to the server root directory)</li>
80
80
  <li><code>req</code> - Request object (can be modified)</li>
81
81
  <li><code>res</code> - Response object (can be modified)</li>
82
82
  <li><code>next</code> - Function to call the next middleware or route handler</li>
@@ -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.1.0",
5
5
  "description": "A lightweight, zero-dependency, file based routing server.",
6
6
  "exports": {
7
7
  "./rescan": "./dist/rescan.js",
package/src/router.js CHANGED
@@ -17,7 +17,7 @@ import {
17
17
  loggingMiddleware
18
18
  } from './builtinMiddleware.js';
19
19
  import { onRescan } from './rescan.js';
20
- import { renderDir, renderPage } from './templating/index.js';
20
+ import { renderDir, renderExternalPage } from './templating/index.js';
21
21
 
22
22
  export default async (flags, log) => {
23
23
  log('Initializing router', 3);
@@ -218,7 +218,7 @@ export default async (flags, log) => {
218
218
  const customMiddleware = middlewareModule.default;
219
219
 
220
220
  if (typeof customMiddleware === 'function') {
221
- middlewareRunner.use(customMiddleware(config.middleware));
221
+ middlewareRunner.use(customMiddleware({ ...config.middleware, rootPath }));
222
222
  log(`Custom middleware loaded: ${middlewarePath}`, 3);
223
223
  } else {
224
224
  log(`Custom middleware error: ${middlewarePath} does not export a default function`, 1);
@@ -269,8 +269,9 @@ export default async (flags, log) => {
269
269
  // Convert wildcard pattern to regex
270
270
  // IMPORTANT: Replace ** BEFORE * to avoid replacing both * in **
271
271
  const regexPattern = normalizedPattern
272
- .replace(/\*\*/g, '(.+)') // Replace ** with capture group for multiple segments
273
- .replace(/\*/g, '([^/]+)'); // Replace * with capture group for single segment
272
+ .replace(/\*\*/g, '\x00GLOBSTAR\x00') // placeholder to avoid double-replace
273
+ .replace(/\*/g, '([^/]+)') // single * one path segment
274
+ .replace(/\x00GLOBSTAR\x00/g, '(.*)'); // ** — zero or more segments including slashes
274
275
 
275
276
  const regex = new RegExp(`^${regexPattern}$`);
276
277
  return regex.exec(requestPath);
@@ -395,6 +396,18 @@ export default async (flags, log) => {
395
396
  return null;
396
397
  };
397
398
 
399
+ // Build a virtual resolveDir that reflects the URL depth, so pathToRoot is computed correctly.
400
+ // For pages inside rootPath use their actual dir; for external pages fake a subdir at the right depth.
401
+ const getResolveDir = (pageFilePath, reqUrl) => {
402
+ if(pageFilePath.startsWith(rootPath)) return path.dirname(pageFilePath);
403
+ const urlParts = reqUrl.split('?')[0].replace(/\/+$/, '').split('/').filter(Boolean);
404
+ const depth = urlParts.length;
405
+ // Build a virtual path depth levels deep inside rootPath
406
+ let fakeDir = rootPath;
407
+ for(let i = 0; i < depth; i++) fakeDir = path.join(fakeDir, urlParts[i] || '__scope__');
408
+ return fakeDir;
409
+ };
410
+
398
411
  // Serve a resolved file or directory (fileStat already known).
399
412
  // Returns true if handled, null if directory has no matching route/index file.
400
413
  const serveResolvedPath = async (filePath, fileStat, params, req, res) => {
@@ -418,7 +431,8 @@ export default async (flags, log) => {
418
431
  if(candidate.endsWith('.page.html')) {
419
432
  log(`Rendering page template: ${candidatePath}`, 2);
420
433
  const {globals, state, maxFragmentDepth} = config.templating;
421
- const html = await renderPage(candidatePath, rootPath, globals, state, maxFragmentDepth);
434
+ const resolveDir = getResolveDir(candidatePath, req.url);
435
+ const html = await renderExternalPage(candidatePath, rootPath, resolveDir, globals, state, maxFragmentDepth);
422
436
  res.writeHead(200, {'Content-Type': 'text/html; charset=utf-8'});
423
437
  res.end(html);
424
438
  return true;
@@ -439,7 +453,8 @@ export default async (flags, log) => {
439
453
  if(fileName.endsWith('.page.html')) {
440
454
  log(`Rendering page template: ${filePath}`, 2);
441
455
  const {globals, state, maxFragmentDepth} = config.templating;
442
- const html = await renderPage(filePath, rootPath, globals, state, maxFragmentDepth);
456
+ const resolveDir = getResolveDir(filePath, req.url);
457
+ const html = await renderExternalPage(filePath, rootPath, resolveDir, globals, state, maxFragmentDepth);
443
458
  res.writeHead(200, {'Content-Type': 'text/html; charset=utf-8'});
444
459
  res.end(html);
445
460
  return true;
@@ -496,7 +511,8 @@ export default async (flags, log) => {
496
511
  for(const pageFile of [base + '.page.html', path.join(base, 'index.page.html')]) {
497
512
  try {
498
513
  await stat(pageFile);
499
- const html = await renderPage(pageFile, customRootDir, globals, state, maxFragmentDepth);
514
+ const resolveDir = getResolveDir(pageFile, req.url);
515
+ const html = await renderExternalPage(pageFile, rootPath, resolveDir, globals, state, maxFragmentDepth);
500
516
  res.writeHead(200, {'Content-Type': 'text/html; charset=utf-8'});
501
517
  res.end(html);
502
518
  log(`SSR rendered custom route: ${pageFile}`, 2);
@@ -513,22 +529,23 @@ export default async (flags, log) => {
513
529
  // Track 404 attempts to avoid unnecessary rescans
514
530
  const rescanAttempts = new Map(); // path -> attempt count
515
531
 
516
- // Walk up the directory tree from requestPath looking for CATCH.js, CATCH.html, CATCH.page.html.
532
+ // Walk up the directory tree looking for CATCH.js, CATCH.html, CATCH.page.html.
533
+ // startDir: absolute path to begin the walk. boundDir: walk stops here (inclusive).
517
534
  // Returns true if a catch fallback handler was found and served, false otherwise.
518
- const serveCatchFallback = async (requestPath, req, res) => {
535
+ const serveCatchFallbackFrom = async (startDir, boundDir, req, res) => {
519
536
  const candidates = ['CATCH.js', 'CATCH.html', 'CATCH.page.html'];
520
- let dir = path.join(rootPath, requestPath.startsWith('/') ? requestPath.slice(1) : requestPath);
521
- // Start from the requested directory (or its parent if it's a file path)
522
- if(path.extname(dir)) dir = path.dirname(dir);
537
+ let dir = path.extname(startDir) ? path.dirname(startDir) : startDir;
538
+ const bound = path.resolve(boundDir);
523
539
 
524
- while(dir.startsWith(rootPath)) {
540
+ while(path.resolve(dir).startsWith(bound)) {
525
541
  for(const candidate of candidates) {
526
542
  const candidatePath = path.join(dir, candidate);
527
543
  try { await stat(candidatePath); } catch { continue; }
528
544
  log(`Serving catch fallback: ${candidatePath}`, 2);
529
545
  if(candidate === 'CATCH.page.html') {
530
546
  const {globals, state, maxFragmentDepth} = config.templating;
531
- const html = await renderPage(candidatePath, rootPath, globals, state, maxFragmentDepth);
547
+ const resolveDir = getResolveDir(candidatePath, req.url);
548
+ const html = await renderExternalPage(candidatePath, rootPath, resolveDir, globals, state, maxFragmentDepth);
532
549
  res.writeHead(404, {'Content-Type': 'text/html; charset=utf-8'});
533
550
  res.end(html);
534
551
  return true;
@@ -549,6 +566,12 @@ export default async (flags, log) => {
549
566
  }
550
567
  return false;
551
568
  };
569
+
570
+ const serveCatchFallback = (requestPath, req, res) => {
571
+ const startDir = path.join(rootPath, requestPath.startsWith('/') ? requestPath.slice(1) : requestPath);
572
+ return serveCatchFallbackFrom(startDir, rootPath, req, res);
573
+ };
574
+
552
575
  const dynamicNoRescanPaths = new Set(); // paths that have exceeded max attempts
553
576
 
554
577
  // Helper function to check if a path should skip rescanning
@@ -692,6 +715,7 @@ export default async (flags, log) => {
692
715
  const result = await serveCustomRoutePath(resolvedFilePath, req, res, customRootDir);
693
716
  if(result) return;
694
717
  log(`Wildcard route path not found: ${requestPath}`, 2);
718
+ if(await serveCatchFallbackFrom(resolvedFilePath, customRootDir, req, res)) return;
695
719
  } catch(error) {
696
720
  log(`Error serving wildcard route ${requestPath}: ${error.message}`, 1);
697
721
  enhancedResponse.writeHead(500, { 'Content-Type': 'text/plain' });
@@ -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
+ };