The best way to control Claude Code, Codex and more from any computer or phone
| 1 | import { expect } from "@alchemy.run/test"; |
| 2 | import * as Data from "effect/Data"; |
| 3 | import * as Effect from "effect/Effect"; |
| 4 | import * as FileSystem from "effect/FileSystem"; |
| 5 | import type { PlatformError } from "effect/PlatformError"; |
| 6 | import * as ChildProcess from "effect/process/ChildProcess"; |
| 7 | import * as Schedule from "effect/Schedule"; |
| 8 | import * as Semaphore from "effect/Semaphore"; |
| 9 | import * as Stream from "effect/Stream"; |
| 10 | import * as pathe from "pathe"; |
| 11 | import { cloneFixture } from "../Cloudflare/Utils/Fixture.ts"; |
| 12 | |
| 13 | export type FoldkitMode = "spa" | "ssg" | "ssr" | "hybrid" | "static"; |
| 14 | export const foldkitModes = ["spa", "ssg", "ssr", "hybrid"] as const; |
| 15 | /** Browser hydration checks need the `terminal-browser` CLI; opt in like the Neon suites. */ |
| 16 | const browserEnabled = process.env.FOLDKIT_WEBSITE_BROWSER === "1"; |
| 17 | export const foldkitMemo = { |
| 18 | include: ["index.html", "src/**", "public/**", "package.json", "vite.config.ts"], |
| 19 | }; |
| 20 | |
| 21 | const cloudflareWebsite = (...segments: string[]) => |
| 22 | pathe.join(import.meta.dirname, "../Cloudflare/Website", ...segments); |
| 23 | const overlays = pathe.join(import.meta.dirname, "fixtures/foldkit-modes"); |
| 24 | |
| 25 | /** Copy an overlay directory over a fixture clone, replacing same-named files. */ |
| 26 | const overlay = ( |
| 27 | from: string, |
| 28 | to: string, |
| 29 | ): Effect.Effect<void, PlatformError, FileSystem.FileSystem> => |
| 30 | Effect.gen(function* () { |
| 31 | const fs = yield* FileSystem.FileSystem; |
| 32 | if (!(yield* fs.exists(from))) return; |
| 33 | yield* fs.makeDirectory(to, { recursive: true }); |
| 34 | for (const entry of yield* fs.readDirectory(from)) { |
| 35 | const source = pathe.join(from, entry); |
| 36 | const target = pathe.join(to, entry); |
| 37 | if ((yield* fs.stat(source)).type === "Directory") { |
| 38 | yield* fs.makeDirectory(target, { recursive: true }); |
| 39 | yield* overlay(source, target); |
| 40 | } else { |
| 41 | yield* fs.writeFile(target, yield* fs.readFile(source)); |
| 42 | } |
| 43 | } |
| 44 | }); |
| 45 | |
| 46 | /** |
| 47 | * A private clone of the Foldkit fixture for one rendering mode: the |
| 48 | * client-only fixture for `spa`, otherwise the SSR fixture with the mode's |
| 49 | * checked-in overlay (`fixtures/foldkit-modes/<mode>`) copied over it. |
| 50 | */ |
| 51 | export const foldkitFixture = (mode: FoldkitMode) => |
| 52 | Effect.gen(function* () { |
| 53 | const root = yield* cloneFixture( |
| 54 | cloudflareWebsite(mode === "spa" ? "foldkit-fixture" : "foldkit-ssr-fixture"), |
| 55 | { |
| 56 | prefix: `foldkit-${mode}-`, |
| 57 | tempRoot: pathe.resolve(import.meta.dirname, "../../.tmp"), |
| 58 | entries: [ |
| 59 | "package.json", |
| 60 | "vite.config.ts", |
| 61 | "src", |
| 62 | ...(mode === "spa" ? ["index.html"] : []), |
| 63 | ], |
| 64 | }, |
| 65 | ); |
| 66 | if (mode === "spa") { |
| 67 | yield* overlay(pathe.join(overlays, "common/public"), pathe.join(root, "public")); |
| 68 | } else { |
| 69 | yield* overlay(pathe.join(overlays, "common"), root); |
| 70 | yield* overlay(pathe.join(overlays, mode), root); |
| 71 | } |
| 72 | return root; |
| 73 | }); |
| 74 | |
| 75 | class RequestFailed extends Data.TaggedError("RequestFailed")<{ url: string; cause: unknown }> {} |
| 76 | |
| 77 | const requestOnce = (url: string, init?: RequestInit) => |
| 78 | Effect.tryPromise({ |
| 79 | try: async () => { |
| 80 | const response = await fetch(url, { |
| 81 | ...init, |
| 82 | signal: AbortSignal.timeout(5000), |
| 83 | }); |
| 84 | return { |
| 85 | status: response.status, |
| 86 | body: await response.text(), |
| 87 | type: response.headers.get("content-type"), |
| 88 | }; |
| 89 | }, |
| 90 | catch: (cause) => new RequestFailed({ url, cause }), |
| 91 | }); |
| 92 | class EdgePlaceholder extends Data.TaggedError("EdgePlaceholder")<{ url: string }> {} |
| 93 | |
| 94 | /** |
| 95 | * A fresh deployment can briefly answer from an edge node that has not |
| 96 | * picked it up yet, with the CDN's own HTML error page (Cloudflare's |
| 97 | * workers.dev placeholder). The app's own 404s are plain text, so retry only |
| 98 | * the CDN's page (for bodiless HEAD responses: an HTML error). |
| 99 | */ |
| 100 | const request = (url: string, init?: RequestInit) => |
| 101 | requestOnce(url, init).pipe( |
| 102 | Effect.flatMap((result) => |
| 103 | result.status >= 400 && |
| 104 | (init?.method === "HEAD" |
| 105 | ? (result.type ?? "").includes("text/html") |
| 106 | : result.body.includes("<!--[if lt IE 7]>")) |
| 107 | ? Effect.fail(new EdgePlaceholder({ url })) |
| 108 | : Effect.succeed(result), |
| 109 | ), |
| 110 | Effect.retry({ |
| 111 | while: (error) => error._tag === "EdgePlaceholder", |
| 112 | schedule: Schedule.spaced("1 second"), |
| 113 | times: 15, |
| 114 | }), |
| 115 | ); |
| 116 | |
| 117 | const routes = (mode: FoldkitMode) => [ |
| 118 | { path: "/?count=7", count: mode === "ssr" ? 7 : 0 }, |
| 119 | { path: "/about/?count=9", count: mode === "ssr" ? 9 : 0 }, |
| 120 | ...(mode === "static" || mode === "ssg" |
| 121 | ? [] |
| 122 | : [{ path: "/counter/42?count=3", count: mode === "spa" ? 0 : 3 }]), |
| 123 | ]; |
| 124 | |
| 125 | /** Exercise the public origin, including asset routing and the actual deployed SSR handler. */ |
| 126 | export const verifyFoldkitRendering = ( |
| 127 | origin: string, |
| 128 | mode: FoldkitMode, |
| 129 | options: { |
| 130 | /** |
| 131 | * Where a POST to a prerendered page goes. Cloudflare's asset layer |
| 132 | * answers non-GET/HEAD requests for a matching asset with 405 before |
| 133 | * the Worker runs; other platforms forward them to the server. |
| 134 | * @default "server" |
| 135 | */ |
| 136 | prerenderedPost?: "server" | 405; |
| 137 | } = {}, |
| 138 | ) => |
| 139 | Effect.gen(function* () { |
| 140 | const base = origin.replace(/\/+$/, ""); |
| 141 | // Readiness: the asset layer and the server can go live at different |
| 142 | // moments, so wait for both an asset and the first page. A redeploy |
| 143 | // that changes which pages are prerendered also waits on the CDN's |
| 144 | // routing data (CloudFront KeyValueStore propagation). |
| 145 | const ready = (path: string, check: (body: string) => boolean) => |
| 146 | request(base + path).pipe( |
| 147 | Effect.flatMap((result) => |
| 148 | result.status === 200 && check(result.body) |
| 149 | ? Effect.void |
| 150 | : Effect.fail(new Error(`Foldkit deployment is not serving ${path} yet`)), |
| 151 | ), |
| 152 | Effect.retry({ schedule: Schedule.spaced("2 seconds"), times: 45 }), |
| 153 | ); |
| 154 | yield* ready("/foldkit-probe.txt", (body) => body === "FOLDKIT_STATIC_ASSET"); |
| 155 | const first = routes(mode)[0]!; |
| 156 | yield* ready( |
| 157 | first.path, |
| 158 | (body) => mode === "spa" || new RegExp(`id="count"[^>]*>${first.count}<`).test(body), |
| 159 | ); |
| 160 | const assetHead = yield* request(`${base}/foldkit-probe.txt`, { |
| 161 | method: "HEAD", |
| 162 | }); |
| 163 | expect(assetHead.status).toBe(200); |
| 164 | expect(assetHead.body).toBe(""); |
| 165 | for (const route of routes(mode)) { |
| 166 | const response = yield* request(base + route.path); |
| 167 | expect({ path: route.path, status: response.status }).toEqual({ |
| 168 | path: route.path, |
| 169 | status: 200, |
| 170 | }); |
| 171 | if (mode === "spa") { |
| 172 | expect(response.body).toContain("Foldkit Fixture"); |
| 173 | expect(response.body).not.toMatch(/id="count"/); |
| 174 | } else { |
| 175 | expect(response.body).toMatch(new RegExp(`id="count"[^>]*>${route.count}<`)); |
| 176 | } |
| 177 | const script = response.body.match(/<script[^>]+src="([^" ]+)"/); |
| 178 | expect(script).not.toBeNull(); |
| 179 | const javascript = yield* request(new URL(script![1]!, base + route.path).href); |
| 180 | expect(javascript.status).toBe(200); |
| 181 | expect(javascript.type).toMatch(/javascript/); |
| 182 | if (mode !== "spa") { |
| 183 | const stylesheet = response.body.match(/<link[^>]+rel="stylesheet"[^>]+href="([^"]+)"/); |
| 184 | expect(stylesheet).not.toBeNull(); |
| 185 | const css = yield* request(new URL(stylesheet![1]!, base + route.path).href); |
| 186 | expect(css.status).toBe(200); |
| 187 | expect(css.type).toMatch(/text\/css/); |
| 188 | } |
| 189 | const head = yield* request(base + route.path, { method: "HEAD" }); |
| 190 | expect({ head: route.path, status: head.status }).toEqual({ |
| 191 | head: route.path, |
| 192 | status: 200, |
| 193 | }); |
| 194 | expect(head.body).toBe(""); |
| 195 | } |
| 196 | if (mode === "ssr" || mode === "hybrid") { |
| 197 | const posted = yield* request(`${base}/about/?count=11`, { |
| 198 | method: "POST", |
| 199 | body: "request body", |
| 200 | }); |
| 201 | if (mode === "hybrid" && options.prerenderedPost === 405) { |
| 202 | expect(posted.status).toBe(405); |
| 203 | } else { |
| 204 | expect(posted.status).toBe(200); |
| 205 | expect(posted.body).toMatch(/id="count"[^>]*>11</); |
| 206 | } |
| 207 | expect((yield* request(`${base}/assets/missing.js`)).status).toBe(404); |
| 208 | } |
| 209 | if (mode === "ssg") { |
| 210 | expect((yield* request(`${base}/about/`, { method: "POST" })).status).toBe(405); |
| 211 | expect((yield* request(`${base}/assets/missing.js`)).status).toBe(404); |
| 212 | } |
| 213 | if (mode === "static" || mode === "ssg") |
| 214 | expect((yield* request(`${base}/not-prerendered`)).status).toBe(404); |
| 215 | }); |
| 216 | |
| 217 | const browsers = Semaphore.makeUnsafe(1); |
| 218 | const command = (args: string[]) => |
| 219 | Effect.gen(function* () { |
| 220 | const child = yield* ChildProcess.make("terminal-browser", args, { |
| 221 | env: { ...process.env, NODE_OPTIONS: undefined }, |
| 222 | }); |
| 223 | const [code, stdout, stderr] = yield* Effect.all( |
| 224 | [ |
| 225 | child.exitCode, |
| 226 | child.stdout.pipe(Stream.decodeText, Stream.mkString), |
| 227 | child.stderr.pipe(Stream.decodeText, Stream.mkString), |
| 228 | ], |
| 229 | { concurrency: 3 }, |
| 230 | ); |
| 231 | if (code !== 0) return yield* Effect.fail(new Error(`Browser command failed: ${stderr}`)); |
| 232 | return stdout; |
| 233 | }).pipe(Effect.scoped, Effect.timeout("10 seconds")); |
| 234 | |
| 235 | /** |
| 236 | * Hydration in a real browser: initial count, click, reload, click. A no-op |
| 237 | * unless `FOLDKIT_WEBSITE_BROWSER=1`. |
| 238 | */ |
| 239 | export const verifyFoldkitBrowser = (origin: string, mode: FoldkitMode) => |
| 240 | Effect.gen(function* () { |
| 241 | if (!browserEnabled) return; |
| 242 | for (const route of routes(mode)) { |
| 243 | yield* Effect.gen(function* () { |
| 244 | const opened = yield* command(["new-tab", origin.replace(/\/+$/, "") + route.path]); |
| 245 | const browser = yield* Effect.try( |
| 246 | () => |
| 247 | JSON.parse(opened) as { |
| 248 | key: string; |
| 249 | openedTab?: number; |
| 250 | tabs?: { id: number; active: boolean }[]; |
| 251 | }, |
| 252 | ); |
| 253 | const tab = browser.openedTab ?? browser.tabs?.find((tab) => tab.active)?.id; |
| 254 | if (tab === undefined) |
| 255 | return yield* Effect.fail(new Error("Browser did not report its active tab")); |
| 256 | const action = (...args: string[]) => |
| 257 | command(["action", "--browser", browser.key, "--tab", String(tab), "--", ...args]); |
| 258 | yield* Effect.addFinalizer(() => |
| 259 | action("close").pipe( |
| 260 | Effect.andThen( |
| 261 | command(["action", "--browser", browser.key, "--tab", String(tab), "done"]), |
| 262 | ), |
| 263 | Effect.ignore, |
| 264 | ), |
| 265 | ); |
| 266 | const countIs = (count: number) => |
| 267 | action( |
| 268 | "eval", |
| 269 | `document.readyState === "complete" && document.getElementById("count")?.textContent === ${JSON.stringify(String(count))} ? "FOLDKIT_COUNT_OK" : "WAITING"`, |
| 270 | ).pipe( |
| 271 | Effect.repeat({ |
| 272 | schedule: Schedule.spaced("500 millis"), |
| 273 | times: 8, |
| 274 | until: (text) => text.includes("FOLDKIT_COUNT_OK"), |
| 275 | }), |
| 276 | Effect.tap((text) => Effect.sync(() => expect(text).toContain("FOLDKIT_COUNT_OK"))), |
| 277 | ); |
| 278 | yield* countIs(route.count); |
| 279 | yield* action("click", "#increment"); |
| 280 | yield* countIs(route.count + 1); |
| 281 | // A reload must hydrate the server's initial flags again, not retain the clicked state. |
| 282 | yield* action("reload"); |
| 283 | yield* countIs(route.count); |
| 284 | yield* action("click", "#increment"); |
| 285 | yield* countIs(route.count + 1); |
| 286 | }).pipe(Effect.scoped); |
| 287 | } |
| 288 | }).pipe(browsers.withPermit, Effect.timeout("60 seconds")); |