#!/usr/bin/env node // gateway: 直接运行开发用 native browser gateway;不依赖 systemd。 import { spawn } from "node:child_process"; import { existsSync, readFileSync } from "node:fs"; import os from "node:os"; import path from "node:path"; import { fileURLToPath } from "node:url"; const root = path.dirname(path.dirname(fileURLToPath(import.meta.url))); function readEnvFile(filePath) { if (!existsSync(filePath)) return {}; const values = {}; for (const line of readFileSync(filePath, "utf8").split("\n")) { const match = /^([A-Za-z_][A-Za-z0-9_]*)=(.*)$/.exec(line.trim()); if (match) values[match[1]] = match[2]; } return values; } const rootEnv = readEnvFile(path.join(root, ".env")); const gatewayEnvPath = process.env.CREATORHUB_BROWSER_GATEWAY_ENV ?? path.join(os.homedir(), ".config", "creatorhub", "browser-gateway.env"); const gatewayEnv = readEnvFile(gatewayEnvPath); const env = { ...process.env, ...rootEnv, ...gatewayEnv }; if (!env.LISTEN_ADDR) env.LISTEN_ADDR = "127.0.0.1:28187"; if (!env.GATEWAY_TOKEN) env.GATEWAY_TOKEN = "dev-creatorhub-gateway-token"; const port = env.LISTEN_ADDR.match(/:(\d+)$/)?.[1] ?? "28187"; try { const response = await fetch(`http://127.0.0.1:${port}/healthz`, { signal: AbortSignal.timeout(1000), }); if (response.status === 204 || response.ok) { console.log(`[dev-gateway] 已有 gateway 运行于 127.0.0.1:${port},直接复用。`); process.exit(0); } } catch { // The port is available or belongs to a different service; let the gateway report that clearly. } const gateway = spawn("python3", ["-m", "browser_gateway.server.http"], { cwd: root, env, stdio: "inherit", }); for (const signal of ["SIGINT", "SIGTERM"]) { process.on(signal, () => gateway.kill(signal)); } gateway.on("exit", (code, signal) => { if (signal) process.exit(1); process.exit(code ?? 0); });