Unverified Commit d8d3b2e0 authored by Hendrik Liebau's avatar Hendrik Liebau Committed by GitHub

Unhook WebSocket (#82931)

Currently, the WebSocket that's used for `next dev` is created in a React hook inside of the `HotReload` component, which is (transitively) rendered by the `ServerRoot` component, but only after the initial RSC response is processed, at least partially.

This creates a problem when integrating React's debug channel, because the root model of the RSC payload will be blocked until the associated debug info has been received through the debug channel. Since we will be using the existing WebSocket connection for the debug channel, we need to establish it before the `ServerRoot` component is rendered to avoid a deadlock.

The next-devtools dispatcher does queue events before React has provided the `dispatch` function in `DevOverlayRoot`. So creating the WebSocket outside of rendering is already supported in that regard.

closes NAR-323
parent 94f422e4
......@@ -780,5 +780,9 @@
"779": "Route %s used \"searchParams\" inside \"use cache\". Accessing dynamic request data inside a cache scope is not supported. If you need some search params inside a cached function await \"searchParams\" outside of the cached function and pass only the required search params as arguments to the cached function. See more info here: https://nextjs.org/docs/messages/next-request-in-use-cache",
"780": "Invariant: failed to find parent dynamic route for notFound route %s",
"781": "No LRU node to remove",
"782": "Failed to find the root directory of the project. This is a bug in Next.js."
"782": "Failed to find the root directory of the project. This is a bug in Next.js.",
"783": "Expected document.currentScript to be a <script> element. Received %s instead.",
"784": "Expected document.currentScript src to contain '/_next/'. Received %s instead.",
"785": "Expected webSocket to be defined in dev mode.",
"786": "Expected staticIndicatorState to be defined in dev mode."
}
......@@ -5,6 +5,7 @@
* - next/script with `beforeInteractive` strategy
*/
import { getAssetPrefix } from './asset-prefix'
import { setAttributesFromProps } from './set-attributes-from-props'
const version = process.env.__NEXT_VERSION
......@@ -54,7 +55,9 @@ function loadScriptsInSequence(
})
}
export function appBootstrap(hydrate: () => void) {
export function appBootstrap(hydrate: (assetPrefix: string) => void) {
const assetPrefix = getAssetPrefix()
loadScriptsInSequence((self as any).__next_s, () => {
// If the static shell is being debugged, skip hydration if the
// `__nextppronly` query is present. This is only enabled when the
......@@ -73,6 +76,6 @@ export function appBootstrap(hydrate: () => void) {
}
}
hydrate()
hydrate(assetPrefix)
})
}
......@@ -21,6 +21,7 @@ import type { InitialRSCPayload } from '../shared/lib/app-router-types'
import { createInitialRouterState } from './components/router-reducer/create-initial-router-state'
import { MissingSlotContext } from '../shared/lib/app-router-context.shared-runtime'
import { setAppBuildId } from './app-build-id'
import type { StaticIndicatorState } from './dev/hot-reloader/app/hot-reloader-app'
/// <reference types="react-dom/experimental" />
......@@ -160,8 +161,12 @@ const initialServerResponse = createFromReadableStream<InitialRSCPayload>(
function ServerRoot({
pendingActionQueue,
webSocket,
staticIndicatorState,
}: {
pendingActionQueue: Promise<AppRouterActionQueue>
webSocket: WebSocket | undefined
staticIndicatorState: StaticIndicatorState | undefined
}): React.ReactNode {
const initialRSCPayload = use(initialServerResponse)
const actionQueue = use<AppRouterActionQueue>(pendingActionQueue)
......@@ -170,7 +175,8 @@ function ServerRoot({
<AppRouter
actionQueue={actionQueue}
globalErrorState={initialRSCPayload.G}
assetPrefix={initialRSCPayload.p}
webSocket={webSocket}
staticIndicatorState={staticIndicatorState}
/>
)
......@@ -225,8 +231,20 @@ export type ClientInstrumentationHooks = {
}
export function hydrate(
instrumentationHooks: ClientInstrumentationHooks | null
instrumentationHooks: ClientInstrumentationHooks | null,
assetPrefix: string
) {
let staticIndicatorState: StaticIndicatorState | undefined
let webSocket: WebSocket | undefined
if (process.env.NODE_ENV !== 'production') {
const { createWebSocket } =
require('./dev/hot-reloader/app/web-socket') as typeof import('./dev/hot-reloader/app/web-socket')
staticIndicatorState = { pathname: null, appIsrManifest: {} }
webSocket = createWebSocket(assetPrefix, staticIndicatorState)
}
// React overrides `.then` and doesn't return a new promise chain,
// so we wrap the action queue in a promise to ensure that its value
// is defined when the promise resolves.
......@@ -266,7 +284,11 @@ export function hydrate(
<StrictModeIfEnabled>
<HeadManagerContext.Provider value={{ appDir: true }}>
<Root>
<ServerRoot pendingActionQueue={pendingActionQueue} />
<ServerRoot
pendingActionQueue={pendingActionQueue}
webSocket={webSocket}
staticIndicatorState={staticIndicatorState}
/>
</Root>
</HeadManagerContext.Provider>
</StrictModeIfEnabled>
......
......@@ -10,10 +10,10 @@ import { isRecoverableError } from './react-client-callbacks/on-recoverable-erro
// eslint-disable-next-line @next/internal/typechecked-require
const instrumentationHooks = require('../lib/require-instrumentation-client')
appBootstrap(() => {
appBootstrap((assetPrefix) => {
const { hydrate } = require('./app-index') as typeof import('./app-index')
try {
hydrate(instrumentationHooks)
hydrate(instrumentationHooks, assetPrefix)
} finally {
renderAppDevOverlay(getOwnerStack, isRecoverableError)
}
......
......@@ -7,10 +7,10 @@ window.next.turbopack = true
// eslint-disable-next-line @next/internal/typechecked-require
const instrumentationHooks = require('../lib/require-instrumentation-client')
appBootstrap(() => {
appBootstrap((assetPrefix) => {
const { hydrate } = require('./app-index') as typeof import('./app-index')
try {
hydrate(instrumentationHooks)
hydrate(instrumentationHooks, assetPrefix)
} finally {
if (process.env.NODE_ENV !== 'production') {
const { getOwnerStack } =
......
......@@ -7,12 +7,12 @@ const instrumentationHooks =
// eslint-disable-next-line @next/internal/typechecked-require -- not a module
require('../lib/require-instrumentation-client')
appBootstrap(() => {
appBootstrap((assetPrefix) => {
const { hydrate } = require('./app-index') as typeof import('./app-index')
// Include app-router and layout-router in the main chunk
// eslint-disable-next-line @next/internal/typechecked-require -- Why not relative imports?
require('next/dist/client/components/app-router')
// eslint-disable-next-line @next/internal/typechecked-require -- Why not relative imports?
require('next/dist/client/components/layout-router')
hydrate(instrumentationHooks)
hydrate(instrumentationHooks, assetPrefix)
})
import { InvariantError } from '../shared/lib/invariant-error'
export function getAssetPrefix() {
const currentScript = document.currentScript
if (!(currentScript instanceof HTMLScriptElement)) {
throw new InvariantError(
`Expected document.currentScript to be a <script> element. Received ${currentScript} instead.`
)
}
const { pathname } = new URL(currentScript.src)
const nextIndex = pathname.indexOf('/_next/')
if (nextIndex === -1) {
throw new InvariantError(
`Expected document.currentScript src to contain '/_next/'. Received ${currentScript.src} instead.`
)
}
return pathname.slice(0, nextIndex)
}
......@@ -47,6 +47,7 @@ import { pingVisibleLinks } from './links'
import RootErrorBoundary from './errors/root-error-boundary'
import DefaultGlobalError from './builtin/global-error'
import { RootLayoutBoundary } from '../../lib/framework/boundary-components'
import type { StaticIndicatorState } from '../dev/hot-reloader/app/hot-reloader-app'
const globalMutable: {
pendingMpaPath?: string
......@@ -196,12 +197,14 @@ function Head({
*/
function Router({
actionQueue,
assetPrefix,
globalError,
webSocket,
staticIndicatorState,
}: {
actionQueue: AppRouterActionQueue
assetPrefix: string
globalError: GlobalErrorState
webSocket: WebSocket | undefined
staticIndicatorState: StaticIndicatorState | undefined
}) {
const state = useActionQueue(actionQueue)
const { canonicalUrl } = state
......@@ -524,7 +527,11 @@ function Router({
).default
content = (
<HotReloader assetPrefix={assetPrefix} globalError={globalError}>
<HotReloader
globalError={globalError}
webSocket={webSocket}
staticIndicatorState={staticIndicatorState}
>
{content}
</HotReloader>
)
......@@ -570,19 +577,22 @@ function Router({
export default function AppRouter({
actionQueue,
globalErrorState,
assetPrefix,
webSocket,
staticIndicatorState,
}: {
actionQueue: AppRouterActionQueue
globalErrorState: GlobalErrorState
assetPrefix: string
webSocket?: WebSocket
staticIndicatorState?: StaticIndicatorState
}) {
useNavFailureHandler()
const router = (
<Router
actionQueue={actionQueue}
assetPrefix={assetPrefix}
globalError={globalErrorState}
webSocket={webSocket}
staticIndicatorState={staticIndicatorState}
/>
)
......
/// <reference types="webpack/module.d.ts" />
import type { ReactNode } from 'react'
import { useEffect, startTransition, useRef } from 'react'
import { useEffect, startTransition } from 'react'
import stripAnsi from 'next/dist/compiled/strip-ansi'
import formatWebpackMessages from '../../../../shared/lib/format-webpack-messages'
import { useRouter } from '../../../components/navigation'
import {
REACT_REFRESH_FULL_RELOAD,
REACT_REFRESH_FULL_RELOAD_FROM_ERROR,
reportInvalidHmrMessage,
} from '../shared'
import { dispatcher } from 'next/dist/compiled/next-devtools'
import { ReplaySsrOnlyErrors } from '../../../../next-devtools/userspace/app/errors/replay-ssr-only-errors'
import { AppDevOverlayErrorBoundary } from '../../../../next-devtools/userspace/app/app-dev-overlay-error-boundary'
import { useErrorHandler } from '../../../../next-devtools/userspace/app/errors/use-error-handler'
import { RuntimeErrorHandler } from '../../runtime-error-handler'
import {
useSendMessage,
useTurbopack,
useWebSocket,
useWebSocketPing,
} from './web-socket'
import { useWebSocketPing } from './web-socket'
import { HMR_ACTIONS_SENT_TO_BROWSER } from '../../../../server/dev/hot-reloader-types'
import type {
HMR_ACTION_TYPES,
......@@ -30,8 +23,16 @@ import { useUntrackedPathname } from '../../../components/navigation-untracked'
import reportHmrLatency from '../../report-hmr-latency'
import { TurbopackHmr } from '../turbopack-hot-reloader-common'
import { NEXT_HMR_REFRESH_HASH_COOKIE } from '../../../components/app-router-headers'
import type { GlobalErrorState } from '../../../components/app-router-instance'
import { useForwardConsoleLog } from '../../../../next-devtools/userspace/app/errors/use-forward-console-log'
import {
publicAppRouterInstance,
type GlobalErrorState,
} from '../../../components/app-router-instance'
import { InvariantError } from '../../../../shared/lib/invariant-error'
export interface StaticIndicatorState {
pathname: string | null
appIsrManifest: Record<string, true>
}
let mostRecentCompilationHash: any = null
let __nextDevClientId = Math.round(Math.random() * 100 + Date.now())
......@@ -95,7 +96,10 @@ function afterApplyUpdates(fn: any) {
}
}
function performFullReload(err: any, sendMessage: any) {
export function performFullReload(
err: any,
sendMessage: (data: string) => void
) {
const stackTrace =
err &&
((err.stack && err.stack.split('\n').slice(0, 5).join('\n')) ||
......@@ -192,13 +196,11 @@ function tryApplyUpdatesWebpack(sendMessage: (message: string) => void) {
}
/** Handles messages from the server for the App Router. */
function processMessage(
export function processMessage(
obj: HMR_ACTION_TYPES,
sendMessage: (message: string) => void,
processTurbopackMessage: (msg: TurbopackMsgToBrowser) => void,
router: ReturnType<typeof useRouter>,
appIsrManifestRef: ReturnType<typeof useRef>,
pathnameRef: ReturnType<typeof useRef>
staticIndicatorState: StaticIndicatorState
) {
if (!('action' in obj)) {
return
......@@ -251,18 +253,19 @@ function processMessage(
switch (obj.action) {
case HMR_ACTIONS_SENT_TO_BROWSER.ISR_MANIFEST: {
if (process.env.__NEXT_DEV_INDICATOR) {
if (appIsrManifestRef) {
appIsrManifestRef.current = obj.data
// handle initial status on receiving manifest
// navigation is handled in useEffect for pathname changes
// as we'll receive the updated manifest before usePathname
// triggers for new value
if ((pathnameRef.current as string) in obj.data) {
dispatcher.onStaticIndicator(true)
} else {
dispatcher.onStaticIndicator(false)
}
staticIndicatorState.appIsrManifest = obj.data
// handle initial status on receiving manifest
// navigation is handled in useEffect for pathname changes
// as we'll receive the updated manifest before usePathname
// triggers for new value
if (
staticIndicatorState.pathname &&
staticIndicatorState.pathname in obj.data
) {
dispatcher.onStaticIndicator(true)
} else {
dispatcher.onStaticIndicator(false)
}
}
break
......@@ -401,7 +404,7 @@ function processMessage(
}
startTransition(() => {
router.hmrRefresh()
publicAppRouterInstance.hmrRefresh()
dispatcher.onRefresh()
})
......@@ -430,7 +433,7 @@ function processMessage(
case HMR_ACTIONS_SENT_TO_BROWSER.REMOVED_PAGE: {
turbopackHmr?.onPageAddRemove()
// TODO-APP: potentially only refresh if the currently viewed page was added/removed.
return router.hmrRefresh()
return publicAppRouterInstance.hmrRefresh()
}
case HMR_ACTIONS_SENT_TO_BROWSER.SERVER_ERROR: {
const { errorJSON } = obj
......@@ -456,96 +459,44 @@ function processMessage(
}
export default function HotReload({
assetPrefix,
children,
globalError,
webSocket,
staticIndicatorState,
}: {
assetPrefix: string
children: ReactNode
globalError: GlobalErrorState
webSocket: WebSocket | undefined
staticIndicatorState: StaticIndicatorState | undefined
}) {
useErrorHandler(dispatcher.onUnhandledError, dispatcher.onUnhandledRejection)
const webSocketRef = useWebSocket(assetPrefix)
useWebSocketPing(webSocketRef)
const sendMessage = useSendMessage(webSocketRef)
useForwardConsoleLog(webSocketRef)
const processTurbopackMessage = useTurbopack(sendMessage, (err) =>
performFullReload(err, sendMessage)
)
const router = useRouter()
useWebSocketPing(webSocket)
// We don't want access of the pathname for the dev tools to trigger a dynamic
// access (as the dev overlay will never be present in production).
const pathname = useUntrackedPathname()
const appIsrManifestRef = useRef<Record<string, false | number>>({})
const pathnameRef = useRef(pathname)
if (process.env.__NEXT_DEV_INDICATOR) {
// this conditional is only for dead-code elimination which
// isn't a runtime conditional only build-time so ignore hooks rule
// eslint-disable-next-line react-hooks/rules-of-hooks
useEffect(() => {
pathnameRef.current = pathname
const appIsrManifest = appIsrManifestRef.current
if (appIsrManifest) {
if (pathname && pathname in appIsrManifest) {
try {
dispatcher.onStaticIndicator(true)
} catch (reason) {
let message = ''
if (reason instanceof DOMException) {
// Most likely a SecurityError, because of an unavailable localStorage
message = reason.stack ?? reason.message
} else if (reason instanceof Error) {
message = 'Error: ' + reason.message + '\n' + (reason.stack ?? '')
} else {
message = 'Unexpected Exception: ' + reason
}
console.warn('[HMR] ' + message)
}
} else {
dispatcher.onStaticIndicator(false)
}
if (!staticIndicatorState) {
throw new InvariantError(
'Expected staticIndicatorState to be defined in dev mode.'
)
}
}, [pathname])
}
useEffect(() => {
const websocket = webSocketRef.current
if (!websocket) return
staticIndicatorState.pathname = pathname
const handler = (event: MessageEvent<any>) => {
try {
const obj = JSON.parse(event.data)
processMessage(
obj,
sendMessage,
processTurbopackMessage,
router,
appIsrManifestRef,
pathnameRef
)
} catch (err: unknown) {
reportInvalidHmrMessage(event, err)
if (pathname && pathname in staticIndicatorState.appIsrManifest) {
dispatcher.onStaticIndicator(true)
} else {
dispatcher.onStaticIndicator(false)
}
}
}, [pathname, staticIndicatorState])
}
websocket.addEventListener('message', handler)
return () => websocket.removeEventListener('message', handler)
}, [
sendMessage,
router,
webSocketRef,
processTurbopackMessage,
appIsrManifestRef,
])
return (
<AppDevOverlayErrorBoundary globalError={globalError}>
<ReplaySsrOnlyErrors onBlockingError={dispatcher.openErrorOverlay} />
......
import { useCallback, useContext, useEffect, useRef } from 'react'
import { useContext, useEffect } from 'react'
import { GlobalLayoutRouterContext } from '../../../../shared/lib/app-router-context.shared-runtime'
import { getSocketUrl } from '../get-socket-url'
import type { TurbopackMsgToBrowser } from '../../../../server/dev/hot-reloader-types'
import { reportInvalidHmrMessage } from '../shared'
import {
performFullReload,
processMessage,
type StaticIndicatorState,
} from './hot-reloader-app'
import {
isTerminalLoggingEnabled,
logQueue,
} from '../../../../next-devtools/userspace/app/forward-logs'
import { InvariantError } from '../../../../shared/lib/invariant-error'
export function useWebSocket(assetPrefix: string) {
const webSocketRef = useRef<WebSocket>(undefined)
export function createWebSocket(
assetPrefix: string,
staticIndicatorState: StaticIndicatorState
) {
const url = getSocketUrl(assetPrefix)
const webSocket = new window.WebSocket(`${url}/_next/webpack-hmr`)
useEffect(() => {
if (webSocketRef.current) {
return
if (isTerminalLoggingEnabled) {
webSocket.addEventListener('open', () => {
logQueue.onSocketReady(webSocket)
})
}
const sendMessage = (data: string) => {
if (webSocket.readyState === webSocket.OPEN) {
webSocket.send(data)
}
}
const url = getSocketUrl(assetPrefix)
const processTurbopackMessage = createProcessTurbopackMessage(sendMessage)
webSocketRef.current = new window.WebSocket(`${url}/_next/webpack-hmr`)
}, [assetPrefix])
webSocket.addEventListener('message', (event) => {
try {
const obj = JSON.parse(event.data)
processMessage(
obj,
sendMessage,
processTurbopackMessage,
staticIndicatorState
)
} catch (err: unknown) {
reportInvalidHmrMessage(event, err)
}
})
return webSocketRef
return webSocket
}
export function useSendMessage(webSocketRef: ReturnType<typeof useWebSocket>) {
const sendMessage = useCallback(
(data: string) => {
const socket = webSocketRef.current
if (!socket || socket.readyState !== socket.OPEN) {
return
}
return socket.send(data)
},
[webSocketRef]
)
return sendMessage
}
export function createProcessTurbopackMessage(
sendMessage: (data: string) => void
): (msg: TurbopackMsgToBrowser) => void {
if (!process.env.TURBOPACK) {
return () => {}
}
export function useTurbopack(
sendMessage: ReturnType<typeof useSendMessage>,
onUpdateError: (err: unknown) => void
) {
const turbopackState = useRef<{
init: boolean
queue: Array<TurbopackMsgToBrowser> | undefined
callback: ((msg: TurbopackMsgToBrowser) => void) | undefined
}>({
init: false,
// Until the dynamic import resolves, queue any turbopack messages which will be replayed.
queue: [],
callback: undefined,
})
let queue: TurbopackMsgToBrowser[] = []
let callback: ((msg: TurbopackMsgToBrowser) => void) | undefined
const processTurbopackMessage = useCallback((msg: TurbopackMsgToBrowser) => {
const { callback, queue } = turbopackState.current
const processTurbopackMessage = (msg: TurbopackMsgToBrowser) => {
if (callback) {
callback(msg)
} else {
queue!.push(msg)
queue.push(msg)
}
}, [])
}
useEffect(() => {
const { current: initCurrent } = turbopackState
// TODO(WEB-1589): only install if `process.turbopack` set.
if (initCurrent.init) {
return
}
initCurrent.init = true
import(
// @ts-expect-error requires "moduleResolution": "node16" in tsconfig.json and not .ts extension
'@vercel/turbopack-ecmascript-runtime/browser/dev/hmr-client/hmr-client.ts'
).then(({ connect }) => {
const { current } = turbopackState
connect({
addMessageListener(cb: (msg: TurbopackMsgToBrowser) => void) {
current.callback = cb
// Replay all Turbopack messages before we were able to establish the HMR client.
for (const msg of current.queue!) {
cb(msg)
}
current.queue = undefined
},
sendMessage,
onUpdateError,
})
import(
// @ts-expect-error requires "moduleResolution": "node16" in tsconfig.json and not .ts extension
'@vercel/turbopack-ecmascript-runtime/browser/dev/hmr-client/hmr-client.ts'
).then(({ connect }) => {
connect({
addMessageListener(cb: (msg: TurbopackMsgToBrowser) => void) {
callback = cb
// Replay all Turbopack messages before we were able to establish the HMR client.
for (const msg of queue) {
cb(msg)
}
queue.length = 0
},
sendMessage,
onUpdateError: (err: unknown) => performFullReload(err, sendMessage),
})
}, [sendMessage, onUpdateError])
})
return processTurbopackMessage
}
export function useWebSocketPing(
webSocketRef: ReturnType<typeof useWebSocket>
) {
const sendMessage = useSendMessage(webSocketRef)
export function useWebSocketPing(webSocket: WebSocket | undefined) {
const { tree } = useContext(GlobalLayoutRouterContext)
useEffect(() => {
if (!webSocket) {
throw new InvariantError('Expected webSocket to be defined in dev mode.')
}
// Never send pings when using Turbopack as it's not used.
// Pings were originally used to keep track of active routes in on-demand-entries with webpack.
if (process.env.TURBOPACK) {
......@@ -104,14 +108,16 @@ export function useWebSocketPing(
// Taken from on-demand-entries-client.js
const interval = setInterval(() => {
sendMessage(
JSON.stringify({
event: 'ping',
tree,
appDirRoute: true,
})
)
if (webSocket.readyState === webSocket.OPEN) {
webSocket.send(
JSON.stringify({
event: 'ping',
tree,
appDirRoute: true,
})
)
}
}, 2500)
return () => clearInterval(interval)
}, [tree, sendMessage])
}, [tree, webSocket])
}
import { useEffect } from 'react'
import { isTerminalLoggingEnabled, logQueue } from '../forward-logs'
import type { useWebSocket } from '../../../../client/dev/hot-reloader/app/web-socket'
export const useForwardConsoleLog = (
socketRef: ReturnType<typeof useWebSocket>
) => {
useEffect(() => {
if (!isTerminalLoggingEnabled) {
return
}
const socket = socketRef.current
if (!socket) {
return
}
const onOpen = () => {
logQueue.onSocketReady(socket)
}
socket.addEventListener('open', onOpen)
return () => {
socket.removeEventListener('open', onOpen)
}
}, [socketRef])
}
......@@ -1171,7 +1171,6 @@ async function getRSCPayload(
// See the comment above the `Preloads` component (below) for why this is part of the payload
P: <Preloads preloadCallbacks={preloadCallbacks} />,
b: ctx.sharedContext.buildId,
p: ctx.assetPrefix,
c: prepareInitialCanonicalUrl(url),
i: !!couldBeIntercepted,
f: [
......@@ -1293,7 +1292,6 @@ async function getErrorRSCPayload(
return {
b: ctx.sharedContext.buildId,
p: ctx.assetPrefix,
c: prepareInitialCanonicalUrl(url),
m: undefined,
i: false,
......@@ -1372,11 +1370,7 @@ function App<T>({
}}
>
<ServerInsertedHTMLProvider>
<AppRouter
actionQueue={actionQueue}
globalErrorState={response.G}
assetPrefix={response.p}
/>
<AppRouter actionQueue={actionQueue} globalErrorState={response.G} />
</ServerInsertedHTMLProvider>
</HeadManagerContext.Provider>
)
......@@ -1426,11 +1420,7 @@ function ErrorApp<T>({
return (
<ServerInsertedHTMLProvider>
<AppRouter
actionQueue={actionQueue}
globalErrorState={response.G}
assetPrefix={response.p}
/>
<AppRouter actionQueue={actionQueue} globalErrorState={response.G} />
</ServerInsertedHTMLProvider>
)
}
......@@ -1542,7 +1532,7 @@ async function renderToHTMLOrFlightImpl(
if (process.env.NODE_ENV === 'development') {
// reset isr status at start of request
const { pathname } = new URL(req.url || '/', 'http://n')
renderOpts.setIsrStatus?.(pathname, null)
renderOpts.setIsrStatus?.(pathname, false)
}
if (
......
......@@ -93,7 +93,7 @@ export interface RenderOptsPartial {
}
isOnDemandRevalidate?: boolean
isPossibleServerAction?: boolean
setIsrStatus?: (key: string, value: boolean | null) => void
setIsrStatus?: (key: string, value: boolean) => void
isRevalidate?: boolean
nextExport?: boolean
nextConfigOutput?: 'standalone' | 'export'
......
......@@ -119,7 +119,7 @@ export interface TurbopackConnectedAction {
export interface AppIsrManifestAction {
action: HMR_ACTIONS_SENT_TO_BROWSER.ISR_MANIFEST
data: Record<string, boolean>
data: Record<string, true>
}
export interface DevToolsConfigAction {
......
......@@ -11,7 +11,7 @@ import { HMR_ACTIONS_SENT_TO_BROWSER } from '../dev/hot-reloader-types'
* bundler while in development.
*/
export class DevBundlerService {
public appIsrManifestInner: InstanceType<typeof LRUCache<boolean>>
public appIsrManifestInner: InstanceType<typeof LRUCache<true>>
constructor(
private readonly bundler: DevBundler,
......@@ -85,7 +85,7 @@ export class DevBundlerService {
}
public get appIsrManifest() {
const serializableManifest: Record<string, boolean> = {}
const serializableManifest: Record<string, true> = {}
for (const [key, value] of this.appIsrManifestInner) {
serializableManifest[key] = value
......@@ -94,8 +94,8 @@ export class DevBundlerService {
return serializableManifest
}
public setIsrStatus(key: string, value: boolean | null) {
if (value === null) {
public setIsrStatus(key: string, value: boolean) {
if (value === false) {
this.appIsrManifestInner.remove(key)
} else {
this.appIsrManifestInner.set(key, value)
......
......@@ -39,7 +39,7 @@ export type RouterServerContext = Record<
// allow dev server to log with original stack
logErrorWithOriginalStack?: (err: unknown, type: string) => void
// allow setting ISR status in dev
setIsrStatus?: (key: string, value: boolean | null) => void
setIsrStatus?: (key: string, value: boolean) => void
}
>
......
......@@ -265,7 +265,7 @@ export type RenderOptsPartial = {
assetQueryString?: string
resolvedUrl?: string
resolvedAsPath?: string
setIsrStatus?: (key: string, value: boolean | null) => void
setIsrStatus?: (key: string, value: boolean) => void
clientReferenceManifest?: DeepReadonly<ClientReferenceManifest>
nextFontManifest?: DeepReadonly<NextFontManifest>
distDir?: string
......@@ -662,7 +662,7 @@ export async function renderToHTMLImpl(
}
if (renderOpts?.setIsrStatus) {
renderOpts.setIsrStatus(asPath, isSSG || isAutoExport ? true : null)
renderOpts.setIsrStatus(asPath, isSSG || isAutoExport)
}
}
......
......@@ -258,8 +258,6 @@ export type ActionResult = Promise<any>
export type InitialRSCPayload = {
/** buildId */
b: string
/** assetPrefix */
p: string
/** initialCanonicalUrlParts */
c: string[]
/** couldBeIntercepted */
......
......@@ -214,7 +214,7 @@ describe('Error overlay for hydration errors in App router', () => {
await expect(browser).toDisplayCollapsedRedbox(`
{
"componentStack": "...
<HotReload assetPrefix="" globalError={[...]}>
<HotReload globalError={[...]} webSocket={WebSocket} staticIndicatorState={{pathname:null, ...}}>
<AppDevOverlayErrorBoundary globalError={[...]}>
<ReplaySsrOnlyErrors>
<DevRootHTTPAccessFallbackBoundary>
......@@ -251,7 +251,7 @@ describe('Error overlay for hydration errors in App router', () => {
await expect(browser).toDisplayCollapsedRedbox(`
{
"componentStack": "...
<HotReload assetPrefix="" globalError={[...]}>
<HotReload globalError={[...]} webSocket={WebSocket} staticIndicatorState={{pathname:null, ...}}>
<AppDevOverlayErrorBoundary globalError={[...]}>
<ReplaySsrOnlyErrors>
<DevRootHTTPAccessFallbackBoundary>
......@@ -1092,7 +1092,7 @@ describe('Error overlay for hydration errors in App router', () => {
},
{
"componentStack": "...
<HotReload assetPrefix="" globalError={[...]}>
<HotReload globalError={[...]} webSocket={WebSocket} staticIndicatorState={{pathname:null, ...}}>
<AppDevOverlayErrorBoundary globalError={[...]}>
<ReplaySsrOnlyErrors>
<DevRootHTTPAccessFallbackBoundary>
......@@ -1155,7 +1155,7 @@ describe('Error overlay for hydration errors in App router', () => {
},
{
"componentStack": "...
<HotReload assetPrefix="" globalError={[...]}>
<HotReload globalError={[...]} webSocket={WebSocket} staticIndicatorState={{pathname:null, ...}}>
<AppDevOverlayErrorBoundary globalError={[...]}>
<ReplaySsrOnlyErrors>
<DevRootHTTPAccessFallbackBoundary>
......
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