From 5fd0a642667a7f3aaf3c09bd031fe97bebe4e990 Mon Sep 17 00:00:00 2001 From: Harsh Bhanushali Date: Sat, 28 Nov 2026 20:42:07 +0000 Subject: [PATCH 1/4] feat(pages): let _not-found and _error declare their title (#825) A boundary component can export head = { title } as an object literal. Void reads it from the source and uses it as the page title, so titleTemplate applies to it like any other page. --- docs/guide/pages-routing/errors.md | 34 ++++ packages/void/src/pages/boundary-plans.ts | 24 ++- packages/void/src/pages/protocol.ts | 30 ++-- packages/void/src/pages/scan.ts | 55 +++++++ packages/void/src/pages/types.ts | 2 + packages/void/src/router/compile.ts | 9 +- .../void/test/unit/page-boundaries.test.ts | 152 ++++++++++++++++++ 7 files changed, 291 insertions(+), 15 deletions(-) diff --git a/docs/guide/pages-routing/errors.md b/docs/guide/pages-routing/errors.md index dbb0f253c3..7abb3f404c 100644 --- a/docs/guide/pages-routing/errors.md +++ b/docs/guide/pages-routing/errors.md @@ -114,6 +114,40 @@ Error components handle these exceptions on page GET and HEAD requests. API rout Use [`c.status()`](./loaders.md#response-status) instead when you want an error status while rendering the requested page with its normal props. +## Page titles + +Error pages use the default titles `Not Found` and `Internal Server Error`, with your [`titleTemplate`](./head.md#page-title-templates) applied. To set your own, export a `head` with a string `title` from `_not-found` or `_error`: + +::: code-group + +```tsx [React] +// pages/_not-found.tsx +export const head = { title: 'Page not found' }; +``` + +```vue [Vue] + + +``` + +```svelte [Svelte] + + +``` + +```tsx [Solid] +// pages/_not-found.tsx +export const head = { title: 'Page not found' }; +``` + +::: + +Declare it as an object literal with `title` as its only field; Void reads it from the source, so other forms are ignored with a warning. An `_error` title applies to every status that component renders. + ## Nested errors Put an error component in a subdirectory to customize that section. Void uses the closest one and keeps its surrounding layouts. If a layout fails, an error component outside that layout handles it. If an error component fails, Void tries an outer one, then its built-in error page. diff --git a/packages/void/src/pages/boundary-plans.ts b/packages/void/src/pages/boundary-plans.ts index d9de7e6fa9..02f0cf2630 100644 --- a/packages/void/src/pages/boundary-plans.ts +++ b/packages/void/src/pages/boundary-plans.ts @@ -9,11 +9,14 @@ export type BoundaryPlan = { kind: 'error' | 'not-found'; source: string; layouts: Array; + head?: { title: string }; }; export type PageBoundaryPlans = { notFound?: string; notFoundErrors?: Array; errors: Array; + /** Titles a boundary component declares, by plan id. */ + heads?: Record; catches: Array<{ depth: number; plan: string }>; }; export type BoundaryManifest = { @@ -22,6 +25,20 @@ export type BoundaryManifest = { root?: string; rootErrors?: Array; }; +/** The declared heads of the plans a request may render, keyed by plan id. */ +export function boundaryHeads( + plans: BoundaryManifest['plans'], + ids: ReadonlyArray, +): Pick { + const heads: Record = {}; + for (const id of ids) { + const head = id ? plans[id]?.head : undefined; + if (id && head) { + heads[id] = head; + } + } + return Object.keys(heads).length > 0 ? { heads } : {}; +} const encloses = (outer: string, inner: string) => !outer || outer === inner || inner.startsWith(outer + '/'); @@ -50,7 +67,7 @@ export function createBoundaryManifest(scan: PageScanResult): BoundaryManifest { }; const errors = candidates.filter((b) => b.kind === 'error'); const notFound = candidates.find((b) => b.kind === 'not-found'); - pages[page.componentId] = { + const entry: PageBoundaryPlans = { ...(notFound ? { notFound: add(notFound), @@ -65,6 +82,10 @@ export function createBoundaryManifest(scan: PageScanResult): BoundaryManifest { plan: add(b), })), }; + pages[page.componentId] = { + ...entry, + ...boundaryHeads(plans, [entry.notFound, ...(entry.notFoundErrors ?? []), ...entry.errors]), + }; } const root = scan.boundaries?.find((b) => b.kind === 'not-found' && !b.directory); if (root) { @@ -86,6 +107,7 @@ export function createBoundaryManifest(scan: PageScanResult): BoundaryManifest { } pages[id] = { errors: rootErrors, + ...boundaryHeads(plans, [id, ...rootErrors]), catches: rootErrors.map((plan) => ({ depth: plans[id].layouts.length, plan })), }; return { plans, pages, root: id, rootErrors }; diff --git a/packages/void/src/pages/protocol.ts b/packages/void/src/pages/protocol.ts index 10288cdeec..d2010fee0b 100644 --- a/packages/void/src/pages/protocol.ts +++ b/packages/void/src/pages/protocol.ts @@ -74,7 +74,13 @@ type PageRenderOptions = { renderMode?: PageRenderMode; /** Dev server build: rejected deferred props keep their raw error message. */ dev?: boolean; - boundaries?: { notFound?: string; notFoundErrors?: Array; errors: Array }; + boundaries?: { + notFound?: string; + notFoundErrors?: Array; + errors: Array; + /** Titles the boundary components declare, by plan id. */ + heads?: Record; + }; }; type AssetTags = { css: string; @@ -529,6 +535,7 @@ async function renderPageFailure( continue; } attempted.add(component); + const declaredTitle = options?.boundaries?.heads?.[component]; const page: PageObject = { component, props: { error: { status, message } }, @@ -538,16 +545,17 @@ async function renderPageFailure( errors: null, head: { ...head, - title: - head?.title ?? - resolveHead(configHead, middlewareHead, { - title: - status === 404 - ? 'Not Found' - : recoverHttpError && status !== 500 - ? message - : 'Internal Server Error', - })?.title, + title: declaredTitle + ? resolveHead(configHead, middlewareHead, declaredTitle)?.title + : (head?.title ?? + resolveHead(configHead, middlewareHead, { + title: + status === 404 + ? 'Not Found' + : recoverHttpError && status !== 500 + ? message + : 'Internal Server Error', + })?.title), }, }; try { diff --git a/packages/void/src/pages/scan.ts b/packages/void/src/pages/scan.ts index d98fecd255..ba196e34d1 100644 --- a/packages/void/src/pages/scan.ts +++ b/packages/void/src/pages/scan.ts @@ -26,6 +26,7 @@ import { readStaticExports, staticExports, staticLiteral, + unwrapStaticExpression, } from '../shared/static-exports.ts'; import { MARKDOWN_SCRIPT_RE, scriptBlocks } from './island-imports.ts'; import { resolveNamedLayout } from './layout-resolution.ts'; @@ -161,6 +162,53 @@ function componentLayout(source: string, filename: string): ComponentLayout { return { layout: undefined, warnings: [] }; } +type BoundaryHead = { + head: { title: string } | undefined; + /** Head exports the scan ignores, reported once by scanPages. */ + warnings: Array; +}; + +const HEAD_EXPORT: ReadonlySet = new Set(['head']); + +/** The `title` of an `export const head = { title: '...' }` in a boundary component. */ +function boundaryHead(source: string, filename: string): BoundaryHead { + const ignored = (reason: string) => + `pages: head in '${filename}' is ignored. ${reason} Declare it as \`export const head = { title: 'Page not found' }\`.`; + for (const script of scriptBlocks(source, filename)) { + // `export let head` in a Svelte instance script declares a prop of that name. + if (script.instance || !script.source.includes('head')) { + continue; + } + const exports = readStaticExports(script.filename, script.source, HEAD_EXPORT); + if (exports.unreadable.has('head')) { + return { + head: undefined, + warnings: [ignored('Re-exported heads and other export forms are not read.')], + }; + } + const initializer = unwrapStaticExpression(exports.initializers.get('head')); + if (!initializer) { + continue; + } + const properties = ( + initializer.type === 'ObjectExpression' ? initializer.properties : [] + ) as Array; + const only = properties.length === 1 ? properties[0] : undefined; + const key = only?.type === 'Property' && !only.computed ? (only.key as AstNode) : undefined; + const title = + (isIdentifier(key) ? key.name : staticLiteral(key)) === 'title' + ? staticLiteral(only?.value as AstNode | undefined) + : undefined; + return typeof title === 'string' + ? { head: { title }, warnings: [] } + : { + head: undefined, + warnings: [ignored('It must be an object literal whose only field is a string `title`.')], + }; + } + return { head: undefined, warnings: [] }; +} + const TRANSPARENT_EXPRESSION_TYPES = new Set([ 'ParenthesizedExpression', 'TSAsExpression', @@ -389,11 +437,18 @@ export async function scanPages(root: string, options?: PageScanOptions): Promis throw new Error(`pages: Ambiguous boundary files '${prior.filePath}' and '${file}'.`); } } + const { head, warnings } = deriveFromSource( + join(pagesDir, file), + 'page-boundary-head', + (source) => boundaryHead(source, file), + ); + warnPageSettings(pagesDir, warnings); boundaries.push({ kind: boundary[1] as PageBoundaryDefinition['kind'], directory, componentId: base, filePath: file, + ...(head && { head }), }); continue; } diff --git a/packages/void/src/pages/types.ts b/packages/void/src/pages/types.ts index ce3cbdabaa..503e4a935d 100644 --- a/packages/void/src/pages/types.ts +++ b/packages/void/src/pages/types.ts @@ -76,6 +76,8 @@ export type PageBoundaryDefinition = { directory: string; componentId: string; filePath: string; + /** From `export const head = { title }` in the boundary component. */ + head?: { title: string }; }; export type PageError = Readonly<{ status: number; message: string }>; diff --git a/packages/void/src/router/compile.ts b/packages/void/src/router/compile.ts index 9683661503..0b35d118b5 100644 --- a/packages/void/src/router/compile.ts +++ b/packages/void/src/router/compile.ts @@ -4,7 +4,7 @@ import type { VoidAuthProvider } from '../auth/providers.ts'; import type { DevRedirectRule, HeaderRule } from '../cli/types.ts'; import type { NotFoundHandling } from '../config.ts'; import type { MigrationPlanBundle } from '../migrations/plan.ts'; -import { createBoundaryManifest } from '../pages/boundary-plans.ts'; +import { boundaryHeads, createBoundaryManifest } from '../pages/boundary-plans.ts'; import { resolveLayoutIds } from '../pages/layout-resolution.ts'; import { patternToRegex } from '../pages/manifest.ts'; import { cloudflareQueueName } from '../queues/cloudflare-names.ts'; @@ -1074,7 +1074,7 @@ function compilePageRoutes( if (boundaryManifest.root) { const island = scan.pages.pages.length > 0 && scan.pages.pages.every((page) => page.island); lines.push( - `const __voidRootNotFoundOptions = { componentId: ${JSON.stringify(boundaryManifest.root)}, load: async () => ({ loader: () => new Response(null, { status: 404 }) }), render: ${island ? 'renderIslandPage' : 'renderPage'}, assets: ${island && pages.islandClientEntryId ? 'getIslandsAssetTags' : 'getPagesAssetTags'}, headConfig: __voidHeadConfig, renderOptions: ${JSON.stringify({ renderMode: island ? 'island' : 'server', dev: options.dev === true, boundaries: { notFound: boundaryManifest.root, errors: boundaryManifest.rootErrors ?? [] } })} }; const __voidRootNotFound = __createPageGetHandler(__voidRootNotFoundOptions); export const __voidRenderStaticNotFound = __createStaticNotFound({ ...__voidRootNotFoundOptions, render: renderPage, assets: getPagesAssetTags });`, + `const __voidRootNotFoundOptions = { componentId: ${JSON.stringify(boundaryManifest.root)}, load: async () => ({ loader: () => new Response(null, { status: 404 }) }), render: ${island ? 'renderIslandPage' : 'renderPage'}, assets: ${island && pages.islandClientEntryId ? 'getIslandsAssetTags' : 'getPagesAssetTags'}, headConfig: __voidHeadConfig, renderOptions: ${JSON.stringify({ renderMode: island ? 'island' : 'server', dev: options.dev === true, boundaries: { notFound: boundaryManifest.root, errors: boundaryManifest.rootErrors ?? [], ...boundaryHeads(boundaryManifest.plans, [boundaryManifest.root, ...(boundaryManifest.rootErrors ?? [])]) } })} }; const __voidRootNotFound = __createPageGetHandler(__voidRootNotFoundOptions); export const __voidRenderStaticNotFound = __createStaticNotFound({ ...__voidRootNotFoundOptions, render: renderPage, assets: getPagesAssetTags });`, ); } @@ -1119,7 +1119,10 @@ function compilePageRoutes( const trailingCatchAll = options.trailingSlash && page.catchAll; const pattern = trailingCatchAll ? page.pattern.slice(0, -1) : page.pattern; const catchAllParam = page.pattern.match(/:([^/{}]+)\{\.\+\}\/$/)?.[1]; - const middlewareBoundaries = `middlewareBoundaries: ${JSON.stringify({ notFound: boundaryManifest.root, errors: (boundaryManifest.pages[page.componentId]?.errors ?? []).filter((id) => !boundaryManifest.plans[id].directory) })}, `; + const middlewareErrors = (boundaryManifest.pages[page.componentId]?.errors ?? []).filter( + (id) => !boundaryManifest.plans[id].directory, + ); + const middlewareBoundaries = `middlewareBoundaries: ${JSON.stringify({ notFound: boundaryManifest.root, errors: middlewareErrors, ...boundaryHeads(boundaryManifest.plans, [boundaryManifest.root, ...middlewareErrors]) })}, `; const routeOptions = `{ ${serverImportPath ? 'load: _pload_' + safeId + ', ' : ''}${mdHeadRef ? 'head: ' + mdHeadRef + ', ' : ''}${trailingCatchAll ? `trailingSlash: true, catchAllParam: ${JSON.stringify(catchAllParam)}, ` : ''}${middlewareBoundaries}componentId: ${JSON.stringify(page.componentId)}, render: ${renderer}, assets: ${assetTags}, headConfig: __voidHeadConfig, renderOptions: ${JSON.stringify({ renderMode: page.renderMode, ...(options.dev === true ? { dev: true } : {}), ...(boundaryManifest.pages[page.componentId] && { boundaries: boundaryManifest.pages[page.componentId] }) })} }`; lines.push(`app.get(${JSON.stringify(pattern)}, __createPageGetHandler(${routeOptions}));`); if (page.methods.includes('action') || page.methods.includes('actions')) { diff --git a/packages/void/test/unit/page-boundaries.test.ts b/packages/void/test/unit/page-boundaries.test.ts index 9f64359068..df8734af12 100644 --- a/packages/void/test/unit/page-boundaries.test.ts +++ b/packages/void/test/unit/page-boundaries.test.ts @@ -127,6 +127,72 @@ describe('Pages boundary inventory', () => { }); }); +describe('boundary head exports', () => { + it.each([ + [ + '_not-found.tsx', + `export const head = { title: 'Page not found' }; export default () => null`, + ], + [ + '_not-found.vue', + `\n\n`, + ], + [ + '_not-found.svelte', + `\n
`, + ], + ])('reads a static title from %s', async (file, source) => { + const scan = await scanPages(fixture({ [file]: source })); + expect(scan.boundaries).toEqual([ + { + kind: 'not-found', + directory: '', + componentId: '_not-found', + filePath: file, + head: { title: 'Page not found' }, + }, + ]); + }); + + it.each([ + `const title = 'Page not found'; export const head = { title }; export default () => null`, + `export const head = { title: 'Gone', meta: [] }; export default () => null`, + `export const head = () => ({ title: 'Gone' }); export default () => null`, + `export let head = { title: 'Gone' }; export default () => null`, + ])('ignores a head it cannot read statically: %s', async (source) => { + const scan = await scanPages(fixture({ '_error.tsx': source })); + expect(scan.boundaries).toEqual([ + { kind: 'error', directory: '', componentId: '_error', filePath: '_error.tsx' }, + ]); + }); + + it('hands the declared titles to every plan a page can render', async () => { + const root = fixture({ + 'layout.tsx': 'export default () => null', + 'items/page.tsx': 'export default () => null', + '_not-found.tsx': `export const head = { title: 'Page not found' }; export default () => null`, + '_error.tsx': 'export default () => null', + 'items/_error.tsx': `export const head = { title: 'Items broke' }; export default () => null`, + }); + const manifest = createBoundaryManifest(await scanPages(root)); + const titles = (id: string) => + Object.fromEntries( + Object.entries(manifest.pages[id].heads ?? {}).map(([plan, head]) => [ + manifest.plans[plan].componentId, + head.title, + ]), + ); + expect(titles('items/page')).toEqual({ + '_not-found': 'Page not found', + 'items/_error': 'Items broke', + }); + expect(manifest.pages['items/page'].errors).toHaveLength(2); + // The root not-found page and its error page render outside any route. + expect(manifest.root).toBeDefined(); + expect(titles(manifest.root ?? '')).toEqual({ '_not-found': 'Page not found' }); + }); +}); + describe('boundary render plans', () => { it('keeps named replacements at their logical slot instead of their file directory', async () => { const root = fixture({ @@ -658,6 +724,92 @@ describe.each([false, true])('boundary titles (Pages: %s)', (pages) => { ); }); +describe.each([false, true])('declared boundary titles (Pages: %s)', (pages) => { + it.each([ + { status: 404, expected: 'Page not found | Site' }, + { status: 500, expected: 'Something went wrong | Site' }, + { + status: 404, + middlewareTitle: 'Ignored', + middlewareTemplate: '%s | Admin', + expected: 'Page not found | Admin', + }, + ])( + 'renders $expected for status $status', + async ({ status, expected, middlewareTitle, middlewareTemplate }) => { + const app = new Hono(); + app.use(async (c, next) => { + if (middlewareTemplate) { + c.set('headDefaults', { title: middlewareTitle, titleTemplate: middlewareTemplate }); + } + await next(); + }); + app.get( + '/', + createPageGetHandler({ + componentId: 'index', + load: async () => ({ + loader: () => { + if (status === 404) { + return new Response(null, { status: 404 }); + } + throw new Error('SECRET_FAILURE'); + }, + }), + assets: async () => ({ css: '', body: '', preloads: '' }), + headConfig: { titleTemplate: '%s | Site' }, + renderOptions: { + boundaries: { + notFound: 'missing-plan', + errors: ['error-plan'], + heads: { + 'missing-plan': { title: 'Page not found' }, + 'error-plan': { title: 'Something went wrong' }, + }, + }, + }, + render: async (page) => renderHeadToString(page.head!), + }), + ); + const response = await app.request('https://app.test/', { + headers: pages + ? { 'X-VoidPages': 'true', 'X-VoidPages-Version': PAGES_PROTOCOL_VERSION } + : {}, + }); + expect(response.status).toBe(status); + const body = await response.text(); + if (pages) { + expect(deserializePageData(body)).toMatchObject({ head: { title: expected } }); + } else { + expect(body).toContain(`${expected}`); + } + }, + ); + + it('keeps the default title for a boundary that declares none', async () => { + const app = new Hono(); + app.get( + '/', + createPageGetHandler({ + componentId: 'index', + load: async () => ({ loader: () => new Response(null, { status: 404 }) }), + assets: async () => ({ css: '', body: '', preloads: '' }), + headConfig: { titleTemplate: '%s | Site' }, + renderOptions: { + boundaries: { + notFound: 'missing-plan', + errors: ['error-plan'], + heads: { 'error-plan': { title: 'Something went wrong' } }, + }, + }, + render: async (page) => renderHeadToString(page.head!), + }), + ); + const response = await app.request('https://app.test/'); + expect(await response.text()).toContain('Not Found | Site'); + }); +}); + describe('boundary recovery failures', () => { it.each(['malformed JSON', 'body rejection', 'exhausted fallback'])( 'handles %s without replaying the loader', From cf3bf33fc1d49950446f31c7f8f8c00223dbec08 Mon Sep 17 00:00:00 2001 From: Harsh Bhanushali Date: Mon, 30 Nov 2026 17:20:36 +0000 Subject: [PATCH 2/4] feat(pages): let _not-found and _error export head() from a .server companion (#825) Replace the static head export read from the component with an optional _not-found.server.ts / _error.server.ts that exports the usual head(). It receives the Hono context and the error the boundary renders, and its result goes through resolveHead() like a page head. --- docs/guide/pages-routing/errors.md | 18 ++- packages/void/src/pages/boundary-plans.ts | 18 ++- packages/void/src/pages/protocol.ts | 36 ++++- packages/void/src/pages/scan.ts | 19 ++- packages/void/src/pages/types.ts | 2 + packages/void/src/router/compile.ts | 29 +++- packages/void/src/runtime/routing/pages.ts | 24 ++- .../test/integration/page-errors-suite.ts | 11 +- .../void/test/unit/page-boundaries.test.ts | 146 ++++++++++++++++++ .../0093-pages-error-boundaries.md | 5 +- 10 files changed, 287 insertions(+), 21 deletions(-) diff --git a/docs/guide/pages-routing/errors.md b/docs/guide/pages-routing/errors.md index e72fd898a6..f15f1b9d11 100644 --- a/docs/guide/pages-routing/errors.md +++ b/docs/guide/pages-routing/errors.md @@ -118,7 +118,23 @@ Void renders the error inside the layouts at or above the `_error` file, includi Put an error component in a subdirectory to customize that section. Void uses the closest one and keeps its surrounding layouts. If a layout fails, an error component outside that layout handles it. If an error component fails, Void tries an outer one, then its built-in error page. -Boundary components don't have `.server` companions, actions, or their own `layout` export. They aren't routes: `/error` and `/not-found` remain available for ordinary pages. `.dev` and `.prod` variants work like other Pages components. +Boundary components don't have loaders, actions, or their own `layout` export. A `.server` companion is allowed only for [`head()`](#page-titles). They aren't routes: `/error` and `/not-found` remain available for ordinary pages. `.dev` and `.prod` variants work like other Pages components. + +## Page titles + +Error pages use the default titles `Not Found` and `Internal Server Error`, with your [`titleTemplate`](./head.md#page-title-templates) applied. To set your own, add an optional `.server.ts` file next to `_not-found` or `_error` and export a [`head()`](./head.md) from it. It receives the Hono context and the same `error` the component renders: + +```ts +// pages/_error.server.ts (or pages/_not-found.server.ts) +import { defineHead } from 'void/handler'; +import type { ErrorPageProps } from 'void/pages'; + +export const head = defineHead((c, { error }) => ({ + title: error.status === 404 ? 'Page not found' : 'Something went wrong', +})); +``` + +`head()` can return anything a page's head can, and it merges with your config and middleware the same way, so `titleTemplate` still applies. A boundary whose `head()` sets no `title` keeps the default one. The file can only export `head()`; a loader or action is an error. If `head()` throws, Void logs the error and renders the page with the default title. ## Recovery diff --git a/packages/void/src/pages/boundary-plans.ts b/packages/void/src/pages/boundary-plans.ts index d9de7e6fa9..45704995d2 100644 --- a/packages/void/src/pages/boundary-plans.ts +++ b/packages/void/src/pages/boundary-plans.ts @@ -22,6 +22,13 @@ export type BoundaryManifest = { root?: string; rootErrors?: Array; }; +/** What the client manifest carries; the server companion stays out of it. */ +const planFields = ({ kind, directory, componentId, filePath }: PageBoundaryDefinition) => ({ + kind, + directory, + componentId, + filePath, +}); const encloses = (outer: string, inner: string) => !outer || outer === inner || inner.startsWith(outer + '/'); @@ -45,7 +52,7 @@ export function createBoundaryManifest(scan: PageScanResult): BoundaryManifest { .filter((l) => encloses(l.directory, boundary.directory)) .map((l) => layoutKey(l.id)); const id = `_void:boundary:${JSON.stringify([page.componentId, boundary.componentId, retained])}`; - plans[id] = { id, ...boundary, source: page.componentId, layouts: retained }; + plans[id] = { id, ...planFields(boundary), source: page.componentId, layouts: retained }; return id; }; const errors = candidates.filter((b) => b.kind === 'error'); @@ -71,7 +78,7 @@ export function createBoundaryManifest(scan: PageScanResult): BoundaryManifest { const id = `_void:boundary:root-not-found:${JSON.stringify(scan.layouts.filter((l) => !l.directory).map((l) => l.filePath))}`; plans[id] = { id, - ...root, + ...planFields(root), source: id, layouts: scan.layouts .filter((l) => !l.directory) @@ -81,7 +88,12 @@ export function createBoundaryManifest(scan: PageScanResult): BoundaryManifest { const rootErrors: Array = []; if (error) { const errorId = `_void:boundary:root-error:${id}`; - plans[errorId] = { ...error, id: errorId, source: id, layouts: [...plans[id].layouts] }; + plans[errorId] = { + ...planFields(error), + id: errorId, + source: id, + layouts: [...plans[id].layouts], + }; rootErrors.push(errorId); } pages[id] = { diff --git a/packages/void/src/pages/protocol.ts b/packages/void/src/pages/protocol.ts index 10288cdeec..5c3c7377ed 100644 --- a/packages/void/src/pages/protocol.ts +++ b/packages/void/src/pages/protocol.ts @@ -69,6 +69,10 @@ type PageHandler = ((c: CloudContext) => unknown | Promise) | undefined type PageHeadHandler = | ((c: CloudContext, props: Record) => HeadConfig | undefined) | undefined; +type BoundaryHeadHandler = ( + c: CloudContext, + props: { error: { status: number; message: string } }, +) => HeadConfig | undefined; type PageRequestContext = Context | CloudContext; type PageRenderOptions = { renderMode?: PageRenderMode; @@ -466,6 +470,26 @@ export async function recoverPageHttpException( return renderPageFailure(context, error, undefined, renderFn, getAssetTags, configHead, options); } +/** + * The head() a boundary's `.server` companion exports. An error page must still render when + * that file fails, so a failure is logged and the built-in title applies. + */ +async function declaredHead( + load: (() => Promise<{ head?: BoundaryHeadHandler }>) | undefined, + c: CloudContext, + props: Parameters[1], +): Promise { + if (!load) { + return undefined; + } + try { + return (await load()).head?.(c, props); + } catch (failure) { + console.error(failure); + return undefined; + } +} + /** Recover one completed GET operation without replaying its middleware or loader. */ async function renderPageFailure( c: CloudContext, @@ -529,18 +553,24 @@ async function renderPageFailure( continue; } attempted.add(component); + const props = { error: { status, message } }; + const boundaryHead = await declaredHead(options?.boundaries?.loadHeads?.[component], c, props); + const resolved = boundaryHead + ? resolveRequestHead(c, configHead, middlewareHead, boundaryHead) + : head; const page: PageObject = { component, - props: { error: { status, message } }, + props, shared, params: requestParams(c), url: requestPathWithSearch(c), errors: null, head: { - ...head, + ...resolved, title: - head?.title ?? + resolved?.title ?? resolveHead(configHead, middlewareHead, { + ...boundaryHead, title: status === 404 ? 'Not Found' diff --git a/packages/void/src/pages/scan.ts b/packages/void/src/pages/scan.ts index d98fecd255..0cc6090df6 100644 --- a/packages/void/src/pages/scan.ts +++ b/packages/void/src/pages/scan.ts @@ -363,9 +363,11 @@ export async function scanPages(root: string, options?: PageScanOptions): Promis continue; } const base = file.slice(0, -extname(file).length); + const serverPath = ROUTE_EXTENSIONS.map((ext) => `${base}.server.${ext}`).find((candidate) => + existsSync(join(pagesDir, candidate)), + ); if ( boundary[3] || - ROUTE_EXTENSIONS.some((ext) => existsSync(join(pagesDir, `${base}.server.${ext}`))) || deriveFromSource(join(pagesDir, file), 'page-boundary-layout', (source) => scriptBlocks(source, file).some((script) => readStaticExports(script.filename, script.source, new Set(['layout'])).initializers.has( @@ -374,9 +376,7 @@ export async function scanPages(root: string, options?: PageScanOptions): Promis ), ) ) { - throw new Error( - `pages: Boundary '${file}' cannot be an island, select a layout, or have a .server companion.`, - ); + throw new Error(`pages: Boundary '${file}' cannot be an island or select a layout.`); } const directory = segments.slice(0, -1).join('/'); for (const prior of boundaries) { @@ -389,11 +389,22 @@ export async function scanPages(root: string, options?: PageScanOptions): Promis throw new Error(`pages: Ambiguous boundary files '${prior.filePath}' and '${file}'.`); } } + if (serverPath) { + const { methods } = deriveFromSource(join(pagesDir, serverPath), 'page-server', (source) => + detectPageServerMetadata(source, serverPath), + ); + if (methods.length > 0) { + throw new Error( + `pages: '${serverPath}' can only export head(). Boundaries have no loader or actions, so remove ${methods.join(', ')}.`, + ); + } + } boundaries.push({ kind: boundary[1] as PageBoundaryDefinition['kind'], directory, componentId: base, filePath: file, + ...(serverPath && { serverPath }), }); continue; } diff --git a/packages/void/src/pages/types.ts b/packages/void/src/pages/types.ts index ce3cbdabaa..a436d379b4 100644 --- a/packages/void/src/pages/types.ts +++ b/packages/void/src/pages/types.ts @@ -76,6 +76,8 @@ export type PageBoundaryDefinition = { directory: string; componentId: string; filePath: string; + /** Optional `.server` companion that exports `head()`, relative to pages/. */ + serverPath?: string; }; export type PageError = Readonly<{ status: number; message: string }>; diff --git a/packages/void/src/router/compile.ts b/packages/void/src/router/compile.ts index 3b12e08b2d..0d17e9bef0 100644 --- a/packages/void/src/router/compile.ts +++ b/packages/void/src/router/compile.ts @@ -1057,6 +1057,31 @@ function compilePageRoutes( ]; } lines.push('const __loadPagesManifest = __createManifestLoader();'); + // A boundary's optional `.server` companion supplies head(); its module loads only when that boundary renders. + const boundaryHeadLoaders: Record = {}; + const boundaryHeadModules = new Map(); + for (const plan of Object.values(boundaryManifest.plans)) { + const serverPath = scan.pages.boundaries?.find( + (boundary) => boundary.filePath === plan.filePath, + )?.serverPath; + if (!serverPath) { + continue; + } + let loader = boundaryHeadModules.get(serverPath); + if (!loader) { + loader = `__boundaryHead${boundaryHeadModules.size}`; + boundaryHeadModules.set(serverPath, loader); + lines.push( + `const ${loader} = __createModuleLoader(() => import(${JSON.stringify(`${pages.pagesDir}/${serverPath}`)}));`, + ); + } + boundaryHeadLoaders[plan.id] = loader; + } + const boundaryHeadsOption = boundaryHeadModules.size + ? `boundaryHeads: { ${Object.entries(boundaryHeadLoaders) + .map(([id, loader]) => `${JSON.stringify(id)}: ${loader}`) + .join(', ')} }, ` + : ''; const assetMetadata = { pageCssKeys, devRootPhases: options.dev ? pageDevRootPhases : undefined, @@ -1075,7 +1100,7 @@ function compilePageRoutes( if (boundaryManifest.root) { const island = scan.pages.pages.length > 0 && scan.pages.pages.every((page) => page.island); lines.push( - `const __voidRootNotFoundOptions = { componentId: ${JSON.stringify(boundaryManifest.root)}, load: async () => ({ loader: () => new Response(null, { status: 404 }) }), render: ${island ? 'renderIslandPage' : 'renderPage'}, assets: ${island && pages.islandClientEntryId ? 'getIslandsAssetTags' : 'getPagesAssetTags'}, headConfig: __voidHeadConfig, renderOptions: ${JSON.stringify({ renderMode: island ? 'island' : 'server', dev: options.dev === true, boundaries: { notFound: boundaryManifest.root, errors: boundaryManifest.rootErrors ?? [] } })} }; const __voidRootNotFound = __createPageGetHandler(__voidRootNotFoundOptions); export const __voidRenderStaticNotFound = __createStaticNotFound({ ...__voidRootNotFoundOptions, render: renderPage, assets: getPagesAssetTags });`, + `const __voidRootNotFoundOptions = { ${boundaryHeadsOption}componentId: ${JSON.stringify(boundaryManifest.root)}, load: async () => ({ loader: () => new Response(null, { status: 404 }) }), render: ${island ? 'renderIslandPage' : 'renderPage'}, assets: ${island && pages.islandClientEntryId ? 'getIslandsAssetTags' : 'getPagesAssetTags'}, headConfig: __voidHeadConfig, renderOptions: ${JSON.stringify({ renderMode: island ? 'island' : 'server', dev: options.dev === true, boundaries: { notFound: boundaryManifest.root, errors: boundaryManifest.rootErrors ?? [] } })} }; const __voidRootNotFound = __createPageGetHandler(__voidRootNotFoundOptions); export const __voidRenderStaticNotFound = __createStaticNotFound({ ...__voidRootNotFoundOptions, render: renderPage, assets: getPagesAssetTags });`, ); } @@ -1121,7 +1146,7 @@ function compilePageRoutes( const pattern = trailingCatchAll ? page.pattern.slice(0, -1) : page.pattern; const catchAllParam = page.pattern.match(/:([^/{}]+)\{\.\+\}\/$/)?.[1]; const middlewareBoundaries = `middlewareBoundaries: ${JSON.stringify({ notFound: boundaryManifest.root, errors: (boundaryManifest.pages[page.componentId]?.errors ?? []).filter((id) => !boundaryManifest.plans[id].directory) })}, `; - const routeOptions = `{ ${serverImportPath ? 'load: _pload_' + safeId + ', ' : ''}${mdHeadRef ? 'head: ' + mdHeadRef + ', ' : ''}${trailingCatchAll ? `trailingSlash: true, catchAllParam: ${JSON.stringify(catchAllParam)}, ` : ''}${middlewareBoundaries}componentId: ${JSON.stringify(page.componentId)}, render: ${renderer}, assets: ${assetTags}, headConfig: __voidHeadConfig, renderOptions: ${JSON.stringify({ renderMode: page.renderMode, ...(options.dev === true ? { dev: true } : {}), ...(boundaryManifest.pages[page.componentId] && { boundaries: boundaryManifest.pages[page.componentId] }) })} }`; + const routeOptions = `{ ${boundaryHeadsOption}${serverImportPath ? 'load: _pload_' + safeId + ', ' : ''}${mdHeadRef ? 'head: ' + mdHeadRef + ', ' : ''}${trailingCatchAll ? `trailingSlash: true, catchAllParam: ${JSON.stringify(catchAllParam)}, ` : ''}${middlewareBoundaries}componentId: ${JSON.stringify(page.componentId)}, render: ${renderer}, assets: ${assetTags}, headConfig: __voidHeadConfig, renderOptions: ${JSON.stringify({ renderMode: page.renderMode, ...(options.dev === true ? { dev: true } : {}), ...(boundaryManifest.pages[page.componentId] && { boundaries: boundaryManifest.pages[page.componentId] }) })} }`; lines.push(`app.get(${JSON.stringify(pattern)}, __createPageGetHandler(${routeOptions}));`); if (page.methods.includes('action') || page.methods.includes('actions')) { lines.push( diff --git a/packages/void/src/runtime/routing/pages.ts b/packages/void/src/runtime/routing/pages.ts index 98a3bae659..136c33b75a 100644 --- a/packages/void/src/runtime/routing/pages.ts +++ b/packages/void/src/runtime/routing/pages.ts @@ -39,10 +39,26 @@ export type PageRouteOptions = { headConfig: PageGetArguments[6] | null; renderOptions: PageGetArguments[7]; middlewareBoundaries?: NonNullable['boundaries']; + /** Loads the `.server` companion of a boundary component, by plan id. */ + boundaryHeads?: NonNullable['boundaries']>['loadHeads']; namedActions?: boolean; trailingSlash?: boolean; catchAllParam?: string; }; +/** Render options with the boundary head loaders, which the JSON-serialized options cannot carry. */ +function withBoundaryHeads( + options: PageRouteOptions, + boundaries = options.renderOptions?.boundaries, +): PageGetArguments[7] { + return { + ...options.renderOptions, + ...(boundaries && { + boundaries: options.boundaryHeads + ? { ...boundaries, loadHeads: options.boundaryHeads } + : boundaries, + }), + }; +} // Hono's trie matcher cannot match a named catch-all followed by a literal slash. // Register that route without the slash, then enforce the public URL and exclude // the final separator from the parameter before invoking application code. @@ -113,7 +129,7 @@ export function createPageErrorHandler( options.render, options.assets, options.headConfig ?? undefined, - { ...options.renderOptions, boundaries: options.middlewareBoundaries ?? { errors: [] } }, + withBoundaryHeads(options, options.middlewareBoundaries ?? { errors: [] }), ); // oxlint-disable-next-line typescript/return-await -- Keep failures from the fallback outside boundary recovery and restore the route index immediately. return response ?? fallback(error, c); @@ -173,7 +189,7 @@ export function createPageGetHandler(options: PageRouteOptions): (c: Context) => options.render, options.assets, options.headConfig ?? undefined, - options.renderOptions, + withBoundaryHeads(options), ); } catch (error) { const response = await recoverPageHttpException( @@ -182,7 +198,7 @@ export function createPageGetHandler(options: PageRouteOptions): (c: Context) => options.render, options.assets, options.headConfig ?? undefined, - options.renderOptions, + withBoundaryHeads(options), ); if (response) { return response; @@ -247,7 +263,7 @@ export function createPageMutationHandler( options.render, options.assets, options.headConfig ?? undefined, - options.renderOptions, + withBoundaryHeads(options), ); }; if (options.namedActions) { diff --git a/packages/void/test/integration/page-errors-suite.ts b/packages/void/test/integration/page-errors-suite.ts index 6af61b857d..b5e728f7fa 100644 --- a/packages/void/test/integration/page-errors-suite.ts +++ b/packages/void/test/integration/page-errors-suite.ts @@ -131,6 +131,11 @@ export default defineMiddleware(async (c, next) => { ), ); write(`pages/_error.${extension}`, component('

Error page

{error.message}

')); + write( + 'pages/_not-found.server.ts', + `import { defineHead } from 'void/handler'; +export const head = defineHead<{ error: { status: number } }>((_c, { error }) => ({ title: error.status === 404 ? 'Page not found' : 'Unexpected status' }));`, + ); if (framework === 'vue') { write( `pages/_not-found.${extension}`, @@ -386,7 +391,7 @@ export const loader = defineHandler(c => { expect(response.headers.get('X-Security')).toBe('retained'); const text = await response.text(); expect(text).not.toContain('SECRET_'); - const title = `${status === 404 ? 'Not Found' : 'Internal Server Error'} | Error tests`; + const title = `${status === 404 ? 'Page not found' : 'Internal Server Error'} | Error tests`; if (pages) { expect(response.headers.get('X-VoidPages')).toBe('true'); expect(deserializePageData(text)).toMatchObject({ @@ -476,7 +481,9 @@ export const loader = defineHandler(c => { if (name !== 'Crash') { await expect .poll(() => page.title()) - .toBe(`${name === 'Unexpected' ? 'Internal Server Error' : 'Not Found'} | Error tests`); + .toBe( + `${name === 'Unexpected' ? 'Internal Server Error' : 'Page not found'} | Error tests`, + ); } expect(await page.evaluate(() => (window as unknown as { marker: boolean }).marker)).toBe( true, diff --git a/packages/void/test/unit/page-boundaries.test.ts b/packages/void/test/unit/page-boundaries.test.ts index 9f64359068..0ee605624b 100644 --- a/packages/void/test/unit/page-boundaries.test.ts +++ b/packages/void/test/unit/page-boundaries.test.ts @@ -9,6 +9,7 @@ import { createActionErrorFromResponse } from '../../src/pages/action-result.ts' import { clientPageError } from '../../src/pages/boundary-client.ts'; import { createBoundaryManifest } from '../../src/pages/boundary-plans.ts'; import { renderHeadToString } from '../../src/pages/head.ts'; +import type { HeadConfig } from '../../src/pages/head.ts'; import { generateComponentManifest } from '../../src/pages/manifest.ts'; import { scanPages } from '../../src/pages/scan.ts'; import { deserializePageData } from '../../src/pages/serialize.ts'; @@ -127,6 +128,36 @@ describe('Pages boundary inventory', () => { }); }); +describe('boundary head companions', () => { + it('records an optional .server companion without sending its path to the client manifest', async () => { + const root = fixture({ + 'index.tsx': 'export default()=>null', + '_not-found.tsx': 'export default()=>null', + '_not-found.server.ts': 'export const head = () => ({ title: "Page not found" })', + '_error.tsx': 'export default()=>null', + }); + const scan = await scanPages(root); + expect(scan.boundaries?.map(({ kind, serverPath }) => ({ kind, serverPath }))).toEqual([ + { kind: 'error', serverPath: undefined }, + { kind: 'not-found', serverPath: '_not-found.server.ts' }, + ]); + expect(JSON.stringify(createBoundaryManifest(scan))).not.toContain('.server'); + expect(scan.pages.map((page) => page.serverPath)).toEqual([null]); + }); + it('rejects a companion that exports a loader or actions', async () => { + for (const exported of ['loader', 'action']) { + await expect( + scanPages( + fixture({ + '_error.tsx': 'export default()=>null', + '_error.server.ts': `export const ${exported} = () => ({})`, + }), + ), + ).rejects.toThrow(`'_error.server.ts' can only export head()`); + } + }); +}); + describe('boundary render plans', () => { it('keeps named replacements at their logical slot instead of their file directory', async () => { const root = fixture({ @@ -658,6 +689,121 @@ describe.each([false, true])('boundary titles (Pages: %s)', (pages) => { ); }); +describe.each([false, true])('boundary head companions (Pages: %s)', (pages) => { + type Head = ( + c: unknown, + props: { error: { status: number; message: string } }, + ) => HeadConfig | undefined; + async function request( + head: Head | undefined, + status: number, + options: { middleware?: boolean; load?: () => Promise<{ head?: Head }> } = {}, + ) { + const app = new Hono(); + app.use(async (c, next) => { + if (options.middleware) { + c.set('headDefaults', { title: 'Ignored', titleTemplate: '%s | Admin' }); + } + await next(); + }); + app.get( + '/', + createPageGetHandler({ + componentId: 'index', + load: async () => ({ + loader: () => { + if (status === 404) { + return new Response(null, { status: 404 }); + } + throw new Error('SECRET_FAILURE'); + }, + }), + assets: async () => ({ css: '', body: '', preloads: '' }), + headConfig: { titleTemplate: '%s | Site' }, + boundaryHeads: { + 'missing-plan': options.load ?? (async () => ({ head })), + 'error-plan': options.load ?? (async () => ({ head })), + }, + renderOptions: { boundaries: { notFound: 'missing-plan', errors: ['error-plan'] } }, + render: async (page) => renderHeadToString(page.head!), + }), + ); + const response = await app.request('https://app.test/', { + headers: pages + ? { 'X-VoidPages': 'true', 'X-VoidPages-Version': PAGES_PROTOCOL_VERSION } + : {}, + }); + const body = await response.text(); + return { + status: response.status, + body, + head: pages ? deserializePageData(body).head : undefined, + }; + } + const titleOf = (result: Awaited>) => + pages ? result.head?.title : /(.*?)<\/title>/.exec(result.body)?.[1]; + + it.each([ + { status: 404, expected: 'Page not found | Site' }, + { status: 500, expected: 'Something went wrong | Site' }, + ])('uses the head() title for status $status', async ({ status, expected }) => { + const result = await request( + (_c, { error }) => ({ + title: error.status === 404 ? 'Page not found' : 'Something went wrong', + }), + status, + ); + expect(result.status).toBe(status); + expect(titleOf(result)).toBe(expected); + expect(result.body).not.toContain('SECRET_'); + }); + it('gives head() the context and the error the component renders', async () => { + const seen: Array<unknown> = []; + await request((c, props) => { + seen.push(typeof (c as { req?: unknown }).req, props.error); + return undefined; + }, 500); + expect(seen).toEqual(['object', { status: 500, message: 'Internal Server Error' }]); + }); + it('applies the middleware title template and keeps the other head fields', async () => { + const result = await request( + () => ({ title: 'Page not found', meta: [{ name: 'robots', content: 'noindex' }] }), + 404, + { middleware: true }, + ); + expect(titleOf(result)).toBe('Page not found | Admin'); + expect(JSON.stringify(result.head ?? result.body)).toContain('noindex'); + }); + it('keeps the default title when head() sets none', async () => { + const result = await request(() => ({ meta: [{ name: 'robots', content: 'noindex' }] }), 404); + expect(titleOf(result)).toBe('Not Found | Site'); + }); + it('keeps the default title when the boundary exports no head()', async () => { + expect(titleOf(await request(undefined, 404))).toBe('Not Found | Site'); + }); + it.each(['head() throws', 'the module fails to load'])( + 'still renders the error page when %s', + async (failure) => { + const result = await request( + () => { + throw new Error('SECRET_HEAD_FAILURE'); + }, + 404, + failure === 'head() throws' + ? undefined + : { + load: async () => { + throw new Error('SECRET_IMPORT_FAILURE'); + }, + }, + ); + expect(result.status).toBe(404); + expect(titleOf(result)).toBe('Not Found | Site'); + expect(result.body).not.toContain('SECRET_'); + }, + ); +}); + describe('boundary recovery failures', () => { it.each(['malformed JSON', 'body rejection', 'exhausted fallback'])( 'handles %s without replaying the loader', diff --git a/platform/meta/design-docs/0093-pages-error-boundaries.md b/platform/meta/design-docs/0093-pages-error-boundaries.md index 921ea42fa9..9223441aa7 100644 --- a/platform/meta/design-docs/0093-pages-error-boundaries.md +++ b/platform/meta/design-docs/0093-pages-error-boundaries.md @@ -23,8 +23,9 @@ Pages environment selection; reject ambiguous definitions in one environment. Files inside `_layouts` or any other ignored underscore directory remain ignored. The two exact basenames are the only exception to the scanner's ignored-file -rule. Boundary files cannot be islands, export a `layout` selection, or have -`.server` companions/loaders/actions. Report unsupported combinations with the +rule. Boundary files cannot be islands or export a `layout` selection. A boundary +may have a `.server` companion, but only for `head()`; a companion that exports a +loader or actions is an error. Report unsupported combinations with the source filename. Multiple supported component extensions for the same boundary are an error, just as competing ordinary routes are; do not guess an adapter. From 2d07f95c5d975a5d9fb850fa2c85b6e6810834ba Mon Sep 17 00:00:00 2001 From: Harsh Bhanushali <bhanushaliharsh434@gmail.com> Date: Mon, 30 Nov 2026 18:13:16 +0000 Subject: [PATCH 3/4] ci: retrigger From 9b5ab660fef1aab2bb81b66946e0d786a8288361 Mon Sep 17 00:00:00 2001 From: Harsh Bhanushali <bhanushaliharsh434@gmail.com> Date: Mon, 30 Nov 2026 18:19:46 +0000 Subject: [PATCH 4/4] ci: retrigger 2