File size: 6,957 Bytes
1e92f2d |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 |
import { execSync, spawn } from 'child_process'
import { join } from 'path'
import { fileURLToPath } from 'url'
import fetch from 'node-fetch'
import {
existsSync,
readFileSync,
writeFileSync,
unlinkSync,
promises as fs,
} from 'fs'
import prettyMs from 'pretty-ms'
import treeKill from 'tree-kill'
const ROOT_DIR = join(fileURLToPath(import.meta.url), '..', '..', '..')
const CWD = join(ROOT_DIR, 'bench', 'nested-deps-app-router')
const NEXT_BIN = join(ROOT_DIR, 'packages', 'next', 'dist', 'bin', 'next')
const [, , command = 'all'] = process.argv
async function killApp(instance) {
await new Promise((resolve, reject) => {
treeKill(instance.pid, (err) => {
if (err) {
if (
process.platform === 'win32' &&
typeof err.message === 'string' &&
(err.message.includes(`no running instance of the task`) ||
err.message.includes(`not found`))
) {
// Windows throws an error if the process is already stopped
//
// Command failed: taskkill /pid 6924 /T /F
// ERROR: The process with PID 6924 (child process of PID 6736) could not be terminated.
// Reason: There is no running instance of the task.
return resolve()
}
return reject(err)
}
resolve()
})
})
}
class File {
constructor(path) {
this.path = path
this.originalContent = existsSync(this.path)
? readFileSync(this.path, 'utf8')
: null
}
write(content) {
if (!this.originalContent) {
this.originalContent = content
}
writeFileSync(this.path, content, 'utf8')
}
replace(pattern, newValue) {
const currentContent = readFileSync(this.path, 'utf8')
if (pattern instanceof RegExp) {
if (!pattern.test(currentContent)) {
throw new Error(
`Failed to replace content.\n\nPattern: ${pattern.toString()}\n\nContent: ${currentContent}`
)
}
} else if (typeof pattern === 'string') {
if (!currentContent.includes(pattern)) {
throw new Error(
`Failed to replace content.\n\nPattern: ${pattern}\n\nContent: ${currentContent}`
)
}
} else {
throw new Error(`Unknown replacement attempt type: ${pattern}`)
}
const newContent = currentContent.replace(pattern, newValue)
this.write(newContent)
}
prepend(line) {
const currentContent = readFileSync(this.path, 'utf8')
this.write(line + '\n' + currentContent)
}
delete() {
unlinkSync(this.path)
}
restore() {
this.write(this.originalContent)
}
}
function runNextCommandDev(argv, opts = {}) {
const env = {
...process.env,
NODE_ENV: undefined,
__NEXT_TEST_MODE: 'true',
FORCE_COLOR: 3,
...opts.env,
}
const nodeArgs = opts.nodeArgs || []
return new Promise((resolve, reject) => {
const instance = spawn(NEXT_BIN, [...nodeArgs, ...argv], {
cwd: CWD,
env,
})
let didResolve = false
function handleStdout(data) {
const message = data.toString()
const bootupMarkers = {
dev: /Ready in .*/i,
start: /started server/i,
}
if (
(opts.bootupMarker && opts.bootupMarker.test(message)) ||
bootupMarkers[opts.nextStart ? 'start' : 'dev'].test(message)
) {
if (!didResolve) {
didResolve = true
resolve(instance)
instance.removeListener('data', handleStdout)
}
}
if (typeof opts.onStdout === 'function') {
opts.onStdout(message)
}
if (opts.stdout !== false) {
process.stdout.write(message)
}
}
function handleStderr(data) {
const message = data.toString()
if (typeof opts.onStderr === 'function') {
opts.onStderr(message)
}
if (opts.stderr !== false) {
process.stderr.write(message)
}
}
instance.stdout.on('data', handleStdout)
instance.stderr.on('data', handleStderr)
instance.on('close', () => {
instance.stdout.removeListener('data', handleStdout)
instance.stderr.removeListener('data', handleStderr)
if (!didResolve) {
didResolve = true
resolve()
}
})
instance.on('error', (err) => {
reject(err)
})
})
}
function waitFor(millis) {
return new Promise((resolve) => setTimeout(resolve, millis))
}
for (const testCase of [
'client-components-only',
'server-and-client-components',
'server-components-only',
]) {
await fs.rm('.next', { recursive: true }).catch(() => {})
const file = new File(join(CWD, `app/${testCase}/page.js`))
const results = []
try {
if (command === 'dev' || command === 'all') {
const instance = await runNextCommandDev(['dev', '--port', '3000'])
function waitForCompiled() {
return new Promise((resolve) => {
function waitForOnData(data) {
const message = data.toString()
const compiledRegex =
/Compiled (?:.+ )?in (\d*[.]?\d+)\s*(m?s)(?: \((\d+) modules\))?/gm
const matched = compiledRegex.exec(message)
if (matched) {
resolve({
'time (ms)':
(matched[2] === 's' ? 1000 : 1) * Number(matched[1]),
modules: Number(matched[3]),
})
instance.stdout.removeListener('data', waitForOnData)
}
}
instance.stdout.on('data', waitForOnData)
})
}
const [res, initial] = await Promise.all([
fetch(`http://localhost:3000/${testCase}`),
waitForCompiled(),
])
if (res.status !== 200) {
throw new Error(`Fetching /${testCase} failed`)
}
results.push(initial)
await waitFor(1000)
file.replace('Hello', 'Hello!')
results.push(await waitForCompiled())
await waitFor(1000)
file.replace('Hello', 'Hello!')
results.push(await waitForCompiled())
await waitFor(1000)
file.replace('Hello', 'Hello!')
results.push(await waitForCompiled())
console.table(results)
await killApp(instance)
}
if (command === 'build' || command === 'all') {
// ignore error
await fs.rm('.next', { recursive: true, force: true }).catch(() => {})
execSync(`node ${NEXT_BIN} build ./bench/nested-deps-app-router`, {
cwd: ROOT_DIR,
stdio: 'inherit',
env: {
...process.env,
TRACE_TARGET: 'jaeger',
},
})
const traceString = await fs.readFile(join(CWD, '.next', 'trace'), 'utf8')
const traces = traceString
.split('\n')
.filter((line) => line)
.map((line) => JSON.parse(line))
const { duration } = traces
.pop()
.find(({ name }) => name === 'next-build')
console.info('next build duration: ', prettyMs(duration / 1000))
}
} finally {
file.restore()
}
}
|