Telemetry event for invalid CLI flags

parent c5263474
...@@ -136,6 +136,8 @@ function parseValidInspectAddress(value: string): DebugAddress { ...@@ -136,6 +136,8 @@ function parseValidInspectAddress(value: string): DebugAddress {
} }
const program = new NextRootCommand() const program = new NextRootCommand()
// Must be called before subcommands are defined so they inherit the override.
program.exitOverride()
program program
.name('next') .name('next')
...@@ -700,4 +702,52 @@ internal ...@@ -700,4 +702,52 @@ internal
}) })
.usage('[directory] [options]') .usage('[directory] [options]')
program.parse(process.argv) try {
program.parse(process.argv)
} catch (err: any) {
if (err?.code === 'commander.unknownOption') {
const match = /unknown option '([^']+)'/.exec(err.message)
const unknownFlag = match?.[1] ?? ''
const firstArg = program.args?.[0]
const cliCommand = firstArg && !firstArg.startsWith('-') ? firstArg : 'dev'
// Commander already wrote the error message to stderr before throwing,
// so we don't need to re-print it.
const exitWithError = () => {
process.exit(err.exitCode ?? 1)
}
if (cliCommand === 'dev' || cliCommand === 'build') {
Promise.all([
import('../telemetry/storage.js'),
import('../telemetry/events/unknown-cli-flag.js'),
])
.then(async ([{ Telemetry }, { eventUnknownCliFlag }]) => {
// Submit the event inline. We can't use flushDetached here because
// the detached child computes distDir via loadConfig, which may
// disagree with any path we guess (e.g. dev mode uses `.next/dev`).
// The submitRecord HTTP call has a 5s timeout, which is acceptable
// on an already-failing command.
//
// distDir: process.cwd() mirrors `next telemetry` (see
// cli/next-telemetry.ts) — we have no loaded config at this point.
const telemetry = new Telemetry({ distDir: process.cwd() })
await telemetry.record(
eventUnknownCliFlag({ cliCommand, unknownFlag })
)
await telemetry.flush()
})
.catch(() => {})
.finally(exitWithError)
} else {
exitWithError()
}
} else if (
typeof err?.code === 'string' &&
err.code.startsWith('commander.')
) {
process.exit(err.exitCode ?? 1)
} else {
throw err
}
}
export * from './version' export * from './version'
export * from './build' export * from './build'
export * from './plugins' export * from './plugins'
export * from './unknown-cli-flag'
// Re-export MCP-specific types and functions // Re-export MCP-specific types and functions
export type { McpToolName, EventMcpToolUsage } from './build' export type { McpToolName, EventMcpToolUsage } from './build'
......
const EVENT_UNKNOWN_CLI_FLAG = 'NEXT_CLI_UNKNOWN_FLAG'
type EventUnknownCliFlag = {
cliCommand: string
unknownFlag: string
}
export function eventUnknownCliFlag(event: EventUnknownCliFlag): {
eventName: string
payload: EventUnknownCliFlag
} {
return {
eventName: EVENT_UNKNOWN_CLI_FLAG,
payload: event,
}
}
...@@ -371,16 +371,34 @@ describe('CLI Usage', () => { ...@@ -371,16 +371,34 @@ describe('CLI Usage', () => {
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,
env: { NEXT_TELEMETRY_DISABLED: '1' },
}) })
expect(stderr).toEqual(`error: unknown 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'], {
stderr: true, stderr: true,
env: { NEXT_TELEMETRY_DISABLED: '1' },
}) })
expect(stderr).not.toContain('UnhandledPromiseRejectionWarning') expect(stderr).not.toContain('UnhandledPromiseRejectionWarning')
}) })
test('should record telemetry event for unknown flag', async () => {
const { stderr, code } = await runNextCommand(
['build', '--not-a-real-flag'],
{
stderr: true,
ignoreFail: true,
env: { NEXT_TELEMETRY_DEBUG: '1' },
}
)
expect(code).toBe(1)
expect(stderr).toContain(`unknown option '--not-a-real-flag'`)
expect(stderr).toContain('NEXT_CLI_UNKNOWN_FLAG')
expect(stderr).toContain('"cliCommand": "build"')
expect(stderr).toContain('"unknownFlag": "--not-a-real-flag"')
})
test('should exit when SIGINT is signalled', async () => { test('should exit when SIGINT is signalled', async () => {
await testExitSignal('SIGINT', ['build', dirBasic], undefined, 130) await testExitSignal('SIGINT', ['build', dirBasic], undefined, 130)
}) })
...@@ -482,6 +500,36 @@ describe('CLI Usage', () => { ...@@ -482,6 +500,36 @@ describe('CLI Usage', () => {
expect(help.stdout).toMatch(/Starts Next.js in development mode/) expect(help.stdout).toMatch(/Starts Next.js in development mode/)
}) })
test('should record telemetry event for unknown flag', async () => {
const { stderr, code } = await runNextCommand(
['dev', '--not-a-real-flag'],
{
stderr: true,
ignoreFail: true,
env: { NEXT_TELEMETRY_DEBUG: '1' },
}
)
expect(code).toBe(1)
expect(stderr).toContain(`unknown option '--not-a-real-flag'`)
expect(stderr).toContain('NEXT_CLI_UNKNOWN_FLAG')
expect(stderr).toContain('"cliCommand": "dev"')
expect(stderr).toContain('"unknownFlag": "--not-a-real-flag"')
})
test('should not record telemetry event for unknown flag on other subcommands', async () => {
const { stderr, code } = await runNextCommand(
['start', '--not-a-real-flag'],
{
stderr: true,
ignoreFail: true,
env: { NEXT_TELEMETRY_DEBUG: '1' },
}
)
expect(code).toBe(1)
expect(stderr).toContain(`unknown option '--not-a-real-flag'`)
expect(stderr).not.toContain('NEXT_CLI_UNKNOWN_FLAG')
})
test('custom directory', async () => { test('custom directory', async () => {
const port = await findPort() const port = await findPort()
let output = '' let output = ''
......
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