|
| 1 | +import { type ChildProcess, spawn } from 'node:child_process' |
| 2 | +import { once } from 'node:events' |
| 3 | +import { mkdtemp, rm } from 'node:fs/promises' |
| 4 | +import http from 'node:http' |
| 5 | +import { createRequire } from 'node:module' |
| 6 | +import net from 'node:net' |
| 7 | +import os from 'node:os' |
| 8 | +import path from 'node:path' |
| 9 | +import { fileURLToPath } from 'node:url' |
| 10 | + |
| 11 | +/** |
| 12 | + * Boots `next start` over the production build in `.next` and checks the |
| 13 | + * behaviour a Next or React upgrade can break without failing the build: |
| 14 | + * config redirects and headers, the proxy's locale and self-host gate, |
| 15 | + * server-rendered pages, route handlers, and that force-dynamic scene reads |
| 16 | + * are never served from a cache. |
| 17 | + */ |
| 18 | + |
| 19 | +const appDirectory = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..') |
| 20 | +const dataDirectory = await mkdtemp(path.join(os.tmpdir(), 'pascal-next-smoke-')) |
| 21 | +const port = await freePort() |
| 22 | +const origin = `http://127.0.0.1:${port}` |
| 23 | +let server: ChildProcess | null = null |
| 24 | +const serverOutput: string[] = [] |
| 25 | +const REQUEST_TIMEOUT_MS = 15_000 |
| 26 | + |
| 27 | +for (const signal of ['SIGINT', 'SIGTERM'] as const) { |
| 28 | + process.once(signal, () => { |
| 29 | + server?.kill('SIGKILL') |
| 30 | + process.exit(1) |
| 31 | + }) |
| 32 | +} |
| 33 | + |
| 34 | +try { |
| 35 | + // Production runs `next start` on Node, so the smoke does too (not Bun's Node compatibility). |
| 36 | + server = spawn( |
| 37 | + 'node', |
| 38 | + [ |
| 39 | + createRequire(import.meta.url).resolve('next/dist/bin/next'), |
| 40 | + 'start', |
| 41 | + '-H', |
| 42 | + '127.0.0.1', |
| 43 | + '-p', |
| 44 | + String(port), |
| 45 | + ], |
| 46 | + { |
| 47 | + cwd: appDirectory, |
| 48 | + env: { |
| 49 | + ...process.env, |
| 50 | + NODE_ENV: 'production', |
| 51 | + PASCAL_DATA_DIR: dataDirectory, |
| 52 | + PASCAL_ADMIN_PASSWORD: '', |
| 53 | + PASCAL_AUTH: '', |
| 54 | + PASCAL_SCENE_API_TOKEN: '', |
| 55 | + }, |
| 56 | + stdio: ['ignore', 'pipe', 'pipe'], |
| 57 | + }, |
| 58 | + ) |
| 59 | + server.stdout?.on('data', (chunk: Buffer) => serverOutput.push(chunk.toString())) |
| 60 | + server.stderr?.on('data', (chunk: Buffer) => serverOutput.push(chunk.toString())) |
| 61 | + await waitForHealth() |
| 62 | + |
| 63 | + await check('health route answers JSON', async () => { |
| 64 | + const response = await get(`${origin}/api/health`) |
| 65 | + expect(response.status === 200, `status ${response.status}`) |
| 66 | + const body = (await response.json()) as { status?: string; app?: string } |
| 67 | + expect(body.status === 'ok' && body.app === 'editor', JSON.stringify(body)) |
| 68 | + }) |
| 69 | + |
| 70 | + await check('config redirects keep old links working', async () => { |
| 71 | + for (const [from, to] of [ |
| 72 | + ['/editor/smoke', '/project/smoke'], |
| 73 | + ['/scene/smoke', '/project/smoke'], |
| 74 | + ['/scenes', '/'], |
| 75 | + ]) { |
| 76 | + const response = await get(`${origin}${from}`, { redirect: 'manual' }) |
| 77 | + const location = new URL(response.headers.get('location') ?? '', origin).pathname |
| 78 | + expect( |
| 79 | + response.status === 307 && location === to, |
| 80 | + `${from}: ${response.status} → ${location}`, |
| 81 | + ) |
| 82 | + } |
| 83 | + }) |
| 84 | + |
| 85 | + await check('embed pages allow framing', async () => { |
| 86 | + const response = await get(`${origin}/embed/smoke`) |
| 87 | + const policy = response.headers.get('content-security-policy') |
| 88 | + expect(policy === 'frame-ancestors *', `content-security-policy: ${policy}`) |
| 89 | + }) |
| 90 | + |
| 91 | + await check('the proxy passes ?lang to the server-rendered layout', async () => { |
| 92 | + for (const [query, lang] of [ |
| 93 | + ['', 'en'], |
| 94 | + ['?lang=fr', 'fr'], |
| 95 | + ]) { |
| 96 | + const response = await get(`${origin}/${query}`) |
| 97 | + const html = await response.text() |
| 98 | + expect(response.status === 200, `/${query}: status ${response.status}`) |
| 99 | + expect( |
| 100 | + new RegExp(`<html[^>]*\\slang="${lang}"`).test(html), |
| 101 | + `/${query} did not render <html lang="${lang}">`, |
| 102 | + ) |
| 103 | + } |
| 104 | + }) |
| 105 | + |
| 106 | + await check('the proxy gates a non-loopback host', async () => { |
| 107 | + const page = await requestWithHost('/', 'editor.example.com') |
| 108 | + expect( |
| 109 | + page.status === 307 && page.location?.endsWith('/setup') === true, |
| 110 | + `page: ${page.status} → ${page.location}`, |
| 111 | + ) |
| 112 | + const api = await requestWithHost('/api/plugins/mint/manifest', 'editor.example.com') |
| 113 | + expect( |
| 114 | + api.status === 503 && api.body.includes('self_host_unconfigured'), |
| 115 | + `api: ${api.status} ${api.body}`, |
| 116 | + ) |
| 117 | + }) |
| 118 | + |
| 119 | + await check('scene routes round-trip without serving stale reads', async () => { |
| 120 | + const created = await get(`${origin}/api/scenes`, { |
| 121 | + method: 'POST', |
| 122 | + headers: { 'content-type': 'application/json' }, |
| 123 | + body: JSON.stringify({ id: 'smoke-scene', name: 'Smoke scene', graph: sceneGraph() }), |
| 124 | + }) |
| 125 | + expect(created.status === 201, `create: ${created.status} ${await created.clone().text()}`) |
| 126 | + |
| 127 | + const first = (await (await get(`${origin}/api/scenes/smoke-scene`)).json()) as { |
| 128 | + name?: string |
| 129 | + version?: number |
| 130 | + } |
| 131 | + expect(first.name === 'Smoke scene', `first read: ${JSON.stringify(first)}`) |
| 132 | + |
| 133 | + const renamed = await get(`${origin}/api/scenes/smoke-scene`, { |
| 134 | + method: 'PATCH', |
| 135 | + headers: { 'content-type': 'application/json', 'if-match': `"${first.version}"` }, |
| 136 | + body: JSON.stringify({ name: 'Renamed smoke scene' }), |
| 137 | + }) |
| 138 | + expect(renamed.status === 200, `rename: ${renamed.status} ${await renamed.clone().text()}`) |
| 139 | + |
| 140 | + const second = (await (await get(`${origin}/api/scenes/smoke-scene`)).json()) as { |
| 141 | + name?: string |
| 142 | + } |
| 143 | + expect(second.name === 'Renamed smoke scene', `read after rename: ${JSON.stringify(second)}`) |
| 144 | + |
| 145 | + const listed = (await (await get(`${origin}/api/scenes`)).json()) as { |
| 146 | + scenes?: Array<{ id: string; name: string }> |
| 147 | + } |
| 148 | + expect( |
| 149 | + listed.scenes?.some((scene) => scene.id === 'smoke-scene' && scene.name === second.name) === |
| 150 | + true, |
| 151 | + `list: ${JSON.stringify(listed)}`, |
| 152 | + ) |
| 153 | + |
| 154 | + const stale = await get(`${origin}/api/scenes/smoke-scene`, { |
| 155 | + method: 'PATCH', |
| 156 | + headers: { 'content-type': 'application/json', 'if-match': `"${first.version}"` }, |
| 157 | + body: JSON.stringify({ name: 'Lost update' }), |
| 158 | + }) |
| 159 | + expect(stale.status === 409, `stale rename: ${stale.status}`) |
| 160 | + }) |
| 161 | + |
| 162 | + await check('a saved project page renders on the server', async () => { |
| 163 | + const response = await get(`${origin}/project/smoke-scene`) |
| 164 | + expect(response.status === 200, `status ${response.status}`) |
| 165 | + expect((await response.text()).includes('<html'), 'no HTML document') |
| 166 | + }) |
| 167 | + |
| 168 | + await check('the image optimizer serves raster images and refuses SVG', async () => { |
| 169 | + const raster = await get(`${origin}/_next/image?url=%2Ficons%2Fappliance.webp&w=64&q=75`) |
| 170 | + expect( |
| 171 | + raster.status === 200 && raster.headers.get('content-type')?.startsWith('image/') === true, |
| 172 | + `webp: ${raster.status} ${raster.headers.get('content-type')}`, |
| 173 | + ) |
| 174 | + const svg = await get(`${origin}/_next/image?url=%2Fglobe.svg&w=64&q=75`) |
| 175 | + const body = await svg.text() |
| 176 | + expect( |
| 177 | + svg.status === 400 && body.includes('image type is not allowed'), |
| 178 | + `svg: ${svg.status} ${body}`, |
| 179 | + ) |
| 180 | + }) |
| 181 | + |
| 182 | + console.log(`Next production server smoke passed on ${origin}.`) |
| 183 | +} catch (error) { |
| 184 | + console.error(serverOutput.join('').slice(-4000)) |
| 185 | + throw error |
| 186 | +} finally { |
| 187 | + await stopServer() |
| 188 | + await rm(dataDirectory, { recursive: true, force: true }) |
| 189 | +} |
| 190 | + |
| 191 | +function sceneGraph() { |
| 192 | + const levelId = 'level_smoke' |
| 193 | + return { |
| 194 | + nodes: { [levelId]: { object: 'node', id: levelId, type: 'level', level: 0, children: [] } }, |
| 195 | + rootNodeIds: [levelId], |
| 196 | + } |
| 197 | +} |
| 198 | + |
| 199 | +function get(url: string, init: RequestInit = {}): Promise<Response> { |
| 200 | + return fetch(url, { ...init, signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS) }) |
| 201 | +} |
| 202 | + |
| 203 | +async function stopServer(): Promise<void> { |
| 204 | + if (!server || server.exitCode !== null || server.signalCode !== null) return |
| 205 | + const exited = once(server, 'exit') |
| 206 | + server.kill('SIGTERM') |
| 207 | + const timer = setTimeout(() => server?.kill('SIGKILL'), 10_000) |
| 208 | + await exited |
| 209 | + clearTimeout(timer) |
| 210 | +} |
| 211 | + |
| 212 | +async function check(name: string, run: () => Promise<void>): Promise<void> { |
| 213 | + await run() |
| 214 | + console.log(`ok - ${name}`) |
| 215 | +} |
| 216 | + |
| 217 | +function expect(condition: boolean, detail: string): asserts condition { |
| 218 | + if (!condition) throw new Error(detail) |
| 219 | +} |
| 220 | + |
| 221 | +async function waitForHealth(): Promise<void> { |
| 222 | + const deadline = Date.now() + 60_000 |
| 223 | + while (Date.now() < deadline) { |
| 224 | + if (!server || server.exitCode !== null || server.signalCode !== null) { |
| 225 | + throw new Error(`next start exited (${server?.exitCode ?? server?.signalCode})`) |
| 226 | + } |
| 227 | + try { |
| 228 | + const response = await fetch(`${origin}/api/health`, { signal: AbortSignal.timeout(2_000) }) |
| 229 | + if (response.ok) return |
| 230 | + } catch {} |
| 231 | + await new Promise((resolve) => setTimeout(resolve, 250)) |
| 232 | + } |
| 233 | + throw new Error('next start did not become healthy within 60 s') |
| 234 | +} |
| 235 | + |
| 236 | +function requestWithHost( |
| 237 | + pathname: string, |
| 238 | + host: string, |
| 239 | +): Promise<{ status: number; location?: string; body: string }> { |
| 240 | + return new Promise((resolve, reject) => { |
| 241 | + const request = http.request( |
| 242 | + { host: '127.0.0.1', port, path: pathname, headers: { host } }, |
| 243 | + (response) => { |
| 244 | + const chunks: Buffer[] = [] |
| 245 | + response.on('data', (chunk: Buffer) => chunks.push(chunk)) |
| 246 | + response.on('end', () => |
| 247 | + resolve({ |
| 248 | + status: response.statusCode ?? 0, |
| 249 | + location: response.headers.location, |
| 250 | + body: Buffer.concat(chunks).toString('utf8'), |
| 251 | + }), |
| 252 | + ) |
| 253 | + }, |
| 254 | + ) |
| 255 | + request.setTimeout(REQUEST_TIMEOUT_MS, () => |
| 256 | + request.destroy(new Error(`${pathname} timed out`)), |
| 257 | + ) |
| 258 | + request.on('error', reject) |
| 259 | + request.end() |
| 260 | + }) |
| 261 | +} |
| 262 | + |
| 263 | +function freePort(): Promise<number> { |
| 264 | + return new Promise((resolve, reject) => { |
| 265 | + const probe = net.createServer() |
| 266 | + probe.once('error', reject) |
| 267 | + probe.listen(0, '127.0.0.1', () => { |
| 268 | + const address = probe.address() |
| 269 | + probe.close(() => |
| 270 | + typeof address === 'object' && address |
| 271 | + ? resolve(address.port) |
| 272 | + : reject(new Error('no port')), |
| 273 | + ) |
| 274 | + }) |
| 275 | + }) |
| 276 | +} |
0 commit comments