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

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