Unverified Commit 47f73cd8 authored by Sam Ko's avatar Sam Ko Committed by GitHub

refactor(cli): refactor cli to commander (#61877)

## Description
Refactor the [Next.js
CLI](https://nextjs.org/docs/app/api-reference/next-cli) to use
[commander](https://github.com/tj/commander.js) instead of
[arg](https://github.com/vercel/arg).

## Why?
- Auto-generated, properly formatted help command + output. With `arg`,
much of the help commands were manually added via a single
`console.log`, causing deviations over time.
- Ergonomic, ease of adding new subcommands and rules

## Breaking Changes
- Update the experimental `next experimental-compile` and `next
experimental-generate` build commands in favor of `next build
--experimental-build-mode=compile/generate`

---------
Co-authored-by: 's avatarJJ Kasper <jj@jjsweb.site>
parent 2f7721a6
...@@ -209,6 +209,7 @@ ...@@ -209,6 +209,7 @@
"ci-info": "watson/ci-info#f43f6a1cefff47fb361c88cf4b943fdbcaafe540", "ci-info": "watson/ci-info#f43f6a1cefff47fb361c88cf4b943fdbcaafe540",
"cli-select": "1.1.2", "cli-select": "1.1.2",
"client-only": "0.0.1", "client-only": "0.0.1",
"commander": "12.0.0",
"comment-json": "3.0.3", "comment-json": "3.0.3",
"compression": "1.7.4", "compression": "1.7.4",
"conf": "5.0.0", "conf": "5.0.0",
......
This diff is collapsed.
...@@ -674,14 +674,14 @@ export default async function build( ...@@ -674,14 +674,14 @@ export default async function build(
noMangling = false, noMangling = false,
appDirOnly = false, appDirOnly = false,
turboNextBuild = false, turboNextBuild = false,
buildMode: 'default' | 'experimental-compile' | 'experimental-generate' experimentalBuildMode: 'default' | 'compile' | 'generate'
): Promise<void> { ): Promise<void> {
const isCompileMode = buildMode === 'experimental-compile' const isCompileMode = experimentalBuildMode === 'compile'
const isGenerateMode = buildMode === 'experimental-generate' const isGenerateMode = experimentalBuildMode === 'generate'
try { try {
const nextBuildSpan = trace('next-build', undefined, { const nextBuildSpan = trace('next-build', undefined, {
buildMode: buildMode, buildMode: experimentalBuildMode,
isTurboBuild: String(turboNextBuild), isTurboBuild: String(turboNextBuild),
version: process.env.__NEXT_VERSION as string, version: process.env.__NEXT_VERSION as string,
}) })
......
import type arg from 'next/dist/compiled/arg/index.js'
export const validArgs: arg.Spec = {
// Types
'--help': Boolean,
'--profile': Boolean,
'--debug': Boolean,
'--no-lint': Boolean,
'--no-mangling': Boolean,
'--experimental-app-only': Boolean,
'--experimental-turbo': Boolean,
'--experimental-turbo-root': String,
'--build-mode': String,
// Aliases
'-h': '--help',
'-d': '--debug',
}
...@@ -2,68 +2,73 @@ ...@@ -2,68 +2,73 @@
import '../server/lib/cpu-profile' import '../server/lib/cpu-profile'
import { existsSync } from 'fs' import { existsSync } from 'fs'
import * as Log from '../build/output/log' import { italic } from '../lib/picocolors'
import type { CliCommand } from '../lib/commands'
import build from '../build' import build from '../build'
import { warn } from '../build/output/log'
import { printAndExit } from '../server/lib/utils' import { printAndExit } from '../server/lib/utils'
import isError from '../lib/is-error' import isError from '../lib/is-error'
import { getProjectDir } from '../lib/get-project-dir' import { getProjectDir } from '../lib/get-project-dir'
const nextBuild: CliCommand = (args) => { type NextBuildOptions = {
if (args['--help']) { debug?: boolean
printAndExit( profile?: boolean
` lint: boolean
Description mangling: boolean
Compiles the application for production deployment experimentalAppOnly?: boolean
experimentalTurbo?: boolean
experimentalBuildMode: 'default' | 'compile' | 'generate'
}
Usage const nextBuild = (options: NextBuildOptions, directory?: string) => {
$ next build <dir> process.on('SIGTERM', () => process.exit(0))
process.on('SIGINT', () => process.exit(0))
<dir> represents the directory of the Next.js application. const {
If no directory is provided, the current directory will be used. debug,
profile,
lint,
mangling,
experimentalAppOnly,
experimentalTurbo,
experimentalBuildMode,
} = options
Options if (!lint) {
--profile Can be used to enable React Production Profiling warn('Linting is disabled.')
--no-lint Disable linting
--no-mangling Disable mangling
--experimental-app-only Only build 'app' routes
--experimental-turbo Enable experimental turbo mode
--help, -h Displays this message
`,
0
)
} }
if (args['--profile']) {
Log.warn('Profiling is enabled. Note: This may affect performance') if (!mangling) {
} warn(
if (args['--no-lint']) { 'Mangling is disabled. Note: This may affect performance and should only be used for debugging purposes.'
Log.warn('Linting is disabled') )
} }
if (args['--no-mangling']) {
Log.warn( if (profile) {
'Mangling is disabled. Note: This may affect performance and should only be used for debugging purposes' warn(
`Profiling is enabled. ${italic('Note: This may affect performance.')}`
) )
} }
const dir = getProjectDir(args._[0])
const dir = getProjectDir(directory)
// Check if the provided directory exists // Check if the provided directory exists
if (!existsSync(dir)) { if (!existsSync(dir)) {
printAndExit(`> No such directory exists as the project root: ${dir}`) printAndExit(`> No such directory exists as the project root: ${dir}`)
} }
if (args['--experimental-turbo']) { if (experimentalTurbo) {
process.env.TURBOPACK = '1' process.env.TURBOPACK = '1'
} }
return build( return build(
dir, dir,
args['--profile'], profile,
args['--debug'] || process.env.NEXT_DEBUG_BUILD, debug || Boolean(process.env.NEXT_DEBUG_BUILD),
!args['--no-lint'], lint,
args['--no-mangling'], !mangling,
args['--experimental-app-only'], experimentalAppOnly,
!!process.env.TURBOPACK, !!process.env.TURBOPACK,
args['--build-mode'] || 'default' experimentalBuildMode
).catch((err) => { ).catch((err) => {
console.error('') console.error('')
if ( if (
......
import type arg from 'next/dist/compiled/arg/index.js'
export const validArgs: arg.Spec = {
// Types
'--help': Boolean,
'--port': Number,
'--hostname': String,
'--turbo': Boolean,
'--experimental-https': Boolean,
'--experimental-https-key': String,
'--experimental-https-cert': String,
'--experimental-https-ca': String,
'--experimental-test-proxy': Boolean,
'--experimental-upload-trace': String,
// To align current messages with native binary.
// Will need to adjust subcommand later.
'--show-all': Boolean,
'--root': String,
// Aliases
'-h': '--help',
'-p': '--port',
'-H': '--hostname',
}
...@@ -8,11 +8,9 @@ import { ...@@ -8,11 +8,9 @@ import {
getDebugPort, getDebugPort,
getMaxOldSpaceSize, getMaxOldSpaceSize,
getNodeOptionsWithoutInspect, getNodeOptionsWithoutInspect,
getPort,
printAndExit, printAndExit,
} from '../server/lib/utils' } from '../server/lib/utils'
import * as Log from '../build/output/log' import * as Log from '../build/output/log'
import type { CliCommand } from '../lib/commands'
import { getProjectDir } from '../lib/get-project-dir' import { getProjectDir } from '../lib/get-project-dir'
import { PHASE_DEVELOPMENT_SERVER } from '../shared/lib/constants' import { PHASE_DEVELOPMENT_SERVER } from '../shared/lib/constants'
import path from 'path' import path from 'path'
...@@ -36,6 +34,18 @@ import { ...@@ -36,6 +34,18 @@ import {
import os from 'os' import os from 'os'
import { once } from 'node:events' import { once } from 'node:events'
type NextDevOptions = {
turbo?: boolean
port: number
hostname?: string
experimentalHttps?: boolean
experimentalHttpsKey?: string
experimentalHttpsCert?: string
experimentalHttpsCa?: string
experimentalUploadTrace?: string
experimentalTestProxy?: boolean
}
let dir: string let dir: string
let child: undefined | ChildProcess let child: undefined | ChildProcess
let config: NextConfigComplete let config: NextConfigComplete
...@@ -117,32 +127,8 @@ process.on('SIGTERM', () => handleSessionStop('SIGKILL')) ...@@ -117,32 +127,8 @@ process.on('SIGTERM', () => handleSessionStop('SIGKILL'))
// exit event must be synchronous // exit event must be synchronous
process.on('exit', () => child?.kill('SIGKILL')) process.on('exit', () => child?.kill('SIGKILL'))
const nextDev: CliCommand = async (args) => { const nextDev = async (options: NextDevOptions, directory?: string) => {
if (args['--help']) { dir = getProjectDir(process.env.NEXT_PRIVATE_DEV_DIR || directory)
console.log(`
Description
Starts the application in development mode (hot-code reloading, error
reporting, etc.)
Usage
$ next dev <dir> -p <port number>
<dir> represents the directory of the Next.js application.
If no directory is provided, the current directory will be used.
Options
--port, -p A port number to start the application on
--hostname, -H Hostname start the application on (default: 0.0.0.0)
--experimental-https Start the server with HTTPS and generate a self-signed certificate
--experimental-https-key <path> Path to a HTTPS key file
--experimental-https-cert <path> Path to a HTTPS certificate file
--experimental-https-ca <path> Path to a HTTPS certificate authority file
--experimental-upload-trace=<trace-url> Report a subset of the debugging trace to a remote http url. Includes sensitive data. Disabled by default and url must be provided.
--help, -h Displays this message
`)
process.exit(0)
}
dir = getProjectDir(process.env.NEXT_PRIVATE_DEV_DIR || args._[0])
// Check if pages dir exists and warn if not // Check if pages dir exists and warn if not
if (!(await fileExists(dir, FileType.Directory))) { if (!(await fileExists(dir, FileType.Directory))) {
...@@ -187,7 +173,7 @@ const nextDev: CliCommand = async (args) => { ...@@ -187,7 +173,7 @@ const nextDev: CliCommand = async (args) => {
} }
} }
const port = getPort(args) const port = options.port
if (isPortIsReserved(port)) { if (isPortIsReserved(port)) {
printAndExit(getReservedPortExplanation(port), 1) printAndExit(getReservedPortExplanation(port), 1)
...@@ -195,21 +181,21 @@ const nextDev: CliCommand = async (args) => { ...@@ -195,21 +181,21 @@ const nextDev: CliCommand = async (args) => {
// If neither --port nor PORT were specified, it's okay to retry new ports. // If neither --port nor PORT were specified, it's okay to retry new ports.
const allowRetry = const allowRetry =
args['--port'] === undefined && process.env.PORT === undefined options.port === undefined && process.env.PORT === undefined
// We do not set a default host value here to prevent breaking // We do not set a default host value here to prevent breaking
// some set-ups that rely on listening on other interfaces // some set-ups that rely on listening on other interfaces
const host = args['--hostname'] const host = options.hostname
config = await loadConfig(PHASE_DEVELOPMENT_SERVER, dir) config = await loadConfig(PHASE_DEVELOPMENT_SERVER, dir)
const isExperimentalTestProxy = args['--experimental-test-proxy'] const isExperimentalTestProxy = options.experimentalTestProxy
if ( if (
args['--experimental-upload-trace'] && options.experimentalUploadTrace &&
!process.env.NEXT_TRACE_UPLOAD_DISABLED !process.env.NEXT_TRACE_UPLOAD_DISABLED
) { ) {
traceUploadUrl = args['--experimental-upload-trace'] traceUploadUrl = options.experimentalUploadTrace
} }
// TODO: remove in the next major version // TODO: remove in the next major version
...@@ -228,7 +214,7 @@ const nextDev: CliCommand = async (args) => { ...@@ -228,7 +214,7 @@ const nextDev: CliCommand = async (args) => {
isExperimentalTestProxy, isExperimentalTestProxy,
} }
if (args['--turbo']) { if (options.turbo) {
process.env.TURBOPACK = '1' process.env.TURBOPACK = '1'
} }
...@@ -239,7 +225,8 @@ const nextDev: CliCommand = async (args) => { ...@@ -239,7 +225,8 @@ const nextDev: CliCommand = async (args) => {
setGlobal('distDir', distDir) setGlobal('distDir', distDir)
const startServerPath = require.resolve('../server/lib/start-server') const startServerPath = require.resolve('../server/lib/start-server')
async function startServer(options: StartServerOptions) {
async function startServer(startServerOptions: StartServerOptions) {
return new Promise<void>((resolve) => { return new Promise<void>((resolve) => {
let resolved = false let resolved = false
const defaultEnv = (initialEnv || process.env) as typeof process.env const defaultEnv = (initialEnv || process.env) as typeof process.env
...@@ -269,8 +256,8 @@ const nextDev: CliCommand = async (args) => { ...@@ -269,8 +256,8 @@ const nextDev: CliCommand = async (args) => {
...defaultEnv, ...defaultEnv,
TURBOPACK: process.env.TURBOPACK, TURBOPACK: process.env.TURBOPACK,
NEXT_PRIVATE_WORKER: '1', NEXT_PRIVATE_WORKER: '1',
NODE_EXTRA_CA_CERTS: options.selfSignedCertificate NODE_EXTRA_CA_CERTS: startServerOptions.selfSignedCertificate
? options.selfSignedCertificate.rootCA ? startServerOptions.selfSignedCertificate.rootCA
: defaultEnv.NODE_EXTRA_CA_CERTS, : defaultEnv.NODE_EXTRA_CA_CERTS,
NODE_OPTIONS, NODE_OPTIONS,
}, },
...@@ -279,7 +266,7 @@ const nextDev: CliCommand = async (args) => { ...@@ -279,7 +266,7 @@ const nextDev: CliCommand = async (args) => {
child.on('message', (msg: any) => { child.on('message', (msg: any) => {
if (msg && typeof msg === 'object') { if (msg && typeof msg === 'object') {
if (msg.nextWorkerReady) { if (msg.nextWorkerReady) {
child?.send({ nextWorkerOptions: options }) child?.send({ nextWorkerOptions: startServerOptions })
} else if (msg.nextServerReady && !resolved) { } else if (msg.nextServerReady && !resolved) {
resolved = true resolved = true
resolve() resolve()
...@@ -304,7 +291,7 @@ const nextDev: CliCommand = async (args) => { ...@@ -304,7 +291,7 @@ const nextDev: CliCommand = async (args) => {
sync: true, sync: true,
}) })
} }
return startServer(options) return startServer(startServerOptions)
} }
await handleSessionStop(signal) await handleSessionStop(signal)
}) })
...@@ -313,16 +300,16 @@ const nextDev: CliCommand = async (args) => { ...@@ -313,16 +300,16 @@ const nextDev: CliCommand = async (args) => {
const runDevServer = async (reboot: boolean) => { const runDevServer = async (reboot: boolean) => {
try { try {
if (!!args['--experimental-https']) { if (!!options.experimentalHttps) {
Log.warn( Log.warn(
'Self-signed certificates are currently an experimental feature, use with caution.' 'Self-signed certificates are currently an experimental feature, use with caution.'
) )
let certificate: SelfSignedCertificate | undefined let certificate: SelfSignedCertificate | undefined
const key = args['--experimental-https-key'] const key = options.experimentalHttpsKey
const cert = args['--experimental-https-cert'] const cert = options.experimentalHttpsCert
const rootCA = args['--experimental-https-ca'] const rootCA = options.experimentalHttpsCa
if (key && cert) { if (key && cert) {
certificate = { certificate = {
......
import type arg from 'next/dist/compiled/arg/index.js'
export const validArgs: arg.Spec = {
// Types
'--help': Boolean,
'--silent': Boolean,
'--outdir': String,
'--threads': Number,
// Aliases
'-h': '--help',
'-o': '--outdir',
'-s': '--silent',
}
#!/usr/bin/env node
import { cyan } from '../lib/picocolors' import { cyan } from '../lib/picocolors'
import * as Log from '../build/output/log' import { error } from '../build/output/log'
import type { CliCommand } from '../lib/commands'
const nextExport: CliCommand = () => { const nextExport = () => {
Log.error(` error(`
The "next export" command has been removed in favor of "output: export" in next.config.js. Learn more: ${cyan( \`next export\` has been removed in favor of 'output: export' in next.config.js.\nLearn more: ${cyan(
'https://nextjs.org/docs/advanced-features/static-html-export' 'https://nextjs.org/docs/app/building-your-application/deploying/static-exports'
)} )}
`) `)
process.exit(1) process.exit(1)
} }
......
import type arg from 'next/dist/compiled/arg/index.js'
/**
* Supported CLI arguments.
*/
export const validArgs: arg.Spec = {
// Types
'--help': Boolean,
// Aliases
'-h': '--help',
// Detailed diagnostics
'--verbose': Boolean,
}
...@@ -4,7 +4,6 @@ import os from 'os' ...@@ -4,7 +4,6 @@ import os from 'os'
import childProcess from 'child_process' import childProcess from 'child_process'
import { bold, cyan, yellow } from '../lib/picocolors' import { bold, cyan, yellow } from '../lib/picocolors'
import type { CliCommand } from '../lib/commands'
import { PHASE_INFO } from '../shared/lib/constants' import { PHASE_INFO } from '../shared/lib/constants'
import loadConfig from '../server/config' import loadConfig from '../server/config'
import { getRegistry } from '../lib/helpers/get-registry' import { getRegistry } from '../lib/helpers/get-registry'
...@@ -12,7 +11,9 @@ import { parseVersionInfo } from '../server/dev/parse-version-info' ...@@ -12,7 +11,9 @@ import { parseVersionInfo } from '../server/dev/parse-version-info'
import { getStaleness } from '../client/components/react-dev-overlay/internal/components/VersionStalenessInfo/VersionStalenessInfo' import { getStaleness } from '../client/components/react-dev-overlay/internal/components/VersionStalenessInfo/VersionStalenessInfo'
import { warn } from '../build/output/log' import { warn } from '../build/output/log'
const dir = process.cwd() type NextInfoOptions = {
verbose?: boolean
}
type TaskResult = { type TaskResult = {
// Additional messages to notify to the users, i.e certain script cannot be run due to missing xyz. // Additional messages to notify to the users, i.e certain script cannot be run due to missing xyz.
...@@ -23,6 +24,7 @@ type TaskResult = { ...@@ -23,6 +24,7 @@ type TaskResult = {
} }
type TaskScript = () => Promise<TaskResult> type TaskScript = () => Promise<TaskResult>
type PlatformTaskScript = type PlatformTaskScript =
| { | {
win32: TaskScript win32: TaskScript
...@@ -59,7 +61,7 @@ function getPackageVersion(packageName: string) { ...@@ -59,7 +61,7 @@ function getPackageVersion(packageName: string) {
} }
async function getNextConfig() { async function getNextConfig() {
const config = await loadConfig(PHASE_INFO, dir) const config = await loadConfig(PHASE_INFO, process.cwd())
return { return {
output: config.output ?? 'N/A', output: config.output ?? 'N/A',
...@@ -84,37 +86,20 @@ function getBinaryVersion(binaryName: string) { ...@@ -84,37 +86,20 @@ function getBinaryVersion(binaryName: string) {
} }
} }
function printHelp() {
console.log(
`
Description
Prints relevant details about the current system which can be used to report Next.js bugs
Usage
$ next info
Options
--help, -h Displays this message
--verbose Collect additional information for debugging
Learn more: ${cyan('https://nextjs.org/docs/api-reference/cli#info')}`
)
}
/** /**
* Collect basic next.js installation information and print it to stdout. * Collect basic next.js installation information and print it to stdout.
*/ */
async function printDefaultInfo() { async function printInfo() {
const installedRelease = getPackageVersion('next') const installedRelease = getPackageVersion('next')
const nextConfig = await getNextConfig() const nextConfig = await getNextConfig()
let stalenessWithTitle = '' let stalenessWithTitle = ''
let title = '' let title = ''
let versionInfo let versionInfo
try { try {
const registry = getRegistry() const registry = getRegistry()
const res = await fetch(`${registry}-/package/next/dist-tags`) const res = await fetch(`${registry}-/package/next/dist-tags`)
const tags = await res.json() const tags = await res.json()
versionInfo = parseVersionInfo({ versionInfo = parseVersionInfo({
...@@ -122,8 +107,12 @@ async function printDefaultInfo() { ...@@ -122,8 +107,12 @@ async function printDefaultInfo() {
latest: tags.latest, latest: tags.latest,
canary: tags.canary, canary: tags.canary,
}) })
title = getStaleness(versionInfo).title title = getStaleness(versionInfo).title
if (title) stalenessWithTitle = ` // ${title}`
if (title) {
stalenessWithTitle = ` // ${title}`
}
} catch (e) { } catch (e) {
console.warn( console.warn(
`${yellow( `${yellow(
...@@ -133,7 +122,9 @@ async function printDefaultInfo() { ...@@ -133,7 +122,9 @@ async function printDefaultInfo() {
}.) }.)
Detected "${installedRelease}". Visit https://github.com/vercel/next.js/releases. Detected "${installedRelease}". Visit https://github.com/vercel/next.js/releases.
Make sure to try the latest canary version (eg.: \`npm install next@canary\`) to confirm the issue still exists before creating a new issue. Make sure to try the latest canary version (eg.: \`npm install next@canary\`) to confirm the issue still exists before creating a new issue.
Read more - https://nextjs.org/docs/messages/opening-an-issue` \nLearn more: ${cyan(
'https://nextjs.org/docs/messages/opening-an-issue'
)}`
) )
} }
...@@ -157,9 +148,7 @@ Relevant Packages: ...@@ -157,9 +148,7 @@ Relevant Packages:
react-dom: ${getPackageVersion('react-dom')} react-dom: ${getPackageVersion('react-dom')}
typescript: ${getPackageVersion('typescript')} typescript: ${getPackageVersion('typescript')}
Next.js Config: Next.js Config:
output: ${nextConfig.output} output: ${nextConfig.output}`)
`)
if (versionInfo?.staleness.startsWith('stale')) { if (versionInfo?.staleness.startsWith('stale')) {
warn(`${title} warn(`${title}
...@@ -249,7 +238,7 @@ async function runSharedDependencyCheck( ...@@ -249,7 +238,7 @@ async function runSharedDependencyCheck(
/** /**
* Collect additional diagnostics information. * Collect additional diagnostics information.
*/ */
async function printVerbose() { async function printVerboseInfo() {
const fs = require('fs') const fs = require('fs')
const currentPlatform = os.platform() const currentPlatform = os.platform()
...@@ -592,16 +581,11 @@ async function printVerbose() { ...@@ -592,16 +581,11 @@ async function printVerbose() {
* There are 2 modes, by default it collects basic next.js installation with runtime information. If * There are 2 modes, by default it collects basic next.js installation with runtime information. If
* `--verbose` mode is enabled it'll try to collect, verify more data for next-swc installation and others. * `--verbose` mode is enabled it'll try to collect, verify more data for next-swc installation and others.
*/ */
const nextInfo: CliCommand = async (args) => { const nextInfo = async (options: NextInfoOptions) => {
if (args['--help']) { if (options.verbose) {
printHelp() await printVerboseInfo()
return
}
if (!args['--verbose']) {
await printDefaultInfo()
} else { } else {
await printVerbose() await printInfo()
} }
} }
......
import type arg from 'next/dist/compiled/arg/index.js'
const validEslintArgs: arg.Spec = {
// Types
'--config': String,
'--ext': [String],
'--resolve-plugins-relative-to': String,
'--rulesdir': [String],
'--fix': Boolean,
'--fix-type': [String],
'--ignore-path': String,
'--no-ignore': Boolean,
'--quiet': Boolean,
'--max-warnings': Number,
'--no-inline-config': Boolean,
'--report-unused-disable-directives': String,
'--cache': Boolean, // Although cache is enabled by default, this dummy flag still exists to not cause any breaking changes
'--no-cache': Boolean,
'--cache-location': String,
'--cache-strategy': String,
'--error-on-unmatched-pattern': Boolean,
'--format': String,
'--output-file': String,
// Aliases
'-c': '--config',
'-f': '--format',
'-o': '--output-file',
}
export const validArgs: arg.Spec = {
// Types
'--help': Boolean,
'--base-dir': String,
'--dir': [String],
'--file': [String],
'--strict': Boolean,
// Aliases
'-h': '--help',
'-b': '--base-dir',
'-d': '--dir',
...validEslintArgs,
}
#!/usr/bin/env node #!/usr/bin/env node
import type arg from 'next/dist/compiled/arg/index.js'
import { existsSync } from 'fs' import { existsSync } from 'fs'
import { join } from 'path' import { join } from 'path'
import { green } from '../lib/picocolors'
import type { CliCommand } from '../lib/commands' import loadConfig from '../server/config'
import { ESLINT_DEFAULT_DIRS } from '../lib/constants'
import { runLintCheck } from '../lib/eslint/runLintCheck'
import { printAndExit } from '../server/lib/utils' import { printAndExit } from '../server/lib/utils'
import { Telemetry } from '../telemetry/storage' import { Telemetry } from '../telemetry/storage'
import loadConfig from '../server/config' import { green } from '../lib/picocolors'
import { ESLINT_DEFAULT_DIRS } from '../lib/constants'
import { runLintCheck } from '../lib/eslint/runLintCheck'
import { CompileError } from '../lib/compile-error'
import { PHASE_PRODUCTION_BUILD } from '../shared/lib/constants' import { PHASE_PRODUCTION_BUILD } from '../shared/lib/constants'
import { eventLintCheckCompleted } from '../telemetry/events' import { eventLintCheckCompleted } from '../telemetry/events'
import { CompileError } from '../lib/compile-error'
import { getProjectDir } from '../lib/get-project-dir' import { getProjectDir } from '../lib/get-project-dir'
import { findPagesDir } from '../lib/find-pages-dir' import { findPagesDir } from '../lib/find-pages-dir'
import { verifyTypeScriptSetup } from '../lib/verify-typescript-setup' import { verifyTypeScriptSetup } from '../lib/verify-typescript-setup'
const eslintOptions = (args: arg.Spec, defaultCacheLocation: string) => ({ type NextLintOptions = {
overrideConfigFile: args['--config'] || null, cache: boolean
extensions: args['--ext'] ?? [ cacheLocation?: string
'.js', cacheStrategy: string
'.mjs', config?: string
'.cjs', dir?: string[]
'.jsx', errorOnUnmatchedPattern?: boolean
'.ts', ext: string[]
'.mts', file?: string[]
'.cts', fix?: boolean
'.tsx', fixType?: string
], format?: string
resolvePluginsRelativeTo: args['--resolve-plugins-relative-to'] || null, ignore: boolean
rulePaths: args['--rulesdir'] ?? [], ignorePath?: string
fix: args['--fix'] ?? false, inlineConfig: boolean
fixTypes: args['--fix-type'] ?? null, maxWarnings: number
ignorePath: args['--ignore-path'] || null, outputFile?: string
ignore: !Boolean(args['--no-ignore']), quiet?: boolean
allowInlineConfig: !Boolean(args['--no-inline-config']), reportUnusedDisableDirectives: string
reportUnusedDisableDirectives: resolvePluginsRelativeTo?: string
args['--report-unused-disable-directives'] || null, rulesdir?: string
cache: !Boolean(args['--no-cache']), strict?: boolean
cacheLocation: args['--cache-location'] || defaultCacheLocation, }
cacheStrategy: args['--cache-strategy'] || 'metadata',
errorOnUnmatchedPattern: args['--error-on-unmatched-pattern']
? Boolean(args['--error-on-unmatched-pattern'])
: false,
})
const nextLint: CliCommand = async (args) => { const eslintOptions = (
if (args['--help']) { options: NextLintOptions,
printAndExit( defaultCacheLocation: string
` ) => ({
Description overrideConfigFile: options.config || null,
Run ESLint on every file in specified directories. extensions: options.ext ?? [],
If not configured, ESLint will be set up for the first time. resolvePluginsRelativeTo: options.resolvePluginsRelativeTo || null,
rulePaths: options.rulesdir ?? [],
Usage fix: options.fix ?? false,
$ next lint <baseDir> [options] fixTypes: options.fixType ?? null,
ignorePath: options.ignorePath || null,
<baseDir> represents the directory of the Next.js application. ignore: options.ignore,
If no directory is provided, the current directory will be used. allowInlineConfig: options.inlineConfig,
reportUnusedDisableDirectives: options.reportUnusedDisableDirectives || null,
Options cache: options.cache,
Basic configuration: cacheLocation: options.cacheLocation || defaultCacheLocation,
-h, --help List this help cacheStrategy: options.cacheStrategy,
-d, --dir Array Include directory, or directories, to run ESLint - default: 'pages', 'components', and 'lib' errorOnUnmatchedPattern: options.errorOnUnmatchedPattern ?? false,
--file Array Include file, or files, to run ESLint })
-c, --config path::String Use this configuration file, overriding all other config options
--ext [String] Specify JavaScript file extensions - default: .js, .mjs, .cjs, .jsx, .ts, .mts, .cts, .tsx
--resolve-plugins-relative-to path::String A folder where plugins should be resolved from, CWD by default
Initial setup:
--strict Creates an .eslintrc.json file using the Next.js strict configuration (only possible if no .eslintrc.json file is present)
Specifying rules:
--rulesdir [path::String] Use additional rules from this directory
Fixing problems:
--fix Automatically fix problems
--fix-type Array Specify the types of fixes to apply (problem, suggestion, layout)
Ignoring files:
--ignore-path path::String Specify path of ignore file
--no-ignore Disable use of ignore files and patterns
Handling warnings:
--quiet Report errors only - default: false
--max-warnings Int Number of warnings to trigger nonzero exit code - default: -1
Output:
-o, --output-file path::String Specify file to write report to
-f, --format String Use a specific output format - default: Next.js custom formatter
Inline configuration comments:
--no-inline-config Prevent comments from changing config or rules
--report-unused-disable-directives Adds reported errors for unused eslint-disable directives ("error" | "warn" | "off")
Caching:
--no-cache Disable caching
--cache-location path::String Path to the cache file or directory - default: .eslintcache
--cache-strategy String Strategy to use for detecting changed files in the cache, either metadata or content - default: metadata
Miscellaneous:
--error-on-unmatched-pattern Show errors when any file patterns are unmatched - default: false
`,
0
)
}
const baseDir = getProjectDir(args._[0]) const nextLint = async (options: NextLintOptions, directory?: string) => {
const baseDir = getProjectDir(directory)
// Check if the provided directory exists // Check if the provided directory exists
if (!existsSync(baseDir)) { if (!existsSync(baseDir)) {
...@@ -116,24 +70,28 @@ const nextLint: CliCommand = async (args) => { ...@@ -116,24 +70,28 @@ const nextLint: CliCommand = async (args) => {
const nextConfig = await loadConfig(PHASE_PRODUCTION_BUILD, baseDir) const nextConfig = await loadConfig(PHASE_PRODUCTION_BUILD, baseDir)
const files: string[] = args['--file'] ?? [] const files = options.file ?? []
const dirs: string[] = args['--dir'] ?? nextConfig.eslint?.dirs const dirs = options.dir ?? nextConfig.eslint?.dirs
const filesToLint = [...(dirs ?? []), ...files] const filesToLint = [...(dirs ?? []), ...files]
const pathsToLint = ( const pathsToLint = (
filesToLint.length ? filesToLint : ESLINT_DEFAULT_DIRS filesToLint.length ? filesToLint : ESLINT_DEFAULT_DIRS
).reduce((res: string[], d: string) => { ).reduce((res: string[], d: string) => {
const currDir = join(baseDir, d) const currDir = join(baseDir, d)
if (!existsSync(currDir)) return res
if (!existsSync(currDir)) {
return res
}
res.push(currDir) res.push(currDir)
return res return res
}, []) }, [])
const reportErrorsOnly = Boolean(args['--quiet']) const reportErrorsOnly = Boolean(options.quiet)
const maxWarnings = args['--max-warnings'] ?? -1 const maxWarnings = options.maxWarnings
const formatter = args['--format'] || null const formatter = options.format || null
const strict = Boolean(args['--strict']) const strict = Boolean(options.strict)
const outputFile = args['--output-file'] || null const outputFile = options.outputFile || null
const distDir = join(baseDir, nextConfig.distDir) const distDir = join(baseDir, nextConfig.distDir)
const defaultCacheLocation = join(distDir, 'cache', 'eslint/') const defaultCacheLocation = join(distDir, 'cache', 'eslint/')
...@@ -141,7 +99,7 @@ const nextLint: CliCommand = async (args) => { ...@@ -141,7 +99,7 @@ const nextLint: CliCommand = async (args) => {
await verifyTypeScriptSetup({ await verifyTypeScriptSetup({
dir: baseDir, dir: baseDir,
distDir: nextConfig.distDir, distDir: distDir,
intentDirs: [pagesDir, appDir].filter(Boolean) as string[], intentDirs: [pagesDir, appDir].filter(Boolean) as string[],
typeCheckPreflight: false, typeCheckPreflight: false,
tsconfigPath: nextConfig.typescript.tsconfigPath, tsconfigPath: nextConfig.typescript.tsconfigPath,
...@@ -152,8 +110,8 @@ const nextLint: CliCommand = async (args) => { ...@@ -152,8 +110,8 @@ const nextLint: CliCommand = async (args) => {
runLintCheck(baseDir, pathsToLint, { runLintCheck(baseDir, pathsToLint, {
lintDuringBuild: false, lintDuringBuild: false,
eslintOptions: eslintOptions(args, defaultCacheLocation), eslintOptions: eslintOptions(options, defaultCacheLocation),
reportErrorsOnly: reportErrorsOnly, reportErrorsOnly,
maxWarnings, maxWarnings,
formatter, formatter,
outputFile, outputFile,
......
import type arg from 'next/dist/compiled/arg/index.js'
export const validArgs: arg.Spec = {
// Types
'--help': Boolean,
'--port': Number,
'--hostname': String,
'--keepAliveTimeout': Number,
'--experimental-test-proxy': Boolean,
// Aliases
'-h': '--help',
'-p': '--port',
'-H': '--hostname',
}
#!/usr/bin/env node #!/usr/bin/env node
import '../server/lib/cpu-profile' import '../server/lib/cpu-profile'
import { startServer } from '../server/lib/start-server' import { startServer } from '../server/lib/start-server'
import { getPort, printAndExit } from '../server/lib/utils' import { printAndExit } from '../server/lib/utils'
import { getProjectDir } from '../lib/get-project-dir' import { getProjectDir } from '../lib/get-project-dir'
import type { CliCommand } from '../lib/commands'
import { import {
getReservedPortExplanation, getReservedPortExplanation,
isPortIsReserved, isPortIsReserved,
} from '../lib/helpers/get-reserved-port' } from '../lib/helpers/get-reserved-port'
const nextStart: CliCommand = async (args) => { type NextStartOptions = {
if (args['--help']) { port: number
console.log(` hostname?: string
Description keepAliveTimeout?: number
Starts the application in production mode. experimentalTestProxy?: boolean
The application should be compiled with \`next build\` first. }
Usage
$ next start <dir> -p <port>
<dir> represents the directory of the Next.js application.
If no directory is provided, the current directory will be used.
Options
--port, -p A port number on which to start the application
--hostname, -H Hostname on which to start the application (default: 0.0.0.0)
--keepAliveTimeout Max milliseconds to wait before closing inactive connections
--help, -h Displays this message
`)
process.exit(0)
}
const dir = getProjectDir(args._[0]) const nextStart = async (options: NextStartOptions, directory?: string) => {
const host = args['--hostname'] const dir = getProjectDir(directory)
const port = getPort(args) const host = options.hostname
const port = options.port
const isExperimentalTestProxy = options.experimentalTestProxy
let keepAliveTimeout = options.keepAliveTimeout
if (isPortIsReserved(port)) { if (isPortIsReserved(port)) {
printAndExit(getReservedPortExplanation(port), 1) printAndExit(getReservedPortExplanation(port), 1)
} }
const isExperimentalTestProxy = args['--experimental-test-proxy']
const keepAliveTimeoutArg: number | undefined = args['--keepAliveTimeout']
if (
typeof keepAliveTimeoutArg !== 'undefined' &&
(Number.isNaN(keepAliveTimeoutArg) ||
!Number.isFinite(keepAliveTimeoutArg) ||
keepAliveTimeoutArg < 0)
) {
printAndExit(
`Invalid --keepAliveTimeout, expected a non negative number but received "${keepAliveTimeoutArg}"`,
1
)
}
const keepAliveTimeout = keepAliveTimeoutArg
? Math.ceil(keepAliveTimeoutArg)
: undefined
await startServer({ await startServer({
dir, dir,
isDev: false, isDev: false,
......
import type arg from 'next/dist/compiled/arg/index.js'
export const validArgs: arg.Spec = {
// Types
'--enable': Boolean,
'--disable': Boolean,
'--help': Boolean,
// Aliases
'-h': '--help',
}
#!/usr/bin/env node #!/usr/bin/env node
import { bold, cyan, green, red, yellow } from '../lib/picocolors' import { bold, cyan, green, red, yellow } from '../lib/picocolors'
import type { CliCommand } from '../lib/commands'
import { Telemetry } from '../telemetry/storage' import { Telemetry } from '../telemetry/storage'
const nextTelemetry: CliCommand = (args) => { type NextTelemetryOptions = {
if (args['--help']) { enable?: boolean
console.log( disable?: boolean
` }
Description
Allows you to control Next.js' telemetry collection
Usage
$ next telemetry [enable/disable]
You may pass the 'enable' or 'disable' argument to turn Next.js' telemetry collection on or off.
Options
--enable Enables Next.js' telemetry collection
--disable Disables Next.js' telemetry collection
--help, -h Displays this message
Learn more: ${cyan('https://nextjs.org/telemetry')}
`
)
return
}
const telemetry = new Telemetry({ distDir: process.cwd() })
let isEnabled = telemetry.isEnabled const telemetry = new Telemetry({ distDir: process.cwd() })
let isEnabled = telemetry.isEnabled
if (args['--enable'] || args._[0] === 'enable') { const nextTelemetry = (options: NextTelemetryOptions, arg: string) => {
if (options.enable || arg === 'enable') {
telemetry.setEnabled(true) telemetry.setEnabled(true)
console.log(cyan('Success!'))
console.log()
isEnabled = true isEnabled = true
} else if (args['--disable'] || args._[0] === 'disable') {
console.log(cyan('Success!'))
} else if (options.disable || arg === 'disable') {
const path = telemetry.setEnabled(false) const path = telemetry.setEnabled(false)
if (isEnabled) { if (isEnabled) {
console.log( console.log(
cyan(`Your preference has been saved${path ? ` to ${path}` : ''}.`) cyan(`Your preference has been saved${path ? ` to ${path}` : ''}.`)
...@@ -45,30 +27,27 @@ const nextTelemetry: CliCommand = (args) => { ...@@ -45,30 +27,27 @@ const nextTelemetry: CliCommand = (args) => {
} else { } else {
console.log(yellow(`Next.js' telemetry collection is already disabled.`)) console.log(yellow(`Next.js' telemetry collection is already disabled.`))
} }
console.log()
isEnabled = false isEnabled = false
} else { } else {
console.log(bold('Next.js Telemetry')) console.log(bold('Next.js Telemetry'))
console.log()
} }
console.log( console.log(
`Status: ${isEnabled ? bold(green('Enabled')) : bold(red('Disabled'))}` `\nStatus: ${isEnabled ? bold(green('Enabled')) : bold(red('Disabled'))}`
) )
console.log()
if (isEnabled) { if (isEnabled) {
console.log( console.log(
`Next.js telemetry is completely anonymous. Thank you for participating!` '\nNext.js telemetry is completely anonymous. Thank you for participating!'
) )
} else { } else {
console.log(`You have opted-out of Next.js' anonymous telemetry program.`) console.log(
console.log(`No data will be collected from your machine.`) `\nYou have opted-out of Next.js' anonymous telemetry program.\nNo data will be collected from your machine.`
)
} }
console.log(`Learn more: https://nextjs.org/telemetry`) console.log(`\nLearn more: ${cyan('https://nextjs.org/telemetry')}`)
console.log()
} }
export { nextTelemetry } export { nextTelemetry }
(The MIT License)
Copyright (c) 2011 TJ Holowaychuk <tj@vision-media.ca>
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
'Software'), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
This diff is collapsed.
{"name":"commander","main":"index.js","author":"TJ Holowaychuk <tj@vision-media.ca>","license":"MIT"}
import type { getValidatedArgs } from './get-validated-args'
export type CliCommand = (args: ReturnType<typeof getValidatedArgs>) => void
export const commandArgs: {
[command: string]: () => Parameters<typeof getValidatedArgs>[0]
} = {
build: () => require('../cli/next-build-args').validArgs,
start: () => require('../cli/next-start-args').validArgs,
export: () => require('../cli/next-export-args').validArgs,
dev: () => require('../cli/next-dev-args').validArgs,
lint: () => require('../cli/next-lint-args').validArgs,
telemetry: () => require('../cli/next-telemetry-args').validArgs,
info: () => require('../cli/next-info-args').validArgs,
'experimental-compile': () => require('../cli/next-build-args').validArgs,
'experimental-generate': () => require('../cli/next-build-args').validArgs,
}
import type { getValidatedArgs } from './get-validated-args'
export type CliCommand = (args: ReturnType<typeof getValidatedArgs>) => void
export const commands: { [command: string]: () => Promise<CliCommand> } = {
build: () => Promise.resolve(require('../cli/next-build').nextBuild),
start: () => Promise.resolve(require('../cli/next-start').nextStart),
export: () => Promise.resolve(require('../cli/next-export').nextExport),
dev: () => Promise.resolve(require('../cli/next-dev').nextDev),
lint: () => Promise.resolve(require('../cli/next-lint').nextLint),
telemetry: () =>
Promise.resolve(require('../cli/next-telemetry').nextTelemetry),
info: () => Promise.resolve(require('../cli/next-info').nextInfo),
'experimental-compile': () =>
Promise.resolve(require('../cli/next-build').nextBuild),
'experimental-generate': () =>
Promise.resolve(require('../cli/next-build').nextBuild),
}
import type { Command, Help } from 'next/dist/compiled/commander'
import { bold } from '../lib/picocolors'
// Copy-pasted from Commander's Help class -> formatHelp().
// TL;DR, we're overriding the built-in help to add a few niceties.
// Link: https://github.com/tj/commander.js/blob/master/lib/help.js
const formatCliHelpOutput = (cmd: Command, helper: Help) => {
const termWidth = helper.padWidth(cmd, helper)
const helpWidth = helper.helpWidth || 80
const itemIndentWidth = 2
const itemSeparatorWidth = 2 // between term and description
function formatItem(term: string, description: string) {
let value = term
if (description) {
if (term === 'directory') {
value = `[${term}]`
}
const fullText = `${value.padEnd(
termWidth + itemSeparatorWidth
)}${description}`
return helper.wrap(
fullText,
helpWidth - itemIndentWidth,
termWidth + itemSeparatorWidth
)
}
return term
}
function formatList(textArray: string[]) {
return textArray.join('\n').replace(/^/gm, ' '.repeat(itemIndentWidth))
}
// Usage
let output = [`${bold('Usage:')} ${helper.commandUsage(cmd)}`, '']
// Description
const commandDescription = helper.commandDescription(cmd)
if (commandDescription.length > 0) {
output = output.concat([helper.wrap(commandDescription, helpWidth, 0), ''])
}
// Arguments
const argumentList = helper.visibleArguments(cmd).map((argument) => {
return formatItem(
helper.argumentTerm(argument),
helper.argumentDescription(argument)
)
})
if (argumentList.length > 0) {
output = output.concat([
`${bold('Arguments:')}`,
formatList(argumentList),
'',
])
}
// Options
const optionList = helper.visibleOptions(cmd).map((option) => {
return formatItem(
helper.optionTerm(option),
helper.optionDescription(option)
)
})
if (optionList.length > 0) {
output = output.concat([`${bold('Options:')}`, formatList(optionList), ''])
}
// Commands
const commandList = helper.visibleCommands(cmd).map((subCmd) => {
return formatItem(
helper.subcommandTerm(subCmd),
helper.subcommandDescription(subCmd)
)
})
if (commandList.length > 0) {
output = output.concat([
`${bold('Commands:')}`,
formatList(commandList),
'',
])
}
return output.join('\n')
}
export { formatCliHelpOutput }
import path from 'path' import path from 'path'
import { commands } from './commands' import { error, warn } from '../build/output/log'
import * as Log from '../build/output/log'
import { detectTypo } from './detect-typo' import { detectTypo } from './detect-typo'
import { realpathSync } from './realpath' import { realpathSync } from './realpath'
...@@ -13,7 +12,7 @@ export function getProjectDir(dir?: string) { ...@@ -13,7 +12,7 @@ export function getProjectDir(dir?: string) {
resolvedDir !== realDir && resolvedDir !== realDir &&
resolvedDir.toLowerCase() === realDir.toLowerCase() resolvedDir.toLowerCase() === realDir.toLowerCase()
) { ) {
Log.warn( warn(
`Invalid casing detected for project dir, received ${resolvedDir} actual path ${realDir}, see more info here https://nextjs.org/docs/messages/invalid-project-dir-casing` `Invalid casing detected for project dir, received ${resolvedDir} actual path ${realDir}, see more info here https://nextjs.org/docs/messages/invalid-project-dir-casing`
) )
} }
...@@ -22,17 +21,24 @@ export function getProjectDir(dir?: string) { ...@@ -22,17 +21,24 @@ export function getProjectDir(dir?: string) {
} catch (err: any) { } catch (err: any) {
if (err.code === 'ENOENT') { if (err.code === 'ENOENT') {
if (typeof dir === 'string') { if (typeof dir === 'string') {
const detectedTypo = detectTypo(dir, Object.keys(commands)) const detectedTypo = detectTypo(dir, [
'build',
'dev',
'info',
'lint',
'start',
'telemetry',
])
if (detectedTypo) { if (detectedTypo) {
Log.error( error(
`"next ${dir}" does not exist. Did you mean "next ${detectedTypo}"?` `"next ${dir}" does not exist. Did you mean "next ${detectedTypo}"?`
) )
process.exit(1) process.exit(1)
} }
} }
Log.error( error(
`Invalid project directory provided, no such directory: ${path.resolve( `Invalid project directory provided, no such directory: ${path.resolve(
dir || '.' dir || '.'
)}` )}`
......
import arg from 'next/dist/compiled/arg/index.js'
import { printAndExit } from '../server/lib/utils'
import isError from './is-error'
export function getValidatedArgs(validArgs: arg.Spec, argv?: string[]) {
let args: arg.Result<arg.Spec>
try {
args = arg(validArgs, { argv })
} catch (error) {
if (isError(error) && error.code === 'ARG_UNKNOWN_OPTION') {
printAndExit(error.message, 1)
}
throw error
}
return args
}
...@@ -33,7 +33,7 @@ export interface StartServerOptions { ...@@ -33,7 +33,7 @@ export interface StartServerOptions {
dir: string dir: string
port: number port: number
isDev: boolean isDev: boolean
hostname: string hostname?: string
allowRetry?: boolean allowRetry?: boolean
customServer?: boolean customServer?: boolean
minimalMode?: boolean minimalMode?: boolean
...@@ -59,7 +59,7 @@ export async function getRequestHandlers({ ...@@ -59,7 +59,7 @@ export async function getRequestHandlers({
port: number port: number
isDev: boolean isDev: boolean
server?: import('http').Server server?: import('http').Server
hostname: string hostname?: string
minimalMode?: boolean minimalMode?: boolean
isNodeDebugging?: boolean isNodeDebugging?: boolean
keepAliveTimeout?: number keepAliveTimeout?: number
......
import type arg from 'next/dist/compiled/arg/index.js' import { InvalidArgumentError } from 'next/dist/compiled/commander'
export function printAndExit(message: string, code = 1) { export function printAndExit(message: string, code = 1) {
if (code === 0) { if (code === 0) {
...@@ -28,17 +28,14 @@ export function getNodeOptionsWithoutInspect() { ...@@ -28,17 +28,14 @@ export function getNodeOptionsWithoutInspect() {
return (process.env.NODE_OPTIONS || '').replace(NODE_INSPECT_RE, '') return (process.env.NODE_OPTIONS || '').replace(NODE_INSPECT_RE, '')
} }
export function getPort(args: arg.Result<arg.Spec>): number { export function myParseInt(value: string) {
if (typeof args['--port'] === 'number') { // parseInt takes a string and a radix
return args['--port'] const parsedValue = parseInt(value, 10)
}
const parsed = process.env.PORT && parseInt(process.env.PORT, 10) if (isNaN(parsedValue) || !isFinite(parsedValue) || parsedValue < 0) {
if (typeof parsed === 'number' && !Number.isNaN(parsed)) { throw new InvalidArgumentError(`'${value}' is not a non-negative number.`)
return parsed
} }
return parsedValue
return 3000
} }
export const RESTART_EXIT_CODE = 77 export const RESTART_EXIT_CODE = 77
......
...@@ -1008,14 +1008,6 @@ export async function ncc_amp_optimizer(task, opts) { ...@@ -1008,14 +1008,6 @@ export async function ncc_amp_optimizer(task, opts) {
.target('dist/compiled/@ampproject/toolbox-optimizer') .target('dist/compiled/@ampproject/toolbox-optimizer')
} }
// eslint-disable-next-line camelcase // eslint-disable-next-line camelcase
externals['arg'] = 'next/dist/compiled/arg'
export async function ncc_arg(task, opts) {
await task
.source(relative(__dirname, require.resolve('arg')))
.ncc({ packageName: 'arg' })
.target('src/compiled/arg')
}
// eslint-disable-next-line camelcase
externals['async-retry'] = 'next/dist/compiled/async-retry' externals['async-retry'] = 'next/dist/compiled/async-retry'
export async function ncc_async_retry(task, opts) { export async function ncc_async_retry(task, opts) {
await task await task
...@@ -1159,6 +1151,13 @@ export async function ncc_cli_select(task, opts) { ...@@ -1159,6 +1151,13 @@ export async function ncc_cli_select(task, opts) {
.ncc({ packageName: 'cli-select', externals }) .ncc({ packageName: 'cli-select', externals })
.target('src/compiled/cli-select') .target('src/compiled/cli-select')
} }
externals['commmander'] = 'next/dist/compiled/commander'
export async function ncc_commander(task, opts) {
await task
.source(relative(__dirname, require.resolve('commander')))
.ncc({ packageName: 'commander', externals })
.target('src/compiled/commander')
}
externals['comment-json'] = 'next/dist/compiled/comment-json' externals['comment-json'] = 'next/dist/compiled/comment-json'
export async function ncc_comment_json(task, opts) { export async function ncc_comment_json(task, opts) {
await task await task
...@@ -2178,6 +2177,7 @@ export async function ncc(task, opts) { ...@@ -2178,6 +2177,7 @@ export async function ncc(task, opts) {
'ncc_image_size', 'ncc_image_size',
'ncc_get_orientation', 'ncc_get_orientation',
'ncc_hapi_accept', 'ncc_hapi_accept',
'ncc_commander',
'ncc_node_fetch', 'ncc_node_fetch',
'ncc_node_anser', 'ncc_node_anser',
'ncc_node_stacktrace_parser', 'ncc_node_stacktrace_parser',
...@@ -2187,7 +2187,6 @@ export async function ncc(task, opts) { ...@@ -2187,7 +2187,6 @@ export async function ncc(task, opts) {
'ncc_node_shell_quote', 'ncc_node_shell_quote',
'ncc_acorn', 'ncc_acorn',
'ncc_amphtml_validator', 'ncc_amphtml_validator',
'ncc_arg',
'ncc_async_retry', 'ncc_async_retry',
'ncc_async_sema', 'ncc_async_sema',
'ncc_postcss_plugin_stub_for_cssnano_simple', 'ncc_postcss_plugin_stub_for_cssnano_simple',
......
...@@ -47,6 +47,12 @@ declare module 'next/dist/compiled/node-fetch' { ...@@ -47,6 +47,12 @@ declare module 'next/dist/compiled/node-fetch' {
export default fetch export default fetch
} }
declare module 'next/dist/compiled/commander' {
import commander from 'commander'
export * from 'commander'
export default commander
}
declare module 'next/dist/compiled/node-html-parser' { declare module 'next/dist/compiled/node-html-parser' {
export * from 'node-html-parser' export * from 'node-html-parser'
} }
...@@ -111,32 +117,6 @@ declare module 'next/dist/compiled/async-sema' { ...@@ -111,32 +117,6 @@ declare module 'next/dist/compiled/async-sema' {
import m from 'async-sema' import m from 'async-sema'
export = m export = m
} }
declare module 'next/dist/compiled/arg/index.js' {
function arg<T extends arg.Spec>(
spec: T,
options?: { argv?: string[]; permissive?: boolean }
): arg.Result<T>
namespace arg {
export type Handler = (value: string) => any
export interface Spec {
[key: string]: string | Handler | [Handler]
}
export type Result<T extends Spec> = { _: string[] } & {
[K in keyof T]: T[K] extends string
? never
: T[K] extends Handler
? ReturnType<T[K]>
: T[K] extends [Handler]
? Array<ReturnType<T[K][0]>>
: never
}
}
export = arg
}
declare module 'next/dist/compiled/babel/code-frame' { declare module 'next/dist/compiled/babel/code-frame' {
export * from '@babel/code-frame' export * from '@babel/code-frame'
......
...@@ -1124,6 +1124,9 @@ importers: ...@@ -1124,6 +1124,9 @@ importers:
client-only: client-only:
specifier: 0.0.1 specifier: 0.0.1
version: 0.0.1 version: 0.0.1
commander:
specifier: 12.0.0
version: 12.0.0
comment-json: comment-json:
specifier: 3.0.3 specifier: 3.0.3
version: 3.0.3 version: 3.0.3
...@@ -9582,13 +9585,14 @@ packages: ...@@ -9582,13 +9585,14 @@ packages:
/comma-separated-tokens@2.0.3: /comma-separated-tokens@2.0.3:
resolution: {integrity: sha512-Fu4hJdvzeylCfQPp9SGWidpzrMs7tTrlu6Vb8XGaRGck8QSNZJJp538Wrb60Lax4fPwR64ViY468OIUTbRlGZg==} resolution: {integrity: sha512-Fu4hJdvzeylCfQPp9SGWidpzrMs7tTrlu6Vb8XGaRGck8QSNZJJp538Wrb60Lax4fPwR64ViY468OIUTbRlGZg==}
/commander@12.0.0:
resolution: {integrity: sha512-MwVNWlYjDTtOjX5PiD7o5pK0UrFU/OYgcJfjjK4RaHZETNtjJqrZa9Y9ds88+A+f+d5lv+561eZ+yCKoS3gbAA==}
engines: {node: '>=18'}
dev: true
/commander@2.20.0: /commander@2.20.0:
resolution: {integrity: sha512-7j2y+40w61zy6YC2iRNpUe/NwhNyoXrYpHMrSunaMG64nRnaf96zO/KMQR4OyN/UnE5KLyEBnKHd4aG3rskjpQ==} resolution: {integrity: sha512-7j2y+40w61zy6YC2iRNpUe/NwhNyoXrYpHMrSunaMG64nRnaf96zO/KMQR4OyN/UnE5KLyEBnKHd4aG3rskjpQ==}
/commander@2.20.3:
resolution: {integrity: sha512-GpVkmM8vF2vQUkj2LvZmD35JxeJOLCwJ9cUkugyk2nuhbv3+mJvpLYYt+0+USMxE+oj+ey/lJEnhZw75x/OMcQ==}
dev: true
/commander@4.1.1: /commander@4.1.1:
resolution: {integrity: sha512-NOKm8xhkzAjzFx8B2v5OAHT+u5pRQc2UCa2Vq9jYL/31o2wi9mxBA7LIFs3sV5VSC49z6pEhfbMULvShKj26WA==} resolution: {integrity: sha512-NOKm8xhkzAjzFx8B2v5OAHT+u5pRQc2UCa2Vq9jYL/31o2wi9mxBA7LIFs3sV5VSC49z6pEhfbMULvShKj26WA==}
engines: {node: '>= 6'} engines: {node: '>= 6'}
...@@ -24940,7 +24944,7 @@ packages: ...@@ -24940,7 +24944,7 @@ packages:
hasBin: true hasBin: true
dependencies: dependencies:
chalk: 1.1.3 chalk: 1.1.3
commander: 2.20.3 commander: 2.20.0
debug: 2.6.9 debug: 2.6.9
transitivePeerDependencies: transitivePeerDependencies:
- supports-color - supports-color
......
...@@ -13,7 +13,7 @@ createNextDescribe( ...@@ -13,7 +13,7 @@ createNextDescribe(
{ {
files: __dirname, files: __dirname,
buildCommand: process.env.NEXT_EXPERIMENTAL_COMPILE buildCommand: process.env.NEXT_EXPERIMENTAL_COMPILE
? 'pnpm next experimental-compile' ? `pnpm next build --experimental-build-mode=compile`
: undefined, : undefined,
dependencies: { dependencies: {
nanoid: '4.0.1', nanoid: '4.0.1',
......
...@@ -57,7 +57,7 @@ describe('app dir - with output export (next dev / next build)', () => { ...@@ -57,7 +57,7 @@ describe('app dir - with output export (next dev / next build)', () => {
} }
expect(error).toBeDefined() expect(error).toBeDefined()
expect(stderr).toContain( expect(stderr).toContain(
'The "next export" command has been removed in favor of "output: export" in next.config.js' `\`next export\` has been removed in favor of 'output: export' in next.config.js`
) )
expect(stdout).not.toContain('Export successful. Files written to') expect(stdout).not.toContain('Export successful. Files written to')
expect(await getFiles()).toEqual([]) expect(await getFiles()).toEqual([])
......
...@@ -124,14 +124,14 @@ describe('CLI Usage', () => { ...@@ -124,14 +124,14 @@ describe('CLI Usage', () => {
const help = await runNextCommand(['start', '--help'], { const help = await runNextCommand(['start', '--help'], {
stdout: true, stdout: true,
}) })
expect(help.stdout).toMatch(/Starts the application in production mode/) expect(help.stdout).toMatch(/Starts Next.js in production mode/)
}) })
test('-h', async () => { test('-h', async () => {
const help = await runNextCommand(['start', '-h'], { const help = await runNextCommand(['start', '-h'], {
stdout: true, stdout: true,
}) })
expect(help.stdout).toMatch(/Starts the application in production mode/) expect(help.stdout).toMatch(/Starts Next.js in production mode/)
}) })
test('should format IPv6 addresses correctly', async () => { test('should format IPv6 addresses correctly', async () => {
...@@ -167,7 +167,7 @@ describe('CLI Usage', () => { ...@@ -167,7 +167,7 @@ describe('CLI Usage', () => {
const { stderr } = await runNextCommand(['start', '--random'], { const { stderr } = await runNextCommand(['start', '--random'], {
stderr: true, stderr: true,
}) })
expect(stderr).toEqual('Unknown or unexpected option: --random\n') expect(stderr).toEqual(`error: unknown option '--random'\n`)
}) })
test('should not throw UnhandledPromiseRejectionWarning', async () => { test('should not throw UnhandledPromiseRejectionWarning', async () => {
const { stderr } = await runNextCommand(['start', '--random'], { const { stderr } = await runNextCommand(['start', '--random'], {
...@@ -211,7 +211,7 @@ describe('CLI Usage', () => { ...@@ -211,7 +211,7 @@ describe('CLI Usage', () => {
} }
) )
expect(stderr).toContain( expect(stderr).toContain(
'Invalid --keepAliveTimeout, expected a non negative number but received "NaN"' `error: option '--keepAliveTimeout <keepAliveTimeout>' argument 'string' is invalid. 'string' is not a non-negative number.`
) )
}) })
...@@ -223,7 +223,7 @@ describe('CLI Usage', () => { ...@@ -223,7 +223,7 @@ describe('CLI Usage', () => {
} }
) )
expect(stderr).toContain( expect(stderr).toContain(
'Invalid --keepAliveTimeout, expected a non negative number but received "-100"' `error: option '--keepAliveTimeout <keepAliveTimeout>' argument '-100' is invalid. '-100' is not a non-negative number.`
) )
}) })
...@@ -235,7 +235,7 @@ describe('CLI Usage', () => { ...@@ -235,7 +235,7 @@ describe('CLI Usage', () => {
} }
) )
expect(stderr).toContain( expect(stderr).toContain(
'Invalid --keepAliveTimeout, expected a non negative number but received "Infinity"' `error: option '--keepAliveTimeout <keepAliveTimeout>' argument 'Infinity' is invalid. 'Infinity' is not a non-negative number.`
) )
}) })
...@@ -247,7 +247,7 @@ describe('CLI Usage', () => { ...@@ -247,7 +247,7 @@ describe('CLI Usage', () => {
} }
) )
expect(stderr).not.toContain( expect(stderr).not.toContain(
'Invalid keep alive timeout provided, expected a non negative number' `error: option '--keepAliveTimeout <keepAliveTimeout>' argument '100' is invalid. '100' is not a non-negative number.`
) )
}) })
...@@ -283,25 +283,21 @@ describe('CLI Usage', () => { ...@@ -283,25 +283,21 @@ describe('CLI Usage', () => {
const help = await runNextCommand(['telemetry', '--help'], { const help = await runNextCommand(['telemetry', '--help'], {
stdout: true, stdout: true,
}) })
expect(help.stdout).toMatch( expect(help.stdout).toMatch(/Allows you to enable or disable Next\.js'/)
/Allows you to control Next\.js' telemetry collection/
)
}) })
test('-h', async () => { test('-h', async () => {
const help = await runNextCommand(['telemetry', '-h'], { const help = await runNextCommand(['telemetry', '-h'], {
stdout: true, stdout: true,
}) })
expect(help.stdout).toMatch( expect(help.stdout).toMatch(/Allows you to enable or disable Next\.js'/)
/Allows you to control Next\.js' telemetry collection/
)
}) })
test('should warn when unknown argument provided', async () => { test('should warn when unknown argument provided', async () => {
const { stderr } = await runNextCommand(['telemetry', '--random'], { const { stderr } = await runNextCommand(['telemetry', '--random'], {
stderr: true, stderr: true,
}) })
expect(stderr).toEqual('Unknown or unexpected option: --random\n') expect(stderr).toEqual(`error: unknown option '--random'\n`)
}) })
test('should not throw UnhandledPromiseRejectionWarning', async () => { test('should not throw UnhandledPromiseRejectionWarning', async () => {
const { stderr } = await runNextCommand(['telemetry', '--random'], { const { stderr } = await runNextCommand(['telemetry', '--random'], {
...@@ -316,25 +312,21 @@ describe('CLI Usage', () => { ...@@ -316,25 +312,21 @@ describe('CLI Usage', () => {
const help = await runNextCommand(['build', '--help'], { const help = await runNextCommand(['build', '--help'], {
stdout: true, stdout: true,
}) })
expect(help.stdout).toMatch( expect(help.stdout).toMatch(/Creates an optimized production build/)
/Compiles the application for production deployment/
)
}) })
test('-h', async () => { test('-h', async () => {
const help = await runNextCommand(['build', '-h'], { const help = await runNextCommand(['build', '-h'], {
stdout: true, stdout: true,
}) })
expect(help.stdout).toMatch( expect(help.stdout).toMatch(/Creates an optimized production build/)
/Compiles the application for production deployment/
)
}) })
test('should warn when unknown argument provided', async () => { test('should warn when unknown argument provided', async () => {
const { stderr } = await runNextCommand(['build', '--random'], { const { stderr } = await runNextCommand(['build', '--random'], {
stderr: true, stderr: true,
}) })
expect(stderr).toEqual('Unknown or unexpected option: --random\n') expect(stderr).toEqual(`error: unknown option '--random'\n`)
}) })
test('should not throw UnhandledPromiseRejectionWarning', async () => { test('should not throw UnhandledPromiseRejectionWarning', async () => {
const { stderr } = await runNextCommand(['build', '--random'], { const { stderr } = await runNextCommand(['build', '--random'], {
...@@ -367,14 +359,18 @@ describe('CLI Usage', () => { ...@@ -367,14 +359,18 @@ describe('CLI Usage', () => {
const help = await runNextCommand(['--help'], { const help = await runNextCommand(['--help'], {
stdout: true, stdout: true,
}) })
expect(help.stdout).toMatch(/Usage/) expect(help.stdout).toMatch(
/The Next.js CLI allows you to develop, build, start/
)
}) })
test('-h', async () => { test('-h', async () => {
const help = await runNextCommand(['-h'], { const help = await runNextCommand(['-h'], {
stdout: true, stdout: true,
}) })
expect(help.stdout).toMatch(/Usage/) expect(help.stdout).toMatch(
/The Next.js CLI allows you to develop, build, start/
)
}) })
test('--version', async () => { test('--version', async () => {
...@@ -429,14 +425,14 @@ describe('CLI Usage', () => { ...@@ -429,14 +425,14 @@ describe('CLI Usage', () => {
const help = await runNextCommand(['dev', '--help'], { const help = await runNextCommand(['dev', '--help'], {
stdout: true, stdout: true,
}) })
expect(help.stdout).toMatch(/Starts the application in development mode/) expect(help.stdout).toMatch(/Starts Next.js in development mode/)
}) })
test('-h', async () => { test('-h', async () => {
const help = await runNextCommand(['dev', '-h'], { const help = await runNextCommand(['dev', '-h'], {
stdout: true, stdout: true,
}) })
expect(help.stdout).toMatch(/Starts the application in development mode/) expect(help.stdout).toMatch(/Starts Next.js in development mode/)
}) })
test('custom directory', async () => { test('custom directory', async () => {
...@@ -732,7 +728,7 @@ describe('CLI Usage', () => { ...@@ -732,7 +728,7 @@ describe('CLI Usage', () => {
const { stderr } = await runNextCommand(['dev', '--random'], { const { stderr } = await runNextCommand(['dev', '--random'], {
stderr: true, stderr: true,
}) })
expect(stderr).toEqual('Unknown or unexpected option: --random\n') expect(stderr).toEqual(`error: unknown option '--random'\n`)
}) })
test('should not throw UnhandledPromiseRejectionWarning', async () => { test('should not throw UnhandledPromiseRejectionWarning', async () => {
const { stderr } = await runNextCommand(['dev', '--random'], { const { stderr } = await runNextCommand(['dev', '--random'], {
...@@ -767,7 +763,18 @@ describe('CLI Usage', () => { ...@@ -767,7 +763,18 @@ describe('CLI Usage', () => {
stderr: true, stderr: true,
}) })
expect(help.stderr).toMatch( expect(help.stderr).toMatch(
'The "next export" command has been removed in favor of "output: export" in next.config.js' `error: unknown option '--help'\n(Did you mean --help?)`
)
expect(help.code).toBe(1)
})
test('run export command', async () => {
const help = await runNextCommand(['export'], {
stdout: true,
stderr: true,
})
expect(help.stderr).toMatch(
`\`next export\` has been removed in favor of 'output: export' in next.config.js`
) )
expect(help.code).toBe(1) expect(help.code).toBe(1)
}) })
...@@ -805,7 +812,7 @@ Next.js Config: ...@@ -805,7 +812,7 @@ Next.js Config:
stdout: true, stdout: true,
}) })
expect(help.stdout).toMatch( expect(help.stdout).toMatch(
/Prints relevant details about the current system which can be used to report Next\.js bugs/ /Prints relevant details about the current system which can be used to report/
) )
}) })
...@@ -814,7 +821,7 @@ Next.js Config: ...@@ -814,7 +821,7 @@ Next.js Config:
stdout: true, stdout: true,
}) })
expect(help.stdout).toMatch( expect(help.stdout).toMatch(
/Prints relevant details about the current system which can be used to report Next\.js bugs/ /Prints relevant details about the current system which can be used to report/
) )
}) })
......
import { nextStart } from 'next/dist/cli/next-start'
import httpMock, { Server } from 'http'
// Prevents bin from running
jest.mock('next/dist/bin/next', () => ({}))
jest.mock('next/dist/lib/get-project-dir', () => ({ getProjectDir: () => '' }))
jest.mock('http')
// this test is unreliable as nextStart is not synchronous and the
// server could be created at any point
describe.skip('start', () => {
test('--keepAliveTimeout changes server.keepAliveTimeout when passed', () => {
const server = {
on: () => {},
listen: () => {},
} as any as Server
;(httpMock as any).createServer.mockReturnValue(server)
expect(server.keepAliveTimeout).toBe(undefined)
nextStart(['--keepAliveTimeout', '1234'])
expect(server.keepAliveTimeout).toBe(1234)
})
test("--keepAliveTimeout doesn't change server.keepAliveTimeout when not passed", () => {
const server = {
on: () => {},
listen: () => {},
} as any as Server
;(httpMock as any).createServer.mockReturnValue(server)
expect(server.keepAliveTimeout).toBe(undefined)
nextStart([])
expect(server.keepAliveTimeout).toBe(undefined)
})
})
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