Unverified Commit e0449a5b authored by Joe Haddad's avatar Joe Haddad Committed by GitHub

[Fast Refresh] New Overlay for Prerender Error (#12485)

parent 0d4707d6
......@@ -152,8 +152,8 @@ export default async function getBaseWebpackConfig(
}
}
const hasReactRefresh =
dev && !isServer && config.experimental.reactRefresh === true
const isReactRefreshEnabled = config.experimental.reactRefresh === true
const hasReactRefresh = dev && !isServer && isReactRefreshEnabled
const distDir = path.join(dir, config.distDir)
const defaultLoaders = {
......@@ -1032,7 +1032,7 @@ export default async function getBaseWebpackConfig(
customAppFile,
isDevelopment: dev,
isServer,
hasReactRefresh,
isReactRefreshEnabled,
assetPrefix: config.assetPrefix || '',
sassOptions: config.experimental.sassOptions,
})
......
......@@ -12,11 +12,17 @@ export const base = curry(function base(
// https://webpack.js.org/configuration/devtool/#development
config.devtool = ctx.isDevelopment
? ctx.hasReactRefresh
? // `eval-source-map` results in the fastest rebuilds during dev. The
// only drawback is cold boot time, but this is mitigated by the fact
// that we load entries on-demand.
'eval-source-map'
? ctx.isReactRefreshEnabled
? ctx.isServer
? // Non-eval based source maps are very slow to rebuild, so we only
// enable them for the server. Unfortunately, eval source maps are
// not supported by Node.js.
'inline-source-map'
: // `eval-source-map` provides full-fidelity source maps for the
// original source, including columns and original variable names.
// This is desirable so the in-browser debugger can correctly pause
// and show scoped variables with their original names.
'eval-source-map'
: // `cheap-module-source-map` is the old preferred format that was
// required for `react-error-overlay`.
'cheap-module-source-map'
......
......@@ -10,7 +10,7 @@ export async function build(
customAppFile,
isDevelopment,
isServer,
hasReactRefresh,
isReactRefreshEnabled,
assetPrefix,
sassOptions,
}: {
......@@ -18,7 +18,7 @@ export async function build(
customAppFile: string | null
isDevelopment: boolean
isServer: boolean
hasReactRefresh: boolean
isReactRefreshEnabled: boolean
assetPrefix: string
sassOptions: any
}
......@@ -28,7 +28,7 @@ export async function build(
customAppFile,
isDevelopment,
isProduction: !isDevelopment,
hasReactRefresh,
isReactRefreshEnabled,
isServer,
isClient: !isServer,
assetPrefix: assetPrefix
......
......@@ -6,7 +6,7 @@ export type ConfigurationContext = {
isDevelopment: boolean
isProduction: boolean
hasReactRefresh: boolean
isReactRefreshEnabled: boolean
isServer: boolean
isClient: boolean
......
......@@ -107,14 +107,10 @@ export default function connect(options) {
},
reportRuntimeError(err) {
if (process.env.__NEXT_FAST_REFRESH) {
// FIXME: this code branch should be eliminated
setTimeout(() => {
// An unhandled rendering error occurred
throw err
})
} else {
ErrorOverlay.reportRuntimeError(err)
return
}
ErrorOverlay.reportRuntimeError(err)
},
prepareError(err) {
// Temporary workaround for https://github.com/facebook/create-react-app/issues/4760
......
/* global location */
import { createRouter, makePublicRouterInstance } from 'next/router'
import { parse as parseQs, stringify as stringifyQs } from 'querystring'
import React from 'react'
import ReactDOM from 'react-dom'
import initHeadManager from './head-manager'
import { createRouter, makePublicRouterInstance } from 'next/router'
import mitt from '../next-server/lib/mitt'
import { loadGetInitialProps, getURL, ST } from '../next-server/lib/utils'
import PageLoader from './page-loader'
import * as envConfig from '../next-server/lib/runtime-config'
import { HeadManagerContext } from '../next-server/lib/head-manager-context'
import mitt from '../next-server/lib/mitt'
import { RouterContext } from '../next-server/lib/router-context'
import { parse as parseQs, stringify as stringifyQs } from 'querystring'
import { isDynamicRoute } from '../next-server/lib/router/utils/is-dynamic'
import * as envConfig from '../next-server/lib/runtime-config'
import { getURL, loadGetInitialProps, ST } from '../next-server/lib/utils'
import initHeadManager from './head-manager'
import PageLoader from './page-loader'
import {
observeLayoutShift,
observeLargestContentfulPaint,
observeLayoutShift,
observePaint,
} from './performance-relayer'
......@@ -263,13 +263,50 @@ export async function render(props) {
// This method handles all runtime and debug errors.
// 404 and 500 errors are special kind of errors
// and they are still handle via the main render method.
export async function renderError(props) {
export function renderError(props) {
const { App, err } = props
// In development runtime errors are caught by react-error-overlay
// In production we catch runtime errors using componentDidCatch which will trigger renderError
if (process.env.NODE_ENV !== 'production') {
return webpackHMR.reportRuntimeError(webpackHMR.prepareError(err))
if (process.env.__NEXT_FAST_REFRESH) {
const { getNodeError } = require('@next/react-dev-overlay/lib/client')
// Server-side runtime errors need to be re-thrown on the client-side so
// that the overlay is rendered.
if (isInitialRender) {
setTimeout(() => {
let error
try {
// Generate a new error object. We `throw` it because some browsers
// will set the `stack` when thrown, and we want to ensure ours is
// not overridden when we re-throw it below.
throw new Error(err.message)
} catch (e) {
error = e
}
error.name = err.name
error.stack = err.stack
const node = getNodeError(error)
throw node
})
}
// We need to render an empty <App> so that the `<ReactDevOverlay>` can
// render itself.
return doRender({
App: () => null,
props: {},
Component: () => null,
err: null,
})
}
// Legacy behavior:
return Promise.resolve(
webpackHMR.reportRuntimeError(webpackHMR.prepareError(err))
)
}
if (process.env.__NEXT_PLUGINS) {
// eslint-disable-next-line
......@@ -284,24 +321,28 @@ export async function renderError(props) {
// Make sure we log the error to the console, otherwise users can't track down issues.
console.error(err)
;({ page: ErrorComponent } = await pageLoader.loadPage('/_error'))
// In production we do a normal render with the `ErrorComponent` as component.
// If we've gotten here upon initial render, we can use the props from the server.
// Otherwise, we need to call `getInitialProps` on `App` before mounting.
const AppTree = wrapApp(App)
const appCtx = {
Component: ErrorComponent,
AppTree,
router,
ctx: { err, pathname: page, query, asPath, AppTree },
}
const initProps = props.props
? props.props
: await loadGetInitialProps(App, appCtx)
await doRender({ ...props, err, Component: ErrorComponent, props: initProps })
return pageLoader.loadPage('/_error').then(({ page: ErrorComponent }) => {
// In production we do a normal render with the `ErrorComponent` as component.
// If we've gotten here upon initial render, we can use the props from the server.
// Otherwise, we need to call `getInitialProps` on `App` before mounting.
const AppTree = wrapApp(App)
const appCtx = {
Component: ErrorComponent,
AppTree,
router,
ctx: { err, pathname: page, query, asPath, AppTree },
}
return Promise.resolve(
props.props ? props.props : loadGetInitialProps(App, appCtx)
).then(initProps =>
doRender({
...props,
err,
Component: ErrorComponent,
props: initProps,
})
)
})
}
// If hydrate does not exist, eg in preact.
......
import AmpHtmlValidator from 'next/dist/compiled/amphtml-validator'
import { ReactDevOverlay } from '@next/react-dev-overlay/lib/client'
import crypto from 'crypto'
import findUp from 'next/dist/compiled/find-up'
import fs from 'fs'
import { IncomingMessage, ServerResponse } from 'http'
import Worker from 'jest-worker'
import AmpHtmlValidator from 'next/dist/compiled/amphtml-validator'
import findUp from 'next/dist/compiled/find-up'
import { join, relative, resolve, sep } from 'path'
import React from 'react'
import { UrlWithParsedQuery } from 'url'
......@@ -48,7 +49,10 @@ export default class DevServer extends Server {
constructor(options: ServerConstructor & { isNextDevCommand?: boolean }) {
super({ ...options, dev: true })
this.renderOpts.dev = true
;(this.renderOpts as any).ErrorDebug = ErrorDebug
;(this.renderOpts as any).ErrorDebug =
this.nextConfig.experimental?.reactRefresh === true
? ReactDevOverlay
: ErrorDebug
this.devReady = new Promise(resolve => {
this.setDevReady = resolve
})
......
......@@ -20,6 +20,7 @@
"anser": "1.4.9",
"chalk": "4.0.0",
"classnames": "2.2.6",
"data-uri-to-buffer": "3.0.0",
"shell-quote": "1.7.2",
"source-map": "0.8.0-beta.0",
"stacktrace-parser": "0.1.9",
......
......@@ -75,5 +75,6 @@ function onRefresh() {
Bus.emit({ type: Bus.TYPE_REFFRESH })
}
export { getNodeError } from './internal/helpers/nodeStackFrames'
export { default as ReactDevOverlay } from './internal/ReactDevOverlay'
export { register, unregister, onRefresh }
......@@ -54,7 +54,9 @@ function ReactDevOverlay({ children }) {
return (
<React.Fragment>
<ErrorBoundary onError={onComponentError}>{children}</ErrorBoundary>
<ErrorBoundary onError={onComponentError}>
{children ?? null}
</ErrorBoundary>
{state.errors.length ? (
<ShadowPortal>
<CssReset />
......
......@@ -14,7 +14,7 @@ const CallStackFrame: React.FC<{
// TODO: render error or external indicator
const f: StackFrame = frame.originalStackFrame ?? frame.sourceStackFrame
const hasSource = Boolean(frame.originalStackFrame?.file)
const hasSource = Boolean(frame.originalCodeFrame)
const open = React.useCallback(() => {
if (!hasSource) return
......
import dataUriToBuffer, { MimeBuffer } from 'data-uri-to-buffer'
import { RawSourceMap } from 'source-map'
import { getSourceMapUrl } from './getSourceMapUrl'
export function getRawSourceMap(fileContents: string): RawSourceMap | null {
const sourceUrl = getSourceMapUrl(fileContents)
if (sourceUrl == null) {
return null
}
let buffer: MimeBuffer
try {
buffer = dataUriToBuffer(sourceUrl)
} catch (err) {
console.error('Failed to parse source map URL:', err)
return null
}
if (buffer.type !== 'application/json') {
console.error(`Unknown source map type: ${buffer.typeFull}.`)
return null
}
try {
return JSON.parse(buffer.toString())
} catch {
console.error('Failed to parse source map.')
return null
}
}
export function getSourceMapUrl(fileContents: string): string | null {
const regex = /\/\/[#@] ?sourceMappingURL=([^\s'"]+)\s*$/gm
let match = null
for (;;) {
let next = regex.exec(fileContents)
if (next == null) {
break
}
match = next
}
if (!(match && match[1])) {
return null
}
return match[1].toString()
}
import { parse, StackFrame } from 'stacktrace-parser'
export function getFilesystemFrame(frame: StackFrame): StackFrame {
const f: StackFrame = { ...frame }
if (typeof f.file === 'string') {
if (
// Posix:
f.file.startsWith('/') ||
// Win32:
/^[a-z]:\\/i.test(f.file) ||
// Win32 UNC:
f.file.startsWith('\\\\')
) {
f.file = `file://${f.file}`
}
}
return f
}
export function getNodeError(error: Error): Error {
let n: Error
try {
throw new Error(error.message)
} catch (e) {
n = e
}
n.name = error.name
try {
n.stack = parse(error.stack)
.map(getFilesystemFrame)
.map(f => {
let str = ` at ${f.methodName}`
if (f.file) {
let loc = f.file
if (f.lineNumber) {
loc += `:${f.lineNumber}`
if (f.column) {
loc += `:${f.column}`
}
}
str += ` (${loc})`
}
return str
})
.join('\n')
} catch {
n.stack = error.stack
}
return n
}
......@@ -70,7 +70,12 @@ export function getOriginalStackFrame(
}
}
if (!source.file?.startsWith('webpack-internal:')) {
if (
!(
source.file?.startsWith('webpack-internal:') ||
source.file?.startsWith('file:')
)
) {
return Promise.resolve({
error: false,
reason: null,
......@@ -103,7 +108,13 @@ export function getFrameSource(frame: StackFrame): string {
typeof globalThis !== 'undefined' &&
globalThis.location?.origin !== u.origin
) {
str += u.origin
// URLs can be valid without an `origin`, so long as they have a
// `protocol`. However, `origin` is preferred.
if (u.origin === 'null') {
str += u.protocol
} else {
str += u.origin
}
}
// Strip query string information as it's typically too verbose to be
......
......@@ -2,11 +2,15 @@ import { codeFrameColumns } from '@babel/code-frame'
import { constants as FS, promises as fs } from 'fs'
import { IncomingMessage, ServerResponse } from 'http'
import path from 'path'
import { NullableMappedPosition, SourceMapConsumer } from 'source-map'
import {
NullableMappedPosition,
RawSourceMap,
SourceMapConsumer,
} from 'source-map'
import { StackFrame } from 'stacktrace-parser'
import url from 'url'
import webpack from 'webpack'
import { OriginalSource } from 'webpack-sources'
import { getRawSourceMap } from './internal/helpers/getRawSourceMap'
import { launchEditor } from './internal/helpers/launchEditor'
export type OverlayMiddlewareOptions = {
......@@ -19,8 +23,31 @@ export type OriginalStackFrameResponse = {
originalCodeFrame: string | null
}
type Source = { map: () => RawSourceMap } | null
function getOverlayMiddleware(options: OverlayMiddlewareOptions) {
function getSourceById(id: string): OriginalSource | null {
async function getSourceById(protocol: string, id: string): Promise<Source> {
if (protocol === 'file:') {
const fileContent: string | null = await fs
.readFile(id, 'utf-8')
.catch(() => null)
if (fileContent == null) {
return null
}
const map = getRawSourceMap(fileContent)
if (map == null) {
return null
}
return {
map() {
return map
},
}
}
try {
const compilation = options.stats()?.compilation
const m = compilation?.modules?.find(m => m.id === id)
......@@ -46,82 +73,107 @@ function getOverlayMiddleware(options: OverlayMiddlewareOptions) {
if (pathname === '/__nextjs_original-stack-frame') {
const frame = (query as unknown) as StackFrame
if (
frame.file?.startsWith('webpack-internal:///') ||
!parseInt(frame.lineNumber?.toString() ?? '', 10)
) {
const moduleId = frame.file.slice(20)
const source = getSourceById(moduleId)
if (source == null) {
res.statusCode = 404
res.write('Not Found')
return res.end()
}
const frameLine = parseInt(frame.lineNumber?.toString() ?? '', 10)
let frameColumn: number | null = parseInt(
frame.column?.toString() ?? '',
10
!(
(frame.file?.startsWith('webpack-internal:///') ||
frame.file?.startsWith('file://')) &&
Boolean(parseInt(frame.lineNumber?.toString() ?? '', 10))
)
if (!frameColumn) {
frameColumn = null
}
let pos: NullableMappedPosition
try {
const consumer = await new SourceMapConsumer(source.map())
pos = consumer.originalPositionFor({
line: frameLine,
column: frameColumn,
})
consumer.destroy()
} catch (err) {
console.log('Failed to parse source map:', err)
res.statusCode = 500
res.write('Internal Server Error')
return res.end()
}
if (pos.source == null) {
res.statusCode = 404
res.write('Not Found')
return res.end()
}
const filePath = path.resolve(options.rootDirectory, pos.source)
const fileContent: string | null = await fs
.readFile(filePath, 'utf-8')
.catch(() => null)
const originalFrame: StackFrame = {
file: fileContent
? path.relative(options.rootDirectory, filePath)
: pos.source,
lineNumber: pos.line,
column: pos.column,
methodName: frame.methodName, // TODO: resolve original method name (?)
arguments: [],
}
const originalCodeFrame: string | null =
fileContent && pos.line
? (codeFrameColumns(
fileContent,
{ start: { line: pos.line, column: pos.column } },
{ forceColor: true }
) as string)
: null
const o: OriginalStackFrameResponse = {
originalStackFrame: originalFrame,
originalCodeFrame,
}
res.statusCode = 200
res.setHeader('Content-Type', 'application/json')
res.write(Buffer.from(JSON.stringify(o)))
) {
res.statusCode = 400
res.write('Bad Request')
return res.end()
}
res.statusCode = 400
res.write('Bad Request')
const moduleUrl = new URL(frame.file)
const moduleId: string =
moduleUrl.protocol === 'webpack-internal:'
? // Important to use original file to retain full path structure.
// e.g. `webpack-internal:///./pages/index.js`
frame.file.slice(20)
: moduleUrl.pathname
let source: Source
try {
source = await getSourceById(moduleUrl.protocol, moduleId)
} catch (err) {
console.log('Failed to get source map:', err)
res.statusCode = 500
res.write('Internal Server Error')
return res.end()
}
if (source == null) {
res.statusCode = 404
res.write('Not Found')
return res.end()
}
const frameLine = parseInt(frame.lineNumber?.toString() ?? '', 10)
let frameColumn: number | null = parseInt(
frame.column?.toString() ?? '',
10
)
if (!frameColumn) {
frameColumn = null
}
let pos: NullableMappedPosition
try {
const consumer = await new SourceMapConsumer(source.map())
pos = consumer.originalPositionFor({
line: frameLine,
column: frameColumn,
})
consumer.destroy()
} catch (err) {
console.log('Failed to parse source map:', err)
res.statusCode = 500
res.write('Internal Server Error')
return res.end()
}
if (pos.source == null) {
res.statusCode = 404
res.write('Not Found')
return res.end()
}
const filePath = path.resolve(
options.rootDirectory,
pos.source.startsWith('webpack:///')
? pos.source.substring(11)
: pos.source
)
const fileContent: string | null = await fs
.readFile(filePath, 'utf-8')
.catch(() => null)
const originalFrame: StackFrame = {
file: fileContent
? path.relative(options.rootDirectory, filePath)
: pos.source,
lineNumber: pos.line,
column: pos.column,
methodName: frame.methodName, // TODO: resolve original method name (?)
arguments: [],
}
const originalCodeFrame: string | null =
fileContent && pos.line
? (codeFrameColumns(
fileContent,
{ start: { line: pos.line, column: pos.column } },
{ forceColor: true }
) as string)
: null
const o: OriginalStackFrameResponse = {
originalStackFrame: originalFrame,
originalCodeFrame,
}
res.statusCode = 200
res.setHeader('Content-Type', 'application/json')
res.write(Buffer.from(JSON.stringify(o)))
return res.end()
} else if (pathname === '/__nextjs_launch-editor') {
const frame = (query as unknown) as StackFrame
......
......@@ -4092,7 +4092,7 @@ buffer-equal-constant-time@1.0.1:
resolved "https://registry.yarnpkg.com/buffer-equal-constant-time/-/buffer-equal-constant-time-1.0.1.tgz#f8e71132f7ffe6e01a5c9697a4c6f3e48d5cc819"
integrity sha1-+OcRMvf/5uAaXJaXpMbz5I1cyBk=
buffer-from@^1.0.0:
buffer-from@^1.0.0, buffer-from@^1.1.1:
version "1.1.1"
resolved "https://registry.yarnpkg.com/buffer-from/-/buffer-from-1.1.1.tgz#32713bc028f75c02fdb710d7c7bcec1f2c6070ef"
integrity sha512-MQcXEUbCKtEo7bhqEs6560Hyd4XaovZlO/k9V3hjVUF/zwW7KBVdSK4gIt/bzwS9MbR5qob+F5jusZsb0YQK2A==
......@@ -5771,6 +5771,13 @@ dashdash@^1.12.0:
dependencies:
assert-plus "^1.0.0"
data-uri-to-buffer@3.0.0:
version "3.0.0"
resolved "https://registry.yarnpkg.com/data-uri-to-buffer/-/data-uri-to-buffer-3.0.0.tgz#8a3088a5efd3f53c3682343313c6895d498eb8d7"
integrity sha512-MJ6mFTZ+nPQO+39ua/ltwNePXrfdF3Ww0wP1Od7EePySXN1cP9XNqRQOG3FxTfipp8jx898LUCgBCEP11Qw/ZQ==
dependencies:
buffer-from "^1.1.1"
data-urls@^1.0.0:
version "1.1.0"
resolved "https://registry.yarnpkg.com/data-urls/-/data-urls-1.1.0.tgz#15ee0582baa5e22bb59c77140da8f9c76963bbfe"
......
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