Unverified Commit 440560fb authored by JJ Kasper's avatar JJ Kasper Committed by GitHub

Ensure config warnings only show once (#45142)

Since we now call `loadConfig()` in various processes our `execOnce`
handling isn't tracking when we have already shown warnings/logs in
another process so this adds a `silent` flag that we can leverage when
calling `loadConfig()`.

## Bug

- [x] Related issues linked using `fixes #number`
- [x] Integration tests added
- [ ] Errors have a helpful link attached, see
[`contributing.md`](https://github.com/vercel/next.js/blob/canary/contributing.md)

Fixes: [slack
thread](https://vercel.slack.com/archives/C03KAR5DCKC/p1674351677627259)
parent 70282b72
...@@ -35,7 +35,13 @@ const handleSessionStop = async () => { ...@@ -35,7 +35,13 @@ const handleSessionStop = async () => {
const { eventCliSession } = const { eventCliSession } =
require('../telemetry/events/session-stopped') as typeof import('../telemetry/events/session-stopped') require('../telemetry/events/session-stopped') as typeof import('../telemetry/events/session-stopped')
const config = await loadConfig(PHASE_DEVELOPMENT_SERVER, dir) const config = await loadConfig(
PHASE_DEVELOPMENT_SERVER,
dir,
undefined,
undefined,
true
)
let telemetry = let telemetry =
(traceGlobals.get('telemetry') as InstanceType< (traceGlobals.get('telemetry') as InstanceType<
...@@ -493,7 +499,13 @@ If you cannot make the changes above, but still want to try out\nNext.js v13 wit ...@@ -493,7 +499,13 @@ If you cannot make the changes above, but still want to try out\nNext.js v13 wit
cluster.settings.stdio = ['ipc', 'pipe', 'pipe'] cluster.settings.stdio = ['ipc', 'pipe', 'pipe']
setupFork() setupFork()
config = await loadConfig(PHASE_DEVELOPMENT_SERVER, dir) config = await loadConfig(
PHASE_DEVELOPMENT_SERVER,
dir,
undefined,
undefined,
true
)
const handleProjectDirRename = (newDir: string) => { const handleProjectDirRename = (newDir: string) => {
clusterExitUnsub() clusterExitUnsub()
......
...@@ -56,19 +56,22 @@ const experimentalWarning = execOnce( ...@@ -56,19 +56,22 @@ const experimentalWarning = execOnce(
} }
) )
export function setHttpClientAndAgentOptions(config: { export function setHttpClientAndAgentOptions(
config: {
httpAgentOptions?: NextConfig['httpAgentOptions'] httpAgentOptions?: NextConfig['httpAgentOptions']
experimental?: { experimental?: {
enableUndici?: boolean enableUndici?: boolean
} }
}) { },
silent = false
) {
if (isAboveNodejs16) { if (isAboveNodejs16) {
// Node.js 18 has undici built-in. // Node.js 18 has undici built-in.
if (config.experimental?.enableUndici && !isAboveNodejs18) { if (config.experimental?.enableUndici && !isAboveNodejs18) {
// When appDir is enabled undici is the default because of Response.clone() issues in node-fetch // When appDir is enabled undici is the default because of Response.clone() issues in node-fetch
;(globalThis as any).__NEXT_USE_UNDICI = config.experimental?.enableUndici ;(globalThis as any).__NEXT_USE_UNDICI = config.experimental?.enableUndici
} }
} else if (config.experimental?.enableUndici) { } else if (config.experimental?.enableUndici && !silent) {
Log.warn( Log.warn(
`\`enableUndici\` option requires Node.js v${NODE_16_VERSION} or greater. Falling back to \`node-fetch\`` `\`enableUndici\` option requires Node.js v${NODE_16_VERSION} or greater. Falling back to \`node-fetch\``
) )
...@@ -130,14 +133,17 @@ export function warnOptionHasBeenMovedOutOfExperimental( ...@@ -130,14 +133,17 @@ export function warnOptionHasBeenMovedOutOfExperimental(
config: NextConfig, config: NextConfig,
oldKey: string, oldKey: string,
newKey: string, newKey: string,
configFileName: string configFileName: string,
silent = false
) { ) {
if (config.experimental && oldKey in config.experimental) { if (config.experimental && oldKey in config.experimental) {
if (!silent) {
Log.warn( Log.warn(
`\`${oldKey}\` has been moved out of \`experimental\`` + `\`${oldKey}\` has been moved out of \`experimental\`` +
(newKey.includes('.') ? ` and into \`${newKey}\`` : '') + (newKey.includes('.') ? ` and into \`${newKey}\`` : '') +
`. Please update your ${configFileName} file accordingly.` `. Please update your ${configFileName} file accordingly.`
) )
}
let current = config let current = config
const newKeys = newKey.split('.') const newKeys = newKey.split('.')
...@@ -152,9 +158,13 @@ export function warnOptionHasBeenMovedOutOfExperimental( ...@@ -152,9 +158,13 @@ export function warnOptionHasBeenMovedOutOfExperimental(
return config return config
} }
function assignDefaults(dir: string, userConfig: { [key: string]: any }) { function assignDefaults(
dir: string,
userConfig: { [key: string]: any },
silent = false
) {
const configFileName = userConfig.configFileName const configFileName = userConfig.configFileName
if (typeof userConfig.exportTrailingSlash !== 'undefined') { if (!silent && typeof userConfig.exportTrailingSlash !== 'undefined') {
console.warn( console.warn(
chalk.yellow.bold('Warning: ') + chalk.yellow.bold('Warning: ') +
`The "exportTrailingSlash" option has been renamed to "trailingSlash". Please update your ${configFileName}.` `The "exportTrailingSlash" option has been renamed to "trailingSlash". Please update your ${configFileName}.`
...@@ -200,7 +210,7 @@ function assignDefaults(dir: string, userConfig: { [key: string]: any }) { ...@@ -200,7 +210,7 @@ function assignDefaults(dir: string, userConfig: { [key: string]: any }) {
} }
} }
if (enabledExperiments.length > 0) { if (!silent && enabledExperiments.length > 0) {
experimentalWarning(configFileName, enabledExperiments) experimentalWarning(configFileName, enabledExperiments)
} }
} }
...@@ -572,43 +582,52 @@ function assignDefaults(dir: string, userConfig: { [key: string]: any }) { ...@@ -572,43 +582,52 @@ function assignDefaults(dir: string, userConfig: { [key: string]: any }) {
result, result,
'relay', 'relay',
'compiler.relay', 'compiler.relay',
configFileName configFileName,
silent
) )
warnOptionHasBeenMovedOutOfExperimental( warnOptionHasBeenMovedOutOfExperimental(
result, result,
'styledComponents', 'styledComponents',
'compiler.styledComponents', 'compiler.styledComponents',
configFileName configFileName,
silent
) )
warnOptionHasBeenMovedOutOfExperimental( warnOptionHasBeenMovedOutOfExperimental(
result, result,
'emotion', 'emotion',
'compiler.emotion', 'compiler.emotion',
configFileName configFileName,
silent
) )
warnOptionHasBeenMovedOutOfExperimental( warnOptionHasBeenMovedOutOfExperimental(
result, result,
'reactRemoveProperties', 'reactRemoveProperties',
'compiler.reactRemoveProperties', 'compiler.reactRemoveProperties',
configFileName configFileName,
silent
) )
warnOptionHasBeenMovedOutOfExperimental( warnOptionHasBeenMovedOutOfExperimental(
result, result,
'removeConsole', 'removeConsole',
'compiler.removeConsole', 'compiler.removeConsole',
configFileName configFileName,
silent
) )
if (result.experimental?.swcMinifyDebugOptions) { if (result.experimental?.swcMinifyDebugOptions) {
if (!silent) {
Log.warn( Log.warn(
'SWC minify debug option specified. This option is for debugging minifier issues and will be removed once SWC minifier is stable.' 'SWC minify debug option specified. This option is for debugging minifier issues and will be removed once SWC minifier is stable.'
) )
} }
}
if ((result.experimental as any).outputStandalone) { if ((result.experimental as any).outputStandalone) {
if (!silent) {
Log.warn( Log.warn(
`experimental.outputStandalone has been renamed to "output: 'standalone'", please move the config.` `experimental.outputStandalone has been renamed to "output: 'standalone'", please move the config.`
) )
}
result.output = 'standalone' result.output = 'standalone'
} }
...@@ -616,19 +635,22 @@ function assignDefaults(dir: string, userConfig: { [key: string]: any }) { ...@@ -616,19 +635,22 @@ function assignDefaults(dir: string, userConfig: { [key: string]: any }) {
result, result,
'transpilePackages', 'transpilePackages',
'transpilePackages', 'transpilePackages',
configFileName configFileName,
silent
) )
warnOptionHasBeenMovedOutOfExperimental( warnOptionHasBeenMovedOutOfExperimental(
result, result,
'skipMiddlewareUrlNormalize', 'skipMiddlewareUrlNormalize',
'skipMiddlewareUrlNormalize', 'skipMiddlewareUrlNormalize',
configFileName configFileName,
silent
) )
warnOptionHasBeenMovedOutOfExperimental( warnOptionHasBeenMovedOutOfExperimental(
result, result,
'skipTrailingSlashRedirect', 'skipTrailingSlashRedirect',
'skipTrailingSlashRedirect', 'skipTrailingSlashRedirect',
configFileName configFileName,
silent
) )
if ( if (
...@@ -638,19 +660,23 @@ function assignDefaults(dir: string, userConfig: { [key: string]: any }) { ...@@ -638,19 +660,23 @@ function assignDefaults(dir: string, userConfig: { [key: string]: any }) {
result.experimental.outputFileTracingRoot = resolve( result.experimental.outputFileTracingRoot = resolve(
result.experimental.outputFileTracingRoot result.experimental.outputFileTracingRoot
) )
if (!silent) {
Log.warn( Log.warn(
`experimental.outputFileTracingRoot should be absolute, using: ${result.experimental.outputFileTracingRoot}` `experimental.outputFileTracingRoot should be absolute, using: ${result.experimental.outputFileTracingRoot}`
) )
} }
}
if (result.output === 'standalone' && !result.outputFileTracing) { if (result.output === 'standalone' && !result.outputFileTracing) {
if (!silent) {
Log.warn( Log.warn(
`"output: 'standalone'" requires outputFileTracing not be disabled please enable it to leverage the standalone build` `"output: 'standalone'" requires outputFileTracing not be disabled please enable it to leverage the standalone build`
) )
}
result.output = undefined result.output = undefined
} }
setHttpClientAndAgentOptions(result || defaultConfig) setHttpClientAndAgentOptions(result || defaultConfig, silent)
if (result.i18n) { if (result.i18n) {
const { i18n } = result const { i18n } = result
...@@ -668,7 +694,7 @@ function assignDefaults(dir: string, userConfig: { [key: string]: any }) { ...@@ -668,7 +694,7 @@ function assignDefaults(dir: string, userConfig: { [key: string]: any }) {
) )
} }
if (i18n.locales.length > 100) { if (i18n.locales.length > 100 && !silent) {
Log.warn( Log.warn(
`Received ${i18n.locales.length} i18n.locales items which exceeds the recommended max of 100.\nSee more info here: https://nextjs.org/docs/advanced-features/i18n-routing#how-does-this-work-with-static-generation` `Received ${i18n.locales.length} i18n.locales items which exceeds the recommended max of 100.\nSee more info here: https://nextjs.org/docs/advanced-features/i18n-routing#how-does-this-work-with-static-generation`
) )
...@@ -700,7 +726,7 @@ function assignDefaults(dir: string, userConfig: { [key: string]: any }) { ...@@ -700,7 +726,7 @@ function assignDefaults(dir: string, userConfig: { [key: string]: any }) {
altItem.domain !== item.domain altItem.domain !== item.domain
) )
if (defaultLocaleDuplicate) { if (!silent && defaultLocaleDuplicate) {
console.warn( console.warn(
`Both ${item.domain} and ${defaultLocaleDuplicate.domain} configured the defaultLocale ${item.defaultLocale} but only one can. Change one item's default locale to continue` `Both ${item.domain} and ${defaultLocaleDuplicate.domain} configured the defaultLocale ${item.defaultLocale} but only one can. Change one item's default locale to continue`
) )
...@@ -830,9 +856,18 @@ export default async function loadConfig( ...@@ -830,9 +856,18 @@ export default async function loadConfig(
phase: string, phase: string,
dir: string, dir: string,
customConfig?: object | null, customConfig?: object | null,
rawConfig?: boolean rawConfig?: boolean,
silent?: boolean
): Promise<NextConfigComplete> { ): Promise<NextConfigComplete> {
await loadEnvConfig(dir, phase === PHASE_DEVELOPMENT_SERVER, Log) const curLog = silent
? {
warn: () => {},
info: () => {},
error: () => {},
}
: Log
await loadEnvConfig(dir, phase === PHASE_DEVELOPMENT_SERVER, curLog)
if (!customConfig) { if (!customConfig) {
loadWebpackHook() loadWebpackHook()
...@@ -841,11 +876,15 @@ export default async function loadConfig( ...@@ -841,11 +876,15 @@ export default async function loadConfig(
let configFileName = 'next.config.js' let configFileName = 'next.config.js'
if (customConfig) { if (customConfig) {
return assignDefaults(dir, { return assignDefaults(
dir,
{
configOrigin: 'server', configOrigin: 'server',
configFileName, configFileName,
...customConfig, ...customConfig,
}) as NextConfigComplete },
silent
) as NextConfigComplete
} }
const path = await findUp(CONFIG_FILES, { cwd: dir }) const path = await findUp(CONFIG_FILES, { cwd: dir })
...@@ -872,7 +911,7 @@ export default async function loadConfig( ...@@ -872,7 +911,7 @@ export default async function loadConfig(
return userConfigModule return userConfigModule
} }
} catch (err) { } catch (err) {
Log.error( curLog.error(
`Failed to load ${configFileName}, see more info here https://nextjs.org/docs/messages/next-config-error` `Failed to load ${configFileName}, see more info here https://nextjs.org/docs/messages/next-config-error`
) )
throw err throw err
...@@ -884,8 +923,8 @@ export default async function loadConfig( ...@@ -884,8 +923,8 @@ export default async function loadConfig(
const validateResult = validateConfig(userConfig) const validateResult = validateConfig(userConfig)
if (validateResult.errors) { if (!silent && validateResult.errors) {
Log.warn(`Invalid next.config.js options detected: `) curLog.warn(`Invalid next.config.js options detected: `)
// Only load @segment/ajv-human-errors when invalid config is detected // Only load @segment/ajv-human-errors when invalid config is detected
const { AggregateAjvError } = const { AggregateAjvError } =
...@@ -903,7 +942,7 @@ export default async function loadConfig( ...@@ -903,7 +942,7 @@ export default async function loadConfig(
} }
if (Object.keys(userConfig).length === 0) { if (Object.keys(userConfig).length === 0) {
Log.warn( curLog.warn(
`Detected ${configFileName}, no exported configuration found. https://nextjs.org/docs/messages/empty-configuration` `Detected ${configFileName}, no exported configuration found. https://nextjs.org/docs/messages/empty-configuration`
) )
} }
...@@ -924,12 +963,16 @@ export default async function loadConfig( ...@@ -924,12 +963,16 @@ export default async function loadConfig(
: canonicalBase) || '' : canonicalBase) || ''
} }
const completeConfig = assignDefaults(dir, { const completeConfig = assignDefaults(
dir,
{
configOrigin: relative(dir, path), configOrigin: relative(dir, path),
configFile: path, configFile: path,
configFileName, configFileName,
...userConfig, ...userConfig,
}) as NextConfigComplete },
silent
) as NextConfigComplete
setFontLoaderDefaults(completeConfig) setFontLoaderDefaults(completeConfig)
return completeConfig return completeConfig
} else { } else {
...@@ -956,10 +999,11 @@ export default async function loadConfig( ...@@ -956,10 +999,11 @@ export default async function loadConfig(
// reactRoot can be updated correctly even with no next.config.js // reactRoot can be updated correctly even with no next.config.js
const completeConfig = assignDefaults( const completeConfig = assignDefaults(
dir, dir,
defaultConfig defaultConfig,
silent
) as NextConfigComplete ) as NextConfigComplete
completeConfig.configFileName = configFileName completeConfig.configFileName = configFileName
setHttpClientAndAgentOptions(completeConfig) setHttpClientAndAgentOptions(completeConfig, silent)
setFontLoaderDefaults(completeConfig) setFontLoaderDefaults(completeConfig)
return completeConfig return completeConfig
} }
...@@ -20,7 +20,13 @@ import { PHASE_DEVELOPMENT_SERVER } from '../shared/lib/constants' ...@@ -20,7 +20,13 @@ import { PHASE_DEVELOPMENT_SERVER } from '../shared/lib/constants'
} }
dir = getProjectDir(dir) dir = getProjectDir(dir)
const config = await loadConfig(PHASE_DEVELOPMENT_SERVER, dir) const config = await loadConfig(
PHASE_DEVELOPMENT_SERVER,
dir,
undefined,
undefined,
true
)
const distDir = path.join(dir, config.distDir || '.next') const distDir = path.join(dir, config.distDir || '.next')
const eventsPath = path.join(distDir, '_events.json') const eventsPath = path.join(distDir, '_events.json')
......
...@@ -247,7 +247,7 @@ export class Telemetry { ...@@ -247,7 +247,7 @@ export class Telemetry {
JSON.stringify(allEvents) JSON.stringify(allEvents)
) )
spawn(process.execPath, [require.resolve('./deteched-flush'), mode, dir], { spawn(process.execPath, [require.resolve('./detached-flush'), mode, dir], {
detached: !this.NEXT_TELEMETRY_DEBUG, detached: !this.NEXT_TELEMETRY_DEBUG,
windowsHide: true, windowsHide: true,
shell: false, shell: false,
......
...@@ -2,6 +2,7 @@ import { createNextDescribe } from 'e2e-utils' ...@@ -2,6 +2,7 @@ import { createNextDescribe } from 'e2e-utils'
import crypto from 'crypto' import crypto from 'crypto'
import { check, getRedboxHeader, hasRedbox, waitFor } from 'next-test-utils' import { check, getRedboxHeader, hasRedbox, waitFor } from 'next-test-utils'
import cheerio from 'cheerio' import cheerio from 'cheerio'
import stripAnsi from 'strip-ansi'
createNextDescribe( createNextDescribe(
'app dir', 'app dir',
...@@ -15,6 +16,22 @@ createNextDescribe( ...@@ -15,6 +16,22 @@ createNextDescribe(
}, },
}, },
({ next, isNextDev: isDev, isNextStart, isNextDeploy }) => { ({ next, isNextDev: isDev, isNextStart, isNextDeploy }) => {
if (isDev) {
it('should not have duplicate config warnings', async () => {
await next.fetch('/')
expect(
stripAnsi(next.cliOutput).match(
/You have enabled experimental feature/g
).length
).toBe(1)
expect(
stripAnsi(next.cliOutput).match(
/Experimental features are not covered by semver/g
).length
).toBe(1)
})
}
if (!isNextDeploy) { if (!isNextDeploy) {
it('should not share edge workers', async () => { it('should not share edge workers', async () => {
const controller1 = new AbortController() const controller1 = new AbortController()
......
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