From 34c7dad0c38da78d2c3395ad51c4a01d9e338c60 Mon Sep 17 00:00:00 2001 From: James Date: Thu, 26 Nov 2026 06:25:32 +0000 Subject: [PATCH 01/12] feat(instrumentation): pass a router transition start event with instrumentationClientRouterTransitionEvents --- packages/vinext/src/check.ts | 1 + .../client/instrumentation-client-state.ts | 63 ++++++- .../src/client/instrumentation-client.ts | 6 +- packages/vinext/src/config/next-config.ts | 11 ++ packages/vinext/src/index.ts | 4 + .../private-next-instrumentation-client.d.ts | 7 +- .../vinext/src/routing/app-route-graph.ts | 16 ++ .../src/routing/browser-route-manifest.ts | 11 +- .../vinext/src/server/app-browser-entry.ts | 16 +- .../server/app-browser-transition-routes.ts | 158 ++++++++++++++++++ .../vinext/src/shims/app-router-navigation.ts | 12 +- packages/vinext/src/shims/link.tsx | 19 ++- playwright.config.ts | 1 + tests/app-browser-transition-routes.test.ts | 121 ++++++++++++++ tests/app-route-graph.test.ts | 1 + .../instrumentation-client-inject.spec.ts | 2 +- ...mentation-client-transition-events.spec.ts | 130 ++++++++++++++ tests/entry-templates.test.ts | 6 + .../(marketing)/about/page.tsx | 3 + .../transition-events/blog/[slug]/page.tsx | 4 + .../dashboard/@analytics/page.tsx | 3 + .../transition-events/dashboard/layout.tsx | 16 ++ .../transition-events/dashboard/page.tsx | 3 + .../transition-events/docs/[...slug]/page.tsx | 3 + .../gallery/@modal/(.)photos/[id]/page.tsx | 4 + .../gallery/@modal/default.tsx | 3 + .../transition-events/gallery/layout.tsx | 16 ++ .../transition-events/gallery/page.tsx | 10 ++ .../gallery/photos/[id]/page.tsx | 4 + .../transition-events/layout.tsx | 30 ++++ .../transition-events/page.tsx | 10 ++ .../transition-events/push-button.tsx | 15 ++ .../shop/[[...slug]]/page.tsx | 3 + .../transition-events/some-page/page.tsx | 3 + ...nstrumentation-client-inject-late-hook.cjs | 6 +- .../app-basic/instrumentation-client.ts | 11 +- tests/fixtures/app-basic/next.config.ts | 4 + tests/instrumentation.test.ts | 57 +++++++ tests/next-config.test.ts | 15 ++ 39 files changed, 784 insertions(+), 24 deletions(-) create mode 100644 packages/vinext/src/server/app-browser-transition-routes.ts create mode 100644 tests/app-browser-transition-routes.test.ts create mode 100644 tests/e2e/app-router/instrumentation-client-transition-events.spec.ts create mode 100644 tests/fixtures/app-basic/app/instrumentation-client/transition-events/(marketing)/about/page.tsx create mode 100644 tests/fixtures/app-basic/app/instrumentation-client/transition-events/blog/[slug]/page.tsx create mode 100644 tests/fixtures/app-basic/app/instrumentation-client/transition-events/dashboard/@analytics/page.tsx create mode 100644 tests/fixtures/app-basic/app/instrumentation-client/transition-events/dashboard/layout.tsx create mode 100644 tests/fixtures/app-basic/app/instrumentation-client/transition-events/dashboard/page.tsx create mode 100644 tests/fixtures/app-basic/app/instrumentation-client/transition-events/docs/[...slug]/page.tsx create mode 100644 tests/fixtures/app-basic/app/instrumentation-client/transition-events/gallery/@modal/(.)photos/[id]/page.tsx create mode 100644 tests/fixtures/app-basic/app/instrumentation-client/transition-events/gallery/@modal/default.tsx create mode 100644 tests/fixtures/app-basic/app/instrumentation-client/transition-events/gallery/layout.tsx create mode 100644 tests/fixtures/app-basic/app/instrumentation-client/transition-events/gallery/page.tsx create mode 100644 tests/fixtures/app-basic/app/instrumentation-client/transition-events/gallery/photos/[id]/page.tsx create mode 100644 tests/fixtures/app-basic/app/instrumentation-client/transition-events/layout.tsx create mode 100644 tests/fixtures/app-basic/app/instrumentation-client/transition-events/page.tsx create mode 100644 tests/fixtures/app-basic/app/instrumentation-client/transition-events/push-button.tsx create mode 100644 tests/fixtures/app-basic/app/instrumentation-client/transition-events/shop/[[...slug]]/page.tsx create mode 100644 tests/fixtures/app-basic/app/instrumentation-client/transition-events/some-page/page.tsx diff --git a/packages/vinext/src/check.ts b/packages/vinext/src/check.ts index 957f21e182..b80fe538c2 100644 --- a/packages/vinext/src/check.ts +++ b/packages/vinext/src/check.ts @@ -310,6 +310,7 @@ const CONFIG_SUPPORT: Record = { "experimental.disableOptimizedLoading": { status: "supported" }, "experimental.gestureTransition": { status: "supported" }, "experimental.appNavFailHandling": { status: "supported" }, + "experimental.instrumentationClientRouterTransitionEvents": { status: "supported" }, "experimental.rootParams": { status: "supported", detail: "no longer needed; root params are always available", diff --git a/packages/vinext/src/client/instrumentation-client-state.ts b/packages/vinext/src/client/instrumentation-client-state.ts index b9a4719a1d..e4398858de 100644 --- a/packages/vinext/src/client/instrumentation-client-state.ts +++ b/packages/vinext/src/client/instrumentation-client-state.ts @@ -31,18 +31,69 @@ export function getClientInstrumentationHooks(): ClientInstrumentationHooks | nu export const INSTRUMENTATION_CLIENT_HOOK_FAILED_MESSAGE = "An instrumentation-client router transition hook failed"; +export type RouterTransitionType = "push" | "replace" | "traverse"; + +/** How the `` that started a navigation prefetches: `prefetch={true}` is "full". */ +export type RouterTransitionPrefetchIntent = "full" | "auto" | "none"; + +/** Next.js' `RouterTransitionStartEvent` (client/router-transition-types.ts). */ +export type RouterTransitionStartEvent = { + id: string; + timestamp: number; + /** Source route patterns of the page being left, its primary route first. */ + fromRoutes: string[]; + /** `null` when the navigation did not start from a ``. */ + prefetchIntent: RouterTransitionPrefetchIntent | null; +}; + +// The App Router browser entry registers how to read the committed route tree. +// It lives on globalThis for the same reason as the hooks above. +const VINEXT_ROUTER_TRANSITION_FROM_ROUTES = Symbol.for("vinext.client.routerTransitionFromRoutes"); + +export function setRouterTransitionFromRoutesResolver(resolve: (() => string[]) | null): void { + Reflect.set(globalThis, VINEXT_ROUTER_TRANSITION_FROM_ROUTES, resolve); +} + +function resolveRouterTransitionFromRoutes(): string[] { + const resolve = Reflect.get(globalThis, VINEXT_ROUTER_TRANSITION_FROM_ROUTES) as + | (() => string[]) + | null + | undefined; + return resolve ? resolve() : []; +} + +let nextTransitionId = 0; + /** - * Mirrors Next.js' `startRouterTransition` without - * `experimental.instrumentationClientRouterTransitionEvents`: the third - * argument is `null`, and a throwing hook is logged instead of breaking the - * navigation (client/components/router-transition.ts). + * Mirrors Next.js' `startRouterTransition` + * (client/components/router-transition.ts). The third argument is `null` + * unless `experimental.instrumentationClientRouterTransitionEvents` is set, + * and a throwing hook is logged instead of breaking the navigation. */ export function notifyAppRouterTransitionStart( href: string, - navigationType: "push" | "replace" | "traverse", + navigationType: RouterTransitionType, + prefetchIntent: RouterTransitionPrefetchIntent | null = null, ): void { + const hooks = getClientInstrumentationHooks(); + if (typeof hooks?.onRouterTransitionStart !== "function") return; + // Positive flag check so the event path drops out of builds without the flag. + const id = process.env.__NEXT_INSTRUMENTATION_CLIENT_ROUTER_TRANSITION_EVENTS + ? `${Date.now().toString(36)}-${(++nextTransitionId).toString(36)}` + : null; try { - getClientInstrumentationHooks()?.onRouterTransitionStart?.(href, navigationType, null); + // Built inside the try like Next.js, so a failure is logged like a + // throwing hook. + const event: RouterTransitionStartEvent | null = + id === null + ? null + : { + id, + timestamp: performance.timeOrigin + performance.now(), + fromRoutes: resolveRouterTransitionFromRoutes(), + prefetchIntent, + }; + hooks.onRouterTransitionStart(href, navigationType, event); } catch (error) { console.error(INSTRUMENTATION_CLIENT_HOOK_FAILED_MESSAGE, error); } diff --git a/packages/vinext/src/client/instrumentation-client.ts b/packages/vinext/src/client/instrumentation-client.ts index 1e90622ae7..e736739b74 100644 --- a/packages/vinext/src/client/instrumentation-client.ts +++ b/packages/vinext/src/client/instrumentation-client.ts @@ -2,13 +2,15 @@ import * as instrumentationClientHooks from "private-next-instrumentation-client import { normalizeClientInstrumentationHooks, setClientInstrumentationHooks, + type RouterTransitionStartEvent, + type RouterTransitionType, } from "./instrumentation-client-state.js"; export type ClientInstrumentationHooks = { onRouterTransitionStart?: ( href: string, - navigationType: "push" | "replace" | "traverse", - event: null, + navigationType: RouterTransitionType, + event: RouterTransitionStartEvent | null, ) => void; }; diff --git a/packages/vinext/src/config/next-config.ts b/packages/vinext/src/config/next-config.ts index 4d391c4d36..53238f597e 100644 --- a/packages/vinext/src/config/next-config.ts +++ b/packages/vinext/src/config/next-config.ts @@ -486,6 +486,12 @@ export type NextConfig = { * `useRouter().experimental_gesturePush()`. */ gestureTransition?: boolean; + /** + * Passes a start event (`id`, `timestamp`, `fromRoutes`, `prefetchIntent`) + * as the third argument of the instrumentation-client + * `onRouterTransitionStart` hook. Without it the hook receives `null`. + */ + instrumentationClientRouterTransitionEvents?: boolean; /** * Enables App Router Segment Cache prefetch inlining. When provided as an * object, thresholds are resolved with Next.js defaults and non-finite @@ -591,6 +597,8 @@ export type ResolvedNextConfig = { * `useRouter().experimental_gesturePush()`. */ gestureTransition: boolean; + /** `experimental.instrumentationClientRouterTransitionEvents`. */ + instrumentationClientRouterTransitionEvents: boolean; /** * Resolved `experimental.prefetchInlining` config. Next.js normalizes `true` * and partial object config into concrete thresholds. @@ -2026,6 +2034,7 @@ export async function resolveNextConfig( cachedNavigations: false, appNavFailHandling: false, gestureTransition: false, + instrumentationClientRouterTransitionEvents: false, prefetchInlining: false, redirects: [], rewrites: { beforeFiles: [], afterFiles: [], fallback: [] }, @@ -2471,6 +2480,8 @@ export async function resolveNextConfig( cachedNavigations: cacheComponents && experimental?.cachedNavigations === true, appNavFailHandling: experimental?.appNavFailHandling === true, gestureTransition: experimental?.gestureTransition === true, + instrumentationClientRouterTransitionEvents: + experimental?.instrumentationClientRouterTransitionEvents === true, prefetchInlining, redirects, rewrites, diff --git a/packages/vinext/src/index.ts b/packages/vinext/src/index.ts index c9bcc32d35..223bc9a8b5 100644 --- a/packages/vinext/src/index.ts +++ b/packages/vinext/src/index.ts @@ -3442,6 +3442,10 @@ export default function vinext(options: VinextOptions = {}): PluginOption[] { defines["process.env.__NEXT_APP_NAV_FAIL_HANDLING"] = JSON.stringify( nextConfig.appNavFailHandling, ); + // Raw boolean like Next.js define-env.ts, so the event-building path in + // instrumentation-client-state.ts drops out when the flag is off. + defines["process.env.__NEXT_INSTRUMENTATION_CLIENT_ROUTER_TRANSITION_EVENTS"] = + JSON.stringify(nextConfig.instrumentationClientRouterTransitionEvents); defines["process.env.__NEXT_TEST_MODE"] = JSON.stringify( process.env.__NEXT_TEST_MODE ?? false, ); diff --git a/packages/vinext/src/private-next-instrumentation-client.d.ts b/packages/vinext/src/private-next-instrumentation-client.d.ts index e2d623e89b..f9349072f3 100644 --- a/packages/vinext/src/private-next-instrumentation-client.d.ts +++ b/packages/vinext/src/private-next-instrumentation-client.d.ts @@ -4,6 +4,11 @@ declare module "private-next-instrumentation-client" { export function onRouterTransitionStart( href: string, navigationType: "push" | "replace" | "traverse", - event: null, + event: { + id: string; + timestamp: number; + fromRoutes: string[]; + prefetchIntent: "full" | "auto" | "none" | null; + } | null, ): void; } diff --git a/packages/vinext/src/routing/app-route-graph.ts b/packages/vinext/src/routing/app-route-graph.ts index a4e4e21d13..75420dec55 100644 --- a/packages/vinext/src/routing/app-route-graph.ts +++ b/packages/vinext/src/routing/app-route-graph.ts @@ -407,6 +407,12 @@ export type RouteManifestSlotBinding = { export type RouteManifestInterception = { id: string; + /** + * The intercepting page's directory from app/ in Next.js' source-path form, + * route groups omitted (e.g. `/gallery/@modal/(.)photos/[id]`). Reported in + * the instrumentation-client router transition event's `fromRoutes`. + */ + sourcePagePath?: string; sourcePattern: string; sourcePatternParts: readonly string[]; targetPattern: string; @@ -707,6 +713,7 @@ function createStaticSegmentGraph(routes: readonly AppRouteGraphRoute[]): Static createAppRouteGraphInterceptionId(ir.slotId, ir.sourceMatchPattern, ir.targetPattern); interceptions.set(id, { id, + ...createInterceptionSourcePagePath(ir.sourcePageSegments), sourcePattern: ir.sourceMatchPattern, sourcePatternParts: splitRouteManifestPatternParts(ir.sourceMatchPattern), targetPattern: ir.targetPattern, @@ -817,6 +824,7 @@ function addRouteManifestInterceptionFacts(input: { ); input.interceptions.set(id, { id, + ...createInterceptionSourcePagePath(interception.sourcePageSegments), sourcePattern: interception.sourceMatchPattern, sourcePatternParts: splitRouteManifestPatternParts(interception.sourceMatchPattern), targetPattern: interception.targetPattern, @@ -829,6 +837,14 @@ function addRouteManifestInterceptionFacts(input: { } } +function createInterceptionSourcePagePath( + segments: readonly string[] | undefined, +): Pick { + if (segments === undefined) return {}; + const visible = segments.filter((segment) => !(segment.startsWith("(") && segment.endsWith(")"))); + return { sourcePagePath: `/${visible.join("/")}` }; +} + function createRouteManifestInterceptionsBySlotId( interceptions: ReadonlyMap, ): ReadonlyMap { diff --git a/packages/vinext/src/routing/browser-route-manifest.ts b/packages/vinext/src/routing/browser-route-manifest.ts index be886dfcc5..44e71a6fe5 100644 --- a/packages/vinext/src/routing/browser-route-manifest.ts +++ b/packages/vinext/src/routing/browser-route-manifest.ts @@ -40,7 +40,13 @@ type BrowserRouteManifestSlotBinding = Pick< export type BrowserRouteManifestInterception = Pick< RouteManifestInterception, - "id" | "sourcePatternParts" | "targetPatternParts" | "slotId" | "ownerLayoutId" | "targetRouteId" + | "id" + | "sourcePagePath" + | "sourcePatternParts" + | "targetPatternParts" + | "slotId" + | "ownerLayoutId" + | "targetRouteId" >; type BrowserRouteManifestRootBoundary = Pick; @@ -258,6 +264,9 @@ export function toBrowserRouteManifestWire(routeManifest: RouteManifest): Browse })), interceptions: Array.from(graph.interceptions.values(), (interception) => ({ id: interception.id, + ...(interception.sourcePagePath === undefined + ? {} + : { sourcePagePath: interception.sourcePagePath }), sourcePatternParts: interception.sourcePatternParts, targetPatternParts: interception.targetPatternParts, slotId: interception.slotId, diff --git a/packages/vinext/src/server/app-browser-entry.ts b/packages/vinext/src/server/app-browser-entry.ts index af15cc01ba..640989aff7 100644 --- a/packages/vinext/src/server/app-browser-entry.ts +++ b/packages/vinext/src/server/app-browser-entry.ts @@ -20,7 +20,11 @@ import { flushSync } from "react-dom"; import { createRoot, hydrateRoot } from "react-dom/client"; import "../client/instrumentation-client.js"; import { AppRouterAnnouncer } from "../client/app-router-announcer.js"; -import { notifyAppRouterTransitionStart } from "../client/instrumentation-client-state.js"; +import { + notifyAppRouterTransitionStart, + setRouterTransitionFromRoutesResolver, +} from "../client/instrumentation-client-state.js"; +import { resolveRouterTransitionFromRoutes } from "./app-browser-transition-routes.js"; import { __basePath, activateNavigationSnapshot, @@ -410,6 +414,16 @@ const browserNavigationController = createAppBrowserNavigationController({ syncHistoryStatePreviousNextUrl: (previousNextUrl, bfcacheIds) => historyController.syncCurrentHistoryStatePreviousNextUrl(previousNextUrl, bfcacheIds), }); + +// experimental.instrumentationClientRouterTransitionEvents: report the source +// routes of the committed tree. The flag check drops the resolver otherwise. +if (process.env.__NEXT_INSTRUMENTATION_CLIENT_ROUTER_TRANSITION_EVENTS) { + setRouterTransitionFromRoutesResolver(() => + hasBrowserRouterState() + ? resolveRouterTransitionFromRoutes(getBrowserRouterState(), getBrowserRouteManifest()) + : [], + ); +} const discardedServerActionRefreshScheduler = hasServerActions ? createDiscardedServerActionRefreshScheduler({ runRefresh() { diff --git a/packages/vinext/src/server/app-browser-transition-routes.ts b/packages/vinext/src/server/app-browser-transition-routes.ts new file mode 100644 index 0000000000..f744308215 --- /dev/null +++ b/packages/vinext/src/server/app-browser-transition-routes.ts @@ -0,0 +1,158 @@ +import type { BrowserRouteManifest } from "../routing/browser-route-manifest.js"; +import { matchRoutePattern } from "../routing/route-pattern.js"; +import { splitPathnameForRouteMatch } from "../routing/utils.js"; +import { + AppElementsWire, + type AppElementsInterception, + type AppElementsSlotBinding, +} from "./app-elements.js"; +import { matchOptimisticRouteManifestRoute } from "./app-optimistic-routing.js"; + +// Synthetic slot of an interception marker without an @slot wrapper. Its page +// renders as the owner's children, so Next.js reports it as the primary route. +// Matches SIBLING_INTERCEPT_SLOT_NAME in routing/app-route-graph.ts. +const SIBLING_INTERCEPT_SLOT_NAME = "__vinext_sibling_intercept"; + +type TransitionRouteState = Readonly<{ + interception: AppElementsInterception | null; + routeId: string; + slotBindings: readonly AppElementsSlotBinding[]; +}>; + +function isRouteGroupSegment(segment: string): boolean { + return segment.startsWith("(") && segment.endsWith(")"); +} + +/** A manifest pattern part in source form: `:id` → `[id]`, `:slug+` → `[...slug]`. */ +function toSourceSegment(part: string): string { + if (!part.startsWith(":")) return part; + if (part.endsWith("+")) return `[...${part.slice(1, -1)}]`; + if (part.endsWith("*")) return `[[...${part.slice(1, -1)}]]`; + return `[${part.slice(1)}]`; +} + +function joinSourcePath(segments: readonly string[]): string { + return `/${segments.filter((segment) => segment.length > 0 && !isRouteGroupSegment(segment)).join("/")}`; +} + +function routePathFromId(routeId: string): string | null { + const parsed = AppElementsWire.parseElementKey(routeId); + return parsed?.kind === "route" ? parsed.path : null; +} + +function matchManifestRoute( + routePath: string, + routeManifest: BrowserRouteManifest | null, +): { id: string; patternParts: readonly string[] } | null { + if (routeManifest === null) return null; + return ( + matchOptimisticRouteManifestRoute({ basePath: "", href: routePath, routeManifest })?.route ?? + null + ); +} + +function resolveRouteSourcePath( + routePath: string, + routeManifest: BrowserRouteManifest | null, +): string { + const route = matchManifestRoute(routePath, routeManifest); + if (route === null) return routePath; + return joinSourcePath(route.patternParts.map(toSourceSegment)); +} + +function resolveInterceptionSourcePagePath( + interception: AppElementsInterception, + interceptionId: string | null | undefined, + routeManifest: BrowserRouteManifest | null, +): string | null { + if (routeManifest === null) return null; + const graph = routeManifest.segmentGraph; + const byId = interceptionId ? graph.interceptions.get(interceptionId) : undefined; + if (byId?.sourcePagePath) return byId.sourcePagePath; + const targetParts = splitPathnameForRouteMatch(interception.targetMatchedUrl); + const match = graph.interceptionsBySlotId + .get(interception.slotId) + ?.find((candidate) => matchRoutePattern(targetParts, candidate.targetPatternParts) !== null); + return match?.sourcePagePath ?? null; +} + +function resolveSlotSourcePath( + binding: AppElementsSlotBinding, + slotBase: readonly string[], + routeManifest: BrowserRouteManifest | null, +): string { + if (binding.state !== "active" || binding.activeRouteId == null) { + return joinSourcePath([...slotBase, "default"]); + } + const activeRoutePath = routePathFromId(binding.activeRouteId); + const activeRoute = + activeRoutePath === null ? null : matchManifestRoute(activeRoutePath, routeManifest); + const manifestBinding = + activeRoute === null + ? undefined + : routeManifest?.segmentGraph.slotBindings.get(`${activeRoute.id}::${binding.slotId}`); + if (manifestBinding?.state === "active" && manifestBinding.routeSegments) { + return joinSourcePath([...slotBase, ...manifestBinding.routeSegments]); + } + if (manifestBinding === undefined) return joinSourcePath(slotBase); + return joinSourcePath([...slotBase, "default"]); +} + +/** + * The source route patterns of the committed App Router tree, as Next.js + * reports them in `RouterTransitionStartEvent.fromRoutes`: the primary + * (children) route first, then one entry per parallel slot, sorted. Route + * groups are omitted, a slot showing its default reports `@slot/default`, and + * an intercepted slot reports the intercepting page's directory. + * + * Ref: packages/next/src/client/components/router-transition.ts + * (getActiveRoutePaths) + */ +export function resolveRouterTransitionFromRoutes( + state: TransitionRouteState, + routeManifest: BrowserRouteManifest | null, +): string[] { + const interception = state.interception; + const interceptionSlot = + interception === null ? null : AppElementsWire.parseElementKey(interception.slotId); + const siblingInterceptPath = + interception !== null && + interceptionSlot?.kind === "slot" && + interceptionSlot.name === SIBLING_INTERCEPT_SLOT_NAME + ? resolveInterceptionSourcePagePath(interception, null, routeManifest) + : null; + + const primaryRoutePath = routePathFromId(interception?.sourceRouteId ?? state.routeId); + const primary = + siblingInterceptPath ?? + (primaryRoutePath === null ? null : resolveRouteSourcePath(primaryRoutePath, routeManifest)); + + const slots: string[] = []; + for (const binding of state.slotBindings) { + const slot = AppElementsWire.parseElementKey(binding.slotId); + if ( + slot?.kind !== "slot" || + slot.name === "children" || + slot.name === SIBLING_INTERCEPT_SLOT_NAME + ) { + continue; + } + if (interception !== null && interception.slotId === binding.slotId) { + const intercepted = resolveInterceptionSourcePagePath( + interception, + binding.interceptionId, + routeManifest, + ); + if (intercepted !== null) { + slots.push(intercepted); + continue; + } + } + slots.push( + resolveSlotSourcePath(binding, [...slot.treePath.split("/"), `@${slot.name}`], routeManifest), + ); + } + + slots.sort((left, right) => left.localeCompare(right)); + return primary === null ? slots : [primary, ...slots]; +} diff --git a/packages/vinext/src/shims/app-router-navigation.ts b/packages/vinext/src/shims/app-router-navigation.ts index 29dee11aa3..791ca5dfe1 100644 --- a/packages/vinext/src/shims/app-router-navigation.ts +++ b/packages/vinext/src/shims/app-router-navigation.ts @@ -30,7 +30,10 @@ import { loadNavigationRuntimeRouteManifest, type NavigationRuntimeVisibleCommitMode, } from "../client/navigation-runtime.js"; -import { notifyAppRouterTransitionStart } from "../client/instrumentation-client-state.js"; +import { + notifyAppRouterTransitionStart, + type RouterTransitionPrefetchIntent, +} from "../client/instrumentation-client-state.js"; import { clearAppNavigationFailureTarget, stageAppNavigationFailureTarget, @@ -2226,6 +2229,7 @@ export async function navigateClientSide( scroll: boolean, programmaticTransition = false, visibleCommitMode: NavigationRuntimeVisibleCommitMode = "transition", + prefetchIntent: RouterTransitionPrefetchIntent | null = null, ): Promise { notifyAppNavigationStart(href); @@ -2234,7 +2238,7 @@ export async function navigateClientSide( if (isExternalUrl(href)) { const localPath = toSameOriginAppPath(href, __basePath); if (localPath == null) { - notifyAppRouterTransitionStart(href, mode); + notifyAppRouterTransitionStart(href, mode, prefetchIntent); const externalNavigate = getNavigationRuntime()?.functions.navigateExternal; if (externalNavigate) { @@ -2266,7 +2270,7 @@ export async function navigateClientSide( __basePath, __trailingSlash, ); - notifyAppRouterTransitionStart(fullHref, mode); + notifyAppRouterTransitionStart(fullHref, mode, prefetchIntent); if (mode === "push") { saveScrollPosition(); } @@ -2291,7 +2295,7 @@ export async function navigateClientSide( stageAppNavigationFailureTarget(fullHref); // Match Next.js: App Router reports navigation start before dispatching, // including hash-only navigations that short-circuit after URL update. - notifyAppRouterTransitionStart(fullHref, mode); + notifyAppRouterTransitionStart(fullHref, mode, prefetchIntent); // Save scroll position before navigating (for back/forward restoration) if (mode === "push") { diff --git a/packages/vinext/src/shims/link.tsx b/packages/vinext/src/shims/link.tsx index a5ade6637b..0f19e3405b 100644 --- a/packages/vinext/src/shims/link.tsx +++ b/packages/vinext/src/shims/link.tsx @@ -1709,12 +1709,19 @@ const Link = forwardRef(function Link( if (setter) setLinkForCurrentNavigation(setter); setPending(true); React.startTransition(() => { - void navigateClientSide(navigateHref, replace ? "replace" : "push", scroll, false).finally( - () => { - setPending(false); - if (setter) clearLinkForCurrentNavigation(setter); - }, - ); + void navigateClientSide( + navigateHref, + replace ? "replace" : "push", + scroll, + false, + "transition", + // Next.js reports the Link's prefetch prop as the transition's + // prefetch intent (client/app-dir/link.tsx). + prefetchProp === false ? "none" : prefetchProp === true ? "full" : "auto", + ).finally(() => { + setPending(false); + if (setter) clearLinkForCurrentNavigation(setter); + }); }); return; } else if (HAS_PAGES_ROUTER) { diff --git a/playwright.config.ts b/playwright.config.ts index 5d6f9525db..fbd0e50ceb 100644 --- a/playwright.config.ts +++ b/playwright.config.ts @@ -126,6 +126,7 @@ const projectServers = { "app-router/tsconfig-exact-path.spec.ts", "app-router/nextjs-compat/segment-cache-dynamic-params.spec.ts", "app-router/instrumentation-client-inject.spec.ts", + "app-router/instrumentation-client-transition-events.spec.ts", ], use: { baseURL: "http://localhost:4198" }, server: { diff --git a/tests/app-browser-transition-routes.test.ts b/tests/app-browser-transition-routes.test.ts new file mode 100644 index 0000000000..9d09660576 --- /dev/null +++ b/tests/app-browser-transition-routes.test.ts @@ -0,0 +1,121 @@ +// Ported from Next.js: test/e2e/instrumentation-client-hook/instrumentation-client-hook.test.ts +// ("router transition start context"), pinned to getActiveRoutePaths in +// packages/next/src/client/components/router-transition.ts. +// https://github.com/vercel/next.js/blob/v16.4.6/test/e2e/instrumentation-client-hook/instrumentation-client-hook.test.ts +import path from "node:path"; +import { beforeAll, describe, expect, it } from "vite-plus/test"; +import { appRouteGraph } from "../packages/vinext/src/routing/app-router.js"; +import { + decodeBrowserRouteManifest, + toBrowserRouteManifestWire, + type BrowserRouteManifest, +} from "../packages/vinext/src/routing/browser-route-manifest.js"; +import { resolveRouterTransitionFromRoutes } from "../packages/vinext/src/server/app-browser-transition-routes.js"; + +// The transition-events pages, scanned as their own app/ root. +const APP_DIR = path.resolve( + import.meta.dirname, + "fixtures/app-basic/app/instrumentation-client/transition-events", +); + +let manifest: BrowserRouteManifest; + +beforeAll(async () => { + const graph = await appRouteGraph(APP_DIR); + manifest = decodeBrowserRouteManifest(toBrowserRouteManifestWire(graph.routeManifest)); +}); + +function page(routePath: string) { + return { interception: null, routeId: `route:${routePath}`, slotBindings: [] }; +} + +describe("resolveRouterTransitionFromRoutes", () => { + it("reports route patterns, without route groups", () => { + expect(resolveRouterTransitionFromRoutes(page("/"), manifest)).toEqual(["/"]); + expect(resolveRouterTransitionFromRoutes(page("/blog/hello"), manifest)).toEqual([ + "/blog/[slug]", + ]); + expect(resolveRouterTransitionFromRoutes(page("/about"), manifest)).toEqual(["/about"]); + expect(resolveRouterTransitionFromRoutes(page("/docs/a/b"), manifest)).toEqual([ + "/docs/[...slug]", + ]); + expect(resolveRouterTransitionFromRoutes(page("/shop"), manifest)).toEqual([ + "/shop/[[...slug]]", + ]); + }); + + it("puts the primary route first, then each slot", () => { + expect( + resolveRouterTransitionFromRoutes( + { + interception: null, + routeId: "route:/dashboard", + slotBindings: [ + { + activeRouteId: "route:/dashboard", + ownerLayoutId: "layout:/dashboard", + slotId: "slot:analytics:/dashboard", + state: "active", + }, + ], + }, + manifest, + ), + ).toEqual(["/dashboard", "/dashboard/@analytics"]); + }); + + it("reports a slot showing its default as @slot/default", () => { + expect( + resolveRouterTransitionFromRoutes( + { + interception: null, + routeId: "route:/gallery", + slotBindings: [ + { ownerLayoutId: "layout:/gallery", slotId: "slot:modal:/gallery", state: "default" }, + ], + }, + manifest, + ), + ).toEqual(["/gallery", "/gallery/@modal/default"]); + }); + + it("reports the intercepting page for an intercepted slot", () => { + const interception = { + sourceMatchedUrl: "/gallery", + sourceRouteId: "route:/gallery", + slotId: "slot:modal:/gallery", + targetMatchedUrl: "/gallery/photos/1", + targetRouteId: "route:/gallery/photos/1", + }; + const binding = { + activeRouteId: "route:/gallery/photos/1", + ownerLayoutId: "layout:/gallery", + slotId: "slot:modal:/gallery", + state: "active" as const, + }; + const expected = ["/gallery", "/gallery/@modal/(.)photos/[id]"]; + + expect( + resolveRouterTransitionFromRoutes( + { + interception, + routeId: "route:/gallery", + slotBindings: [ + { + ...binding, + interceptionId: "interception:slot:modal:/gallery:/gallery->/gallery/photos/:id", + }, + ], + }, + manifest, + ), + ).toEqual(expected); + // Without the binding's interception id, the target URL selects it. + expect( + resolveRouterTransitionFromRoutes( + { interception, routeId: "route:/gallery", slotBindings: [binding] }, + manifest, + ), + ).toEqual(expected); + }); +}); diff --git a/tests/app-route-graph.test.ts b/tests/app-route-graph.test.ts index 447f7acd1f..7a6a4df8ad 100644 --- a/tests/app-route-graph.test.ts +++ b/tests/app-route-graph.test.ts @@ -1805,6 +1805,7 @@ describe("App Router route graph builder", () => { expect(interceptions).toEqual([ { id: "interception:slot:modal:/[locale]/feed:/:locale/feed->/:locale/photos/:id", + sourcePagePath: "/[locale]/feed/@modal/(..)photos/[id]", sourcePattern: "/:locale/feed", sourcePatternParts: [":locale", "feed"], targetPattern: "/:locale/photos/:id", diff --git a/tests/e2e/app-router/instrumentation-client-inject.spec.ts b/tests/e2e/app-router/instrumentation-client-inject.spec.ts index cb8b0cecfd..c2939985e8 100644 --- a/tests/e2e/app-router/instrumentation-client-inject.spec.ts +++ b/tests/e2e/app-router/instrumentation-client-inject.spec.ts @@ -36,7 +36,7 @@ test("instrumentationClientInject hooks are read at transition time and isolated message.startsWith("[Router Transition Start]"), ), ).toEqual([ - "[Injected Transition Start] [push] /instrumentation-client/some-page late-hook null", + "[Injected Transition Start] [push] /instrumentation-client/some-page late-hook event", "[Injected Transition Start] [push] /instrumentation-client/some-page package-late-hook", "[Injected Transition Start] [push] /instrumentation-client/some-page throws", "[Router Transition Start] [push] /instrumentation-client/some-page", diff --git a/tests/e2e/app-router/instrumentation-client-transition-events.spec.ts b/tests/e2e/app-router/instrumentation-client-transition-events.spec.ts new file mode 100644 index 0000000000..5b86727a2c --- /dev/null +++ b/tests/e2e/app-router/instrumentation-client-transition-events.spec.ts @@ -0,0 +1,130 @@ +// Ported from Next.js: +// test/e2e/instrumentation-client-hook/instrumentation-client-hook.test.ts +// ("router transition start context") +// https://github.com/vercel/next.js/blob/v16.4.6/test/e2e/instrumentation-client-hook/instrumentation-client-hook.test.ts +// +// app-basic enables experimental.instrumentationClientRouterTransitionEvents, +// so onRouterTransitionStart receives a start event as its third argument. + +import { test, expect, type Page } from "@playwright/test"; +import { waitForAppRouterHydration } from "../helpers"; + +const BASE = "/instrumentation-client/transition-events"; + +type TransitionStart = { + url: string; + navigationType: string; + event: { + id: string; + timestamp: number; + fromRoutes: string[]; + prefetchIntent: string | null; + } | null; +}; + +async function open(page: Page, pathname: string): Promise { + await page.goto(`${BASE}${pathname}`); + await waitForAppRouterHydration(page); +} + +async function getTransitionEvents(page: Page): Promise { + return page.evaluate( + () => + (window as Window & { __ROUTER_TRANSITION_EVENTS?: TransitionStart[] }) + .__ROUTER_TRANSITION_EVENTS ?? [], + ); +} + +async function lastFromRoutes(page: Page): Promise { + return (await getTransitionEvents(page)).at(-1)?.event?.fromRoutes; +} + +test.describe("instrumentation-client router transition start event", () => { + test("reports transition metadata, source routes, and prefetch intent", async ({ page }) => { + await open(page, ""); + await page.locator(`a[href="${BASE}/some-page"]`).click(); + await expect(page.locator("#some-page")).toBeVisible(); + + const [start] = await getTransitionEvents(page); + expect(start.url).toBe(`${BASE}/some-page`); + expect(start.navigationType).toBe("push"); + expect(typeof start.event?.id).toBe("string"); + expect(start.event?.timestamp).toBeGreaterThan(0); + expect(start.event?.fromRoutes).toEqual([BASE]); + expect(start.event?.prefetchIntent).toBe("full"); + }); + + test("reports a null prefetch intent for programmatic navigation", async ({ page }) => { + await open(page, ""); + await page.locator("#push-some-page").click(); + await expect(page.locator("#some-page")).toBeVisible(); + + const [start] = await getTransitionEvents(page); + expect(start.url).toBe(`${BASE}/some-page`); + expect(start.navigationType).toBe("push"); + expect(start.event?.prefetchIntent).toBe(null); + }); + + test("uses route patterns and puts the primary source route first", async ({ page }) => { + await open(page, ""); + await page.locator(`a[href="${BASE}/blog/hello"]`).click(); + await expect(page.locator("#blog-post")).toBeVisible(); + await page.locator(`a[href="${BASE}"]`).click(); + await expect(page.locator("#home")).toBeVisible(); + + expect(await lastFromRoutes(page)).toEqual([`${BASE}/blog/[slug]`]); + expect((await getTransitionEvents(page)).at(-1)?.event?.prefetchIntent).toBe("auto"); + + await page.locator(`a[href="${BASE}/dashboard"]`).click(); + await expect(page.locator("#dashboard")).toBeVisible(); + await expect(page.locator("#analytics")).toBeVisible(); + await page.locator(`a[href="${BASE}"]`).click(); + await expect(page.locator("#home")).toBeVisible(); + + expect(await lastFromRoutes(page)).toEqual([ + `${BASE}/dashboard`, + `${BASE}/dashboard/@analytics`, + ]); + }); + + test("omits route groups from fromRoutes", async ({ page }) => { + await open(page, "/about"); + await page.locator(`a[href="${BASE}"]`).click(); + await expect(page.locator("#home")).toBeVisible(); + + expect(await lastFromRoutes(page)).toEqual([`${BASE}/about`]); + }); + + test("reports default and intercepted slot routes in fromRoutes", async ({ page }) => { + await open(page, "/gallery"); + await page.locator(`a[href="${BASE}/gallery/photos/1"]`).click(); + await expect(page.locator("#photo-modal")).toBeVisible(); + + // The gallery's @modal slot showed its default before the interception. + expect(await lastFromRoutes(page)).toEqual([ + `${BASE}/gallery`, + `${BASE}/gallery/@modal/default`, + ]); + + await page.locator(`a[href="${BASE}"]`).click(); + await expect(page.locator("#home")).toBeVisible(); + + expect(await lastFromRoutes(page)).toEqual([ + `${BASE}/gallery`, + `${BASE}/gallery/@modal/(.)photos/[id]`, + ]); + }); + + test("reports a null prefetch intent for back/forward navigation", async ({ page }) => { + await open(page, ""); + await page.locator(`a[href="${BASE}/blog/hello"]`).click(); + await expect(page.locator("#blog-post")).toBeVisible(); + await page.goBack(); + await expect(page.locator("#home")).toBeVisible(); + + const start = (await getTransitionEvents(page)).at(-1); + expect(start?.navigationType).toBe("traverse"); + expect(start?.event?.prefetchIntent).toBe(null); + expect(start?.event?.fromRoutes).toEqual([`${BASE}/blog/[slug]`]); + }); +}); diff --git a/tests/entry-templates.test.ts b/tests/entry-templates.test.ts index 33aefd94f1..090d69506b 100644 --- a/tests/entry-templates.test.ts +++ b/tests/entry-templates.test.ts @@ -173,6 +173,9 @@ function pickBrowserRouteManifest(routeManifest: RouteManifest) { ): Map => new Map(Array.from(map, ([key, value]) => [key, pick(value)])); const pickInterception = (interception: RouteManifestInterception) => ({ id: interception.id, + ...(interception.sourcePagePath === undefined + ? {} + : { sourcePagePath: interception.sourcePagePath }), sourcePatternParts: interception.sourcePatternParts, targetPatternParts: interception.targetPatternParts, slotId: interception.slotId, @@ -878,6 +881,9 @@ describe("App Router generated manifest construction", () => { "layout:/(protected)/admin", ]); expect(decoded.segmentGraph.interceptionsBySlotId.size).toBe(1); + expect([...decoded.segmentGraph.interceptions.values()][0]?.sourcePagePath).toBe( + "/feed/@modal/(..)photos/[photoId]", + ); expect(generateBrowserRouteManifestModule(null)).toBe("export default null;"); // A route id that is not `route:` plus its pattern travels explicitly. diff --git a/tests/fixtures/app-basic/app/instrumentation-client/transition-events/(marketing)/about/page.tsx b/tests/fixtures/app-basic/app/instrumentation-client/transition-events/(marketing)/about/page.tsx new file mode 100644 index 0000000000..1846afde9d --- /dev/null +++ b/tests/fixtures/app-basic/app/instrumentation-client/transition-events/(marketing)/about/page.tsx @@ -0,0 +1,3 @@ +export default function Page() { + return

About

; +} diff --git a/tests/fixtures/app-basic/app/instrumentation-client/transition-events/blog/[slug]/page.tsx b/tests/fixtures/app-basic/app/instrumentation-client/transition-events/blog/[slug]/page.tsx new file mode 100644 index 0000000000..a917cfdc4f --- /dev/null +++ b/tests/fixtures/app-basic/app/instrumentation-client/transition-events/blog/[slug]/page.tsx @@ -0,0 +1,4 @@ +export default async function Page({ params }: { params: Promise<{ slug: string }> }) { + const { slug } = await params; + return

Blog post {slug}

; +} diff --git a/tests/fixtures/app-basic/app/instrumentation-client/transition-events/dashboard/@analytics/page.tsx b/tests/fixtures/app-basic/app/instrumentation-client/transition-events/dashboard/@analytics/page.tsx new file mode 100644 index 0000000000..5cfbca734d --- /dev/null +++ b/tests/fixtures/app-basic/app/instrumentation-client/transition-events/dashboard/@analytics/page.tsx @@ -0,0 +1,3 @@ +export default function Page() { + return
Analytics
; +} diff --git a/tests/fixtures/app-basic/app/instrumentation-client/transition-events/dashboard/layout.tsx b/tests/fixtures/app-basic/app/instrumentation-client/transition-events/dashboard/layout.tsx new file mode 100644 index 0000000000..334fc653ff --- /dev/null +++ b/tests/fixtures/app-basic/app/instrumentation-client/transition-events/dashboard/layout.tsx @@ -0,0 +1,16 @@ +import type { ReactNode } from "react"; + +export default function DashboardLayout({ + children, + analytics, +}: { + children: ReactNode; + analytics: ReactNode; +}) { + return ( + <> + {children} + {analytics} + + ); +} diff --git a/tests/fixtures/app-basic/app/instrumentation-client/transition-events/dashboard/page.tsx b/tests/fixtures/app-basic/app/instrumentation-client/transition-events/dashboard/page.tsx new file mode 100644 index 0000000000..448a465177 --- /dev/null +++ b/tests/fixtures/app-basic/app/instrumentation-client/transition-events/dashboard/page.tsx @@ -0,0 +1,3 @@ +export default function Page() { + return

Dashboard

; +} diff --git a/tests/fixtures/app-basic/app/instrumentation-client/transition-events/docs/[...slug]/page.tsx b/tests/fixtures/app-basic/app/instrumentation-client/transition-events/docs/[...slug]/page.tsx new file mode 100644 index 0000000000..d5af77b925 --- /dev/null +++ b/tests/fixtures/app-basic/app/instrumentation-client/transition-events/docs/[...slug]/page.tsx @@ -0,0 +1,3 @@ +export default function Page() { + return

Docs

; +} diff --git a/tests/fixtures/app-basic/app/instrumentation-client/transition-events/gallery/@modal/(.)photos/[id]/page.tsx b/tests/fixtures/app-basic/app/instrumentation-client/transition-events/gallery/@modal/(.)photos/[id]/page.tsx new file mode 100644 index 0000000000..4b7c7af15c --- /dev/null +++ b/tests/fixtures/app-basic/app/instrumentation-client/transition-events/gallery/@modal/(.)photos/[id]/page.tsx @@ -0,0 +1,4 @@ +export default async function Page({ params }: { params: Promise<{ id: string }> }) { + const { id } = await params; + return
Photo modal {id}
; +} diff --git a/tests/fixtures/app-basic/app/instrumentation-client/transition-events/gallery/@modal/default.tsx b/tests/fixtures/app-basic/app/instrumentation-client/transition-events/gallery/@modal/default.tsx new file mode 100644 index 0000000000..6ddf1b76fa --- /dev/null +++ b/tests/fixtures/app-basic/app/instrumentation-client/transition-events/gallery/@modal/default.tsx @@ -0,0 +1,3 @@ +export default function Default() { + return null; +} diff --git a/tests/fixtures/app-basic/app/instrumentation-client/transition-events/gallery/layout.tsx b/tests/fixtures/app-basic/app/instrumentation-client/transition-events/gallery/layout.tsx new file mode 100644 index 0000000000..671f458b28 --- /dev/null +++ b/tests/fixtures/app-basic/app/instrumentation-client/transition-events/gallery/layout.tsx @@ -0,0 +1,16 @@ +import type { ReactNode } from "react"; + +export default function GalleryLayout({ + children, + modal, +}: { + children: ReactNode; + modal: ReactNode; +}) { + return ( + <> + {children} + {modal} + + ); +} diff --git a/tests/fixtures/app-basic/app/instrumentation-client/transition-events/gallery/page.tsx b/tests/fixtures/app-basic/app/instrumentation-client/transition-events/gallery/page.tsx new file mode 100644 index 0000000000..fce38e81a6 --- /dev/null +++ b/tests/fixtures/app-basic/app/instrumentation-client/transition-events/gallery/page.tsx @@ -0,0 +1,10 @@ +import Link from "next/link"; + +export default function Page() { + return ( + <> +

Gallery

+ Photo 1 + + ); +} diff --git a/tests/fixtures/app-basic/app/instrumentation-client/transition-events/gallery/photos/[id]/page.tsx b/tests/fixtures/app-basic/app/instrumentation-client/transition-events/gallery/photos/[id]/page.tsx new file mode 100644 index 0000000000..b69e99f7d2 --- /dev/null +++ b/tests/fixtures/app-basic/app/instrumentation-client/transition-events/gallery/photos/[id]/page.tsx @@ -0,0 +1,4 @@ +export default async function Page({ params }: { params: Promise<{ id: string }> }) { + const { id } = await params; + return

Photo {id}

; +} diff --git a/tests/fixtures/app-basic/app/instrumentation-client/transition-events/layout.tsx b/tests/fixtures/app-basic/app/instrumentation-client/transition-events/layout.tsx new file mode 100644 index 0000000000..89e1cfe6fd --- /dev/null +++ b/tests/fixtures/app-basic/app/instrumentation-client/transition-events/layout.tsx @@ -0,0 +1,30 @@ +import Link from "next/link"; +import type { ReactNode } from "react"; + +// Ported from Next.js: test/e2e/instrumentation-client-hook/app-router (app/layout.tsx) +// https://github.com/vercel/next.js/blob/v16.4.6/test/e2e/instrumentation-client-hook/app-router/app/layout.tsx +const base = "/instrumentation-client/transition-events"; + +export default function TransitionEventsLayout({ children }: { children: ReactNode }) { + return ( + <> +
    +
  • + Home +
  • +
  • + + Some Page + +
  • +
  • + Dashboard +
  • +
  • + Blog post +
  • +
+ {children} + + ); +} diff --git a/tests/fixtures/app-basic/app/instrumentation-client/transition-events/page.tsx b/tests/fixtures/app-basic/app/instrumentation-client/transition-events/page.tsx new file mode 100644 index 0000000000..9975db3c75 --- /dev/null +++ b/tests/fixtures/app-basic/app/instrumentation-client/transition-events/page.tsx @@ -0,0 +1,10 @@ +import { PushButton } from "./push-button"; + +export default function Page() { + return ( + <> +

Home

+ + + ); +} diff --git a/tests/fixtures/app-basic/app/instrumentation-client/transition-events/push-button.tsx b/tests/fixtures/app-basic/app/instrumentation-client/transition-events/push-button.tsx new file mode 100644 index 0000000000..0fe3a9696e --- /dev/null +++ b/tests/fixtures/app-basic/app/instrumentation-client/transition-events/push-button.tsx @@ -0,0 +1,15 @@ +"use client"; + +import { useRouter } from "next/navigation"; + +export function PushButton() { + const router = useRouter(); + return ( + + ); +} diff --git a/tests/fixtures/app-basic/app/instrumentation-client/transition-events/shop/[[...slug]]/page.tsx b/tests/fixtures/app-basic/app/instrumentation-client/transition-events/shop/[[...slug]]/page.tsx new file mode 100644 index 0000000000..d9de8f73e3 --- /dev/null +++ b/tests/fixtures/app-basic/app/instrumentation-client/transition-events/shop/[[...slug]]/page.tsx @@ -0,0 +1,3 @@ +export default function Page() { + return

Shop

; +} diff --git a/tests/fixtures/app-basic/app/instrumentation-client/transition-events/some-page/page.tsx b/tests/fixtures/app-basic/app/instrumentation-client/transition-events/some-page/page.tsx new file mode 100644 index 0000000000..c55cff7d74 --- /dev/null +++ b/tests/fixtures/app-basic/app/instrumentation-client/transition-events/some-page/page.tsx @@ -0,0 +1,3 @@ +export default function Page() { + return

Some Page

; +} diff --git a/tests/fixtures/app-basic/instrumentation-client-inject-late-hook.cjs b/tests/fixtures/app-basic/instrumentation-client-inject-late-hook.cjs index 71ddab2259..8b8014738b 100644 --- a/tests/fixtures/app-basic/instrumentation-client-inject-late-hook.cjs +++ b/tests/fixtures/app-basic/instrumentation-client-inject-late-hook.cjs @@ -6,6 +6,10 @@ module.exports = hooks; window.__VINEXT_INSTALL_LATE_INSTRUMENTATION_HOOK = () => { hooks.onRouterTransitionStart = (href, navigationType, event) => { const pathname = new URL(href, window.location.href).pathname; - console.log(`[Injected Transition Start] [${navigationType}] ${pathname} late-hook ${event}`); + // app-basic enables instrumentationClientRouterTransitionEvents. + const eventKind = event === null ? "null" : typeof event.id === "string" ? "event" : "invalid"; + console.log( + `[Injected Transition Start] [${navigationType}] ${pathname} late-hook ${eventKind}`, + ); }; }; diff --git a/tests/fixtures/app-basic/instrumentation-client.ts b/tests/fixtures/app-basic/instrumentation-client.ts index 006886ce1e..5c8baa0487 100644 --- a/tests/fixtures/app-basic/instrumentation-client.ts +++ b/tests/fixtures/app-basic/instrumentation-client.ts @@ -1,8 +1,12 @@ const instrumentationWindow = window as Window & { __INSTRUMENTATION_CLIENT_EXECUTED_AT?: number; __INSTRUMENTATION_CLIENT_UPDATED?: boolean; + __ROUTER_TRANSITION_EVENTS?: unknown[]; }; +// Read by app-router/instrumentation-client-transition-events.spec.ts. +instrumentationWindow.__ROUTER_TRANSITION_EVENTS = []; + instrumentationWindow.__INSTRUMENTATION_CLIENT_EXECUTED_AT = performance.now(); if (window.location.pathname.startsWith("/instrumentation-client")) { @@ -12,7 +16,12 @@ if (window.location.pathname.startsWith("/instrumentation-client")) { } } -export function onRouterTransitionStart(href: string, navigationType: string): void { +export function onRouterTransitionStart( + href: string, + navigationType: string, + event: unknown, +): void { const pathname = new URL(href, window.location.href).pathname; console.log(`[Router Transition Start] [${navigationType}] ${pathname}`); + instrumentationWindow.__ROUTER_TRANSITION_EVENTS?.push({ url: pathname, navigationType, event }); } diff --git a/tests/fixtures/app-basic/next.config.ts b/tests/fixtures/app-basic/next.config.ts index e481deb756..66ed93f5ed 100644 --- a/tests/fixtures/app-basic/next.config.ts +++ b/tests/fixtures/app-basic/next.config.ts @@ -32,6 +32,10 @@ const nextConfig: NextConfig = { // don't assert the method's absence against this fixture. experimental: { gestureTransition: true, + // Used by E2E: app-router/instrumentation-client-transition-events.spec.ts — + // onRouterTransitionStart receives a start event instead of null, so the + // fixture does NOT represent the default (null event) config. + instrumentationClientRouterTransitionEvents: true, // Used by E2E: optimize-imports-client-barrel.spec.ts — a "use client" // barrel whose imports SSR rewrites to the modules that define them. optimizePackageImports: ["fake-client-barrel"], diff --git a/tests/instrumentation.test.ts b/tests/instrumentation.test.ts index d23fb63d52..2fb43a0aa1 100644 --- a/tests/instrumentation.test.ts +++ b/tests/instrumentation.test.ts @@ -1184,4 +1184,61 @@ describe("client instrumentation hook state", () => { consoleError.mockRestore(); } }); + + // Ported from Next.js: test/e2e/instrumentation-client-hook/instrumentation-client-hook.test.ts + // ("router transition start context"), pinned to client/components/router-transition.ts. + // https://github.com/vercel/next.js/blob/v16.4.6/test/e2e/instrumentation-client-hook/instrumentation-client-hook.test.ts + describe("with experimental.instrumentationClientRouterTransitionEvents", () => { + beforeEach(() => { + vi.stubEnv("__NEXT_INSTRUMENTATION_CLIENT_ROUTER_TRANSITION_EVENTS", "true"); + }); + + afterEach(async () => { + vi.unstubAllEnvs(); + (await import(statePath)).setRouterTransitionFromRoutesResolver(null); + }); + + it("passes a start event with a fresh id, the source routes and the prefetch intent", async () => { + const state = await import(statePath); + const onRouterTransitionStart = vi.fn(); + state.setClientInstrumentationHooks({ onRouterTransitionStart }); + state.setRouterTransitionFromRoutesResolver(() => ["/blog/[slug]"]); + + state.notifyAppRouterTransitionStart("/about", "push", "full"); + state.notifyAppRouterTransitionStart("/", "traverse"); + + const [first, second] = onRouterTransitionStart.mock.calls; + expect(first.slice(0, 2)).toEqual(["/about", "push"]); + expect(first[2]).toEqual({ + id: expect.any(String), + timestamp: expect.any(Number), + fromRoutes: ["/blog/[slug]"], + prefetchIntent: "full", + }); + expect(first[2].timestamp).toBeGreaterThan(0); + expect(second[2].prefetchIntent).toBe(null); + expect(second[2].id).not.toBe(first[2].id); + }); + + it("logs a failure to build the event like a throwing hook", async () => { + const state = await import(statePath); + const error = new Error("resolver failed"); + const onRouterTransitionStart = vi.fn(); + const consoleError = vi.spyOn(console, "error").mockImplementation(() => {}); + try { + state.setClientInstrumentationHooks({ onRouterTransitionStart }); + state.setRouterTransitionFromRoutesResolver(() => { + throw error; + }); + expect(() => state.notifyAppRouterTransitionStart("/about", "push")).not.toThrow(); + expect(onRouterTransitionStart).not.toHaveBeenCalled(); + expect(consoleError).toHaveBeenCalledWith( + "An instrumentation-client router transition hook failed", + error, + ); + } finally { + consoleError.mockRestore(); + } + }); + }); }); diff --git a/tests/next-config.test.ts b/tests/next-config.test.ts index c394e52bf0..4ceb760bcf 100644 --- a/tests/next-config.test.ts +++ b/tests/next-config.test.ts @@ -2436,6 +2436,20 @@ describe("resolveNextConfig gestureTransition", () => { }); }); +describe("resolveNextConfig instrumentationClientRouterTransitionEvents", () => { + it("defaults experimental.instrumentationClientRouterTransitionEvents to false", async () => { + const resolved = await resolveNextConfig({}); + expect(resolved.instrumentationClientRouterTransitionEvents).toBe(false); + }); + + it("reads experimental.instrumentationClientRouterTransitionEvents from next.config", async () => { + const resolved = await resolveNextConfig({ + experimental: { instrumentationClientRouterTransitionEvents: true }, + }); + expect(resolved.instrumentationClientRouterTransitionEvents).toBe(true); + }); +}); + describe("resolveNextConfig cachedNavigations", () => { it("defaults experimental.cachedNavigations to false", async () => { const resolved = await resolveNextConfig({ cacheComponents: true }); @@ -2843,6 +2857,7 @@ describe("detectNextIntlConfig", () => { cachedNavigations: false, appNavFailHandling: false, gestureTransition: false, + instrumentationClientRouterTransitionEvents: false, prefetchInlining: false, redirects: [], rewrites: { beforeFiles: [], afterFiles: [], fallback: [] }, From c6cf07e4c6e8168804bbc7b703372b5355cb079c Mon Sep 17 00:00:00 2001 From: James Date: Thu, 26 Nov 2026 06:47:14 +0000 Subject: [PATCH 02/12] fix(instrumentation): report fromRoutes from the committed tree and load the manifest before transitions --- .../vinext/src/server/app-browser-entry.ts | 9 +- .../server/app-browser-transition-routes.ts | 136 ++++++++----- tests/app-browser-transition-routes.test.ts | 179 +++++++++++++++--- 3 files changed, 250 insertions(+), 74 deletions(-) diff --git a/packages/vinext/src/server/app-browser-entry.ts b/packages/vinext/src/server/app-browser-entry.ts index 640989aff7..215affea1c 100644 --- a/packages/vinext/src/server/app-browser-entry.ts +++ b/packages/vinext/src/server/app-browser-entry.ts @@ -2126,7 +2126,7 @@ async function main(): Promise { if (!claimInitialAppRouterBootstrap()) return; // Fetch the RouteManifest chunk alongside bootstrap and hydration rather than // in the entry chunk. Navigations and prefetches wait for it before reading it. - void loadNavigationRuntimeRouteManifest(); + const routeManifestLoad = loadNavigationRuntimeRouteManifest(); if (hasServerActions) registerServerActionCallback(); installAppNavigationFailureListeners(); @@ -2154,6 +2154,13 @@ async function main(): Promise { // The recovery path reloads the document, which resets the "starting" claim; // this module instance is intentionally not eligible to retry bootstrap. if (rscStream === null) return; + // experimental.instrumentationClientRouterTransitionEvents: a transition + // reports the committed tree's slot and interception routes from the + // manifest, synchronously as it starts, so the manifest loads before + // hydration makes anything able to navigate. + if (process.env.__NEXT_INSTRUMENTATION_CLIENT_ROUTER_TRANSITION_EVENTS) { + await routeManifestLoad; + } bootstrapHydration(rscStream, devErrorOverlay, initialRscBootstrap); } diff --git a/packages/vinext/src/server/app-browser-transition-routes.ts b/packages/vinext/src/server/app-browser-transition-routes.ts index f744308215..62a15d4970 100644 --- a/packages/vinext/src/server/app-browser-transition-routes.ts +++ b/packages/vinext/src/server/app-browser-transition-routes.ts @@ -1,21 +1,23 @@ import type { BrowserRouteManifest } from "../routing/browser-route-manifest.js"; import { matchRoutePattern } from "../routing/route-pattern.js"; import { splitPathnameForRouteMatch } from "../routing/utils.js"; +import { rendersSiblingIntercept } from "./app-browser-state.js"; import { AppElementsWire, + type AppElements, type AppElementsInterception, type AppElementsSlotBinding, } from "./app-elements.js"; import { matchOptimisticRouteManifestRoute } from "./app-optimistic-routing.js"; // Synthetic slot of an interception marker without an @slot wrapper. Its page -// renders as the owner's children, so Next.js reports it as the primary route. +// renders as the owner's children, which the committed source page reports. // Matches SIBLING_INTERCEPT_SLOT_NAME in routing/app-route-graph.ts. const SIBLING_INTERCEPT_SLOT_NAME = "__vinext_sibling_intercept"; type TransitionRouteState = Readonly<{ + elements: AppElements; interception: AppElementsInterception | null; - routeId: string; slotBindings: readonly AppElementsSlotBinding[]; }>; @@ -23,14 +25,6 @@ function isRouteGroupSegment(segment: string): boolean { return segment.startsWith("(") && segment.endsWith(")"); } -/** A manifest pattern part in source form: `:id` → `[id]`, `:slug+` → `[...slug]`. */ -function toSourceSegment(part: string): string { - if (!part.startsWith(":")) return part; - if (part.endsWith("+")) return `[...${part.slice(1, -1)}]`; - if (part.endsWith("*")) return `[[...${part.slice(1, -1)}]]`; - return `[${part.slice(1)}]`; -} - function joinSourcePath(segments: readonly string[]): string { return `/${segments.filter((segment) => segment.length > 0 && !isRouteGroupSegment(segment)).join("/")}`; } @@ -51,24 +45,18 @@ function matchManifestRoute( ); } -function resolveRouteSourcePath( - routePath: string, - routeManifest: BrowserRouteManifest | null, -): string { - const route = matchManifestRoute(routePath, routeManifest); - if (route === null) return routePath; - return joinSourcePath(route.patternParts.map(toSourceSegment)); -} - function resolveInterceptionSourcePagePath( - interception: AppElementsInterception, - interceptionId: string | null | undefined, + binding: AppElementsSlotBinding, + interception: AppElementsInterception | null, routeManifest: BrowserRouteManifest | null, ): string | null { if (routeManifest === null) return null; const graph = routeManifest.segmentGraph; - const byId = interceptionId ? graph.interceptions.get(interceptionId) : undefined; + // A merge can keep an intercepted slot from an earlier payload, so the + // binding's own interception id decides, not only the latest interception. + const byId = binding.interceptionId ? graph.interceptions.get(binding.interceptionId) : undefined; if (byId?.sourcePagePath) return byId.sourcePagePath; + if (interception === null || interception.slotId !== binding.slotId) return null; const targetParts = splitPathnameForRouteMatch(interception.targetMatchedUrl); const match = graph.interceptionsBySlotId .get(interception.slotId) @@ -76,6 +64,21 @@ function resolveInterceptionSourcePagePath( return match?.sourcePagePath ?? null; } +function treePathSegments(treePath: string): string[] { + return treePath.split("/").filter(Boolean); +} + +/** The committed source page's directory segments, or null on a route miss. */ +function sourcePageDirectory(sourcePage: string | null): string[] | null { + if (sourcePage === null) return null; + const segments = sourcePage.split("/").filter(Boolean); + return segments.at(-1) === "page" ? segments.slice(0, -1) : segments; +} + +function startsWithSegments(segments: readonly string[], prefix: readonly string[]): boolean { + return prefix.every((segment, index) => segments[index] === segment); +} + function resolveSlotSourcePath( binding: AppElementsSlotBinding, slotBase: readonly string[], @@ -102,8 +105,9 @@ function resolveSlotSourcePath( * The source route patterns of the committed App Router tree, as Next.js * reports them in `RouterTransitionStartEvent.fromRoutes`: the primary * (children) route first, then one entry per parallel slot, sorted. Route - * groups are omitted, a slot showing its default reports `@slot/default`, and - * an intercepted slot reports the intercepting page's directory. + * groups are omitted, a slot or children showing its default reports + * `.../default`, an intercepted slot reports the intercepting page's + * directory, and a URL that matched no route reports `/_not-found`. * * Ref: packages/next/src/client/components/router-transition.ts * (getActiveRoutePaths) @@ -112,20 +116,54 @@ export function resolveRouterTransitionFromRoutes( state: TransitionRouteState, routeManifest: BrowserRouteManifest | null, ): string[] { - const interception = state.interception; - const interceptionSlot = - interception === null ? null : AppElementsWire.parseElementKey(interception.slotId); - const siblingInterceptPath = - interception !== null && - interceptionSlot?.kind === "slot" && - interceptionSlot.name === SIBLING_INTERCEPT_SLOT_NAME - ? resolveInterceptionSourcePagePath(interception, null, routeManifest) - : null; + const metadata = AppElementsWire.readMetadata(state.elements); + const sourceSegments = sourcePageDirectory(metadata.sourcePage); + // A render of a whole intercepting route shows the owner's default as its + // children and the intercepting page in its one active slot. Its source page + // is the intercepting page's, without the slot's own segment. + const wholeInterceptedSlot = + metadata.wholeInterceptionSource === null + ? null + : (state.slotBindings.find((binding) => { + const slot = AppElementsWire.parseElementKey(binding.slotId); + return slot?.kind === "slot" && slot.name !== "children" && binding.state === "active"; + }) ?? null); - const primaryRoutePath = routePathFromId(interception?.sourceRouteId ?? state.routeId); - const primary = - siblingInterceptPath ?? - (primaryRoutePath === null ? null : resolveRouteSourcePath(primaryRoutePath, routeManifest)); + let primary: string; + let wholeInterceptedSlotPath: string | null = null; + if (sourceSegments === null) { + primary = "/_not-found"; + } else if (wholeInterceptedSlot !== null) { + const slot = AppElementsWire.parseElementKey(wholeInterceptedSlot.slotId); + const ownerSegments = slot?.kind === "slot" ? treePathSegments(slot.treePath) : []; + primary = joinSourcePath([...ownerSegments, "default"]); + if (slot?.kind === "slot") { + wholeInterceptedSlotPath = joinSourcePath([ + ...ownerSegments, + `@${slot.name}`, + ...sourceSegments.slice(ownerSegments.length), + ]); + } + } else { + // The deepest children slot above the page decides whether the children + // render its page or its default, as a synthetic parallel sub-route's do. + let children: { binding: AppElementsSlotBinding; owner: string[] } | null = null; + if (!rendersSiblingIntercept(metadata)) { + for (const binding of state.slotBindings) { + const slot = AppElementsWire.parseElementKey(binding.slotId); + if (slot?.kind !== "slot" || slot.name !== "children") continue; + const owner = treePathSegments(slot.treePath); + if (!startsWithSegments(sourceSegments, owner)) continue; + if (children === null || owner.length > children.owner.length) { + children = { binding, owner }; + } + } + } + primary = + children !== null && children.binding.state !== "active" + ? joinSourcePath([...children.owner, "default"]) + : joinSourcePath(sourceSegments); + } const slots: string[] = []; for (const binding of state.slotBindings) { @@ -137,16 +175,18 @@ export function resolveRouterTransitionFromRoutes( ) { continue; } - if (interception !== null && interception.slotId === binding.slotId) { - const intercepted = resolveInterceptionSourcePagePath( - interception, - binding.interceptionId, - routeManifest, - ); - if (intercepted !== null) { - slots.push(intercepted); - continue; - } + if (binding === wholeInterceptedSlot && wholeInterceptedSlotPath !== null) { + slots.push(wholeInterceptedSlotPath); + continue; + } + const intercepted = resolveInterceptionSourcePagePath( + binding, + state.interception, + routeManifest, + ); + if (intercepted !== null) { + slots.push(intercepted); + continue; } slots.push( resolveSlotSourcePath(binding, [...slot.treePath.split("/"), `@${slot.name}`], routeManifest), @@ -154,5 +194,5 @@ export function resolveRouterTransitionFromRoutes( } slots.sort((left, right) => left.localeCompare(right)); - return primary === null ? slots : [primary, ...slots]; + return [primary, ...slots]; } diff --git a/tests/app-browser-transition-routes.test.ts b/tests/app-browser-transition-routes.test.ts index 9d09660576..5b09b5b9bc 100644 --- a/tests/app-browser-transition-routes.test.ts +++ b/tests/app-browser-transition-routes.test.ts @@ -11,6 +11,11 @@ import { type BrowserRouteManifest, } from "../packages/vinext/src/routing/browser-route-manifest.js"; import { resolveRouterTransitionFromRoutes } from "../packages/vinext/src/server/app-browser-transition-routes.js"; +import { + AppElementsWire, + type AppElementsInterception, + type AppElementsSlotBinding, +} from "../packages/vinext/src/server/app-elements.js"; // The transition-events pages, scanned as their own app/ root. const APP_DIR = path.resolve( @@ -25,31 +30,150 @@ beforeAll(async () => { manifest = decodeBrowserRouteManifest(toBrowserRouteManifestWire(graph.routeManifest)); }); -function page(routePath: string) { - return { interception: null, routeId: `route:${routePath}`, slotBindings: [] }; +type CommittedTree = { + interception?: AppElementsInterception | null; + interceptionContext?: string | null; + slotBindings?: readonly AppElementsSlotBinding[]; + /** The committed source page, as the server renders it; null on a route miss. */ + sourcePage: string | null; + wholeInterceptionSource?: string | null; +}; + +// A committed router state, holding the metadata of the payload it rendered. +function committed(tree: CommittedTree) { + const interception = tree.interception ?? null; + const slotBindings = tree.slotBindings ?? []; + return { + elements: AppElementsWire.createMetadataEntries({ + interception, + interceptionContext: tree.interceptionContext ?? null, + layoutIds: [...new Set(slotBindings.flatMap((binding) => binding.ownerLayoutId ?? []))], + rootLayoutTreePath: "/", + routeId: "route:/ignored", + slotBindings, + sourcePage: tree.sourcePage, + wholeInterceptionSource: tree.wholeInterceptionSource ?? null, + }), + interception, + slotBindings, + }; +} + +function page(sourcePage: string) { + return committed({ sourcePage }); } describe("resolveRouterTransitionFromRoutes", () => { it("reports route patterns, without route groups", () => { - expect(resolveRouterTransitionFromRoutes(page("/"), manifest)).toEqual(["/"]); - expect(resolveRouterTransitionFromRoutes(page("/blog/hello"), manifest)).toEqual([ + expect(resolveRouterTransitionFromRoutes(page("/page"), manifest)).toEqual(["/"]); + expect(resolveRouterTransitionFromRoutes(page("/blog/[slug]/page"), manifest)).toEqual([ "/blog/[slug]", ]); - expect(resolveRouterTransitionFromRoutes(page("/about"), manifest)).toEqual(["/about"]); - expect(resolveRouterTransitionFromRoutes(page("/docs/a/b"), manifest)).toEqual([ + expect(resolveRouterTransitionFromRoutes(page("/(marketing)/about/page"), manifest)).toEqual([ + "/about", + ]); + expect(resolveRouterTransitionFromRoutes(page("/docs/[...slug]/page"), manifest)).toEqual([ "/docs/[...slug]", ]); - expect(resolveRouterTransitionFromRoutes(page("/shop"), manifest)).toEqual([ + expect(resolveRouterTransitionFromRoutes(page("/shop/[[...slug]]/page"), manifest)).toEqual([ "/shop/[[...slug]]", ]); }); + it("reports /_not-found for a URL that matched no route", () => { + expect(resolveRouterTransitionFromRoutes(committed({ sourcePage: null }), manifest)).toEqual([ + "/_not-found", + ]); + }); + + it("reports a sibling intercept's own page as the primary route", () => { + expect( + resolveRouterTransitionFromRoutes( + committed({ + interceptionContext: "/gallery", + slotBindings: [ + { + activeRouteId: "route:/gallery/photos/1", + ownerLayoutId: "layout:/gallery", + slotId: "slot:__vinext_sibling_intercept:/gallery", + state: "active", + }, + ], + sourcePage: "/gallery/(.)photos/[id]/page", + }), + manifest, + ), + ).toEqual(["/gallery/(.)photos/[id]"]); + }); + + it("reports the children default of a synthetic parallel sub-route", () => { + // /dashboard/settings matched only @analytics/settings, so the children + // render /dashboard/default, as Next.js's __DEFAULT__ segment reports it. + expect( + resolveRouterTransitionFromRoutes( + committed({ + slotBindings: [ + { + ownerLayoutId: "layout:/dashboard", + slotId: "slot:children:/dashboard", + state: "default", + }, + { + activeRouteId: "route:/dashboard/settings", + ownerLayoutId: "layout:/dashboard", + slotId: "slot:analytics:/dashboard", + state: "active", + }, + ], + sourcePage: "/dashboard/settings/page", + }), + manifest, + )[0], + ).toBe("/dashboard/default"); + // Active children render the page itself. + expect( + resolveRouterTransitionFromRoutes( + committed({ + slotBindings: [ + { + activeRouteId: "route:/dashboard", + ownerLayoutId: "layout:/dashboard", + slotId: "slot:children:/dashboard", + state: "active", + }, + ], + sourcePage: "/dashboard/page", + }), + manifest, + ), + ).toEqual(["/dashboard"]); + }); + + it("reports a whole intercepting route as the owner's default and the intercepted slot", () => { + expect( + resolveRouterTransitionFromRoutes( + committed({ + interceptionContext: "/gallery", + slotBindings: [ + { + activeRouteId: "route:/gallery/photos/1", + ownerLayoutId: "layout:/gallery", + slotId: "slot:modal:/gallery", + state: "active", + }, + ], + sourcePage: "/gallery/(.)photos/[id]/page", + wholeInterceptionSource: "/gallery", + }), + manifest, + ), + ).toEqual(["/gallery/default", "/gallery/@modal/(.)photos/[id]"]); + }); + it("puts the primary route first, then each slot", () => { expect( resolveRouterTransitionFromRoutes( - { - interception: null, - routeId: "route:/dashboard", + committed({ slotBindings: [ { activeRouteId: "route:/dashboard", @@ -58,7 +182,8 @@ describe("resolveRouterTransitionFromRoutes", () => { state: "active", }, ], - }, + sourcePage: "/dashboard/page", + }), manifest, ), ).toEqual(["/dashboard", "/dashboard/@analytics"]); @@ -67,13 +192,12 @@ describe("resolveRouterTransitionFromRoutes", () => { it("reports a slot showing its default as @slot/default", () => { expect( resolveRouterTransitionFromRoutes( - { - interception: null, - routeId: "route:/gallery", + committed({ slotBindings: [ { ownerLayoutId: "layout:/gallery", slotId: "slot:modal:/gallery", state: "default" }, ], - }, + sourcePage: "/gallery/page", + }), manifest, ), ).toEqual(["/gallery", "/gallery/@modal/default"]); @@ -95,25 +219,30 @@ describe("resolveRouterTransitionFromRoutes", () => { }; const expected = ["/gallery", "/gallery/@modal/(.)photos/[id]"]; + const interceptionId = "interception:slot:modal:/gallery:/gallery->/gallery/photos/:id"; + expect( resolveRouterTransitionFromRoutes( - { + committed({ interception, - routeId: "route:/gallery", - slotBindings: [ - { - ...binding, - interceptionId: "interception:slot:modal:/gallery:/gallery->/gallery/photos/:id", - }, - ], - }, + slotBindings: [{ ...binding, interceptionId }], + sourcePage: "/gallery/page", + }), manifest, ), ).toEqual(expected); // Without the binding's interception id, the target URL selects it. expect( resolveRouterTransitionFromRoutes( - { interception, routeId: "route:/gallery", slotBindings: [binding] }, + committed({ interception, slotBindings: [binding], sourcePage: "/gallery/page" }), + manifest, + ), + ).toEqual(expected); + // A merge keeps the intercepted slot after an ordinary payload clears the + // latest interception; its binding still names the interception. + expect( + resolveRouterTransitionFromRoutes( + committed({ slotBindings: [{ ...binding, interceptionId }], sourcePage: "/gallery/page" }), manifest, ), ).toEqual(expected); From edaaf0ea114da4d849354ecca77ced094b971f4f Mon Sep 17 00:00:00 2001 From: James Date: Thu, 26 Nov 2026 07:04:02 +0000 Subject: [PATCH 03/12] fix(instrumentation): keep the route manifest off the hydration path --- packages/vinext/src/server/app-browser-entry.ts | 9 +-------- .../vinext/src/server/app-browser-transition-routes.ts | 3 +++ 2 files changed, 4 insertions(+), 8 deletions(-) diff --git a/packages/vinext/src/server/app-browser-entry.ts b/packages/vinext/src/server/app-browser-entry.ts index 215affea1c..640989aff7 100644 --- a/packages/vinext/src/server/app-browser-entry.ts +++ b/packages/vinext/src/server/app-browser-entry.ts @@ -2126,7 +2126,7 @@ async function main(): Promise { if (!claimInitialAppRouterBootstrap()) return; // Fetch the RouteManifest chunk alongside bootstrap and hydration rather than // in the entry chunk. Navigations and prefetches wait for it before reading it. - const routeManifestLoad = loadNavigationRuntimeRouteManifest(); + void loadNavigationRuntimeRouteManifest(); if (hasServerActions) registerServerActionCallback(); installAppNavigationFailureListeners(); @@ -2154,13 +2154,6 @@ async function main(): Promise { // The recovery path reloads the document, which resets the "starting" claim; // this module instance is intentionally not eligible to retry bootstrap. if (rscStream === null) return; - // experimental.instrumentationClientRouterTransitionEvents: a transition - // reports the committed tree's slot and interception routes from the - // manifest, synchronously as it starts, so the manifest loads before - // hydration makes anything able to navigate. - if (process.env.__NEXT_INSTRUMENTATION_CLIENT_ROUTER_TRANSITION_EVENTS) { - await routeManifestLoad; - } bootstrapHydration(rscStream, devErrorOverlay, initialRscBootstrap); } diff --git a/packages/vinext/src/server/app-browser-transition-routes.ts b/packages/vinext/src/server/app-browser-transition-routes.ts index 62a15d4970..e035a0b73e 100644 --- a/packages/vinext/src/server/app-browser-transition-routes.ts +++ b/packages/vinext/src/server/app-browser-transition-routes.ts @@ -109,6 +109,9 @@ function resolveSlotSourcePath( * `.../default`, an intercepted slot reports the intercepting page's * directory, and a URL that matched no route reports `/_not-found`. * + * The route manifest loads alongside hydration, not before it. A transition + * that starts before it arrives reports an active slot as its slot directory. + * * Ref: packages/next/src/client/components/router-transition.ts * (getActiveRoutePaths) */ From 1d90ee383e68562ffaf51f09bec84e56d2561fad Mon Sep 17 00:00:00 2001 From: James Date: Thu, 26 Nov 2026 07:06:10 +0000 Subject: [PATCH 04/12] fix(instrumentation): give each hook its own start event and identify the whole-intercepted slot --- .../client/instrumentation-client-inject.ts | 12 +++- .../server/app-browser-transition-routes.ts | 67 +++++++++++++------ tests/app-browser-transition-routes.test.ts | 26 +++++++ tests/instrumentation.test.ts | 45 ++++++++++++- 4 files changed, 125 insertions(+), 25 deletions(-) diff --git a/packages/vinext/src/client/instrumentation-client-inject.ts b/packages/vinext/src/client/instrumentation-client-inject.ts index 51f8b99cc8..268bf36f5a 100644 --- a/packages/vinext/src/client/instrumentation-client-inject.ts +++ b/packages/vinext/src/client/instrumentation-client-inject.ts @@ -107,8 +107,16 @@ export function generateInstrumentationClientInjectModule( " index < __vinext_inject_modules.length", " ? __vinext_inject_hook(__vinext_inject_modules[index])", ` : { hooks: __vinj_${userSlot}, hook: __vinj_${userSlot}.onRouterTransitionStart };`, - " // Reflect.apply calls the hook itself, even if it overrides call.", - " if (hook != null) Reflect.apply(hook, hooks, [url, type, event]);", + " // Next.js builds the start event per hook, so one hook's mutation", + " // never reaches the next. Reflect.apply calls the hook itself, even", + " // if it overrides call.", + " if (hook != null) {", + " Reflect.apply(hook, hooks, [", + " url,", + " type,", + " event == null ? event : { ...event, fromRoutes: [...event.fromRoutes] },", + " ]);", + " }", " } catch (error) {", ` console.error(${JSON.stringify(INSTRUMENTATION_CLIENT_HOOK_FAILED_MESSAGE)}, error);`, " }", diff --git a/packages/vinext/src/server/app-browser-transition-routes.ts b/packages/vinext/src/server/app-browser-transition-routes.ts index e035a0b73e..fff8363441 100644 --- a/packages/vinext/src/server/app-browser-transition-routes.ts +++ b/packages/vinext/src/server/app-browser-transition-routes.ts @@ -101,6 +101,41 @@ function resolveSlotSourcePath( return joinSourcePath([...slotBase, "default"]); } +type WholeInterceptedSlot = { + binding: AppElementsSlotBinding; + ownerSegments: string[]; + path: string; +}; + +function resolveWholeInterceptedSlot( + bindings: readonly AppElementsSlotBinding[], + sourceSegments: readonly string[], + routeManifest: BrowserRouteManifest | null, +): WholeInterceptedSlot | null { + const candidates: WholeInterceptedSlot[] = []; + for (const binding of bindings) { + const slot = AppElementsWire.parseElementKey(binding.slotId); + if (slot?.kind !== "slot" || slot.name === "children" || binding.state !== "active") continue; + const ownerSegments = treePathSegments(slot.treePath); + if (!startsWithSegments(sourceSegments, ownerSegments)) continue; + const path = joinSourcePath([ + ...ownerSegments, + `@${slot.name}`, + ...sourceSegments.slice(ownerSegments.length), + ]); + candidates.push({ binding, ownerSegments, path }); + } + return ( + candidates.find((candidate) => + routeManifest?.segmentGraph.interceptionsBySlotId + .get(candidate.binding.slotId) + ?.some((interception) => interception.sourcePagePath === candidate.path), + ) ?? + candidates[0] ?? + null + ); +} + /** * The source route patterns of the committed App Router tree, as Next.js * reports them in `RouterTransitionStartEvent.fromRoutes`: the primary @@ -122,31 +157,19 @@ export function resolveRouterTransitionFromRoutes( const metadata = AppElementsWire.readMetadata(state.elements); const sourceSegments = sourcePageDirectory(metadata.sourcePage); // A render of a whole intercepting route shows the owner's default as its - // children and the intercepting page in its one active slot. Its source page - // is the intercepting page's, without the slot's own segment. - const wholeInterceptedSlot = - metadata.wholeInterceptionSource === null + // children and the intercepting page in its slot. Its source page is the + // intercepting page's, without the slot's own segment. A merge can keep + // another active slot, so the manifest's interceptions pick the slot. + const wholeIntercepted = + metadata.wholeInterceptionSource === null || sourceSegments === null ? null - : (state.slotBindings.find((binding) => { - const slot = AppElementsWire.parseElementKey(binding.slotId); - return slot?.kind === "slot" && slot.name !== "children" && binding.state === "active"; - }) ?? null); + : resolveWholeInterceptedSlot(state.slotBindings, sourceSegments, routeManifest); let primary: string; - let wholeInterceptedSlotPath: string | null = null; if (sourceSegments === null) { primary = "/_not-found"; - } else if (wholeInterceptedSlot !== null) { - const slot = AppElementsWire.parseElementKey(wholeInterceptedSlot.slotId); - const ownerSegments = slot?.kind === "slot" ? treePathSegments(slot.treePath) : []; - primary = joinSourcePath([...ownerSegments, "default"]); - if (slot?.kind === "slot") { - wholeInterceptedSlotPath = joinSourcePath([ - ...ownerSegments, - `@${slot.name}`, - ...sourceSegments.slice(ownerSegments.length), - ]); - } + } else if (wholeIntercepted !== null) { + primary = joinSourcePath([...wholeIntercepted.ownerSegments, "default"]); } else { // The deepest children slot above the page decides whether the children // render its page or its default, as a synthetic parallel sub-route's do. @@ -178,8 +201,8 @@ export function resolveRouterTransitionFromRoutes( ) { continue; } - if (binding === wholeInterceptedSlot && wholeInterceptedSlotPath !== null) { - slots.push(wholeInterceptedSlotPath); + if (binding === wholeIntercepted?.binding) { + slots.push(wholeIntercepted.path); continue; } const intercepted = resolveInterceptionSourcePagePath( diff --git a/tests/app-browser-transition-routes.test.ts b/tests/app-browser-transition-routes.test.ts index 5b09b5b9bc..2240e1091e 100644 --- a/tests/app-browser-transition-routes.test.ts +++ b/tests/app-browser-transition-routes.test.ts @@ -168,6 +168,32 @@ describe("resolveRouterTransitionFromRoutes", () => { manifest, ), ).toEqual(["/gallery/default", "/gallery/@modal/(.)photos/[id]"]); + // A merge kept an active @aside, which sorts before @modal; the manifest's + // interceptions still identify @modal as the intercepted slot. + expect( + resolveRouterTransitionFromRoutes( + committed({ + interceptionContext: "/gallery", + slotBindings: [ + { + activeRouteId: "route:/gallery", + ownerLayoutId: "layout:/gallery", + slotId: "slot:aside:/gallery", + state: "active", + }, + { + activeRouteId: "route:/gallery/photos/1", + ownerLayoutId: "layout:/gallery", + slotId: "slot:modal:/gallery", + state: "active", + }, + ], + sourcePage: "/gallery/(.)photos/[id]/page", + wholeInterceptionSource: "/gallery", + }), + manifest, + ), + ).toEqual(["/gallery/default", "/gallery/@aside", "/gallery/@modal/(.)photos/[id]"]); }); it("puts the primary route first, then each slot", () => { diff --git a/tests/instrumentation.test.ts b/tests/instrumentation.test.ts index 2fb43a0aa1..d542cc0986 100644 --- a/tests/instrumentation.test.ts +++ b/tests/instrumentation.test.ts @@ -882,7 +882,7 @@ describe("generateInstrumentationClientInjectModule", () => { const code = generateInstrumentationClientInjectModule(["./inject-a.js"], null); expect(code).toContain('import * as __vinj_0 from "./inject-a.js"'); expect(code).toContain("export function onRouterTransitionStart(url, type, event)"); - expect(code).toContain("Reflect.apply(hook, hooks, [url, type, event]);"); + expect(code).toContain("Reflect.apply(hook, hooks, ["); }); it("generates imports in config order with user file last", () => { @@ -978,6 +978,49 @@ export default { onRouterTransitionStart() { globalThis.__vinextInjectCalls.push } }); + // Next.js builds the start event inside each callHooks invocation + // (client/components/router-transition.ts startRouterTransition). + it("gives each hook its own start event", async () => { + const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "vinext-inject-event-")); + try { + fs.writeFileSync( + path.join(tmpDir, "mutates.mjs"), + `export function onRouterTransitionStart(url, type, event) { + event.id = "changed"; + event.fromRoutes.push("/mutated"); +} +`, + ); + fs.writeFileSync( + path.join(tmpDir, "user.mjs"), + `export function onRouterTransitionStart(url, type, event) { + globalThis.__vinextInjectEvents.push(event); +} +`, + ); + const entryPath = path.join(tmpDir, "entry.mjs"); + fs.writeFileSync( + entryPath, + generateInstrumentationClientInjectModule(["./mutates.mjs"], "./user.mjs"), + ); + const events: unknown[] = []; + (globalThis as { __vinextInjectEvents?: unknown[] }).__vinextInjectEvents = events; + const mod = (await import(pathToFileURL(entryPath).href)) as { + onRouterTransitionStart: (url: string, type: string, event: unknown) => void; + }; + const event = { id: "1", timestamp: 1, fromRoutes: ["/"], prefetchIntent: "auto" }; + + mod.onRouterTransitionStart("/a", "push", event); + + expect(events).toEqual([event]); + expect(events[0]).not.toBe(event); + expect(event).toEqual({ id: "1", timestamp: 1, fromRoutes: ["/"], prefetchIntent: "auto" }); + } finally { + delete (globalThis as { __vinextInjectEvents?: unknown[] }).__vinextInjectEvents; + fs.rmSync(tmpDir, { recursive: true, force: true }); + } + }); + // Next.js reads each module's hook inside callHooks' per-module try // (client/components/router-transition.ts). it("isolates a CommonJS inject whose hook export is a throwing getter", async () => { From 743313132cab7b5f07b67ba9a3dda1215ca20efd Mon Sep 17 00:00:00 2001 From: James Date: Thu, 26 Nov 2026 07:13:49 +0000 Subject: [PATCH 05/12] fix(instrumentation): read an active slot's route by its manifest id --- .../server/app-browser-transition-routes.ts | 6 ++- tests/app-browser-transition-routes.test.ts | 52 +++++++++++++++++++ 2 files changed, 57 insertions(+), 1 deletion(-) diff --git a/packages/vinext/src/server/app-browser-transition-routes.ts b/packages/vinext/src/server/app-browser-transition-routes.ts index fff8363441..1fa497f117 100644 --- a/packages/vinext/src/server/app-browser-transition-routes.ts +++ b/packages/vinext/src/server/app-browser-transition-routes.ts @@ -87,9 +87,13 @@ function resolveSlotSourcePath( if (binding.state !== "active" || binding.activeRouteId == null) { return joinSourcePath([...slotBase, "default"]); } + // An ordinary slot's active route id is the manifest route id (`route:` + // plus its pattern). Only an id that isn't one, such as a concrete + // interception target, is matched as a URL. const activeRoutePath = routePathFromId(binding.activeRouteId); const activeRoute = - activeRoutePath === null ? null : matchManifestRoute(activeRoutePath, routeManifest); + routeManifest?.segmentGraph.routes.get(binding.activeRouteId) ?? + (activeRoutePath === null ? null : matchManifestRoute(activeRoutePath, routeManifest)); const manifestBinding = activeRoute === null ? undefined diff --git a/tests/app-browser-transition-routes.test.ts b/tests/app-browser-transition-routes.test.ts index 2240e1091e..82090278d6 100644 --- a/tests/app-browser-transition-routes.test.ts +++ b/tests/app-browser-transition-routes.test.ts @@ -229,6 +229,58 @@ describe("resolveRouterTransitionFromRoutes", () => { ).toEqual(["/gallery", "/gallery/@modal/default"]); }); + it("reads an active slot's route by its manifest id, not as a URL", () => { + // As a URL, the catch-all's id "/shop/:slug*" is one segment, which a + // sibling /shop/:id would match first and report its default slot. + const catchAll = manifest.segmentGraph.routes.get("route:/shop/:slug*"); + expect(catchAll).toBeDefined(); + const slotId = "slot:panel:/shop"; + const binding = (routeId: string, state: "active" | "default") => ({ + id: `${routeId}::${slotId}`, + ownerLayoutId: null, + routeId, + routeSegments: state === "active" ? ["[[...slug]]"] : null, + slotId, + slotPatternParts: null, + state, + }); + const withSibling = { + ...manifest, + segmentGraph: { + ...manifest.segmentGraph, + routes: new Map([ + ...manifest.segmentGraph.routes, + [ + "route:/shop/:id", + { + ...catchAll!, + id: "route:/shop/:id", + paramNames: ["id"], + patternParts: ["shop", ":id"], + }, + ], + ]), + slotBindings: new Map([ + ...manifest.segmentGraph.slotBindings, + [`route:/shop/:slug*::${slotId}`, binding("route:/shop/:slug*", "active")], + [`route:/shop/:id::${slotId}`, binding("route:/shop/:id", "default")], + ]), + }, + } as BrowserRouteManifest; + + expect( + resolveRouterTransitionFromRoutes( + committed({ + slotBindings: [ + { activeRouteId: "route:/shop/:slug*", ownerLayoutId: null, slotId, state: "active" }, + ], + sourcePage: "/shop/[[...slug]]/page", + }), + withSibling, + ), + ).toEqual(["/shop/[[...slug]]", "/shop/@panel/[[...slug]]"]); + }); + it("reports the intercepting page for an intercepted slot", () => { const interception = { sourceMatchedUrl: "/gallery", From 24ae79c9918f2ac3880c44ba40827ee4deb2c354 Mon Sep 17 00:00:00 2001 From: James Date: Thu, 26 Nov 2026 07:21:34 +0000 Subject: [PATCH 06/12] test(instrumentation): type the sibling-route manifest fixture --- tests/app-browser-transition-routes.test.ts | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/tests/app-browser-transition-routes.test.ts b/tests/app-browser-transition-routes.test.ts index 82090278d6..9876f8e1f3 100644 --- a/tests/app-browser-transition-routes.test.ts +++ b/tests/app-browser-transition-routes.test.ts @@ -24,6 +24,10 @@ const APP_DIR = path.resolve( ); let manifest: BrowserRouteManifest; +type ManifestSlotBinding = + BrowserRouteManifest["segmentGraph"]["slotBindings"] extends ReadonlyMap + ? Binding + : never; beforeAll(async () => { const graph = await appRouteGraph(APP_DIR); @@ -235,13 +239,12 @@ describe("resolveRouterTransitionFromRoutes", () => { const catchAll = manifest.segmentGraph.routes.get("route:/shop/:slug*"); expect(catchAll).toBeDefined(); const slotId = "slot:panel:/shop"; - const binding = (routeId: string, state: "active" | "default") => ({ + const binding = (routeId: string, state: "active" | "default"): ManifestSlotBinding => ({ id: `${routeId}::${slotId}`, ownerLayoutId: null, routeId, routeSegments: state === "active" ? ["[[...slug]]"] : null, slotId, - slotPatternParts: null, state, }); const withSibling = { From 538b466345b6f3442dc5ba7a3626b9e13d4dc510 Mon Sep 17 00:00:00 2001 From: James Date: Thu, 26 Nov 2026 07:28:56 +0000 Subject: [PATCH 07/12] fix(instrumentation): name nested slots of a whole interception and sample each hook's timestamp --- .../client/instrumentation-client-inject.ts | 14 +++++-- .../server/app-browser-transition-routes.ts | 42 ++++++++++++------- tests/app-browser-transition-routes.test.ts | 28 +++++++++++++ tests/instrumentation.test.ts | 16 +++++-- 4 files changed, 77 insertions(+), 23 deletions(-) diff --git a/packages/vinext/src/client/instrumentation-client-inject.ts b/packages/vinext/src/client/instrumentation-client-inject.ts index 268bf36f5a..901da7d0de 100644 --- a/packages/vinext/src/client/instrumentation-client-inject.ts +++ b/packages/vinext/src/client/instrumentation-client-inject.ts @@ -107,14 +107,20 @@ export function generateInstrumentationClientInjectModule( " index < __vinext_inject_modules.length", " ? __vinext_inject_hook(__vinext_inject_modules[index])", ` : { hooks: __vinj_${userSlot}, hook: __vinj_${userSlot}.onRouterTransitionStart };`, - " // Next.js builds the start event per hook, so one hook's mutation", - " // never reaches the next. Reflect.apply calls the hook itself, even", - " // if it overrides call.", + " // Next.js builds the start event per hook, sampling its timestamp", + " // then, so one hook's mutation never reaches the next. Reflect.apply", + " // calls the hook itself, even if it overrides call.", " if (hook != null) {", " Reflect.apply(hook, hooks, [", " url,", " type,", - " event == null ? event : { ...event, fromRoutes: [...event.fromRoutes] },", + " event == null", + " ? event", + " : {", + " ...event,", + " timestamp: performance.timeOrigin + performance.now(),", + " fromRoutes: [...event.fromRoutes],", + " },", " ]);", " }", " } catch (error) {", diff --git a/packages/vinext/src/server/app-browser-transition-routes.ts b/packages/vinext/src/server/app-browser-transition-routes.ts index 1fa497f117..31e9caeebb 100644 --- a/packages/vinext/src/server/app-browser-transition-routes.ts +++ b/packages/vinext/src/server/app-browser-transition-routes.ts @@ -111,33 +111,43 @@ type WholeInterceptedSlot = { path: string; }; +function withoutSlotSegments(sourcePagePath: string): string { + return joinSourcePath(sourcePagePath.split("/").filter((segment) => !segment.startsWith("@"))); +} + function resolveWholeInterceptedSlot( bindings: readonly AppElementsSlotBinding[], sourceSegments: readonly string[], routeManifest: BrowserRouteManifest | null, ): WholeInterceptedSlot | null { - const candidates: WholeInterceptedSlot[] = []; + const sourcePath = joinSourcePath(sourceSegments); + let fallback: WholeInterceptedSlot | null = null; for (const binding of bindings) { const slot = AppElementsWire.parseElementKey(binding.slotId); if (slot?.kind !== "slot" || slot.name === "children" || binding.state !== "active") continue; const ownerSegments = treePathSegments(slot.treePath); if (!startsWithSegments(sourceSegments, ownerSegments)) continue; - const path = joinSourcePath([ - ...ownerSegments, - `@${slot.name}`, - ...sourceSegments.slice(ownerSegments.length), - ]); - candidates.push({ binding, ownerSegments, path }); + // The manifest's source page path names every slot between the + // intercepting route and its page, which the source page leaves out. + const sourcePagePath = routeManifest?.segmentGraph.interceptionsBySlotId + .get(binding.slotId) + ?.find( + (interception) => + interception.sourcePagePath !== undefined && + withoutSlotSegments(interception.sourcePagePath) === sourcePath, + )?.sourcePagePath; + if (sourcePagePath !== undefined) return { binding, ownerSegments, path: sourcePagePath }; + fallback ??= { + binding, + ownerSegments, + path: joinSourcePath([ + ...ownerSegments, + `@${slot.name}`, + ...sourceSegments.slice(ownerSegments.length), + ]), + }; } - return ( - candidates.find((candidate) => - routeManifest?.segmentGraph.interceptionsBySlotId - .get(candidate.binding.slotId) - ?.some((interception) => interception.sourcePagePath === candidate.path), - ) ?? - candidates[0] ?? - null - ); + return fallback; } /** diff --git a/tests/app-browser-transition-routes.test.ts b/tests/app-browser-transition-routes.test.ts index 9876f8e1f3..d4c896e772 100644 --- a/tests/app-browser-transition-routes.test.ts +++ b/tests/app-browser-transition-routes.test.ts @@ -200,6 +200,34 @@ describe("resolveRouterTransitionFromRoutes", () => { ).toEqual(["/gallery/default", "/gallery/@aside", "/gallery/@modal/(.)photos/[id]"]); }); + it("reports every slot of a whole intercepting route nested through slots", async () => { + // @modal/(.)test-nested renders its page through its own @sidebar slot. + const graph = await appRouteGraph( + path.resolve(import.meta.dirname, "fixtures/app-basic/app/interception-dyn-seg"), + ); + const nestedManifest = decodeBrowserRouteManifest( + toBrowserRouteManifestWire(graph.routeManifest), + ); + expect( + resolveRouterTransitionFromRoutes( + committed({ + interceptionContext: "/", + slotBindings: [ + { + activeRouteId: "route:/test-nested", + ownerLayoutId: "layout:/", + slotId: "slot:modal:/", + state: "active", + }, + ], + sourcePage: "/(.)test-nested/page", + wholeInterceptionSource: "/", + }), + nestedManifest, + ), + ).toEqual(["/default", "/@modal/(.)test-nested/@sidebar"]); + }); + it("puts the primary route first, then each slot", () => { expect( resolveRouterTransitionFromRoutes( diff --git a/tests/instrumentation.test.ts b/tests/instrumentation.test.ts index d542cc0986..0a6c55d83d 100644 --- a/tests/instrumentation.test.ts +++ b/tests/instrumentation.test.ts @@ -986,6 +986,7 @@ export default { onRouterTransitionStart() { globalThis.__vinextInjectCalls.push fs.writeFileSync( path.join(tmpDir, "mutates.mjs"), `export function onRouterTransitionStart(url, type, event) { + globalThis.__vinextInjectEvents.push({ ...event, fromRoutes: [...event.fromRoutes] }); event.id = "changed"; event.fromRoutes.push("/mutated"); } @@ -1009,11 +1010,20 @@ export default { onRouterTransitionStart() { globalThis.__vinextInjectCalls.push onRouterTransitionStart: (url: string, type: string, event: unknown) => void; }; const event = { id: "1", timestamp: 1, fromRoutes: ["/"], prefetchIntent: "auto" }; + // Each hook's event samples its own timestamp, as Next.js's does. + let now = 0; + const nowSpy = vi.spyOn(performance, "now").mockImplementation(() => (now += 10)); - mod.onRouterTransitionStart("/a", "push", event); + try { + mod.onRouterTransitionStart("/a", "push", event); + } finally { + nowSpy.mockRestore(); + } - expect(events).toEqual([event]); - expect(events[0]).not.toBe(event); + expect(events).toEqual([ + { ...event, timestamp: performance.timeOrigin + 10 }, + { ...event, timestamp: performance.timeOrigin + 20 }, + ]); expect(event).toEqual({ id: "1", timestamp: 1, fromRoutes: ["/"], prefetchIntent: "auto" }); } finally { delete (globalThis as { __vinextInjectEvents?: unknown[] }).__vinextInjectEvents; From 117fad3a0925e9a328e277d11e03bd6df131b98c Mon Sep 17 00:00:00 2001 From: James Date: Thu, 26 Nov 2026 07:47:04 +0000 Subject: [PATCH 08/12] fix(instrumentation): drop the inject event copy without the flag and omit children a layout doesn't declare --- .../client/instrumentation-client-inject.ts | 5 ++-- .../server/app-browser-transition-routes.ts | 14 ++++++---- tests/app-browser-transition-routes.test.ts | 28 +++++++++++++++++++ tests/instrumentation.test.ts | 27 ++++++++++++++++-- 4 files changed, 65 insertions(+), 9 deletions(-) diff --git a/packages/vinext/src/client/instrumentation-client-inject.ts b/packages/vinext/src/client/instrumentation-client-inject.ts index 901da7d0de..e7a87eab9c 100644 --- a/packages/vinext/src/client/instrumentation-client-inject.ts +++ b/packages/vinext/src/client/instrumentation-client-inject.ts @@ -108,13 +108,14 @@ export function generateInstrumentationClientInjectModule( " ? __vinext_inject_hook(__vinext_inject_modules[index])", ` : { hooks: __vinj_${userSlot}, hook: __vinj_${userSlot}.onRouterTransitionStart };`, " // Next.js builds the start event per hook, sampling its timestamp", - " // then, so one hook's mutation never reaches the next. Reflect.apply", + " // then, so one hook's mutation never reaches the next. The flag check", + " // drops the event copy from builds without the flag. Reflect.apply", " // calls the hook itself, even if it overrides call.", " if (hook != null) {", " Reflect.apply(hook, hooks, [", " url,", " type,", - " event == null", + " event == null || !process.env.__NEXT_INSTRUMENTATION_CLIENT_ROUTER_TRANSITION_EVENTS", " ? event", " : {", " ...event,", diff --git a/packages/vinext/src/server/app-browser-transition-routes.ts b/packages/vinext/src/server/app-browser-transition-routes.ts index 31e9caeebb..15ba3c8b7a 100644 --- a/packages/vinext/src/server/app-browser-transition-routes.ts +++ b/packages/vinext/src/server/app-browser-transition-routes.ts @@ -179,7 +179,7 @@ export function resolveRouterTransitionFromRoutes( ? null : resolveWholeInterceptedSlot(state.slotBindings, sourceSegments, routeManifest); - let primary: string; + let primary: string | null; if (sourceSegments === null) { primary = "/_not-found"; } else if (wholeIntercepted !== null) { @@ -199,10 +199,14 @@ export function resolveRouterTransitionFromRoutes( } } } + // A layout composed only of named slots has no children branch, so the + // route reports only its slots (Next.js explicitParallelRouteChildren). primary = - children !== null && children.binding.state !== "active" - ? joinSourcePath([...children.owner, "default"]) - : joinSourcePath(sourceSegments); + children === null || children.binding.state === "active" + ? joinSourcePath(sourceSegments) + : children.binding.state === "unmatched" + ? null + : joinSourcePath([...children.owner, "default"]); } const slots: string[] = []; @@ -234,5 +238,5 @@ export function resolveRouterTransitionFromRoutes( } slots.sort((left, right) => left.localeCompare(right)); - return [primary, ...slots]; + return primary === null ? slots : [primary, ...slots]; } diff --git a/tests/app-browser-transition-routes.test.ts b/tests/app-browser-transition-routes.test.ts index d4c896e772..3932799e3d 100644 --- a/tests/app-browser-transition-routes.test.ts +++ b/tests/app-browser-transition-routes.test.ts @@ -153,6 +153,34 @@ describe("resolveRouterTransitionFromRoutes", () => { ).toEqual(["/dashboard"]); }); + it("reports only the slots of a layout composed only of named slots", async () => { + // parallel-nested/home declares no children: its route renders through + // @parallelB, so Next.js's tree has no children branch to report. + const graph = await appRouteGraph( + path.resolve(import.meta.dirname, "fixtures/app-basic/app/parallel-nested"), + ); + const namedSlotsManifest = decodeBrowserRouteManifest( + toBrowserRouteManifestWire(graph.routeManifest), + ); + expect( + resolveRouterTransitionFromRoutes( + committed({ + slotBindings: [ + { ownerLayoutId: "layout:/home", slotId: "slot:children:/home", state: "unmatched" }, + { + activeRouteId: "route:/home/nested", + ownerLayoutId: "layout:/home", + slotId: "slot:parallelB:/home", + state: "active", + }, + ], + sourcePage: "/home/nested/page", + }), + namedSlotsManifest, + ), + ).toEqual(["/home/@parallelB/nested"]); + }); + it("reports a whole intercepting route as the owner's default and the intercepted slot", () => { expect( resolveRouterTransitionFromRoutes( diff --git a/tests/instrumentation.test.ts b/tests/instrumentation.test.ts index 0a6c55d83d..2183c861fb 100644 --- a/tests/instrumentation.test.ts +++ b/tests/instrumentation.test.ts @@ -4,7 +4,7 @@ import os from "node:os"; import path from "node:path"; import { pathToFileURL } from "node:url"; import * as Sentry from "@sentry/nextjs"; -import { createServer, parseAst } from "vite-plus"; +import { createServer, minifySync, parseAst } from "vite-plus"; import vinext from "../packages/vinext/src/index.js"; import { findInstrumentationClientFile, @@ -870,6 +870,15 @@ describe("instrumentationClientInject plugin pipeline", () => { }); }); +// Applies the client define vinext sets for +// experimental.instrumentationClientRouterTransitionEvents. +function withTransitionEventsFlag(code: string, enabled: boolean): string { + return code.replaceAll( + "process.env.__NEXT_INSTRUMENTATION_CLIENT_ROUTER_TRANSITION_EVENTS", + JSON.stringify(enabled), + ); +} + describe("generateInstrumentationClientInjectModule", () => { it("returns passthrough when injects is empty (userPath ignored)", () => { expect(generateInstrumentationClientInjectModule([], null)).toBe("export {};"); @@ -978,6 +987,17 @@ export default { onRouterTransitionStart() { globalThis.__vinextInjectCalls.push } }); + // Ported from Next.js: test/production/app-dir/instrumentation-client-dce/instrumentation-client-dce.test.ts + // https://github.com/vercel/next.js/blob/v16.4.6/test/production/app-dir/instrumentation-client-dce/instrumentation-client-dce.test.ts + it("drops the start event copy from builds without the transition events flag", () => { + const code = generateInstrumentationClientInjectModule(["./inject-a.js"], null); + const minified = (enabled: boolean) => + minifySync("inject.mjs", withTransitionEventsFlag(code, enabled)).code; + + expect(minified(true)).toContain("fromRoutes"); + expect(minified(false)).not.toContain("fromRoutes"); + }); + // Next.js builds the start event inside each callHooks invocation // (client/components/router-transition.ts startRouterTransition). it("gives each hook its own start event", async () => { @@ -1002,7 +1022,10 @@ export default { onRouterTransitionStart() { globalThis.__vinextInjectCalls.push const entryPath = path.join(tmpDir, "entry.mjs"); fs.writeFileSync( entryPath, - generateInstrumentationClientInjectModule(["./mutates.mjs"], "./user.mjs"), + withTransitionEventsFlag( + generateInstrumentationClientInjectModule(["./mutates.mjs"], "./user.mjs"), + true, + ), ); const events: unknown[] = []; (globalThis as { __vinextInjectEvents?: unknown[] }).__vinextInjectEvents = events; From 99f24bacc6619f2ddc98be01b34edd54da3e9141 Mon Sep 17 00:00:00 2001 From: James Date: Thu, 26 Nov 2026 07:54:48 +0000 Subject: [PATCH 09/12] fix(instrumentation): report the children route a slot-only navigation kept --- .../server/app-browser-transition-routes.ts | 21 ++++++++++++---- tests/app-browser-transition-routes.test.ts | 25 ++++++++++++++++++- 2 files changed, 40 insertions(+), 6 deletions(-) diff --git a/packages/vinext/src/server/app-browser-transition-routes.ts b/packages/vinext/src/server/app-browser-transition-routes.ts index 15ba3c8b7a..bb3537ca76 100644 --- a/packages/vinext/src/server/app-browser-transition-routes.ts +++ b/packages/vinext/src/server/app-browser-transition-routes.ts @@ -1,5 +1,6 @@ import type { BrowserRouteManifest } from "../routing/browser-route-manifest.js"; import { matchRoutePattern } from "../routing/route-pattern.js"; +import { patternToNextFormat } from "../routing/route-validation.js"; import { splitPathnameForRouteMatch } from "../routing/utils.js"; import { rendersSiblingIntercept } from "./app-browser-state.js"; import { @@ -201,12 +202,22 @@ export function resolveRouterTransitionFromRoutes( } // A layout composed only of named slots has no children branch, so the // route reports only its slots (Next.js explicitParallelRouteChildren). + // A slot-only navigation keeps the children branch that was showing, so + // its binding, not the latest payload's source page, names that route. + const childrenRoutePath = + children?.binding.state === "active" && + children.binding.activeRouteId != null && + children.binding.activeRouteId !== metadata.routeId + ? routePathFromId(children.binding.activeRouteId) + : null; primary = - children === null || children.binding.state === "active" - ? joinSourcePath(sourceSegments) - : children.binding.state === "unmatched" - ? null - : joinSourcePath([...children.owner, "default"]); + childrenRoutePath !== null + ? patternToNextFormat(childrenRoutePath) + : children === null || children.binding.state === "active" + ? joinSourcePath(sourceSegments) + : children.binding.state === "unmatched" + ? null + : joinSourcePath([...children.owner, "default"]); } const slots: string[] = []; diff --git a/tests/app-browser-transition-routes.test.ts b/tests/app-browser-transition-routes.test.ts index 3932799e3d..7103d8a046 100644 --- a/tests/app-browser-transition-routes.test.ts +++ b/tests/app-browser-transition-routes.test.ts @@ -37,6 +37,7 @@ beforeAll(async () => { type CommittedTree = { interception?: AppElementsInterception | null; interceptionContext?: string | null; + routeId?: string; slotBindings?: readonly AppElementsSlotBinding[]; /** The committed source page, as the server renders it; null on a route miss. */ sourcePage: string | null; @@ -53,7 +54,7 @@ function committed(tree: CommittedTree) { interceptionContext: tree.interceptionContext ?? null, layoutIds: [...new Set(slotBindings.flatMap((binding) => binding.ownerLayoutId ?? []))], rootLayoutTreePath: "/", - routeId: "route:/ignored", + routeId: tree.routeId ?? "route:/ignored", slotBindings, sourcePage: tree.sourcePage, wholeInterceptionSource: tree.wholeInterceptionSource ?? null, @@ -153,6 +154,28 @@ describe("resolveRouterTransitionFromRoutes", () => { ).toEqual(["/dashboard"]); }); + it("reports the children route a slot-only navigation kept", () => { + // /parallel-layouts/settings -> /parallel-layouts/modal keeps the settings + // children branch; the merged metadata is the modal payload's. + expect( + resolveRouterTransitionFromRoutes( + committed({ + routeId: "route:/some-page", + slotBindings: [ + { + activeRouteId: "route:/blog/:slug", + ownerLayoutId: "layout:/", + slotId: "slot:children:/", + state: "active", + }, + ], + sourcePage: "/some-page/page", + }), + manifest, + ), + ).toEqual(["/blog/[slug]"]); + }); + it("reports only the slots of a layout composed only of named slots", async () => { // parallel-nested/home declares no children: its route renders through // @parallelB, so Next.js's tree has no children branch to report. From 507e9521dc9586c2a8997a616ebbac730d686898 Mon Sep 17 00:00:00 2001 From: James Date: Thu, 26 Nov 2026 08:03:32 +0000 Subject: [PATCH 10/12] fix(instrumentation): resolve a kept children route's pattern through the manifest --- .../server/app-browser-transition-routes.ts | 30 ++++++++++++------- tests/app-browser-transition-routes.test.ts | 3 +- 2 files changed, 21 insertions(+), 12 deletions(-) diff --git a/packages/vinext/src/server/app-browser-transition-routes.ts b/packages/vinext/src/server/app-browser-transition-routes.ts index bb3537ca76..83ff6fb0f1 100644 --- a/packages/vinext/src/server/app-browser-transition-routes.ts +++ b/packages/vinext/src/server/app-browser-transition-routes.ts @@ -46,6 +46,17 @@ function matchManifestRoute( ); } +/** A route id's manifest route: by id, or else its concrete URL matched. */ +function resolveManifestRoute( + routeId: string, + routeManifest: BrowserRouteManifest | null, +): { id: string; patternParts: readonly string[] } | null { + const direct = routeManifest?.segmentGraph.routes.get(routeId); + if (direct) return direct; + const routePath = routePathFromId(routeId); + return routePath === null ? null : matchManifestRoute(routePath, routeManifest); +} + function resolveInterceptionSourcePagePath( binding: AppElementsSlotBinding, interception: AppElementsInterception | null, @@ -88,13 +99,9 @@ function resolveSlotSourcePath( if (binding.state !== "active" || binding.activeRouteId == null) { return joinSourcePath([...slotBase, "default"]); } - // An ordinary slot's active route id is the manifest route id (`route:` - // plus its pattern). Only an id that isn't one, such as a concrete - // interception target, is matched as a URL. - const activeRoutePath = routePathFromId(binding.activeRouteId); - const activeRoute = - routeManifest?.segmentGraph.routes.get(binding.activeRouteId) ?? - (activeRoutePath === null ? null : matchManifestRoute(activeRoutePath, routeManifest)); + // The active route id names the render's URL, which is the manifest id for + // a static route; a dynamic route's concrete URL is matched instead. + const activeRoute = resolveManifestRoute(binding.activeRouteId, routeManifest); const manifestBinding = activeRoute === null ? undefined @@ -204,15 +211,16 @@ export function resolveRouterTransitionFromRoutes( // route reports only its slots (Next.js explicitParallelRouteChildren). // A slot-only navigation keeps the children branch that was showing, so // its binding, not the latest payload's source page, names that route. - const childrenRoutePath = + // The id is the render's concrete URL, so the manifest gives its pattern. + const keptChildrenRoute = children?.binding.state === "active" && children.binding.activeRouteId != null && children.binding.activeRouteId !== metadata.routeId - ? routePathFromId(children.binding.activeRouteId) + ? resolveManifestRoute(children.binding.activeRouteId, routeManifest) : null; primary = - childrenRoutePath !== null - ? patternToNextFormat(childrenRoutePath) + keptChildrenRoute !== null + ? patternToNextFormat(`/${keptChildrenRoute.patternParts.join("/")}`) : children === null || children.binding.state === "active" ? joinSourcePath(sourceSegments) : children.binding.state === "unmatched" diff --git a/tests/app-browser-transition-routes.test.ts b/tests/app-browser-transition-routes.test.ts index 7103d8a046..6d2a2b9292 100644 --- a/tests/app-browser-transition-routes.test.ts +++ b/tests/app-browser-transition-routes.test.ts @@ -163,7 +163,8 @@ describe("resolveRouterTransitionFromRoutes", () => { routeId: "route:/some-page", slotBindings: [ { - activeRouteId: "route:/blog/:slug", + // A render's route id names its concrete URL. + activeRouteId: "route:/blog/hello", ownerLayoutId: "layout:/", slotId: "slot:children:/", state: "active", From 3068c5eaf62e9864b5ca166c306d07aa20e3836d Mon Sep 17 00:00:00 2001 From: James Date: Thu, 26 Nov 2026 08:12:42 +0000 Subject: [PATCH 11/12] fix(instrumentation): skip a transition when no injected module has a hook --- .../client/instrumentation-client-inject.ts | 31 +++++++-- .../client/instrumentation-client-state.ts | 14 ++++ .../src/client/instrumentation-client.ts | 2 + tests/instrumentation.test.ts | 64 +++++++++++++++++++ 4 files changed, 106 insertions(+), 5 deletions(-) diff --git a/packages/vinext/src/client/instrumentation-client-inject.ts b/packages/vinext/src/client/instrumentation-client-inject.ts index e7a87eab9c..60e79c91aa 100644 --- a/packages/vinext/src/client/instrumentation-client-inject.ts +++ b/packages/vinext/src/client/instrumentation-client-inject.ts @@ -1,6 +1,9 @@ import fs from "node:fs"; import path from "pathslash"; -import { INSTRUMENTATION_CLIENT_HOOK_FAILED_MESSAGE } from "./instrumentation-client-state.js"; +import { + HAS_ROUTER_TRANSITION_START_EXPORT, + INSTRUMENTATION_CLIENT_HOOK_FAILED_MESSAGE, +} from "./instrumentation-client-state.js"; /** Resolve empty-module next to this file (.js in dist, .ts in source). */ function resolveInstrumentationClientEmptyModule(dir: string): string { @@ -99,14 +102,32 @@ export function generateInstrumentationClientInjectModule( " : { hooks: namespace, hook: undefined };", "}", "", + "// The user's own module is read directly, without the default fallback.", + "function __vinext_read_hook(index) {", + " return index < __vinext_inject_modules.length", + " ? __vinext_inject_hook(__vinext_inject_modules[index])", + ` : { hooks: __vinj_${userSlot}, hook: __vinj_${userSlot}.onRouterTransitionStart };`, + "}", + "", + "// Whether any module has a hook now. Next.js checks this before it numbers", + "// a transition and builds its start event. A throwing read counts, so the", + "// fan-out logs it.", + `export function ${HAS_ROUTER_TRANSITION_START_EXPORT}() {`, + ` for (let index = 0; index <= __vinext_inject_modules.length; index++) {`, + " try {", + ' if (typeof __vinext_read_hook(index).hook === "function") return true;', + " } catch {", + " return true;", + " }", + " }", + " return false;", + "}", + "", "export function onRouterTransitionStart(url, type, event) {", ` for (let index = 0; index <= __vinext_inject_modules.length; index++) {`, " try {", " // Every hook read is inside the try, since a getter can throw.", - " const { hooks, hook } =", - " index < __vinext_inject_modules.length", - " ? __vinext_inject_hook(__vinext_inject_modules[index])", - ` : { hooks: __vinj_${userSlot}, hook: __vinj_${userSlot}.onRouterTransitionStart };`, + " const { hooks, hook } = __vinext_read_hook(index);", " // Next.js builds the start event per hook, sampling its timestamp", " // then, so one hook's mutation never reaches the next. The flag check", " // drops the event copy from builds without the flag. Reflect.apply", diff --git a/packages/vinext/src/client/instrumentation-client-state.ts b/packages/vinext/src/client/instrumentation-client-state.ts index e4398858de..a110e61bc1 100644 --- a/packages/vinext/src/client/instrumentation-client-state.ts +++ b/packages/vinext/src/client/instrumentation-client-state.ts @@ -27,6 +27,12 @@ export function getClientInstrumentationHooks(): ClientInstrumentationHooks | nu ); } +/** + * Exported by the generated instrumentationClientInject module: whether any + * module it fans out to has an onRouterTransitionStart hook right now. + */ +export const HAS_ROUTER_TRANSITION_START_EXPORT = "__vinextHasRouterTransitionStart"; + /** Logged when one instrumentation-client module's router transition hook throws. */ export const INSTRUMENTATION_CLIENT_HOOK_FAILED_MESSAGE = "An instrumentation-client router transition hook failed"; @@ -77,6 +83,14 @@ export function notifyAppRouterTransitionStart( ): void { const hooks = getClientInstrumentationHooks(); if (typeof hooks?.onRouterTransitionStart !== "function") return; + // Next.js numbers a transition only when some module has a hook. The + // inject fan-out is always a function, so it reports that itself. + if ( + process.env.__NEXT_INSTRUMENTATION_CLIENT_ROUTER_TRANSITION_EVENTS && + hooks[HAS_ROUTER_TRANSITION_START_EXPORT]?.() === false + ) { + return; + } // Positive flag check so the event path drops out of builds without the flag. const id = process.env.__NEXT_INSTRUMENTATION_CLIENT_ROUTER_TRANSITION_EVENTS ? `${Date.now().toString(36)}-${(++nextTransitionId).toString(36)}` diff --git a/packages/vinext/src/client/instrumentation-client.ts b/packages/vinext/src/client/instrumentation-client.ts index e736739b74..40cb11ccab 100644 --- a/packages/vinext/src/client/instrumentation-client.ts +++ b/packages/vinext/src/client/instrumentation-client.ts @@ -12,6 +12,8 @@ export type ClientInstrumentationHooks = { navigationType: RouterTransitionType, event: RouterTransitionStartEvent | null, ) => void; + /** Exported by the generated instrumentationClientInject module. */ + __vinextHasRouterTransitionStart?: () => boolean; }; export const clientInstrumentationHooks = setClientInstrumentationHooks( diff --git a/tests/instrumentation.test.ts b/tests/instrumentation.test.ts index 2183c861fb..d86f8213ae 100644 --- a/tests/instrumentation.test.ts +++ b/tests/instrumentation.test.ts @@ -987,6 +987,44 @@ export default { onRouterTransitionStart() { globalThis.__vinextInjectCalls.push } }); + // Next.js's startRouterTransition checks every module for a hook first. + it("reports whether any module has a hook right now", async () => { + const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "vinext-inject-has-hook-")); + try { + const code = generateInstrumentationClientInjectModule(["./getter.cjs"], null); + const getterImport = 'import * as __vinj_0 from "./getter.cjs";'; + expect(code).toContain(getterImport); + const entryPath = path.join(tmpDir, "entry.mjs"); + // A CommonJS module that installs its hook late, through a live getter. + fs.writeFileSync( + entryPath, + code.replace( + getterImport, + `const __vinj_0 = { + get onRouterTransitionStart() { + if (globalThis.__vinextInjectHook === "throw") throw new Error("getter failed"); + return globalThis.__vinextInjectHook; + }, +};`, + ), + ); + const scope = globalThis as { __vinextInjectHook?: unknown }; + const mod = (await import(pathToFileURL(entryPath).href)) as { + __vinextHasRouterTransitionStart: () => boolean; + }; + + expect(mod.__vinextHasRouterTransitionStart()).toBe(false); + scope.__vinextInjectHook = () => {}; + expect(mod.__vinextHasRouterTransitionStart()).toBe(true); + // A throwing read reaches the fan-out, which logs it. + scope.__vinextInjectHook = "throw"; + expect(mod.__vinextHasRouterTransitionStart()).toBe(true); + } finally { + delete (globalThis as { __vinextInjectHook?: unknown }).__vinextInjectHook; + fs.rmSync(tmpDir, { recursive: true, force: true }); + } + }); + // Ported from Next.js: test/production/app-dir/instrumentation-client-dce/instrumentation-client-dce.test.ts // https://github.com/vercel/next.js/blob/v16.4.6/test/production/app-dir/instrumentation-client-dce/instrumentation-client-dce.test.ts it("drops the start event copy from builds without the transition events flag", () => { @@ -1296,6 +1334,32 @@ describe("client instrumentation hook state", () => { expect(second[2].id).not.toBe(first[2].id); }); + it("skips a transition while the inject fan-out has no hook to call", async () => { + const state = await import(statePath); + const onRouterTransitionStart = vi.fn(); + const resolveFromRoutes = vi.fn(() => ["/"]); + let hasHook = false; + state.setClientInstrumentationHooks({ + onRouterTransitionStart, + __vinextHasRouterTransitionStart: () => hasHook, + }); + state.setRouterTransitionFromRoutesResolver(resolveFromRoutes); + + state.notifyAppRouterTransitionStart("/a", "push"); + expect(onRouterTransitionStart).not.toHaveBeenCalled(); + expect(resolveFromRoutes).not.toHaveBeenCalled(); + + // The skipped transition took no id, as in Next.js. + hasHook = true; + state.notifyAppRouterTransitionStart("/b", "push"); + state.notifyAppRouterTransitionStart("/c", "push"); + const [first, second] = onRouterTransitionStart.mock.calls.map(([, , event]) => + Number.parseInt(String(event.id).split("-")[1], 36), + ); + expect(second).toBe(first + 1); + expect(resolveFromRoutes).toHaveBeenCalledTimes(2); + }); + it("logs a failure to build the event like a throwing hook", async () => { const state = await import(statePath); const error = new Error("resolver failed"); From 7cf1444ec7fd75f928362257a13fdfa2fd2b7532 Mon Sep 17 00:00:00 2001 From: James Date: Thu, 26 Nov 2026 08:32:30 +0000 Subject: [PATCH 12/12] fix(instrumentation): treat an @children directory as the children key in source routes --- .../server/app-browser-transition-routes.ts | 21 ++++++++++--- tests/app-browser-transition-routes.test.ts | 30 +++++++++++++++++++ 2 files changed, 47 insertions(+), 4 deletions(-) diff --git a/packages/vinext/src/server/app-browser-transition-routes.ts b/packages/vinext/src/server/app-browser-transition-routes.ts index 83ff6fb0f1..79667cdc77 100644 --- a/packages/vinext/src/server/app-browser-transition-routes.ts +++ b/packages/vinext/src/server/app-browser-transition-routes.ts @@ -26,8 +26,19 @@ function isRouteGroupSegment(segment: string): boolean { return segment.startsWith("(") && segment.endsWith(")"); } +// Next.js normalizes an `@children` directory to the children parallel key, +// so, like a route group, it adds no segment to a source path. +function isSourcePathSegment(segment: string): boolean { + return segment.length > 0 && segment !== "@children" && !isRouteGroupSegment(segment); +} + function joinSourcePath(segments: readonly string[]): string { - return `/${segments.filter((segment) => segment.length > 0 && !isRouteGroupSegment(segment)).join("/")}`; + return `/${segments.filter(isSourcePathSegment).join("/")}`; +} + +/** A manifest interception's source page path, in the same source form. */ +function normalizeSourcePagePath(sourcePagePath: string): string { + return joinSourcePath(sourcePagePath.split("/")); } function routePathFromId(routeId: string): string | null { @@ -67,13 +78,13 @@ function resolveInterceptionSourcePagePath( // A merge can keep an intercepted slot from an earlier payload, so the // binding's own interception id decides, not only the latest interception. const byId = binding.interceptionId ? graph.interceptions.get(binding.interceptionId) : undefined; - if (byId?.sourcePagePath) return byId.sourcePagePath; + if (byId?.sourcePagePath) return normalizeSourcePagePath(byId.sourcePagePath); if (interception === null || interception.slotId !== binding.slotId) return null; const targetParts = splitPathnameForRouteMatch(interception.targetMatchedUrl); const match = graph.interceptionsBySlotId .get(interception.slotId) ?.find((candidate) => matchRoutePattern(targetParts, candidate.targetPatternParts) !== null); - return match?.sourcePagePath ?? null; + return match?.sourcePagePath === undefined ? null : normalizeSourcePagePath(match.sourcePagePath); } function treePathSegments(treePath: string): string[] { @@ -144,7 +155,9 @@ function resolveWholeInterceptedSlot( interception.sourcePagePath !== undefined && withoutSlotSegments(interception.sourcePagePath) === sourcePath, )?.sourcePagePath; - if (sourcePagePath !== undefined) return { binding, ownerSegments, path: sourcePagePath }; + if (sourcePagePath !== undefined) { + return { binding, ownerSegments, path: normalizeSourcePagePath(sourcePagePath) }; + } fallback ??= { binding, ownerSegments, diff --git a/tests/app-browser-transition-routes.test.ts b/tests/app-browser-transition-routes.test.ts index 6d2a2b9292..7ea808afa9 100644 --- a/tests/app-browser-transition-routes.test.ts +++ b/tests/app-browser-transition-routes.test.ts @@ -83,6 +83,10 @@ describe("resolveRouterTransitionFromRoutes", () => { expect(resolveRouterTransitionFromRoutes(page("/shop/[[...slug]]/page"), manifest)).toEqual([ "/shop/[[...slug]]", ]); + // Next.js normalizes an @children directory to the children key. + expect(resolveRouterTransitionFromRoutes(page("/@children/foo/page"), manifest)).toEqual([ + "/foo", + ]); }); it("reports /_not-found for a URL that matched no route", () => { @@ -392,6 +396,32 @@ describe("resolveRouterTransitionFromRoutes", () => { manifest, ), ).toEqual(expected); + // A manifest source page path through @children reports it the same way. + const interceptionWithChildrenDir = { + ...manifest, + segmentGraph: { + ...manifest.segmentGraph, + interceptions: new Map([ + [ + interceptionId, + { + ...manifest.segmentGraph.interceptions.get(interceptionId)!, + sourcePagePath: "/@children/gallery/@modal/(.)photos/[id]", + }, + ], + ]), + }, + } as BrowserRouteManifest; + expect( + resolveRouterTransitionFromRoutes( + committed({ + interception, + slotBindings: [{ ...binding, interceptionId }], + sourcePage: "/gallery/page", + }), + interceptionWithChildrenDir, + ), + ).toEqual(expected); // Without the binding's interception id, the target URL selects it. expect( resolveRouterTransitionFromRoutes(