feat(views): @Html string/file/template modes with boot validation

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
This commit is contained in:
chrnx committed 2026-07-10 14:36:40 -05:00
1 parent e1a2c3253b
commit b8ebb9d04b
3 files changed
+163 -6

No files matched your search

+57 -6
View File
@@ -11,7 +11,19 @@ import { matchWsRoute, runWsConnection, type WsRequest, type WsSocket } from '..
import { isAsyncIterable } from '../channel';
import { JsonTransformer, type ErrorRenderer } from '../transformers';
import { mountPlugin, Plugin, ScopeApi, ScopeNode } from '../plugin';
import { Ctor, getModuleMeta, getProviderMeta, getStepMeta, getRoutes, getTransformer, joinPath } from '../metadata';
import {
Ctor,
getModuleMeta,
getProviderMeta,
getStepMeta,
getRoutes,
getTransformer,
getHtmlMeta,
joinPath,
type RouteMeta,
type TransformerFn,
} from '../metadata';
import { buildHtmlTransformer, type ViewsContext } from '../views';
import { getArgs, getHandlerNeeds, resolveArgs } from '../params';
import { buildOpenApi, type OpenApiInfo } from '../openapi';
import { connectLink, type Link } from '../mesh/link';
@@ -69,6 +81,10 @@ export function createApp(opts: {
bodyDuplicates?: 'array' | 'last';
/** Render errors your own way (HTML, custom JSON, …); return a response or undefined to fall back to JSON. */
onError?: ErrorRenderer;
/** Base directory `@Html('file.html')` paths resolve against (default: `process.cwd()`). */
views?: string;
/** Bring-your-own template engine for `@Html(..., { template: true })`; defaults to the built-in `render`. */
viewEngine?: (source: string, data: unknown) => string;
/** Opt in to alpha features whose API may still change. Currently gates `mesh`. */
experimental?: boolean;
}): App {
@@ -86,7 +102,8 @@ export function createApp(opts: {
const degradedProviders: string[] = []; // optional providers that failed to boot (running degraded)
// Collect declarations from modules, then splice in plugin- and built-in-provided nodes.
const registry = collectModules(opts.modules);
const viewsCtx: ViewsContext = { views: opts.views, viewEngine: opts.viewEngine };
const registry = collectModules(opts.modules, viewsCtx);
const { providerNodes, stepNodes, runners, providerMeta, routePlans } = registry;
mountPlugins(opts.plugins, bus, registry);
provideBuiltins(registry);
@@ -278,7 +295,13 @@ function collectSteps(steps: Ctor[], origin: string, registry: Registry): void {
}
/** Registers each `@Route` handler on a module's controllers as a {@link RoutePlan}. */
function collectControllers(controllers: Ctor[], mountpoint: string, origin: string, registry: Registry): void {
function collectControllers(
controllers: Ctor[],
mountpoint: string,
origin: string,
registry: Registry,
viewsCtx: ViewsContext,
): void {
for (const ControllerClass of controllers) {
for (const route of getRoutes(ControllerClass)) {
const instance: any = new ControllerClass();
@@ -290,6 +313,8 @@ function collectControllers(controllers: Ctor[], mountpoint: string, origin: str
registry.exportedRoutes.push({ method: route.method, pattern });
}
const transformer = resolveTransformer(ControllerClass, route, pattern, viewsCtx);
registry.routePlans.push({
pattern,
method: route.method,
@@ -300,7 +325,7 @@ function collectControllers(controllers: Ctor[], mountpoint: string, origin: str
handlerName: route.handlerName,
needs: getHandlerNeeds(argSpecs),
run: async (context: any) => instance[route.handlerName](...(await resolveArgs(argSpecs, context))),
transformer: getTransformer(ControllerClass, route.handlerName) ?? JsonTransformer,
transformer,
duplicates: route.duplicates,
maxBodyBytes: route.maxBodyBytes,
maxParts: route.maxParts,
@@ -310,8 +335,34 @@ function collectControllers(controllers: Ctor[], mountpoint: string, origin: str
}
}
/**
* Resolves the response transformer for a route: `@Html` metadata builds an HTML transformer (after
* validating placement — buffered GET/POST only, and not combined with `@Transformer`); otherwise the
* user's `@Transformer` wins, falling back to {@link JsonTransformer}.
*/
function resolveTransformer(
ControllerClass: Ctor,
route: RouteMeta,
pattern: string,
viewsCtx: ViewsContext,
): TransformerFn {
const html = getHtmlMeta(ControllerClass, route.handlerName);
const userTransformer = getTransformer(ControllerClass, route.handlerName);
if (!html) return userTransformer ?? JsonTransformer;
if (route.transport !== 'buffer' || (route.method !== 'GET' && route.method !== 'POST')) {
throw new Error(
`@Html on ${route.method} ${pattern} is not allowed — @Html only supports buffered GET/POST routes (not SSE/WS/PUT/PATCH/DELETE)`,
);
}
if (userTransformer) throw new Error(`@Html and @Transformer on ${pattern} conflict — use one`);
return buildHtmlTransformer(html, viewsCtx);
}
/** Reads every module's metadata into a fresh {@link Registry} of graph nodes, runners and exports. */
function collectModules(modules: Ctor[]): Registry {
function collectModules(modules: Ctor[], viewsCtx: ViewsContext): Registry {
const registry = emptyRegistry();
for (const mod of modules) {
@@ -320,7 +371,7 @@ function collectModules(modules: Ctor[]): Registry {
const origin = `module:${mod.name}`;
collectProviders(moduleMeta.providers ?? [], origin, registry);
collectSteps(moduleMeta.steps ?? [], origin, registry);
collectControllers(moduleMeta.controllers ?? [], moduleMeta.mountpoint, origin, registry);
collectControllers(moduleMeta.controllers ?? [], moduleMeta.mountpoint, origin, registry, viewsCtx);
}
return registry;
+47
View File
@@ -1,6 +1,9 @@
// 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).
import type { TransformerFn } from './metadata';
import type { HtmlMeta } from './metadata';
/** 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;' };
@@ -44,3 +47,47 @@ const CONTENT_TYPES: Record<string, string> = {
export function contentTypeFor(ext: string): string {
return CONTENT_TYPES[ext.toLowerCase()] ?? 'application/octet-stream';
}
const HTML_HEADERS = { 'content-type': 'text/html; charset=utf-8' } as const;
/** Boot-time context for building `@Html` transformers: the views base dir and an optional BYO engine. */
export interface ViewsContext {
views?: string;
viewEngine?: (source: string, data: unknown) => string;
}
/** Reads a view file at boot (lazy fs). Relative paths resolve against `views` (default cwd); absolute as-is.
* node:fs/node:path are loaded lazily so importing the barrel stays edge/workerd-safe
* (workerd's nodejs_compat provides no filesystem). This path only runs for path/template `@Html` modes. */
function readViewFile(views: string | undefined, path: string): string {
// eslint-disable-next-line @typescript-eslint/no-require-imports
const nodePath = require('node:path') as typeof import('node:path');
// eslint-disable-next-line @typescript-eslint/no-require-imports
const fs = require('node:fs') as typeof import('node:fs');
const base = views ?? process.cwd();
const full = nodePath.isAbsolute(path) ? path : nodePath.resolve(base, path);
try {
return fs.readFileSync(full, 'utf8');
} catch (err) {
throw new Error(
`@Html('${path}') could not read '${full}' — on a runtime without a filesystem (edge), return a string from @Html instead. (${(err as Error).message})`,
);
}
}
/** Turns `@Html` metadata into a response transformer at boot. String mode is fs-free; path/template modes read+cache the file. */
export function buildHtmlTransformer(meta: HtmlMeta, ctx: ViewsContext): TransformerFn {
if (!meta.path) {
return (value) => ({ status: 200, headers: { ...HTML_HEADERS }, body: String(value) });
}
const source = readViewFile(ctx.views, meta.path);
if (meta.template) {
const engine = ctx.viewEngine ?? render;
return (value) => ({ status: 200, headers: { ...HTML_HEADERS }, body: engine(source, value) });
}
return () => ({ status: 200, headers: { ...HTML_HEADERS }, body: source });
}
+59
View File
@@ -0,0 +1,59 @@
import { describe, expect, it } from 'vitest';
import { writeFileSync, mkdirSync } from 'node:fs';
import { join } from 'node:path';
import { tmpdir } from 'node:os';
import { createApp, Route, Get, Post, Sse, Transformer, Html, Module } from '../src/index';
const dir = join(tmpdir(), 'gt-views-test');
mkdirSync(dir, { recursive: true });
writeFileSync(join(dir, 'dash.html'), '<h1>Dash</h1>');
writeFileSync(join(dir, 'user.html'), '<h1>Hi {{ name }}</h1>');
@Route('/')
class Views {
@Get('/str') @Html str() { return '<p>inline</p>'; }
@Get('/dash') @Html('dash.html') dash() {}
@Get('/user') @Html('user.html', { template: true }) user() { return { name: '<b>D</b>' }; }
}
@Module({ mountpoint: '/', controllers: [Views] })
class M {}
const app = createApp({ modules: [M], views: dir });
describe('@Html modes', () => {
it('string mode sends the handler return as text/html', async () => {
const res = await app.fetch(new Request('http://x/str'));
expect(res.headers.get('content-type')).toBe('text/html; charset=utf-8');
expect(await res.text()).toBe('<p>inline</p>');
});
it('path mode serves the file and ignores the return', async () => {
expect(await (await app.fetch(new Request('http://x/dash'))).text()).toBe('<h1>Dash</h1>');
});
it('template mode renders the file with returned data, escaping by default', async () => {
expect(await (await app.fetch(new Request('http://x/user'))).text()).toBe('<h1>Hi &lt;b&gt;D&lt;/b&gt;</h1>');
});
});
describe('@Html boot validation', () => {
it('rejects @Html on a streaming (SSE) route', () => {
@Route('/') class Bad { @Sse('/s') @Html s() { return (async function* () {})(); } }
@Module({ mountpoint: '/', controllers: [Bad] }) class BM {}
expect(() => createApp({ modules: [BM] })).toThrow(/@Html/);
});
it('rejects @Html combined with @Transformer', () => {
const t = (v: unknown) => ({ status: 200, headers: {}, body: String(v) });
@Route('/') class Bad2 { @Get('/g') @Html @Transformer(t) g() { return ''; } }
@Module({ mountpoint: '/', controllers: [Bad2] }) class BM2 {}
expect(() => createApp({ modules: [BM2] })).toThrow(/@Html and @Transformer/);
});
});
describe('viewEngine override', () => {
it('uses a bring-your-own engine for template mode', async () => {
const app2 = createApp({
modules: [M],
views: dir,
viewEngine: (source, data: any) => source.replace('{{ name }}', `RAW:${data.name}`),
});
expect(await (await app2.fetch(new Request('http://x/user'))).text()).toBe('<h1>Hi RAW:<b>D</b></h1>');
});
});