()
| 238 | } |
| 239 | |
| 240 | async function main() { |
| 241 | const port = readArgValue(['--port', '-p']); |
| 242 | const publicPort = process.env.MC_PUBLIC_PORT || '4731'; |
| 243 | const isCloudflarePort = port === publicPort; |
| 244 | const distDir = isCloudflarePort ? (process.env.MC_PUBLIC_DIST_DIR || '.next') : '.next'; |
| 245 | const nextEnv = { |
| 246 | ...process.env, |
| 247 | MC_RUNTIME_WRAPPER: 'dev-server', |
| 248 | }; |
| 249 | |
| 250 | if (distDir !== '.next') { |
| 251 | nextEnv.NEXT_DIST_DIR = distDir; |
| 252 | } |
| 253 | |
| 254 | rmSync(path.join(process.cwd(), distDir), { recursive: true, force: true }); |
| 255 | |
| 256 | if (isCloudflarePort) { |
| 257 | console.log(`[dev-server] port 4731 detected -> using production server with dist dir (${distDir})`); |
| 258 | const buildCode = await runNext(['build', '--webpack'], nextEnv); |
| 259 | if (buildCode !== 0) { |
| 260 | process.exit(buildCode); |
| 261 | } |
| 262 | |
| 263 | const bindHost = process.env.MC_BIND_HOST || '127.0.0.1'; |
| 264 | const smokeHost = bindHost === '0.0.0.0' ? '127.0.0.1' : bindHost; |
| 265 | const internalPort = String(Number(publicPort) + 10); |
| 266 | const internalArgs = ['start', '-H', bindHost, '-p', internalPort]; |
| 267 | const child = spawnNext(internalArgs, nextEnv); |
| 268 | let processKeepAlive = null; |
| 269 | let shuttingDown = false; |
| 270 | let publicSmokeFailed = false; |
| 271 | |
| 272 | const server = http.createServer((request, response) => { |
| 273 | if (tryServeStaticAsset(request, response, distDir)) { |
| 274 | return; |
| 275 | } |
| 276 | |
| 277 | proxyToInternal(request, response, smokeHost, internalPort); |
| 278 | }); |
| 279 | |
| 280 | const shutdown = () => { |
| 281 | if (shuttingDown) return; |
| 282 | shuttingDown = true; |
| 283 | if (processKeepAlive) { |
| 284 | clearInterval(processKeepAlive); |
| 285 | processKeepAlive = null; |
| 286 | } |
| 287 | server.close(() => { |
| 288 | child.kill('SIGTERM'); |
| 289 | }); |
| 290 | }; |
| 291 | |
| 292 | process.on('SIGINT', shutdown); |
| 293 | process.on('SIGTERM', shutdown); |
| 294 | |
| 295 | child.on('exit', (code, signal) => { |
| 296 | if (shuttingDown) { |
| 297 | process.exit(publicSmokeFailed ? 1 : (code ?? 0)); |
no test coverage detected