Unverified Commit 231a942a authored by vercel-fleet-prod[bot]'s avatar vercel-fleet-prod[bot] Committed by GitHub

Don't block the dev overlay on the npm registry version check

Co-authored-by: 's avatarTobias Koppers <1365881+sokra@users.noreply.github.com>
parent 70e94d8e
...@@ -313,6 +313,10 @@ export function processMessage( ...@@ -313,6 +313,10 @@ export function processMessage(
dispatcher.onVulnerabilityInsight(message.hasVulnerabilityInsight) dispatcher.onVulnerabilityInsight(message.hasVulnerabilityInsight)
break break
} }
case HMR_MESSAGE_SENT_TO_BROWSER.VERSION_INFO: {
dispatcher.onVersionInfo(message.versionInfo)
break
}
case HMR_MESSAGE_SENT_TO_BROWSER.BUILT: case HMR_MESSAGE_SENT_TO_BROWSER.BUILT:
case HMR_MESSAGE_SENT_TO_BROWSER.SYNC: { case HMR_MESSAGE_SENT_TO_BROWSER.SYNC: {
dispatcher.buildingIndicatorHide() dispatcher.buildingIndicatorHide()
......
...@@ -302,6 +302,10 @@ function processMessage(message: HmrMessageSentToBrowser) { ...@@ -302,6 +302,10 @@ function processMessage(message: HmrMessageSentToBrowser) {
dispatcher.onVulnerabilityInsight(message.hasVulnerabilityInsight) dispatcher.onVulnerabilityInsight(message.hasVulnerabilityInsight)
break break
} }
case HMR_MESSAGE_SENT_TO_BROWSER.VERSION_INFO: {
dispatcher.onVersionInfo(message.versionInfo)
break
}
case HMR_MESSAGE_SENT_TO_BROWSER.BUILT: case HMR_MESSAGE_SENT_TO_BROWSER.BUILT:
case HMR_MESSAGE_SENT_TO_BROWSER.SYNC: { case HMR_MESSAGE_SENT_TO_BROWSER.SYNC: {
dispatcher.buildingIndicatorHide() dispatcher.buildingIndicatorHide()
......
...@@ -121,6 +121,7 @@ export function pageBootstrap(assetPrefix: string) { ...@@ -121,6 +121,7 @@ export function pageBootstrap(assetPrefix: string) {
case HMR_MESSAGE_SENT_TO_BROWSER.ISR_MANIFEST: case HMR_MESSAGE_SENT_TO_BROWSER.ISR_MANIFEST:
case HMR_MESSAGE_SENT_TO_BROWSER.DEVTOOLS_CONFIG: case HMR_MESSAGE_SENT_TO_BROWSER.DEVTOOLS_CONFIG:
case HMR_MESSAGE_SENT_TO_BROWSER.VULNERABILITY_INSIGHT: case HMR_MESSAGE_SENT_TO_BROWSER.VULNERABILITY_INSIGHT:
case HMR_MESSAGE_SENT_TO_BROWSER.VERSION_INFO:
case HMR_MESSAGE_SENT_TO_BROWSER.REACT_DEBUG_CHUNK: case HMR_MESSAGE_SENT_TO_BROWSER.REACT_DEBUG_CHUNK:
case HMR_MESSAGE_SENT_TO_BROWSER.REQUEST_CURRENT_ERROR_STATE: case HMR_MESSAGE_SENT_TO_BROWSER.REQUEST_CURRENT_ERROR_STATE:
case HMR_MESSAGE_SENT_TO_BROWSER.RUNTIME_ERRORS: case HMR_MESSAGE_SENT_TO_BROWSER.RUNTIME_ERRORS:
......
...@@ -26,6 +26,7 @@ import type ws from 'next/dist/compiled/ws' ...@@ -26,6 +26,7 @@ import type ws from 'next/dist/compiled/ws'
import type { DevToolsConfig } from '../../next-devtools/dev-overlay/shared' import type { DevToolsConfig } from '../../next-devtools/dev-overlay/shared'
import { isMiddlewareFilename } from '../../build/utils' import { isMiddlewareFilename } from '../../build/utils'
import type { VersionInfo } from './parse-version-info' import type { VersionInfo } from './parse-version-info'
import { getPendingVersionInfo } from './hot-reloader-shared-utils'
import type { import type {
HmrMessageSentToBrowser, HmrMessageSentToBrowser,
RuntimeErrorStateMessage, RuntimeErrorStateMessage,
...@@ -91,15 +92,25 @@ export class WebpackHotMiddleware { ...@@ -91,15 +92,25 @@ export class WebpackHotMiddleware {
null null
private serverLatestStats: { ts: number; stats: webpack.Stats } | null = null private serverLatestStats: { ts: number; stats: webpack.Stats } | null = null
private hasVulnerabilityInsight = false private hasVulnerabilityInsight = false
private versionInfo: VersionInfo = getPendingVersionInfo()
constructor( constructor(
compilers: webpack.Compiler[], compilers: webpack.Compiler[],
private versionInfo: VersionInfo, versionInfo: Promise<VersionInfo>,
private devtoolsFrontendUrl: string | undefined, private devtoolsFrontendUrl: string | undefined,
private config: NextConfigComplete, private config: NextConfigComplete,
private devToolsConfig: DevToolsConfig, private devToolsConfig: DevToolsConfig,
hasVulnerabilityInsight: Promise<boolean> hasVulnerabilityInsight: Promise<boolean>
) { ) {
// Clients that connected before the npm registry responded received the
// placeholder in `sync`. Later clients get the resolved info in `sync`.
versionInfo.then((resolvedVersionInfo) => {
this.versionInfo = resolvedVersionInfo
this.publish({
type: HMR_MESSAGE_SENT_TO_BROWSER.VERSION_INFO,
versionInfo: resolvedVersionInfo,
})
})
hasVulnerabilityInsight.then((enabled) => { hasVulnerabilityInsight.then((enabled) => {
if (enabled) { if (enabled) {
this.hasVulnerabilityInsight = true this.hasVulnerabilityInsight = true
......
...@@ -4,6 +4,19 @@ import { parseVersionInfo, type VersionInfo } from './parse-version-info' ...@@ -4,6 +4,19 @@ import { parseVersionInfo, type VersionInfo } from './parse-version-info'
export const matchNextPageBundleRequest = getPathMatch( export const matchNextPageBundleRequest = getPathMatch(
'/_next/static/chunks/pages/:path*.js(\\.map|)' '/_next/static/chunks/pages/:path*.js(\\.map|)'
) )
/**
* Version info to send while the npm registry request from `getVersionInfo()`
* is still pending. Never await that request before talking to the browser.
* A slow registry would otherwise delay the dev overlay.
*/
export function getPendingVersionInfo(): VersionInfo {
let installed = '0.0.0'
try {
installed = require('next/package.json').version
} catch {}
return { installed, staleness: 'unknown' }
}
export async function getVersionInfo(): Promise<VersionInfo> { export async function getVersionInfo(): Promise<VersionInfo> {
let installed = '0.0.0' let installed = '0.0.0'
......
...@@ -139,9 +139,11 @@ import { ...@@ -139,9 +139,11 @@ import {
setReactDebugChannelForHtmlRequest, setReactDebugChannelForHtmlRequest,
} from './debug-channel' } from './debug-channel'
import { import {
getPendingVersionInfo,
getVersionInfo, getVersionInfo,
matchNextPageBundleRequest, matchNextPageBundleRequest,
} from './hot-reloader-shared-utils' } from './hot-reloader-shared-utils'
import type { VersionInfo } from './parse-version-info'
import { getMcpMiddleware } from '../mcp/get-mcp-middleware' import { getMcpMiddleware } from '../mcp/get-mcp-middleware'
import { formatCompilationIssues } from '../mcp/tools/utils/format-compilation-issues' import { formatCompilationIssues } from '../mcp/tools/utils/format-compilation-issues'
import { import {
...@@ -1486,16 +1488,33 @@ export async function createHotReloaderTurbopack( ...@@ -1486,16 +1488,33 @@ export async function createHotReloaderTurbopack(
}) })
}) })
let versionInfoCached: ReturnType<typeof getVersionInfo> | undefined let resolvedVersionInfo: VersionInfo | undefined
// This fetch, even though not awaited, is not kicked off eagerly because the first `fetch()` in let versionInfoRequested = false
// This fetch is not kicked off eagerly because the first `fetch()` in
// Node.js adds roughly 20ms main-thread blocking to load the SSL certificate cache // Node.js adds roughly 20ms main-thread blocking to load the SSL certificate cache
// We don't want that blocking time to be in the hot path for the `ready in` logging. // We don't want that blocking time to be in the hot path for the `ready in` logging.
// Instead, the fetch is kicked off lazily when the first `getVersionInfoCached()` is called. // Instead, the fetch is kicked off lazily when `getCurrentVersionInfo()` is first called.
const getVersionInfoCached = (): ReturnType<typeof getVersionInfo> => { // The registry request is never awaited: until it resolves, clients get a
if (!versionInfoCached) { // placeholder in `sync`, and every connected client receives the resolved
versionInfoCached = getVersionInfo() // info in a `versionInfo` message. Otherwise a slow registry would delay
// `sync`, and with it the whole dev overlay.
const getCurrentVersionInfo = (): VersionInfo => {
if (!versionInfoRequested) {
versionInfoRequested = true
void getVersionInfo().then((versionInfo) => {
resolvedVersionInfo = versionInfo
for (const client of [
...clientsWithoutHtmlRequestId,
...clientsByHtmlRequestId.values(),
]) {
sendToClient(client, {
type: HMR_MESSAGE_SENT_TO_BROWSER.VERSION_INFO,
versionInfo,
})
}
})
} }
return versionInfoCached return resolvedVersionInfo ?? getPendingVersionInfo()
} }
let devtoolsFrontendUrl: string | undefined let devtoolsFrontendUrl: string | undefined
...@@ -1810,34 +1829,36 @@ export async function createHotReloaderTurbopack( ...@@ -1810,34 +1829,36 @@ export async function createHotReloaderTurbopack(
} }
sendToClient(client, turbopackConnectedMessage) sendToClient(client, turbopackConnectedMessage)
const errors: CompilationError[] = []
for (const entryIssues of currentEntryIssues.values()) {
for (const issue of entryIssues.values()) {
if (issue.severity !== 'warning') {
errors.push({
message: formatIssue(issue),
})
} else {
printNonFatalIssue(issue)
}
}
}
if (devIndicatorServerState.disabledUntil < Date.now()) { if (devIndicatorServerState.disabledUntil < Date.now()) {
devIndicatorServerState.disabledUntil = 0 devIndicatorServerState.disabledUntil = 0
} }
;(async function () { ;(async function () {
const versionInfo = await getVersionInfoCached()
const devToolsConfig = await getDevToolsConfig(distDir) const devToolsConfig = await getDevToolsConfig(distDir)
// Collect the issues only after the await so that `sync` reflects the
// current build state. Stale errors here would replace newer ones on
// the client.
const errors: CompilationError[] = []
for (const entryIssues of currentEntryIssues.values()) {
for (const issue of entryIssues.values()) {
if (issue.severity !== 'warning') {
errors.push({
message: formatIssue(issue),
})
} else {
printNonFatalIssue(issue)
}
}
}
const syncMessage: SyncMessage = { const syncMessage: SyncMessage = {
type: HMR_MESSAGE_SENT_TO_BROWSER.SYNC, type: HMR_MESSAGE_SENT_TO_BROWSER.SYNC,
errors, errors,
warnings: [], warnings: [],
hash: '', hash: '',
versionInfo, versionInfo: getCurrentVersionInfo(),
hasVulnerabilityInsight, hasVulnerabilityInsight,
debug: { debug: {
devtoolsFrontendUrl, devtoolsFrontendUrl,
......
...@@ -42,6 +42,7 @@ export const enum HMR_MESSAGE_SENT_TO_BROWSER { ...@@ -42,6 +42,7 @@ export const enum HMR_MESSAGE_SENT_TO_BROWSER {
DEV_INDICATOR = 'devIndicator', DEV_INDICATOR = 'devIndicator',
DEVTOOLS_CONFIG = 'devtoolsConfig', DEVTOOLS_CONFIG = 'devtoolsConfig',
VULNERABILITY_INSIGHT = 'vulnerabilityInsight', VULNERABILITY_INSIGHT = 'vulnerabilityInsight',
VERSION_INFO = 'versionInfo',
REQUEST_CURRENT_ERROR_STATE = 'requestCurrentErrorState', REQUEST_CURRENT_ERROR_STATE = 'requestCurrentErrorState',
RUNTIME_ERRORS = 'runtimeErrors', RUNTIME_ERRORS = 'runtimeErrors',
REQUEST_PAGE_METADATA = 'requestPageMetadata', REQUEST_PAGE_METADATA = 'requestPageMetadata',
...@@ -271,6 +272,17 @@ export interface VulnerabilityInsightMessage { ...@@ -271,6 +272,17 @@ export interface VulnerabilityInsightMessage {
hasVulnerabilityInsight: boolean hasVulnerabilityInsight: boolean
} }
/**
* Sent when the version staleness info resolves after the client already
* received a placeholder in the `sync` message. The npm registry request
* behind it is never awaited before `sync`, so a slow registry cannot delay
* the dev overlay.
*/
export interface VersionInfoMessage {
type: HMR_MESSAGE_SENT_TO_BROWSER.VERSION_INFO
versionInfo: VersionInfo
}
export type HmrMessageSentToBrowser = export type HmrMessageSentToBrowser =
| TurbopackMessage | TurbopackMessage
| TurbopackConnectedMessage | TurbopackConnectedMessage
...@@ -297,6 +309,7 @@ export type HmrMessageSentToBrowser = ...@@ -297,6 +309,7 @@ export type HmrMessageSentToBrowser =
| CacheIndicatorMessage | CacheIndicatorMessage
| RequestInsightsUpdateMessage | RequestInsightsUpdateMessage
| VulnerabilityInsightMessage | VulnerabilityInsightMessage
| VersionInfoMessage
export type BinaryHmrMessageSentToBrowser = Extract< export type BinaryHmrMessageSentToBrowser = Extract<
HmrMessageSentToBrowser, HmrMessageSentToBrowser,
......
...@@ -258,10 +258,9 @@ export default class HotReloaderWebpack implements NextJsHotReloaderInterface { ...@@ -258,10 +258,9 @@ export default class HotReloaderWebpack implements NextJsHotReloaderInterface {
private telemetry: Telemetry private telemetry: Telemetry
private resetFetch: () => void private resetFetch: () => void
private lockfile: Lockfile | undefined private lockfile: Lockfile | undefined
private versionInfo: VersionInfo = { // Resolves once the npm registry responds. Never awaited during start-up so a
staleness: 'unknown', // slow registry cannot delay the dev server or the dev overlay.
installed: '0.0.0', private versionInfo!: Promise<VersionInfo>
}
private devtoolsFrontendUrl: string | undefined private devtoolsFrontendUrl: string | undefined
private reloadAfterInvalidation: boolean = false private reloadAfterInvalidation: boolean = false
private isSrcDir: boolean private isSrcDir: boolean
...@@ -877,7 +876,7 @@ export default class HotReloaderWebpack implements NextJsHotReloaderInterface { ...@@ -877,7 +876,7 @@ export default class HotReloaderWebpack implements NextJsHotReloaderInterface {
const startSpan = this.hotReloaderSpan.traceChild('start') const startSpan = this.hotReloaderSpan.traceChild('start')
startSpan.stop() // Stop immediately to create an artificial parent span startSpan.stop() // Stop immediately to create an artificial parent span
this.versionInfo = await this.tracedGetVersionInfo(startSpan) this.versionInfo = this.tracedGetVersionInfo(startSpan)
const inspectorURLRaw = inspector.url() const inspectorURLRaw = inspector.url()
if (inspectorURLRaw !== undefined) { if (inspectorURLRaw !== undefined) {
......
import type { ReactNode } from 'react'
export default function Root({ children }: { children: ReactNode }) {
return (
<html>
<body>{children}</body>
</html>
)
}
export default function Page() {
return <p>hello world</p>
}
import { nextTestSetup, type Playwright } from 'e2e-utils'
import { getRedboxDescription, retry, waitForRedbox } from 'next-test-utils'
// The fixture's next.config.js makes the dev server's npm registry request
// (used for the version staleness indicator) hang until the test creates the
// `release-registry` marker file.
function getVersionStatus(browser: Playwright) {
return browser
.waitForElementByCss('.nextjs-container-build-error-version-status')
.text()
}
describe.each([
{
router: 'app router',
pathname: '/',
file: 'app/page.tsx',
content: 'hello world',
},
{
router: 'pages router',
pathname: '/pages-router',
file: 'pages/pages-router.tsx',
content: 'hello pages',
},
])(
'dev-overlay-pending-version-info ($router)',
({ pathname, file, content }) => {
const { next } = nextTestSetup({
files: __dirname,
})
it('shows build errors while the registry request is pending and updates the version once it resolves', async () => {
const browser = await next.browser(pathname)
expect(await browser.elementByCss('p').text()).toBe(content)
await next.patchFile(file, (source) =>
source!.replace(
'export default function Page',
"import 'does-not-exist'\n\nexport default function Page"
)
)
await waitForRedbox(browser)
expect(await getRedboxDescription(browser)).toBe(
"Module not found: Can't resolve 'does-not-exist'"
)
expect(await getVersionStatus(browser)).toContain('(unknown)')
await next.patchFile('release-registry', '')
await retry(async () => {
expect(await getVersionStatus(browser)).toContain('(outdated)')
}, 10_000)
// A late version update must not clear the current build error.
await waitForRedbox(browser)
expect(await getRedboxDescription(browser)).toBe(
"Module not found: Can't resolve 'does-not-exist'"
)
})
}
)
const fs = require('fs')
const path = require('path')
// Simulates an npm registry that does not respond: the dev server's
// version-staleness request hangs until the test creates the marker file.
// The fake dist-tags then mark the installed version as outdated.
const DIST_TAGS_URL = 'https://registry.npmjs.org/-/package/next/dist-tags'
const releaseMarker = path.join(__dirname, 'release-registry')
if (!globalThis.__hangingRegistryInstalled) {
globalThis.__hangingRegistryInstalled = true
const originalFetch = globalThis.fetch
globalThis.fetch = async function (input, init) {
const url =
typeof input === 'string' || input instanceof URL
? String(input)
: input.url
if (url !== DIST_TAGS_URL) {
return originalFetch.call(this, input, init)
}
while (!fs.existsSync(releaseMarker)) {
await new Promise((resolve) => setTimeout(resolve, 100))
}
return new Response(
JSON.stringify({ latest: '999.0.0', canary: '999.0.0-canary.0' }),
{ headers: { 'content-type': 'application/json' } }
)
}
}
/**
* @type {import('next').NextConfig}
*/
const nextConfig = {}
module.exports = nextConfig
export default function Page() {
return <p>hello pages</p>
}
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