Skip to content

Commit 677c6fd

Browse files
committed
Avoid rendering the root fallback for loader not-found results.
1 parent 99bc816 commit 677c6fd

5 files changed

Lines changed: 149 additions & 9 deletions

File tree

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
import type { Context } from 'hono';
2+
3+
const loaderBoundaries = new WeakSet<Context>();
4+
5+
export function handlesPageLoaderNotFound(c: Context): boolean {
6+
return loaderBoundaries.has(c);
7+
}
8+
9+
/** Defer only Void's app fallback while a loader can select its own boundary. */
10+
export async function withLoaderNotFoundBoundary(
11+
c: Context,
12+
load: () => unknown,
13+
): Promise<unknown> {
14+
const alreadyHandled = loaderBoundaries.has(c);
15+
loaderBoundaries.add(c);
16+
try {
17+
return await load();
18+
} finally {
19+
if (!alreadyHandled) {
20+
loaderBoundaries.delete(c);
21+
}
22+
}
23+
}

‎packages/void/src/pages/protocol.ts‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@ import {
1313
type HeadDescriptor,
1414
type HeadConfig,
1515
} from './head.ts';
16+
import { withLoaderNotFoundBoundary } from './not-found-context.ts';
1617
import { escapeScriptJson } from './script-json.ts';
1718
import { serializePageData } from './serialize.ts';
1819
import type { DevCssAsset, PageRenderMode } from './types.ts';
@@ -333,14 +334,15 @@ async function runLoader(
333334
c: CloudContext,
334335
render: (props: Record<string, unknown>) => Promise<Response>,
335336
recover?: (error: unknown, response?: Response) => Promise<Response | undefined>,
337+
recoverNotFound = false,
336338
): Promise<Response> {
337339
if (!handler) {
338340
return render({});
339341
}
340342
return runPageHandler(handler, c, async (leaf) => {
341343
let result: unknown;
342344
try {
343-
result = await leaf(c);
345+
result = recoverNotFound ? await withLoaderNotFoundBoundary(c, () => leaf(c)) : await leaf(c);
344346
} catch (error) {
345347
const recovered = await recover?.(error);
346348
if (recovered) {
@@ -826,6 +828,7 @@ async function runPageGet(
826828
}
827829
},
828830
recover,
831+
options?.boundaries?.notFound !== undefined,
829832
);
830833
}
831834

‎packages/void/src/runtime/routing-pages.ts‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import { Context, type MiddlewareHandler } from 'hono';
22
import { markActionKey } from '../pages/action-key.ts';
3+
import { handlesPageLoaderNotFound } from '../pages/not-found-context.ts';
34
import { handlePageGet, handlePageMutation } from '../pages/protocol.ts';
45
import { decodePagePath } from '../pages/url.ts';
56
import type { ClientAssetTags } from './routing-assets.ts';
@@ -171,6 +172,10 @@ export function createPagesFallback(options: {
171172
}): (c: Context) => Promise<Response> {
172173
const cachePolicy = createAssetCachePolicy(options.assetsDir);
173174
return async (c) => {
175+
// The loader's boundary owns this 404; skip root rendering and asset fallbacks.
176+
if (handlesPageLoaderNotFound(c)) {
177+
return c.newResponse(null, 404);
178+
}
174179
const path = c.req.path;
175180
if (
176181
path === '/api' ||

‎packages/void/test/integration/page-errors.test.ts‎

Lines changed: 16 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -79,7 +79,7 @@ describe.each(frameworks)('Pages errors with %s', (framework) => {
7979
);
8080
write(
8181
'middleware/shared.ts',
82-
`import { defineMiddleware } from 'void/handler'; export default defineMiddleware(async (c,next)=>{c.set('shared',{viewer:'alice'}); c.header('X-Security','retained'); const guard=c.req.header('X-Test-Guard'); if(guard==='not-found') return c.notFound(); if(guard==='explicit') return c.text('Hidden by guard',404); await next(); if(guard==='after-not-found') c.res=await c.notFound();});`,
82+
`import { defineMiddleware } from 'void/handler'; export default defineMiddleware(async (c,next)=>{c.set('shared',{viewer:'alice',...(c.req.header('X-Test-No-Root') ? { noRoot: true } : {})}); c.header('X-Security','retained'); const guard=c.req.header('X-Test-Guard'); if(guard==='not-found') return c.notFound(); if(guard==='explicit') return c.text('Hidden by guard',404); await next(); if(guard==='after-not-found') c.res=await c.notFound();});`,
8383
);
8484
write('pages/style.css', 'nav { color: rgb(20, 80, 100); }');
8585
const nav =
@@ -102,13 +102,19 @@ describe.each(frameworks)('Pages errors with %s', (framework) => {
102102
);
103103
write(
104104
`pages/_not-found.${extension}`,
105-
component('<h1>Missing page</h1><p>{error.message}</p>'),
105+
component(
106+
'<h1>Missing page</h1><p>{error.message}</p>',
107+
"if(shared.noRoot) throw new Error('UNUSED_ROOT_BOUNDARY');",
108+
),
106109
);
107110
write(`pages/_error.${extension}`, component('<h1>Error page</h1><p>{error.message}</p>'));
108111
if (framework === 'vue') {
109112
write(
110113
`pages/_not-found.${extension}`,
111-
component('<h1>Missing page</h1><p>{{error.message}}</p>'),
114+
component(
115+
'<h1>Missing page</h1><p>{{error.message}}</p>',
116+
"if(shared.noRoot) throw new Error('UNUSED_ROOT_BOUNDARY');",
117+
),
112118
);
113119
write(`pages/_error.${extension}`, component('<h1>Error page</h1><p>{{error.message}}</p>'));
114120
}
@@ -189,10 +195,7 @@ describe.each(frameworks)('Pages errors with %s', (framework) => {
189195
);
190196
write(`pages/nested/other.${extension}`, component('<h1>Other nested page</h1>'));
191197
write(`pages/islands/index.island.${extension}`, component('<h1>Island document</h1>'));
192-
write(
193-
'pages/islands/index.server.ts',
194-
'export const loader = () => new Response(null,{status:404});',
195-
);
198+
write('pages/islands/index.server.ts', 'export const loader = c => c.notFound();');
196199
write(`pages/islands/_not-found.${extension}`, component('<h1>Missing island page</h1>'));
197200
const counter =
198201
framework === 'react'
@@ -286,6 +289,12 @@ describe.each(frameworks)('Pages errors with %s', (framework) => {
286289
},
287290
);
288291

292+
it('renders a loader not-found without attempting an unused root boundary', async () => {
293+
const response = await fetch(base + '/islands', { headers: { 'X-Test-No-Root': 'true' } });
294+
expect(response.status).toBe(404);
295+
expect(await response.text()).toContain('Missing island page');
296+
});
297+
289298
it('returns status-correct documents and marked error payloads without exposing secrets', async () => {
290299
for (const [path, status] of [
291300
['/unknown', 404],

‎packages/void/test/unit/page-boundaries.test.ts‎

Lines changed: 101 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,9 @@ import { generateComponentManifest } from '../../src/pages/manifest.ts';
1212
import { scanPages } from '../../src/pages/scan.ts';
1313
import { deserializePageData } from '../../src/pages/serialize.ts';
1414
import { defineHandler } from '../../src/runtime/handler.ts';
15-
import { createPageGetHandler } from '../../src/runtime/routing-pages.ts';
15+
import { createErrorRenderer } from '../../src/runtime/routing-errors.ts';
16+
import { createPageGetHandler, createPagesFallback } from '../../src/runtime/routing-pages.ts';
17+
import { createRoutingRuntime } from '../../src/runtime/routing.ts';
1618

1719
const roots: Array<string> = [];
1820
function fixture(files: Record<string, string>) {
@@ -277,6 +279,104 @@ describe('Pages loader boundary protocol', () => {
277279
});
278280
});
279281

282+
describe('loader not-found dispatch', () => {
283+
it('preserves a custom app not-found redirect', async () => {
284+
const app = new Hono();
285+
app.notFound((c) => c.redirect('/login'));
286+
app.get(
287+
'/',
288+
createPageGetHandler({
289+
componentId: 'index',
290+
load: async () => ({ loader: (c) => c.notFound() }),
291+
render: async () => '<main>Missing page</main>',
292+
assets: async () => ({ css: '', body: '', preloads: '' }),
293+
headConfig: null,
294+
renderOptions: { boundaries: { notFound: 'missing', errors: [] } },
295+
}),
296+
);
297+
const response = await app.request('https://app.test/');
298+
expect(response.status).toBe(302);
299+
expect(response.headers.get('Location')).toBe('/login');
300+
});
301+
302+
it.each([
303+
{ pages: false, boundary: true },
304+
{ pages: true, boundary: true },
305+
{ pages: false, boundary: false },
306+
])(
307+
'renders a loader not-found once (Pages: $pages, boundary: $boundary)',
308+
async ({ pages, boundary }) => {
309+
let rootCalls = 0;
310+
let loaderCalls = 0;
311+
const rendered: Array<string> = [];
312+
const app = new Hono();
313+
app.notFound(
314+
createPagesFallback({
315+
routing: createRoutingRuntime(app, { nodeTarget: true }),
316+
errors: createErrorRenderer({ projectRoot: '/project', homeDir: '/home' }),
317+
pageNotFound: createPageGetHandler({
318+
componentId: 'root',
319+
load: async () => ({ loader: () => new Response(null, { status: 404 }) }),
320+
render: async () => {
321+
rootCalls++;
322+
return '<main>Root not found</main>';
323+
},
324+
assets: async () => ({ css: '', body: '', preloads: '' }),
325+
headConfig: null,
326+
renderOptions: { boundaries: { notFound: 'root/not-found', errors: [] } },
327+
}),
328+
}),
329+
);
330+
app.get(
331+
'/items/:id',
332+
createPageGetHandler({
333+
componentId: 'items/item',
334+
load: async () => ({
335+
loader: defineHandler(
336+
async (c, next) => {
337+
const notFound = c.notFound;
338+
await next();
339+
expect(c.notFound).toBe(notFound);
340+
},
341+
async (c) => {
342+
loaderCalls++;
343+
await Promise.resolve();
344+
return c.notFound();
345+
},
346+
),
347+
}),
348+
render: async (page) => {
349+
rendered.push(page.component);
350+
return '<main>' + page.component + '</main>';
351+
},
352+
assets: async () => ({ css: '', body: '', preloads: '' }),
353+
headConfig: null,
354+
renderOptions: boundary
355+
? { boundaries: { notFound: 'items/not-found', errors: [] } }
356+
: undefined,
357+
}),
358+
);
359+
const response = await app.request('https://app.test/items/1', {
360+
headers: pages
361+
? { 'X-VoidPages': 'true', 'X-VoidPages-Version': PAGES_PROTOCOL_VERSION }
362+
: {},
363+
});
364+
expect(response.status).toBe(404);
365+
expect(rootCalls).toBe(boundary ? 0 : 1);
366+
expect(loaderCalls).toBe(1);
367+
expect(rendered).toEqual(pages || !boundary ? [] : ['items/not-found']);
368+
const body = await response.text();
369+
if (pages) {
370+
expect(deserializePageData(body)).toMatchObject({ component: 'items/not-found' });
371+
} else {
372+
expect(body).toBe(
373+
boundary ? '<main>items/not-found</main>' : '<main>Root not found</main>',
374+
);
375+
}
376+
},
377+
);
378+
});
379+
280380
describe('boundary recovery failures', () => {
281381
it.each(['malformed JSON', 'body rejection', 'exhausted fallback'])(
282382
'handles %s without replaying the loader',

0 commit comments

Comments
 (0)