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