The best way to control Claude Code, Codex and more from any computer or phone

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