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
# 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.
#!/usr/bin/env node
// Next.js CLI entry point
// Tries native Rust binary first, falls back to Node.js implementation
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-*)
for pkg in "$DIR"/../../@next/cli-*/next; do
[ -x "$pkg" ] && exec "$pkg" "$@"
done
const platform = process.platform
const arch = process.arch
# Fallback: Node.js (also used for in-repo development)
exec node "$DIR/../dist/bin/next" "$@"
// Map to @next/cli-* package names
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'
import stripAnsi from 'strip-ansi'
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 {
private _cliOutput: string = ''
......@@ -150,54 +154,78 @@ export class NextDevInstance extends NextInstance {
}
}
const spawnServer = () => {
this.childProcess = spawn(startArgs[0], startArgs.slice(1), {
cwd: this.testDir,
stdio: ['ignore', 'pipe', 'pipe'],
shell: false,
env: {
...process.env,
...this.env,
NODE_ENV: this.env.NODE_ENV || ('' as any),
PORT: this.forcedPort || '0',
__NEXT_TEST_MODE: 'e2e',
},
})
this.childProcess.stdout!.on('data', (chunk) => {
const msg = chunk.toString()
process.stdout.write(chunk)
this._cliOutput += msg
this.emit('stdout', [msg])
})
this.childProcess.stderr!.on('data', (chunk) => {
const msg = chunk.toString()
process.stderr.write(chunk)
this._cliOutput += msg
this.emit('stderr', [msg])
})
return this.childProcess
}
console.log('running', shellQuote(startArgs))
await new Promise<void>((resolve, reject) => {
try {
this.childProcess = spawn(startArgs[0], startArgs.slice(1), {
cwd: this.testDir,
stdio: ['ignore', 'pipe', 'pipe'],
shell: false,
env: {
...process.env,
...this.env,
NODE_ENV: this.env.NODE_ENV || ('' as any),
PORT: this.forcedPort || '0',
__NEXT_TEST_MODE: 'e2e',
},
})
spawnServer()
this._cliOutput = ''
this.childProcess.stdout!.on('data', (chunk) => {
const msg = chunk.toString()
process.stdout.write(chunk)
this._cliOutput += msg
this.emit('stdout', [msg])
})
this.childProcess.stderr!.on('data', (chunk) => {
const msg = chunk.toString()
process.stderr.write(chunk)
this._cliOutput += msg
this.emit('stderr', [msg])
})
const serverReadyTimeoutId = this.setServerReadyTimeout(
reject,
this.startServerTimeout
)
this.childProcess.on('close', (code, signal) => {
if (this.isStopping) return
if (code || signal) {
this.childProcess = undefined
const error = new Error(
`next dev exited unexpectedly with code/signal ${code || signal}`
)
clearTimeout(serverReadyTimeoutId)
require('console').error(error)
reject(error)
}
})
let isInitialStartup = true
const setupCloseHandler = () => {
this.childProcess!.on('close', (code, signal) => {
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) {
this.childProcess = undefined
const error = new Error(
`next dev exited unexpectedly with code/signal ${code || signal}`
)
if (isInitialStartup) {
clearTimeout(serverReadyTimeoutId)
require('console').error(error)
reject(error)
} else {
// After initial startup, log but don't reject (promise already resolved)
require('console').error(error)
}
}
})
}
setupCloseHandler()
const readyCb = (msg) => {
const resolveServer = () => {
......@@ -211,6 +239,7 @@ export class NextDevInstance extends NextInstance {
})
}
// server might reload so we keep listening
isInitialStartup = false
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