|
| 1 | +import { randomBytes } from 'node:crypto' |
| 2 | +import { mkdtempSync, rmSync, writeFileSync } from 'node:fs' |
| 3 | +import { tmpdir } from 'node:os' |
| 4 | +import { join, dirname } from 'node:path' |
| 5 | +import { fileURLToPath } from 'node:url' |
| 6 | +import net from 'node:net' |
| 7 | +import { spawn, execSync } from 'node:child_process' |
| 8 | +import type { ChildProcess } from 'node:child_process' |
| 9 | + |
| 10 | +// Workers can't inherit process.env from globalSetup, so we write config to a file |
| 11 | +// and let setupFile.ts read it in each worker. |
| 12 | +export const TEST_CONFIG_FILE = join(tmpdir(), 'hapi-test-config.json') |
| 13 | + |
| 14 | +async function getFreePort(): Promise<number> { |
| 15 | + return new Promise((resolve, reject) => { |
| 16 | + const server = net.createServer() |
| 17 | + server.listen(0, '127.0.0.1', () => { |
| 18 | + const addr = server.address() as net.AddressInfo |
| 19 | + server.close(() => resolve(addr.port)) |
| 20 | + }) |
| 21 | + server.on('error', reject) |
| 22 | + }) |
| 23 | +} |
| 24 | + |
| 25 | +async function waitForHub(baseUrl: string, timeoutMs = 15_000): Promise<void> { |
| 26 | + const healthUrl = `${baseUrl}/health` |
| 27 | + const start = Date.now() |
| 28 | + while (Date.now() - start < timeoutMs) { |
| 29 | + try { |
| 30 | + const res = await fetch(healthUrl, { signal: AbortSignal.timeout(1000) }) |
| 31 | + if (res.ok) return |
| 32 | + } catch { |
| 33 | + // not ready yet — connection refused or timeout |
| 34 | + } |
| 35 | + await new Promise(resolve => setTimeout(resolve, 200)) |
| 36 | + } |
| 37 | + throw new Error(`Hub did not become ready within ${timeoutMs}ms`) |
| 38 | +} |
| 39 | + |
| 40 | +function findBunExec(): string { |
| 41 | + const cmd = process.platform === 'win32' ? 'where bun' : 'command -v bun' |
| 42 | + const p = execSync(cmd, { encoding: 'utf8' }) |
| 43 | + .split(/\r?\n/) |
| 44 | + .map(line => line.trim()) |
| 45 | + .find(Boolean) |
| 46 | + if (!p) throw new Error('[globalSetup] bun executable not found') |
| 47 | + return p |
| 48 | +} |
| 49 | + |
| 50 | +let hubProcess: ChildProcess | null = null |
| 51 | +let tmpHome: string | null = null |
| 52 | + |
| 53 | +export async function setup() { |
| 54 | + const port = await getFreePort() |
| 55 | + tmpHome = mkdtempSync(join(tmpdir(), 'hapi-test-')) |
| 56 | + const token = randomBytes(20).toString('base64url') |
| 57 | + const bunExec = findBunExec() |
| 58 | + |
| 59 | + // Use a minimal env whitelist to prevent shell credentials (DB_PATH, |
| 60 | + // TELEGRAM_BOT_TOKEN, ELEVENLABS_API_KEY, etc.) from leaking into the |
| 61 | + // test hub and triggering real notifications or opening a production DB. |
| 62 | + const hubEnv: NodeJS.ProcessEnv = { |
| 63 | + PATH: process.env.PATH, |
| 64 | + HOME: process.env.HOME, |
| 65 | + ...(process.env.TMPDIR ? { TMPDIR: process.env.TMPDIR } : {}), |
| 66 | + ...(process.env.BUN_INSTALL ? { BUN_INSTALL: process.env.BUN_INSTALL } : {}), |
| 67 | + HAPI_HOME: tmpHome, |
| 68 | + DB_PATH: join(tmpHome, 'hapi.db'), |
| 69 | + HAPI_LISTEN_PORT: String(port), |
| 70 | + HAPI_LISTEN_HOST: '127.0.0.1', |
| 71 | + HAPI_PUBLIC_URL: `http://127.0.0.1:${port}`, |
| 72 | + CLI_API_TOKEN: token, |
| 73 | + TELEGRAM_NOTIFICATION: 'false', |
| 74 | + SERVERCHAN_NOTIFICATION: 'false', |
| 75 | + } |
| 76 | + |
| 77 | + // Write config so setupFile.ts can inject env vars into each test worker |
| 78 | + writeFileSync(TEST_CONFIG_FILE, JSON.stringify({ port, token, tmpHome, bunExec })) |
| 79 | + |
| 80 | + const hubEntry = join( |
| 81 | + dirname(fileURLToPath(import.meta.url)), |
| 82 | + '../../../hub/src/index.ts' |
| 83 | + ) |
| 84 | + |
| 85 | + hubProcess = spawn(bunExec, ['run', hubEntry], { |
| 86 | + env: hubEnv, |
| 87 | + stdio: 'ignore', |
| 88 | + }) |
| 89 | + |
| 90 | + hubProcess.on('error', (err) => { |
| 91 | + throw new Error(`[globalSetup] Failed to spawn hub: ${err.message}`) |
| 92 | + }) |
| 93 | + |
| 94 | + await waitForHub(`http://127.0.0.1:${port}`) |
| 95 | +} |
| 96 | + |
| 97 | +async function stopHubProcess(): Promise<void> { |
| 98 | + if (!hubProcess || hubProcess.exitCode !== null) return |
| 99 | + |
| 100 | + await new Promise<void>((resolve) => { |
| 101 | + const timeout = setTimeout(resolve, 5_000) |
| 102 | + hubProcess!.once('exit', () => { |
| 103 | + clearTimeout(timeout) |
| 104 | + resolve() |
| 105 | + }) |
| 106 | + hubProcess!.kill() |
| 107 | + }) |
| 108 | +} |
| 109 | + |
| 110 | +export async function teardown() { |
| 111 | + await stopHubProcess() |
| 112 | + try { rmSync(TEST_CONFIG_FILE) } catch {} |
| 113 | + if (tmpHome) { |
| 114 | + rmSync(tmpHome, { recursive: true, force: true }) |
| 115 | + } |
| 116 | +} |
0 commit comments