feat(views): built-in template engine + content-type map

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
This commit is contained in:
chrnx committed 2026-07-10 14:26:57 -05:00
1 parent e54de8c1db
commit da5cc936a3
3 files changed
+77

No files matched your search

+3
View File
@@ -18,6 +18,9 @@ export type { GraphView } from './graph-viz';
export { buildOpenApi } from './openapi';
export type { OpenApiDoc, OpenApiInfo, OpenApiRoute } from './openapi';
// Views
export { render } from './views';
// Routing & decorators
export { Provider, Step, Route, Get, Module, Transformer, Sse, Ws, Stream, Post, Put, Patch, Delete } from './metadata';
export type { Transport, HttpMethod } from './metadata';
+46
View File
@@ -0,0 +1,46 @@
// src/views.ts — HTML views: built-in templating, content-type map, and boot-time builders.
// fs/path are lazy-required inside functions so the barrel stays edge-loadable (workerd has no filesystem).
/** Escape the five HTML-significant characters so interpolated data can't inject markup. */
export function escapeHtml(s: string): string {
const map: Record<string, string> = { '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' };
return s.replace(/[&<>"']/g, (c) => map[c]);
}
function stringify(v: unknown): string {
return v === null || v === undefined ? '' : String(v);
}
/**
* Minimal built-in template engine: `{{ key }}` interpolates HTML-escaped, `{{{ key }}}` raw,
* `{{ a.b }}` walks nested keys, a missing key renders empty. No loops/conditionals/partials.
*/
export function render(source: string, data: unknown): string {
const lookup = (key: string): unknown =>
key.split('.').reduce<any>((obj, k) => (obj === null || obj === undefined ? undefined : obj[k]), data);
return source
.replace(/\{\{\{\s*([\w.]+)\s*\}\}\}/g, (_, key) => stringify(lookup(key)))
.replace(/\{\{\s*([\w.]+)\s*\}\}/g, (_, key) => escapeHtml(stringify(lookup(key))));
}
const CONTENT_TYPES: Record<string, string> = {
'.html': 'text/html; charset=utf-8',
'.css': 'text/css; charset=utf-8',
'.js': 'text/javascript; charset=utf-8',
'.mjs': 'text/javascript; charset=utf-8',
'.json': 'application/json; charset=utf-8',
'.svg': 'image/svg+xml',
'.png': 'image/png',
'.jpg': 'image/jpeg',
'.jpeg': 'image/jpeg',
'.gif': 'image/gif',
'.webp': 'image/webp',
'.ico': 'image/x-icon',
'.woff2': 'font/woff2',
'.txt': 'text/plain; charset=utf-8',
};
/** Content-type for a file extension (case-insensitive, leading dot); unknown → `application/octet-stream`. */
export function contentTypeFor(ext: string): string {
return CONTENT_TYPES[ext.toLowerCase()] ?? 'application/octet-stream';
}