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

[dev-overlay] Use same bundle for Pages and App Router (#80019)

parent 9e9d13fb
......@@ -695,5 +695,7 @@
"694": "createPrerenderPathname was called inside a client component scope.",
"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"
"697": "Next DevTools: Can't render in this environment. This is a bug in Next.js",
"698": "Next DevTools: App Dev Overlay is already mounted. This is a bug in Next.js",
"699": "Next DevTools: Pages Dev Overlay is already mounted. This is a bug in Next.js"
}
......@@ -27,7 +27,7 @@ module.exports = ({ dev, ...rest }) => {
return {
entry: path.join(
__dirname,
'src/client/components/react-dev-overlay/app/entrypoint.js'
'src/client/components/react-dev-overlay/entrypoint.js'
),
target,
mode: dev ? 'development' : 'production',
......
......@@ -93,7 +93,7 @@ const sharedExternals = [
const externalsMap = {
'./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',
'commonjs next/dist/client/components/react-dev-overlay/dev-overlay.shim.js',
}
const externalsRegexMap = {
......
......@@ -17,15 +17,16 @@ import {
ACTION_BUILDING_INDICATOR_SHOW,
ACTION_RENDERING_INDICATOR_HIDE,
ACTION_RENDERING_INDICATOR_SHOW,
} from '../shared'
} 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'
import { FontStyles } from './font/font-styles'
import type { HydrationErrorState } from './pages/hydration-error-state'
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
......@@ -143,22 +144,21 @@ function replayQueuedEvents(dispatch: NonNullable<typeof maybeDispatch>) {
}
}
function getSquashedHydrationErrorDetails() {
// We don't squash hydration errors in the App Router.
return null
}
function AppDevOverlay({
function DevOverlayRoot({
getComponentStack,
getOwnerStack,
getSquashedHydrationErrorDetails,
isRecoverableError,
routerType,
}: {
getComponentStack: (error: Error) => string | undefined
getOwnerStack: (error: Error) => string | null | undefined
getSquashedHydrationErrorDetails: (error: Error) => HydrationErrorState | null
isRecoverableError: (error: Error) => boolean
routerType: 'app' | 'pages'
}) {
const [state, dispatch] = useErrorOverlayReducer(
'app',
routerType,
getComponentStack,
getOwnerStack,
isRecoverableError
......@@ -193,13 +193,28 @@ function AppDevOverlay({
)
}
let isMounted = false
let isPagesMounted = false
let isAppMounted = false
function getSquashedHydrationErrorDetailsApp() {
// We don't squash hydration errors in the App Router.
return null
}
export function renderAppDevOverlay(
getComponentStack: (error: Error) => string | undefined,
getOwnerStack: (error: Error) => string | null | undefined,
isRecoverableError: (error: Error) => boolean
): void {
if (!isMounted) {
if (isPagesMounted) {
// Switching between App and Pages Router is always a hard navigation
// TODO: Support soft navigation between App and Pages Router
throw new Error(
'Next DevTools: Pages Dev Overlay is already mounted. This is a bug in Next.js'
)
}
if (!isAppMounted) {
// 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')
......@@ -225,14 +240,80 @@ export function renderAppDevOverlay(
// TODO: Dedicated error boundary or root error callbacks?
// At least it won't unmount any user code if it errors.
root.render(
<AppDevOverlay
<DevOverlayRoot
getComponentStack={getComponentStack}
getOwnerStack={getOwnerStack}
getSquashedHydrationErrorDetails={getSquashedHydrationErrorDetailsApp}
isRecoverableError={isRecoverableError}
routerType="app"
/>
)
})
isAppMounted = true
}
}
export function renderPagesDevOverlay(
getComponentStack: (error: Error) => string | undefined,
getOwnerStack: (error: Error) => string | null | undefined,
getSquashedHydrationErrorDetails: (
error: Error
) => HydrationErrorState | null,
isRecoverableError: (error: Error) => boolean
): void {
if (isAppMounted) {
// Switching between App and Pages Router is always a hard navigation
// TODO: Support soft navigation between App and Pages Router
throw new Error(
'Next DevTools: App Dev Overlay is already mounted. This is a bug in Next.js'
)
}
if (!isPagesMounted) {
const container = document.createElement('nextjs-portal')
// 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.
container.style.position = 'absolute'
// Pages Router runs with React 18 or 19 so we can't use the same trick as with
// App Router. We just reconnect the container if React wipes it e.g. when
// we recover from a shell error via createRoot()
new MutationObserver((records) => {
for (const record of records) {
if (record.type === 'childList') {
for (const node of record.removedNodes) {
if (node === container) {
// Reconnect the container to the body
document.body.appendChild(container)
}
}
}
}
}).observe(document.body, {
childList: true,
})
document.body.appendChild(container)
const root = createRoot(container)
startTransition(() => {
// TODO: Dedicated error boundary or root error callbacks?
// At least it won't unmount any user code if it errors.
root.render(
<DevOverlayRoot
getComponentStack={getComponentStack}
getOwnerStack={getOwnerStack}
getSquashedHydrationErrorDetails={getSquashedHydrationErrorDetails}
isRecoverableError={isRecoverableError}
routerType="pages"
/>
)
})
isMounted = true
isPagesMounted = true
}
}
......@@ -4,6 +4,12 @@ export function renderAppDevOverlay() {
)
}
export function renderPagesDevOverlay() {
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(
{},
......
import * as Bus from './bus'
import { dispatcher } from 'next/dist/compiled/next-devtools'
import {
attachHydrationErrorState,
storeHydrationErrorStateFromConsoleArgs,
} from './hydration-error-state'
import {
ACTION_BEFORE_REFRESH,
ACTION_BUILDING_INDICATOR_HIDE,
ACTION_BUILD_ERROR,
ACTION_BUILD_OK,
ACTION_BUILDING_INDICATOR_SHOW,
ACTION_DEV_INDICATOR,
ACTION_REFRESH,
ACTION_STATIC_INDICATOR,
ACTION_UNHANDLED_ERROR,
ACTION_UNHANDLED_REJECTION,
ACTION_VERSION_INFO,
} from '../shared'
import type { VersionInfo } from '../../../../server/dev/parse-version-info'
import type { DevIndicatorServerState } from '../../../../server/dev/dev-indicator-server-state'
......@@ -35,10 +22,7 @@ function handleError(error: unknown) {
error.name !== 'ModuleBuildError' &&
error.name !== 'ModuleNotFoundError'
) {
Bus.emit({
type: ACTION_UNHANDLED_ERROR,
reason: error,
})
dispatcher.onUnhandledError(error)
}
}
......@@ -68,10 +52,7 @@ function onUnhandledRejection(ev: PromiseRejectionEvent) {
return
}
Bus.emit({
type: ACTION_UNHANDLED_REJECTION,
reason: reason,
})
dispatcher.onUnhandledRejection(reason)
}
export function register() {
......@@ -90,39 +71,39 @@ export function register() {
}
export function onBuildOk() {
Bus.emit({ type: ACTION_BUILD_OK })
dispatcher.onBuildOk()
}
export function onBuildError(message: string) {
Bus.emit({ type: ACTION_BUILD_ERROR, message })
dispatcher.onBuildError(message)
}
export function onRefresh() {
Bus.emit({ type: ACTION_REFRESH })
dispatcher.onRefresh()
}
export function onBeforeRefresh() {
Bus.emit({ type: ACTION_BEFORE_REFRESH })
dispatcher.onBeforeRefresh()
}
export function onVersionInfo(versionInfo: VersionInfo) {
Bus.emit({ type: ACTION_VERSION_INFO, versionInfo })
dispatcher.onVersionInfo(versionInfo)
}
export function onStaticIndicator(isStatic: boolean) {
Bus.emit({ type: ACTION_STATIC_INDICATOR, staticIndicator: isStatic })
dispatcher.onStaticIndicator(isStatic)
}
export function onDevIndicator(devIndicatorsState: DevIndicatorServerState) {
Bus.emit({ type: ACTION_DEV_INDICATOR, devIndicator: devIndicatorsState })
dispatcher.onDevIndicator(devIndicatorsState)
}
export function buildingIndicatorShow() {
Bus.emit({ type: ACTION_BUILDING_INDICATOR_SHOW })
dispatcher.buildingIndicatorShow()
}
export function buildingIndicatorHide() {
Bus.emit({ type: ACTION_BUILDING_INDICATOR_HIDE })
dispatcher.buildingIndicatorHide()
}
export { getErrorByType } from '../utils/get-error-by-type'
......
import React from 'react'
import * as Bus from './bus'
import { useErrorOverlayReducer } from '../shared'
import { Router } from '../../../router'
import { renderPagesDevOverlay } from 'next/dist/compiled/next-devtools'
import { getComponentStack, getOwnerStack } from '../../errors/stitched-error'
import { isRecoverableError } from '../../../react-client-callbacks/on-recoverable-error'
import { getSquashedHydrationErrorDetails } from './hydration-error-state'
export const usePagesDevOverlay = () => {
const [state, dispatch] = useErrorOverlayReducer(
'pages',
getComponentStack,
getOwnerStack,
isRecoverableError
)
export const usePagesDevOverlayBridge = () => {
React.useInsertionEffect(() => {
// NDT uses a different React instance so it's not technically a state update
// scheduled from useInsertionEffect.
renderPagesDevOverlay(
getComponentStack,
getOwnerStack,
getSquashedHydrationErrorDetails,
isRecoverableError
)
}, [])
React.useEffect(() => {
Bus.on(dispatch)
const { handleStaticIndicator } =
require('./hot-reloader-client') as typeof import('./hot-reloader-client')
......@@ -23,12 +25,6 @@ export const usePagesDevOverlay = () => {
return function () {
Router.events.off('routeChangeComplete', handleStaticIndicator)
Bus.off(dispatch)
}
}, [dispatch])
return {
state,
dispatch,
}
}, [])
}
import { PagesDevOverlayErrorBoundary } from './pages-dev-overlay-error-boundary'
import { usePagesDevOverlayBridge } from './hooks'
export type ErrorType = 'runtime' | 'build'
export type PagesDevOverlayBridgeType = typeof PagesDevOverlayBridge
interface PagesDevOverlayBridgeProps {
children?: React.ReactNode
}
export function PagesDevOverlayBridge({
children,
}: PagesDevOverlayBridgeProps) {
usePagesDevOverlayBridge()
return <PagesDevOverlayErrorBoundary>{children}</PagesDevOverlayErrorBoundary>
}
import { useInsertionEffect } from 'react'
import { PagesDevOverlayErrorBoundary } from './pages-dev-overlay-error-boundary'
import { usePagesDevOverlay } from './hooks'
import { FontStyles } from '../font/font-styles'
import { DevOverlay } from '../ui/dev-overlay'
import { getSquashedHydrationErrorDetails } from './hydration-error-state'
export type ErrorType = 'runtime' | 'build'
export type PagesDevOverlayType = typeof PagesDevOverlay
interface PagesDevOverlayProps {
children?: React.ReactNode
}
export function PagesDevOverlay({ children }: PagesDevOverlayProps) {
const { state, dispatch } = usePagesDevOverlay()
// TODO: Remove once Root initializer creates this element
useInsertionEffect(() => {
const container = document.createElement('nextjs-portal')
document.body.appendChild(container)
}, [])
return (
<>
<PagesDevOverlayErrorBoundary>{children}</PagesDevOverlayErrorBoundary>
{/* Fonts can only be loaded outside the Shadow DOM. */}
<FontStyles />
<DevOverlay
state={state}
dispatch={dispatch}
getSquashedHydrationErrorDetails={getSquashedHydrationErrorDetails}
/>
</>
)
}
......@@ -179,9 +179,11 @@ class Container extends React.Component<{
if (process.env.NODE_ENV === 'production') {
return this.props.children
} else {
const { PagesDevOverlay } =
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>
const { PagesDevOverlayBridge } =
require('./components/react-dev-overlay/pages/pages-dev-overlay-bridge') as typeof import('./components/react-dev-overlay/pages/pages-dev-overlay-bridge')
return (
<PagesDevOverlayBridge>{this.props.children}</PagesDevOverlayBridge>
)
}
}
}
......
......@@ -21,6 +21,7 @@ import type { NodeNextResponse, NodeNextRequest } from '../base-http/node'
import type { RouteEnsurer } from '../route-matcher-managers/dev-route-matcher-manager'
import type { PagesManifest } from '../../build/webpack/plugins/pages-manifest-plugin'
import * as React from 'react'
import fs from 'fs'
import { Worker } from 'next/dist/compiled/jest-worker'
import { join as pathJoin } from 'path'
......@@ -67,21 +68,21 @@ import type { ServerOnInstrumentationRequestError } from '../app-render/types'
import type { ServerComponentsHmrCache } from '../response-cache'
import { logRequests } from './log-requests'
import { FallbackMode } from '../../lib/fallback'
import type { PagesDevOverlayType } from '../../client/components/react-dev-overlay/pages/pages-dev-overlay'
import type { PagesDevOverlayBridgeType } from '../../client/components/react-dev-overlay/pages/pages-dev-overlay-bridge'
import {
ensureInstrumentationRegistered,
getInstrumentationModule,
} from '../lib/router-utils/instrumentation-globals.external'
// Load ReactDevOverlay only when needed
let ReactDevOverlayImpl: PagesDevOverlayType
const ReactDevOverlay: PagesDevOverlayType = (props) => {
if (ReactDevOverlayImpl === undefined) {
ReactDevOverlayImpl = (
require('../../client/components/react-dev-overlay/pages/pages-dev-overlay') as typeof import('../../client/components/react-dev-overlay/pages/pages-dev-overlay')
).PagesDevOverlay as PagesDevOverlayType
}
return ReactDevOverlayImpl(props)
let PagesDevOverlayBridgeImpl: PagesDevOverlayBridgeType
const ReactDevOverlay: PagesDevOverlayBridgeType = (props) => {
if (PagesDevOverlayBridgeImpl === undefined) {
PagesDevOverlayBridgeImpl = (
require('../../client/components/react-dev-overlay/pages/pages-dev-overlay-bridge') as typeof import('../../client/components/react-dev-overlay/pages/pages-dev-overlay-bridge')
).PagesDevOverlayBridge
}
return React.createElement(PagesDevOverlayBridgeImpl, props)
}
export interface Options extends ServerOptions {
......
......@@ -103,7 +103,7 @@ import { ReflectAdapter } from './web/spec-extension/adapters/reflect'
import { getCacheControlHeader } from './lib/cache-control'
import { getErrorSource } from '../shared/lib/error-source'
import type { DeepReadonly } from '../shared/lib/deep-readonly'
import type { PagesDevOverlayType } from '../client/components/react-dev-overlay/pages/pages-dev-overlay'
import type { PagesDevOverlayBridgeType } from '../client/components/react-dev-overlay/pages/pages-dev-overlay-bridge'
import { getScriptNonceFromHeader } from './app-render/get-script-nonce-from-header'
let tryGetPreviewData: typeof import('./api-utils/node/try-get-preview-data').tryGetPreviewData
......@@ -247,7 +247,7 @@ export type RenderOptsPartial = {
nextExport?: boolean
dev?: boolean
ampPath?: string
ErrorDebug?: PagesDevOverlayType
ErrorDebug?: PagesDevOverlayBridgeType
ampValidator?: (html: string, pathname: string) => Promise<void>
ampSkipValidation?: boolean
ampOptimizerConfig?: { [key: string]: any }
......@@ -813,15 +813,7 @@ export async function renderToHTMLImpl(
<Noop />
<AppContainer>
<>
{/* <ReactDevOverlay/> */}
{dev ? (
<>
{children}
<Noop />
</>
) : (
children
)}
{children}
{/* <RouteAnnouncer/> */}
<Noop />
</>
......
......@@ -7,7 +7,7 @@ import type { CloneableBody } from './body-streams'
import type { RouteMatch } from './route-matches/route-match'
import type { NEXT_RSC_UNION_QUERY } from '../client/components/app-router-headers'
import type { ServerComponentsHmrCache } from './response-cache'
import type { PagesDevOverlayType } from '../client/components/react-dev-overlay/pages/pages-dev-overlay'
import type { PagesDevOverlayBridgeType } from '../client/components/react-dev-overlay/pages/pages-dev-overlay-bridge'
// FIXME: (wyattjoh) this is a temporary solution to allow us to pass data between bundled modules
export const NEXT_REQUEST_META = Symbol.for('NextInternalRequestMeta')
......@@ -224,7 +224,7 @@ export interface RequestMeta {
/**
* ErrorOverlay component to use in development for pages router
*/
PagesErrorDebug?: PagesDevOverlayType
PagesErrorDebug?: PagesDevOverlayBridgeType
}
/**
......
......@@ -27,7 +27,7 @@
// 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"
// "./src/client/components/react-dev-overlay/entrypoint.d.ts"
// ],
"next/dist/shared/lib/image-loader": ["./src/shared/lib/image-loader.ts"]
}
......
......@@ -16,5 +16,5 @@
"incremental": true
},
"include": ["next-env.d.ts", "**/*.ts", "**/*.tsx"],
"exclude": ["node_modules"]
"exclude": ["node_modules", "**/*.test.ts", "**/*.test.tsx"]
}
......@@ -20,5 +20,5 @@
]
},
"include": ["next-env.d.ts", ".next/types/**/*.ts", "**/*.ts", "**/*.tsx"],
"exclude": ["node_modules"]
"exclude": ["node_modules", "**/*.test.ts", "**/*.test.tsx"]
}
......@@ -16,7 +16,7 @@
"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"
"packages/next/src/client/components/react-dev-overlay/dev-overlay.browser.tsx"
],
"ban-script-content-assignments": ["packages/next/src/client/script.tsx"],
"ban-script-src-assignments": [
......
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