Unverified Commit 1ebc9bbb authored by Jan Potoms's avatar Jan Potoms Committed by GitHub

Load next.config.js async (#22578)

Just the conversion of config loading from sync to async from https://github.com/vercel/next.js/pull/22153

cc @Timer 
parent a289d380
......@@ -125,8 +125,9 @@ export default async function build(
loadEnvConfig(dir, false, Log)
)
const config = traceFn(tracer.startSpan('load-next-config'), () =>
loadConfig(PHASE_PRODUCTION_BUILD, dir, conf)
const config = await traceAsyncFn(
tracer.startSpan('load-next-config'),
() => loadConfig(PHASE_PRODUCTION_BUILD, dir, conf)
)
const { target } = config
const buildId = await traceAsyncFn(
......
......@@ -148,9 +148,9 @@ export default async function exportApp(
const nextConfig =
configuration ||
traceFn(tracer.startSpan('load-next-config'), () =>
(await traceAsyncFn(tracer.startSpan('load-next-config'), () =>
loadConfig(PHASE_EXPORT, dir)
)
))
const threads = options.threads || Math.max(cpus().length - 1, 1)
const distDir = join(dir, nextConfig.distDir)
......
......@@ -487,7 +487,7 @@ export function normalizeConfig(phase: string, config: any) {
return config
}
export default function loadConfig(
export default async function loadConfig(
phase: string,
dir: string,
customConfig?: object | null
......@@ -495,9 +495,8 @@ export default function loadConfig(
if (customConfig) {
return assignDefaults({ configOrigin: 'server', ...customConfig })
}
const path = findUp.sync(CONFIG_FILE, {
cwd: dir,
})
const path = await findUp(CONFIG_FILE, { cwd: dir })
// If config file was found
if (path?.length) {
......
......@@ -27,7 +27,6 @@ import {
CLIENT_STATIC_FILES_RUNTIME,
PAGES_MANIFEST,
PERMANENT_REDIRECT_STATUS,
PHASE_PRODUCTION_SERVER,
PRERENDER_MANIFEST,
ROUTES_MANIFEST,
SERVERLESS_DIRECTORY,
......@@ -50,11 +49,7 @@ import {
tryGetPreviewData,
__ApiPreviewProps,
} from './api-utils'
import loadConfig, {
DomainLocales,
isTargetLikeServerless,
NextConfig,
} from './config'
import { DomainLocales, isTargetLikeServerless, NextConfig } from './config'
import pathMatch from '../lib/router/utils/path-match'
import { recursiveReadDirSync } from './lib/recursive-readdir-sync'
import { loadComponents, LoadComponentsReturnType } from './load-components'
......@@ -173,17 +168,16 @@ export default class Server {
public constructor({
dir = '.',
quiet = false,
conf = null,
conf,
dev = false,
minimalMode = false,
customServer = true,
}: ServerConstructor & { minimalMode?: boolean } = {}) {
}: ServerConstructor & { conf: NextConfig; minimalMode?: boolean }) {
this.dir = resolve(dir)
this.quiet = quiet
const phase = this.currentPhase()
loadEnvConfig(this.dir, dev, Log)
this.nextConfig = loadConfig(phase, this.dir, conf)
this.nextConfig = conf
this.distDir = join(this.dir, this.nextConfig.distDir)
this.publicDir = join(this.dir, CLIENT_PUBLIC_FILES_PATH)
this.hasStaticDir = !minimalMode && fs.existsSync(join(this.dir, 'static'))
......@@ -293,10 +287,6 @@ export default class Server {
}
}
protected currentPhase(): string {
return PHASE_PRODUCTION_SERVER
}
public logError(err: Error): void {
if (this.onErrorMiddleware) {
this.onErrorMiddleware({ err })
......
......@@ -11,7 +11,7 @@ export default async function start(
customServer: false,
})
const srv = http.createServer(app.getRequestHandler())
await new Promise((resolve, reject) => {
await new Promise<void>((resolve, reject) => {
// This code catches EADDRINUSE error if the port is already in use
srv.on('error', reject)
srv.on('listening', () => resolve())
......
......@@ -38,6 +38,7 @@ import HotReloader from './hot-reloader'
import { findPageFile } from './lib/find-page-file'
import { getNodeOptionsWithoutInspect } from './lib/utils'
import { withCoalescedInvoke } from '../lib/coalesced-function'
import { NextConfig } from '../next-server/server/config'
if (typeof React.Suspense === 'undefined') {
throw new Error(
......@@ -57,7 +58,12 @@ export default class DevServer extends Server {
loadStaticPaths: typeof import('./static-paths-worker').loadStaticPaths
}
constructor(options: ServerConstructor & { isNextDevCommand?: boolean }) {
constructor(
options: ServerConstructor & {
conf: NextConfig
isNextDevCommand?: boolean
}
) {
super({ ...options, dev: true })
this.renderOpts.dev = true
;(this.renderOpts as any).ErrorDebug = ReactDevOverlay
......@@ -116,10 +122,6 @@ export default class DevServer extends Server {
this.staticPathsWorker.getStderr().pipe(process.stderr)
}
protected currentPhase(): string {
return PHASE_DEVELOPMENT_SERVER
}
protected readBuildId(): string {
return 'development'
}
......
import Server, { ServerConstructor } from '../next-server/server/next-server'
import { NON_STANDARD_NODE_ENV } from '../lib/constants'
import * as log from '../build/output/log'
import loadConfig, { NextConfig } from '../next-server/server/config'
import { resolve } from 'path'
import {
PHASE_DEVELOPMENT_SERVER,
PHASE_PRODUCTION_SERVER,
} from '../next-server/lib/constants'
import { IncomingMessage, ServerResponse } from 'http'
import { UrlWithParsedQuery } from 'url'
type NextServerConstructor = ServerConstructor & {
/**
......@@ -9,8 +17,133 @@ type NextServerConstructor = ServerConstructor & {
dev?: boolean
}
export class NextServer {
private serverPromise?: Promise<Server>
private server?: Server
private reqHandlerPromise?: Promise<any>
private preparedAssetPrefix?: string
options: NextServerConstructor
constructor(options: NextServerConstructor) {
this.options = options
}
getRequestHandler() {
return async (
req: IncomingMessage,
res: ServerResponse,
parsedUrl?: UrlWithParsedQuery
) => {
const requestHandler = await this.getServerRequestHandler()
return requestHandler(req, res, parsedUrl)
}
}
setAssetPrefix(assetPrefix: string) {
if (this.server) {
this.server.setAssetPrefix(assetPrefix)
} else {
this.preparedAssetPrefix = assetPrefix
}
}
logError(...args: Parameters<Server['logError']>) {
if (this.server) {
this.server.logError(...args)
}
}
async render(...args: Parameters<Server['render']>) {
const server = await this.getServer()
return server.render(...args)
}
async renderToHTML(...args: Parameters<Server['renderToHTML']>) {
const server = await this.getServer()
return server.renderToHTML(...args)
}
async renderError(...args: Parameters<Server['renderError']>) {
const server = await this.getServer()
return server.renderError(...args)
}
async renderErrorToHTML(...args: Parameters<Server['renderErrorToHTML']>) {
const server = await this.getServer()
return server.renderErrorToHTML(...args)
}
async render404(...args: Parameters<Server['render404']>) {
const server = await this.getServer()
return server.render404(...args)
}
async serveStatic(...args: Parameters<Server['serveStatic']>) {
const server = await this.getServer()
return server.serveStatic(...args)
}
async prepare() {
const server = await this.getServer()
return server.prepare()
}
async close() {
const server = await this.getServer()
return (server as any).close()
}
private createServer(
options: NextServerConstructor & {
conf: NextConfig
isNextDevCommand?: boolean
}
): Server {
if (options.dev) {
const DevServer = require('./next-dev-server').default
return new DevServer(options)
}
return new Server(options)
}
private async loadConfig() {
const phase = this.options.dev
? PHASE_DEVELOPMENT_SERVER
: PHASE_PRODUCTION_SERVER
const dir = resolve(this.options.dir || '.')
const conf = await loadConfig(phase, dir, this.options.conf)
return conf
}
private async getServer() {
if (!this.serverPromise) {
this.serverPromise = this.loadConfig().then(async (conf) => {
this.server = this.createServer({
...this.options,
conf,
})
if (this.preparedAssetPrefix) {
this.server.setAssetPrefix(this.preparedAssetPrefix)
}
return this.server
})
}
return this.serverPromise
}
private async getServerRequestHandler() {
// Memoize request handler creation
if (!this.reqHandlerPromise) {
this.reqHandlerPromise = this.getServer().then((server) =>
server.getRequestHandler().bind(server)
)
}
return this.reqHandlerPromise
}
}
// This file is used for when users run `require('next')`
function createServer(options: NextServerConstructor): Server {
function createServer(options: NextServerConstructor): NextServer {
const standardEnv = ['production', 'development', 'test']
if (options == null) {
......@@ -33,12 +166,9 @@ function createServer(options: NextServerConstructor): Server {
"Warning: 'dev' is not a boolean which could introduce unexpected behavior. https://err.sh/next.js/invalid-server-options"
)
}
const DevServer = require('./next-dev-server').default
return new DevServer(options)
}
return new Server(options)
return new NextServer(options)
}
// Support commonjs `require('next')`
......
......@@ -89,7 +89,7 @@ describe('CLI Usage', () => {
test('should exit when SIGINT is signalled', async () => {
const killSigint = (instance) =>
setTimeout(() => instance.kill('SIGINT'), 500)
setTimeout(() => instance.kill('SIGINT'), 1000)
const { code, signal } = await runNextCommand(['build', dir], {
ignoreFail: true,
instance: killSigint,
......@@ -103,7 +103,7 @@ describe('CLI Usage', () => {
})
test('should exit when SIGTERM is signalled', async () => {
const killSigterm = (instance) =>
setTimeout(() => instance.kill('SIGTERM'), 500)
setTimeout(() => instance.kill('SIGTERM'), 1000)
const { code, signal } = await runNextCommand(['build', dir], {
ignoreFail: true,
instance: killSigterm,
......@@ -294,7 +294,7 @@ describe('CLI Usage', () => {
test('should exit when SIGINT is signalled', async () => {
const killSigint = (instance) =>
setTimeout(() => instance.kill('SIGINT'), 500)
setTimeout(() => instance.kill('SIGINT'), 1000)
const port = await findPort()
const { code, signal } = await runNextCommand(['dev', dir, '-p', port], {
ignoreFail: true,
......@@ -309,7 +309,7 @@ describe('CLI Usage', () => {
})
test('should exit when SIGTERM is signalled', async () => {
const killSigterm = (instance) =>
setTimeout(() => instance.kill('SIGTERM'), 500)
setTimeout(() => instance.kill('SIGTERM'), 1000)
const port = await findPort()
const { code, signal } = await runNextCommand(['dev', dir, '-p', port], {
ignoreFail: true,
......@@ -478,7 +478,7 @@ describe('CLI Usage', () => {
test('should exit when SIGINT is signalled', async () => {
const killSigint = (instance) =>
setTimeout(() => instance.kill('SIGINT'), 500)
setTimeout(() => instance.kill('SIGINT'), 1000)
await nextBuild(dir)
const port = await findPort()
const { code, signal } = await runNextCommand(
......@@ -497,7 +497,7 @@ describe('CLI Usage', () => {
})
test('should exit when SIGTERM is signalled', async () => {
const killSigterm = (instance) =>
setTimeout(() => instance.kill('SIGTERM'), 500)
setTimeout(() => instance.kill('SIGTERM'), 1000)
await nextBuild(dir)
const port = await findPort()
const { code, signal } = await runNextCommand(
......
......@@ -6,12 +6,13 @@ jest.setTimeout(1000 * 60 * 5)
describe('Production Usage without production build', () => {
it('should show error when there is no production build', async () => {
expect(() => {
nextServer({
await expect(async () => {
const srv = nextServer({
dir: appDir,
dev: false,
quiet: true,
})
}).toThrow(/Could not find a production build in the/)
await srv.prepare()
}).rejects.toThrow(/Could not find a production build in the/)
})
})
......@@ -4,7 +4,7 @@ import http from 'http'
import fs from 'fs-extra'
import { join } from 'path'
import cheerio from 'cheerio'
import Server from 'next/dist/next-server/server/next-server'
import { nextServer } from 'next-test-utils'
import {
fetchViaHTTP,
findPort,
......@@ -47,7 +47,7 @@ describe('Required Server Files', () => {
}
await fs.rename(join(appDir, 'pages'), join(appDir, 'pages-bak'))
nextApp = new Server({
nextApp = nextServer({
conf: {},
dir: appDir,
quiet: false,
......
......@@ -8,41 +8,41 @@ const pathToConfig = join(__dirname, '_resolvedata', 'without-function')
const pathToConfigFn = join(__dirname, '_resolvedata', 'with-function')
describe('config', () => {
it('Should get the configuration', () => {
const config = loadConfig(PHASE_DEVELOPMENT_SERVER, pathToConfig)
it('Should get the configuration', async () => {
const config = await loadConfig(PHASE_DEVELOPMENT_SERVER, pathToConfig)
expect(config.customConfig).toBe(true)
})
it('Should pass the phase correctly', () => {
const config = loadConfig(PHASE_DEVELOPMENT_SERVER, pathToConfigFn)
it('Should pass the phase correctly', async () => {
const config = await loadConfig(PHASE_DEVELOPMENT_SERVER, pathToConfigFn)
expect(config.phase).toBe(PHASE_DEVELOPMENT_SERVER)
})
it('Should pass the defaultConfig correctly', () => {
const config = loadConfig(PHASE_DEVELOPMENT_SERVER, pathToConfigFn)
it('Should pass the defaultConfig correctly', async () => {
const config = await loadConfig(PHASE_DEVELOPMENT_SERVER, pathToConfigFn)
expect(config.defaultConfig).toBeDefined()
})
it('Should assign object defaults deeply to user config', () => {
const config = loadConfig(PHASE_DEVELOPMENT_SERVER, pathToConfigFn)
it('Should assign object defaults deeply to user config', async () => {
const config = await loadConfig(PHASE_DEVELOPMENT_SERVER, pathToConfigFn)
expect(config.distDir).toEqual('.next')
expect(config.onDemandEntries.maxInactiveAge).toBeDefined()
})
it('Should pass the customConfig correctly', () => {
const config = loadConfig(PHASE_DEVELOPMENT_SERVER, null, {
it('Should pass the customConfig correctly', async () => {
const config = await loadConfig(PHASE_DEVELOPMENT_SERVER, null, {
customConfig: true,
})
expect(config.customConfig).toBe(true)
})
it('Should not pass the customConfig when it is null', () => {
const config = loadConfig(PHASE_DEVELOPMENT_SERVER, null, null)
it('Should not pass the customConfig when it is null', async () => {
const config = await loadConfig(PHASE_DEVELOPMENT_SERVER, null, null)
expect(config.webpack).toBe(null)
})
it('Should assign object defaults deeply to customConfig', () => {
const config = loadConfig(PHASE_DEVELOPMENT_SERVER, null, {
it('Should assign object defaults deeply to customConfig', async () => {
const config = await loadConfig(PHASE_DEVELOPMENT_SERVER, null, {
customConfig: true,
onDemandEntries: { custom: true },
})
......@@ -50,66 +50,67 @@ describe('config', () => {
expect(config.onDemandEntries.maxInactiveAge).toBeDefined()
})
it('Should allow setting objects which do not have defaults', () => {
const config = loadConfig(PHASE_DEVELOPMENT_SERVER, null, {
it('Should allow setting objects which do not have defaults', async () => {
const config = await loadConfig(PHASE_DEVELOPMENT_SERVER, null, {
bogusSetting: { custom: true },
})
expect(config.bogusSetting).toBeDefined()
expect(config.bogusSetting.custom).toBe(true)
})
it('Should override defaults for arrays from user arrays', () => {
const config = loadConfig(PHASE_DEVELOPMENT_SERVER, null, {
it('Should override defaults for arrays from user arrays', async () => {
const config = await loadConfig(PHASE_DEVELOPMENT_SERVER, null, {
pageExtensions: ['.bogus'],
})
expect(config.pageExtensions).toEqual(['.bogus'])
})
it('Should throw when an invalid target is provided', () => {
expect(() => {
loadConfig(
it('Should throw when an invalid target is provided', async () => {
await expect(async () => {
await loadConfig(
PHASE_DEVELOPMENT_SERVER,
join(__dirname, '_resolvedata', 'invalid-target')
)
}).toThrow(/Specified target is invalid/)
}).rejects.toThrow(/Specified target is invalid/)
})
it('Should pass when a valid target is provided', () => {
const config = loadConfig(
it('Should pass when a valid target is provided', async () => {
const config = await loadConfig(
PHASE_DEVELOPMENT_SERVER,
join(__dirname, '_resolvedata', 'valid-target')
)
expect(config.target).toBe('serverless')
})
it('Should throw an error when next.config.js is not present', () => {
expect(() =>
loadConfig(
PHASE_DEVELOPMENT_SERVER,
join(__dirname, '_resolvedata', 'typescript-config')
)
).toThrow(
it('Should throw an error when next.config.js is not present', async () => {
await expect(
async () =>
await loadConfig(
PHASE_DEVELOPMENT_SERVER,
join(__dirname, '_resolvedata', 'typescript-config')
)
).rejects.toThrow(
/Configuring Next.js via .+ is not supported. Please replace the file with 'next.config.js'/
)
})
it('Should not throw an error when two versions of next.config.js are present', () => {
const config = loadConfig(
it('Should not throw an error when two versions of next.config.js are present', async () => {
const config = await loadConfig(
PHASE_DEVELOPMENT_SERVER,
join(__dirname, '_resolvedata', 'js-ts-config')
)
expect(config.__test__ext).toBe('js')
})
it('Should ignore configs set to `undefined`', () => {
const config = loadConfig(PHASE_DEVELOPMENT_SERVER, null, {
it('Should ignore configs set to `undefined`', async () => {
const config = await loadConfig(PHASE_DEVELOPMENT_SERVER, null, {
target: undefined,
})
expect(config.target).toBe('server')
})
it('Should ignore configs set to `null`', () => {
const config = loadConfig(PHASE_DEVELOPMENT_SERVER, null, {
it('Should ignore configs set to `null`', async () => {
const config = await loadConfig(PHASE_DEVELOPMENT_SERVER, null, {
target: null,
})
expect(config.target).toBe('server')
......
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