mirror of
https://github.com/cloudflare/vinext.git
synced 2026-09-14 19:04:59 +08:00
cda19e1c58
* fix(app-router): preserve recent segment state with Activity BFCache Fresh App Router navigations were reusing the active React tree when moving between dynamic segment values. That leaked client state into a newly entered segment and made the upstream back-forward-cache suite fail before it even reached browser traversal assertions. The root cause was that vinext had history-entry bfcacheId plumbing but no separate segment state-key cache. Next.js treats those identities separately: render state is keyed by segment identity/pathname, while useRouter().bfcacheId identifies a concrete history entry. Add state-key maps for app router slots, render retained entries through React.Activity when cacheComponents is enabled, keep the active one-entry keyed reset path otherwise, and port focused Next.js regression coverage for the three-entry BFCache behavior. * fix(bfcache): store stateKeyMap in retained slot entries and re-provide on render Review feedback requested two changes: 1. Add stateKeyMap to BfcacheSlotEntry so each retained BFCache entry carries the state-key map that belonged to it when active, rather than borrowing the current navigation's map. This prevents nested hidden entries from being rendered with old elements but new pathname-derived state keys — an identity corruption bug that upstream Next.js avoids by rendering each retained entry from its own state. 2. Add a nested dynamic regression test: /nested/[section]/item/[id] with client counters in both the [section] layout and [id] page. The existing flat /page/[n] tests do not exercise nested retained-entry identity, which is exactly where the missing state-key-map bug lives. Changes: - BfcacheSlotEntry gains stateKeyMap?: Readonly<Record<string, string>> - updateBfcacheSlotEntries accepts and stores an optional stateKeyMap argument - BfcacheSlotBoundary stores the current stateKeyMap alongside elements when caching the active entry - Both the Activity visible/hidden path and the non-cacheComponents single-entry path now wrap rendered entries in BfcacheStateKeyMapContext.Provider using the entry's own stateKeyMap (falling back to current map for forward compatibility) - New e2e test verifies nested layout + page counter preservation across segment navigations * refactor(bfcache): extract shared provider stack into BfcacheEntryProviders BfcacheSlotBoundary rendered the BfcacheStateKeyMapContext / ElementsContext / SegmentContext provider stack in two places: the one-entry keyed reset path and the per-entry Activity retention list. The two stacks were identical except for where the React key sat, so the retained-entry bookkeeping and its render shape were tangled together and harder to audit than needed. Extract BfcacheEntryProviders as a pure presentational helper and render it from both paths. The keyed-reset path keeps its remount semantics: the key now sits on the BfcacheEntryProviders element, so a fresh active stateKey still remounts the whole provider subtree. Hook ordering is unchanged. All hooks stay above the early returns in BfcacheSlotBoundary, so the boundary still satisfies the Rules of Hooks across the activeStateKey undefined-to-defined transition. Covered by the slot BFCache entry-state suite in tests/shims.test.ts. * test(bfcache): isolate cacheComponents BFCache coverage in a dedicated fixture The back/forward-cache e2e suite ran against the shared app-basic fixture with cacheComponents: true. app-basic backs the single app-router Playwright server that every app-router spec uses, so enabling cacheComponents globally changed a core DOM invariant for unrelated tests: inactive route trees stay mounted as hidden Activity DOM. The contamination already leaked a :visible workaround into the interception-modal bfcacheId spec, which had nothing to do with Activity. cacheComponents is an opt-in semantic mode, not default app-router behaviour, so it does not belong on the shared baseline fixture. Move the BFCache routes into a dedicated tests/fixtures/app-bfcache fixture with cacheComponents: true, served by a new app-router-bfcache Playwright project on port 4183, and run the back-forward-cache spec there against the project baseURL. The :visible locators stay in that spec, where duplicate hidden DOM is the expected contract. Remove cacheComponents and the BFCache routes from app-basic so the shared fixture models default behaviour again, and revert the :visible workaround in use-router-bfcache-id.spec.ts now that the modal route no longer retains hidden DOM. Fix the nested item page import while moving it: nested/[section]/item/[id]/ page.tsx imported ../counter, but the counter lives two levels up at nested/[section]/counter.tsx, so it must be ../../counter. Validation: PLAYWRIGHT_PROJECT=app-router-bfcache (5 passed) and the full use-router-bfcache-id spec under app-router (11 passed), plus the slot BFCache unit suite (1172 passed) and vp check (formatting + lint + types clean). * ci: run the app-router-bfcache e2e project in the matrix The dedicated app-router-bfcache Playwright project was added to playwright.config.ts but not to the CI E2E matrix, so the back/forward-cache specs never ran in CI. Add it to the matrix project list so the BFCache suite runs on every push. It uses the default chromium browser, so the existing setup and browser-cache steps apply unchanged. * fix(bfcache): keep persisted slots mounted when cacheComponents is off Without cacheComponents there is no Activity retention, yet BfcacheSlotBoundary still keyed the active entry by its segment stateKey. That stateKey tracks the pathname (createBfcacheSegmentIdentity), so any slot whose identity moves with the URL (shared layouts, interception source slots) was remounted on navigation, discarding client state that survives a normal route change. The baseline router reconciles these slots in place. This regressed seven existing app-router e2e tests once cacheComponents was no longer masking it on the shared fixture: interception source-context and modal preservation in advanced.spec.ts, and layout-persistence.spec.ts dynamic-segment layout counter survival. Fresh-entry reset is driven by userland bfcacheId keying in the fixtures, not by remounting the slot subtree, so the keying was pure overreach in the non-cacheComponents path. Render the single active entry unkeyed when cacheComponents is off so the boundary reconciles in place like the baseline. The keyed Activity retention path is unchanged for cacheComponents. Validation: full app-router project 436 passed / 0 failed (the seven regressions now pass); use-router-bfcache-id 11 passed (fresh-push reset intact); app-bfcache 5 passed (Activity retention intact); shims unit suite 1024 passed. * docs(test): point bfcacheId spec comment at the app-router-bfcache project The header noted that Activity-backed preservation is covered in back-forward-cache.spec.ts, but that spec moved to the dedicated app-bfcache fixture under the app-router-bfcache project. Name the project and path so the cross-reference stays accurate. * docs: align cacheComponents comment with unkeyed active-segment behavior * test(bfcache): assert fresh bfcacheId after Activity-restored return * style: collapse locator chains per oxfmt * refactor(bfcache): split slot entry order from snapshots * fix(bfcache): keep non-cacheComponents slot path baseline * fix(bfcache): use string cacheComponents define * test: remove external fetch from revalidate tag fixture * fix(bfcache): harden Activity state key retention * docs(bfcache): document cacheComponents Activity caveats * fix(bfcache): preserve navigation context for fallback SSR Fallback boundary rendering can outlive the original request-scoped navigation context. That made app SSR fail fast with a missing navigation context when loading-boundary digest routes rendered their HTTP fallback shell. The SSR boundary contract still requires a navigation context for real request renders, but boundary renderers now synthesize the same typed shape from the request URL and matched params when request scope has already been cleared. * refactor(bfcache): normalize pathname in state-key map, document invariant callers Moves hydration-pathname normalization into createBfcacheSegmentStateKeyMap so SSR and client always produce byte-identical Activity keys. Documents the requireNavigationContext guaranteeing callers per review feedback. * fix(bfcache): tolerate malformed state-key pathnames * docs(bfcache): document known Next.js divergence and dead-branch contract * chore(deps): update lockfile for vite 0.1.24 * fix(app-router): preserve encoded delimiters in bfcache keys * docs(bfcache): track router-owned retention follow-up * chore: retrigger ci * fix(app-router): preserve redirect bridge fallback
625 lines
20 KiB
TypeScript
625 lines
20 KiB
TypeScript
import { describe, expect, it, vi } from "vite-plus/test";
|
|
import React from "react";
|
|
import ReactDOMServer from "react-dom/server";
|
|
import {
|
|
renderAppPageErrorBoundary,
|
|
renderAppPageHttpAccessFallback,
|
|
} from "../packages/vinext/src/server/app-page-boundary-render.js";
|
|
import type { AppElements } from "../packages/vinext/src/server/app-elements.js";
|
|
import type { MetadataFileRoute } from "../packages/vinext/src/server/metadata-routes.js";
|
|
import { VINEXT_RSC_VARY_HEADER } from "../packages/vinext/src/server/app-rsc-cache-busting.js";
|
|
|
|
function createStreamFromMarkup(markup: string): ReadableStream<Uint8Array> {
|
|
return new ReadableStream({
|
|
start(controller) {
|
|
controller.enqueue(new TextEncoder().encode(markup));
|
|
controller.close();
|
|
},
|
|
});
|
|
}
|
|
|
|
function renderElementToStream(element: React.ReactNode | AppElements): ReadableStream<Uint8Array> {
|
|
if (element !== null && typeof element === "object" && !React.isValidElement(element)) {
|
|
// Flat map payload — extract the route element and render it to HTML
|
|
// (mirrors what the real SSR entry does after deserializing the Flight stream)
|
|
const record = element as Record<string, unknown>;
|
|
const routeId = record.__route;
|
|
if (typeof routeId === "string" && React.isValidElement(record[routeId])) {
|
|
return createStreamFromMarkup(
|
|
ReactDOMServer.renderToStaticMarkup(record[routeId] as React.ReactNode),
|
|
);
|
|
}
|
|
return createStreamFromMarkup(JSON.stringify(element));
|
|
}
|
|
return createStreamFromMarkup(ReactDOMServer.renderToStaticMarkup(element));
|
|
}
|
|
|
|
function renderWirePayloadToStream(payload: unknown): ReadableStream<Uint8Array> {
|
|
return createStreamFromMarkup(JSON.stringify(payload));
|
|
}
|
|
|
|
function createCommonOptions() {
|
|
const clearRequestContext = vi.fn();
|
|
const loadSsrHandler = vi.fn(async () => ({
|
|
async handleSsr(rscStream: ReadableStream<Uint8Array>) {
|
|
return rscStream;
|
|
},
|
|
}));
|
|
|
|
return {
|
|
buildFontLinkHeader(preloads: readonly { href: string; type: string }[] | null | undefined) {
|
|
if (!preloads || preloads.length === 0) {
|
|
return "";
|
|
}
|
|
return preloads.map((preload) => `<${preload.href}>; rel=preload`).join(", ");
|
|
},
|
|
clearRequestContext,
|
|
createRscOnErrorHandler() {
|
|
return () => null;
|
|
},
|
|
getFontLinks() {
|
|
return ["/styles.css"];
|
|
},
|
|
getFontPreloads() {
|
|
return [{ href: "/font.woff2", type: "font/woff2" }];
|
|
},
|
|
getFontStyles() {
|
|
return [".font { font-family: Test; }"];
|
|
},
|
|
getNavigationContext() {
|
|
return { pathname: "/posts/missing", searchParams: new URLSearchParams(), params: {} };
|
|
},
|
|
isRscRequest: false,
|
|
loadSsrHandler,
|
|
makeThenableParams<T>(params: T) {
|
|
return params;
|
|
},
|
|
middlewareContext: {
|
|
headers: null,
|
|
status: null,
|
|
},
|
|
metadataRoutes: [],
|
|
renderToReadableStream: renderElementToStream,
|
|
requestUrl: "https://example.com/posts/missing",
|
|
resolveChildSegments() {
|
|
return [];
|
|
},
|
|
rootLayouts: EMPTY_ROOT_LAYOUTS,
|
|
};
|
|
}
|
|
|
|
function createMiddlewareContext() {
|
|
const headers = new Headers();
|
|
headers.set("x-middleware-security", "present");
|
|
headers.append("set-cookie", "session=rotated; Path=/; HttpOnly");
|
|
headers.set("vary", "x-auth-state");
|
|
|
|
return {
|
|
headers,
|
|
status: 299,
|
|
};
|
|
}
|
|
|
|
function RootLayout({
|
|
children,
|
|
params,
|
|
}: {
|
|
children: React.ReactNode;
|
|
params: { slug?: string };
|
|
}) {
|
|
return React.createElement("div", { "data-layout": "root", "data-slug": params.slug }, children);
|
|
}
|
|
|
|
function LeafLayout({
|
|
children,
|
|
params,
|
|
}: {
|
|
children: React.ReactNode;
|
|
params: { slug?: string };
|
|
}) {
|
|
return React.createElement(
|
|
"section",
|
|
{ "data-layout": "leaf", "data-slug": params.slug },
|
|
children,
|
|
);
|
|
}
|
|
|
|
function NotFoundBoundary() {
|
|
return React.createElement("p", { "data-boundary": "not-found" }, "Missing page");
|
|
}
|
|
|
|
function RouteErrorBoundary({ error }: { error: Error }) {
|
|
return React.createElement("p", { "data-boundary": "route-error" }, `route:${error.message}`);
|
|
}
|
|
|
|
function GlobalErrorBoundary({ error }: { error: Error }) {
|
|
return React.createElement("p", { "data-boundary": "global-error" }, `global:${error.message}`);
|
|
}
|
|
|
|
type TestModule = {
|
|
default: React.ComponentType<any>;
|
|
metadata?: { description?: string; title?: string };
|
|
viewport?: { themeColor: string };
|
|
};
|
|
|
|
const rootLayoutModule = {
|
|
default: RootLayout,
|
|
metadata: { description: "Root layout description" },
|
|
viewport: { themeColor: "#111111" },
|
|
} satisfies TestModule;
|
|
|
|
const leafLayoutModule = {
|
|
default: LeafLayout,
|
|
} satisfies TestModule;
|
|
|
|
const notFoundModule = {
|
|
default: NotFoundBoundary,
|
|
} satisfies TestModule;
|
|
|
|
const notFoundModuleWithMetadata = {
|
|
default: NotFoundBoundary,
|
|
metadata: { title: "notfound title" },
|
|
} satisfies TestModule;
|
|
|
|
const routeErrorModule = {
|
|
default: RouteErrorBoundary,
|
|
} satisfies TestModule;
|
|
|
|
const globalErrorModule = {
|
|
default: GlobalErrorBoundary,
|
|
} satisfies TestModule;
|
|
|
|
const EMPTY_ROOT_LAYOUTS: readonly TestModule[] = [];
|
|
|
|
describe("app page boundary render helpers", () => {
|
|
it("returns null when no HTTP access fallback boundary exists", async () => {
|
|
const common = createCommonOptions();
|
|
|
|
const response = await renderAppPageHttpAccessFallback<TestModule>({
|
|
...common,
|
|
matchedParams: { slug: "missing" },
|
|
route: {
|
|
pattern: "/posts/[slug]",
|
|
params: { slug: "missing" },
|
|
},
|
|
statusCode: 404,
|
|
});
|
|
|
|
expect(response).toBeNull();
|
|
expect(common.loadSsrHandler).not.toHaveBeenCalled();
|
|
expect(common.clearRequestContext).not.toHaveBeenCalled();
|
|
});
|
|
|
|
it("renders HTTP access fallbacks with layout metadata and wrapped HTML", async () => {
|
|
const common = createCommonOptions();
|
|
|
|
const response = await renderAppPageHttpAccessFallback<TestModule>({
|
|
...common,
|
|
matchedParams: { slug: "missing" },
|
|
rootLayouts: [rootLayoutModule],
|
|
route: {
|
|
layoutTreePositions: [0, 1],
|
|
layouts: [rootLayoutModule, leafLayoutModule],
|
|
notFound: notFoundModule,
|
|
params: { slug: "missing" },
|
|
pattern: "/posts/[slug]",
|
|
routeSegments: ["posts", "[slug]"],
|
|
},
|
|
statusCode: 404,
|
|
});
|
|
|
|
expect(common.loadSsrHandler).toHaveBeenCalledTimes(1);
|
|
expect(response?.status).toBe(404);
|
|
expect(response?.headers.get("link")).toContain("/font.woff2");
|
|
|
|
const html = await response?.text();
|
|
expect(common.clearRequestContext).toHaveBeenCalledTimes(1);
|
|
expect(html).toContain('data-layout="root"');
|
|
expect(html).toContain('data-layout="leaf"');
|
|
expect(html).toContain('data-boundary="not-found"');
|
|
expect(html).toContain('content="Root layout description"');
|
|
expect(html).toContain('name="viewport"');
|
|
expect(html).toContain('name="theme-color" content="#111111"');
|
|
expect(html).toContain('name="robots"');
|
|
expect(html).toContain('content="noindex"');
|
|
});
|
|
|
|
it("renders not-found boundary metadata exactly once for HTTP access fallbacks", async () => {
|
|
// Ported from Next.js:
|
|
// test/e2e/app-dir/metadata-streaming/metadata-streaming.test.ts
|
|
// "should not duplicate metadata with navigation API"
|
|
//
|
|
// The upstream fixture calls notFound() from generateMetadata() and expects
|
|
// the rendered not-found boundary's metadata (`not-found.tsx` static
|
|
// metadata) to produce a single title in the document.
|
|
const common = createCommonOptions();
|
|
|
|
const response = await renderAppPageHttpAccessFallback<TestModule>({
|
|
...common,
|
|
matchedParams: { slug: "missing" },
|
|
rootLayouts: [rootLayoutModule],
|
|
route: {
|
|
layoutTreePositions: [0],
|
|
layouts: [rootLayoutModule],
|
|
notFound: notFoundModuleWithMetadata,
|
|
params: { slug: "missing" },
|
|
pattern: "/posts/[slug]",
|
|
routeSegments: ["posts", "[slug]"],
|
|
},
|
|
statusCode: 404,
|
|
});
|
|
|
|
expect(response?.status).toBe(404);
|
|
|
|
const html = await response?.text();
|
|
expect(html?.match(/<title>/g) ?? []).toHaveLength(1);
|
|
expect(html).toContain("<title>notfound title</title>");
|
|
});
|
|
|
|
it("does not inject child route file metadata into layout-level HTTP access fallbacks", async () => {
|
|
const common = createCommonOptions();
|
|
const metadataRoutes: MetadataFileRoute[] = [
|
|
{
|
|
type: "opengraph-image",
|
|
isDynamic: false,
|
|
filePath: "/tmp/app/posts/[slug]/opengraph-image.png",
|
|
routePrefix: "/posts/[slug]",
|
|
routeSegments: ["posts", "[slug]"],
|
|
servedUrl: "/posts/-/opengraph-image.png",
|
|
contentType: "image/png",
|
|
headData: {
|
|
kind: "openGraph",
|
|
href: "/posts/-/opengraph-image.png?hash",
|
|
type: "image/png",
|
|
width: 1200,
|
|
height: 630,
|
|
},
|
|
},
|
|
];
|
|
|
|
const response = await renderAppPageHttpAccessFallback<TestModule>({
|
|
...common,
|
|
layoutModules: [rootLayoutModule],
|
|
matchedParams: { slug: "missing" },
|
|
metadataRoutes,
|
|
route: {
|
|
layoutTreePositions: [0, 1],
|
|
layouts: [rootLayoutModule, leafLayoutModule],
|
|
notFound: notFoundModule,
|
|
params: { slug: "missing" },
|
|
pattern: "/posts/[slug]",
|
|
routeSegments: ["posts", "[slug]"],
|
|
},
|
|
statusCode: 404,
|
|
});
|
|
|
|
expect(response?.status).toBe(404);
|
|
|
|
const html = await response?.text();
|
|
expect(html).toContain('content="Root layout description"');
|
|
expect(html).not.toContain("opengraph-image");
|
|
});
|
|
|
|
it("preserves middleware headers on HTTP access fallback HTML responses", async () => {
|
|
const common = createCommonOptions();
|
|
|
|
const response = await renderAppPageHttpAccessFallback<TestModule>({
|
|
...common,
|
|
matchedParams: { slug: "missing" },
|
|
middlewareContext: createMiddlewareContext(),
|
|
route: {
|
|
layouts: [rootLayoutModule],
|
|
notFound: notFoundModule,
|
|
params: { slug: "missing" },
|
|
pattern: "/posts/[slug]",
|
|
},
|
|
statusCode: 404,
|
|
});
|
|
|
|
expect(response?.status).toBe(404);
|
|
expect(response?.headers.get("x-middleware-security")).toBe("present");
|
|
expect(response?.headers.get("vary")).toBe(`${VINEXT_RSC_VARY_HEADER}, x-auth-state`);
|
|
expect(response?.headers.getSetCookie()).toContain("session=rotated; Path=/; HttpOnly");
|
|
});
|
|
|
|
it("renders HTTP access fallback RSC responses as flat payloads", async () => {
|
|
const common = createCommonOptions();
|
|
|
|
const response = await renderAppPageHttpAccessFallback<TestModule>({
|
|
...common,
|
|
isRscRequest: true,
|
|
matchedParams: { slug: "missing" },
|
|
renderToReadableStream: renderWirePayloadToStream,
|
|
rootLayouts: [rootLayoutModule],
|
|
route: {
|
|
layoutTreePositions: [0, 1],
|
|
layouts: [rootLayoutModule, leafLayoutModule],
|
|
notFound: notFoundModule,
|
|
params: { slug: "missing" },
|
|
pattern: "/posts/[slug]",
|
|
routeSegments: ["posts", "[slug]"],
|
|
},
|
|
statusCode: 404,
|
|
});
|
|
|
|
expect(response?.status).toBe(404);
|
|
expect(response?.headers.get("Content-Type")).toBe("text/x-component");
|
|
|
|
const payload = JSON.parse((await response?.text()) ?? "{}") as Record<string, unknown>;
|
|
expect(payload.__route).toBe("route:/posts/missing");
|
|
expect(payload.__layoutIds).toEqual(["layout:/", "layout:/posts"]);
|
|
expect(payload.__rootLayout).toBe("/");
|
|
expect(payload["route:/posts/missing"]).toBeTruthy();
|
|
});
|
|
|
|
it("derives HTTP access fallback layout metadata from the rendered layout subset", async () => {
|
|
const common = createCommonOptions();
|
|
|
|
const response = await renderAppPageHttpAccessFallback<TestModule>({
|
|
...common,
|
|
isRscRequest: true,
|
|
layoutModules: [rootLayoutModule],
|
|
matchedParams: { slug: "missing" },
|
|
renderToReadableStream: renderWirePayloadToStream,
|
|
route: {
|
|
layoutTreePositions: [0, 1],
|
|
layouts: [rootLayoutModule, leafLayoutModule],
|
|
notFound: notFoundModule,
|
|
params: { slug: "missing" },
|
|
pattern: "/posts/[slug]",
|
|
routeSegments: ["posts", "[slug]"],
|
|
},
|
|
statusCode: 404,
|
|
});
|
|
|
|
expect(response?.status).toBe(404);
|
|
|
|
const payload = JSON.parse((await response?.text()) ?? "{}") as Record<string, unknown>;
|
|
expect(payload.__layoutIds).toEqual(["layout:/"]);
|
|
expect(payload.__rootLayout).toBe("/");
|
|
expect(payload["route:/posts/missing"]).toBeTruthy();
|
|
});
|
|
|
|
it("uses unknown root metadata when no route layout is rendered for an HTTP access fallback", async () => {
|
|
const common = createCommonOptions();
|
|
|
|
const response = await renderAppPageHttpAccessFallback<TestModule>({
|
|
...common,
|
|
isRscRequest: true,
|
|
layoutModules: [],
|
|
matchedParams: { slug: "missing" },
|
|
renderToReadableStream: renderWirePayloadToStream,
|
|
route: {
|
|
layoutTreePositions: [0, 1],
|
|
layouts: [rootLayoutModule, leafLayoutModule],
|
|
notFound: notFoundModule,
|
|
params: { slug: "missing" },
|
|
pattern: "/posts/[slug]",
|
|
routeSegments: ["posts", "[slug]"],
|
|
},
|
|
statusCode: 404,
|
|
});
|
|
|
|
expect(response?.status).toBe(404);
|
|
|
|
const payload = JSON.parse((await response?.text()) ?? "{}") as Record<string, unknown>;
|
|
expect(payload.__layoutIds).toEqual([]);
|
|
expect(payload.__rootLayout).toBeNull();
|
|
expect(payload["route:/posts/missing"]).toBeTruthy();
|
|
});
|
|
|
|
it("preserves middleware headers on HTTP access fallback RSC responses", async () => {
|
|
const common = createCommonOptions();
|
|
|
|
const response = await renderAppPageHttpAccessFallback<TestModule>({
|
|
...common,
|
|
isRscRequest: true,
|
|
matchedParams: { slug: "missing" },
|
|
middlewareContext: createMiddlewareContext(),
|
|
renderToReadableStream: renderWirePayloadToStream,
|
|
route: {
|
|
notFound: notFoundModule,
|
|
params: { slug: "missing" },
|
|
pattern: "/posts/[slug]",
|
|
},
|
|
statusCode: 404,
|
|
});
|
|
|
|
expect(response?.status).toBe(404);
|
|
expect(response?.headers.get("x-middleware-security")).toBe("present");
|
|
expect(response?.headers.get("vary")).toBe(`${VINEXT_RSC_VARY_HEADER}, x-auth-state`);
|
|
expect(response?.headers.getSetCookie()).toContain("session=rotated; Path=/; HttpOnly");
|
|
});
|
|
|
|
it("uses null root layout metadata when a boundary payload has no route context", async () => {
|
|
const common = createCommonOptions();
|
|
|
|
const response = await renderAppPageHttpAccessFallback<TestModule>({
|
|
...common,
|
|
boundaryComponent: NotFoundBoundary,
|
|
isRscRequest: true,
|
|
matchedParams: { slug: "missing" },
|
|
renderToReadableStream: renderWirePayloadToStream,
|
|
rootLayouts: [rootLayoutModule],
|
|
route: null,
|
|
statusCode: 404,
|
|
});
|
|
|
|
expect(response?.status).toBe(404);
|
|
|
|
const payload = JSON.parse((await response?.text()) ?? "{}") as Record<string, unknown>;
|
|
expect(payload.__route).toBe("route:/posts/missing");
|
|
expect(payload.__layoutIds).toEqual([]);
|
|
expect(payload.__rootLayout).toBeNull();
|
|
expect(payload["route:/posts/missing"]).toBeTruthy();
|
|
});
|
|
|
|
it("renders route error boundaries with sanitized errors inside layouts", async () => {
|
|
const common = createCommonOptions();
|
|
const sanitizeErrorForClient = vi.fn((error: Error) => new Error(`safe:${error.message}`));
|
|
|
|
const response = await renderAppPageErrorBoundary<TestModule>({
|
|
...common,
|
|
error: new Error("secret"),
|
|
matchedParams: { slug: "post" },
|
|
route: {
|
|
error: routeErrorModule,
|
|
layouts: [rootLayoutModule],
|
|
params: { slug: "post" },
|
|
pattern: "/posts/[slug]",
|
|
},
|
|
sanitizeErrorForClient,
|
|
});
|
|
|
|
expect(response?.status).toBe(200);
|
|
expect(sanitizeErrorForClient).toHaveBeenCalledTimes(1);
|
|
|
|
const html = await response?.text();
|
|
expect(common.clearRequestContext).toHaveBeenCalledTimes(1);
|
|
expect(html).toContain('data-layout="root"');
|
|
expect(html).toContain('data-boundary="route-error"');
|
|
expect(html).toContain("route:safe:secret");
|
|
});
|
|
|
|
it("preserves middleware headers on error boundary responses", async () => {
|
|
const common = createCommonOptions();
|
|
|
|
const response = await renderAppPageErrorBoundary<TestModule>({
|
|
...common,
|
|
error: new Error("secret"),
|
|
matchedParams: { slug: "post" },
|
|
middlewareContext: createMiddlewareContext(),
|
|
route: {
|
|
error: routeErrorModule,
|
|
params: { slug: "post" },
|
|
pattern: "/posts/[slug]",
|
|
},
|
|
sanitizeErrorForClient(error: Error) {
|
|
return error;
|
|
},
|
|
});
|
|
|
|
expect(response?.status).toBe(200);
|
|
expect(response?.headers.get("x-middleware-security")).toBe("present");
|
|
expect(response?.headers.get("vary")).toBe(`${VINEXT_RSC_VARY_HEADER}, x-auth-state`);
|
|
expect(response?.headers.getSetCookie()).toContain("session=rotated; Path=/; HttpOnly");
|
|
});
|
|
|
|
it("renders error boundaries when dynamic file metadata resolution fails", async () => {
|
|
const error = new Error("metadata boom");
|
|
const consoleError = vi.spyOn(console, "error").mockImplementation(() => {});
|
|
const common = createCommonOptions();
|
|
const metadataRoutes: MetadataFileRoute[] = [
|
|
{
|
|
type: "opengraph-image",
|
|
isDynamic: true,
|
|
filePath: "/tmp/app/posts/[slug]/opengraph-image.tsx",
|
|
routePrefix: "/posts/[slug]",
|
|
routeSegments: ["posts", "[slug]"],
|
|
servedUrl: "/posts/[slug]/opengraph-image",
|
|
contentType: "image/png",
|
|
contentHash: "hash",
|
|
module: {
|
|
generateImageMetadata() {
|
|
throw error;
|
|
},
|
|
},
|
|
},
|
|
];
|
|
|
|
try {
|
|
const response = await renderAppPageErrorBoundary<TestModule>({
|
|
...common,
|
|
error: new Error("secret"),
|
|
matchedParams: { slug: "post" },
|
|
metadataRoutes,
|
|
route: {
|
|
error: routeErrorModule,
|
|
layoutTreePositions: [0],
|
|
layouts: [rootLayoutModule],
|
|
params: { slug: "post" },
|
|
pattern: "/posts/[slug]",
|
|
routeSegments: ["posts", "[slug]"],
|
|
},
|
|
sanitizeErrorForClient(error: Error) {
|
|
return error;
|
|
},
|
|
});
|
|
|
|
expect(response?.status).toBe(200);
|
|
expect(consoleError).toHaveBeenCalledWith(
|
|
"[vinext] File-based metadata resolution failed while rendering error boundary for /posts/[slug]:",
|
|
error,
|
|
);
|
|
|
|
const html = await response?.text();
|
|
expect(html).toContain('data-boundary="route-error"');
|
|
expect(html).toContain("route:secret");
|
|
expect(html).toContain('content="Root layout description"');
|
|
expect(html).not.toContain("opengraph-image");
|
|
} finally {
|
|
consoleError.mockRestore();
|
|
}
|
|
});
|
|
|
|
it("renders error boundary RSC responses as flat payloads", async () => {
|
|
const common = createCommonOptions();
|
|
|
|
const response = await renderAppPageErrorBoundary<TestModule>({
|
|
...common,
|
|
error: new Error("secret"),
|
|
isRscRequest: true,
|
|
matchedParams: { slug: "missing" },
|
|
renderToReadableStream: renderWirePayloadToStream,
|
|
route: {
|
|
error: routeErrorModule,
|
|
layoutTreePositions: [0],
|
|
layouts: [rootLayoutModule],
|
|
params: { slug: "missing" },
|
|
pattern: "/posts/[slug]",
|
|
routeSegments: ["posts", "[slug]"],
|
|
},
|
|
sanitizeErrorForClient(error: Error) {
|
|
return new Error(`safe:${error.message}`);
|
|
},
|
|
});
|
|
|
|
expect(response?.status).toBe(200);
|
|
expect(response?.headers.get("Content-Type")).toBe("text/x-component");
|
|
|
|
const payload = JSON.parse((await response?.text()) ?? "{}") as Record<string, unknown>;
|
|
expect(payload.__route).toBe("route:/posts/missing");
|
|
expect(payload.__layoutIds).toEqual(["layout:/"]);
|
|
expect(payload.__rootLayout).toBe("/");
|
|
expect(payload["route:/posts/missing"]).toBeTruthy();
|
|
});
|
|
|
|
it("renders global-error boundaries without layout wrapping", async () => {
|
|
const common = createCommonOptions();
|
|
|
|
const response = await renderAppPageErrorBoundary<TestModule>({
|
|
...common,
|
|
error: new Error("boom"),
|
|
globalErrorModule,
|
|
matchedParams: { slug: "post" },
|
|
route: {
|
|
layouts: [rootLayoutModule],
|
|
params: { slug: "post" },
|
|
pattern: "/posts/[slug]",
|
|
},
|
|
sanitizeErrorForClient(error: Error) {
|
|
return error;
|
|
},
|
|
});
|
|
|
|
expect(response?.status).toBe(200);
|
|
|
|
const html = await response?.text();
|
|
expect(html).toContain('data-boundary="global-error"');
|
|
expect(html).toContain("global:boom");
|
|
expect(html).not.toContain('data-layout="root"');
|
|
expect(html).not.toContain("Root layout description");
|
|
expect(html).not.toContain('name="viewport"');
|
|
});
|
|
});
|