@devries-cameron20 / t3code Mirror · read-only
Fork 0

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

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 04:45 UTC

main
ts 193 lines 6.75 KB
Raw
1 /**
2 * True `alchemy dev` end-to-end for the Astro site: spawns the REAL CLI
3 * (mirroring examples/aws-dev/test/dev.test.ts), which runs Astro's own
4 * dev server as the local `Website.Server` provider — no Hetzner Server, no
5 * Hetzner, 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 * - routing → `/about/` (prerendered route) serves
12 * - static assets → `/robots.txt` from public/
13 * - HOT RELOAD → editing src/pages/index.astro is served by the
14 * framework's 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, "src", "pages", "index.astro");
33 const pageSource = fs.readFileSync(pagePath, "utf8");
34 const MARKER = "server-rendered in a Hetzner Server";
35 const MARKER_V2 = "server-rendered in a Hetzner Server [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 const destroyed = spawnSync("bun", [alchemyBin, "destroy", "--stage", STAGE, "--yes"], {
109 cwd: root,
110 stdio: "inherit",
111 timeout: 120_000,
112 });
113 if (destroyed.status !== 0) {
114 throw new Error(`alchemy destroy exited ${destroyed.status} — local teardown must succeed`);
115 }
116 }
117 }, 180_000);
118
119 test(
120 "alchemy dev serves the Astro site locally with hot reload",
121 async () => {
122 proc = spawn("bun", [alchemyBin, "dev", "--stage", STAGE], {
123 cwd: root,
124 // Own process group, so teardown can deliver Ctrl-C to the whole
125 // tree the way a terminal would.
126 detached: true,
127 stdio: ["ignore", "pipe", "pipe"],
128 });
129 pump(proc.stdout!);
130 pump(proc.stderr!);
131
132 const url = await pollUntil("url in stack outputs", outputUrl, {
133 tries: 180,
134 delayMs: 1000,
135 });
136
137 // Dev identity: the framework dev server, not Hetzner. The port is
138 // whatever the framework bound — only the URL captured from the CLI's
139 // stdout is authoritative.
140 expect(new URL(url).hostname).toBe("localhost");
141 expect(url).not.toContain("example.invalid");
142
143 // SSR env parity: GREETING from alchemy.run.ts reaches the dev server.
144 const home = await (await fetchOk(url)).text();
145 expect(home).toContain("Hello from Astro on Hetzner!");
146 expect(home).toContain(MARKER);
147
148 // Prerendered route serves through the dev server.
149 const about = await fetchOk(new URL("/about/", url));
150 expect(about.status).toBe(200);
151
152 // Static asset from public/.
153 const robots = await (await fetchOk(new URL("/robots.txt", url))).text();
154 expect(robots).toContain("User-agent:");
155
156 // ── HOT RELOAD: rewrite the index page with the CLI still running —
157 // the framework dev server serves the new markup without a deploy ──
158 fs.writeFileSync(pagePath, pageSource.replace(MARKER, MARKER_V2));
159 await pollUntil(
160 "hot-reloaded page (v2 marker)",
161 async () => {
162 try {
163 const res = await fetch(url);
164 if (!res.ok) return undefined;
165 const html = await res.text();
166 return html.includes(MARKER_V2) ? true : undefined;
167 } catch {
168 return undefined; // mid-reload
169 }
170 },
171 { tries: 120, delayMs: 500 },
172 );
173
174 // Restore — the swap back is itself a second hot reload and leaves
175 // the checked-in tree clean.
176 fs.writeFileSync(pagePath, pageSource);
177 await pollUntil(
178 "restored page (v2 marker gone)",
179 async () => {
180 try {
181 const res = await fetch(url);
182 if (!res.ok) return undefined;
183 const html = await res.text();
184 return html.includes(MARKER_V2) ? undefined : true;
185 } catch {
186 return undefined; // mid-reload
187 }
188 },
189 { tries: 120, delayMs: 500 },
190 );
191 },
192 { timeout: 600_000 },
193 );