diff --git a/scripts/start.mjs b/scripts/start.mjs index 1dd3eda..433f9ba 100755 --- a/scripts/start.mjs +++ b/scripts/start.mjs @@ -26,15 +26,24 @@ for (const f of [".env", ".env.local"]) { const isSet = (v) => !!v && !/^your[_-]|your-project|YOUR-PASSWORD/.test(v); // same rule as lib/setup.ts const ready = ["NEXT_PUBLIC_SUPABASE_URL", "NEXT_PUBLIC_SUPABASE_PUBLISHABLE_KEY", "SUPABASE_SERVICE_ROLE_KEY"].every((k) => isSet(env[k])); -const port = process.env.PORT || "3000"; +// The first port that is free or already running broke. Something else on 3000 (another dev server, a video render) +// moves broke along to 3001, 3002 and so on, instead of failing or opening the wrong page. +const isBroke = (p) => fetch(`http://localhost:${p}/api/setup/first-run`, { redirect: "manual" }).then((r) => r.ok && (r.headers.get("content-type") ?? "").includes("json"), () => false); +const isFree = (p) => fetch(`http://localhost:${p}/`, { redirect: "manual" }).then(() => false, () => true); +let port = Number(process.env.PORT || 3000), running = false; +for (let i = 0; i < 20; i++, port++) { + if (await isBroke(port)) { running = true; break; } + if (await isFree(port)) break; +} const url = `http://localhost:${port}${ready ? "" : "/setup"}`; const openIt = () => { if (!process.env.BROKE_NO_OPEN) spawn(win ? "cmd" : process.platform === "darwin" ? "open" : "xdg-open", win ? ["/c", "start", url] : [url], { stdio: "ignore", detached: true }).on("error", () => {}).unref(); }; -// Started twice: open the one already running instead of failing on a busy port. -if (await fetch(url, { redirect: "manual" }).then(() => true, () => false)) { +if (running) { console.log(`broke is already running at ${url}.`); openIt(); process.exit(0); } +if (port !== Number(process.env.PORT || 3000)) console.log(`Port ${process.env.PORT || 3000} is busy with something else, so broke uses ${port}.`); + // The last build is reused when nothing it was built from has changed since: code, packages, settings or keys. const newest = (p) => !existsSync(p) ? 0 : statSync(p).isDirectory() ? Math.max(0, ...readdirSync(p, { recursive: true }).map((f) => statSync(join(p, String(f))).mtimeMs)) @@ -45,7 +54,7 @@ if (ready && !stale) console.log("Nothing changed since the last build: starting if (ready && stale && !npm("run", "build")) process.exit(1); const next = join("node_modules", ".bin", win ? "next.cmd" : "next"); // Listens on this computer only, which is what makes saving keys from the page safe (writeGate checks the rest). -const args = ready ? ["start", "-H", "127.0.0.1", "-p", port] : ["dev", "--turbopack", "-H", "127.0.0.1", "-p", port]; +const args = ready ? ["start", "-H", "127.0.0.1", "-p", String(port)] : ["dev", "--turbopack", "-H", "127.0.0.1", "-p", String(port)]; const server = spawn(next, args, { stdio: "inherit", shell: win, env: { ...process.env, ALLOW_SETUP_WRITES: "1" } }); server.on("exit", (code) => process.exit(code ?? 0)); process.on("SIGINT", () => server.kill("SIGINT"));