Unverified Commit c37a39bf authored by Benjamin Woodruff's avatar Benjamin Woodruff Committed by GitHub

chore(HMR clients): Clean up and share code between app and pages router (#76960)

# Do not review this PR in Graphite, review it one commit at a time: https://github.com/vercel/next.js/pull/76960/commits

This is a series of very small changes to the hot reloader clients in both app and pages router to share more code and unify some of the logic or behavior between the two.

This code is very fragile, so lots of small commits have been useful in bisecting test failures.

These changes are too small to be practical as separate stacked graphite PRs.
parent 8bc202ba
......@@ -21,6 +21,8 @@ import {
ACTION_UNHANDLED_ERROR,
ACTION_UNHANDLED_REJECTION,
ACTION_VERSION_INFO,
REACT_REFRESH_FULL_RELOAD,
reportInvalidHmrMessage,
useErrorOverlayReducer,
} from '../shared'
import { parseStack } from '../utils/parse-stack'
......@@ -50,6 +52,7 @@ import { shouldRenderRootLevelErrorOverlay } from '../../../lib/is-error-thrown-
import { handleDevBuildIndicatorHmrEvents } from '../../../dev/dev-build-indicator/internal/handle-dev-build-indicator-hmr-events'
import type { GlobalErrorComponent } from '../../error-boundary'
import type { DevIndicatorServerState } from '../../../../server/dev/dev-indicator-server-state'
import reportHmrLatency from '../utils/report-hmr-latency'
export interface Dispatcher {
onBuildOk(): void
......@@ -83,15 +86,6 @@ export function waitForWebpackRuntimeHotUpdate() {
return pendingHotUpdateWebpack
}
function handleBeforeHotUpdateWebpack(
dispatcher: Dispatcher,
hasUpdates: boolean
) {
if (hasUpdates) {
dispatcher.onBeforeRefresh()
}
}
function handleSuccessfulHotUpdateWebpack(
dispatcher: Dispatcher,
sendMessage: (message: string) => void,
......@@ -99,36 +93,11 @@ function handleSuccessfulHotUpdateWebpack(
) {
resolvePendingHotUpdateWebpack()
dispatcher.onBuildOk()
reportHmrLatency(sendMessage, updatedModules)
reportHmrLatency(sendMessage, updatedModules, startLatency!, Date.now())
dispatcher.onRefresh()
}
function reportHmrLatency(
sendMessage: (message: string) => void,
updatedModules: ReadonlyArray<string>
) {
if (!startLatency) return
// turbopack has a debounce for the "built" event which we don't want to
// incorrectly show in this number, use the last TURBOPACK_MESSAGE time
let endLatency = turbopackLastUpdateLatency ?? Date.now()
const latency = endLatency - startLatency
console.log(`[Fast Refresh] done in ${latency}ms`)
sendMessage(
JSON.stringify({
event: 'client-hmr-latency',
id: window.__nextDevClientId,
startTime: startLatency,
endTime: endLatency,
page: window.location.pathname,
updatedModules,
// Whether the page (tab) was hidden at the time the event occurred.
// This can impact the accuracy of the event's timing.
isPageHidden: document.visibilityState === 'hidden',
})
)
}
// There is a newer version of the code available.
function handleAvailableHash(hash: string) {
// Update last known compilation hash.
......@@ -203,21 +172,14 @@ function tryApplyUpdates(
if (!isUpdateAvailable() || !canApplyUpdates()) {
resolvePendingHotUpdateWebpack()
dispatcher.onBuildOk()
reportHmrLatency(sendMessage, [])
reportHmrLatency(sendMessage, [], startLatency!, Date.now())
return
}
function handleApplyUpdates(err: any, updatedModules: string[] | null) {
if (err || RuntimeErrorHandler.hadRuntimeError || !updatedModules) {
if (err) {
console.warn(
'[Fast Refresh] performing full reload\n\n' +
"Fast Refresh will perform a full reload when you edit a file that's imported by modules outside of the React rendering tree.\n" +
'You might have a file which exports a React component but also exports a value that is imported by a non-React component file.\n' +
'Consider migrating the non-React component export to a separate file and importing it into both files.\n\n' +
'It is also possible the parent component of the component you edited is a class component, which disables Fast Refresh.\n' +
'Fast Refresh requires at least one parent function component in your React tree.'
)
console.warn(REACT_REFRESH_FULL_RELOAD)
} else if (RuntimeErrorHandler.hadRuntimeError) {
console.warn(REACT_REFRESH_FULL_RELOAD_FROM_ERROR)
}
......@@ -321,11 +283,18 @@ function processMessage(
function handleHotUpdate() {
if (process.env.TURBOPACK) {
dispatcher.onBuildOk()
reportHmrLatency(sendMessage, [...turbopackUpdatedModules])
reportHmrLatency(
sendMessage,
[...turbopackUpdatedModules],
startLatency!,
turbopackLastUpdateLatency ?? Date.now()
)
} else {
tryApplyUpdates(
function onBeforeHotUpdate(hasUpdates: boolean) {
handleBeforeHotUpdateWebpack(dispatcher, hasUpdates)
if (hasUpdates) {
dispatcher.onBeforeRefresh()
}
},
function onSuccessfulHotUpdate(webpackUpdatedModules: string[]) {
// Only dismiss it when we're sure it's a hot update.
......@@ -437,7 +406,6 @@ function processMessage(
)
if (obj.action === HMR_ACTIONS_SENT_TO_BROWSER.BUILT) {
// Handle hot updates
handleHotUpdate()
}
return
......@@ -691,13 +659,8 @@ export default function HotReload({
appIsrManifestRef,
pathnameRef
)
} catch (err: any) {
console.warn(
'[HMR] Invalid message: ' +
JSON.stringify(event.data) +
'\n' +
(err?.stack ?? '')
)
} catch (err: unknown) {
reportInvalidHmrMessage(event, err)
}
}
......
......@@ -47,8 +47,13 @@ import type {
TurbopackMsgToBrowser,
} from '../../../../server/dev/hot-reloader-types'
import { extractModulesFromTurbopackMessage } from '../../../../server/dev/extract-modules-from-turbopack-message'
import { REACT_REFRESH_FULL_RELOAD_FROM_ERROR } from '../shared'
import {
REACT_REFRESH_FULL_RELOAD,
REACT_REFRESH_FULL_RELOAD_FROM_ERROR,
reportInvalidHmrMessage,
} from '../shared'
import { RuntimeErrorHandler } from '../../errors/runtime-error-handler'
import reportHmrLatency from '../utils/report-hmr-latency'
// This alternative WebpackDevServer combines the functionality of:
// https://github.com/webpack/webpack-dev-server/blob/webpack-1/client/index.js
// https://github.com/webpack/webpack/blob/webpack-1/hot/dev-server.js
......@@ -62,7 +67,6 @@ declare global {
const __webpack_hash__: string
interface Window {
__nextDevClientId: number
__NEXT_HMR_LATENCY_CB: any
}
}
......@@ -70,9 +74,7 @@ window.__nextDevClientId = Math.round(Math.random() * 100 + Date.now())
let customHmrEventHandler: any
let turbopackMessageListeners: ((msg: TurbopackMsgToBrowser) => void)[] = []
let MODE: 'webpack' | 'turbopack' = 'webpack'
export default function connect(mode: 'webpack' | 'turbopack') {
MODE = mode
export default function connect() {
register()
addMessageListener((payload) => {
......@@ -82,13 +84,8 @@ export default function connect(mode: 'webpack' | 'turbopack') {
try {
processMessage(payload)
} catch (err: any) {
console.warn(
'[HMR] Invalid message: ' +
JSON.stringify(payload) +
'\n' +
(err?.stack ?? '')
)
} catch (err: unknown) {
reportInvalidHmrMessage(payload, err)
}
})
......@@ -129,7 +126,15 @@ function clearOutdatedErrors() {
function handleSuccess() {
clearOutdatedErrors()
if (MODE === 'webpack') {
if (process.env.TURBOPACK) {
reportHmrLatency(
sendMessage,
[...turbopackUpdatedModules],
startLatency!,
turbopackLastUpdateLatency ?? Date.now()
)
onBuildOk()
} else {
const isHotUpdate =
!isFirstCompilation ||
(window.__NEXT_DATA__.page !== '/_error' && isUpdateAvailable())
......@@ -140,9 +145,6 @@ function handleSuccess() {
if (isHotUpdate) {
tryApplyUpdates(onBeforeFastRefresh, onFastRefresh)
}
} else {
reportHmrLatency([...turbopackUpdatedModules])
onBuildOk()
}
}
......@@ -238,32 +240,12 @@ function onFastRefresh(updatedModules: ReadonlyArray<string> = []) {
onRefresh()
reportHmrLatency()
}
function reportHmrLatency(updatedModules: ReadonlyArray<string> = []) {
if (!startLatency) return
// turbopack has a debounce for the BUILT event which we don't want to
// incorrectly show in this number, use the last TURBOPACK_MESSAGE time
let endLatency = turbopackLastUpdateLatency ?? Date.now()
const latency = endLatency - startLatency
console.log(`[Fast Refresh] done in ${latency}ms`)
sendMessage(
JSON.stringify({
event: 'client-hmr-latency',
id: window.__nextDevClientId,
startTime: startLatency,
endTime: endLatency,
page: window.location.pathname,
updatedModules,
// Whether the page (tab) was hidden at the time the event occurred.
// This can impact the accuracy of the event's timing.
isPageHidden: document.visibilityState === 'hidden',
})
reportHmrLatency(
sendMessage,
updatedModules,
startLatency!,
turbopackLastUpdateLatency ?? Date.now()
)
if (self.__NEXT_HMR_LATENCY_CB) {
self.__NEXT_HMR_LATENCY_CB(latency)
}
}
// There is a newer version of the code available.
......@@ -278,7 +260,7 @@ export function handleStaticIndicator() {
const pageComponent = routeInfo?.Component
const appComponent = window.next.router.components['/_app']?.Component
const isDynamicPage =
Boolean(pageComponent?.getInitialProps) || Boolean(routeInfo.__N_SSP)
Boolean(pageComponent?.getInitialProps) || Boolean(routeInfo?.__N_SSP)
const hasAppGetInitialProps =
Boolean(appComponent?.getInitialProps) &&
appComponent?.getInitialProps !== appComponent?.origGetInitialProps
......@@ -297,7 +279,6 @@ function processMessage(obj: HMR_ACTION_TYPES) {
return
}
// Use turbopack message for analytics, (still need built for webpack)
switch (obj.action) {
case HMR_ACTIONS_SENT_TO_BROWSER.ISR_MANIFEST: {
isrManifest = obj.data
......@@ -458,18 +439,9 @@ function tryApplyUpdates(
function handleApplyUpdates(err: any, updatedModules: string[] | null) {
if (err || RuntimeErrorHandler.hadRuntimeError || !updatedModules) {
if (err) {
console.warn(
'[Fast Refresh] performing full reload\n\n' +
"Fast Refresh will perform a full reload when you edit a file that's imported by modules outside of the React rendering tree.\n" +
'You might have a file which exports a React component but also exports a value that is imported by a non-React component file.\n' +
'Consider migrating the non-React component export to a separate file and importing it into both files.\n\n' +
'It is also possible the parent component of the component you edited is a class component, which disables Fast Refresh.\n' +
'Fast Refresh requires at least one parent function component in your React tree.'
)
console.warn(REACT_REFRESH_FULL_RELOAD)
} else if (RuntimeErrorHandler.hadRuntimeError) {
console.warn(
'[Fast Refresh] performing full reload because your application had an unrecoverable error'
)
console.warn(REACT_REFRESH_FULL_RELOAD_FROM_ERROR)
}
performFullReload(err)
return
......
......@@ -6,6 +6,7 @@ import type { SupportedErrorEvent } from './ui/container/runtime-error/render-er
import type { ComponentStackFrame } from './utils/parse-component-stack'
import type { DebugInfo } from './types'
import type { DevIndicatorServerState } from '../../../server/dev/dev-indicator-server-state'
import type { HMR_ACTION_TYPES } from '../../../server/dev/hot-reloader-types'
type FastRefreshState =
/** No refresh in progress. */
......@@ -224,5 +225,25 @@ export function useErrorOverlayReducer(routerType: 'pages' | 'app') {
}, getInitialState(routerType))
}
export const REACT_REFRESH_FULL_RELOAD =
'[Fast Refresh] performing full reload\n\n' +
"Fast Refresh will perform a full reload when you edit a file that's imported by modules outside of the React rendering tree.\n" +
'You might have a file which exports a React component but also exports a value that is imported by a non-React component file.\n' +
'Consider migrating the non-React component export to a separate file and importing it into both files.\n\n' +
'It is also possible the parent component of the component you edited is a class component, which disables Fast Refresh.\n' +
'Fast Refresh requires at least one parent function component in your React tree.'
export const REACT_REFRESH_FULL_RELOAD_FROM_ERROR =
'[Fast Refresh] performing full reload because your application had an unrecoverable error'
export function reportInvalidHmrMessage(
message: HMR_ACTION_TYPES | MessageEvent<unknown>,
err: unknown
) {
console.warn(
'[HMR] Invalid message: ' +
JSON.stringify(message) +
'\n' +
((err instanceof Error && err?.stack) || '')
)
}
declare global {
interface Window {
__NEXT_HMR_LATENCY_CB: ((latencyMs: number) => void) | undefined
}
}
export default function reportHmrLatency(
sendMessage: (message: string) => void,
updatedModules: ReadonlyArray<string>,
startMsSinceEpoch: number,
endMsSinceEpoch: number
) {
const latencyMs = endMsSinceEpoch - startMsSinceEpoch
console.log(`[Fast Refresh] done in ${latencyMs}ms`)
sendMessage(
JSON.stringify({
event: 'client-hmr-latency',
id: window.__nextDevClientId,
startTime: startMsSinceEpoch,
endTime: endMsSinceEpoch,
page: window.location.pathname,
updatedModules,
// Whether the page (tab) was hidden at the time the event occurred.
// This can impact the accuracy of the event's timing.
isPageHidden: document.visibilityState === 'hidden',
})
)
if (self.__NEXT_HMR_LATENCY_CB) {
self.__NEXT_HMR_LATENCY_CB(latencyMs)
}
}
......@@ -6,6 +6,7 @@ import {
connectHMR,
} from '../components/react-dev-overlay/pages/websocket'
import { HMR_ACTIONS_SENT_TO_BROWSER } from '../../server/dev/hot-reloader-types'
import { reportInvalidHmrMessage } from '../components/react-dev-overlay/shared'
declare global {
const __webpack_runtime_id__: string
......@@ -106,13 +107,8 @@ addMessageListener((message) => {
} else if (message.action === HMR_ACTIONS_SENT_TO_BROWSER.RELOAD_PAGE) {
window.location.reload()
}
} catch (err: any) {
console.warn(
'[HMR] Invalid message: ' +
JSON.stringify(message) +
'\n' +
(err?.stack ?? '')
)
} catch (err: unknown) {
reportInvalidHmrMessage(message, err)
}
})
......
......@@ -20,8 +20,8 @@ declare const window: NextWindow
let reloading = false
export default (mode: 'webpack' | 'turbopack') => {
const devClient = connect(mode)
export default () => {
const devClient = connect()
devClient.subscribeToHmrEvent((obj: any) => {
if (reloading) return
......
......@@ -21,7 +21,7 @@ window.next = {
// for the page loader
declare let __turbopack_load__: any
const devClient = initHMR('turbopack')
const devClient = initHMR()
initialize({
devClient,
})
......
......@@ -13,7 +13,7 @@ window.next = {
emitter,
}
const devClient = initHMR('webpack')
const devClient = initHMR()
initialize({ devClient })
.then(({ assetPrefix }) => {
return pageBootstrap(assetPrefix)
......
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