Unverified Commit 026445d0 authored by Benjamin Woodruff's avatar Benjamin Woodruff Committed by GitHub

chore(HMR clients): Clean up tryApplyUpdates, reduce differences between…

chore(HMR clients): Clean up tryApplyUpdates, reduce differences between app/pages versions (#77219)

Various cleanup efforts in `tryApplyUpdates`:
- Code across pages and app are more similar.
- Inlined functions that were only called once.
- Less code overall, less branches.
- Better type signatures, less usage of `any`.
parent ace4574c
...@@ -81,23 +81,6 @@ export function waitForWebpackRuntimeHotUpdate() { ...@@ -81,23 +81,6 @@ export function waitForWebpackRuntimeHotUpdate() {
return pendingHotUpdateWebpack return pendingHotUpdateWebpack
} }
function handleSuccessfulHotUpdateWebpack(
dispatcher: Dispatcher,
sendMessage: (message: string) => void,
updatedModules: ReadonlyArray<string>
) {
resolvePendingHotUpdateWebpack()
dispatcher.onBuildOk()
reportHmrLatency(
sendMessage,
updatedModules,
webpackStartMsSinceEpoch!,
Date.now()
)
dispatcher.onRefresh()
}
// There is a newer version of the code available. // There is a newer version of the code available.
function handleAvailableHash(hash: string) { function handleAvailableHash(hash: string) {
// Update last known compilation hash. // Update last known compilation hash.
...@@ -160,10 +143,8 @@ function performFullReload(err: any, sendMessage: any) { ...@@ -160,10 +143,8 @@ 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 tryApplyUpdates( function tryApplyUpdatesWebpack(
onBeforeUpdate: (hasUpdates: boolean) => void, sendMessage: (message: string) => void,
onHotUpdateSuccess: (updatedModules: string[]) => void,
sendMessage: any,
dispatcher: Dispatcher dispatcher: Dispatcher
) { ) {
if (!isUpdateAvailable() || !canApplyUpdates()) { if (!isUpdateAvailable() || !canApplyUpdates()) {
...@@ -173,8 +154,11 @@ function tryApplyUpdates( ...@@ -173,8 +154,11 @@ function tryApplyUpdates(
return return
} }
function handleApplyUpdates(err: any, updatedModules: string[] | null) { function handleApplyUpdates(
if (err || RuntimeErrorHandler.hadRuntimeError || !updatedModules) { err: any,
updatedModules: (string | number)[] | null
) {
if (err || RuntimeErrorHandler.hadRuntimeError || updatedModules == null) {
if (err) { if (err) {
console.warn(REACT_REFRESH_FULL_RELOAD) console.warn(REACT_REFRESH_FULL_RELOAD)
} else if (RuntimeErrorHandler.hadRuntimeError) { } else if (RuntimeErrorHandler.hadRuntimeError) {
...@@ -184,50 +168,50 @@ function tryApplyUpdates( ...@@ -184,50 +168,50 @@ function tryApplyUpdates(
return return
} }
const hasUpdates = Boolean(updatedModules.length) dispatcher.onBuildOk()
if (typeof onHotUpdateSuccess === 'function') {
// Maybe we want to do something.
onHotUpdateSuccess(updatedModules)
}
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.
tryApplyUpdates( tryApplyUpdatesWebpack(sendMessage, dispatcher)
hasUpdates ? () => {} : onBeforeUpdate, return
hasUpdates ? () => dispatcher.onBuildOk() : onHotUpdateSuccess, }
sendMessage,
dispatcher dispatcher.onRefresh()
) resolvePendingHotUpdateWebpack()
} else { reportHmrLatency(
dispatcher.onBuildOk() sendMessage,
if (process.env.__NEXT_TEST_MODE) { updatedModules,
afterApplyUpdates(() => { webpackStartMsSinceEpoch!,
if (self.__NEXT_HMR_CB) { Date.now()
self.__NEXT_HMR_CB() )
self.__NEXT_HMR_CB = null
} if (process.env.__NEXT_TEST_MODE) {
}) afterApplyUpdates(() => {
} if (self.__NEXT_HMR_CB) {
self.__NEXT_HMR_CB()
self.__NEXT_HMR_CB = null
}
})
} }
} }
// https://webpack.js.org/api/hot-module-replacement/#check // https://webpack.js.org/api/hot-module-replacement/#check
module.hot module.hot
.check(/* autoApply */ false) .check(/* autoApply */ false)
.then((updatedModules: any[] | null) => { .then((updatedModules: (string | number)[] | null) => {
if (!updatedModules) { if (updatedModules == null) {
return null return null
} }
if (typeof onBeforeUpdate === 'function') { // We should always handle an update, even if updatedModules is empty (but
const hasUpdates = Boolean(updatedModules.length) // non-null) for any reason. That's what webpack would normally do:
onBeforeUpdate(hasUpdates) // https://github.com/webpack/webpack/blob/3aa6b6bc3a64/lib/hmr/HotModuleReplacement.runtime.js#L296-L298
} dispatcher.onBeforeRefresh()
// https://webpack.js.org/api/hot-module-replacement/#apply // https://webpack.js.org/api/hot-module-replacement/#apply
return module.hot.apply() return module.hot.apply()
}) })
.then( .then(
(updatedModules: any[] | null) => { (updatedModules: (string | number)[] | null) => {
handleApplyUpdates(null, updatedModules) handleApplyUpdates(null, updatedModules)
}, },
(err: any) => { (err: any) => {
...@@ -236,7 +220,7 @@ function tryApplyUpdates( ...@@ -236,7 +220,7 @@ function tryApplyUpdates(
) )
} }
/** Handles messages from the sevrer for the App Router. */ /** Handles messages from the server for the App Router. */
function processMessage( function processMessage(
obj: HMR_ACTION_TYPES, obj: HMR_ACTION_TYPES,
sendMessage: (message: string) => void, sendMessage: (message: string) => void,
...@@ -288,24 +272,7 @@ function processMessage( ...@@ -288,24 +272,7 @@ function processMessage(
} }
dispatcher.onBuildOk() dispatcher.onBuildOk()
} else { } else {
tryApplyUpdates( tryApplyUpdatesWebpack(sendMessage, dispatcher)
function onBeforeHotUpdate(hasUpdates: boolean) {
if (hasUpdates) {
dispatcher.onBeforeRefresh()
}
},
function onSuccessfulHotUpdate(webpackUpdatedModules: string[]) {
// Only dismiss it when we're sure it's a hot update.
// Otherwise it would flicker right before the reload.
handleSuccessfulHotUpdateWebpack(
dispatcher,
sendMessage,
webpackUpdatedModules
)
},
sendMessage,
dispatcher
)
} }
} }
......
...@@ -24,6 +24,8 @@ ...@@ -24,6 +24,8 @@
* SOFTWARE. * SOFTWARE.
*/ */
/// <reference types="webpack/module.d.ts" />
// This file is a modified version of the Create React App HMR dev client that // This file is a modified version of the Create React App HMR dev client that
// can be found here: // can be found here:
// https://github.com/facebook/create-react-app/blob/v3.4.1/packages/react-dev-utils/webpackHotDevClient.js // https://github.com/facebook/create-react-app/blob/v3.4.1/packages/react-dev-utils/webpackHotDevClient.js
...@@ -55,10 +57,8 @@ import { ...@@ -55,10 +57,8 @@ import {
} from '../shared' } from '../shared'
import { RuntimeErrorHandler } from '../../errors/runtime-error-handler' import { RuntimeErrorHandler } from '../../errors/runtime-error-handler'
import reportHmrLatency from '../utils/report-hmr-latency' import reportHmrLatency from '../utils/report-hmr-latency'
import { import { TurbopackHmr } from '../utils/turbopack-hot-reloader-common'
extractModulesFromTurbopackMessage,
TurbopackHmr,
} from '../utils/turbopack-hot-reloader-common'
// This alternative WebpackDevServer combines the functionality of: // 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-dev-server/blob/webpack-1/client/index.js
// https://github.com/webpack/webpack/blob/webpack-1/hot/dev-server.js // https://github.com/webpack/webpack/blob/webpack-1/hot/dev-server.js
...@@ -149,7 +149,7 @@ function handleSuccess() { ...@@ -149,7 +149,7 @@ function handleSuccess() {
// Attempt to apply hot updates or reload. // Attempt to apply hot updates or reload.
if (isHotUpdate) { if (isHotUpdate) {
tryApplyUpdates(onBeforeFastRefresh, onFastRefresh) tryApplyUpdatesWebpack()
} }
} }
...@@ -189,7 +189,7 @@ function handleWarnings(warnings: any) { ...@@ -189,7 +189,7 @@ function handleWarnings(warnings: any) {
// Attempt to apply hot updates or reload. // Attempt to apply hot updates or reload.
if (isHotUpdate) { if (isHotUpdate) {
tryApplyUpdates(onBeforeFastRefresh, onFastRefresh) tryApplyUpdatesWebpack()
} }
} }
...@@ -233,30 +233,6 @@ const turbopackHmr: TurbopackHmr | null = process.env.TURBOPACK ...@@ -233,30 +233,6 @@ const turbopackHmr: TurbopackHmr | null = process.env.TURBOPACK
: null : null
let isrManifest: Record<string, boolean> = {} let isrManifest: Record<string, boolean> = {}
function onBeforeFastRefresh(updatedModules: string[]) {
if (updatedModules.length > 0) {
// Only trigger a pending state if we have updates to apply
// (cf. onFastRefresh)
onBeforeRefresh()
}
}
function onFastRefresh(updatedModules: ReadonlyArray<string> = []) {
onBuildOk()
if (updatedModules.length === 0) {
return
}
onRefresh()
reportHmrLatency(
sendMessage,
updatedModules,
webpackStartMsSinceEpoch!,
Date.now()
)
}
// There is a newer version of the code available. // There is a newer version of the code available.
function handleAvailableHash(hash: string) { function handleAvailableHash(hash: string) {
// Update last known compilation hash. // Update last known compilation hash.
...@@ -282,7 +258,7 @@ export function handleStaticIndicator() { ...@@ -282,7 +258,7 @@ export function handleStaticIndicator() {
} }
} }
/** Handles messages from the sevrer for the Pages Router. */ /** Handles messages from the server for the Pages Router. */
function processMessage(obj: HMR_ACTION_TYPES) { function processMessage(obj: HMR_ACTION_TYPES) {
if (!('action' in obj)) { if (!('action' in obj)) {
return return
...@@ -325,6 +301,7 @@ function processMessage(obj: HMR_ACTION_TYPES) { ...@@ -325,6 +301,7 @@ function processMessage(obj: HMR_ACTION_TYPES) {
return handleErrors(errors) return handleErrors(errors)
} }
// NOTE: Turbopack does not currently send warnings
const hasWarnings = Boolean(warnings && warnings.length) const hasWarnings = Boolean(warnings && warnings.length)
if (hasWarnings) { if (hasWarnings) {
sendMessage( sendMessage(
...@@ -371,8 +348,7 @@ function processMessage(obj: HMR_ACTION_TYPES) { ...@@ -371,8 +348,7 @@ function processMessage(obj: HMR_ACTION_TYPES) {
break break
} }
case HMR_ACTIONS_SENT_TO_BROWSER.TURBOPACK_MESSAGE: { case HMR_ACTIONS_SENT_TO_BROWSER.TURBOPACK_MESSAGE: {
const updatedModules = extractModulesFromTurbopackMessage(obj.data) onBeforeRefresh()
onBeforeFastRefresh([...updatedModules])
for (const listener of turbopackMessageListeners) { for (const listener of turbopackMessageListeners) {
listener({ listener({
type: HMR_ACTIONS_SENT_TO_BROWSER.TURBOPACK_MESSAGE, type: HMR_ACTIONS_SENT_TO_BROWSER.TURBOPACK_MESSAGE,
...@@ -424,10 +400,7 @@ function afterApplyUpdates(fn: () => void) { ...@@ -424,10 +400,7 @@ function afterApplyUpdates(fn: () => void) {
} }
// 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 tryApplyUpdates( function tryApplyUpdatesWebpack() {
onBeforeHotUpdate: ((updatedModules: string[]) => unknown) | undefined,
onHotUpdateSuccess: (updatedModules: string[]) => unknown
) {
if (!module.hot) { if (!module.hot) {
// HotModuleReplacementPlugin is not in Webpack configuration. // HotModuleReplacementPlugin is not in Webpack configuration.
console.error('HotModuleReplacementPlugin is not in Webpack configuration.') console.error('HotModuleReplacementPlugin is not in Webpack configuration.')
...@@ -440,8 +413,11 @@ function tryApplyUpdates( ...@@ -440,8 +413,11 @@ function tryApplyUpdates(
return return
} }
function handleApplyUpdates(err: any, updatedModules: string[] | null) { function handleApplyUpdates(
if (err || RuntimeErrorHandler.hadRuntimeError || !updatedModules) { err: any,
updatedModules: (string | number)[] | null
) {
if (err || RuntimeErrorHandler.hadRuntimeError || updatedModules == null) {
if (err) { if (err) {
console.warn(REACT_REFRESH_FULL_RELOAD) console.warn(REACT_REFRESH_FULL_RELOAD)
} else if (RuntimeErrorHandler.hadRuntimeError) { } else if (RuntimeErrorHandler.hadRuntimeError) {
...@@ -451,46 +427,49 @@ function tryApplyUpdates( ...@@ -451,46 +427,49 @@ function tryApplyUpdates(
return return
} }
if (typeof onHotUpdateSuccess === 'function') { onBuildOk()
// Maybe we want to do something.
onHotUpdateSuccess(updatedModules)
}
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.
// However, this time, don't trigger a pending refresh state. tryApplyUpdatesWebpack()
tryApplyUpdates( return
updatedModules.length > 0 ? undefined : onBeforeHotUpdate, }
updatedModules.length > 0 ? onBuildOk : onHotUpdateSuccess
) onRefresh()
} else { reportHmrLatency(
onBuildOk() sendMessage,
if (process.env.__NEXT_TEST_MODE) { updatedModules,
afterApplyUpdates(() => { webpackStartMsSinceEpoch!,
if (self.__NEXT_HMR_CB) { Date.now()
self.__NEXT_HMR_CB() )
self.__NEXT_HMR_CB = null
} if (process.env.__NEXT_TEST_MODE) {
}) afterApplyUpdates(() => {
} if (self.__NEXT_HMR_CB) {
self.__NEXT_HMR_CB()
self.__NEXT_HMR_CB = null
}
})
} }
} }
// https://webpack.js.org/api/hot-module-replacement/#check // https://webpack.js.org/api/hot-module-replacement/#check
module.hot module.hot
.check(/* autoApply */ false) .check(/* autoApply */ false)
.then((updatedModules: any) => { .then((updatedModules: (string | number)[] | null) => {
if (!updatedModules) { if (updatedModules == null) {
return null return null
} }
if (typeof onBeforeHotUpdate === 'function') { // We should always handle an update, even if updatedModules is empty (but
onBeforeHotUpdate(updatedModules) // non-null) for any reason. That's what webpack would normally do:
} // https://github.com/webpack/webpack/blob/3aa6b6bc3a64/lib/hmr/HotModuleReplacement.runtime.js#L296-L298
onBeforeRefresh()
// https://webpack.js.org/api/hot-module-replacement/#apply
return module.hot.apply() return module.hot.apply()
}) })
.then( .then(
(updatedModules: any) => { (updatedModules: (string | number)[] | null) => {
handleApplyUpdates(null, updatedModules) handleApplyUpdates(null, updatedModules)
}, },
(err: any) => { (err: any) => {
......
...@@ -6,7 +6,7 @@ declare global { ...@@ -6,7 +6,7 @@ declare global {
export default function reportHmrLatency( export default function reportHmrLatency(
sendMessage: (message: string) => void, sendMessage: (message: string) => void,
updatedModules: ReadonlyArray<string>, updatedModules: ReadonlyArray<string | number>,
startMsSinceEpoch: number, startMsSinceEpoch: number,
endMsSinceEpoch: number endMsSinceEpoch: number
) { ) {
......
...@@ -48,7 +48,7 @@ export class TurbopackHmr { ...@@ -48,7 +48,7 @@ export class TurbopackHmr {
} }
} }
export function extractModulesFromTurbopackMessage( function extractModulesFromTurbopackMessage(
data: TurbopackUpdate | TurbopackUpdate[] data: TurbopackUpdate | TurbopackUpdate[]
): Set<string> { ): Set<string> {
const updatedModules: Set<string> = new Set() const updatedModules: Set<string> = new Set()
......
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