Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
37 changes: 32 additions & 5 deletions packages/void/src/pages/not-found-context.ts
Original file line number Diff line number Diff line change
@@ -1,22 +1,49 @@
import type { Context } from 'hono';

const loaderNotFound = new WeakSet<Context>();
const loaderBoundaries = new WeakSet<Context>();

/** The loader already answered this URL with `c.notFound()`, so assets must not. */
export function handlesPageLoaderNotFound(c: Context): boolean {
return loaderNotFound.has(c);
}

/** The active loader's not-found boundary renders instead of the fallback. */
export function ownsLoaderNotFoundBoundary(c: Context): boolean {
return loaderBoundaries.has(c);
}

/** Defer only Void's app fallback while a loader can select its own boundary. */
export async function withLoaderNotFoundBoundary(
/**
* Record a loader's `c.notFound()` for the rest of the request.
*
* Hono resolves `c.notFound()` inside the loader call, so the marker has to be
* set before the fallback runs. It also has to outlive the loader: the loader
* returns the fallback's response, which must never be read as page props.
* Boundary ownership ends with the loader so outer middleware can render the
* root not-found page after `await next()`.
*/
export async function withLoaderNotFoundDecision(
c: Context,
ownBoundary: boolean,
load: () => unknown,
): Promise<unknown> {
const alreadyHandled = loaderBoundaries.has(c);
loaderBoundaries.add(c);
const notFound = c.notFound;
const alreadyOwned = loaderBoundaries.has(c);
c.notFound = () => {
// The outer page owns the decision when a fallback render re-enters a loader.
if (!loaderNotFound.has(c)) {
loaderNotFound.add(c);
if (ownBoundary) {
loaderBoundaries.add(c);
}
}
return notFound.call(c);
};
try {
return await load();
} finally {
if (!alreadyHandled) {
c.notFound = notFound;
if (!alreadyOwned) {
loaderBoundaries.delete(c);
}
}
Expand Down
8 changes: 5 additions & 3 deletions packages/void/src/pages/protocol.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ import {
type HeadDescriptor,
type HeadConfig,
} from './head.ts';
import { withLoaderNotFoundBoundary } from './not-found-context.ts';
import { withLoaderNotFoundDecision } from './not-found-context.ts';
import { escapeScriptJson } from './script-json.ts';
import { serializePageData } from './serialize.ts';
import type { DevCssAsset, PageRenderMode } from './types.ts';
Expand Down Expand Up @@ -352,15 +352,17 @@ async function runLoader(
c: CloudContext,
render: (props: Record<string, unknown>) => Promise<Response>,
recover?: (error: unknown, response?: Response) => Promise<Response | undefined>,
recoverNotFound = false,
ownsNotFoundBoundary = false,
): Promise<Response> {
if (!handler) {
return render({});
}
return runPageHandler(handler, c, async (leaf) => {
let result: unknown;
try {
result = recoverNotFound ? await withLoaderNotFoundBoundary(c, () => leaf(c)) : await leaf(c);
// Always wrapped: even without a boundary, a loader's `c.notFound()`
// decides the response and keeps the asset fallback out of the URL.
result = await withLoaderNotFoundDecision(c, ownsNotFoundBoundary, () => leaf(c));
} catch (error) {
const recovered = await recover?.(error);
if (recovered) {
Expand Down
17 changes: 12 additions & 5 deletions packages/void/src/runtime/routing-pages.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,10 @@ import {
markActionKey,
searchWithoutPreservedQuery,
} from '../pages/action-key.ts';
import { handlesPageLoaderNotFound } from '../pages/not-found-context.ts';
import {
handlesPageLoaderNotFound,
ownsLoaderNotFoundBoundary,
} from '../pages/not-found-context.ts';
import { handlePageGet, handlePageMutation } from '../pages/protocol.ts';
import { decodePagePath } from '../pages/url.ts';
import type { ClientAssetTags } from './routing-assets.ts';
Expand Down Expand Up @@ -181,8 +184,8 @@ export function createPagesFallback(options: {
}): (c: Context) => Promise<Response> {
const cachePolicy = createAssetCachePolicy(options.assetsDir);
return async (c) => {
// The loader's boundary owns this 404; skip root rendering and asset fallbacks.
if (handlesPageLoaderNotFound(c)) {
// The loader's own boundary owns this 404; skip root rendering and asset fallbacks.
if (ownsLoaderNotFoundBoundary(c)) {
return c.newResponse(null, 404);
}
const path = c.req.path;
Expand All @@ -194,8 +197,12 @@ export function createPagesFallback(options: {
return c.text('Not Found', 404);
}
const assets = c.env?.ASSETS;
const assetResponse: Response =
assets && typeof assets.fetch === 'function'
// A loader that called `c.notFound()` already claimed this URL. Serving a
// static file that happens to share the path would turn its bytes into the
// loader's return value, so answer from the not-found path instead.
const assetResponse: Response = handlesPageLoaderNotFound(c)
? new Response('Not Found', { status: 404 })
: assets && typeof assets.fetch === 'function'
? await assets.fetch(c.req.raw)
: options.routing.markNoMatch(c.req.raw, new Response('Not Found', { status: 404 }));
const filePath = path.includes('/.') || path.substring(path.lastIndexOf('/') + 1).includes('.');
Expand Down
107 changes: 107 additions & 0 deletions packages/void/test/unit/page-boundaries.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -375,6 +375,113 @@ describe('loader not-found dispatch', () => {
}
},
);

it.each([false, true])(
'renders the root boundary for middleware after a loader not-found (Pages: %s)',
async (pages) => {
let assetReads = 0;
const app = new Hono();
const runtime = createRoutingRuntime(app, { nodeTarget: true });
const common = {
assets: async () => ({ css: '', body: '', preloads: '' }),
headConfig: null,
render: async (page: { component: string }) => `<h1>${page.component}</h1>`,
};
app.use(runtime.contextMiddleware);
app.use(async (c, next) => {
await next();
c.res = await c.notFound();
});
app.notFound(
createPagesFallback({
routing: runtime,
errors: createErrorRenderer({ projectRoot: '/project', homeDir: '/home' }),
pageNotFound: createPageGetHandler({
...common,
componentId: 'root',
load: async () => ({ loader: () => new Response(null, { status: 404 }) }),
renderOptions: { boundaries: { notFound: 'root-not-found', errors: [] } },
}),
}),
);
app.get(
'/items/:id',
createPageGetHandler({
...common,
componentId: 'item',
load: async () => ({ loader: (c) => c.notFound() }),
renderOptions: { boundaries: { notFound: 'item-not-found', errors: [] } },
}),
);
const response = await app.request(
'https://app.test/items/missing',
{
headers: pages
? { 'X-VoidPages': 'true', 'X-VoidPages-Version': PAGES_PROTOCOL_VERSION }
: {},
},
{
ASSETS: {
fetch: async () => {
assetReads++;
return Response.json({ static: 'item' });
},
},
},
);
expect(response.status).toBe(404);
expect(assetReads).toBe(0);
const body = await response.text();
if (pages) {
expect(deserializePageData(body)).toMatchObject({ component: 'root-not-found' });
} else {
expect(body).toContain('<h1>root-not-found</h1>');
}
},
);

it('keeps a static file at the same path out of a loader not-found', async () => {
const fetched: Array<string> = [];
const rendered: Array<string> = [];
const app = new Hono();
app.notFound(
createPagesFallback({
routing: createRoutingRuntime(app, { nodeTarget: true }),
errors: createErrorRenderer({ projectRoot: '/project', homeDir: '/home' }),
}),
);
app.get(
'/docs/:name',
createPageGetHandler({
componentId: 'docs/name',
load: async () => ({ loader: (c) => c.notFound() }),
render: async (page) => {
rendered.push(JSON.stringify(page.props));
return '<main>docs page</main>';
},
assets: async () => ({ css: '', body: '', preloads: '' }),
headConfig: null,
renderOptions: { boundaries: { errors: [] } },
}),
);
const assets = {
fetch: async (request: Request): Promise<Response> => {
const path = new URL(request.url).pathname;
fetched.push(path);
return path === '/docs/readme.json'
? new Response('{"static":"docs"}', {
headers: { 'Content-Type': 'application/json' },
})
: new Response('Not Found', { status: 404 });
},
};
const response = await app.request('https://app.test/docs/readme.json', {}, { ASSETS: assets });
expect(response.status).toBe(404);
// The loader's `c.notFound()` decides the response, never the asset's bytes.
expect(fetched).not.toContain('/docs/readme.json');
expect(rendered).toEqual([]);
expect(await response.text()).not.toContain('static');
});
});

describe('boundary recovery failures', () => {
Expand Down
Loading