@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, 06:00 UTC

main
ts 149 lines 6.6 KB
Raw
1 import { readFile, writeFile } from "node:fs/promises";
2 import { fileURLToPath } from "node:url";
3 import * as Playwright from "@alchemy.run/cloudflare-test-tools/e2e/Playwright";
4 import { expect, test } from "@playwright/test";
5
6 const SECRET = "s3cret-from-binding";
7
8 // Both modes run the shared contract: `event.context.cloudflare` is served
9 // natively by the cloudflare_module preset in live mode, and by the
10 // platform-proxy dev bridge (nitro's SSR worker thread → workerd, wrangler-
11 // free) in dev mode.
12 for (const mode of Playwright.SERVER_METHODS) {
13 test.describe(mode, () => {
14 const it = Playwright.make(mode);
15
16 it("server-renders the home page with the cloudflare env binding", async ({ page, server }) => {
17 const response = await page.goto(server.url.toString());
18 expect(response?.status()).toBe(200);
19 await expect(page.getByTestId("page-marker")).toHaveText("NUXT_FIXTURE");
20 // `runtimeConfig.public.fixtureMarker` comes from the user's own
21 // nuxt.config.ts — proves the config file loaded natively (in dev
22 // too: the dev driver injects only the overrides layer).
23 await expect(page.getByTestId("config-marker")).toHaveText("user-nuxt-config-loaded");
24 // Read during SSR from event.context.cloudflare.env.
25 await expect(page.getByTestId("env-secret")).toHaveText(`secret:${SECRET}`);
26 });
27
28 it("hydrates the client-interactive counter", async ({ page, server }) => {
29 await page.goto(new URL("/counter", server.url).toString());
30 await expect(page.locator("#count")).toHaveText("count:0");
31 // wait for hydration before interacting (onMounted flips the marker)
32 await expect(page.locator("#increment")).toHaveAttribute("data-hydrated", "true");
33 await page.click("#increment");
34 await expect(page.locator("#count")).toHaveText("count:1");
35 await page.click("#increment");
36 await expect(page.locator("#count")).toHaveText("count:2");
37 });
38
39 it("serves the prerendered page", async ({ server }) => {
40 // Live: written into .output/public at build time and served by the
41 // assets layer. Dev: rendered on demand (dev does not prerender).
42 const response = await server.fetch("/prerendered");
43 expect(response.status).toBe(200);
44 expect(await response.text()).toContain("this-page-is-prerendered");
45 });
46
47 it("serves static assets", async ({ server }) => {
48 const response = await server.fetch("/robots.txt");
49 expect(response.status).toBe(200);
50 expect(await response.text()).toContain("User-agent: *");
51 });
52
53 it("runs the API route with the cloudflare runtime context", async ({ server }) => {
54 const body = await server.fetchJson<{
55 marker: string;
56 secret: string | null;
57 hasWaitUntil: boolean;
58 }>("/api/hello");
59 expect(body.marker).toBe("api-route-ok");
60 expect(body.secret).toBe(SECRET);
61 expect(body.hasWaitUntil).toBe(true);
62 });
63
64 it("round-trips KV through event.context.cloudflare.env", async ({ server }) => {
65 // Random payload data (not a resource name) — fine per the naming
66 // doctrine, and proves the read observes THIS run's write.
67 const value = `value-${Math.random().toString(36).slice(2)}`;
68 const put = await fetch(
69 new URL(`/api/kv?key=e2e-key&value=${encodeURIComponent(value)}`, server.url),
70 { method: "POST" },
71 );
72 expect(put.status).toBe(200);
73 expect(((await put.json()) as { put: boolean }).put).toBe(true);
74 const read = await server.fetchJson<{ value: string | null }>("/api/kv?key=e2e-key");
75 expect(read.value).toBe(value);
76 });
77
78 if (mode === "live") {
79 // Live-only: the Counter DO class reaches the worker through nitro's
80 // entry/exports seam (`worker-entry.ts`), which only exists in the
81 // production build — the dev platform proxy cannot host it (yet).
82 it("increments the Counter DO exported through the entry/exports seam", async ({
83 server,
84 }) => {
85 // Plain HTTP fetch (not `server.fetch`): the live-mode dispatchFetch
86 // wrapper drops RequestInit, losing the POST method.
87 const post = async (): Promise<number> => {
88 const response = await fetch(new URL("/api/counter", server.url), {
89 method: "POST",
90 });
91 expect(response.status).toBe(200);
92 const body = (await response.json()) as { count: number };
93 return body.count;
94 };
95
96 const first = await post();
97 const second = await post();
98 // Relative assertion: DO storage may persist across runs locally.
99 expect(second).toBe(first + 1);
100
101 // GET observes the state written by the POSTs — same DO instance.
102 const read = await fetch(new URL("/api/counter", server.url));
103 expect(read.status).toBe(200);
104 expect(((await read.json()) as { count: number }).count).toBe(second);
105 });
106 }
107
108 if (mode === "dev") {
109 // Dev-only: a server-route edit is reflected on the next request
110 // (nitro dev rebuild + worker-thread replacement; the bridge plugin
111 // reconnects on its own with binding state intact).
112 it("reflects a server-route edit on the next request", async ({ server }) => {
113 const file = fileURLToPath(new URL("../server/api/hmr.ts", import.meta.url));
114 const source = await readFile(file, "utf8");
115 const edited = source.replace('"hmr-marker-v1"', '"hmr-marker-v2"');
116 expect(edited).not.toBe(source);
117
118 // Bounded poll: mid-rebuild requests may fail; retry until the
119 // expected marker (or give up well inside the test timeout).
120 const pollFor = async (expected: string) => {
121 for (let attempt = 0; attempt < 30; attempt++) {
122 try {
123 const body = await server.fetchJson<{ marker: string }>("/api/hmr");
124 if (body.marker === expected) return;
125 } catch {
126 // mid-rebuild — retry
127 }
128 await new Promise((resolve) => setTimeout(resolve, 500));
129 }
130 throw new Error(`timed out waiting for /api/hmr to serve "${expected}"`);
131 };
132
133 await pollFor("hmr-marker-v1");
134 try {
135 await writeFile(file, edited);
136 await pollFor("hmr-marker-v2");
137 } finally {
138 await writeFile(file, source);
139 }
140 // Wait for the restore to land so later specs see a settled server.
141 await pollFor("hmr-marker-v1");
142
143 // The bridge survived the reloads: bindings still resolve.
144 const hello = await server.fetchJson<{ secret: string | null }>("/api/hello");
145 expect(hello.secret).toBe(SECRET);
146 });
147 }
148 });
149 }