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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions packages/vinext/src/check.ts
Original file line number Diff line number Diff line change
Expand Up @@ -310,6 +310,7 @@ const CONFIG_SUPPORT: Record<string, { status: Status; detail?: string }> = {
"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",
Expand Down
50 changes: 43 additions & 7 deletions packages/vinext/src/client/instrumentation-client-inject.ts
Original file line number Diff line number Diff line change
@@ -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 {
Expand Down Expand Up @@ -99,16 +102,49 @@ 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 };`,
" // Reflect.apply calls the hook itself, even if it overrides call.",
" if (hook != null) Reflect.apply(hook, hooks, [url, type, event]);",
" 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",
" // calls the hook itself, even if it overrides call.",
" if (hook != null) {",
" Reflect.apply(hook, hooks, [",
" url,",
" type,",
" event == null || !process.env.__NEXT_INSTRUMENTATION_CLIENT_ROUTER_TRANSITION_EVENTS",
" ? event",
" : {",
" ...event,",
" timestamp: performance.timeOrigin + performance.now(),",
" fromRoutes: [...event.fromRoutes],",
" },",
" ]);",
" }",
" } catch (error) {",
` console.error(${JSON.stringify(INSTRUMENTATION_CLIENT_HOOK_FAILED_MESSAGE)}, error);`,
" }",
Expand Down
77 changes: 71 additions & 6 deletions packages/vinext/src/client/instrumentation-client-state.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,22 +27,87 @@ 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";

export type RouterTransitionType = "push" | "replace" | "traverse";

/** How the `<Link>` 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 `<Link>`. */
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;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

With instrumentationClientInject, this guard sees the generated aggregate function even when none of the injected/user modules currently exports a hook. Next.js v16.4.6 checks the raw modules with .some(...) before incrementing nextTransitionId or resolving fromRoutes. Consequently, transitions before a late CommonJS hook is installed consume IDs (and can run/fail the resolver) that Next skips, so the first event that hook observes can be ...-2 instead of ...-1. Give the aggregate a live has-hook probe or defer rich-event creation into its fan-out.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Fixed in 3068c5e. The generated inject module now also exports __vinextHasRouterTransitionStart(), a live check that reads each module's hook the same way the fan-out does. With the flag on, notifyAppRouterTransitionStart returns before numbering the transition or resolving fromRoutes when that check reports no hook, as Next's .some(...) does. A read that throws counts as a hook, so the fan-out still logs it rather than the transition being skipped silently. With the flag off, the check isn't called and that path drops out, as before.

New tests: "reports whether any module has a hook right now" covers a late CommonJS getter and a throwing read. "skips a transition while the inject fan-out has no hook to call" checks that a skipped transition takes no id and never runs the resolver. Both fail on the previous head. The dev e2e still passes.

// 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)}`
: 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);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

With instrumentationClientInject, this calls the generated aggregate hook once with one mutable event object, and instrumentation-client-inject.ts then forwards that same object to every injected/user hook. Next.js v16.4.6 constructs the event object inside each callHooks invocation, so each module receives a fresh object and fromRoutes array. An early injected hook can currently mutate either and corrupt what later hooks observe. Rebuild or clone the event per generated fan-out invocation, including fromRoutes, and cover mutation isolation.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Fixed in 5e5007d: the generated fan-out now passes each hook its own copy of the event, with its own fromRoutes array ({ ...event, fromRoutes: [...event.fromRoutes] }), so a mutation in one inject never reaches a later hook. That matches Next.js building the event inside each callHooks invocation. A null event (flag off) passes through unchanged. New test: "gives each hook its own start event". An inject mutates id and fromRoutes, and the user hook still sees the original values; the test fails on the previous generator.

} catch (error) {
console.error(INSTRUMENTATION_CLIENT_HOOK_FAILED_MESSAGE, error);
}
Expand Down
8 changes: 6 additions & 2 deletions packages/vinext/src/client/instrumentation-client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,18 @@ 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;
/** Exported by the generated instrumentationClientInject module. */
__vinextHasRouterTransitionStart?: () => boolean;
};

export const clientInstrumentationHooks = setClientInstrumentationHooks(
Expand Down
11 changes: 11 additions & 0 deletions packages/vinext/src/config/next-config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

The runtime type exported from vinext accepts this option, but the drop-in next package still re-exports Next 16.2.7's ExperimentalConfig from packages/types/next/upstream/dist/server/config-shared.d.ts, where this property is absent. A standard import type { NextConfig } from "next" config therefore rejects the newly supported flag; the fixture masks this by importing NextConfig from vinext. Please augment the shipped next declaration and add type coverage using the public next import.

/**
* Enables App Router Segment Cache prefetch inlining. When provided as an
* object, thresholds are resolved with Next.js defaults and non-finite
Expand Down Expand Up @@ -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.
Expand Down Expand Up @@ -2026,6 +2034,7 @@ export async function resolveNextConfig(
cachedNavigations: false,
appNavFailHandling: false,
gestureTransition: false,
instrumentationClientRouterTransitionEvents: false,
prefetchInlining: false,
redirects: [],
rewrites: { beforeFiles: [], afterFiles: [], fallback: [] },
Expand Down Expand Up @@ -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,
Expand Down
4 changes: 4 additions & 0 deletions packages/vinext/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
);
Expand Down
7 changes: 6 additions & 1 deletion packages/vinext/src/private-next-instrumentation-client.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}
16 changes: 16 additions & 0 deletions packages/vinext/src/routing/app-route-graph.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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,
Expand All @@ -829,6 +837,14 @@ function addRouteManifestInterceptionFacts(input: {
}
}

function createInterceptionSourcePagePath(
segments: readonly string[] | undefined,
): Pick<RouteManifestInterception, "sourcePagePath"> {
if (segments === undefined) return {};
const visible = segments.filter((segment) => !(segment.startsWith("(") && segment.endsWith(")")));
return { sourcePagePath: `/${visible.join("/")}` };
}

function createRouteManifestInterceptionsBySlotId(
interceptions: ReadonlyMap<string, RouteManifestInterception>,
): ReadonlyMap<string, readonly RouteManifestInterception[]> {
Expand Down
11 changes: 10 additions & 1 deletion packages/vinext/src/routing/browser-route-manifest.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<RouteManifestRootBoundary, "id" | "treePath">;
Expand Down Expand Up @@ -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,
Expand Down
16 changes: 15 additions & 1 deletion packages/vinext/src/server/app-browser-entry.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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())

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

The resolver can run before the manifest exists. main() only starts loadNavigationRuntimeRouteManifest() fire-and-forget, while notifyAppRouterTransitionStart() runs before navigation awaits that load. On a first interaction under a slow manifest-chunk fetch, this passes null here and resolveRouteSourcePath falls back to concrete URLs (for example /blog/hello instead of /blog/[slug]) and loses slot/interception source paths. When this feature is enabled, make the manifest available before transition hooks can fire.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Fixed in e4783fc: with instrumentationClientRouterTransitionEvents on, main() now awaits the manifest load it already starts before it hydrates (the fetch still overlaps reading the initial RSC stream). Nothing can start a client transition before hydration (Link, router hooks and popstate handling are wired by bootstrapHydration), so the resolver always sees the manifest. The primary route no longer reads the manifest at all (see the next thread). Without the flag, the await is dropped at build time and startup is unchanged.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Update, 043cf1b: I reverted the pre-hydration manifest await. With the flag on in app-basic it put the manifest back on the hydration path, which #3957 deliberately removed, and route-manifest-chunk.spec.ts ("an intercepted navigation started before the route manifest loads waits for it") failed in app-router-isr-prod. I won't change hydration timing for an experimental instrumentation field.

The rest of this round's fix makes the remaining gap small. The primary route now comes from the committed payload's sourcePage and never reads the manifest. Only a transition that starts before the manifest chunk arrives (a first interaction under a slow chunk fetch) reports an active slot as its slot directory, not the slot sub-page or intercepting page. That's documented on the resolver and under Known limitations in the PR body.

: [],
);
}
const discardedServerActionRefreshScheduler = hasServerActions
? createDiscardedServerActionRefreshScheduler({
runRefresh() {
Expand Down
Loading
Loading