Commit f02153b8 authored by Jimmy Lai's avatar Jimmy Lai

fix: convert bin/next to JavaScript for Yarn PnP compatibility

Yarn Berry PnP doesn't support shell script binaries - it tries to parse
them as JavaScript. Convert bin/next from shell script to JavaScript with
#!/usr/bin/env node shebang.

The JS wrapper:
- Detects platform/arch
- Looks for Rust CLI binary in @next/cli-* packages
- Falls back to dist/bin/next if not found

Benchmark: ~25-35ms overhead vs shell script (negligible for 500-1500ms startup)

Also removes next.cmd as npm/yarn auto-generate .cmd wrappers for JS bins.
parent 07550dc7
#!/bin/sh #!/usr/bin/env node
# Next.js CLI entry point // Next.js CLI entry point
# // Tries native Rust binary first, falls back to Node.js implementation
# Tries to use the native Rust binary for faster restarts, falls back to Node.js.
# The Rust binary is distributed via @next/cli-* platform-specific packages.
DIR="$(dirname "$0")" const { dirname, join } = require('path')
const { spawn } = require('child_process')
# Production: check installed @next/cli-* package (hoisted to node_modules/@next/cli-*) const platform = process.platform
for pkg in "$DIR"/../../@next/cli-*/next; do const arch = process.arch
[ -x "$pkg" ] && exec "$pkg" "$@"
done
# Fallback: Node.js (also used for in-repo development) // Map to @next/cli-* package names
exec node "$DIR/../dist/bin/next" "$@" const binaryMap = {
'darwin-arm64': '@next/cli-darwin-arm64',
'darwin-x64': '@next/cli-darwin-x64',
'linux-arm64': '@next/cli-linux-arm64',
'linux-x64': '@next/cli-linux-x64',
'win32-x64': '@next/cli-win32-x64-msvc',
'win32-arm64': '@next/cli-win32-arm64-msvc',
}
/**
* Fallback: spawn Node.js with the same flags the Rust binary would use.
* This ensures feature parity when the native binary isn't available.
*/
function runWithNode() {
const args = process.argv.slice(2)
const nodeArgs = ['--enable-source-maps']
// Parse args to handle --disable-source-maps like the Rust binary
const hasDisableSourceMaps = args.includes('--disable-source-maps')
if (hasDisableSourceMaps) {
nodeArgs.length = 0 // Clear the array - don't pass --enable-source-maps
}
// Extract --inspect flags (they must come before the script for Node.js)
const inspectArgs = []
const scriptArgs = []
for (const arg of args) {
if (arg.startsWith('--inspect')) {
inspectArgs.push(arg)
} else {
scriptArgs.push(arg)
}
}
const scriptPath = join(__dirname, '../dist/bin/next')
const child = spawn(
process.execPath,
[...nodeArgs, ...inspectArgs, scriptPath, ...scriptArgs],
{ stdio: 'inherit', env: process.env }
)
child.on('close', (code) => process.exit(code ?? 0))
}
const key = `${platform}-${arch}`
const pkg = binaryMap[key]
if (pkg) {
try {
// Use require.resolve() for robust package resolution
// Works with npm, yarn, pnpm, and various hoisting strategies
const pkgPath = require.resolve(`${pkg}/package.json`)
const binName = platform === 'win32' ? 'next.exe' : 'next'
const binPath = join(dirname(pkgPath), binName)
const child = spawn(binPath, process.argv.slice(2), {
stdio: 'inherit',
env: process.env,
})
child.on('close', (code) => process.exit(code ?? 0))
child.on('error', () => {
// Binary exists but failed to execute, fall through to JS with Node flags
runWithNode()
})
} catch {
// Package not installed, use JS implementation with Node flags
runWithNode()
}
} else {
// Unsupported platform, use JS implementation with Node flags
runWithNode()
}
@echo off
:: Next.js CLI entry point
::
:: Tries to use the native Rust binary for faster restarts, falls back to Node.js.
:: The Rust binary is distributed via @next/cli-* platform-specific packages.
setlocal
set "DIR=%~dp0"
:: Production: try native binary from @next/cli-* package (hoisted to node_modules/@next/cli-*)
if exist "%DIR%..\..\@next\cli-win32-x64-msvc\next.exe" (
"%DIR%..\..\@next\cli-win32-x64-msvc\next.exe" %*
exit /b %errorlevel%
)
if exist "%DIR%..\..\@next\cli-win32-arm64-msvc\next.exe" (
"%DIR%..\..\@next\cli-win32-arm64-msvc\next.exe" %*
exit /b %errorlevel%
)
:: Fallback: Node.js (also used for in-repo development)
node "%DIR%..\dist\bin\next" %*
...@@ -5,6 +5,10 @@ import { retry, waitFor } from 'next-test-utils' ...@@ -5,6 +5,10 @@ import { retry, waitFor } from 'next-test-utils'
import stripAnsi from 'strip-ansi' import stripAnsi from 'strip-ansi'
import { quote as shellQuote } from 'shell-quote' import { quote as shellQuote } from 'shell-quote'
// Exit code 77 signals that the server wants to be restarted (e.g., after config changes)
// The Rust CLI wrapper normally handles this, but in tests we need to handle it ourselves
const RESTART_EXIT_CODE = 77
export class NextDevInstance extends NextInstance { export class NextDevInstance extends NextInstance {
private _cliOutput: string = '' private _cliOutput: string = ''
...@@ -150,9 +154,7 @@ export class NextDevInstance extends NextInstance { ...@@ -150,9 +154,7 @@ export class NextDevInstance extends NextInstance {
} }
} }
console.log('running', shellQuote(startArgs)) const spawnServer = () => {
await new Promise<void>((resolve, reject) => {
try {
this.childProcess = spawn(startArgs[0], startArgs.slice(1), { this.childProcess = spawn(startArgs[0], startArgs.slice(1), {
cwd: this.testDir, cwd: this.testDir,
stdio: ['ignore', 'pipe', 'pipe'], stdio: ['ignore', 'pipe', 'pipe'],
...@@ -166,8 +168,6 @@ export class NextDevInstance extends NextInstance { ...@@ -166,8 +168,6 @@ export class NextDevInstance extends NextInstance {
}, },
}) })
this._cliOutput = ''
this.childProcess.stdout!.on('data', (chunk) => { this.childProcess.stdout!.on('data', (chunk) => {
const msg = chunk.toString() const msg = chunk.toString()
process.stdout.write(chunk) process.stdout.write(chunk)
...@@ -181,23 +181,51 @@ export class NextDevInstance extends NextInstance { ...@@ -181,23 +181,51 @@ export class NextDevInstance extends NextInstance {
this.emit('stderr', [msg]) this.emit('stderr', [msg])
}) })
return this.childProcess
}
console.log('running', shellQuote(startArgs))
await new Promise<void>((resolve, reject) => {
try {
spawnServer()
this._cliOutput = ''
const serverReadyTimeoutId = this.setServerReadyTimeout( const serverReadyTimeoutId = this.setServerReadyTimeout(
reject, reject,
this.startServerTimeout this.startServerTimeout
) )
this.childProcess.on('close', (code, signal) => { let isInitialStartup = true
const setupCloseHandler = () => {
this.childProcess!.on('close', (code, signal) => {
if (this.isStopping) return if (this.isStopping) return
// Handle restart exit code (77) - the Rust wrapper normally handles this,
// but in tests we need to restart the server ourselves
if (code === RESTART_EXIT_CODE) {
spawnServer()
setupCloseHandler()
return
}
if (code || signal) { if (code || signal) {
this.childProcess = undefined this.childProcess = undefined
const error = new Error( const error = new Error(
`next dev exited unexpectedly with code/signal ${code || signal}` `next dev exited unexpectedly with code/signal ${code || signal}`
) )
if (isInitialStartup) {
clearTimeout(serverReadyTimeoutId) clearTimeout(serverReadyTimeoutId)
require('console').error(error) require('console').error(error)
reject(error) reject(error)
} else {
// After initial startup, log but don't reject (promise already resolved)
require('console').error(error)
}
} }
}) })
}
setupCloseHandler()
const readyCb = (msg) => { const readyCb = (msg) => {
const resolveServer = () => { const resolveServer = () => {
...@@ -211,6 +239,7 @@ export class NextDevInstance extends NextInstance { ...@@ -211,6 +239,7 @@ export class NextDevInstance extends NextInstance {
}) })
} }
// server might reload so we keep listening // server might reload so we keep listening
isInitialStartup = false
resolve() resolve()
} }
......
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