Unverified Commit 5a3a3d19 authored by Andrew Clark's avatar Andrew Clark Committed by GitHub

Reorganize client router modules (#97402)

Pure structural refactor, no behavior changes.

This continues some of the clean-up work I've been doing in the client
router now that more of the implementation has settled, post-Segment
Cache and Instant Navigations.

I have two primary motivations here. The first is purely
maintainability. The current module structure is a mess, and the naming
is misleading when browsing the codebase for the first time.

The second motivation is to prepare for an upcoming rewrite of the
router queue. There will likely be two simultaneous implementations for
a while as the new one settles, so it's extra important the interface
into the router queue is well-defined. I want the fork between the two
worlds to be as clean as possible. This is a similar approach to the one
I took when rewriting the prefetching implementation.

Some of the key name changes:

- ppr-navigations.ts → render-tree.ts. This module's responsibility is
to create the tree that gets passed into React for rendering, currently
called the CacheNode tree. I considered renaming it to cache-node.ts,
but I kept it more generic because I have plans to refactor that type
soon.
- segment-cache/navigation.ts → app-router-state.ts. This module's
responsibility is to compute the next AppRouterState given inputs. It
does perform network requests, but it's conceptually a "pure" operation.
It doesn't deal with any of the router queueing logic. This is the most
reducer-y of the code that still exists, and along with render-tree.ts,
it will remain mostly shared between the old and new state machine
implementations.
- navigator.ts. This is a new module I created to act as the single
entry point for router-level operations: push, replace, navigate,
traverse, restore, refresh, hmrRefresh. This is the primary place where
we'll fork the old and new queue implementations. It's also how we'll
ensure the inactive implementation gets dead-code-eliminated properly
while the two implementations live side-by-side.
parent d1aeb1ce
......@@ -2,6 +2,12 @@ import { startTransition } from 'react'
import { ACTION_SERVER_ACTION } from './components/router-reducer/router-reducer-types'
import { dispatchAppRouterAction } from './components/use-action-queue'
/**
* Invoke a Server Action. The returned promise resolves with the action's
* return value once the response has been processed. Navigation and
* revalidation side effects of the action are handled by the router; they are
* not observable through the returned promise.
*/
export async function callServer(actionId: string, actionArgs: any[]) {
return new Promise((resolve, reject) => {
startTransition(() => {
......
......@@ -301,21 +301,19 @@ function linkClicked(
}
}
const { dispatchNavigateAction } =
const { navigate } =
// TODO(browser-variant): migrate to a .ts/.browser.ts split so the browser bundle drops the server branch; see scripts/generate-browser-variant-aliases.mjs
// ast-grep-ignore: no-typeof-window-require-tsx
require('../components/app-router-instance') as typeof import('../components/app-router-instance')
React.startTransition(() => {
dispatchNavigateAction(
href,
replace ? 'replace' : 'push',
scroll === false ? ScrollBehavior.NoScroll : ScrollBehavior.Default,
linkInstanceRef.current,
transitionTypes,
prefetchIntent
)
})
require('../components/navigator') as typeof import('../components/navigator')
navigate(
href,
replace ? 'replace' : 'push',
scroll === false ? ScrollBehavior.NoScroll : ScrollBehavior.Default,
linkInstanceRef.current,
transitionTypes,
prefetchIntent
)
}
}
......
......@@ -6,39 +6,24 @@ import {
ACTION_SERVER_ACTION,
ACTION_NAVIGATE,
ACTION_RESTORE,
type NavigateAction,
ACTION_HMR_REFRESH,
PrefetchKind,
ScrollBehavior,
type AppHistoryState,
} from './router-reducer/router-reducer-types'
import { reducer } from './router-reducer/router-reducer'
import { addTransitionType, startTransition } from 'react'
import { startTransition } from 'react'
import { isThenable } from '../../shared/lib/is-thenable'
import {
FetchStrategy,
type PrefetchTaskFetchStrategy,
} from './segment-cache/types'
import { prefetch as prefetchWithSegmentCache } from './segment-cache/prefetch'
import { navigate } from './segment-cache/navigation'
import {
dispatchAppRouterAction,
dispatchGestureState,
} from './use-action-queue'
import { resetKnownRoutes } from './segment-cache/optimistic-routes'
import { FreshnessPolicy } from './router-reducer/ppr-navigations'
import { navigate } from './app-router-state'
import { dispatchGestureState } from './use-action-queue'
import { FreshnessPolicy } from './render-tree'
import { addBasePath } from '../add-base-path'
import { isExternalURL } from './app-router-utils'
import type {
AppRouterInstance,
NavigateOptions,
PrefetchOptions,
} from '../../shared/lib/app-router-context.shared-runtime'
import { setLinkForCurrentNavigation, type LinkInstance } from './links'
import type { RouterTransitionPrefetchIntent } from '../router-transition-types'
import type { GlobalErrorComponent } from './builtin/global-error'
import { isJavaScriptURLString } from '../lib/javascript-url'
import { startRouterTransition } from './router-transition'
import { push, replace, refresh, hmrRefresh } from './navigator'
import { prefetchRoute } from './prefetch'
export type DispatchStatePromise = React.Dispatch<ReducerState>
......@@ -269,72 +254,6 @@ export function getCurrentAppRouterState(): AppRouterState | null {
return globalActionQueue !== null ? globalActionQueue.state : null
}
function getAppRouterActionQueue(): AppRouterActionQueue {
if (globalActionQueue === null) {
throw new Error(
'Internal Next.js error: Router action dispatched before initialization.'
)
}
return globalActionQueue
}
export function dispatchNavigateAction(
href: string,
navigateType: NavigateAction['navigateType'],
scrollBehavior: ScrollBehavior,
linkInstanceRef: LinkInstance | null,
transitionTypes: string[] | undefined,
prefetchIntent: RouterTransitionPrefetchIntent | null
): void {
// TODO: This stuff could just go into the reducer. Leaving as-is for now
// since we're about to rewrite all the router reducer stuff anyway.
if (transitionTypes) {
for (const type of transitionTypes) {
addTransitionType(type)
}
}
const url = new URL(addBasePath(href), location.href)
if (process.env.__NEXT_APP_NAV_FAIL_HANDLING) {
window.next.__pendingUrl = url
}
setLinkForCurrentNavigation(linkInstanceRef)
startRouterTransition(
href,
navigateType,
getAppRouterActionQueue().state.tree,
prefetchIntent
)
dispatchAppRouterAction({
type: ACTION_NAVIGATE,
url,
isExternalUrl: isExternalURL(url),
locationSearch: location.search,
scrollBehavior,
navigateType,
})
}
export function dispatchTraverseAction(
href: string,
historyState: AppHistoryState | undefined
) {
startRouterTransition(
href,
'traverse',
getAppRouterActionQueue().state.tree,
null
)
dispatchAppRouterAction({
type: ACTION_RESTORE,
url: new URL(href),
historyState,
})
}
/**
* (Experimental) Perform a gesture navigation. This dispatches through React's
* useOptimistic instead of the main action queue, allowing the state to be
......@@ -391,10 +310,6 @@ function gesturePush(href: string, options?: NavigateOptions): void {
}
}
// Tracks the newest HMR refresh generation so that a newer refresh can abort
// the request of the one it supersedes. Development only.
let activeHmrRefreshController: AbortController | null = null
/**
* The app router that is exposed through `useRouter`. These are public API
* methods. Internal Next.js code should call the lower level methods directly
......@@ -403,121 +318,11 @@ let activeHmrRefreshController: AbortController | null = null
export const publicAppRouterInstance: AppRouterInstance = {
back: () => window.history.back(),
forward: () => window.history.forward(),
prefetch:
// Unlike the old implementation, the Segment Cache doesn't store its
// data in the router reducer state; it writes into a global mutable
// cache. So we don't need to dispatch an action.
(href: string, options?: PrefetchOptions) => {
if (isJavaScriptURLString(href)) {
throw new Error(
'Next.js has blocked a javascript: URL as a security precaution.'
)
}
const actionQueue = getAppRouterActionQueue()
const prefetchKind = options?.kind ?? PrefetchKind.AUTO
// We don't currently offer a way to issue a runtime prefetch via `router.prefetch()`.
// This will be possible when we update its API to not take a PrefetchKind.
let fetchStrategy: PrefetchTaskFetchStrategy
switch (prefetchKind) {
case PrefetchKind.AUTO: {
// We default to PPR. We'll discover whether or not the route supports it with the initial prefetch.
fetchStrategy = FetchStrategy.PPR
break
}
case PrefetchKind.FULL: {
fetchStrategy = FetchStrategy.Full
break
}
default: {
prefetchKind satisfies never
// Despite typescript thinking that this can't happen,
// we might get an unexpected value from user code.
// We don't know what they want, but we know they want a prefetch,
// so use the default.
fetchStrategy = FetchStrategy.PPR
}
}
prefetchWithSegmentCache(
href,
actionQueue.state.nextUrl,
actionQueue.state.tree,
fetchStrategy,
options?.onInvalidate ?? null
)
},
replace: (href: string, options?: NavigateOptions) => {
if (isJavaScriptURLString(href)) {
throw new Error(
'Next.js has blocked a javascript: URL as a security precaution.'
)
}
startTransition(() => {
dispatchNavigateAction(
href,
'replace',
options?.scroll === false
? ScrollBehavior.NoScroll
: ScrollBehavior.Default,
null,
options?.transitionTypes,
null
)
})
},
push: (href: string, options?: NavigateOptions) => {
if (isJavaScriptURLString(href)) {
throw new Error(
'Next.js has blocked a javascript: URL as a security precaution.'
)
}
startTransition(() => {
dispatchNavigateAction(
href,
'push',
options?.scroll === false
? ScrollBehavior.NoScroll
: ScrollBehavior.Default,
null,
options?.transitionTypes,
null
)
})
},
refresh: () => {
startTransition(() => {
dispatchAppRouterAction({
type: ACTION_REFRESH,
})
})
},
hmrRefresh: () => {
if (process.env.NODE_ENV !== 'development') {
throw new Error(
'hmrRefresh can only be used in development mode. Please use refresh instead.'
)
} else {
// Reset the known routes table so that route predictions are cleared
// when routes change during development.
resetKnownRoutes()
let signal: AbortSignal | undefined
if (process.env.__NEXT_SERVER_COMPONENTS_HMR_CANCELLATION) {
// Abort the superseded generation before scheduling the new one, so its
// request is torn down as early as possible. Halting (not rejecting)
// makes the abort safe regardless of order.
activeHmrRefreshController?.abort()
activeHmrRefreshController = new AbortController()
signal = activeHmrRefreshController.signal
}
startTransition(() => {
dispatchAppRouterAction({
type: ACTION_HMR_REFRESH,
signal,
})
})
}
},
prefetch: prefetchRoute,
replace: replace,
push: push,
refresh: refresh,
hmrRefresh: hmrRefresh,
// Default value. Each route segment provides its own value at runtime. Refer
// to `useRouter()`.
bfcacheId: '0',
......
import type {
FlightRouterState,
ScrollRef,
} from '../../../shared/lib/app-router-types'
import type { CacheNode } from '../../../shared/lib/app-router-types'
import { PrefetchHint } from '../../../shared/lib/app-router-types'
import { fetchServerResponse } from '../router-reducer/fetch-server-response'
} from '../../shared/lib/app-router-types'
import type { CacheNode } from '../../shared/lib/app-router-types'
import { PrefetchHint } from '../../shared/lib/app-router-types'
import { fetchServerResponse } from './router-reducer/fetch-server-response'
import {
startPPRNavigation,
spawnDynamicRequests,
......@@ -12,8 +12,8 @@ import {
beginLockedNavigation,
type NavigationLock,
type NavigationRequestAccumulation,
} from '../router-reducer/ppr-navigations'
import { createHrefFromUrl } from '../router-reducer/create-href-from-url'
} from './render-tree'
import { createHrefFromUrl } from './router-reducer/create-href-from-url'
import {
EntryStatus,
segmentCacheMap,
......@@ -23,23 +23,29 @@ import {
spawnStaticStageCacheWrite,
writeRuntimePrefetchStreamIntoCache,
type FulfilledRouteCacheEntry,
} from './cache'
import { discoverKnownRoute } from './optimistic-routes'
import { createCacheKey, type NormalizedSearch } from './cache-key'
import type { CacheMap } from './cache-map'
import { schedulePrefetchTask } from './scheduler'
import { PrefetchPriority, FetchStrategy } from './types'
import { getLinkForCurrentNavigation } from '../links'
import type { AppRouterState } from '../router-reducer/router-reducer-types'
import { ScrollBehavior } from '../router-reducer/router-reducer-types'
import { computeChangedPath } from '../router-reducer/compute-changed-path'
import { isJavaScriptURLString } from '../../lib/javascript-url'
import { UnknownDynamicStaleTime, computeDynamicStaleAt } from './bfcache'
import { createLinkPrefetchPartialError } from '../../../shared/lib/instant-messages'
} from './segment-cache/cache'
import { discoverKnownRoute } from './segment-cache/optimistic-routes'
import {
createCacheKey,
type NormalizedSearch,
} from './segment-cache/cache-key'
import type { CacheMap } from './segment-cache/cache-map'
import { schedulePrefetchTask } from './segment-cache/scheduler'
import { PrefetchPriority, FetchStrategy } from './segment-cache/types'
import { getLinkForCurrentNavigation } from './links'
import type { AppRouterState } from './router-reducer/router-reducer-types'
import { ScrollBehavior } from './router-reducer/router-reducer-types'
import { computeChangedPath } from './router-reducer/compute-changed-path'
import { isJavaScriptURLString } from '../lib/javascript-url'
import {
UnknownDynamicStaleTime,
computeDynamicStaleAt,
} from './segment-cache/bfcache'
import { createLinkPrefetchPartialError } from '../../shared/lib/instant-messages'
import {
createNavigationSeed,
type NavigationSeed,
} from './decode-server-response'
} from './segment-cache/decode-server-response'
/**
* Navigate to a new URL, using the Segment Cache to construct a response.
......@@ -71,7 +77,7 @@ export function navigate(
// requested.
if (process.env.__NEXT_EXPOSE_TESTING_API) {
const { isNavigationLocked } =
require('./navigation-testing-lock') as typeof import('./navigation-testing-lock')
require('./segment-cache/navigation-testing-lock') as typeof import('./segment-cache/navigation-testing-lock')
if (isNavigationLocked()) {
// Signal that a new locked navigation is starting. This force-resolves the
// previous locked navigation's withheld data (so a reused shared segment
......@@ -304,7 +310,7 @@ export function navigateToKnownRoute(
let restrictToShell = false
if (process.env.__NEXT_EXPOSE_TESTING_API) {
const { shouldRestrictNavigationToShell } =
require('./navigation-testing-lock') as typeof import('./navigation-testing-lock')
require('./segment-cache/navigation-testing-lock') as typeof import('./segment-cache/navigation-testing-lock')
const link = getLinkForCurrentNavigation()
restrictToShell = shouldRestrictNavigationToShell(
navigationSeed.routeTree.prefetchHints,
......@@ -867,7 +873,7 @@ async function ensurePrefetchThenNavigate(
// cares about has settled — so the navigation below reads present data
// rather than a still-in-flight entry.
const { beginNavigationLockPrefetch } =
require('./navigation-testing-lock') as typeof import('./navigation-testing-lock')
require('./segment-cache/navigation-testing-lock') as typeof import('./segment-cache/navigation-testing-lock')
const navigationLockPrefetch = beginNavigationLockPrefetch()
const prefetchTask = schedulePrefetchTask(
cacheKey,
......@@ -906,7 +912,7 @@ async function ensurePrefetchThenNavigate(
// document load transition it to captured-MPA.
if (!result.pushRef.mpaNavigation) {
const { updateCapturedSPAToTree } =
require('./navigation-testing-lock') as typeof import('./navigation-testing-lock')
require('./segment-cache/navigation-testing-lock') as typeof import('./segment-cache/navigation-testing-lock')
updateCapturedSPAToTree(currentFlightRouterState, result.tree)
}
......
import React, {
useEffect,
useMemo,
startTransition,
useInsertionEffect,
useDeferredValue,
} from 'react'
......@@ -11,7 +10,6 @@ import {
GlobalLayoutRouterContext,
} from '../../shared/lib/app-router-context.shared-runtime'
import type { CacheNode } from '../../shared/lib/app-router-types'
import { ACTION_RESTORE } from './router-reducer/router-reducer-types'
import type {
AppHistoryState,
AppRouterState,
......@@ -24,7 +22,7 @@ import {
NavigationPromisesContext,
type NavigationPromises,
} from '../../shared/lib/hooks-client-context.shared-runtime'
import { dispatchAppRouterAction, useActionQueue } from './use-action-queue'
import { useActionQueue } from './use-action-queue'
import { setLastCommittedTree } from './router-reducer/reducers/committed-state'
import { AppRouterAnnouncer } from './app-router-announcer'
import { RedirectBoundary } from './redirect-boundary'
......@@ -38,11 +36,11 @@ import {
} from './router-reducer/compute-changed-path'
import { useNavFailureHandler } from './nav-failure-handler'
import {
dispatchTraverseAction,
publicAppRouterInstance,
type AppRouterActionQueue,
type GlobalErrorState,
} from './app-router-instance'
import { legacyUrgentBFCacheRestore, restore, traverse } from './navigator'
import { getRedirectTypeFromError, getURLFromRedirectError } from './redirect'
import { isRedirectError } from './redirect-error'
import { pingVisibleLinks } from './links'
......@@ -99,14 +97,7 @@ function handlePopState(state: PopStateEvent['state']): void {
return
}
// TODO-APP: Ideally the back button should not use startTransition as it should apply the updates synchronously
// Without startTransition works if the cache is there for this path
startTransition(() => {
dispatchTraverseAction(
window.location.href,
state.__PRIVATE_NEXTJS_INTERNALS_TREE
)
})
traverse(window.location.href, state.__PRIVATE_NEXTJS_INTERNALS_TREE)
}
function HistoryUpdater({
......@@ -288,11 +279,10 @@ function Router({
// of the last MPA navigation.
globalMutable.pendingMpaPath = undefined
dispatchAppRouterAction({
type: ACTION_RESTORE,
url: new URL(window.location.href),
historyState: window.history.state.__PRIVATE_NEXTJS_INTERNALS_TREE,
})
legacyUrgentBFCacheRestore(
new URL(window.location.href),
window.history.state.__PRIVATE_NEXTJS_INTERNALS_TREE
)
}
window.addEventListener('pageshow', handlePageShow)
......@@ -377,13 +367,7 @@ function Router({
const appHistoryState: AppHistoryState | undefined =
window.history.state?.__PRIVATE_NEXTJS_INTERNALS_TREE
startTransition(() => {
dispatchAppRouterAction({
type: ACTION_RESTORE,
url: new URL(url ?? href, href),
historyState: appHistoryState,
})
})
restore(new URL(url ?? href, href), appHistoryState)
}
/**
......
......@@ -48,7 +48,7 @@ import {
} from '../../shared/lib/hooks-client-context.shared-runtime'
import { getParamValueFromCacheKey } from '../route-params'
import type { Params } from '../../server/request/params'
import { isDeferredRsc } from './router-reducer/ppr-navigations'
import { isDeferredRsc } from './render-tree'
const enum ScrollTargetState {
NoClientRects,
......
// This module is the router's operation interface: one function per
// user-facing operation, called directly by the corresponding entry points
// (Link, the public router methods, the history event handlers).
//
// The navigator owns the startTransition for its operations, along with the
// centralized safety checks; callers must invoke these functions
// synchronously within the originating event.
//
// Server Actions are not a navigator operation: the action queue is
// semantically separate from the router state queue. Its entry point is
// callServer (app-call-server.ts).
//
// The legacy reducer action objects are an implementation detail of the
// current action queue; they are constructed here and never by callers.
//
// This is also the seam where an experimental rewrite of the router state
// machine will fork from the existing implementation, so nothing above this
// interface may depend on how the operations are processed.
import { addTransitionType, startTransition } from 'react'
import {
ACTION_HMR_REFRESH,
ACTION_NAVIGATE,
ACTION_REFRESH,
ACTION_RESTORE,
type AppHistoryState,
type AppRouterState,
type NavigateAction,
ScrollBehavior,
} from './router-reducer/router-reducer-types'
import type { NavigateOptions } from '../../shared/lib/app-router-context.shared-runtime'
import { dispatchAppRouterAction } from './use-action-queue'
import { getCurrentAppRouterState } from './app-router-instance'
import { setLinkForCurrentNavigation, type LinkInstance } from './links'
import type { RouterTransitionPrefetchIntent } from '../router-transition-types'
import { startRouterTransition } from './router-transition'
import { addBasePath } from '../add-base-path'
import { isExternalURL } from './app-router-utils'
import { isJavaScriptURLString } from '../lib/javascript-url'
import { resetKnownRoutes } from './segment-cache/optimistic-routes'
function getRequiredAppRouterState(): AppRouterState {
const state = getCurrentAppRouterState()
if (state === null) {
throw new Error(
'Internal Next.js error: Router action dispatched before initialization.'
)
}
return state
}
export function navigate(
href: string,
navigateType: NavigateAction['navigateType'],
scrollBehavior: ScrollBehavior,
linkInstanceRef: LinkInstance | null,
transitionTypes: string[] | undefined,
prefetchIntent: RouterTransitionPrefetchIntent | null
): void {
if (isJavaScriptURLString(href)) {
throw new Error(
'Next.js has blocked a javascript: URL as a security precaution.'
)
}
startTransition(() => {
// TODO: This stuff could just go into the reducer. Leaving as-is for now
// since we're about to rewrite all the router reducer stuff anyway.
if (transitionTypes) {
for (const type of transitionTypes) {
addTransitionType(type)
}
}
const url = new URL(addBasePath(href), location.href)
if (process.env.__NEXT_APP_NAV_FAIL_HANDLING) {
window.next.__pendingUrl = url
}
setLinkForCurrentNavigation(linkInstanceRef)
startRouterTransition(
href,
navigateType,
getRequiredAppRouterState().tree,
prefetchIntent
)
dispatchAppRouterAction({
type: ACTION_NAVIGATE,
url,
isExternalUrl: isExternalURL(url),
locationSearch: location.search,
scrollBehavior,
navigateType,
})
})
}
export function push(href: string, options?: NavigateOptions): void {
navigate(
href,
'push',
options?.scroll === false
? ScrollBehavior.NoScroll
: ScrollBehavior.Default,
null,
options?.transitionTypes,
null
)
}
export function replace(href: string, options?: NavigateOptions): void {
navigate(
href,
'replace',
options?.scroll === false
? ScrollBehavior.NoScroll
: ScrollBehavior.Default,
null,
options?.transitionTypes,
null
)
}
export function traverse(
href: string,
historyState: AppHistoryState | undefined
): void {
startTransition(() => {
startRouterTransition(
href,
'traverse',
getRequiredAppRouterState().tree,
null
)
restore(new URL(href), historyState)
})
}
/**
* Sync the router state to a history entry that was written by something
* other than a router navigation (a userland pushState/replaceState, or a
* bfcache restore). Unlike a traversal, this does not represent a transition
* between routes.
*/
export function restore(
url: URL,
historyState: AppHistoryState | undefined
): void {
startTransition(() => {
dispatchAppRouterAction({
type: ACTION_RESTORE,
url,
historyState,
})
})
}
/**
* The bfcache `pageshow` restore (see the pageshow handler in app-router.tsx).
* Unlike every other navigator operation, this dispatches as a deliberately
* urgent (non-transition) update: the restored state reset must render before
* anything else can observe the stale mpaNavigation state and re-fire the MPA
* navigation the restore exists to prevent. As a transition it would be
* interruptible, and an intervening urgent render could commit against the
* stale state first.
*
* This is a preserved legacy special case. It will not be carried into the
* concurrent router queue, which handles bfcache restore through its own
* design.
*/
export function legacyUrgentBFCacheRestore(
url: URL,
historyState: AppHistoryState | undefined
): void {
dispatchAppRouterAction({
type: ACTION_RESTORE,
url,
historyState,
})
}
export function refresh(): void {
startTransition(() => {
dispatchAppRouterAction({
type: ACTION_REFRESH,
})
})
}
// Tracks the newest HMR refresh generation so that a newer refresh can abort
// the request of the one it supersedes. Development only.
let activeHmrRefreshController: AbortController | null = null
// Development only.
export function hmrRefresh(): void {
if (process.env.NODE_ENV !== 'development') {
throw new Error(
'hmrRefresh can only be used in development mode. Please use refresh instead.'
)
} else {
// Reset the known routes table so that route predictions are cleared
// when routes change during development.
resetKnownRoutes()
let signal: AbortSignal | undefined
if (process.env.__NEXT_SERVER_COMPONENTS_HMR_CANCELLATION) {
// Abort the superseded generation before scheduling the new one, so its
// request is torn down as early as possible. Halting (not rejecting)
// makes the abort safe regardless of order.
activeHmrRefreshController?.abort()
activeHmrRefreshController = new AbortController()
signal = activeHmrRefreshController.signal
}
startTransition(() => {
dispatchAppRouterAction({
type: ACTION_HMR_REFRESH,
signal,
})
})
}
}
import type { FlightRouterState } from '../../../shared/lib/app-router-types'
import { createPrefetchURL } from '../app-router-utils'
import { createCacheKey } from './cache-key'
import { schedulePrefetchTask } from './scheduler'
import { PrefetchPriority, type PrefetchTaskFetchStrategy } from './types'
import type { FlightRouterState } from '../../shared/lib/app-router-types'
import type { PrefetchOptions } from '../../shared/lib/app-router-context.shared-runtime'
import { PrefetchKind } from './router-reducer/router-reducer-types'
import { createPrefetchURL } from './app-router-utils'
import { getCurrentAppRouterState } from './app-router-instance'
import { isJavaScriptURLString } from '../lib/javascript-url'
import { createCacheKey } from './segment-cache/cache-key'
import { schedulePrefetchTask } from './segment-cache/scheduler'
import {
FetchStrategy,
PrefetchPriority,
type PrefetchTaskFetchStrategy,
} from './segment-cache/types'
/**
* The public prefetch operation, exposed through `router.prefetch`. Converts
* the public options into a fetch strategy, reads the current router state,
* and drives the Segment Cache.
*
* Unlike the old implementation, the Segment Cache doesn't store its data in
* the router reducer state; it writes into a global mutable cache. So we
* don't need to dispatch an action.
*/
export function prefetchRoute(href: string, options?: PrefetchOptions): void {
if (isJavaScriptURLString(href)) {
throw new Error(
'Next.js has blocked a javascript: URL as a security precaution.'
)
}
const state = getCurrentAppRouterState()
if (state === null) {
throw new Error(
'Internal Next.js error: Router action dispatched before initialization.'
)
}
const prefetchKind = options?.kind ?? PrefetchKind.AUTO
// We don't currently offer a way to issue a runtime prefetch via `router.prefetch()`.
// This will be possible when we update its API to not take a PrefetchKind.
let fetchStrategy: PrefetchTaskFetchStrategy
switch (prefetchKind) {
case PrefetchKind.AUTO: {
// We default to PPR. We'll discover whether or not the route supports it with the initial prefetch.
fetchStrategy = FetchStrategy.PPR
break
}
case PrefetchKind.FULL: {
fetchStrategy = FetchStrategy.Full
break
}
default: {
prefetchKind satisfies never
// Despite typescript thinking that this can't happen,
// we might get an unexpected value from user code.
// We don't know what they want, but we know they want a prefetch,
// so use the default.
fetchStrategy = FetchStrategy.PPR
}
}
prefetch(
href,
state.nextUrl,
state.tree,
fetchStrategy,
options?.onInvalidate ?? null
)
}
/**
* Entrypoint for prefetching a URL into the Segment Cache.
......
import type {
FlightRouterState,
Segment,
} from '../../../shared/lib/app-router-types'
import type { CacheNode } from '../../../shared/lib/app-router-types'
import type { HeadData, ScrollRef } from '../../../shared/lib/app-router-types'
import { PrefetchHint } from '../../../shared/lib/app-router-types'
} from '../../shared/lib/app-router-types'
import type { CacheNode } from '../../shared/lib/app-router-types'
import type { HeadData, ScrollRef } from '../../shared/lib/app-router-types'
import { PrefetchHint } from '../../shared/lib/app-router-types'
import {
PAGE_SEGMENT_KEY,
DEFAULT_SEGMENT_KEY,
NOT_FOUND_SEGMENT_KEY,
} from '../../../shared/lib/segment'
import { matchSegment } from '../match-segments'
import { createHrefFromUrl } from './create-href-from-url'
import { fetchServerResponse } from './fetch-server-response'
import { dispatchAppRouterAction } from '../use-action-queue'
} from '../../shared/lib/segment'
import { matchSegment } from './match-segments'
import { createHrefFromUrl } from './router-reducer/create-href-from-url'
import { fetchServerResponse } from './router-reducer/fetch-server-response'
import { dispatchAppRouterAction } from './use-action-queue'
import {
ACTION_SERVER_PATCH,
type ServerPatchAction,
} from './router-reducer-types'
import { isNavigatingToNewRootLayout } from './is-navigating-to-new-root-layout'
import { getLastCommittedTree } from './reducers/committed-state'
} from './router-reducer/router-reducer-types'
import { isNavigatingToNewRootLayout } from './router-reducer/is-navigating-to-new-root-layout'
import { getLastCommittedTree } from './router-reducer/reducers/committed-state'
import {
createNavigationSeed,
type NavigationSeed,
} from '../segment-cache/decode-server-response'
} from './segment-cache/decode-server-response'
import {
segmentCacheMap,
type SegmentCacheEntry,
......@@ -39,15 +39,15 @@ import {
spawnStaticStageCacheWrite,
writeRuntimePrefetchStreamIntoCache,
EntryStatus,
} from '../segment-cache/cache'
import { discoverKnownRoute } from '../segment-cache/optimistic-routes'
import { urlSearchParamsToParsedUrlQuery } from '../../route-params'
import type { NormalizedSearch } from '../segment-cache/cache-key'
import type { CacheMap } from '../segment-cache/cache-map'
} from './segment-cache/cache'
import { discoverKnownRoute } from './segment-cache/optimistic-routes'
import { urlSearchParamsToParsedUrlQuery } from '../route-params'
import type { NormalizedSearch } from './segment-cache/cache-key'
import type { CacheMap } from './segment-cache/cache-map'
import {
getRenderedSearchFromVaryPath,
type PageVaryPath,
} from '../segment-cache/vary-path'
} from './segment-cache/vary-path'
import {
readFromBFCache,
readFromBFCacheDuringRegularNavigation,
......@@ -55,7 +55,7 @@ import {
writeHeadToBFCache,
updateBFCacheEntryStaleAt,
computeDynamicStaleAt,
} from '../segment-cache/bfcache'
} from './segment-cache/bfcache'
// This is yet another tree type that is used to track pending promises that
// need to be fulfilled once the dynamic data is received. The terminal nodes of
......@@ -2293,7 +2293,7 @@ function createDeferredRsc<
export function getCurrentNavigationLock(): NavigationLock | null {
if (process.env.__NEXT_EXPOSE_TESTING_API) {
const { getCurrentNavigationGate } =
require('../segment-cache/navigation-testing-lock') as typeof import('../segment-cache/navigation-testing-lock')
require('./segment-cache/navigation-testing-lock') as typeof import('./segment-cache/navigation-testing-lock')
return getCurrentNavigationGate()
}
return null
......@@ -2311,7 +2311,7 @@ export function getCurrentNavigationLock(): NavigationLock | null {
export function beginLockedNavigation(): NavigationLock | null {
if (process.env.__NEXT_EXPOSE_TESTING_API) {
const { beginLockedNavigation: begin } =
require('../segment-cache/navigation-testing-lock') as typeof import('../segment-cache/navigation-testing-lock')
require('./segment-cache/navigation-testing-lock') as typeof import('./segment-cache/navigation-testing-lock')
return begin()
}
return null
......@@ -2326,7 +2326,7 @@ export function beginLockedNavigation(): NavigationLock | null {
export function resetNavigationLockToPending(): void {
if (process.env.__NEXT_EXPOSE_TESTING_API) {
const { resetNavigationLockToPending: reset } =
require('../segment-cache/navigation-testing-lock') as typeof import('../segment-cache/navigation-testing-lock')
require('./segment-cache/navigation-testing-lock') as typeof import('./segment-cache/navigation-testing-lock')
reset()
}
}
......@@ -5,7 +5,7 @@ import { extractPathFromFlightRouterState } from './compute-changed-path'
import type { AppRouterState } from './router-reducer-types'
import { transportNodeToFlightRouterState } from '../../../shared/lib/rsc-transport'
import { createInitialCacheNodeForHydration } from './ppr-navigations'
import { createInitialCacheNodeForHydration } from '../render-tree'
import {
writeRuntimePrefetchStreamIntoCache,
spawnStaticStageCacheWrite,
......
......@@ -4,7 +4,7 @@ import type {
ReducerState,
} from '../router-reducer-types'
import { refreshDynamicData } from './refresh-reducer'
import { FreshnessPolicy } from '../ppr-navigations'
import { FreshnessPolicy } from '../../render-tree'
export function hmrRefreshReducer(
state: ReadonlyReducerState,
......
......@@ -7,9 +7,9 @@ import type {
import {
completeHardNavigation,
navigate as navigateUsingSegmentCache,
} from '../../segment-cache/navigation'
} from '../../app-router-state'
import { getStaleTimeMs } from '../../segment-cache/cache'
import { FreshnessPolicy } from '../ppr-navigations'
import { FreshnessPolicy } from '../../render-tree'
// These values are set by `define-env-plugin` (based on `nextConfig.experimental.staleTimes`)
// and default to 5 minutes (static) / 0 seconds (dynamic)
......
......@@ -4,14 +4,14 @@ import type {
RefreshAction,
} from '../router-reducer-types'
import { ScrollBehavior } from '../router-reducer-types'
import { navigateToKnownRoute } from '../../segment-cache/navigation'
import { navigateToKnownRoute } from '../../app-router-state'
import { createNavigationSeed } from '../../segment-cache/decode-server-response'
import {
invalidateSegmentCacheEntries,
segmentCacheMap,
} from '../../segment-cache/cache'
import { hasInterceptionRouteInCurrentTree } from './has-interception-route-in-current-tree'
import { FreshnessPolicy, getCurrentNavigationLock } from '../ppr-navigations'
import { FreshnessPolicy, getCurrentNavigationLock } from '../../render-tree'
import {
invalidateBfCache,
UnknownDynamicStaleTime,
......
......@@ -10,12 +10,12 @@ import {
spawnDynamicRequests,
startPPRNavigation,
type NavigationRequestAccumulation,
} from '../ppr-navigations'
} from '../../render-tree'
import type { FlightRouterState } from '../../../../shared/lib/app-router-types'
import {
completeHardNavigation,
completeTraverseNavigation,
} from '../../segment-cache/navigation'
} from '../../app-router-state'
import { createNavigationSeed } from '../../segment-cache/decode-server-response'
import { segmentCacheMap } from '../../segment-cache/cache'
import { UnknownDynamicStaleTime } from '../../segment-cache/bfcache'
......
......@@ -56,7 +56,7 @@ import {
completeHardNavigation,
navigateToKnownRoute,
navigate,
} from '../../segment-cache/navigation'
} from '../../app-router-state'
import { createNavigationSeed } from '../../segment-cache/decode-server-response'
import { discoverKnownRoute } from '../../segment-cache/optimistic-routes'
import type { NormalizedSearch } from '../../segment-cache/cache-key'
......@@ -67,7 +67,7 @@ import {
type ActionRevalidationKind,
} from '../../../../shared/lib/action-revalidation-kind'
import { isExternalURL } from '../../app-router-utils'
import { FreshnessPolicy, getCurrentNavigationLock } from '../ppr-navigations'
import { FreshnessPolicy, getCurrentNavigationLock } from '../../render-tree'
import { processFetch } from '../fetch-server-response'
import {
invalidateBfCache,
......
......@@ -9,10 +9,10 @@ import {
import {
completeHardNavigation,
navigateToKnownRoute,
} from '../../segment-cache/navigation'
} from '../../app-router-state'
import { segmentCacheMap } from '../../segment-cache/cache'
import { refreshReducer } from './refresh-reducer'
import { getCurrentNavigationLock } from '../ppr-navigations'
import { getCurrentNavigationLock } from '../../render-tree'
export function serverPatchReducer(
state: ReadonlyReducerState,
......
......@@ -2,7 +2,7 @@ import type { CacheNode, ScrollRef } from '../../../shared/lib/app-router-types'
import type { FlightRouterState } from '../../../shared/lib/app-router-types'
import type { NavigationSeed } from '../segment-cache/decode-server-response'
import type { FetchServerResponseResult } from './fetch-server-response'
import type { FreshnessPolicy } from './ppr-navigations'
import type { FreshnessPolicy } from '../render-tree'
export const ACTION_REFRESH = 'refresh'
export const ACTION_NAVIGATE = 'navigate'
......
......@@ -5477,7 +5477,7 @@ async function streamStagedRenderInDev({
// earlier on a cache miss). When streaming live (a client navigation), it's
// surfaced through the Flight payload as `_revealAfter`: the client decodes
// it and defers resolving the response's deferred RSCs on it (see
// `ppr-navigations`), so a Suspense boundary's children aren't revealed
// `render-tree`), so a Suspense boundary's children aren't revealed
// before their row has been decoded, which would flush a premature fallback.
// React serializes the promise as a pending row whose resolution row is
// emitted only when we resolve it here, and that row follows the children's
......
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