Unverified Commit 64665380 authored by Leah's avatar Leah Committed by GitHub

allow turbopack HMR to recover from react errors without hard refresh (#47771)

parent be2237fc
...@@ -8,97 +8,95 @@ import type { ...@@ -8,97 +8,95 @@ import type {
Issue, Issue,
ResourceIdentifier, ResourceIdentifier,
ServerMessage, ServerMessage,
} from "@vercel/turbopack-dev-runtime/types/protocol"; } from '@vercel/turbopack-dev-runtime/types/protocol'
import type { import type {
ChunkPath, ChunkPath,
ModuleId, ModuleId,
UpdateCallback, UpdateCallback,
TurbopackGlobals, TurbopackGlobals,
} from "@vercel/turbopack-dev-runtime/types"; } from '@vercel/turbopack-dev-runtime/types'
import stripAnsi from "@vercel/turbopack-next/compiled/strip-ansi";
import { import {
onBeforeRefresh, onBeforeRefresh,
onBuildOk, onBuildOk,
onRefresh, onRefresh,
onTurbopackIssues, onTurbopackIssues,
} from "../overlay/client"; } from '../overlay/client'
import { addEventListener, sendMessage } from "./websocket"; import { addEventListener, sendMessage } from './websocket'
declare var globalThis: TurbopackGlobals; declare var globalThis: TurbopackGlobals
export type ClientOptions = { export type ClientOptions = {
assetPrefix: string; assetPrefix: string
}; }
export function connect({ assetPrefix }: ClientOptions) { export function connect({ assetPrefix }: ClientOptions) {
addEventListener((event) => { addEventListener((event) => {
switch (event.type) { switch (event.type) {
case "connected": case 'connected':
handleSocketConnected(); handleSocketConnected()
break; break
case "message": case 'message':
const msg: ServerMessage = JSON.parse(event.message.data); const msg: ServerMessage = JSON.parse(event.message.data)
handleSocketMessage(msg); handleSocketMessage(msg)
break; break
} }
}); })
const queued = globalThis.TURBOPACK_CHUNK_UPDATE_LISTENERS; const queued = globalThis.TURBOPACK_CHUNK_UPDATE_LISTENERS
if (queued != null && !Array.isArray(queued)) { if (queued != null && !Array.isArray(queued)) {
throw new Error("A separate HMR handler was already registered"); throw new Error('A separate HMR handler was already registered')
} }
globalThis.TURBOPACK_CHUNK_UPDATE_LISTENERS = { globalThis.TURBOPACK_CHUNK_UPDATE_LISTENERS = {
push: ([chunkPath, callback]: [ChunkPath, UpdateCallback]) => { push: ([chunkPath, callback]: [ChunkPath, UpdateCallback]) => {
subscribeToChunkUpdate(chunkPath, callback); subscribeToChunkUpdate(chunkPath, callback)
}, },
}; }
if (Array.isArray(queued)) { if (Array.isArray(queued)) {
for (const [chunkPath, callback] of queued) { for (const [chunkPath, callback] of queued) {
subscribeToChunkUpdate(chunkPath, callback); subscribeToChunkUpdate(chunkPath, callback)
} }
} }
} }
type UpdateCallbackSet = { type UpdateCallbackSet = {
callbacks: Set<UpdateCallback>; callbacks: Set<UpdateCallback>
unsubscribe: () => void; unsubscribe: () => void
}; }
const updateCallbackSets: Map<ResourceKey, UpdateCallbackSet> = new Map(); const updateCallbackSets: Map<ResourceKey, UpdateCallbackSet> = new Map()
function sendJSON(message: ClientMessage) { function sendJSON(message: ClientMessage) {
sendMessage(JSON.stringify(message)); sendMessage(JSON.stringify(message))
} }
type ResourceKey = string; type ResourceKey = string
function resourceKey(resource: ResourceIdentifier): ResourceKey { function resourceKey(resource: ResourceIdentifier): ResourceKey {
return JSON.stringify({ return JSON.stringify({
path: resource.path, path: resource.path,
headers: resource.headers || null, headers: resource.headers || null,
}); })
} }
function subscribeToUpdates(resource: ResourceIdentifier): () => void { function subscribeToUpdates(resource: ResourceIdentifier): () => void {
sendJSON({ sendJSON({
type: "subscribe", type: 'subscribe',
...resource, ...resource,
}); })
return () => { return () => {
sendJSON({ sendJSON({
type: "unsubscribe", type: 'unsubscribe',
...resource, ...resource,
}); })
}; }
} }
function handleSocketConnected() { function handleSocketConnected() {
for (const key of updateCallbackSets.keys()) { for (const key of updateCallbackSets.keys()) {
subscribeToUpdates(JSON.parse(key)); subscribeToUpdates(JSON.parse(key))
} }
} }
...@@ -106,136 +104,136 @@ function handleSocketConnected() { ...@@ -106,136 +104,136 @@ function handleSocketConnected() {
const chunkListsWithPendingUpdates: Map< const chunkListsWithPendingUpdates: Map<
ResourceKey, ResourceKey,
{ update: ChunkListUpdate; resource: ResourceIdentifier } { update: ChunkListUpdate; resource: ResourceIdentifier }
> = new Map(); > = new Map()
function aggregateUpdates( function aggregateUpdates(
msg: ServerMessage, msg: ServerMessage,
aggregate: boolean aggregate: boolean
): ServerMessage { ): ServerMessage {
const key = resourceKey(msg.resource); const key = resourceKey(msg.resource)
let aggregated = chunkListsWithPendingUpdates.get(key); let aggregated = chunkListsWithPendingUpdates.get(key)
if (msg.type === "issues" && aggregated != null) { if (msg.type === 'issues' && aggregated != null) {
if (!aggregate) { if (!aggregate) {
chunkListsWithPendingUpdates.delete(key); chunkListsWithPendingUpdates.delete(key)
} }
return { return {
...msg, ...msg,
type: "partial", type: 'partial',
instruction: aggregated.update, instruction: aggregated.update,
}; }
} }
if (msg.type !== "partial") return msg; if (msg.type !== 'partial') return msg
if (aggregated == null) { if (aggregated == null) {
if (aggregate) { if (aggregate) {
chunkListsWithPendingUpdates.set(key, { chunkListsWithPendingUpdates.set(key, {
resource: msg.resource, resource: msg.resource,
update: msg.instruction, update: msg.instruction,
}); })
} }
return msg; return msg
} }
aggregated = { aggregated = {
resource: msg.resource, resource: msg.resource,
update: mergeChunkListUpdates(aggregated.update, msg.instruction), update: mergeChunkListUpdates(aggregated.update, msg.instruction),
}; }
if (aggregate) { if (aggregate) {
chunkListsWithPendingUpdates.set(key, aggregated); chunkListsWithPendingUpdates.set(key, aggregated)
} else { } else {
// Once we receive a partial update with no critical issues, we can stop aggregating updates. // Once we receive a partial update with no critical issues, we can stop aggregating updates.
// The aggregated update will be applied. // The aggregated update will be applied.
chunkListsWithPendingUpdates.delete(key); chunkListsWithPendingUpdates.delete(key)
} }
return { return {
...msg, ...msg,
instruction: aggregated.update, instruction: aggregated.update,
}; }
} }
function mergeChunkListUpdates( function mergeChunkListUpdates(
updateA: ChunkListUpdate, updateA: ChunkListUpdate,
updateB: ChunkListUpdate updateB: ChunkListUpdate
): ChunkListUpdate { ): ChunkListUpdate {
let chunks; let chunks
if (updateA.chunks != null) { if (updateA.chunks != null) {
if (updateB.chunks == null) { if (updateB.chunks == null) {
chunks = updateA.chunks; chunks = updateA.chunks
} else { } else {
chunks = mergeChunkListChunks(updateA.chunks, updateB.chunks); chunks = mergeChunkListChunks(updateA.chunks, updateB.chunks)
} }
} else if (updateB.chunks != null) { } else if (updateB.chunks != null) {
chunks = updateB.chunks; chunks = updateB.chunks
} }
let merged; let merged
if (updateA.merged != null) { if (updateA.merged != null) {
if (updateB.merged == null) { if (updateB.merged == null) {
merged = updateA.merged; merged = updateA.merged
} else { } else {
// Since `merged` is an array of updates, we need to merge them all into // Since `merged` is an array of updates, we need to merge them all into
// one, consistent update. // one, consistent update.
// Since there can only be `EcmascriptMergeUpdates` in the array, there is // Since there can only be `EcmascriptMergeUpdates` in the array, there is
// no need to key on the `type` field. // no need to key on the `type` field.
let update = updateA.merged[0]; let update = updateA.merged[0]
for (let i = 1; i < updateA.merged.length; i++) { for (let i = 1; i < updateA.merged.length; i++) {
update = mergeChunkListEcmascriptMergedUpdates( update = mergeChunkListEcmascriptMergedUpdates(
update, update,
updateA.merged[i] updateA.merged[i]
); )
} }
for (let i = 0; i < updateB.merged.length; i++) { for (let i = 0; i < updateB.merged.length; i++) {
update = mergeChunkListEcmascriptMergedUpdates( update = mergeChunkListEcmascriptMergedUpdates(
update, update,
updateB.merged[i] updateB.merged[i]
); )
} }
merged = [update]; merged = [update]
} }
} else if (updateB.merged != null) { } else if (updateB.merged != null) {
merged = updateB.merged; merged = updateB.merged
} }
return { return {
type: "ChunkListUpdate", type: 'ChunkListUpdate',
chunks, chunks,
merged, merged,
}; }
} }
function mergeChunkListChunks( function mergeChunkListChunks(
chunksA: Record<ChunkPath, ChunkUpdate>, chunksA: Record<ChunkPath, ChunkUpdate>,
chunksB: Record<ChunkPath, ChunkUpdate> chunksB: Record<ChunkPath, ChunkUpdate>
): Record<ChunkPath, ChunkUpdate> { ): Record<ChunkPath, ChunkUpdate> {
const chunks: Record<ChunkPath, ChunkUpdate> = {}; const chunks: Record<ChunkPath, ChunkUpdate> = {}
for (const [chunkPath, chunkUpdateA] of Object.entries(chunksA)) { for (const [chunkPath, chunkUpdateA] of Object.entries(chunksA)) {
const chunkUpdateB = chunksB[chunkPath]; const chunkUpdateB = chunksB[chunkPath]
if (chunkUpdateB != null) { if (chunkUpdateB != null) {
const mergedUpdate = mergeChunkUpdates(chunkUpdateA, chunkUpdateB); const mergedUpdate = mergeChunkUpdates(chunkUpdateA, chunkUpdateB)
if (mergedUpdate != null) { if (mergedUpdate != null) {
chunks[chunkPath] = mergedUpdate; chunks[chunkPath] = mergedUpdate
} }
} else { } else {
chunks[chunkPath] = chunkUpdateA; chunks[chunkPath] = chunkUpdateA
} }
} }
for (const [chunkPath, chunkUpdateB] of Object.entries(chunksB)) { for (const [chunkPath, chunkUpdateB] of Object.entries(chunksB)) {
if (chunks[chunkPath] == null) { if (chunks[chunkPath] == null) {
chunks[chunkPath] = chunkUpdateB; chunks[chunkPath] = chunkUpdateB
} }
} }
return chunks; return chunks
} }
function mergeChunkUpdates( function mergeChunkUpdates(
...@@ -243,42 +241,42 @@ function mergeChunkUpdates( ...@@ -243,42 +241,42 @@ function mergeChunkUpdates(
updateB: ChunkUpdate updateB: ChunkUpdate
): ChunkUpdate | undefined { ): ChunkUpdate | undefined {
if ( if (
(updateA.type === "added" && updateB.type === "deleted") || (updateA.type === 'added' && updateB.type === 'deleted') ||
(updateA.type === "deleted" && updateB.type === "added") (updateA.type === 'deleted' && updateB.type === 'added')
) { ) {
return undefined; return undefined
} }
if (updateA.type === "partial") { if (updateA.type === 'partial') {
invariant(updateA.instruction, "Partial updates are unsupported"); invariant(updateA.instruction, 'Partial updates are unsupported')
} }
if (updateB.type === "partial") { if (updateB.type === 'partial') {
invariant(updateB.instruction, "Partial updates are unsupported"); invariant(updateB.instruction, 'Partial updates are unsupported')
} }
return undefined; return undefined
} }
function mergeChunkListEcmascriptMergedUpdates( function mergeChunkListEcmascriptMergedUpdates(
mergedA: EcmascriptMergedUpdate, mergedA: EcmascriptMergedUpdate,
mergedB: EcmascriptMergedUpdate mergedB: EcmascriptMergedUpdate
): EcmascriptMergedUpdate { ): EcmascriptMergedUpdate {
const entries = mergeEcmascriptChunkEntries(mergedA.entries, mergedB.entries); const entries = mergeEcmascriptChunkEntries(mergedA.entries, mergedB.entries)
const chunks = mergeEcmascriptChunksUpdates(mergedA.chunks, mergedB.chunks); const chunks = mergeEcmascriptChunksUpdates(mergedA.chunks, mergedB.chunks)
return { return {
type: "EcmascriptMergedUpdate", type: 'EcmascriptMergedUpdate',
entries, entries,
chunks, chunks,
}; }
} }
function mergeEcmascriptChunkEntries( function mergeEcmascriptChunkEntries(
entriesA: Record<ModuleId, EcmascriptModuleEntry> | undefined, entriesA: Record<ModuleId, EcmascriptModuleEntry> | undefined,
entriesB: Record<ModuleId, EcmascriptModuleEntry> | undefined entriesB: Record<ModuleId, EcmascriptModuleEntry> | undefined
): Record<ModuleId, EcmascriptModuleEntry> { ): Record<ModuleId, EcmascriptModuleEntry> {
return { ...entriesA, ...entriesB }; return { ...entriesA, ...entriesB }
} }
function mergeEcmascriptChunksUpdates( function mergeEcmascriptChunksUpdates(
...@@ -286,245 +284,244 @@ function mergeEcmascriptChunksUpdates( ...@@ -286,245 +284,244 @@ function mergeEcmascriptChunksUpdates(
chunksB: Record<ChunkPath, EcmascriptMergedChunkUpdate> | undefined chunksB: Record<ChunkPath, EcmascriptMergedChunkUpdate> | undefined
): Record<ChunkPath, EcmascriptMergedChunkUpdate> | undefined { ): Record<ChunkPath, EcmascriptMergedChunkUpdate> | undefined {
if (chunksA == null) { if (chunksA == null) {
return chunksB; return chunksB
} }
if (chunksB == null) { if (chunksB == null) {
return chunksA; return chunksA
} }
const chunks: Record<ChunkPath, EcmascriptMergedChunkUpdate> = {}; const chunks: Record<ChunkPath, EcmascriptMergedChunkUpdate> = {}
for (const [chunkPath, chunkUpdateA] of Object.entries(chunksA)) { for (const [chunkPath, chunkUpdateA] of Object.entries(chunksA)) {
const chunkUpdateB = chunksB[chunkPath]; const chunkUpdateB = chunksB[chunkPath]
if (chunkUpdateB != null) { if (chunkUpdateB != null) {
const mergedUpdate = mergeEcmascriptChunkUpdates( const mergedUpdate = mergeEcmascriptChunkUpdates(
chunkUpdateA, chunkUpdateA,
chunkUpdateB chunkUpdateB
); )
if (mergedUpdate != null) { if (mergedUpdate != null) {
chunks[chunkPath] = mergedUpdate; chunks[chunkPath] = mergedUpdate
} }
} else { } else {
chunks[chunkPath] = chunkUpdateA; chunks[chunkPath] = chunkUpdateA
} }
} }
for (const [chunkPath, chunkUpdateB] of Object.entries(chunksB)) { for (const [chunkPath, chunkUpdateB] of Object.entries(chunksB)) {
if (chunks[chunkPath] == null) { if (chunks[chunkPath] == null) {
chunks[chunkPath] = chunkUpdateB; chunks[chunkPath] = chunkUpdateB
} }
} }
if (Object.keys(chunks).length === 0) { if (Object.keys(chunks).length === 0) {
return undefined; return undefined
} }
return chunks; return chunks
} }
function mergeEcmascriptChunkUpdates( function mergeEcmascriptChunkUpdates(
updateA: EcmascriptMergedChunkUpdate, updateA: EcmascriptMergedChunkUpdate,
updateB: EcmascriptMergedChunkUpdate updateB: EcmascriptMergedChunkUpdate
): EcmascriptMergedChunkUpdate | undefined { ): EcmascriptMergedChunkUpdate | undefined {
if (updateA.type === "added" && updateB.type === "deleted") { if (updateA.type === 'added' && updateB.type === 'deleted') {
// These two completely cancel each other out. // These two completely cancel each other out.
return undefined; return undefined
} }
if (updateA.type === "deleted" && updateB.type === "added") { if (updateA.type === 'deleted' && updateB.type === 'added') {
const added = []; const added = []
const deleted = []; const deleted = []
const deletedModules = new Set(updateA.modules ?? []); const deletedModules = new Set(updateA.modules ?? [])
const addedModules = new Set(updateB.modules ?? []); const addedModules = new Set(updateB.modules ?? [])
for (const moduleId of addedModules) { for (const moduleId of addedModules) {
if (!deletedModules.has(moduleId)) { if (!deletedModules.has(moduleId)) {
added.push(moduleId); added.push(moduleId)
} }
} }
for (const moduleId of deletedModules) { for (const moduleId of deletedModules) {
if (!addedModules.has(moduleId)) { if (!addedModules.has(moduleId)) {
deleted.push(moduleId); deleted.push(moduleId)
} }
} }
if (added.length === 0 && deleted.length === 0) { if (added.length === 0 && deleted.length === 0) {
return undefined; return undefined
} }
return { return {
type: "partial", type: 'partial',
added, added,
deleted, deleted,
}; }
} }
if (updateA.type === "partial" && updateB.type === "partial") { if (updateA.type === 'partial' && updateB.type === 'partial') {
const added = new Set([...(updateA.added ?? []), ...(updateB.added ?? [])]); const added = new Set([...(updateA.added ?? []), ...(updateB.added ?? [])])
const deleted = new Set([ const deleted = new Set([
...(updateA.deleted ?? []), ...(updateA.deleted ?? []),
...(updateB.deleted ?? []), ...(updateB.deleted ?? []),
]); ])
if (updateB.added != null) { if (updateB.added != null) {
for (const moduleId of updateB.added) { for (const moduleId of updateB.added) {
deleted.delete(moduleId); deleted.delete(moduleId)
} }
} }
if (updateB.deleted != null) { if (updateB.deleted != null) {
for (const moduleId of updateB.deleted) { for (const moduleId of updateB.deleted) {
added.delete(moduleId); added.delete(moduleId)
} }
} }
return { return {
type: "partial", type: 'partial',
added: [...added], added: [...added],
deleted: [...deleted], deleted: [...deleted],
}; }
} }
if (updateA.type === "added" && updateB.type === "partial") { if (updateA.type === 'added' && updateB.type === 'partial') {
const modules = new Set([ const modules = new Set([
...(updateA.modules ?? []), ...(updateA.modules ?? []),
...(updateB.added ?? []), ...(updateB.added ?? []),
]); ])
for (const moduleId of updateB.deleted ?? []) { for (const moduleId of updateB.deleted ?? []) {
modules.delete(moduleId); modules.delete(moduleId)
} }
return { return {
type: "added", type: 'added',
modules: [...modules], modules: [...modules],
}; }
} }
if (updateA.type === "partial" && updateB.type === "deleted") { if (updateA.type === 'partial' && updateB.type === 'deleted') {
// We could eagerly return `updateB` here, but this would potentially be // We could eagerly return `updateB` here, but this would potentially be
// incorrect if `updateA` has added modules. // incorrect if `updateA` has added modules.
const modules = new Set(updateB.modules ?? []); const modules = new Set(updateB.modules ?? [])
if (updateA.added != null) { if (updateA.added != null) {
for (const moduleId of updateA.added) { for (const moduleId of updateA.added) {
modules.delete(moduleId); modules.delete(moduleId)
} }
} }
return { return {
type: "deleted", type: 'deleted',
modules: [...modules], modules: [...modules],
}; }
} }
// Any other update combination is invalid. // Any other update combination is invalid.
return undefined; return undefined
} }
function invariant(never: never, message: string): never { function invariant(never: never, message: string): never {
throw new Error(`Invariant: ${message}`); throw new Error(`Invariant: ${message}`)
} }
const CRITICAL = ["bug", "error", "fatal"]; const CRITICAL = ['bug', 'error', 'fatal']
function compareByList(list: any[], a: any, b: any) { function compareByList(list: any[], a: any, b: any) {
const aI = list.indexOf(a) + 1 || list.length; const aI = list.indexOf(a) + 1 || list.length
const bI = list.indexOf(b) + 1 || list.length; const bI = list.indexOf(b) + 1 || list.length
return aI - bI; return aI - bI
} }
const chunksWithIssues: Map<ResourceKey, Issue[]> = new Map(); const chunksWithIssues: Map<ResourceKey, Issue[]> = new Map()
function emitIssues() { function emitIssues() {
const issues = []; const issues = []
const deduplicationSet = new Set(); const deduplicationSet = new Set()
for (const [_, chunkIssues] of chunksWithIssues) { for (const [_, chunkIssues] of chunksWithIssues) {
for (const chunkIssue of chunkIssues) { for (const chunkIssue of chunkIssues) {
if (deduplicationSet.has(chunkIssue.formatted)) continue; if (deduplicationSet.has(chunkIssue.formatted)) continue
issues.push(chunkIssue); issues.push(chunkIssue)
deduplicationSet.add(chunkIssue.formatted); deduplicationSet.add(chunkIssue.formatted)
} }
} }
sortIssues(issues); sortIssues(issues)
onTurbopackIssues(issues); onTurbopackIssues(issues)
} }
function handleIssues(msg: ServerMessage): boolean { function handleIssues(msg: ServerMessage): boolean {
const key = resourceKey(msg.resource); const key = resourceKey(msg.resource)
let hasCriticalIssues = false; let hasCriticalIssues = false
for (const issue of msg.issues) { for (const issue of msg.issues) {
if (CRITICAL.includes(issue.severity)) { if (CRITICAL.includes(issue.severity)) {
console.error(stripAnsi(issue.formatted)); hasCriticalIssues = true
hasCriticalIssues = true;
} }
} }
if (msg.issues.length > 0) { if (msg.issues.length > 0) {
chunksWithIssues.set(key, msg.issues); chunksWithIssues.set(key, msg.issues)
} else if (chunksWithIssues.has(key)) { } else if (chunksWithIssues.has(key)) {
chunksWithIssues.delete(key); chunksWithIssues.delete(key)
} }
emitIssues(); emitIssues()
return hasCriticalIssues; return hasCriticalIssues
} }
const SEVERITY_ORDER = ["bug", "fatal", "error", "warning", "info", "log"]; const SEVERITY_ORDER = ['bug', 'fatal', 'error', 'warning', 'info', 'log']
const CATEGORY_ORDER = [ const CATEGORY_ORDER = [
"parse", 'parse',
"resolve", 'resolve',
"code generation", 'code generation',
"rendering", 'rendering',
"typescript", 'typescript',
"other", 'other',
]; ]
function sortIssues(issues: Issue[]) { function sortIssues(issues: Issue[]) {
issues.sort((a, b) => { issues.sort((a, b) => {
const first = compareByList(SEVERITY_ORDER, a.severity, b.severity); const first = compareByList(SEVERITY_ORDER, a.severity, b.severity)
if (first !== 0) return first; if (first !== 0) return first
return compareByList(CATEGORY_ORDER, a.category, b.category); return compareByList(CATEGORY_ORDER, a.category, b.category)
}); })
} }
function handleSocketMessage(msg: ServerMessage) { function handleSocketMessage(msg: ServerMessage) {
sortIssues(msg.issues); sortIssues(msg.issues)
const hasCriticalIssues = handleIssues(msg); const hasCriticalIssues = handleIssues(msg)
// TODO(WEB-582) Disable update aggregation for now. // TODO(WEB-582) Disable update aggregation for now.
const aggregate = /* hasCriticalIssues */ false; const aggregate = /* hasCriticalIssues */ false
const aggregatedMsg = aggregateUpdates(msg, aggregate); const aggregatedMsg = aggregateUpdates(msg, aggregate)
if (aggregate) return; if (aggregate) return
const runHooks = chunkListsWithPendingUpdates.size === 0; const runHooks = chunkListsWithPendingUpdates.size === 0
if (aggregatedMsg.type !== "issues") { if (aggregatedMsg.type !== 'issues') {
if (runHooks) onBeforeRefresh(); if (runHooks) onBeforeRefresh()
triggerUpdate(aggregatedMsg); triggerUpdate(aggregatedMsg)
if (runHooks) onRefresh(); if (runHooks) onRefresh()
} }
if (runHooks) onBuildOk(); if (runHooks) onBuildOk()
// This is used by the Next.js integration test suite to notify it when HMR // This is used by the Next.js integration test suite to notify it when HMR
// updates have been completed. // updates have been completed.
// TODO: Only run this in test environments (gate by `process.env.__NEXT_TEST_MODE`) // TODO: Only run this in test environments (gate by `process.env.__NEXT_TEST_MODE`)
if (globalThis.__NEXT_HMR_CB) { if (globalThis.__NEXT_HMR_CB) {
globalThis.__NEXT_HMR_CB(); globalThis.__NEXT_HMR_CB()
globalThis.__NEXT_HMR_CB = null; globalThis.__NEXT_HMR_CB = null
} }
} }
...@@ -537,63 +534,63 @@ export function subscribeToChunkUpdate( ...@@ -537,63 +534,63 @@ export function subscribeToChunkUpdate(
path: chunkPath, path: chunkPath,
}, },
callback callback
); )
} }
export function subscribeToUpdate( export function subscribeToUpdate(
resource: ResourceIdentifier, resource: ResourceIdentifier,
callback: UpdateCallback callback: UpdateCallback
) { ) {
const key = resourceKey(resource); const key = resourceKey(resource)
let callbackSet: UpdateCallbackSet; let callbackSet: UpdateCallbackSet
const existingCallbackSet = updateCallbackSets.get(key); const existingCallbackSet = updateCallbackSets.get(key)
if (!existingCallbackSet) { if (!existingCallbackSet) {
callbackSet = { callbackSet = {
callbacks: new Set([callback]), callbacks: new Set([callback]),
unsubscribe: subscribeToUpdates(resource), unsubscribe: subscribeToUpdates(resource),
}; }
updateCallbackSets.set(key, callbackSet); updateCallbackSets.set(key, callbackSet)
} else { } else {
existingCallbackSet.callbacks.add(callback); existingCallbackSet.callbacks.add(callback)
callbackSet = existingCallbackSet; callbackSet = existingCallbackSet
} }
return () => { return () => {
callbackSet.callbacks.delete(callback); callbackSet.callbacks.delete(callback)
if (callbackSet.callbacks.size === 0) { if (callbackSet.callbacks.size === 0) {
callbackSet.unsubscribe(); callbackSet.unsubscribe()
updateCallbackSets.delete(key); updateCallbackSets.delete(key)
} }
}; }
} }
function triggerUpdate(msg: ServerMessage) { function triggerUpdate(msg: ServerMessage) {
const key = resourceKey(msg.resource); const key = resourceKey(msg.resource)
const callbackSet = updateCallbackSets.get(key); const callbackSet = updateCallbackSets.get(key)
if (!callbackSet) { if (!callbackSet) {
return; return
} }
try { try {
for (const callback of callbackSet.callbacks) { for (const callback of callbackSet.callbacks) {
callback(msg); callback(msg)
} }
if (msg.type === "notFound") { if (msg.type === 'notFound') {
// This indicates that the resource which we subscribed to either does not exist or // This indicates that the resource which we subscribed to either does not exist or
// has been deleted. In either case, we should clear all update callbacks, so if a // has been deleted. In either case, we should clear all update callbacks, so if a
// new subscription is created for the same resource, it will send a new "subscribe" // new subscription is created for the same resource, it will send a new "subscribe"
// message to the server. // message to the server.
// No need to send an "unsubscribe" message to the server, it will have already // No need to send an "unsubscribe" message to the server, it will have already
// dropped the update stream before sending the "notFound" message. // dropped the update stream before sending the "notFound" message.
updateCallbackSets.delete(key); updateCallbackSets.delete(key)
} }
} catch (err) { } catch (err) {
console.error( console.error(
`An error occurred during the update of resource \`${msg.resource.path}\``, `An error occurred during the update of resource \`${msg.resource.path}\``,
err err
); )
location.reload(); location.reload()
} }
} }
import "@vercel/turbopack-next/internal/shims-client"; import '@vercel/turbopack-next/internal/shims-client'
import { createRoot } from "react-dom/client"; import { createRoot } from 'react-dom/client'
import { import {
initializeHMR, initializeHMR,
ReactDevOverlay, ReactDevOverlay,
} from "@vercel/turbopack-next/dev/client"; } from '@vercel/turbopack-next/dev/client'
import { subscribeToUpdate } from "@vercel/turbopack-next/dev/hmr-client"; import { subscribeToUpdate } from '@vercel/turbopack-next/dev/hmr-client'
const pageChunkPath = location.pathname.slice(1); const pageChunkPath = location.pathname.slice(1)
subscribeToUpdate( subscribeToUpdate(
{ {
path: pageChunkPath, path: pageChunkPath,
headers: { headers: {
accept: "text/html", accept: 'text/html',
}, },
}, },
(update) => { (update) => {
if (update.type === "restart" || update.type === "notFound") { if (update.type === 'restart' || update.type === 'notFound') {
location.reload(); location.reload()
} }
} }
); )
initializeHMR({ initializeHMR({
assetPrefix: "", assetPrefix: '',
}); })
const el = document.getElementById("__next")!; const el = document.getElementById('__next')!
el.innerText = "";
createRoot(el).render(<ReactDevOverlay />); const innerHtml = {
__html: el.innerHTML,
}
createRoot(el).render(
<ReactDevOverlay>
<div dangerouslySetInnerHTML={innerHtml}></div>
</ReactDevOverlay>
)
import React from "react"; import React from 'react'
type ErrorBoundaryProps = { type ErrorBoundaryProps = {
onError: (error: Error, componentStack: string | null) => void; error: Error | null
fallback: React.ReactNode | null; onError: (error: Error, componentStack: string | null) => void
children?: React.ReactNode; fallback: React.ReactNode | null
}; children?: React.ReactNode
}
type ErrorBoundaryState = { error: Error | null }; type ErrorBoundaryState = {
error: Error | null
lastPropsError: Error | null
}
class ErrorBoundary extends React.PureComponent< class ErrorBoundary extends React.PureComponent<
ErrorBoundaryProps, ErrorBoundaryProps,
ErrorBoundaryState ErrorBoundaryState
> { > {
static getDerivedStateFromError(error: Error) { static getDerivedStateFromError(error: Error) {
return { error }; return { error }
} }
state = { error: null }; state = {
error: null,
lastPropsError: null,
}
componentDidCatch( componentDidCatch(
error: Error, error: Error,
...@@ -24,21 +31,48 @@ class ErrorBoundary extends React.PureComponent< ...@@ -24,21 +31,48 @@ class ErrorBoundary extends React.PureComponent<
// accidentally excluded in some versions. // accidentally excluded in some versions.
errorInfo?: { componentStack?: string | null } errorInfo?: { componentStack?: string | null }
) { ) {
this.props.onError(error, errorInfo?.componentStack ?? null); this.props.onError(error, errorInfo?.componentStack ?? null)
}
// I don't like this, but it works to clear the error boundary
//
// props.error is only set 1 render after state.error, so we can't treat it as the source of truth all the time.
// to get around this we store the error from props in state and only accept updates if the stored error from props
// matches the error in state.
//
// this is definitely not a controlled component and it only works if the error matches exactly
static getDerivedStateFromProps(
props: ErrorBoundaryProps,
state: ErrorBoundaryState
): ErrorBoundaryState | null {
if (state.lastPropsError === props.error) {
return null
}
let error = state.error
if (state.error === state.lastPropsError) {
error = props.error
}
return {
error,
lastPropsError: props.error,
}
} }
render() { render() {
const { error } = this.state; const { error } = this.state
const { fallback } = this.props; const { fallback } = this.props
// The component has to be unmounted or else it would continue to error // The component has to be unmounted or else it would continue to error
if (error != null) { if (error != null) {
return fallback; return fallback
} }
return this.props.children; return this.props.children
} }
} }
export { ErrorBoundary }; export { ErrorBoundary }
import * as React from "react"; import * as React from 'react'
import type { Issue } from "@vercel/turbopack-dev-runtime/types/protocol"; import type { Issue } from '@vercel/turbopack-dev-runtime/types/protocol'
import * as Bus from "./bus"; import * as Bus from './bus'
import { ShadowPortal } from "./components/ShadowPortal"; import { ShadowPortal } from './components/ShadowPortal'
import { Errors, SupportedErrorEvent } from "./container/Errors"; import { Errors, SupportedErrorEvent } from './container/Errors'
import { ErrorBoundary } from "./ErrorBoundary"; import { ErrorBoundary } from './ErrorBoundary'
import { Base } from "./styles/Base"; import { Base } from './styles/Base'
import { ComponentStyles } from "./styles/ComponentStyles"; import { ComponentStyles } from './styles/ComponentStyles'
import { CssReset } from "./styles/CssReset"; import { CssReset } from './styles/CssReset'
type RefreshState = type RefreshState =
| { | {
// No refresh in progress. // No refresh in progress.
type: "idle"; type: 'idle'
} }
| { | {
// The refresh process has been triggered, but the new code has not been // The refresh process has been triggered, but the new code has not been
// executed yet. // executed yet.
type: "pending"; type: 'pending'
errors: SupportedErrorEvent[]; errors: SupportedErrorEvent[]
}; reactError: Error | null
}
type OverlayState = { type OverlayState = {
nextId: number; nextId: number
// issues are from turbopack // issues are from turbopack
issues: Issue[]; issues: Issue[]
// errors are client side // errors are client side
errors: SupportedErrorEvent[]; errors: SupportedErrorEvent[]
refreshState: RefreshState; refreshState: RefreshState
reactError: Error | null; reactError: Error | null
}; }
function pushErrorFilterDuplicates( function pushErrorFilterDuplicates(
errors: SupportedErrorEvent[], errors: SupportedErrorEvent[],
...@@ -43,29 +44,25 @@ function pushErrorFilterDuplicates( ...@@ -43,29 +44,25 @@ function pushErrorFilterDuplicates(
return [ return [
...errors.filter((e) => { ...errors.filter((e) => {
// Filter out duplicate errors // Filter out duplicate errors
return e.event.reason !== err.event.reason; return e.event.reason !== err.event.reason
}), }),
err, err,
]; ]
} }
function reducer(state: OverlayState, ev: Bus.BusEvent): OverlayState { function reducer(state: OverlayState, ev: Bus.BusEvent): OverlayState {
switch (ev.type) { switch (ev.type) {
case Bus.TYPE_BUILD_OK: { case Bus.TYPE_BUILD_OK: {
if (state.reactError != null) { return { ...state }
console.warn(
"[Fast Refresh] performing full reload because your application had an unrecoverable error"
);
window.location.reload();
}
return { ...state };
} }
case Bus.TYPE_TURBOPACK_ISSUES: { case Bus.TYPE_TURBOPACK_ISSUES: {
return { ...state, issues: ev.issues }; return { ...state, issues: ev.issues }
} }
case Bus.TYPE_BEFORE_REFRESH: { case Bus.TYPE_BEFORE_REFRESH: {
return { ...state, refreshState: { type: "pending", errors: [] } }; return {
...state,
refreshState: { type: 'pending', errors: [], reactError: null },
}
} }
case Bus.TYPE_REFRESH: { case Bus.TYPE_REFRESH: {
return { return {
...@@ -77,16 +74,20 @@ function reducer(state: OverlayState, ev: Bus.BusEvent): OverlayState { ...@@ -77,16 +74,20 @@ function reducer(state: OverlayState, ev: Bus.BusEvent): OverlayState {
// around until the next refresh. Otherwise we run into a race // around until the next refresh. Otherwise we run into a race
// condition where those errors would be cleared on refresh completion // condition where those errors would be cleared on refresh completion
// before they can be displayed. // before they can be displayed.
state.refreshState.type === "pending" state.refreshState.type === 'pending'
? state.refreshState.errors ? state.refreshState.errors
: [], : [],
refreshState: { type: "idle" }, reactError:
}; state.refreshState.type === 'pending'
? state.refreshState.reactError
: null,
refreshState: { type: 'idle' },
}
} }
case Bus.TYPE_UNHANDLED_ERROR: case Bus.TYPE_UNHANDLED_ERROR:
case Bus.TYPE_UNHANDLED_REJECTION: { case Bus.TYPE_UNHANDLED_REJECTION: {
switch (state.refreshState.type) { switch (state.refreshState.type) {
case "idle": { case 'idle': {
return { return {
...state, ...state,
nextId: state.nextId + 1, nextId: state.nextId + 1,
...@@ -94,9 +95,9 @@ function reducer(state: OverlayState, ev: Bus.BusEvent): OverlayState { ...@@ -94,9 +95,9 @@ function reducer(state: OverlayState, ev: Bus.BusEvent): OverlayState {
id: state.nextId, id: state.nextId,
event: ev, event: ev,
}), }),
}; }
} }
case "pending": { case 'pending': {
return { return {
...state, ...state,
nextId: state.nextId + 1, nextId: state.nextId + 1,
...@@ -107,38 +108,56 @@ function reducer(state: OverlayState, ev: Bus.BusEvent): OverlayState { ...@@ -107,38 +108,56 @@ function reducer(state: OverlayState, ev: Bus.BusEvent): OverlayState {
event: ev, event: ev,
}), }),
}, },
}; }
} }
default: default:
return state; return state
} }
} }
case Bus.TYPE_REACT_ERROR: { case Bus.TYPE_REACT_ERROR: {
return { ...state, reactError: ev.error }; switch (state.refreshState.type) {
case 'idle': {
return {
...state,
reactError: ev.error,
}
}
case 'pending': {
return {
...state,
refreshState: {
...state.refreshState,
reactError: ev.error,
},
}
}
default:
return state
}
} }
default: { default: {
return state; return state
} }
} }
} }
type ErrorType = "runtime" | "build"; type ErrorType = 'runtime' | 'build'
const shouldPreventDisplay = ( const shouldPreventDisplay = (
errorType?: ErrorType | null, errorType?: ErrorType | null,
preventType?: ErrorType[] | null preventType?: ErrorType[] | null
) => { ) => {
if (!preventType || !errorType) { if (!preventType || !errorType) {
return false; return false
} }
return preventType.includes(errorType); return preventType.includes(errorType)
}; }
type ReactDevOverlayProps = { type ReactDevOverlayProps = {
globalOverlay?: boolean; globalOverlay?: boolean
preventDisplay?: ErrorType[]; preventDisplay?: ErrorType[]
children?: React.ReactNode; children?: React.ReactNode
}; }
export default function ReactDevOverlay({ export default function ReactDevOverlay({
children, children,
...@@ -152,17 +171,17 @@ export default function ReactDevOverlay({ ...@@ -152,17 +171,17 @@ export default function ReactDevOverlay({
issues: [], issues: [],
errors: [], errors: [],
refreshState: { refreshState: {
type: "idle", type: 'idle',
}, },
reactError: null, reactError: null,
}); })
React.useEffect(() => { React.useEffect(() => {
Bus.on(dispatch); Bus.on(dispatch)
return function () { return function () {
Bus.off(dispatch); Bus.off(dispatch)
}; }
}, [dispatch]); }, [dispatch])
const onComponentError = React.useCallback( const onComponentError = React.useCallback(
(error: Error, componentStack: string | null) => { (error: Error, componentStack: string | null) => {
...@@ -170,25 +189,26 @@ export default function ReactDevOverlay({ ...@@ -170,25 +189,26 @@ export default function ReactDevOverlay({
type: Bus.TYPE_REACT_ERROR, type: Bus.TYPE_REACT_ERROR,
error, error,
componentStack, componentStack,
}); })
}, },
[] []
); )
const hasBuildError = state.issues.length > 0; const hasBuildError = state.issues.length > 0
const hasRuntimeErrors = state.errors.length > 0; const hasRuntimeErrors = state.errors.length > 0
const errorType = hasBuildError const errorType = hasBuildError
? "build" ? 'build'
: hasRuntimeErrors : hasRuntimeErrors
? "runtime" ? 'runtime'
: null; : null
const isMounted = hasBuildError || hasRuntimeErrors; const isMounted = hasBuildError || hasRuntimeErrors
return ( return (
<React.Fragment> <React.Fragment>
<ErrorBoundary <ErrorBoundary
error={state.reactError}
onError={onComponentError} onError={onComponentError}
fallback={ fallback={
// When the overlay is global for the application and it wraps a component rendering `<html>` // When the overlay is global for the application and it wraps a component rendering `<html>`
...@@ -214,5 +234,5 @@ export default function ReactDevOverlay({ ...@@ -214,5 +234,5 @@ export default function ReactDevOverlay({
</ShadowPortal> </ShadowPortal>
) : null} ) : null}
</React.Fragment> </React.Fragment>
); )
} }
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