Unverified Commit c21bf9cb authored by Willem-Jaap's avatar Willem-Jaap Committed by GitHub

Update Next Command name, add types & update variable wording (#68007)

### What?

This PR adds updates the command name and adds argument types to the
`next` script to improve internal DX, code quality and correctness.
parent e1ee42f7
...@@ -9,8 +9,17 @@ import semver from 'next/dist/compiled/semver' ...@@ -9,8 +9,17 @@ import semver from 'next/dist/compiled/semver'
import { bold, cyan, italic } from '../lib/picocolors' import { bold, cyan, italic } from '../lib/picocolors'
import { formatCliHelpOutput } from '../lib/format-cli-help-output' import { formatCliHelpOutput } from '../lib/format-cli-help-output'
import { NON_STANDARD_NODE_ENV } from '../lib/constants' import { NON_STANDARD_NODE_ENV } from '../lib/constants'
import { myParseInt } from '../server/lib/utils' import { parseValidPositiveInteger } from '../server/lib/utils'
import { SUPPORTED_TEST_RUNNERS_LIST } from '../cli/next-test.js' import {
SUPPORTED_TEST_RUNNERS_LIST,
type NextTestOptions,
} from '../cli/next-test.js'
import type { NextTelemetryOptions } from '../cli/next-telemetry.js'
import type { NextStartOptions } from '../cli/next-start.js'
import type { NextLintOptions } from '../cli/next-lint.js'
import type { NextInfoOptions } from '../cli/next-info.js'
import type { NextDevOptions } from '../cli/next-dev.js'
import type { NextBuildOptions } from '../cli/next-build.js'
if ( if (
semver.lt(process.versions.node, process.env.__NEXT_REQUIRED_NODE_VERSION!) semver.lt(process.versions.node, process.env.__NEXT_REQUIRED_NODE_VERSION!)
...@@ -35,15 +44,15 @@ for (const dependency of ['react', 'react-dom']) { ...@@ -35,15 +44,15 @@ for (const dependency of ['react', 'react-dom']) {
} }
} }
class MyRootCommand extends Command { class NextRootCommand extends Command {
createCommand(name: string) { createCommand(name: string) {
const cmd = new Command(name) const command = new Command(name)
cmd.addOption(new Option('--inspect').hideHelp()) command.addOption(new Option('--inspect').hideHelp())
cmd.hook('preAction', (thisCommand) => { command.hook('preAction', (event) => {
const cmdName = thisCommand.name() const commandName = event.name()
const defaultEnv = cmdName === 'dev' ? 'development' : 'production' const defaultEnv = commandName === 'dev' ? 'development' : 'production'
const standardEnv = ['production', 'development', 'test'] const standardEnv = ['production', 'development', 'test']
if (process.env.NODE_ENV) { if (process.env.NODE_ENV) {
...@@ -55,7 +64,7 @@ class MyRootCommand extends Command { ...@@ -55,7 +64,7 @@ class MyRootCommand extends Command {
? ['dev'] ? ['dev']
: [] : []
if (isNotStandard || shouldWarnCommands.includes(cmdName)) { if (isNotStandard || shouldWarnCommands.includes(commandName)) {
warn(NON_STANDARD_NODE_ENV) warn(NON_STANDARD_NODE_ENV)
} }
} }
...@@ -63,19 +72,19 @@ class MyRootCommand extends Command { ...@@ -63,19 +72,19 @@ class MyRootCommand extends Command {
;(process.env as any).NODE_ENV = process.env.NODE_ENV || defaultEnv ;(process.env as any).NODE_ENV = process.env.NODE_ENV || defaultEnv
;(process.env as any).NEXT_RUNTIME = 'nodejs' ;(process.env as any).NEXT_RUNTIME = 'nodejs'
if (thisCommand.getOptionValue('inspect') === true) { if (event.getOptionValue('inspect') === true) {
console.error( console.error(
`\`--inspect\` flag is deprecated. Use env variable NODE_OPTIONS instead: NODE_OPTIONS='--inspect' next ${cmdName}` `\`--inspect\` flag is deprecated. Use env variable NODE_OPTIONS instead: NODE_OPTIONS='--inspect' next ${commandName}`
) )
process.exit(1) process.exit(1)
} }
}) })
return cmd return command
} }
} }
const program = new MyRootCommand() const program = new NextRootCommand()
program program
.name('next') .name('next')
...@@ -128,7 +137,7 @@ program ...@@ -128,7 +137,7 @@ program
'--experimental-upload-trace, <traceUrl>', '--experimental-upload-trace, <traceUrl>',
'Reports a subset of the debugging trace to a remote HTTP URL. Includes sensitive data.' 'Reports a subset of the debugging trace to a remote HTTP URL. Includes sensitive data.'
) )
.action((directory, options) => .action((directory: string, options: NextBuildOptions) =>
// ensure process exits after build completes so open handles/connections // ensure process exits after build completes so open handles/connections
// don't cause process to hang // don't cause process to hang
import('../cli/next-build.js').then((mod) => import('../cli/next-build.js').then((mod) =>
...@@ -154,7 +163,7 @@ program ...@@ -154,7 +163,7 @@ program
'-p, --port <port>', '-p, --port <port>',
'Specify a port number on which to start the application.' 'Specify a port number on which to start the application.'
) )
.argParser(myParseInt) .argParser(parseValidPositiveInteger)
.default(3000) .default(3000)
.env('PORT') .env('PORT')
) )
...@@ -179,12 +188,14 @@ program ...@@ -179,12 +188,14 @@ program
'--experimental-upload-trace, <traceUrl>', '--experimental-upload-trace, <traceUrl>',
'Reports a subset of the debugging trace to a remote HTTP URL. Includes sensitive data.' 'Reports a subset of the debugging trace to a remote HTTP URL. Includes sensitive data.'
) )
.action((directory, options, { _optionValueSources }) => { .action(
const portSource = _optionValueSources.port (directory: string, options: NextDevOptions, { _optionValueSources }) => {
import('../cli/next-dev.js').then((mod) => const portSource = _optionValueSources.port
mod.nextDev(options, portSource, directory) import('../cli/next-dev.js').then((mod) =>
) mod.nextDev(options, portSource, directory)
}) )
}
)
.usage('[directory] [options]') .usage('[directory] [options]')
program program
...@@ -202,7 +213,7 @@ program ...@@ -202,7 +213,7 @@ program
`\nLearn more: ${cyan('https://nextjs.org/docs/api-reference/cli#info')}` `\nLearn more: ${cyan('https://nextjs.org/docs/api-reference/cli#info')}`
) )
.option('--verbose', 'Collects additional information for debugging.') .option('--verbose', 'Collects additional information for debugging.')
.action((options) => .action((options: NextInfoOptions) =>
import('../cli/next-info.js').then((mod) => mod.nextInfo(options)) import('../cli/next-info.js').then((mod) => mod.nextInfo(options))
) )
...@@ -257,7 +268,7 @@ program ...@@ -257,7 +268,7 @@ program
'--max-warnings [maxWarnings]', '--max-warnings [maxWarnings]',
'Specify the number of warnings before triggering a non-zero exit code.' 'Specify the number of warnings before triggering a non-zero exit code.'
) )
.argParser(myParseInt) .argParser(parseValidPositiveInteger)
.default(-1) .default(-1)
) )
.option( .option(
...@@ -287,7 +298,7 @@ program ...@@ -287,7 +298,7 @@ program
'--error-on-unmatched-pattern', '--error-on-unmatched-pattern',
'Reports errors when any file patterns are unmatched.' 'Reports errors when any file patterns are unmatched.'
) )
.action((directory, options) => .action((directory: string, options: NextLintOptions) =>
import('../cli/next-lint.js').then((mod) => import('../cli/next-lint.js').then((mod) =>
mod.nextLint(options, directory) mod.nextLint(options, directory)
) )
...@@ -310,7 +321,7 @@ program ...@@ -310,7 +321,7 @@ program
'-p, --port <port>', '-p, --port <port>',
'Specify a port number on which to start the application.' 'Specify a port number on which to start the application.'
) )
.argParser(myParseInt) .argParser(parseValidPositiveInteger)
.default(3000) .default(3000)
.env('PORT') .env('PORT')
) )
...@@ -322,9 +333,9 @@ program ...@@ -322,9 +333,9 @@ program
new Option( new Option(
'--keepAliveTimeout <keepAliveTimeout>', '--keepAliveTimeout <keepAliveTimeout>',
'Specify the maximum amount of milliseconds to wait before closing inactive connections.' 'Specify the maximum amount of milliseconds to wait before closing inactive connections.'
).argParser(myParseInt) ).argParser(parseValidPositiveInteger)
) )
.action((directory, options) => .action((directory: string, options: NextStartOptions) =>
import('../cli/next-start.js').then((mod) => import('../cli/next-start.js').then((mod) =>
mod.nextStart(options, directory) mod.nextStart(options, directory)
) )
...@@ -346,7 +357,7 @@ program ...@@ -346,7 +357,7 @@ program
) )
) )
.option('--disable', `Disables Next.js' telemetry collection.`) .option('--disable', `Disables Next.js' telemetry collection.`)
.action((arg, options) => .action((arg: string, options: NextTelemetryOptions) =>
import('../cli/next-telemetry.js').then((mod) => import('../cli/next-telemetry.js').then((mod) =>
mod.nextTelemetry(options, arg) mod.nextTelemetry(options, arg)
) )
...@@ -376,11 +387,13 @@ program ...@@ -376,11 +387,13 @@ program
)}` )}`
) )
.allowUnknownOption() .allowUnknownOption()
.action((directory, testRunnerArgs, options) => { .action(
return import('../cli/next-test.js').then((mod) => { (directory: string, testRunnerArgs: string[], options: NextTestOptions) => {
mod.nextTest(directory, testRunnerArgs, options) return import('../cli/next-test.js').then((mod) => {
}) mod.nextTest(directory, testRunnerArgs, options)
}) })
}
)
.usage('[directory] [options]') .usage('[directory] [options]')
const internal = program const internal = program
...@@ -392,7 +405,7 @@ const internal = program ...@@ -392,7 +405,7 @@ const internal = program
internal internal
.command('turbo-trace-server') .command('turbo-trace-server')
.argument('[file]', 'Trace file to serve.') .argument('[file]', 'Trace file to serve.')
.action((file) => { .action((file: string) => {
return import('../cli/internal/turbo-trace-server.js').then((mod) => return import('../cli/internal/turbo-trace-server.js').then((mod) =>
mod.startTurboTraceServerCli(file) mod.startTurboTraceServerCli(file)
) )
......
...@@ -11,7 +11,7 @@ import { getProjectDir } from '../lib/get-project-dir' ...@@ -11,7 +11,7 @@ import { getProjectDir } from '../lib/get-project-dir'
import { enableMemoryDebuggingMode } from '../lib/memory/startup' import { enableMemoryDebuggingMode } from '../lib/memory/startup'
import { disableMemoryDebuggingMode } from '../lib/memory/shutdown' import { disableMemoryDebuggingMode } from '../lib/memory/shutdown'
type NextBuildOptions = { export type NextBuildOptions = {
debug?: boolean debug?: boolean
profile?: boolean profile?: boolean
lint: boolean lint: boolean
...@@ -67,7 +67,6 @@ const nextBuild = (options: NextBuildOptions, directory?: string) => { ...@@ -67,7 +67,6 @@ const nextBuild = (options: NextBuildOptions, directory?: string) => {
const dir = getProjectDir(directory) const dir = getProjectDir(directory)
// 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}`)
} }
......
...@@ -36,7 +36,7 @@ import { ...@@ -36,7 +36,7 @@ import {
import os from 'os' import os from 'os'
import { once } from 'node:events' import { once } from 'node:events'
type NextDevOptions = { export type NextDevOptions = {
turbo?: boolean turbo?: boolean
port: number port: number
hostname?: string hostname?: string
......
...@@ -11,7 +11,7 @@ import { parseVersionInfo } from '../server/dev/parse-version-info' ...@@ -11,7 +11,7 @@ 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'
type NextInfoOptions = { export type NextInfoOptions = {
verbose?: boolean verbose?: boolean
} }
......
...@@ -16,7 +16,7 @@ import { getProjectDir } from '../lib/get-project-dir' ...@@ -16,7 +16,7 @@ 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'
type NextLintOptions = { export type NextLintOptions = {
cache: boolean cache: boolean
cacheLocation?: string cacheLocation?: string
cacheStrategy: string cacheStrategy: string
......
...@@ -9,17 +9,23 @@ import { ...@@ -9,17 +9,23 @@ import {
isPortIsReserved, isPortIsReserved,
} from '../lib/helpers/get-reserved-port' } from '../lib/helpers/get-reserved-port'
type NextStartOptions = { export type NextStartOptions = {
port: number port: number
hostname?: string hostname?: string
keepAliveTimeout?: number keepAliveTimeout?: number
} }
/**
* Start the Next.js server
*
* @param options The options for the start command
* @param directory The directory to start the server in
*/
const nextStart = async (options: NextStartOptions, directory?: string) => { const nextStart = async (options: NextStartOptions, directory?: string) => {
const dir = getProjectDir(directory) const dir = getProjectDir(directory)
const host = options.hostname const hostname = options.hostname
const port = options.port const port = options.port
let keepAliveTimeout = options.keepAliveTimeout const keepAliveTimeout = options.keepAliveTimeout
if (isPortIsReserved(port)) { if (isPortIsReserved(port)) {
printAndExit(getReservedPortExplanation(port), 1) printAndExit(getReservedPortExplanation(port), 1)
...@@ -28,7 +34,7 @@ const nextStart = async (options: NextStartOptions, directory?: string) => { ...@@ -28,7 +34,7 @@ const nextStart = async (options: NextStartOptions, directory?: string) => {
await startServer({ await startServer({
dir, dir,
isDev: false, isDev: false,
hostname: host, hostname,
port, port,
keepAliveTimeout, keepAliveTimeout,
}) })
......
...@@ -3,7 +3,7 @@ ...@@ -3,7 +3,7 @@
import { bold, cyan, green, red, yellow } from '../lib/picocolors' import { bold, cyan, green, red, yellow } from '../lib/picocolors'
import { Telemetry } from '../telemetry/storage' import { Telemetry } from '../telemetry/storage'
type NextTelemetryOptions = { export type NextTelemetryOptions = {
enable?: boolean enable?: boolean
disable?: boolean disable?: boolean
} }
......
import { isPlainObject } from '../shared/lib/is-plain-object' import { isPlainObject } from '../shared/lib/is-plain-object'
// We allow some additional attached properties for Errors // We allow some additional attached properties for Next.js errors
export interface NextError extends Error { export interface NextError extends Error {
type?: string type?: string
page?: string page?: string
...@@ -9,6 +9,10 @@ export interface NextError extends Error { ...@@ -9,6 +9,10 @@ export interface NextError extends Error {
digest?: number digest?: number
} }
/**
* Checks whether the given value is a NextError.
* This can be used to print a more detailed error message with properties like `code` & `digest`.
*/
export default function isError(err: unknown): err is NextError { export default function isError(err: unknown): err is NextError {
return ( return (
typeof err === 'object' && err !== null && 'name' in err && 'message' in err typeof err === 'object' && err !== null && 'name' in err && 'message' in err
......
...@@ -245,8 +245,12 @@ export function getFormattedNodeOptionsWithoutInspect() { ...@@ -245,8 +245,12 @@ export function getFormattedNodeOptionsWithoutInspect() {
return formatNodeOptions(args) return formatNodeOptions(args)
} }
export function myParseInt(value: string) { /**
// parseInt takes a string and a radix * Check if the value is a valid positive integer and parse it. If it's not, it will throw an error.
*
* @param value The value to be parsed.
*/
export function parseValidPositiveInteger(value: string): number {
const parsedValue = parseInt(value, 10) const parsedValue = parseInt(value, 10)
if (isNaN(parsedValue) || !isFinite(parsedValue) || parsedValue < 0) { if (isNaN(parsedValue) || !isFinite(parsedValue) || parsedValue < 0) {
......
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