Unverified Commit 12f85450 authored by Andrew Clark's avatar Andrew Clark Committed by GitHub

Add experimental flag to expose testing API in production builds (#89499)

## Summary

Adds `experimental.exposeTestingApiInProductionBuild` to make the
Instant Navigation Testing API available in production builds. This is a
stopgap until a dedicated "profiling build" mode exists—similar to
React's profiling builds that include extra instrumentation without the
dev-mode overhead.

The testing API lets e2e tests assert on prefetched UI before dynamic
data streams in. Previously it was dev-only, but production builds have
different timing characteristics (prefetches complete faster, code paths
differ), so testing against production builds is valuable.

## Approach

Introduces a single bundler environment variable
`process.env.__NEXT_EXPOSE_TESTING_API` that's true when either:
- Running in dev mode, OR
- The experimental flag is enabled

This replaces scattered `NODE_ENV !== 'production'` checks throughout
the testing API code paths, making the gating logic consistent and
centralized in the build configuration.

Also renames `dev-navigation-lock.ts` to `navigation-testing-lock.ts`
and updates header/cookie names from "dev-only" to
"instant-navigation-testing" to reflect that the API is no longer
dev-exclusive.

## Test plan

- Updated existing e2e tests to run in both dev and production modes
- Tests pass with `NEXT_TEST_MODE=start` (production build)
parent 99c8038e
...@@ -360,6 +360,8 @@ export function getDefineEnv({ ...@@ -360,6 +360,8 @@ export function getDefineEnv({
'process.env.__NEXT_OPTIMISTIC_ROUTING': 'process.env.__NEXT_OPTIMISTIC_ROUTING':
config.experimental.optimisticRouting ?? false, config.experimental.optimisticRouting ?? false,
'process.env.__NEXT_VARY_PARAMS': config.experimental.varyParams ?? false, 'process.env.__NEXT_VARY_PARAMS': config.experimental.varyParams ?? false,
'process.env.__NEXT_EXPOSE_TESTING_API':
dev || config.experimental.exposeTestingApiInProductionBuild === true,
'process.env.__NEXT_CACHE_LIFE': config.cacheLife, 'process.env.__NEXT_CACHE_LIFE': config.cacheLife,
'process.env.__NEXT_CLIENT_PARAM_PARSING_ORIGINS': 'process.env.__NEXT_CLIENT_PARAM_PARSING_ORIGINS':
config.experimental.clientParamParsingOrigins || [], config.experimental.clientParamParsingOrigins || [],
......
...@@ -348,16 +348,21 @@ export async function handler( ...@@ -348,16 +348,21 @@ export async function handler(
const hasDebugFallbackShellQuery = const hasDebugFallbackShellQuery =
hasDebugStaticShellQuery && query.__nextppronly === 'fallback' hasDebugStaticShellQuery && query.__nextppronly === 'fallback'
// Dev-only: Enable the Instant Navigation Testing API. Renders only the // Whether the testing API is exposed (dev mode or explicit flag)
// prefetched portion of the page, excluding dynamic content. This allows const exposeTestingApi =
// tests to assert on the prefetched UI state deterministically. routeModule.isDev === true ||
nextConfig.experimental.exposeTestingApiInProductionBuild === true
// Enable the Instant Navigation Testing API. Renders only the prefetched
// portion of the page, excluding dynamic content. This allows tests to
// assert on the prefetched UI state deterministically.
// - Header: Used for client-side navigations where we can set request headers // - Header: Used for client-side navigations where we can set request headers
// - Cookie: Used for MPA navigations (page reload, full page load) where we // - Cookie: Used for MPA navigations (page reload, full page load) where we
// can't set request headers. Only applies to document requests (no RSC // can't set request headers. Only applies to document requests (no RSC
// header) - RSC requests should proceed normally even during a locked scope, // header) - RSC requests should proceed normally even during a locked scope,
// with blocking happening on the client side. // with blocking happening on the client side.
const isInstantNavigationTest = const isInstantNavigationTest =
routeModule.isDev === true && exposeTestingApi &&
couldSupportPPR && couldSupportPPR &&
(req.headers[NEXT_INSTANT_PREFETCH_HEADER] === '1' || (req.headers[NEXT_INSTANT_PREFETCH_HEADER] === '1' ||
(req.headers[RSC_HEADER] === undefined && (req.headers[RSC_HEADER] === undefined &&
...@@ -375,9 +380,9 @@ export async function handler( ...@@ -375,9 +380,9 @@ export async function handler(
// Ideally we'd want to check the appConfig to see if this page has PPR // Ideally we'd want to check the appConfig to see if this page has PPR
// enabled or not, but that would require plumbing the appConfig through // enabled or not, but that would require plumbing the appConfig through
// to the server during development. We assume that the page supports it // to the server during development. We assume that the page supports it
// but only during development. // but only during development or when the testing API is exposed.
((hasDebugStaticShellQuery || isInstantNavigationTest) && ((hasDebugStaticShellQuery || isInstantNavigationTest) &&
(routeModule.isDev === true || (exposeTestingApi ||
routerServerContext?.experimentalTestProxy === true))) routerServerContext?.experimentalTestProxy === true)))
const isDebugStaticShell: boolean = const isDebugStaticShell: boolean =
......
...@@ -81,8 +81,8 @@ export function appBootstrap(hydrate: (assetPrefix: string) => void) { ...@@ -81,8 +81,8 @@ export function appBootstrap(hydrate: (assetPrefix: string) => void) {
// and set up a minimal testing API. Hydration would fail because the // and set up a minimal testing API. Hydration would fail because the
// static shell response doesn't include the full Flight data stream. // static shell response doesn't include the full Flight data stream.
// When unlock() is called, we clear the cookie and reload the page. // When unlock() is called, we clear the cookie and reload the page.
if (process.env.NODE_ENV !== 'production') { if (process.env.__NEXT_EXPOSE_TESTING_API) {
const NEXT_INSTANT_TEST_COOKIE = 'next-dev-only-instant-test' const NEXT_INSTANT_TEST_COOKIE = 'next-instant-navigation-testing'
if (document.cookie.includes(NEXT_INSTANT_TEST_COOKIE + '=')) { if (document.cookie.includes(NEXT_INSTANT_TEST_COOKIE + '=')) {
// Set up minimal testing API for the static shell // Set up minimal testing API for the static shell
window.__EXPERIMENTAL_NEXT_TESTING__ = { window.__EXPERIMENTAL_NEXT_TESTING__ = {
......
...@@ -7,10 +7,10 @@ if (process.env.NODE_ENV !== 'production') { ...@@ -7,10 +7,10 @@ if (process.env.NODE_ENV !== 'production') {
} }
// Expose a testing API that allows e2e tests to assert on the prefetched UI // Expose a testing API that allows e2e tests to assert on the prefetched UI
// state before dynamic data streams in. Dev-only, browser-only. // state before dynamic data streams in. Browser-only.
if (process.env.NODE_ENV !== 'production' && typeof window !== 'undefined') { if (process.env.__NEXT_EXPOSE_TESTING_API && typeof window !== 'undefined') {
const { acquireNavigationLock, releaseNavigationLock } = const { acquireNavigationLock, releaseNavigationLock } =
require('./components/segment-cache/dev-navigation-lock') as typeof import('./components/segment-cache/dev-navigation-lock') require('./components/segment-cache/navigation-testing-lock') as typeof import('./components/segment-cache/navigation-testing-lock')
window.__EXPERIMENTAL_NEXT_TESTING__ = { window.__EXPERIMENTAL_NEXT_TESTING__ = {
navigation: { navigation: {
......
...@@ -16,16 +16,19 @@ export const NEXT_HMR_REFRESH_HASH_COOKIE = '__next_hmr_refresh_hash__' as const ...@@ -16,16 +16,19 @@ export const NEXT_HMR_REFRESH_HASH_COOKIE = '__next_hmr_refresh_hash__' as const
export const NEXT_URL = 'next-url' as const export const NEXT_URL = 'next-url' as const
export const RSC_CONTENT_TYPE_HEADER = 'text/x-component' as const export const RSC_CONTENT_TYPE_HEADER = 'text/x-component' as const
// Dev-only header for the Instant Navigation Testing API. In dev mode, static // Header for the Instant Navigation Testing API. In development and testing
// pre-renders normally don't happen. This header tells the server to perform // builds, static pre-renders normally don't happen. This header tells the
// a static pre-render anyway, allowing tests to assert on the prefetched UI. // server to perform a static pre-render anyway, allowing tests to assert on
// the prefetched UI. Not exposed in production builds by default.
export const NEXT_INSTANT_PREFETCH_HEADER = export const NEXT_INSTANT_PREFETCH_HEADER =
'next-dev-only-instant-prefetch' as const 'next-instant-navigation-testing-prefetch' as const
// Dev-only cookie for the Instant Navigation Testing API. Used for MPA // Cookie for the Instant Navigation Testing API. Used for MPA navigations
// navigations (page reload, full page load) where we can't set request headers. // (page reload, full page load) where we can't set request headers. When set,
// When set, the server renders only the static shell. // the server renders only the static shell. Not exposed in production builds
export const NEXT_INSTANT_TEST_COOKIE = 'next-dev-only-instant-test' as const // by default.
export const NEXT_INSTANT_TEST_COOKIE =
'next-instant-navigation-testing' as const
export const FLIGHT_HEADERS = [ export const FLIGHT_HEADERS = [
RSC_HEADER, RSC_HEADER,
......
...@@ -94,7 +94,7 @@ export type RequestHeaders = { ...@@ -94,7 +94,7 @@ export type RequestHeaders = {
'Next-Test-Fetch-Priority'?: RequestInit['priority'] 'Next-Test-Fetch-Priority'?: RequestInit['priority']
[NEXT_HTML_REQUEST_ID_HEADER]?: string // dev-only [NEXT_HTML_REQUEST_ID_HEADER]?: string // dev-only
[NEXT_REQUEST_ID_HEADER]?: string // dev-only [NEXT_REQUEST_ID_HEADER]?: string // dev-only
[NEXT_INSTANT_PREFETCH_HEADER]?: '1' // dev-only [NEXT_INSTANT_PREFETCH_HEADER]?: '1' // testing API only
} }
function doMpaNavigation(url: string): FetchServerResponseResult { function doMpaNavigation(url: string): FetchServerResponseResult {
......
...@@ -1532,10 +1532,10 @@ async function fetchMissingDynamicData( ...@@ -1532,10 +1532,10 @@ async function fetchMissingDynamicData(
result.renderedSearch result.renderedSearch
) )
// Dev-only: If the navigation lock is active, wait for it to be released // If the navigation lock is active, wait for it to be released before
// before writing the dynamic data. This allows tests to assert on the // writing the dynamic data. This allows tests to assert on the prefetched
// prefetched UI state. // UI state.
if (process.env.NODE_ENV !== 'production') { if (process.env.__NEXT_EXPOSE_TESTING_API) {
await waitForNavigationLock() await waitForNavigationLock()
} }
...@@ -1880,15 +1880,16 @@ function createDeferredRsc< ...@@ -1880,15 +1880,16 @@ function createDeferredRsc<
} }
/** /**
* Dev-only helper for the Instant Navigation Testing API. Waits for the * Helper for the Instant Navigation Testing API. Waits for the navigation lock
* navigation lock to be released before returning. The network request has * to be released before returning. The network request has already completed by
* already completed by the time this is called, so this only delays writing * the time this is called, so this only delays writing the dynamic data.
* the dynamic data. *
* Not exposed in production builds by default.
*/ */
async function waitForNavigationLock(): Promise<void> { async function waitForNavigationLock(): Promise<void> {
if (process.env.NODE_ENV !== 'production') { if (process.env.__NEXT_EXPOSE_TESTING_API) {
const { waitForNavigationLockIfActive } = const { waitForNavigationLockIfActive } =
require('../segment-cache/dev-navigation-lock') as typeof import('../segment-cache/dev-navigation-lock') require('../segment-cache/navigation-testing-lock') as typeof import('../segment-cache/navigation-testing-lock')
await waitForNavigationLockIfActive() await waitForNavigationLockIfActive()
} }
} }
...@@ -21,11 +21,11 @@ export function refreshReducer( ...@@ -21,11 +21,11 @@ export function refreshReducer(
// given URL) which doesn't change during a refresh. The segment cache // given URL) which doesn't change during a refresh. The segment cache
// contains the actual RSC data which needs to be re-fetched. // contains the actual RSC data which needs to be re-fetched.
// //
// Dev-only: The Instant Navigation Testing API can bypass cache invalidation // The Instant Navigation Testing API can bypass cache invalidation to
// to preserve prefetched data when refreshing after an MPA navigation. This // preserve prefetched data when refreshing after an MPA navigation. This is
// is only used for testing and is not exposed in production builds. // only used for testing and is not exposed in production builds by default.
const bypassCacheInvalidation = const bypassCacheInvalidation =
process.env.NODE_ENV !== 'production' && action.devBypassCacheInvalidation process.env.__NEXT_EXPOSE_TESTING_API && action.devBypassCacheInvalidation
if (!bypassCacheInvalidation) { if (!bypassCacheInvalidation) {
const currentNextUrl = state.nextUrl const currentNextUrl = state.nextUrl
const currentRouterState = state.tree const currentRouterState = state.tree
......
...@@ -31,9 +31,9 @@ export type RouterChangeByServerResponse = ({ ...@@ -31,9 +31,9 @@ export type RouterChangeByServerResponse = ({
export interface RefreshAction { export interface RefreshAction {
type: typeof ACTION_REFRESH type: typeof ACTION_REFRESH
/** /**
* Dev-only. Bypass invalidating the segment cache. Used by the Instant * Bypass invalidating the segment cache. Used by the Instant Navigation
* Navigation Testing API to preserve prefetched data when refreshing after * Testing API to preserve prefetched data when refreshing after an MPA
* an MPA navigation. * navigation. Not exposed in production builds by default.
*/ */
devBypassCacheInvalidation?: boolean devBypassCacheInvalidation?: boolean
} }
......
...@@ -1555,8 +1555,8 @@ export async function fetchRouteOnCacheMiss( ...@@ -1555,8 +1555,8 @@ export async function fetchRouteOnCacheMiss(
if (nextUrl !== null) { if (nextUrl !== null) {
headers[NEXT_URL] = nextUrl headers[NEXT_URL] = nextUrl
} }
// Dev-only: Tell the server to perform a static pre-render for the Instant // Tell the server to perform a static pre-render for the Instant Navigation
// Navigation Testing API. In dev mode, static pre-renders don't normally happen. // Testing API. Static pre-renders don't normally happen during development.
addInstantPrefetchHeaderIfLocked(headers) addInstantPrefetchHeaderIfLocked(headers)
try { try {
...@@ -1864,8 +1864,8 @@ export async function fetchSegmentOnCacheMiss( ...@@ -1864,8 +1864,8 @@ export async function fetchSegmentOnCacheMiss(
if (nextUrl !== null) { if (nextUrl !== null) {
headers[NEXT_URL] = nextUrl headers[NEXT_URL] = nextUrl
} }
// Dev-only: Tell the server to perform a static pre-render for the Instant // Tell the server to perform a static pre-render for the Instant Navigation
// Navigation Testing API. In dev mode, static pre-renders don't normally happen. // Testing API. Static pre-renders don't normally happen during development.
addInstantPrefetchHeaderIfLocked(headers) addInstantPrefetchHeaderIfLocked(headers)
const requestUrl = isOutputExportMode const requestUrl = isOutputExportMode
...@@ -2616,15 +2616,15 @@ export function canNewFetchStrategyProvideMoreContent( ...@@ -2616,15 +2616,15 @@ export function canNewFetchStrategyProvideMoreContent(
} }
/** /**
* Dev-only: Adds the instant prefetch header if the navigation lock is active. * Adds the instant prefetch header if the navigation lock is active.
* Uses a lazy require to ensure dead code elimination in production. * Uses a lazy require to ensure dead code elimination.
*/ */
function addInstantPrefetchHeaderIfLocked( function addInstantPrefetchHeaderIfLocked(
headers: Record<string, string> headers: Record<string, string>
): void { ): void {
if (process.env.NODE_ENV !== 'production') { if (process.env.__NEXT_EXPOSE_TESTING_API) {
const { isNavigationLocked } = const { isNavigationLocked } =
require('./dev-navigation-lock') as typeof import('./dev-navigation-lock') require('./navigation-testing-lock') as typeof import('./navigation-testing-lock')
if (isNavigationLocked()) { if (isNavigationLocked()) {
headers[NEXT_INSTANT_PREFETCH_HEADER] = '1' headers[NEXT_INSTANT_PREFETCH_HEADER] = '1'
} }
......
/** /**
* Dev-only navigation lock for the Instant Navigation Testing API. * Navigation lock for the Instant Navigation Testing API.
* *
* This module is not meant to be used directly. It's exposed on the window * This module is not meant to be used directly. It's exposed on the window
* object and intended to be called via a wrapper API integrated into an * object and intended to be called via a wrapper API integrated into an
...@@ -35,8 +35,9 @@ ...@@ -35,8 +35,9 @@
* content streams in. Network requests are not blocked - they proceed in * content streams in. Network requests are not blocked - they proceed in
* parallel while the lock is held. * parallel while the lock is held.
* *
* All functions in this module are wrapped in dev-mode checks so they get * All functions in this module are wrapped in checks for the testing API,
* dead code eliminated in production builds. * which is not exposed in production builds by default. This ensures the code
* is dead code eliminated unless explicitly enabled.
*/ */
import { NEXT_INSTANT_TEST_COOKIE } from '../app-router-headers' import { NEXT_INSTANT_TEST_COOKIE } from '../app-router-headers'
...@@ -62,10 +63,10 @@ let mpaLockedStateNeedsRefresh = false ...@@ -62,10 +63,10 @@ let mpaLockedStateNeedsRefresh = false
* Logs an error if the lock is already acquired (concurrent locks are not * Logs an error if the lock is already acquired (concurrent locks are not
* allowed). * allowed).
* *
* Dev mode only. * Not exposed in production builds by default.
*/ */
export function acquireNavigationLock(): void { export function acquireNavigationLock(): void {
if (process.env.NODE_ENV !== 'production') { if (process.env.__NEXT_EXPOSE_TESTING_API) {
if (lockState !== null) { if (lockState !== null) {
console.error( console.error(
'Navigation lock already acquired. Concurrent locks are not allowed. ' + 'Navigation lock already acquired. Concurrent locks are not allowed. ' +
...@@ -95,10 +96,10 @@ export function acquireNavigationLock(): void { ...@@ -95,10 +96,10 @@ export function acquireNavigationLock(): void {
* *
* No-op if the lock is not currently acquired. * No-op if the lock is not currently acquired.
* *
* Dev mode only. * Not exposed in production builds by default.
*/ */
export function releaseNavigationLock(): void { export function releaseNavigationLock(): void {
if (process.env.NODE_ENV !== 'production') { if (process.env.__NEXT_EXPOSE_TESTING_API) {
if (lockState !== null) { if (lockState !== null) {
lockState.resolve() lockState.resolve()
lockState = null lockState = null
...@@ -119,10 +120,11 @@ export function releaseNavigationLock(): void { ...@@ -119,10 +120,11 @@ export function releaseNavigationLock(): void {
/** /**
* Returns true if the navigation lock is currently acquired. * Returns true if the navigation lock is currently acquired.
* *
* Dev mode only. Always returns false in production. * Not exposed in production builds by default. Always returns false when the
* testing API is not available.
*/ */
export function isNavigationLocked(): boolean { export function isNavigationLocked(): boolean {
if (process.env.NODE_ENV !== 'production') { if (process.env.__NEXT_EXPOSE_TESTING_API) {
return lockState !== null return lockState !== null
} }
return false return false
...@@ -132,10 +134,10 @@ export function isNavigationLocked(): boolean { ...@@ -132,10 +134,10 @@ export function isNavigationLocked(): boolean {
* Waits for the navigation lock to be released, if it's currently held. * Waits for the navigation lock to be released, if it's currently held.
* No-op if the lock is not acquired. * No-op if the lock is not acquired.
* *
* Dev mode only. * Not exposed in production builds by default.
*/ */
export async function waitForNavigationLockIfActive(): Promise<void> { export async function waitForNavigationLockIfActive(): Promise<void> {
if (process.env.NODE_ENV !== 'production') { if (process.env.__NEXT_EXPOSE_TESTING_API) {
if (lockState !== null) { if (lockState !== null) {
await lockState.promise await lockState.promise
} }
...@@ -148,10 +150,10 @@ export async function waitForNavigationLockIfActive(): Promise<void> { ...@@ -148,10 +150,10 @@ export async function waitForNavigationLockIfActive(): Promise<void> {
* 1. Client-side navigations during the instant scope also block dynamic data * 1. Client-side navigations during the instant scope also block dynamic data
* 2. When the lock is released, a refresh is triggered to fetch dynamic data * 2. When the lock is released, a refresh is triggered to fetch dynamic data
* *
* Dev mode only. * Not exposed in production builds by default.
*/ */
export function initializeMpaLockedState(): void { export function initializeMpaLockedState(): void {
if (process.env.NODE_ENV !== 'production') { if (process.env.__NEXT_EXPOSE_TESTING_API) {
// Set the MPA flag so we know to trigger a refresh when the lock is released // Set the MPA flag so we know to trigger a refresh when the lock is released
mpaLockedStateNeedsRefresh = true mpaLockedStateNeedsRefresh = true
...@@ -172,7 +174,7 @@ export function initializeMpaLockedState(): void { ...@@ -172,7 +174,7 @@ export function initializeMpaLockedState(): void {
* navigation lock following an MPA navigation. * navigation lock following an MPA navigation.
*/ */
function triggerRefresh(): void { function triggerRefresh(): void {
if (process.env.NODE_ENV !== 'production') { if (process.env.__NEXT_EXPOSE_TESTING_API) {
const { dispatchAppRouterAction } = const { dispatchAppRouterAction } =
require('../use-action-queue') as typeof import('../use-action-queue') require('../use-action-queue') as typeof import('../use-action-queue')
const { ACTION_REFRESH } = const { ACTION_REFRESH } =
......
...@@ -300,10 +300,10 @@ async function navigateToUnknownRoute( ...@@ -300,10 +300,10 @@ async function navigateToUnknownRoute(
shouldScroll: boolean, shouldScroll: boolean,
navigateType: 'push' | 'replace' navigateType: 'push' | 'replace'
): Promise<AppRouterState> { ): Promise<AppRouterState> {
// Dev-only: If the Instant Navigation Testing API lock is active, try to // If the Instant Navigation Testing API lock is active, try to prefetch the
// prefetch the route first. If the prefetch succeeds, navigate using the // route first. If the prefetch succeeds, navigate using the prefetched route
// prefetched route tree. If it fails, fall through to the normal path. // tree. If it fails, fall through to the normal path.
if (process.env.NODE_ENV !== 'production') { if (process.env.__NEXT_EXPOSE_TESTING_API) {
const prefetchResult = await tryNavigateUsingTestingAPIPrefetch( const prefetchResult = await tryNavigateUsingTestingAPIPrefetch(
state, state,
url, url,
...@@ -775,13 +775,15 @@ function convertServerPatchToFullTreeImpl( ...@@ -775,13 +775,15 @@ function convertServerPatchToFullTreeImpl(
} }
/** /**
* Dev-only helper for the Instant Navigation Testing API. If the navigation * Helper for the Instant Navigation Testing API. If the navigation lock is
* lock is active, schedules a prefetch task, waits for it to complete, and * active, schedules a prefetch task, waits for it to complete, and navigates
* navigates using the prefetched route tree. * using the prefetched route tree.
* *
* Returns the new router state if navigation succeeded via prefetch, or null * Returns the new router state if navigation succeeded via prefetch, or null
* if the lock isn't active or the prefetch failed (caller should fall through * if the lock isn't active or the prefetch failed (caller should fall through
* to the normal unknown route path). * to the normal unknown route path).
*
* Not exposed in production builds by default.
*/ */
async function tryNavigateUsingTestingAPIPrefetch( async function tryNavigateUsingTestingAPIPrefetch(
state: AppRouterState, state: AppRouterState,
...@@ -795,10 +797,10 @@ async function tryNavigateUsingTestingAPIPrefetch( ...@@ -795,10 +797,10 @@ async function tryNavigateUsingTestingAPIPrefetch(
shouldScroll: boolean, shouldScroll: boolean,
navigateType: 'push' | 'replace' navigateType: 'push' | 'replace'
): Promise<AppRouterState | null> { ): Promise<AppRouterState | null> {
if (process.env.NODE_ENV !== 'production') { if (process.env.__NEXT_EXPOSE_TESTING_API) {
// Lazy require to ensure dead code elimination in production // Lazy require to ensure dead code elimination
const { isNavigationLocked } = const { isNavigationLocked } =
require('./dev-navigation-lock') as typeof import('./dev-navigation-lock') require('./navigation-testing-lock') as typeof import('./navigation-testing-lock')
if (!isNavigationLocked()) { if (!isNavigationLocked()) {
return null return null
} }
......
...@@ -152,9 +152,9 @@ export type PrefetchTask = { ...@@ -152,9 +152,9 @@ export type PrefetchTask = {
_heapIndex: number _heapIndex: number
/** /**
* Dev-only. Called when the prefetch task finishes (either completed or * Called when the prefetch task finishes (either completed or canceled).
* canceled). Used by the Instant Navigation Testing API to await prefetch * Used by the Instant Navigation Testing API to await prefetch completion.
* completion. * Not exposed in production builds by default.
* *
* Note: "Complete" means the scheduler has no more work to do for this task * Note: "Complete" means the scheduler has no more work to do for this task
* — all network requests have been spawned. It does not mean all data has * — all network requests have been spawned. It does not mean all data has
...@@ -254,7 +254,7 @@ export type IncludeDynamicData = null | 'full' | 'dynamic' ...@@ -254,7 +254,7 @@ export type IncludeDynamicData = null | 'full' | 'dynamic'
* @param treeAtTimeOfPrefetch The app's current FlightRouterState * @param treeAtTimeOfPrefetch The app's current FlightRouterState
* @param fetchStrategy Whether to prefetch dynamic data, in addition to * @param fetchStrategy Whether to prefetch dynamic data, in addition to
* static data. This is used by `<Link prefetch={true}>`. * static data. This is used by `<Link prefetch={true}>`.
* @param _onComplete Dev-only. Called when the prefetch task finishes. * @param _onComplete Called when the prefetch task finishes. Testing API only.
*/ */
export function schedulePrefetchTask( export function schedulePrefetchTask(
key: RouteCacheKey, key: RouteCacheKey,
...@@ -280,7 +280,7 @@ export function schedulePrefetchTask( ...@@ -280,7 +280,7 @@ export function schedulePrefetchTask(
onInvalidate, onInvalidate,
_heapIndex: -1, _heapIndex: -1,
} }
if (process.env.NODE_ENV !== 'production') { if (process.env.__NEXT_EXPOSE_TESTING_API) {
task._onComplete = _onComplete task._onComplete = _onComplete
} }
...@@ -308,7 +308,7 @@ export function cancelPrefetchTask(task: PrefetchTask): void { ...@@ -308,7 +308,7 @@ export function cancelPrefetchTask(task: PrefetchTask): void {
// does not get added back to the queue when it's pinged by the network. // does not get added back to the queue when it's pinged by the network.
task.isCanceled = true task.isCanceled = true
heapDelete(taskHeap, task) heapDelete(taskHeap, task)
if (process.env.NODE_ENV !== 'production') { if (process.env.__NEXT_EXPOSE_TESTING_API) {
// Call completion callback. In practice this shouldn't be reached for // Call completion callback. In practice this shouldn't be reached for
// test-initiated prefetches since cancellation is only used by the Link // test-initiated prefetches since cancellation is only used by the Link
// component when elements scroll out of viewport. // component when elements scroll out of viewport.
...@@ -548,7 +548,7 @@ function processQueueInMicrotask() { ...@@ -548,7 +548,7 @@ function processQueueInMicrotask() {
heapResift(taskHeap, task) heapResift(taskHeap, task)
} else { } else {
// The prefetch is complete. Continue to the next task. // The prefetch is complete. Continue to the next task.
if (process.env.NODE_ENV !== 'production') { if (process.env.__NEXT_EXPOSE_TESTING_API) {
// Notify the Instant Navigation Testing API that the prefetch has // Notify the Instant Navigation Testing API that the prefetch has
// completed, so it can proceed with navigation. // completed, so it can proceed with navigation.
const onComplete = task._onComplete const onComplete = task._onComplete
......
...@@ -2197,13 +2197,17 @@ export default abstract class Server< ...@@ -2197,13 +2197,17 @@ export default abstract class Server<
typeof query.__nextppronly !== 'undefined' && typeof query.__nextppronly !== 'undefined' &&
couldSupportPPR couldSupportPPR
// Dev-only: Check for the instant test cookie for MPA navigations (page // Whether the testing API is exposed (dev mode or explicit flag)
// reload, full page load) in the Instant Navigation Testing API. Only const exposeTestingApi =
// applies to document requests (no RSC header) - RSC requests should this.renderOpts.dev === true ||
// proceed normally even during a locked scope, with blocking happening this.nextConfig.experimental.exposeTestingApiInProductionBuild === true
// on the client side.
// Check for the instant test cookie for MPA navigations (page reload, full
// page load) in the Instant Navigation Testing API. Only applies to
// document requests (no RSC header) - RSC requests should proceed normally
// even during a locked scope, with blocking happening on the client side.
const hasInstantTestCookie = const hasInstantTestCookie =
this.renderOpts.dev === true && exposeTestingApi &&
req.headers[RSC_HEADER] === undefined && req.headers[RSC_HEADER] === undefined &&
typeof req.headers.cookie === 'string' && typeof req.headers.cookie === 'string' &&
req.headers.cookie.includes(NEXT_INSTANT_TEST_COOKIE + '=') && req.headers.cookie.includes(NEXT_INSTANT_TEST_COOKIE + '=') &&
...@@ -2220,10 +2224,9 @@ export default abstract class Server< ...@@ -2220,10 +2224,9 @@ export default abstract class Server<
// Ideally we'd want to check the appConfig to see if this page has PPR // Ideally we'd want to check the appConfig to see if this page has PPR
// enabled or not, but that would require plumbing the appConfig through // enabled or not, but that would require plumbing the appConfig through
// to the server during development. We assume that the page supports it // to the server during development. We assume that the page supports it
// but only during development. // but only during development or when the testing API is exposed.
((hasDebugStaticShellQuery || hasInstantTestCookie) && ((hasDebugStaticShellQuery || hasInstantTestCookie) &&
(this.renderOpts.dev === true || (exposeTestingApi || this.experimentalTestProxy === true)))
this.experimentalTestProxy === true)))
// If we're in minimal mode, then try to get the postponed information from // If we're in minimal mode, then try to get the postponed information from
// the request metadata. If available, use it for resuming the postponed // the request metadata. If available, use it for resuming the postponed
......
...@@ -228,6 +228,7 @@ export const experimentalSchema = { ...@@ -228,6 +228,7 @@ export const experimentalSchema = {
externalDir: z.boolean().optional(), externalDir: z.boolean().optional(),
externalMiddlewareRewritesResolve: z.boolean().optional(), externalMiddlewareRewritesResolve: z.boolean().optional(),
externalProxyRewritesResolve: z.boolean().optional(), externalProxyRewritesResolve: z.boolean().optional(),
exposeTestingApiInProductionBuild: z.boolean().optional(),
fallbackNodePolyfills: z.literal(false).optional(), fallbackNodePolyfills: z.literal(false).optional(),
fetchCacheKeyPrefix: z.string().optional(), fetchCacheKeyPrefix: z.string().optional(),
forceSwcTransforms: z.boolean().optional(), forceSwcTransforms: z.boolean().optional(),
......
...@@ -367,6 +367,18 @@ export interface ExperimentalConfig { ...@@ -367,6 +367,18 @@ export interface ExperimentalConfig {
*/ */
externalMiddlewareRewritesResolve?: boolean externalMiddlewareRewritesResolve?: boolean
externalProxyRewritesResolve?: boolean externalProxyRewritesResolve?: boolean
/**
* Exposes the experimental testing API (`__EXPERIMENTAL_NEXT_TESTING__`) in
* production builds. This API is always available in development mode.
*
* The testing API allows e2e tests to control navigation timing, enabling
* deterministic assertions on prefetched/cached UI before dynamic data
* streams in.
*
* WARNING: This flag is intended for profiling and testing purposes only.
* Do not enable in user-facing production deployments.
*/
exposeTestingApiInProductionBuild?: boolean
extensionAlias?: Record<string, any> extensionAlias?: Record<string, any>
allowedRevalidateHeaderKeys?: string[] allowedRevalidateHeaderKeys?: string[]
fetchCacheKeyPrefix?: string fetchCacheKeyPrefix?: string
...@@ -1771,6 +1783,7 @@ export interface NextConfigRuntime { ...@@ -1771,6 +1783,7 @@ export interface NextConfigRuntime {
| 'runtimeServerDeploymentId' | 'runtimeServerDeploymentId'
| 'maxPostponedStateSize' | 'maxPostponedStateSize'
| 'devCacheControlNoCache' | 'devCacheControlNoCache'
| 'exposeTestingApiInProductionBuild'
> & { > & {
// Pick on @internal fields generates invalid .d.ts files // Pick on @internal fields generates invalid .d.ts files
/** @internal */ /** @internal */
...@@ -1834,6 +1847,7 @@ export function getNextConfigRuntime( ...@@ -1834,6 +1847,7 @@ export function getNextConfigRuntime(
runtimeServerDeploymentId: ex.runtimeServerDeploymentId, runtimeServerDeploymentId: ex.runtimeServerDeploymentId,
maxPostponedStateSize: ex.maxPostponedStateSize, maxPostponedStateSize: ex.maxPostponedStateSize,
devCacheControlNoCache: ex.devCacheControlNoCache, devCacheControlNoCache: ex.devCacheControlNoCache,
exposeTestingApiInProductionBuild: ex.exposeTestingApiInProductionBuild,
trustHostHeader: ex.trustHostHeader, trustHostHeader: ex.trustHostHeader,
isExperimentalCompile: ex.isExperimentalCompile, isExperimentalCompile: ex.isExperimentalCompile,
......
...@@ -17,28 +17,22 @@ ...@@ -17,28 +17,22 @@
* // After exiting instant(), dynamic content streams in * // After exiting instant(), dynamic content streams in
* await expect(page.locator('[data-testid="price"]')).toBeVisible() * await expect(page.locator('[data-testid="price"]')).toBeVisible()
* *
* NOTE: This API is dev-mode only. The tests bail out in production mode. * NOTE: This API is not exposed in production builds by default. These tests
* use the experimental.exposeTestingApiInProductionBuild flag to enable the
* API in production mode for testing purposes.
*/ */
import { nextTestSetup } from 'e2e-utils' import { nextTestSetup } from 'e2e-utils'
import type * as Playwright from 'playwright' import type * as Playwright from 'playwright'
describe('instant-navigation-testing-api', () => { describe('instant-navigation-testing-api', () => {
const { next, isNextDev } = nextTestSetup({ const { next } = nextTestSetup({
files: __dirname, files: __dirname,
// Skip deployment tests because the exposeTestingApiInProductionBuild flag
// doesn't exist in the production version of Next.js yet
skipDeployment: true,
}) })
if (!isNextDev) {
it('should not expose __EXPERIMENTAL_NEXT_TESTING__ API in production mode', async () => {
const browser = await next.browser('/')
const hasTestingAPI = await browser.eval(
'typeof window.__EXPERIMENTAL_NEXT_TESTING__ !== "undefined"'
)
expect(hasTestingAPI).toBe(false)
})
return
}
/** /**
* Opens a browser and returns the underlying Playwright Page instance. * Opens a browser and returns the underlying Playwright Page instance.
* *
......
...@@ -3,6 +3,10 @@ ...@@ -3,6 +3,10 @@
*/ */
const nextConfig = { const nextConfig = {
cacheComponents: true, cacheComponents: true,
experimental: {
// Enable the testing API in production builds for these tests
exposeTestingApiInProductionBuild: true,
},
} }
module.exports = nextConfig module.exports = nextConfig
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment