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
115 changes: 115 additions & 0 deletions packages/vinext/src/build/layout-classification.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,115 @@
/**
* Layout classification — determines whether each layout in an App Router
* route tree is static or dynamic via two complementary detection layers:
*
* Layer 1: Segment config (`export const dynamic`, `export const revalidate`)
* Layer 2: Module graph traversal (checks for transitive dynamic shim imports)
*
* Layer 3 (probe-based runtime detection) is handled separately in
* `app-page-execution.ts` at request time.
*/

import { classifyLayoutSegmentConfig } from "./report.js";
import { createAppPageTreePath } from "../server/app-page-route-wiring.js";

export type ModuleGraphClassification = "static" | "needs-probe";
export type LayoutClassificationResult = "static" | "dynamic" | "needs-probe";

export type ModuleInfoProvider = {
getModuleInfo(id: string): {
importedIds: string[];
dynamicImportedIds: string[];
} | null;
};

type LayoutEntry = {
/** Rollup/Vite module ID for the layout file. */
moduleId: string;
/** Directory depth from the app root, used to build the stable layout ID. */
treePosition: number;
/** Segment config source code extracted at build time, or null when absent. */
segmentConfig?: { code: string } | null;
};

type RouteForClassification = {
layouts: readonly LayoutEntry[];
routeSegments: string[];
};

/**
* BFS traversal of a layout's dependency tree. If any transitive import
* resolves to a dynamic shim path (headers, cache, server), the layout
* cannot be proven static at build time and needs a runtime probe.
*/
export function classifyLayoutByModuleGraph(
layoutModuleId: string,
dynamicShimPaths: ReadonlySet<string>,
moduleInfo: ModuleInfoProvider,
): ModuleGraphClassification {
const visited = new Set<string>();
const queue: string[] = [layoutModuleId];
let head = 0;

while (head < queue.length) {
const currentId = queue[head++]!;

if (visited.has(currentId)) continue;
visited.add(currentId);

if (dynamicShimPaths.has(currentId)) return "needs-probe";

const info = moduleInfo.getModuleInfo(currentId);
if (!info) continue;

for (const importedId of info.importedIds) {
if (!visited.has(importedId)) queue.push(importedId);
}
for (const dynamicId of info.dynamicImportedIds) {
if (!visited.has(dynamicId)) queue.push(dynamicId);
}
}

return "static";
}

/**
* Classifies all layouts across all routes using a two-layer strategy:
*
* 1. Segment config (Layer 1) — short-circuits to "static" or "dynamic"
* 2. Module graph (Layer 2) — BFS for dynamic shim imports → "static" or "needs-probe"
*
* Shared layouts (same file appearing in multiple routes) are classified once
* and deduplicated by layout ID.
*/
export function classifyAllRouteLayouts(
routes: readonly RouteForClassification[],
dynamicShimPaths: ReadonlySet<string>,
moduleInfo: ModuleInfoProvider,
): Map<string, LayoutClassificationResult> {
const result = new Map<string, LayoutClassificationResult>();

for (const route of routes) {
for (const layout of route.layouts) {
const layoutId = `layout:${createAppPageTreePath(route.routeSegments, layout.treePosition)}`;

if (result.has(layoutId)) continue;

// Layer 1: segment config
if (layout.segmentConfig) {
const configResult = classifyLayoutSegmentConfig(layout.segmentConfig.code);
if (configResult !== null) {
result.set(layoutId, configResult);
continue;
}
}

// Layer 2: module graph
result.set(
layoutId,
classifyLayoutByModuleGraph(layout.moduleId, dynamicShimPaths, moduleInfo),
);
}
}

return result;
}
31 changes: 31 additions & 0 deletions packages/vinext/src/build/report.ts
Original file line number Diff line number Diff line change
Expand Up @@ -607,6 +607,37 @@ function findMatchingToken(
return -1;
}

// ─── Layout segment config classification ────────────────────────────────────

/**
* Classification result for layout segment config analysis.
* "static" means the layout is confirmed static via segment config.
* "dynamic" means the layout is confirmed dynamic via segment config.
*/
export type LayoutClassification = "static" | "dynamic";

/**
* Classifies a layout file by its segment config exports (`dynamic`, `revalidate`).
*
* Returns `"static"` or `"dynamic"` when the config is decisive, or `null`
* when no segment config is present (deferring to module graph analysis).
*
* Unlike page classification, positive `revalidate` values are not meaningful
* for layout skip decisions — ISR is a page-level concept. Only the extremes
* (`revalidate = 0` → dynamic, `revalidate = Infinity` → static) are decisive.
*/
export function classifyLayoutSegmentConfig(code: string): LayoutClassification | null {
const dynamicValue = extractExportConstString(code, "dynamic");
if (dynamicValue === "force-dynamic") return "dynamic";
if (dynamicValue === "force-static" || dynamicValue === "error") return "static";

const revalidateValue = extractExportConstNumber(code, "revalidate");
if (revalidateValue === Infinity) return "static";
if (revalidateValue === 0) return "dynamic";

return null;
}

// ─── Route classification ─────────────────────────────────────────────────────

/**
Expand Down
7 changes: 7 additions & 0 deletions packages/vinext/src/server/app-browser-entry.ts
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,7 @@ import {
resolveVisitedResponseInterceptionContext,
type AppElements,
type AppWireElements,
type LayoutFlags,
} from "./app-elements.js";
import {
createHistoryStateWithPreviousNextUrl,
Expand Down Expand Up @@ -458,6 +459,7 @@ async function commitSameUrlNavigatePayload(
pending.action.renderId,
"navigate",
pending.interceptionContext,
pending.action.layoutFlags,
pending.previousNextUrl,
pending.routeId,
pending.rootLayoutTreePath,
Expand Down Expand Up @@ -491,6 +493,7 @@ function BrowserRoot({
const [treeState, dispatchTreeState] = useReducer(routerReducer, {
elements: resolvedElements,
interceptionContext: initialMetadata.interceptionContext,
layoutFlags: initialMetadata.layoutFlags,
navigationSnapshot: initialNavigationSnapshot,
previousNextUrl: null,
renderId: 0,
Expand Down Expand Up @@ -570,6 +573,7 @@ function dispatchBrowserTree(
renderId: number,
actionType: "navigate" | "replace" | "traverse",
interceptionContext: string | null,
layoutFlags: LayoutFlags,
previousNextUrl: string | null,
routeId: string,
rootLayoutTreePath: string | null,
Expand All @@ -581,6 +585,7 @@ function dispatchBrowserTree(
dispatch({
elements,
interceptionContext,
layoutFlags,
navigationSnapshot,
previousNextUrl,
renderId,
Expand Down Expand Up @@ -662,6 +667,7 @@ async function renderNavigationPayload(
renderId,
actionType,
pending.interceptionContext,
pending.action.layoutFlags,
pending.previousNextUrl,
pending.routeId,
pending.rootLayoutTreePath,
Expand Down Expand Up @@ -1146,6 +1152,7 @@ async function main(): Promise<void> {
pending.action.renderId,
"replace",
pending.interceptionContext,
pending.action.layoutFlags,
pending.previousNextUrl,
pending.routeId,
pending.rootLayoutTreePath,
Expand Down
7 changes: 6 additions & 1 deletion packages/vinext/src/server/app-browser-state.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { mergeElements } from "../shims/slot.js";
import { stripBasePath } from "../utils/base-path.js";
import { readAppElementsMetadata, type AppElements } from "./app-elements.js";
import { readAppElementsMetadata, type AppElements, type LayoutFlags } from "./app-elements.js";
import type { ClientNavigationRenderSnapshot } from "../shims/navigation.js";

const VINEXT_PREVIOUS_NEXT_URL_HISTORY_STATE_KEY = "__vinext_previousNextUrl";
Expand All @@ -12,6 +12,7 @@ type HistoryStateRecord = {
export type AppRouterState = {
elements: AppElements;
interceptionContext: string | null;
layoutFlags: LayoutFlags;
previousNextUrl: string | null;
renderId: number;
navigationSnapshot: ClientNavigationRenderSnapshot;
Expand All @@ -22,6 +23,7 @@ export type AppRouterState = {
export type AppRouterAction = {
elements: AppElements;
interceptionContext: string | null;
layoutFlags: LayoutFlags;
navigationSnapshot: ClientNavigationRenderSnapshot;
previousNextUrl: string | null;
renderId: number;
Expand Down Expand Up @@ -95,6 +97,7 @@ export function routerReducer(state: AppRouterState, action: AppRouterAction): A
return {
elements: mergeElements(state.elements, action.elements, action.type === "traverse"),
interceptionContext: action.interceptionContext,
layoutFlags: { ...state.layoutFlags, ...action.layoutFlags },
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Minor thought: the spread merge { ...state.layoutFlags, ...action.layoutFlags } means stale flags for layouts no longer in the current tree persist indefinitely (until a replace/hard navigation). This is harmless for the skip-header optimization (the consumer in PR 768 will only read flags for layouts actually in the current tree), but the state object grows monotonically across soft navigations. Not a practical concern for typical apps, but worth keeping in mind if layout flags ever carry more data.

navigationSnapshot: action.navigationSnapshot,
previousNextUrl: action.previousNextUrl,
renderId: action.renderId,
Expand All @@ -105,6 +108,7 @@ export function routerReducer(state: AppRouterState, action: AppRouterAction): A
return {
elements: action.elements,
interceptionContext: action.interceptionContext,
layoutFlags: action.layoutFlags,
navigationSnapshot: action.navigationSnapshot,
previousNextUrl: action.previousNextUrl,
renderId: action.renderId,
Expand Down Expand Up @@ -168,6 +172,7 @@ export async function createPendingNavigationCommit(options: {
action: {
elements,
interceptionContext: metadata.interceptionContext,
layoutFlags: metadata.layoutFlags,
navigationSnapshot: options.navigationSnapshot,
previousNextUrl,
renderId: options.renderId,
Expand Down
30 changes: 29 additions & 1 deletion packages/vinext/src/server/app-elements.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import type { ReactNode } from "react";
const APP_INTERCEPTION_SEPARATOR = "\0";

export const APP_INTERCEPTION_CONTEXT_KEY = "__interceptionContext";
export const APP_LAYOUT_FLAGS_KEY = "__layoutFlags";
export const APP_ROUTE_KEY = "__route";
export const APP_ROOT_LAYOUT_KEY = "__rootLayout";
export const APP_UNMATCHED_SLOT_WIRE_VALUE = "__VINEXT_UNMATCHED_SLOT__";
Expand All @@ -15,8 +16,12 @@ export type AppWireElementValue = ReactNode | string | null;
export type AppElements = Readonly<Record<string, AppElementValue>>;
export type AppWireElements = Readonly<Record<string, AppWireElementValue>>;

/** Per-layout static/dynamic flags propagated in the RSC payload. `"s"` = static, `"d"` = dynamic. */
export type LayoutFlags = Readonly<Record<string, "s" | "d">>;

export type AppElementsMetadata = {
interceptionContext: string | null;
layoutFlags: LayoutFlags;
routeId: string;
rootLayoutTreePath: string | null;
};
Expand Down Expand Up @@ -102,7 +107,27 @@ export function normalizeAppElements(elements: AppWireElements): AppElements {
return normalized;
}

export function readAppElementsMetadata(elements: AppElements): AppElementsMetadata {
function isLayoutFlagsRecord(value: unknown): value is LayoutFlags {
if (!value || typeof value !== "object" || Array.isArray(value)) return false;
for (const v of Object.values(value)) {
if (v !== "s" && v !== "d") return false;
}
return true;
}

function parseLayoutFlags(value: unknown): LayoutFlags {
if (isLayoutFlagsRecord(value)) return value;
return {};
}

/**
* Parses metadata from the wire payload. Accepts `Record<string, unknown>`
* because the RSC payload carries heterogeneous values (React elements,
* strings, and plain objects like layout flags) under the same record type.
*/
export function readAppElementsMetadata(
elements: Readonly<Record<string, unknown>>,
): AppElementsMetadata {
const routeId = elements[APP_ROUTE_KEY];
if (typeof routeId !== "string") {
throw new Error("[vinext] Missing __route string in App Router payload");
Expand All @@ -125,8 +150,11 @@ export function readAppElementsMetadata(elements: AppElements): AppElementsMetad
throw new Error("[vinext] Invalid __rootLayout in App Router payload: expected string or null");
}

const layoutFlags = parseLayoutFlags(elements[APP_LAYOUT_FLAGS_KEY]);

return {
interceptionContext: interceptionContext ?? null,
layoutFlags,
routeId,
rootLayoutTreePath,
};
Expand Down
Loading
Loading