diff --git a/CHANGELOG.md b/CHANGELOG.md index 82e9b68..70114e6 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,6 +8,10 @@ green-tea uses calendar versioning: `YY.MM.PATCH`. ## [Unreleased] ### Added +- **HTML / views:** `@Html` decorator (string, file, and template modes), a zero-dep built-in + template engine (`{{ }}` escaped / `{{{ }}}` raw, exported as `render`) with a `viewEngine` + bring-your-own hook, and zero-config `static` directory serving (`createApp({ static: true })`). + File and static serving require a filesystem (Node/Deno/Bun); string-mode `@Html` runs everywhere. - **`app.fetch(request): Promise`** — a Web-Standards handler so the same app runs HTTP and SSE on Deno/Bun/edge runtimes via the Fetch API (WebSocket and mesh remain Node-only). diff --git a/src/app/index.ts b/src/app/index.ts index 4a00cc0..18ce2a1 100644 --- a/src/app/index.ts +++ b/src/app/index.ts @@ -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, buildStaticResolver, 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,12 @@ 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; + /** Serve a static directory as a GET/HEAD fallback (after declared routes, before 404). `true` → `./public`. */ + static?: boolean | string; /** Opt in to alpha features whose API may still change. Currently gates `mesh`. */ experimental?: boolean; }): App { @@ -86,7 +104,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); @@ -141,6 +160,8 @@ export function createApp(opts: { degradedProviders, ); + const staticResolver = opts.static ? buildStaticResolver(opts.static) : undefined; + const fetchOpts: HttpOptions = { limits: opts.limits, tls: opts.tls, @@ -149,6 +170,7 @@ export function createApp(opts: { cors: opts.cors, bodyDuplicates: opts.bodyDuplicates, onError: opts.onError, + static: staticResolver, }; const fetchFn = buildAppFetch( () => booted, @@ -201,6 +223,7 @@ export function createApp(opts: { cors: opts.cors, bodyDuplicates: opts.bodyDuplicates, onError: opts.onError, + static: staticResolver, }); server.on('close', () => closeLinks(meshLinks)); await new Promise((resolve) => server!.listen(port, resolve)); @@ -278,7 +301,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 +319,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 +331,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 +341,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 +377,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; diff --git a/src/http/core.ts b/src/http/core.ts index a6771bb..0a4c4fe 100644 --- a/src/http/core.ts +++ b/src/http/core.ts @@ -69,6 +69,18 @@ export async function handle( const matched = matchRoute(routes, req.method, path); if (!matched) { + if ((req.method === 'GET' || req.method === 'HEAD') && opts?.static) { + const hit = await opts.static(path); + + if (hit) { + const body = req.method === 'HEAD' ? '' : hit.body; + return { + injected, + outcome: { kind: 'buffered', status: 200, headers: { 'content-type': hit.contentType }, body }, + }; + } + } + // Path matches a route under a different method → 405 with Allow; otherwise 404. const allow = allowedMethods(routes, path); const err = allow.length ? new HttpError(405, 'Method Not Allowed') : new NotFound('Not Found'); diff --git a/src/http/types.ts b/src/http/types.ts index a12c1e4..5e5f444 100644 --- a/src/http/types.ts +++ b/src/http/types.ts @@ -4,6 +4,7 @@ import type { PipelineResult } from '../pipeline'; import type { ErrorRenderer } from '../transformers'; import type { TlsOptions, SecurityOptions, CorsOptions } from '../security'; import type { WsRequest } from './ws-core'; +import type { StaticResolver } from '../views'; /** Per-request size and timeout ceilings applied by the server. */ export interface RequestLimits { @@ -24,6 +25,7 @@ export interface HttpOptions { cors?: CorsOptions; bodyDuplicates?: 'array' | 'last'; onError?: ErrorRenderer; + static?: StaticResolver; } /** Handler for a matched HTTP route; receives a normalized request and resolves to a pipeline result. */ diff --git a/src/index.ts b/src/index.ts index eb4c42a..de7e9c9 100644 --- a/src/index.ts +++ b/src/index.ts @@ -18,8 +18,26 @@ 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 { + Provider, + Step, + Route, + Get, + Module, + Transformer, + Sse, + Ws, + Stream, + Post, + Put, + Patch, + Delete, + Html, +} from './metadata'; export type { Transport, HttpMethod } from './metadata'; export type { Plugin } from './plugin'; diff --git a/src/metadata.ts b/src/metadata.ts index 2bcab34..530dcff 100644 --- a/src/metadata.ts +++ b/src/metadata.ts @@ -5,6 +5,11 @@ export type Ctor = new (...args: any[]) => any; /** Serializes a handler's return value into an HTTP response envelope. */ export type TransformerFn = (value: unknown) => { status?: number; headers?: Record; body: string }; +/** Metadata attached by `@Html`: optional file path and whether it is a template. */ +export interface HtmlMeta { + path?: string; + template?: boolean; +} /** Metadata attached by `@Provider`: what it provides, what it needs, and its visibility. */ export interface ProviderMeta { provides: string; @@ -49,6 +54,7 @@ const K = { routes: Symbol('gt:routes'), module: Symbol('gt:module'), transformer: Symbol('gt:transformer'), + html: Symbol('gt:html'), }; /** Marks a class as a provider: a lazily-built dependency addressable by its `provides` key. */ @@ -147,6 +153,35 @@ export function Module(opts: ModuleOptions): ClassDecorator { }; } +/** + * Marks a buffered GET/POST handler as serving HTML. Bare `@Html` sends the handler's string return as + * `text/html`. `@Html('file.html')` serves that file (return ignored). `@Html('file.html', { template: true })` + * renders the file with the handler's returned data. Placement is validated at boot (buffered GET/POST only). + */ +export function Html(path: string, opts?: { template?: boolean }): MethodDecorator; +export function Html(target: object, propertyKey: string | symbol): void; + +export function Html(a: unknown, b?: unknown): MethodDecorator | void { + if (typeof a !== 'string') { + // Bare usage: TS calls (prototype, propertyKey, descriptor?). + Reflect.defineMetadata(K.html, {}, (a as { constructor: Ctor }).constructor, String(b)); + return; + } + + const path = a; + const opts = b as { template?: boolean } | undefined; + + return (target, propertyKey) => { + const meta: HtmlMeta = { path, template: opts?.template }; + Reflect.defineMetadata(K.html, meta, (target as { constructor: Ctor }).constructor, String(propertyKey)); + }; +} + +/** Reads the `@Html` metadata registered for a handler method, if any. */ +export function getHtmlMeta(cls: Ctor, methodName: string): HtmlMeta | undefined { + return Reflect.getMetadata(K.html, cls, methodName); +} + /** Reads the `@Provider` metadata off a class, if any. */ export function getProviderMeta(cls: Ctor): ProviderMeta | undefined { return Reflect.getMetadata(K.provider, cls); diff --git a/src/views.ts b/src/views.ts new file mode 100644 index 0000000..210ab9c --- /dev/null +++ b/src/views.ts @@ -0,0 +1,147 @@ +// 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 = { '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }; + 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((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 = { + '.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'; +} + +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})`, + ); + } +} + +/** A static-file hit: the raw bytes and the content-type to send. */ +export interface StaticHit { + body: Buffer; + contentType: string; +} + +/** Resolves a URL path to a static file under a fixed root, or `undefined` for a miss. */ +export type StaticResolver = (urlPath: string) => Promise; + +/** + * Builds a static-file resolver rooted at `root` (`true` → `./public`). Requires a filesystem: throws at + * boot on a runtime without one (edge). Path-traversal-safe — a resolved path outside the root is a miss. + */ +export function buildStaticResolver(root: string | true): StaticResolver { + let fs: typeof import('node:fs'); + let nodePath: typeof import('node:path'); + + try { + // eslint-disable-next-line @typescript-eslint/no-require-imports + fs = require('node:fs'); + // eslint-disable-next-line @typescript-eslint/no-require-imports + nodePath = require('node:path'); + } catch { + throw new Error( + '`static` needs a filesystem and is unavailable on this runtime (edge). Remove it or serve assets from a CDN.', + ); + } + + const abs = nodePath.resolve(process.cwd(), root === true ? 'public' : root); + + return async (urlPath) => { + let rel: string; + + try { + rel = decodeURIComponent(urlPath.split('?')[0]); + } catch { + return undefined; + } + + if (rel === '' || rel.endsWith('/')) rel += 'index.html'; + const full = nodePath.resolve(abs, '.' + (rel.startsWith('/') ? rel : '/' + rel)); + if (full !== abs && !full.startsWith(abs + nodePath.sep)) return undefined; // traversal guard + + try { + const stat = await fs.promises.stat(full); + const target = stat.isDirectory() ? nodePath.join(full, 'index.html') : full; + const body = await fs.promises.readFile(target); + return { body, contentType: contentTypeFor(nodePath.extname(target)) }; + } catch { + return undefined; + } + }; +} + +/** 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 }); +} diff --git a/test/metadata.test.ts b/test/metadata.test.ts index 300d811..857d40f 100644 --- a/test/metadata.test.ts +++ b/test/metadata.test.ts @@ -74,3 +74,24 @@ describe('mesh export flags', () => { expect(byName.priv.export).toBe(false); }); }); + +import { Html, getHtmlMeta } from '../src/metadata'; + +describe('@Html', () => { + it('records empty meta for bare @Html', () => { + class A { @Html m() { return ''; } } + expect(getHtmlMeta(A, 'm')).toEqual({}); + }); + it('records path and template for called @Html', () => { + class B { + @Html('views/x.html') a() {} + @Html('views/y.html', { template: true }) c() { return {}; } + } + expect(getHtmlMeta(B, 'a')).toEqual({ path: 'views/x.html', template: undefined }); + expect(getHtmlMeta(B, 'c')).toEqual({ path: 'views/y.html', template: true }); + }); + it('returns undefined when @Html is absent', () => { + class C { m() {} } + expect(getHtmlMeta(C, 'm')).toBeUndefined(); + }); +}); diff --git a/test/views-html.test.ts b/test/views-html.test.ts new file mode 100644 index 0000000..7eafeb1 --- /dev/null +++ b/test/views-html.test.ts @@ -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, Sse, Transformer, Html, Module } from '../src/index'; + +const dir = join(tmpdir(), 'gt-views-test'); +mkdirSync(dir, { recursive: true }); +writeFileSync(join(dir, 'dash.html'), '

Dash

'); +writeFileSync(join(dir, 'user.html'), '

Hi {{ name }}

'); + +@Route('/') +class Views { + @Get('/str') @Html str() { return '

inline

'; } + @Get('/dash') @Html('dash.html') dash() {} + @Get('/user') @Html('user.html', { template: true }) user() { return { name: 'D' }; } +} +@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('

inline

'); + }); + it('path mode serves the file and ignores the return', async () => { + expect(await (await app.fetch(new Request('http://x/dash'))).text()).toBe('

Dash

'); + }); + 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('

Hi <b>D</b>

'); + }); +}); + +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('

Hi RAW:D

'); + }); +}); diff --git a/test/views-static.test.ts b/test/views-static.test.ts new file mode 100644 index 0000000..80be5ba --- /dev/null +++ b/test/views-static.test.ts @@ -0,0 +1,55 @@ +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, Module } from '../src/index'; +import { buildStaticResolver } from '../src/views'; + +const root = join(tmpdir(), 'gt-static-test'); +mkdirSync(root, { recursive: true }); +writeFileSync(join(root, 'index.html'), '

Home

'); +writeFileSync(join(root, 'app.css'), 'body{}'); +writeFileSync(join(tmpdir(), 'gt-secret.txt'), 'TOP SECRET'); + +@Route('/api') +class Api { + @Get('/ping') + ping() { + return { ok: true }; + } +} +@Module({ mountpoint: '/', controllers: [Api] }) +class M {} +const app = createApp({ modules: [M], static: root }); + +describe('static serving', () => { + it('serves a file by path with its content-type', async () => { + const res = await app.fetch(new Request('http://x/app.css')); + expect(res.status).toBe(200); + expect(res.headers.get('content-type')).toBe('text/css; charset=utf-8'); + expect(await res.text()).toBe('body{}'); + }); + it('serves index.html for /', async () => { + expect(await (await app.fetch(new Request('http://x/'))).text()).toBe('

Home

'); + }); + it('declared routes win over static', async () => { + expect(await (await app.fetch(new Request('http://x/api/ping'))).json()).toEqual({ ok: true }); + }); + it('returns 404 for a missing file', async () => { + expect((await app.fetch(new Request('http://x/nope.html'))).status).toBe(404); + }); + it('rejects path traversal', async () => { + const res = await app.fetch(new Request('http://x/../gt-secret.txt')); + expect(res.status).toBe(404); + }); + it('answers HEAD with headers and no body', async () => { + const res = await app.fetch(new Request('http://x/app.css', { method: 'HEAD' })); + expect(res.status).toBe(200); + expect(await res.text()).toBe(''); + }); + it('resolver refuses to escape its root', async () => { + const resolve = buildStaticResolver(root); + expect(await resolve('/../gt-secret.txt')).toBeUndefined(); + expect(await resolve('/%2e%2e/gt-secret.txt')).toBeUndefined(); + }); +}); diff --git a/test/views.test.ts b/test/views.test.ts new file mode 100644 index 0000000..2523385 --- /dev/null +++ b/test/views.test.ts @@ -0,0 +1,28 @@ +import { describe, expect, it } from 'vitest'; +import { render, escapeHtml, contentTypeFor } from '../src/views'; + +describe('escapeHtml', () => { + it('escapes the five HTML-significant characters', () => { + expect(escapeHtml(`&'`)).toBe('<a href="x">&''); + }); +}); + +describe('render', () => { + it('interpolates and HTML-escapes {{ x }} by default', () => { + expect(render('

{{ name }}

', { name: 'hi' })).toBe('

<b>hi</b>

'); + }); + it('leaves {{{ x }}} raw (unescaped)', () => { + expect(render('{{{ html }}}', { html: 'hi' })).toBe('hi'); + }); + it('resolves nested keys and renders missing keys as empty', () => { + expect(render('{{ user.name }}|{{ nope }}', { user: { name: 'Diego' } })).toBe('Diego|'); + }); +}); + +describe('contentTypeFor', () => { + it('maps known extensions and defaults unknown to octet-stream', () => { + expect(contentTypeFor('.css')).toBe('text/css; charset=utf-8'); + expect(contentTypeFor('.PNG')).toBe('image/png'); + expect(contentTypeFor('.xyz')).toBe('application/octet-stream'); + }); +}); diff --git a/website/astro.config.mjs b/website/astro.config.mjs index db488a6..31175f9 100644 --- a/website/astro.config.mjs +++ b/website/astro.config.mjs @@ -37,6 +37,7 @@ export default defineConfig({ { label: 'Error handling', slug: 'guides/errors' }, { label: 'Streaming & real-time', slug: 'guides/streaming' }, { label: 'File uploads', slug: 'guides/uploads' }, + { label: 'HTML & views', slug: 'guides/html' }, { label: 'Transport security', slug: 'guides/security' }, { label: 'Plugins & observability', slug: 'guides/plugins' }, { label: 'Graph introspection', slug: 'guides/introspection' }, diff --git a/website/src/content/docs/guides/html.md b/website/src/content/docs/guides/html.md new file mode 100644 index 0000000..2914c37 --- /dev/null +++ b/website/src/content/docs/guides/html.md @@ -0,0 +1,158 @@ +--- +title: HTML & views +description: "The @Html decorator, the built-in template engine, and zero-config static file serving." +--- + +Most of green-tea assumes JSON, but not every route is an API endpoint. `@Html` marks a handler as serving HTML instead of going through the JSON transformer — a string, a file, or a file rendered with data. Add a static directory on top and you've got a small server-rendered site without reaching for a template framework. + +## `@Html` — three modes + +### 1. Return a string — every runtime + +Bare `@Html` sends the handler's return value as `text/html; charset=utf-8`. No filesystem involved, so this mode runs on Node, Deno, Bun, and the edge. + +```typescript +import { Route, Get, Html } from '@green-tea/core'; + +@Route('/') +class PageController { + @Get('/') + @Html + home() { + return '

Hello from green-tea

'; + } +} +``` + +### 2. Serve a file — Node/Deno/Bun + +`@Html('file.html')` reads the file at boot, caches it, and serves it verbatim — the handler still runs (for side effects, guards, etc.) but its return value is ignored. + +```typescript +@Route('/about') +class AboutController { + @Get('/') + @Html('about.html') + about() {} +} +``` + +Reading a file needs a filesystem, so this mode is Node/Deno/Bun only — see [Runtimes](/guides/runtimes/) for the edge alternative. + +### 3. Render a template — Node/Deno/Bun + +`@Html('file.html', { template: true })` reads the file at boot and renders it with whatever object the handler returns, on every request. + +```typescript +@Route('/user') +class UserController { + @Get('/:id') + @Html('user.html', { template: true }) + show(@param('id') id: string) { + return { name: lookupName(id) }; + } +} +``` + +`user.html`: + +```html +

Hi {{ name }}

+``` + +Same filesystem requirement as file mode: Node/Deno/Bun only. + +:::caution[Return a string or data, never an `AsyncIterable`] +An `@Html` handler must return a string (bare mode) or a data object (template mode). Don't +return an `AsyncIterable` — the pipeline detects async-iterable returns and streams them raw, +bypassing the HTML transformer entirely, so your markup never gets wrapped or rendered. +::: + +## The `views` base directory + +`@Html('file.html')` paths resolve against `createApp({ views })` — a relative path joins `views`, an absolute path is used as-is (handy for a template stored outside the project, e.g. on an NFS mount). `views` defaults to `process.cwd()` when unset. + +```typescript +const app = createApp({ modules: [ApiModule], views: 'templates' }); +// @Html('about.html') -> /templates/about.html +// @Html('/srv/shared/about.html') -> /srv/shared/about.html (absolute, used as-is) +``` + +Files are read once, at boot — not on every request. + +## The built-in template engine + +Template mode renders with a small, dependency-free engine, also exported as `render` if you want to call it directly: + +```typescript +import { render } from '@green-tea/core'; + +render('

{{ name }}

', { name: 'hi' }); +// '

<b>hi</b>

' — {{ x }} HTML-escapes + +render('{{{ html }}}', { html: 'hi' }); +// 'hi' — {{{ x }}} is raw, unescaped + +render('{{ user.name }} / {{ nope }}', { user: { name: 'Diego' } }); +// 'Diego / ' — {{ a.b }} walks nested keys; a missing key renders empty +``` + +That's the whole engine: interpolation, escaped or raw, with dotted-key lookup. No loops, conditionals, or partials — reach for `viewEngine` below if you need those. + +## Bring your own engine — `viewEngine` + +`createApp({ viewEngine })` swaps in any `(source, data) => string` function for template mode — EJS, Handlebars, or your own: + +```typescript +import ejs from 'ejs'; + +const app = createApp({ + modules: [ApiModule], + views: 'templates', + viewEngine: (source, data) => ejs.render(source, data as object), +}); +``` + +`viewEngine` only affects `@Html(..., { template: true })`; string and plain file modes are unaffected. + +## Static files — `createApp({ static })` + +`static` serves a directory as a GET/HEAD fallback, tried after your declared routes and before a `404`: + +```typescript +const app = createApp({ modules: [ApiModule], static: true }); // ./public, relative to cwd +const app2 = createApp({ modules: [ApiModule], static: 'assets' }); // ./assets, relative to cwd +const app3 = createApp({ modules: [ApiModule], static: '/srv/site' }); // absolute, used as-is +``` + +- Files are served at their URL path; content-type is inferred from the extension. +- `/` (and any directory-shaped path) resolves to `index.html`. +- Only `GET` and `HEAD` are handled — other methods fall through. +- **Declared routes always win.** Static is only consulted when nothing matched, so `@Get('/api/ping')` is never shadowed by a file at `public/api/ping`. +- Path traversal (`../`, encoded or not) is rejected — a request can't escape the static root. + +Like the file/template modes of `@Html`, `static` needs a filesystem: it's Node/Deno/Bun only. Configuring it on an edge runtime throws at `createApp()` time — see [Runtimes](/guides/runtimes/). + +## The boot rule + +`@Html` only supports **buffered `GET`/`POST`** routes. Boot fails fast rather than misbehaving at request time: + +```typescript +@Sse('/ticks') +@Html +ticks() { /* ... */ } +// throws at createApp(): "@Html on GET /ticks is not allowed — +// @Html only supports buffered GET/POST routes (not SSE/WS/PUT/PATCH/DELETE)" +``` + +`@Html` and `@Transformer` also can't be combined on the same handler — pick one: + +```typescript +@Get('/g') +@Html +@Transformer(myTransformer) +g() { /* ... */ } +// throws at createApp(): "@Html and @Transformer on /g conflict — use one" +``` + +Both checks run once, at boot, alongside the rest of the route validation — never per-request. diff --git a/website/src/content/docs/guides/runtimes.md b/website/src/content/docs/guides/runtimes.md index c1bb622..e2f8c73 100644 --- a/website/src/content/docs/guides/runtimes.md +++ b/website/src/content/docs/guides/runtimes.md @@ -117,3 +117,18 @@ this flag; without it, the Worker fails to load. Durable Objects and WebSocket Hibernation are **not** used — `edgeHandler` accepts WebSockets with the standard `WebSocketPair` model, so a Worker holds the connection open for its lifetime rather than hibernating between messages. + +## Filesystem features — Node/Deno/Bun only + +A few [HTML & views](/guides/html/) features read from disk, so they need a runtime with +a filesystem: + +- `@Html('file.html')` — reads and caches the file at boot. +- `@Html('file.html', { template: true })` — same, then renders it per request. +- `createApp({ static })` — serves a directory of files. + +All three throw at boot (`createApp()`/route-build time) on a runtime without a +filesystem, rather than failing per-request. On the edge, use bare `@Html` returning a +string instead — pair it with the exported `render` over a template string you `import` +as a module (so it ships in the bundle, no disk read), and serve other assets (images, +CSS, JS) from a CDN in front of the Worker. diff --git a/website/src/content/docs/reference/createapp.md b/website/src/content/docs/reference/createapp.md index 2bb4e26..9a78f67 100644 --- a/website/src/content/docs/reference/createapp.md +++ b/website/src/content/docs/reference/createapp.md @@ -23,6 +23,9 @@ const app = createApp(options); | `cors` | `CorsOptions` | — | CORS handling | | `bodyDuplicates` | `'array' \| 'last'` | `'last'` | policy for repeated form fields | | `onError` | `ErrorRenderer` | — | render errors your way ([error handling](/guides/errors/)); returns a response or `undefined` to fall back to JSON | +| `views` | `string` | `process.cwd()` | base dir `@Html('file.html')` paths resolve against — relative paths join it, absolute paths are used as-is ([HTML & views](/guides/html/)) | +| `viewEngine` | `(source: string, data: unknown) => string` | built-in `render` | swap in your own template engine for `@Html(..., { template: true })`; template mode only ([HTML & views](/guides/html/)) | +| `static` | `boolean \| string` | — | serve a directory as a `GET`/`HEAD` fallback (after declared routes, before `404`); `true` → `./public`, a string → that dir; path-traversal-safe; needs a filesystem — Node/Deno/Bun only ([HTML & views](/guides/html/)) | | `mesh` | `MeshConfig` | — | distributed DI — **requires `experimental: true`** ([mesh](/guides/mesh/)) | | `experimental` | `boolean` | `false` | opt in to alpha features (currently gates `mesh`) | diff --git a/website/src/content/docs/reference/decorators.md b/website/src/content/docs/reference/decorators.md index d0d60f4..c3233a5 100644 --- a/website/src/content/docs/reference/decorators.md +++ b/website/src/content/docs/reference/decorators.md @@ -46,6 +46,18 @@ A request-scope transform that merges keys into the context. Same options as `@P Method decorator. Turns a handler's return value into `{ status?, headers?, body }`. `JsonTransformer` is the default. +### `@Html` / `@Html(path, opts?)` + +Method decorator. Marks a buffered `GET`/`POST` handler as serving HTML instead of going through the JSON transformer. Three modes ([details](/guides/html/)): + +| Form | Behavior | +|---|---| +| `@Html` (bare) | sends the handler's returned string as `text/html` | +| `@Html('file.html')` | serves that file verbatim; the handler's return value is ignored | +| `@Html('file.html', { template: true })` | renders the file with the handler's returned data, via the built-in `render` engine or `viewEngine` ([createApp](/reference/createapp/)) | + +Only buffered `GET`/`POST` routes are supported, and `@Html` can't be combined with `@Transformer` on the same handler — both are validated at boot, not per-request. + ## Routes Method decorators on a controller. All accept `(path, opts?)` where `opts = { export?: boolean, duplicates?: 'array' | 'last', maxBodyBytes?: number, maxParts?: number }`. `maxBodyBytes` / `maxParts` override the server-wide [`limits`](/reference/createapp/) for this route only.