Unverified Commit 85c718fd authored by Sebastian "Sebbie" Silbermann's avatar Sebastian "Sebbie" Silbermann Committed by GitHub

[dev-overlay] Render /app Dev Overlay with a separate React instance (#79699)

parent 9155c8ac
...@@ -168,6 +168,7 @@ ...@@ -168,6 +168,7 @@
"files": ["packages/**"], "files": ["packages/**"],
"excludedFiles": [ "excludedFiles": [
"packages/next/taskfile*.js", "packages/next/taskfile*.js",
"packages/next/next-devtools.webpack-config.js",
"packages/next/next-runtime.webpack-config.js" "packages/next/next-runtime.webpack-config.js"
], ],
"rules": { "rules": {
......
...@@ -693,5 +693,7 @@ ...@@ -693,5 +693,7 @@
"692": "Expected clientReferenceManifest to be defined.", "692": "Expected clientReferenceManifest to be defined.",
"693": "%s must not be used within a client component. Next.js should be preventing %s from being included in client components statically, but did not in this case.", "693": "%s must not be used within a client component. Next.js should be preventing %s from being included in client components statically, but did not in this case.",
"694": "createPrerenderPathname was called inside a client component scope.", "694": "createPrerenderPathname was called inside a client component scope.",
"695": "Expected workUnitAsyncStorage to have a store." "695": "Expected workUnitAsyncStorage to have a store.",
"696": "Next DevTools: Can't dispatch %s in this environment. This is a bug in Next.js",
"697": "Next DevTools: Can't render in this environment. This is a bug in Next.js"
} }
const path = require('path')
const webpack = require('@rspack/core')
const MODERN_BROWSERSLIST_TARGET = require('./src/shared/lib/modern-browserslist-target')
const DevToolsIgnoreListPlugin = require('./webpack-plugins/devtools-ignore-list-plugin')
function shouldIgnorePath(modulePath) {
// For consumers, everything will be considered 3rd party dependency if they use
// the bundles we produce here.
// In other words, this is all library code and should therefore be ignored.
return true
}
/**
* @param {Object} options
* @param {boolean} options.dev
* @param {Partial<webpack.Configuration>} options.rest
* @returns {webpack.Configuration}
*/
module.exports = ({ dev, ...rest }) => {
const experimental = false
const turbo = false
const bundledReactChannel = experimental ? '-experimental' : ''
const target = `browserslist:${MODERN_BROWSERSLIST_TARGET.join(', ')}`
return {
entry: path.join(
__dirname,
'src/client/components/react-dev-overlay/app/entrypoint.js'
),
target,
mode: dev ? 'development' : 'production',
output: {
path: path.join(__dirname, 'dist/compiled/next-devtools'),
filename: `index.js`,
iife: false,
library: {
type: 'commonjs-static',
},
},
devtool: 'source-map',
optimization: {
moduleIds: 'named',
minimize: true,
concatenateModules: true,
minimizer: [
new webpack.SwcJsMinimizerRspackPlugin({
minimizerOptions: {
mangle: dev || process.env.NEXT_SERVER_NO_MANGLE ? false : true,
},
}),
],
},
plugins: [
// TODO: React Compiler
new DevToolsIgnoreListPlugin({ shouldIgnorePath }),
new webpack.DefinePlugin({
// TODO: Hardcode it and ensure module resolution resolves to .node entrypoint in Node.js
// 'typeof window': JSON.stringify('object'),
'process.env.NEXT_MINIMAL': JSON.stringify('true'),
'this.serverOptions.experimentalTestProxy': JSON.stringify(false),
'this.minimalMode': JSON.stringify(true),
'this.renderOpts.dev': JSON.stringify(dev),
'renderOpts.dev': JSON.stringify(dev),
'process.env.NODE_ENV': JSON.stringify(
dev ? 'development' : 'production'
),
'process.env.__NEXT_EXPERIMENTAL_REACT': JSON.stringify(
experimental ? true : false
),
'process.env.NEXT_RUNTIME': JSON.stringify('nodejs'),
'process.turbopack': JSON.stringify(turbo),
'process.env.TURBOPACK': JSON.stringify(turbo),
}),
].filter(Boolean),
stats: {
optimizationBailout: true,
},
resolve: {
alias: {
// TODO: Get dedicated React version for NDT to uncouple development.
react: `next/dist/compiled/react${bundledReactChannel}`,
'react-dom$': `next/dist/compiled/react-dom${bundledReactChannel}`,
'react-dom/client$': `next/dist/compiled/react-dom${bundledReactChannel}/client`,
'react-is$': `next/dist/compiled/react-is${bundledReactChannel}`,
scheduler$: `next/dist/compiled/scheduler${bundledReactChannel}`,
},
extensions: ['.ts', '.tsx', '.js', '.json'],
},
module: {
rules: [
{ test: /\.m?js$/, loader: `source-map-loader`, enforce: `pre` },
{
test: /\.(ts|tsx)$/,
exclude: [/node_modules/],
loader: 'builtin:swc-loader',
options: {
jsc: {
parser: {
syntax: 'typescript',
tsx: true,
},
transform: {
react: {
development: dev,
runtime: 'automatic',
// TODO: Fast Refresh
// refresh: dev,
},
},
},
},
type: 'javascript/auto',
},
],
},
externals: [],
experiments: {},
...rest,
}
}
...@@ -92,6 +92,8 @@ const sharedExternals = [ ...@@ -92,6 +92,8 @@ const sharedExternals = [
const externalsMap = { const externalsMap = {
'./web/sandbox': 'next/dist/server/web/sandbox', './web/sandbox': 'next/dist/server/web/sandbox',
'next/dist/compiled/next-devtools':
'commonjs next/dist/client/components/react-dev-overlay/app/app-dev-overlay.shim.js',
} }
const externalsRegexMap = { const externalsRegexMap = {
......
...@@ -2,12 +2,22 @@ ...@@ -2,12 +2,22 @@
import './app-webpack' import './app-webpack'
import { renderAppDevOverlay } from 'next/dist/compiled/next-devtools'
import { appBootstrap } from './app-bootstrap' import { appBootstrap } from './app-bootstrap'
import {
getComponentStack,
getOwnerStack,
} from './components/errors/stitched-error'
import { isRecoverableError } from './react-client-callbacks/on-recoverable-error'
// 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(() => {
const { hydrate } = require('./app-index') as typeof import('./app-index') const { hydrate } = require('./app-index') as typeof import('./app-index')
hydrate(instrumentationHooks) try {
hydrate(instrumentationHooks)
} finally {
renderAppDevOverlay(getComponentStack, getOwnerStack, isRecoverableError)
}
}) })
// TODO-APP: hydration warning
import { appBootstrap } from './app-bootstrap' import { appBootstrap } from './app-bootstrap'
import {
getComponentStack,
getOwnerStack,
} from './components/errors/stitched-error'
import { isRecoverableError } from './react-client-callbacks/on-recoverable-error'
window.next.version += '-turbo' window.next.version += '-turbo'
;(self as any).__webpack_hash__ = '' ;(self as any).__webpack_hash__ = ''
...@@ -10,5 +13,13 @@ const instrumentationHooks = require('../lib/require-instrumentation-client') ...@@ -10,5 +13,13 @@ const instrumentationHooks = require('../lib/require-instrumentation-client')
appBootstrap(() => { appBootstrap(() => {
const { hydrate } = require('./app-index') as typeof import('./app-index') const { hydrate } = require('./app-index') as typeof import('./app-index')
hydrate(instrumentationHooks) try {
hydrate(instrumentationHooks)
} finally {
if (process.env.NODE_ENV !== 'production') {
const { renderAppDevOverlay } =
require('next/dist/compiled/next-devtools') as typeof import('next/dist/compiled/next-devtools')
renderAppDevOverlay(getComponentStack, getOwnerStack, isRecoverableError)
}
}
}) })
import { PureComponent } from 'react' import { PureComponent } from 'react'
import { dispatcher } from 'next/dist/compiled/next-devtools'
import { RuntimeErrorHandler } from '../../errors/runtime-error-handler' import { RuntimeErrorHandler } from '../../errors/runtime-error-handler'
import { ErrorBoundary } from '../../error-boundary' import { ErrorBoundary } from '../../error-boundary'
import DefaultGlobalError, { import DefaultGlobalError, {
...@@ -8,7 +9,6 @@ import DefaultGlobalError, { ...@@ -8,7 +9,6 @@ import DefaultGlobalError, {
type AppDevOverlayErrorBoundaryProps = { type AppDevOverlayErrorBoundaryProps = {
children: React.ReactNode children: React.ReactNode
globalError: [GlobalErrorComponent, React.ReactNode] globalError: [GlobalErrorComponent, React.ReactNode]
onError: () => void
} }
type AppDevOverlayErrorBoundaryState = { type AppDevOverlayErrorBoundaryState = {
...@@ -53,7 +53,7 @@ export class AppDevOverlayErrorBoundary extends PureComponent< ...@@ -53,7 +53,7 @@ export class AppDevOverlayErrorBoundary extends PureComponent<
} }
componentDidCatch() { componentDidCatch() {
this.props.onError() dispatcher.openErrorOverlay()
} }
render() { render() {
......
import {
ACTION_BEFORE_REFRESH,
ACTION_BUILD_ERROR,
ACTION_BUILD_OK,
ACTION_DEBUG_INFO,
ACTION_DEV_INDICATOR,
ACTION_REFRESH,
ACTION_ERROR_OVERLAY_CLOSE,
ACTION_ERROR_OVERLAY_OPEN,
ACTION_ERROR_OVERLAY_TOGGLE,
ACTION_STATIC_INDICATOR,
ACTION_UNHANDLED_ERROR,
ACTION_UNHANDLED_REJECTION,
ACTION_VERSION_INFO,
useErrorOverlayReducer,
ACTION_BUILDING_INDICATOR_HIDE,
ACTION_BUILDING_INDICATOR_SHOW,
ACTION_RENDERING_INDICATOR_HIDE,
ACTION_RENDERING_INDICATOR_SHOW,
} from '../shared'
import { startTransition, useInsertionEffect } from 'react'
import { createRoot } from 'react-dom/client'
import { FontStyles } from '../font/font-styles'
import type { DebugInfo } from '../types'
import { DevOverlay } from '../ui/dev-overlay'
import type { DevIndicatorServerState } from '../../../../server/dev/dev-indicator-server-state'
import type { VersionInfo } from '../../../../server/dev/parse-version-info'
export interface Dispatcher {
onBuildOk(): void
onBuildError(message: string): void
onVersionInfo(versionInfo: VersionInfo): void
onDebugInfo(debugInfo: DebugInfo): void
onBeforeRefresh(): void
onRefresh(): void
onStaticIndicator(status: boolean): void
onDevIndicator(devIndicator: DevIndicatorServerState): void
onUnhandledError(reason: Error): void
onUnhandledRejection(reason: Error): void
openErrorOverlay(): void
closeErrorOverlay(): void
toggleErrorOverlay(): void
buildingIndicatorHide(): void
buildingIndicatorShow(): void
renderingIndicatorHide(): void
renderingIndicatorShow(): void
}
type Dispatch = ReturnType<typeof useErrorOverlayReducer>[1]
let maybeDispatch: Dispatch | null = null
const queue: Array<(dispatch: Dispatch) => void> = []
// Events might be dispatched before we get a `dispatch` from React (e.g. console.error during module eval).
// We need to queue them until we have a `dispatch` function available.
function createQueuable<Args extends any[]>(
queueableFunction: (dispatch: Dispatch, ...args: Args) => void
) {
return (...args: Args) => {
if (maybeDispatch) {
queueableFunction(maybeDispatch, ...args)
} else {
queue.push((dispatch: Dispatch) => {
queueableFunction(dispatch, ...args)
})
}
}
}
// TODO: Extract into separate functions that are imported
export const dispatcher: Dispatcher = {
onBuildOk: createQueuable((dispatch: Dispatch) => {
dispatch({ type: ACTION_BUILD_OK })
}),
onBuildError: createQueuable((dispatch: Dispatch, message: string) => {
dispatch({ type: ACTION_BUILD_ERROR, message })
}),
onBeforeRefresh: createQueuable((dispatch: Dispatch) => {
dispatch({ type: ACTION_BEFORE_REFRESH })
}),
onRefresh: createQueuable((dispatch: Dispatch) => {
dispatch({ type: ACTION_REFRESH })
}),
onVersionInfo: createQueuable(
(dispatch: Dispatch, versionInfo: VersionInfo) => {
dispatch({ type: ACTION_VERSION_INFO, versionInfo })
}
),
onStaticIndicator: createQueuable((dispatch: Dispatch, status: boolean) => {
dispatch({ type: ACTION_STATIC_INDICATOR, staticIndicator: status })
}),
onDebugInfo: createQueuable((dispatch: Dispatch, debugInfo: DebugInfo) => {
dispatch({ type: ACTION_DEBUG_INFO, debugInfo })
}),
onDevIndicator: createQueuable(
(dispatch: Dispatch, devIndicator: DevIndicatorServerState) => {
dispatch({ type: ACTION_DEV_INDICATOR, devIndicator })
}
),
onUnhandledError: createQueuable((dispatch: Dispatch, error: Error) => {
dispatch({
type: ACTION_UNHANDLED_ERROR,
reason: error,
})
}),
onUnhandledRejection: createQueuable((dispatch: Dispatch, error: Error) => {
dispatch({
type: ACTION_UNHANDLED_REJECTION,
reason: error,
})
}),
openErrorOverlay: createQueuable((dispatch: Dispatch) => {
dispatch({ type: ACTION_ERROR_OVERLAY_OPEN })
}),
closeErrorOverlay: createQueuable((dispatch: Dispatch) => {
dispatch({ type: ACTION_ERROR_OVERLAY_CLOSE })
}),
toggleErrorOverlay: createQueuable((dispatch: Dispatch) => {
dispatch({ type: ACTION_ERROR_OVERLAY_TOGGLE })
}),
buildingIndicatorHide: createQueuable((dispatch: Dispatch) => {
dispatch({ type: ACTION_BUILDING_INDICATOR_HIDE })
}),
buildingIndicatorShow: createQueuable((dispatch: Dispatch) => {
dispatch({ type: ACTION_BUILDING_INDICATOR_SHOW })
}),
renderingIndicatorHide: createQueuable((dispatch: Dispatch) => {
dispatch({ type: ACTION_RENDERING_INDICATOR_HIDE })
}),
renderingIndicatorShow: createQueuable((dispatch: Dispatch) => {
dispatch({ type: ACTION_RENDERING_INDICATOR_SHOW })
}),
}
function replayQueuedEvents(dispatch: NonNullable<typeof maybeDispatch>) {
try {
for (const queuedFunction of queue) {
queuedFunction(dispatch)
}
} finally {
// TODO: What to do with failed events?
queue.length = 0
}
}
function getSquashedHydrationErrorDetails() {
// We don't squash hydration errors in the App Router.
return null
}
function AppDevOverlay({
getComponentStack,
getOwnerStack,
isRecoverableError,
}: {
getComponentStack: (error: Error) => string | undefined
getOwnerStack: (error: Error) => string | null | undefined
isRecoverableError: (error: Error) => boolean
}) {
const [state, dispatch] = useErrorOverlayReducer(
'app',
getComponentStack,
getOwnerStack,
isRecoverableError
)
useInsertionEffect(() => {
maybeDispatch = dispatch
// Can't schedule updates from useInsertionEffect, so we need to defer.
// Could move this into a passive Effect but we don't want replaying when
// we reconnect.
const replayTimeout = setTimeout(() => {
replayQueuedEvents(dispatch)
})
return () => {
maybeDispatch = null
clearTimeout(replayTimeout)
}
}, [])
return (
<>
{/* Fonts can only be loaded outside the Shadow DOM. */}
<FontStyles />
<DevOverlay
state={state}
dispatch={dispatch}
getSquashedHydrationErrorDetails={getSquashedHydrationErrorDetails}
/>
</>
)
}
let isMounted = false
export function renderAppDevOverlay(
getComponentStack: (error: Error) => string | undefined,
getOwnerStack: (error: Error) => string | null | undefined,
isRecoverableError: (error: Error) => boolean
): void {
if (!isMounted) {
// React 19 will not throw away `<script>` elements in a container it owns.
// This ensures the actual user-space React does not unmount the Dev Overlay.
const script = document.createElement('script')
script.style.display = 'block'
// Although the style applied to the shadow host is isolated,
// the element that attached the shadow host (i.e. "script")
// is still affected by the parent's style (e.g. "body"). This may
// occur style conflicts like "display: flex", with other children
// elements therefore give the shadow host an absolute position.
script.style.position = 'absolute'
script.setAttribute('data-nextjs-dev-overlay', 'true')
const container = document.createElement('nextjs-portal')
script.appendChild(container)
document.body.appendChild(script)
const root = createRoot(container, {
identifierPrefix: 'ndt-',
})
startTransition(() => {
// TODO: Dedicated error boundary or root error callbacks?
// At least it won't unmount any user code if it errors.
root.render(
<AppDevOverlay
getComponentStack={getComponentStack}
getOwnerStack={getOwnerStack}
isRecoverableError={isRecoverableError}
/>
)
})
isMounted = true
}
}
export function renderAppDevOverlay() {
throw new Error(
"Next DevTools: Can't render in this environment. This is a bug in Next.js"
)
}
// TODO: Extract into separate functions that are imported
export const dispatcher = new Proxy(
{},
{
get: (_, prop) => {
return () => {
throw new Error(
`Next DevTools: Can't dispatch ${String(prop)} in this environment. This is a bug in Next.js`
)
}
},
}
)
import {
ACTION_ERROR_OVERLAY_OPEN,
type OverlayDispatch,
type OverlayState,
} from '../shared'
import type { GlobalErrorComponent } from '../../global-error'
import { useCallback } from 'react'
import { AppDevOverlayErrorBoundary } from './app-dev-overlay-error-boundary'
import { FontStyles } from '../font/font-styles'
import { DevOverlay } from '../ui/dev-overlay'
function getSquashedHydrationErrorDetails() {
// We don't squash hydration errors in the App Router.
return null
}
export function AppDevOverlay({
state,
dispatch,
globalError,
children,
}: {
state: OverlayState
dispatch: OverlayDispatch
globalError: [GlobalErrorComponent, React.ReactNode]
children: React.ReactNode
}) {
const openOverlay = useCallback(() => {
dispatch({ type: ACTION_ERROR_OVERLAY_OPEN })
}, [dispatch])
return (
<>
<AppDevOverlayErrorBoundary
globalError={globalError}
onError={openOverlay}
>
{children}
</AppDevOverlayErrorBoundary>
<>
{/* Fonts can only be loaded outside the Shadow DOM. */}
<FontStyles />
<DevOverlay
state={state}
dispatch={dispatch}
getSquashedHydrationErrorDetails={getSquashedHydrationErrorDetails}
/>
</>
</>
)
}
...@@ -4,8 +4,6 @@ import { HMR_ACTIONS_SENT_TO_BROWSER } from '../../../../server/dev/hot-reloader ...@@ -4,8 +4,6 @@ import { HMR_ACTIONS_SENT_TO_BROWSER } from '../../../../server/dev/hot-reloader
import GlobalError from '../../global-error' import GlobalError from '../../global-error'
import { AppDevOverlayErrorBoundary } from './app-dev-overlay-error-boundary' import { AppDevOverlayErrorBoundary } from './app-dev-overlay-error-boundary'
const noop = () => {}
// if an error is thrown while rendering an RSC stream, this will catch it in dev // if an error is thrown while rendering an RSC stream, this will catch it in dev
// and show the error overlay // and show the error overlay
export function createRootLevelDevOverlayElement(reactEl: React.ReactElement) { export function createRootLevelDevOverlayElement(reactEl: React.ReactElement) {
...@@ -31,10 +29,7 @@ export function createRootLevelDevOverlayElement(reactEl: React.ReactElement) { ...@@ -31,10 +29,7 @@ export function createRootLevelDevOverlayElement(reactEl: React.ReactElement) {
socket.addEventListener('message', handler) socket.addEventListener('message', handler)
return ( return (
<AppDevOverlayErrorBoundary <AppDevOverlayErrorBoundary globalError={[GlobalError, null]}>
globalError={[GlobalError, null]}
onError={noop}
>
{reactEl} {reactEl}
</AppDevOverlayErrorBoundary> </AppDevOverlayErrorBoundary>
) )
......
/// <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, useMemo, useRef } from 'react' import { useEffect, startTransition, useRef } from 'react'
import stripAnsi from 'next/dist/compiled/strip-ansi' import stripAnsi from 'next/dist/compiled/strip-ansi'
import formatWebpackMessages from '../utils/format-webpack-messages' import formatWebpackMessages from '../utils/format-webpack-messages'
import { useRouter } from '../../navigation' import { useRouter } from '../../navigation'
import { import { REACT_REFRESH_FULL_RELOAD, reportInvalidHmrMessage } from '../shared'
ACTION_BEFORE_REFRESH, import { dispatcher } from 'next/dist/compiled/next-devtools'
ACTION_BUILDING_INDICATOR_HIDE,
ACTION_BUILD_ERROR,
ACTION_BUILD_OK,
ACTION_BUILDING_INDICATOR_SHOW,
ACTION_DEBUG_INFO,
ACTION_DEV_INDICATOR,
ACTION_ERROR_OVERLAY_OPEN,
ACTION_REFRESH,
ACTION_STATIC_INDICATOR,
ACTION_UNHANDLED_ERROR,
ACTION_UNHANDLED_REJECTION,
ACTION_VERSION_INFO,
REACT_REFRESH_FULL_RELOAD,
reportInvalidHmrMessage,
useErrorOverlayReducer,
} from '../shared'
import { AppDevOverlay } from './app-dev-overlay'
import { ReplaySsrOnlyErrors } from './replay-ssr-only-errors' import { ReplaySsrOnlyErrors } from './replay-ssr-only-errors'
import { AppDevOverlayErrorBoundary } from './app-dev-overlay-error-boundary'
import { useErrorHandler } from '../../errors/use-error-handler' import { useErrorHandler } from '../../errors/use-error-handler'
import { RuntimeErrorHandler } from '../../errors/runtime-error-handler' import { RuntimeErrorHandler } from '../../errors/runtime-error-handler'
import { import {
...@@ -33,38 +17,17 @@ import { ...@@ -33,38 +17,17 @@ import {
useWebsocket, useWebsocket,
useWebsocketPing, useWebsocketPing,
} from '../utils/use-websocket' } from '../utils/use-websocket'
import type { VersionInfo } from '../../../../server/dev/parse-version-info'
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,
TurbopackMsgToBrowser, TurbopackMsgToBrowser,
} from '../../../../server/dev/hot-reloader-types' } from '../../../../server/dev/hot-reloader-types'
import { REACT_REFRESH_FULL_RELOAD_FROM_ERROR } from '../shared' import { REACT_REFRESH_FULL_RELOAD_FROM_ERROR } from '../shared'
import type { DebugInfo } from '../types'
import { useUntrackedPathname } from '../../navigation-untracked' import { useUntrackedPathname } from '../../navigation-untracked'
import type { GlobalErrorComponent } from '../../global-error' import type { GlobalErrorComponent } from '../../global-error'
import type { DevIndicatorServerState } from '../../../../server/dev/dev-indicator-server-state'
import reportHmrLatency from '../utils/report-hmr-latency' import reportHmrLatency from '../utils/report-hmr-latency'
import { TurbopackHmr } from '../utils/turbopack-hot-reloader-common' import { TurbopackHmr } from '../utils/turbopack-hot-reloader-common'
import { NEXT_HMR_REFRESH_HASH_COOKIE } from '../../app-router-headers' import { NEXT_HMR_REFRESH_HASH_COOKIE } from '../../app-router-headers'
import { getComponentStack, getOwnerStack } from '../../errors/stitched-error'
import { isRecoverableError } from '../../../react-client-callbacks/on-recoverable-error'
export interface Dispatcher {
onBuildOk(): void
onBuildError(message: string): void
onVersionInfo(versionInfo: VersionInfo): void
onDebugInfo(debugInfo: DebugInfo): void
onBeforeRefresh(): void
onRefresh(): void
onStaticIndicator(status: boolean): void
onDevIndicator(devIndicator: DevIndicatorServerState): void
onUnhandledError(error: Error): void
onUnhandledRejection(error: Error): void
openErrorOverlay(): void
buildingIndicatorHide(): void
buildingIndicatorShow(): void
}
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())
...@@ -150,10 +113,7 @@ function performFullReload(err: any, sendMessage: any) { ...@@ -150,10 +113,7 @@ function performFullReload(err: any, sendMessage: any) {
} }
// Attempt to update code on the fly, fall back to a hard reload. // Attempt to update code on the fly, fall back to a hard reload.
function tryApplyUpdatesWebpack( function tryApplyUpdatesWebpack(sendMessage: (message: string) => void) {
sendMessage: (message: string) => void,
dispatcher: Dispatcher
) {
if (!isUpdateAvailable() || !canApplyUpdates()) { if (!isUpdateAvailable() || !canApplyUpdates()) {
resolvePendingHotUpdateWebpack() resolvePendingHotUpdateWebpack()
dispatcher.onBuildOk() dispatcher.onBuildOk()
...@@ -179,7 +139,7 @@ function tryApplyUpdatesWebpack( ...@@ -179,7 +139,7 @@ function tryApplyUpdatesWebpack(
if (isUpdateAvailable()) { if (isUpdateAvailable()) {
// While we were updating, there was a new update! Do it again. // While we were updating, there was a new update! Do it again.
tryApplyUpdatesWebpack(sendMessage, dispatcher) tryApplyUpdatesWebpack(sendMessage)
return return
} }
...@@ -233,7 +193,6 @@ function processMessage( ...@@ -233,7 +193,6 @@ function processMessage(
sendMessage: (message: string) => void, sendMessage: (message: string) => void,
processTurbopackMessage: (msg: TurbopackMsgToBrowser) => void, processTurbopackMessage: (msg: TurbopackMsgToBrowser) => void,
router: ReturnType<typeof useRouter>, router: ReturnType<typeof useRouter>,
dispatcher: Dispatcher,
appIsrManifestRef: ReturnType<typeof useRef>, appIsrManifestRef: ReturnType<typeof useRef>,
pathnameRef: ReturnType<typeof useRef> pathnameRef: ReturnType<typeof useRef>
) { ) {
...@@ -281,7 +240,7 @@ function processMessage( ...@@ -281,7 +240,7 @@ function processMessage(
} }
dispatcher.onBuildOk() dispatcher.onBuildOk()
} else { } else {
tryApplyUpdatesWebpack(sendMessage, dispatcher) tryApplyUpdatesWebpack(sendMessage)
} }
} }
...@@ -491,66 +450,6 @@ export default function HotReload({ ...@@ -491,66 +450,6 @@ export default function HotReload({
children: ReactNode children: ReactNode
globalError: [GlobalErrorComponent, React.ReactNode] globalError: [GlobalErrorComponent, React.ReactNode]
}) { }) {
const [state, dispatch] = useErrorOverlayReducer(
'app',
getComponentStack,
getOwnerStack,
isRecoverableError
)
const dispatcher = useMemo<Dispatcher>(() => {
return {
onBuildOk() {
dispatch({ type: ACTION_BUILD_OK })
},
onBuildError(message) {
dispatch({ type: ACTION_BUILD_ERROR, message })
},
onBeforeRefresh() {
dispatch({ type: ACTION_BEFORE_REFRESH })
},
onRefresh() {
dispatch({ type: ACTION_REFRESH })
},
onVersionInfo(versionInfo) {
dispatch({ type: ACTION_VERSION_INFO, versionInfo })
},
onStaticIndicator(status: boolean) {
dispatch({ type: ACTION_STATIC_INDICATOR, staticIndicator: status })
},
onDebugInfo(debugInfo) {
dispatch({ type: ACTION_DEBUG_INFO, debugInfo })
},
onDevIndicator(devIndicator) {
dispatch({
type: ACTION_DEV_INDICATOR,
devIndicator,
})
},
onUnhandledError(error) {
dispatch({
type: ACTION_UNHANDLED_ERROR,
reason: error,
})
},
onUnhandledRejection(error) {
dispatch({
type: ACTION_UNHANDLED_REJECTION,
reason: error,
})
},
openErrorOverlay() {
dispatch({ type: ACTION_ERROR_OVERLAY_OPEN })
},
buildingIndicatorHide() {
dispatch({ type: ACTION_BUILDING_INDICATOR_HIDE })
},
buildingIndicatorShow() {
dispatch({ type: ACTION_BUILDING_INDICATOR_SHOW })
},
}
}, [dispatch])
useErrorHandler(dispatcher.onUnhandledError, dispatcher.onUnhandledRejection) useErrorHandler(dispatcher.onUnhandledError, dispatcher.onUnhandledRejection)
const webSocketRef = useWebsocket(assetPrefix) const webSocketRef = useWebsocket(assetPrefix)
...@@ -599,7 +498,7 @@ export default function HotReload({ ...@@ -599,7 +498,7 @@ export default function HotReload({
dispatcher.onStaticIndicator(false) dispatcher.onStaticIndicator(false)
} }
} }
}, [pathname, dispatcher]) }, [pathname])
} }
useEffect(() => { useEffect(() => {
...@@ -614,7 +513,6 @@ export default function HotReload({ ...@@ -614,7 +513,6 @@ export default function HotReload({
sendMessage, sendMessage,
processTurbopackMessage, processTurbopackMessage,
router, router,
dispatcher,
appIsrManifestRef, appIsrManifestRef,
pathnameRef pathnameRef
) )
...@@ -629,15 +527,14 @@ export default function HotReload({ ...@@ -629,15 +527,14 @@ export default function HotReload({
sendMessage, sendMessage,
router, router,
webSocketRef, webSocketRef,
dispatcher,
processTurbopackMessage, processTurbopackMessage,
appIsrManifestRef, appIsrManifestRef,
]) ])
return ( return (
<AppDevOverlay state={state} dispatch={dispatch} globalError={globalError}> <AppDevOverlayErrorBoundary globalError={globalError}>
<ReplaySsrOnlyErrors onBlockingError={dispatcher.openErrorOverlay} /> <ReplaySsrOnlyErrors onBlockingError={dispatcher.openErrorOverlay} />
{children} {children}
</AppDevOverlay> </AppDevOverlayErrorBoundary>
) )
} }
import { useInsertionEffect } from 'react'
import { PagesDevOverlayErrorBoundary } from './pages-dev-overlay-error-boundary' import { PagesDevOverlayErrorBoundary } from './pages-dev-overlay-error-boundary'
import { usePagesDevOverlay } from './hooks' import { usePagesDevOverlay } from './hooks'
import { FontStyles } from '../font/font-styles' import { FontStyles } from '../font/font-styles'
...@@ -15,6 +16,12 @@ interface PagesDevOverlayProps { ...@@ -15,6 +16,12 @@ interface PagesDevOverlayProps {
export function PagesDevOverlay({ children }: PagesDevOverlayProps) { export function PagesDevOverlay({ children }: PagesDevOverlayProps) {
const { state, dispatch } = usePagesDevOverlay() const { state, dispatch } = usePagesDevOverlay()
// TODO: Remove once Root initializer creates this element
useInsertionEffect(() => {
const container = document.createElement('nextjs-portal')
document.body.appendChild(container)
}, [])
return ( return (
<> <>
<PagesDevOverlayErrorBoundary>{children}</PagesDevOverlayErrorBoundary> <PagesDevOverlayErrorBoundary>{children}</PagesDevOverlayErrorBoundary>
......
...@@ -23,6 +23,7 @@ export interface OverlayState { ...@@ -23,6 +23,7 @@ export interface OverlayState {
versionInfo: VersionInfo versionInfo: VersionInfo
notFound: boolean notFound: boolean
buildingIndicator: boolean buildingIndicator: boolean
renderingIndicator: boolean
staticIndicator: boolean staticIndicator: boolean
showIndicator: boolean showIndicator: boolean
disableDevIndicator: boolean disableDevIndicator: boolean
...@@ -47,6 +48,8 @@ export const ACTION_ERROR_OVERLAY_CLOSE = 'error-overlay-close' ...@@ -47,6 +48,8 @@ export const ACTION_ERROR_OVERLAY_CLOSE = 'error-overlay-close'
export const ACTION_ERROR_OVERLAY_TOGGLE = 'error-overlay-toggle' export const ACTION_ERROR_OVERLAY_TOGGLE = 'error-overlay-toggle'
export const ACTION_BUILDING_INDICATOR_SHOW = 'building-indicator-show' export const ACTION_BUILDING_INDICATOR_SHOW = 'building-indicator-show'
export const ACTION_BUILDING_INDICATOR_HIDE = 'building-indicator-hide' export const ACTION_BUILDING_INDICATOR_HIDE = 'building-indicator-hide'
export const ACTION_RENDERING_INDICATOR_SHOW = 'rendering-indicator-show'
export const ACTION_RENDERING_INDICATOR_HIDE = 'rendering-indicator-hide'
export const STORAGE_KEY_THEME = '__nextjs-dev-tools-theme' export const STORAGE_KEY_THEME = '__nextjs-dev-tools-theme'
export const STORAGE_KEY_POSITION = '__nextjs-dev-tools-position' export const STORAGE_KEY_POSITION = '__nextjs-dev-tools-position'
...@@ -112,6 +115,13 @@ export interface BuildingIndicatorHideAction { ...@@ -112,6 +115,13 @@ export interface BuildingIndicatorHideAction {
type: typeof ACTION_BUILDING_INDICATOR_HIDE type: typeof ACTION_BUILDING_INDICATOR_HIDE
} }
export interface RenderingIndicatorShowAction {
type: typeof ACTION_RENDERING_INDICATOR_SHOW
}
export interface RenderingIndicatorHideAction {
type: typeof ACTION_RENDERING_INDICATOR_HIDE
}
export type BusEvent = export type BusEvent =
| BuildOkAction | BuildOkAction
| BuildErrorAction | BuildErrorAction
...@@ -128,6 +138,8 @@ export type BusEvent = ...@@ -128,6 +138,8 @@ export type BusEvent =
| ErrorOverlayToggleAction | ErrorOverlayToggleAction
| BuildingIndicatorShowAction | BuildingIndicatorShowAction
| BuildingIndicatorHideAction | BuildingIndicatorHideAction
| RenderingIndicatorShowAction
| RenderingIndicatorHideAction
const REACT_ERROR_STACK_BOTTOM_FRAME_REGEX = const REACT_ERROR_STACK_BOTTOM_FRAME_REGEX =
// 1st group: v8 // 1st group: v8
...@@ -153,6 +165,7 @@ export const INITIAL_OVERLAY_STATE: Omit< ...@@ -153,6 +165,7 @@ export const INITIAL_OVERLAY_STATE: Omit<
buildError: null, buildError: null,
errors: [], errors: [],
notFound: false, notFound: false,
renderingIndicator: false,
staticIndicator: false, staticIndicator: false,
/* /*
This is set to `true` when we can reliably know This is set to `true` when we can reliably know
...@@ -315,6 +328,12 @@ export function useErrorOverlayReducer( ...@@ -315,6 +328,12 @@ export function useErrorOverlayReducer(
case ACTION_BUILDING_INDICATOR_HIDE: { case ACTION_BUILDING_INDICATOR_HIDE: {
return { ...state, buildingIndicator: false } return { ...state, buildingIndicator: false }
} }
case ACTION_RENDERING_INDICATOR_SHOW: {
return { ...state, renderingIndicator: true }
}
case ACTION_RENDERING_INDICATOR_HIDE: {
return { ...state, renderingIndicator: false }
}
default: { default: {
return state return state
} }
......
...@@ -55,6 +55,7 @@ const state: OverlayState = { ...@@ -55,6 +55,7 @@ const state: OverlayState = {
versionInfo: mockVersionInfo, versionInfo: mockVersionInfo,
notFound: false, notFound: false,
buildingIndicator: false, buildingIndicator: false,
renderingIndicator: false,
staticIndicator: true, staticIndicator: true,
debugInfo: { devtoolsFrontendUrl: undefined }, debugInfo: { devtoolsFrontendUrl: undefined },
isErrorOverlayOpen: false, isErrorOverlayOpen: false,
......
...@@ -10,7 +10,6 @@ import { ...@@ -10,7 +10,6 @@ import {
import { useState, useEffect, useRef, createContext, useContext } from 'react' import { useState, useEffect, useRef, createContext, useContext } from 'react'
import { Toast } from '../../toast' import { Toast } from '../../toast'
import { NextLogo } from './next-logo' import { NextLogo } from './next-logo'
import { useIsDevRendering } from '../../../../utils/dev-indicator/dev-render-indicator'
import { useDelayedRender } from '../../../hooks/use-delayed-render' import { useDelayedRender } from '../../../hooks/use-delayed-render'
import { TurbopackInfo } from './dev-tools-info/turbopack-info' import { TurbopackInfo } from './dev-tools-info/turbopack-info'
import { RouteInfo } from './dev-tools-info/route-info' import { RouteInfo } from './dev-tools-info/route-info'
...@@ -54,6 +53,7 @@ export function DevToolsIndicator({ ...@@ -54,6 +53,7 @@ export function DevToolsIndicator({
semver={state.versionInfo.installed} semver={state.versionInfo.installed}
issueCount={errorCount} issueCount={errorCount}
isDevBuilding={state.buildingIndicator} isDevBuilding={state.buildingIndicator}
isDevRendering={state.renderingIndicator}
isStaticRoute={state.staticIndicator} isStaticRoute={state.staticIndicator}
hide={() => { hide={() => {
setIsDevToolsIndicatorVisible(false) setIsDevToolsIndicatorVisible(false)
...@@ -96,6 +96,7 @@ function DevToolsPopover({ ...@@ -96,6 +96,7 @@ function DevToolsPopover({
disabled, disabled,
issueCount, issueCount,
isDevBuilding, isDevBuilding,
isDevRendering,
isStaticRoute, isStaticRoute,
isTurbopack, isTurbopack,
isBuildError, isBuildError,
...@@ -110,6 +111,7 @@ function DevToolsPopover({ ...@@ -110,6 +111,7 @@ function DevToolsPopover({
isStaticRoute: boolean isStaticRoute: boolean
semver: string | undefined semver: string | undefined
isDevBuilding: boolean isDevBuilding: boolean
isDevRendering: boolean
isTurbopack: boolean isTurbopack: boolean
isBuildError: boolean isBuildError: boolean
hide: () => void hide: () => void
...@@ -297,7 +299,7 @@ function DevToolsPopover({ ...@@ -297,7 +299,7 @@ function DevToolsPopover({
onTriggerClick={onTriggerClick} onTriggerClick={onTriggerClick}
toggleErrorOverlay={toggleErrorOverlay} toggleErrorOverlay={toggleErrorOverlay}
isDevBuilding={isDevBuilding} isDevBuilding={isDevBuilding}
isDevRendering={useIsDevRendering()} isDevRendering={isDevRendering}
isBuildError={isBuildError} isBuildError={isBuildError}
scale={scale} scale={scale}
/> />
......
...@@ -13,7 +13,7 @@ export function ShadowPortal({ children }: { children: React.ReactNode }) { ...@@ -13,7 +13,7 @@ export function ShadowPortal({ children }: { children: React.ReactNode }) {
// we can assure the root render is not a Transition. // we can assure the root render is not a Transition.
React.useEffect(() => { React.useEffect(() => {
const ownerDocument = document const ownerDocument = document
portalNode.current = ownerDocument.createElement('nextjs-portal') portalNode.current = ownerDocument.querySelector('nextjs-portal')!
// load default color preference from localstorage // load default color preference from localstorage
if (typeof localStorage !== 'undefined') { if (typeof localStorage !== 'undefined') {
const theme = localStorage.getItem(STORAGE_KEY_THEME) const theme = localStorage.getItem(STORAGE_KEY_THEME)
...@@ -26,14 +26,15 @@ export function ShadowPortal({ children }: { children: React.ReactNode }) { ...@@ -26,14 +26,15 @@ export function ShadowPortal({ children }: { children: React.ReactNode }) {
} }
} }
shadowNode.current = portalNode.current.attachShadow({ mode: 'open' }) // We can only attach but never detach a shadow root.
ownerDocument.body.appendChild(portalNode.current) // So if this is a remount, we don't need to attach a shadow root. Only
forceUpdate({}) // on the very first, DOM-wide mount.
return () => { // This is mostly guarding against faulty _app implementations that
if (portalNode.current && portalNode.current.ownerDocument) { // createa React Root in getInitialProps but don't clean it up like test/integration/app-tree/pages/_app.tsx
portalNode.current.ownerDocument.body.removeChild(portalNode.current) if (portalNode.current.shadowRoot === null) {
} shadowNode.current = portalNode.current.attachShadow({ mode: 'open' })
} }
forceUpdate({})
}, []) }, [])
return shadowNode.current return shadowNode.current
......
...@@ -74,6 +74,7 @@ const initialState: OverlayState = { ...@@ -74,6 +74,7 @@ const initialState: OverlayState = {
refreshState: { type: 'idle' }, refreshState: { type: 'idle' },
notFound: false, notFound: false,
buildingIndicator: false, buildingIndicator: false,
renderingIndicator: false,
staticIndicator: false, staticIndicator: false,
debugInfo: { devtoolsFrontendUrl: undefined }, debugInfo: { devtoolsFrontendUrl: undefined },
versionInfo: { versionInfo: {
......
/*
* Singleton store to track whether the app is currently being rendered
* Used by the dev tools indicator to show render status
*/
import { useSyncExternalStore } from 'react'
let isVisible = false
let listeners: Array<() => void> = []
const subscribe = (listener: () => void) => {
listeners.push(listener)
return () => {
listeners = listeners.filter((l) => l !== listener)
}
}
const getSnapshot = () => isVisible
const show = () => {
isVisible = true
listeners.forEach((listener) => listener())
}
const hide = () => {
isVisible = false
listeners.forEach((listener) => listener())
}
export function useIsDevRendering() {
return useSyncExternalStore(subscribe, getSnapshot)
}
export const devRenderIndicator = {
show,
hide,
}
import { useEffect, useTransition } from 'react' import { useEffect, useTransition } from 'react'
import { devRenderIndicator } from './dev-render-indicator' import { dispatcher } from 'next/dist/compiled/next-devtools'
export const useSyncDevRenderIndicator = () => { export const useAppDevRenderingIndicator = () => {
const [isPending, startTransition] = useTransition() const [isPending, startTransition] = useTransition()
useEffect(() => { useEffect(() => {
if (isPending) { if (isPending) {
devRenderIndicator.show() dispatcher.renderingIndicatorShow()
} else { } else {
devRenderIndicator.hide() dispatcher.renderingIndicatorHide()
} }
}, [isPending]) }, [isPending])
......
...@@ -35,14 +35,13 @@ export function useActionQueue( ...@@ -35,14 +35,13 @@ export function useActionQueue(
// this is conceptually how we're modeling the app router state, despite the // this is conceptually how we're modeling the app router state, despite the
// weird implementation details. // weird implementation details.
if (process.env.NODE_ENV !== 'production') { if (process.env.NODE_ENV !== 'production') {
const useSyncDevRenderIndicator = ( const { useAppDevRenderingIndicator } =
require('./react-dev-overlay/utils/dev-indicator/use-sync-dev-render-indicator') as typeof import('./react-dev-overlay/utils/dev-indicator/use-sync-dev-render-indicator') require('./react-dev-overlay/utils/dev-indicator/use-app-dev-rendering-indicator') as typeof import('./react-dev-overlay/utils/dev-indicator/use-app-dev-rendering-indicator')
).useSyncDevRenderIndicator
// eslint-disable-next-line react-hooks/rules-of-hooks // eslint-disable-next-line react-hooks/rules-of-hooks
const syncDevRenderIndicator = useSyncDevRenderIndicator() const appDevRenderingIndicator = useAppDevRenderingIndicator()
dispatch = (action: ReducerActions) => { dispatch = (action: ReducerActions) => {
syncDevRenderIndicator(() => { appDevRenderingIndicator(() => {
actionQueue.dispatch(action, setState) actionQueue.dispatch(action, setState)
}) })
} }
......
...@@ -179,9 +179,7 @@ class Container extends React.Component<{ ...@@ -179,9 +179,7 @@ class Container extends React.Component<{
if (process.env.NODE_ENV === 'production') { if (process.env.NODE_ENV === 'production') {
return this.props.children return this.props.children
} else { } else {
const { const { PagesDevOverlay } =
PagesDevOverlay,
}: typeof import('./components/react-dev-overlay/pages/pages-dev-overlay') =
require('./components/react-dev-overlay/pages/pages-dev-overlay') as typeof import('./components/react-dev-overlay/pages/pages-dev-overlay') require('./components/react-dev-overlay/pages/pages-dev-overlay') as typeof import('./components/react-dev-overlay/pages/pages-dev-overlay')
return <PagesDevOverlay>{this.props.children}</PagesDevOverlay> return <PagesDevOverlay>{this.props.children}</PagesDevOverlay>
} }
......
...@@ -3132,6 +3132,17 @@ export async function next_bundle_server(task, opts) { ...@@ -3132,6 +3132,17 @@ export async function next_bundle_server(task, opts) {
}) })
} }
export async function next_bundle_devtools(task, opts) {
await task.source('dist').webpack({
watch: opts.dev,
config: require('./next-devtools.webpack-config')({
// TODO: Use prod variant
dev: true,
}),
name: 'next-bundle-devtools-dev',
})
}
export async function next_bundle(task, opts) { export async function next_bundle(task, opts) {
await task.parallel( await task.parallel(
[ [
...@@ -3152,6 +3163,8 @@ export async function next_bundle(task, opts) { ...@@ -3152,6 +3163,8 @@ export async function next_bundle(task, opts) {
'next_bundle_pages_dev_turbo', 'next_bundle_pages_dev_turbo',
// builds the minimal server // builds the minimal server
'next_bundle_server', 'next_bundle_server',
// devtools
'next_bundle_devtools',
], ],
opts opts
) )
......
...@@ -24,6 +24,11 @@ ...@@ -24,6 +24,11 @@
"next/dist/compiled/@vercel/og/satori": [ "next/dist/compiled/@vercel/og/satori": [
"./src/compiled/@vercel/og/satori" "./src/compiled/@vercel/og/satori"
], ],
// TODO: Enable types by telling Turbopack to ignore this alias.
// tsconfig#paths are for type locations not source locations.
// "next/dist/compiled/next-devtools": [
// "./src/client/components/react-dev-overlay/app/entrypoint.d.ts"
// ],
"next/dist/shared/lib/image-loader": ["./src/shared/lib/image-loader.ts"] "next/dist/shared/lib/image-loader": ["./src/shared/lib/image-loader.ts"]
} }
}, },
......
...@@ -364,6 +364,9 @@ declare module 'next/dist/compiled/jest-worker' { ...@@ -364,6 +364,9 @@ declare module 'next/dist/compiled/jest-worker' {
export * from 'jest-worker' export * from 'jest-worker'
} }
// TODO: Use tsconfig#paths instead
declare module 'next/dist/compiled/next-devtools'
declare module 'next/dist/compiled/react-is' { declare module 'next/dist/compiled/react-is' {
export * from 'react-is' export * from 'react-is'
} }
......
...@@ -2,6 +2,9 @@ ...@@ -2,6 +2,9 @@
// it is not meant to be used with local type checking and is ignored in our // it is not meant to be used with local type checking and is ignored in our
// local tsconfig.json // local tsconfig.json
// TODO: Use tsconfig#paths instead
declare module 'next/dist/compiled/next-devtools'
declare module 'next/dist/compiled/webpack/webpack' { declare module 'next/dist/compiled/webpack/webpack' {
export function init(): void export function init(): void
export let BasicEvaluatedExpression: any export let BasicEvaluatedExpression: any
......
...@@ -553,7 +553,7 @@ describe('ReactRefreshLogBox app', () => { ...@@ -553,7 +553,7 @@ describe('ReactRefreshLogBox app', () => {
await session.evaluate( await session.evaluate(
() => () =>
document document
.querySelector('body > nextjs-portal') .querySelector('body nextjs-portal')
.shadowRoot.querySelectorAll('#nextjs__container_errors_desc a') .shadowRoot.querySelectorAll('#nextjs__container_errors_desc a')
.length .length
) )
...@@ -563,7 +563,7 @@ describe('ReactRefreshLogBox app', () => { ...@@ -563,7 +563,7 @@ describe('ReactRefreshLogBox app', () => {
() => () =>
( (
document document
.querySelector('body > nextjs-portal') .querySelector('body nextjs-portal')
.shadowRoot.querySelector( .shadowRoot.querySelector(
'#nextjs__container_errors_desc a:nth-of-type(1)' '#nextjs__container_errors_desc a:nth-of-type(1)'
) as any ) as any
...@@ -635,7 +635,7 @@ describe('ReactRefreshLogBox app', () => { ...@@ -635,7 +635,7 @@ describe('ReactRefreshLogBox app', () => {
await session.evaluate( await session.evaluate(
() => () =>
document document
.querySelector('body > nextjs-portal') .querySelector('body nextjs-portal')
.shadowRoot.querySelectorAll('#nextjs__container_errors_desc a') .shadowRoot.querySelectorAll('#nextjs__container_errors_desc a')
.length .length
) )
...@@ -645,7 +645,7 @@ describe('ReactRefreshLogBox app', () => { ...@@ -645,7 +645,7 @@ describe('ReactRefreshLogBox app', () => {
() => () =>
( (
document document
.querySelector('body > nextjs-portal') .querySelector('body nextjs-portal')
.shadowRoot.querySelector( .shadowRoot.querySelector(
'#nextjs__container_errors_desc a:nth-of-type(1)' '#nextjs__container_errors_desc a:nth-of-type(1)'
) as any ) as any
...@@ -717,7 +717,7 @@ describe('ReactRefreshLogBox app', () => { ...@@ -717,7 +717,7 @@ describe('ReactRefreshLogBox app', () => {
await session.evaluate( await session.evaluate(
() => () =>
document document
.querySelector('body > nextjs-portal') .querySelector('body nextjs-portal')
.shadowRoot.querySelectorAll('#nextjs__container_errors_desc a') .shadowRoot.querySelectorAll('#nextjs__container_errors_desc a')
.length .length
) )
...@@ -727,7 +727,7 @@ describe('ReactRefreshLogBox app', () => { ...@@ -727,7 +727,7 @@ describe('ReactRefreshLogBox app', () => {
() => () =>
( (
document document
.querySelector('body > nextjs-portal') .querySelector('body nextjs-portal')
.shadowRoot.querySelector( .shadowRoot.querySelector(
'#nextjs__container_errors_desc a:nth-of-type(1)' '#nextjs__container_errors_desc a:nth-of-type(1)'
) as any ) as any
...@@ -800,7 +800,7 @@ describe('ReactRefreshLogBox app', () => { ...@@ -800,7 +800,7 @@ describe('ReactRefreshLogBox app', () => {
await session.evaluate( await session.evaluate(
() => () =>
document document
.querySelector('body > nextjs-portal') .querySelector('body nextjs-portal')
.shadowRoot.querySelectorAll('#nextjs__container_errors_desc a') .shadowRoot.querySelectorAll('#nextjs__container_errors_desc a')
.length .length
) )
...@@ -810,7 +810,7 @@ describe('ReactRefreshLogBox app', () => { ...@@ -810,7 +810,7 @@ describe('ReactRefreshLogBox app', () => {
() => () =>
( (
document document
.querySelector('body > nextjs-portal') .querySelector('body nextjs-portal')
.shadowRoot.querySelector( .shadowRoot.querySelector(
'#nextjs__container_errors_desc a:nth-of-type(1)' '#nextjs__container_errors_desc a:nth-of-type(1)'
) as any ) as any
...@@ -822,7 +822,7 @@ describe('ReactRefreshLogBox app', () => { ...@@ -822,7 +822,7 @@ describe('ReactRefreshLogBox app', () => {
() => () =>
( (
document document
.querySelector('body > nextjs-portal') .querySelector('body nextjs-portal')
.shadowRoot.querySelector( .shadowRoot.querySelector(
'#nextjs__container_errors_desc a:nth-of-type(2)' '#nextjs__container_errors_desc a:nth-of-type(2)'
) as any ) as any
......
...@@ -209,25 +209,23 @@ describe('Error overlay for hydration errors in App router', () => { ...@@ -209,25 +209,23 @@ describe('Error overlay for hydration errors in App router', () => {
{ {
"componentStack": "... "componentStack": "...
<HotReload assetPrefix="" globalError={[...]}> <HotReload assetPrefix="" globalError={[...]}>
<AppDevOverlay state={{nextId:1, ...}} dispatch={function bound dispatchReducerAction} globalError={[...]}> <AppDevOverlayErrorBoundary globalError={[...]}>
<AppDevOverlayErrorBoundary globalError={[...]} onError={function}> <ReplaySsrOnlyErrors>
<ReplaySsrOnlyErrors> <DevRootHTTPAccessFallbackBoundary>
<DevRootHTTPAccessFallbackBoundary> <HTTPAccessFallbackBoundary notFound={<NotAllowedRootHTTPFallbackError>}>
<HTTPAccessFallbackBoundary notFound={<NotAllowedRootHTTPFallbackError>}> <HTTPAccessFallbackErrorBoundary pathname="/" notFound={<NotAllowedRootHTTPFallbackError>} ...>
<HTTPAccessFallbackErrorBoundary pathname="/" notFound={<NotAllowedRootHTTPFallbackError>} ...> <RedirectBoundary>
<RedirectBoundary> <RedirectErrorBoundary router={{...}}>
<RedirectErrorBoundary router={{...}}> <Head>
<Head> <script>
<script> <script>
<script> <script>
<script> <ClientSegmentRoot Component={function Root} slots={{...}} params={{}}>
<ClientSegmentRoot Component={function Root} slots={{...}} params={{}}> <Root params={Promise}>
<Root params={Promise}> <html
<html - className="server-html"
- className="server-html" >
> ...",
...
...",
"description": "A tree hydrated but some attributes of the server rendered HTML didn't match the client properties. This won't be patched up. This can happen if a SSR-ed Client Component used:", "description": "A tree hydrated but some attributes of the server rendered HTML didn't match the client properties. This won't be patched up. This can happen if a SSR-ed Client Component used:",
"environmentLabel": null, "environmentLabel": null,
"label": "Console Error", "label": "Console Error",
...@@ -245,22 +243,20 @@ describe('Error overlay for hydration errors in App router', () => { ...@@ -245,22 +243,20 @@ describe('Error overlay for hydration errors in App router', () => {
{ {
"componentStack": "... "componentStack": "...
<HotReload assetPrefix="" globalError={[...]}> <HotReload assetPrefix="" globalError={[...]}>
<AppDevOverlay state={{nextId:1, ...}} dispatch={function bound dispatchReducerAction} globalError={[...]}> <AppDevOverlayErrorBoundary globalError={[...]}>
<AppDevOverlayErrorBoundary globalError={[...]} onError={function}> <ReplaySsrOnlyErrors>
<ReplaySsrOnlyErrors> <DevRootHTTPAccessFallbackBoundary>
<DevRootHTTPAccessFallbackBoundary> <HTTPAccessFallbackBoundary notFound={<NotAllowedRootHTTPFallbackError>}>
<HTTPAccessFallbackBoundary notFound={<NotAllowedRootHTTPFallbackError>}> <HTTPAccessFallbackErrorBoundary pathname="/" notFound={<NotAllowedRootHTTPFallbackError>} ...>
<HTTPAccessFallbackErrorBoundary pathname="/" notFound={<NotAllowedRootHTTPFallbackError>} ...> <RedirectBoundary>
<RedirectBoundary> <RedirectErrorBoundary router={{...}}>
<RedirectErrorBoundary router={{...}}> <Head>
<Head> <ClientSegmentRoot Component={function Root} slots={{...}} params={{}}>
<ClientSegmentRoot Component={function Root} slots={{...}} params={{}}> <Root params={Promise}>
<Root params={Promise}> <html
<html - className="server-html"
- className="server-html" >
> ...",
...
...",
"description": "A tree hydrated but some attributes of the server rendered HTML didn't match the client properties. This won't be patched up. This can happen if a SSR-ed Client Component used:", "description": "A tree hydrated but some attributes of the server rendered HTML didn't match the client properties. This won't be patched up. This can happen if a SSR-ed Client Component used:",
"environmentLabel": null, "environmentLabel": null,
"label": "Console Error", "label": "Console Error",
...@@ -1044,9 +1040,11 @@ describe('Error overlay for hydration errors in App router', () => { ...@@ -1044,9 +1040,11 @@ describe('Error overlay for hydration errors in App router', () => {
}, },
{ {
"componentStack": "... "componentStack": "...
<HotReload assetPrefix="" globalError={[...]}> <Router actionQueue={{state:{...}, ...}} assetPrefix="" globalError={[...]} gracefullyDegrade={false}>
<AppDevOverlay state={{nextId:1, ...}} dispatch={function bound dispatchReducerAction} globalError={[...]}> <HistoryUpdater>
<AppDevOverlayErrorBoundary globalError={[...]} onError={function}> <RuntimeStyles>
<HotReload assetPrefix="" globalError={[...]}>
<AppDevOverlayErrorBoundary globalError={[...]}>
<ReplaySsrOnlyErrors> <ReplaySsrOnlyErrors>
<DevRootHTTPAccessFallbackBoundary> <DevRootHTTPAccessFallbackBoundary>
<HTTPAccessFallbackBoundary notFound={<NotAllowedRootHTTPFallbackError>}> <HTTPAccessFallbackBoundary notFound={<NotAllowedRootHTTPFallbackError>}>
...@@ -1059,8 +1057,7 @@ describe('Error overlay for hydration errors in App router', () => { ...@@ -1059,8 +1057,7 @@ describe('Error overlay for hydration errors in App router', () => {
<body> <body>
<Script src="https://ex..." strategy="beforeInte..."> <Script src="https://ex..." strategy="beforeInte...">
> <script nonce={undefined} dangerouslySetInnerHTML={{__html:"(self.__ne..."}}> > <script nonce={undefined} dangerouslySetInnerHTML={{__html:"(self.__ne..."}}>
... ...",
...",
"description": "In HTML, <script> cannot be a child of <html>. "description": "In HTML, <script> cannot be a child of <html>.
This will cause a hydration error.", This will cause a hydration error.",
"environmentLabel": null, "environmentLabel": null,
......
...@@ -15,6 +15,9 @@ ...@@ -15,6 +15,9 @@
"packages/next/src/client/app-bootstrap.ts", "packages/next/src/client/app-bootstrap.ts",
"packages/next/src/client/components/errors/graceful-degrade-boundary.tsx" "packages/next/src/client/components/errors/graceful-degrade-boundary.tsx"
], ],
"ban-script-appendchild-calls": [
"packages/next/src/client/components/react-dev-overlay/app/app-dev-overlay.browser.tsx"
],
"ban-script-content-assignments": ["packages/next/src/client/script.tsx"], "ban-script-content-assignments": ["packages/next/src/client/script.tsx"],
"ban-script-src-assignments": [ "ban-script-src-assignments": [
"packages/next/src/client/script.tsx", "packages/next/src/client/script.tsx",
......
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