1/**
2 * True `alchemy dev` end-to-end for the React Router site: spawns the REAL
3 * CLI (mirroring examples/aws-dev/test/dev.test.ts), which runs the Vite
4 * dev server as the local `Website.Server` provider — no Railway Service, no
5 * Railway, no S3; the only cloud touch is the state store.
6 *
7 * Coverage:
8 * - stack output → `url` is a local dev-server address (port is
9 * whatever the framework bound — never hard-coded)
10 * - SSR env parity → `/` renders the GREETING declared in alchemy.run.ts
11 * (read via `process.env` in the route loader)
12 * - static assets → `/robots.txt` from public/
13 * - HOT RELOAD → editing app/routes/home.tsx is served by
14 * Vite's HMR without a redeploy
15 */
16import { afterAll, expect, test } from "bun:test";
17import { spawn, spawnSync } from "node:child_process";
18import * as fs from "node:fs";
19import * as path from "node:path";
20
21const root = path.resolve(import.meta.dirname, "..");
22// Spawn the CLI entry directly (not through `bun run` / the cli.js
23// launcher) so signals hit the actual CLI process, whose scope teardown
24// kills the dev server and the provider sidecars.
25const alchemyBin = path.join(
26 root,
27 "node_modules",
28 "alchemy",
29 "bin",
30 "alchemy.js",
31);
32// Isolated stage so this suite never fights integ.test.ts (same stack
33// name) over state rows.
34const STAGE = "dev-cli-test";
35
36// Hot-reload surface: the SSR index page. The test rewrites it in place
37// with the CLI running, then restores it.
38const pagePath = path.join(root, "app", "routes", "home.tsx");
39const pageSource = fs.readFileSync(pagePath, "utf8");
40const MARKER = "Styled with Tailwind CSS";
41const MARKER_V2 = "Styled with Tailwind CSS [dev-v2]";
42
43let proc: ReturnType<typeof spawn> | undefined;
44let output = "";
45
46const pump = (stream: NodeJS.ReadableStream) => {
47 stream.on("data", (chunk: Buffer) => {
48 const text = chunk.toString();
49 output += text;
50 if (process.env.DEBUG) process.stderr.write(text);
51 });
52};
53
54/** Bounded poll for a (possibly async) producer to yield a value. */
55const pollUntil = async <T>(
56 what: string,
57 f: () => T | undefined | Promise<T | undefined>,
58 { tries = 30, delayMs = 1000 }: { tries?: number; delayMs?: number } = {},
59): Promise<T> => {
60 for (let i = 0; i < tries; i++) {
61 const value = await f();
62 if (value !== undefined) return value;
63 await Bun.sleep(delayMs);
64 }
65 throw new Error(
66 `Timed out waiting for ${what}.\n--- alchemy dev output (tail) ---\n${output.slice(-4000)}`,
67 );
68};
69
70/** Fetch with retries — the dev server takes a moment to start serving. */
71const fetchOk = async (
72 url: string | URL,
73 { tries = 30, delayMs = 1000 }: { tries?: number; delayMs?: number } = {},
74) => {
75 let last: Response | undefined;
76 for (let i = 0; i < tries; i++) {
77 try {
78 last = await fetch(url);
79 if (last.ok) return last;
80 } catch {
81 // dev server not listening yet
82 }
83 await Bun.sleep(delayMs);
84 }
85 throw new Error(
86 `GET ${url} never returned 2xx (last status: ${last?.status})`,
87 );
88};
89
90/** Extract the stack-output URL the CLI prints on stdout. */
91const outputUrl = () => output.match(/\burl:\s*['"]?(http[^\s'",]+)/)?.[1];
92
93afterAll(async () => {
94 // Always leave the repo tree clean, even on a mid-reload failure.
95 fs.writeFileSync(pagePath, pageSource);
96
97 if (proc?.pid) {
98 // Ctrl-C semantics: signal the whole PROCESS GROUP (the CLI, its
99 // `--watch` exec child, and the provider sidecars).
100 const killGroup = (signal: NodeJS.Signals) => {
101 try {
102 process.kill(-proc!.pid!, signal);
103 } catch {
104 // group already gone
105 }
106 };
107 const exited = new Promise((resolve) => proc!.once("exit", resolve));
108 killGroup("SIGINT");
109 await Promise.race([exited, Bun.sleep(15_000)]);
110 if (proc.exitCode === null && proc.signalCode === null) {
111 killGroup("SIGKILL");
112 await Promise.race([exited, Bun.sleep(5_000)]);
113 }
114 }
115 if (!process.env.NO_DESTROY) {
116 spawnSync("bun", [alchemyBin, "destroy", "--stage", STAGE, "--yes"], {
117 cwd: root,
118 stdio: "inherit",
119 timeout: 120_000,
120 });
121 }
122}, 180_000);
123
124test(
125 "alchemy dev serves the React Router site locally with hot reload",
126 async () => {
127 proc = spawn("bun", [alchemyBin, "dev", "--stage", STAGE], {
128 cwd: root,
129 // Own process group, so teardown can deliver Ctrl-C to the whole
130 // tree the way a terminal would.
131 detached: true,
132 stdio: ["ignore", "pipe", "pipe"],
133 });
134 pump(proc.stdout!);
135 pump(proc.stderr!);
136
137 const url = await pollUntil("url in stack outputs", outputUrl, {
138 tries: 180,
139 delayMs: 1000,
140 });
141
142 // Dev identity: the framework dev server, not Railway. The port is
143 // whatever the framework bound — only the URL captured from the CLI's
144 // stdout is authoritative.
145 expect(new URL(url).hostname).toBe("localhost");
146 expect(url).not.toContain("example.invalid");
147
148 // SSR env parity: GREETING from alchemy.run.ts reaches the dev server
149 // (read via `process.env` in the route loader).
150 const home = await (await fetchOk(url)).text();
151 expect(home).toContain("Hello from React Router on Railway!");
152 expect(home).toContain(MARKER);
153
154 // Static asset from public/.
155 const robots = await (await fetchOk(new URL("/robots.txt", url))).text();
156 expect(robots).toContain("User-agent:");
157
158 // ── HOT RELOAD: rewrite the index page with the CLI still running —
159 // the framework dev server serves the new markup without a deploy ──
160 fs.writeFileSync(pagePath, pageSource.replace(MARKER, MARKER_V2));
161 await pollUntil(
162 "hot-reloaded page (v2 marker)",
163 async () => {
164 try {
165 const res = await fetch(url);
166 if (!res.ok) return undefined;
167 const html = await res.text();
168 return html.includes(MARKER_V2) ? true : undefined;
169 } catch {
170 return undefined; // mid-reload
171 }
172 },
173 { tries: 120, delayMs: 500 },
174 );
175
176 // Restore — the swap back is itself a second hot reload and leaves
177 // the checked-in tree clean.
178 fs.writeFileSync(pagePath, pageSource);
179 await pollUntil(
180 "restored page (v2 marker gone)",
181 async () => {
182 try {
183 const res = await fetch(url);
184 if (!res.ok) return undefined;
185 const html = await res.text();
186 return html.includes(MARKER_V2) ? undefined : true;
187 } catch {
188 return undefined; // mid-reload
189 }
190 },
191 { tries: 120, delayMs: 500 },
192 );
193 },
194 { timeout: 600_000 },
195);