The best way to control Claude Code, Codex and more from any computer or phone
| 1 | import * as Cloudflare from "@alchemy.run/cloudflare"; |
| 2 | import { CloudflareEnvironment } from "@alchemy.run/cloudflare/CloudflareEnvironment"; |
| 3 | import { describe, expect } from "@alchemy.run/test"; |
| 4 | import * as Test from "@alchemy.run/test/Alchemy"; |
| 5 | import * as kv from "@distilled.cloud/cloudflare/kv"; |
| 6 | import * as Data from "effect/Data"; |
| 7 | import * as Effect from "effect/Effect"; |
| 8 | import * as FileSystem from "effect/FileSystem"; |
| 9 | import * as HttpClient from "effect/http/HttpClient"; |
| 10 | import * as HttpClientRequest from "effect/http/HttpClientRequest"; |
| 11 | import * as Path from "effect/Path"; |
| 12 | import { MinimumLogLevel } from "effect/References"; |
| 13 | import * as Schedule from "effect/Schedule"; |
| 14 | import * as Stream from "effect/Stream"; |
| 15 | import * as pathe from "pathe"; |
| 16 | import { cloneFixture } from "../Utils/Fixture.ts"; |
| 17 | import { |
| 18 | expectClientChunkContains, |
| 19 | expectDirectStatus, |
| 20 | expectUrlContains, |
| 21 | expectUrlHeader, |
| 22 | } from "../Utils/Http.ts"; |
| 23 | import { expectWorkerExists, waitForWorkerToBeDeleted } from "../Utils/Worker.ts"; |
| 24 | |
| 25 | const { test } = Test.make({ providers: Cloudflare.providers() }); |
| 26 | |
| 27 | const logLevel = Effect.provideService(MinimumLogLevel, process.env.DEBUG ? "Debug" : "Info"); |
| 28 | |
| 29 | const fixtureDir = pathe.resolve(import.meta.dirname, "fixtures", "waku-app"); |
| 30 | |
| 31 | // Keep the temp clone under the alchemy package (same convention as the |
| 32 | // Vite tests) so the project root stays representable relative to cwd. |
| 33 | const tempRoot = pathe.resolve(import.meta.dirname, "../../../.tmp"); |
| 34 | |
| 35 | const wakuProps = (rootDir: string) => ({ |
| 36 | rootDir, |
| 37 | workersDev: { enabled: true, previewsEnabled: true }, |
| 38 | // Deliberately NO `flags`: Waku's server runtime needs |
| 39 | // AsyncLocalStorage, and the resource must default to `nodejs_als` |
| 40 | // when the user provides no compatibility flags (a zero-config deploy |
| 41 | // would otherwise fail at first request). |
| 42 | compatibility: { date: "2026-03-10" }, |
| 43 | memo: { include: ["src/**", "public/**", "package.json", "tsconfig.json"] }, |
| 44 | }); |
| 45 | |
| 46 | // Concurrent like the other Website suites: the Waku source build runs |
| 47 | // in a child process with cwd = project root (core/BuildChild.ts), so |
| 48 | // nothing here mutates process-global state. |
| 49 | describe.concurrent( |
| 50 | "Waku", |
| 51 | { |
| 52 | tags: [ |
| 53 | "provider:cloudflare", |
| 54 | "provider:cloudflare:website", |
| 55 | "provider:cloudflare:worker", |
| 56 | "live", |
| 57 | ], |
| 58 | }, |
| 59 | () => { |
| 60 | test.provider( |
| 61 | "Waku: deploys RSC SSR + binding + static assets and memoizes unchanged rebuilds", |
| 62 | (stack) => |
| 63 | Effect.gen(function* () { |
| 64 | const { accountId } = yield* yield* CloudflareEnvironment; |
| 65 | const fs = yield* FileSystem.FileSystem; |
| 66 | const path = yield* Path.Path; |
| 67 | |
| 68 | yield* stack.destroy(); |
| 69 | |
| 70 | const rootDir = yield* cloneFixture(fixtureDir, { |
| 71 | prefix: "alchemy-waku-", |
| 72 | tempRoot, |
| 73 | entries: [".gitignore", "package.json", "tsconfig.json", "public", "src"], |
| 74 | }); |
| 75 | |
| 76 | const bindingMarker = "waku-binding-marker"; |
| 77 | |
| 78 | const deploy = () => |
| 79 | stack.deploy( |
| 80 | Effect.gen(function* () { |
| 81 | const siteKv = yield* Cloudflare.KV.Namespace("SiteKV"); |
| 82 | const site = yield* Cloudflare.Website.Waku("WakuSite", { |
| 83 | ...wakuProps(rootDir), |
| 84 | env: { |
| 85 | MESSAGE: bindingMarker, |
| 86 | // A real resource binding (not a plain-string var): the |
| 87 | // `/api/kv` route reads and writes through it at request |
| 88 | // time via `cloudflare:workers` env. |
| 89 | SITE_KV: siteKv, |
| 90 | WAKU_PUBLIC_SITE_MARKER: "WAKU_PUBLIC_ENV_MARKER", |
| 91 | }, |
| 92 | }); |
| 93 | return { site, siteKv }; |
| 94 | }), |
| 95 | ); |
| 96 | |
| 97 | const { site: site1, siteKv } = yield* deploy(); |
| 98 | |
| 99 | expect(site1.url).toBeDefined(); |
| 100 | expect(site1.hash?.input).toBeDefined(); |
| 101 | yield* expectWorkerExists(site1.workerName, accountId); |
| 102 | |
| 103 | // Dynamic RSC page rendered by the Worker at request time. |
| 104 | yield* expectUrlContains(`${site1.url!}/`, "WAKU_PAGE_MARKER", { |
| 105 | timeout: "120 seconds", |
| 106 | label: "waku dynamic home page", |
| 107 | }); |
| 108 | |
| 109 | // A declared public env value is inlined into the deployed client |
| 110 | // bundle at build time. |
| 111 | yield* expectClientChunkContains( |
| 112 | site1.url!, |
| 113 | pathe.join(rootDir, "dist", "public"), |
| 114 | "WAKU_PUBLIC_ENV_MARKER", |
| 115 | { |
| 116 | timeout: "60 seconds", |
| 117 | label: "waku public env", |
| 118 | }, |
| 119 | ); |
| 120 | |
| 121 | // The same page reads the `MESSAGE` binding from `cloudflare:workers` |
| 122 | // env at request time — proves bindings reach the RSC server bundle. |
| 123 | yield* expectUrlContains(`${site1.url!}/`, `MESSAGE=${bindingMarker}`, { |
| 124 | timeout: "60 seconds", |
| 125 | label: "waku env binding in SSR output", |
| 126 | }); |
| 127 | |
| 128 | // Static asset from `public/`. |
| 129 | yield* expectUrlContains(`${site1.url!}/hello.txt`, "hello from public/", { |
| 130 | timeout: "60 seconds", |
| 131 | label: "waku static asset", |
| 132 | }); |
| 133 | // The same file read by a server route through the `ASSETS` binding. |
| 134 | yield* expectUrlContains(`${site1.url!}/asset`, "hello from public/", { |
| 135 | timeout: "60 seconds", |
| 136 | label: "waku ASSETS binding", |
| 137 | }); |
| 138 | |
| 139 | // SSG page prerendered at build time and served from assets. |
| 140 | yield* expectUrlContains(`${site1.url!}/about`, "WAKU_ABOUT_STATIC_MARKER", { |
| 141 | timeout: "60 seconds", |
| 142 | label: "waku SSG page", |
| 143 | }); |
| 144 | |
| 145 | // The SSG page serves 200 directly at the extensionless URL — the |
| 146 | // default `drop-trailing-slash` asset handling must not 307-redirect |
| 147 | // `/about` to `/about/`. |
| 148 | yield* expectDirectStatus(`${site1.url!}/about`, 200, { |
| 149 | label: "waku SSG page serves without a redirect", |
| 150 | }); |
| 151 | |
| 152 | // ── API route: a POST reaches the worker through the asset router |
| 153 | // and round-trips a JSON body plus the env binding ────────────────── |
| 154 | const echoed = yield* requestJsonReady<{ echoed: { ping: string }; message: string }>( |
| 155 | HttpClientRequest.post(`${site1.url!}/echo`).pipe( |
| 156 | HttpClientRequest.bodyJsonUnsafe({ ping: "pong" }), |
| 157 | ), |
| 158 | ); |
| 159 | expect(echoed.echoed).toEqual({ ping: "pong" }); |
| 160 | expect(echoed.message).toBe(bindingMarker); |
| 161 | |
| 162 | // ── middleware: `src/middleware/*.ts` runs ahead of the RSC |
| 163 | // middleware for every worker-handled request — the header shows on |
| 164 | // the dynamic SSR page (static assets bypass the worker) ──────────── |
| 165 | yield* expectUrlHeader(`${site1.url!}/`, "x-waku-middleware", "alchemy-waku-fixture", { |
| 166 | timeout: "60 seconds", |
| 167 | label: "waku middleware response header", |
| 168 | }); |
| 169 | |
| 170 | // ── KV: the SITE_KV namespace binding round-trips through the |
| 171 | // `/api/kv` route ─────────────────────────────────────────────────── |
| 172 | expect(siteKv.namespaceId).toBeDefined(); |
| 173 | yield* requestJsonReady<{ ok: boolean }>( |
| 174 | HttpClientRequest.put(`${site1.url!}/api/kv`).pipe( |
| 175 | HttpClientRequest.bodyJsonUnsafe({ key: "waku-live-key", value: "kv-live-value" }), |
| 176 | ), |
| 177 | ); |
| 178 | const kvRead = yield* requestJsonReady<{ key: string; value: string | null }>( |
| 179 | HttpClientRequest.get(`${site1.url!}/api/kv?key=waku-live-key`), |
| 180 | ).pipe( |
| 181 | Effect.filterOrFail( |
| 182 | (res) => res.value === "kv-live-value", |
| 183 | (res) => new Error(`kv value not visible yet: ${res.value}`), |
| 184 | ), |
| 185 | Effect.retry({ schedule: Schedule.exponential("1 second", 1.5), times: 6 }), |
| 186 | ); |
| 187 | expect(kvRead.value).toBe("kv-live-value"); |
| 188 | |
| 189 | // Out-of-band via the cloud API: the worker's write landed in the |
| 190 | // REAL namespace the stack provisioned. |
| 191 | const rawValue = yield* kv |
| 192 | .getNamespaceValue({ |
| 193 | accountId, |
| 194 | namespaceId: siteKv.namespaceId, |
| 195 | keyName: "waku-live-key", |
| 196 | }) |
| 197 | .pipe( |
| 198 | Effect.flatMap((res) => |
| 199 | Effect.tryPromise(() => |
| 200 | new Response(Stream.toReadableStream(res.body) as BodyInit).text(), |
| 201 | ), |
| 202 | ), |
| 203 | // The KV REST read can lag the worker's write briefly. |
| 204 | Effect.retry({ |
| 205 | while: (e) => e._tag === "KeyNotFound", |
| 206 | schedule: Schedule.exponential("1 second", 1.5), |
| 207 | times: 8, |
| 208 | }), |
| 209 | ); |
| 210 | expect(rawValue).toBe("kv-live-value"); |
| 211 | |
| 212 | // ── deploy 2: no changes ⇒ the rebuild-free input hash matches and |
| 213 | // the deploy short-circuits without rebuilding ─────────────────────── |
| 214 | const { site: site2 } = yield* deploy(); |
| 215 | |
| 216 | expect(site2.hash?.input).toBeDefined(); |
| 217 | expect(site2.hash?.input).toEqual(site1.hash?.input); |
| 218 | expect(site2.url).toBe(site1.url); |
| 219 | |
| 220 | // ── deploy 3: edit a page ⇒ the input hash changes and the new |
| 221 | // content deploys. The edited marker is asserted on the *dynamic* |
| 222 | // page (worker-rendered per request) — a changed static asset at the |
| 223 | // same URL can stay stale at a PoP far longer than a worker-version |
| 224 | // flip ───────────────────────────────────────────────────────────── |
| 225 | const indexPath = path.join(rootDir, "src/pages/index.tsx"); |
| 226 | const index = yield* fs.readFileString(indexPath); |
| 227 | yield* fs.writeFileString( |
| 228 | indexPath, |
| 229 | index.replace("WAKU_PAGE_MARKER", "WAKU_PAGE_MARKER_V2"), |
| 230 | ); |
| 231 | |
| 232 | const { site: site3 } = yield* deploy(); |
| 233 | |
| 234 | expect(site3.hash?.input).toBeDefined(); |
| 235 | expect(site3.hash?.input).not.toEqual(site1.hash?.input); |
| 236 | yield* expectUrlContains(`${site3.url!}/`, "WAKU_PAGE_MARKER_V2", { |
| 237 | timeout: "180 seconds", |
| 238 | label: "waku dynamic page after edit", |
| 239 | }); |
| 240 | |
| 241 | yield* stack.destroy(); |
| 242 | yield* waitForWorkerToBeDeleted(site1.workerName, accountId); |
| 243 | // Destroy must also delete the bound KV namespace from the cloud. |
| 244 | yield* waitForNamespaceToBeDeleted(siteKv.namespaceId, accountId); |
| 245 | }).pipe(logLevel), |
| 246 | { tags: ["provider:cloudflare:kv"], timeout: 360_000 }, |
| 247 | ); |
| 248 | |
| 249 | // ───────────────────────────────────────────────────────────────────── |
| 250 | // Custom worker entry (seam: WakuProps.main → the waku target's |
| 251 | // user-entry carriage → framework-core's DeployTarget.entry) |
| 252 | // |
| 253 | // `main` points the deploy at the user's own module, which wraps waku's |
| 254 | // emitted handler via `virtual:waku/server-entry` and re-exports the |
| 255 | // `Counter` Durable Object class — DO classes must live on the deployed |
| 256 | // worker for their namespace bindings to resolve. Mirrors |
| 257 | // `Website.Vite`'s "main overrides the worker entry" test. |
| 258 | // ───────────────────────────────────────────────────────────────────── |
| 259 | |
| 260 | test.provider( |
| 261 | "Waku: main deploys a custom worker entry hosting a Durable Object", |
| 262 | (stack) => |
| 263 | Effect.gen(function* () { |
| 264 | const { accountId } = yield* yield* CloudflareEnvironment; |
| 265 | |
| 266 | yield* stack.destroy(); |
| 267 | |
| 268 | const rootDir = yield* cloneFixture(fixtureDir, { |
| 269 | prefix: "alchemy-waku-main-", |
| 270 | tempRoot, |
| 271 | entries: [".gitignore", "package.json", "tsconfig.json", "public", "src"], |
| 272 | }); |
| 273 | |
| 274 | const site = yield* stack.deploy( |
| 275 | Effect.gen(function* () { |
| 276 | return yield* Cloudflare.Website.Waku("WakuMainSite", { |
| 277 | ...wakuProps(rootDir), |
| 278 | // The user's own worker entry: wraps waku's handler (imported |
| 279 | // from `virtual:waku/server-entry`) and exports the Counter DO. |
| 280 | main: "src/worker-entry.ts", |
| 281 | env: { |
| 282 | MESSAGE: "waku-main-marker", |
| 283 | COUNTER: Cloudflare.DurableObject("Counter", { className: "Counter" }), |
| 284 | }, |
| 285 | }); |
| 286 | }), |
| 287 | ); |
| 288 | |
| 289 | expect(site.url).toBeDefined(); |
| 290 | yield* expectWorkerExists(site.workerName, accountId); |
| 291 | |
| 292 | // The deployed entry is the USER module, not waku's own entry. |
| 293 | const entry = yield* fetchJsonReady<{ entry: string }>(`${site.url!}/api/entry`); |
| 294 | expect(entry.entry).toBe("worker-entry"); |
| 295 | |
| 296 | // The DO namespace is bound and state increments ACROSS requests — |
| 297 | // instance identity on the deployed worker, through the custom entry. |
| 298 | const first = yield* fetchJsonReady<{ count: number }>( |
| 299 | `${site.url!}/api/counter/increment`, |
| 300 | ); |
| 301 | const second = yield* fetchJsonReady<{ count: number }>( |
| 302 | `${site.url!}/api/counter/increment`, |
| 303 | ); |
| 304 | expect(second.count).toBe(first.count + 1); |
| 305 | |
| 306 | const read = yield* fetchJsonReady<{ count: number }>(`${site.url!}/api/counter`); |
| 307 | expect(read.count).toBe(second.count); |
| 308 | |
| 309 | // Wrapping waku's handler keeps every framework route working: |
| 310 | // the dynamic RSC page still renders (and still reads bindings). |
| 311 | yield* expectUrlContains(`${site.url!}/`, "WAKU_PAGE_MARKER", { |
| 312 | timeout: "120 seconds", |
| 313 | label: "waku dynamic page through the custom entry", |
| 314 | }); |
| 315 | yield* expectUrlContains(`${site.url!}/`, "MESSAGE=waku-main-marker", { |
| 316 | timeout: "60 seconds", |
| 317 | label: "waku env binding through the custom entry", |
| 318 | }); |
| 319 | |
| 320 | // SSG page + public asset still serve from assets alongside the |
| 321 | // custom entry. |
| 322 | yield* expectUrlContains(`${site.url!}/about`, "WAKU_ABOUT_STATIC_MARKER", { |
| 323 | timeout: "60 seconds", |
| 324 | label: "waku SSG page with custom entry", |
| 325 | }); |
| 326 | yield* expectUrlContains(`${site.url!}/hello.txt`, "hello from public/", { |
| 327 | timeout: "60 seconds", |
| 328 | label: "waku static asset with custom entry", |
| 329 | }); |
| 330 | |
| 331 | yield* stack.destroy(); |
| 332 | yield* waitForWorkerToBeDeleted(site.workerName, accountId); |
| 333 | }).pipe(logLevel), |
| 334 | { timeout: 360_000 }, |
| 335 | ); |
| 336 | }, |
| 337 | ); |
| 338 | |
| 339 | /** |
| 340 | * Execute `request` until it answers 200 with a JSON body (fresh |
| 341 | * workers.dev URLs take a few seconds to start serving; DO namespaces can |
| 342 | * lag the first deploy). Generalizes Vite.test.ts's `fetchJsonReady` to |
| 343 | * arbitrary methods/bodies (POST/PUT round-trips). |
| 344 | */ |
| 345 | const requestJsonReady = <T>(request: HttpClientRequest.HttpClientRequest) => |
| 346 | Effect.gen(function* () { |
| 347 | const client = yield* HttpClient.HttpClient; |
| 348 | return yield* client.execute(request).pipe( |
| 349 | Effect.flatMap((res) => |
| 350 | res.status === 200 |
| 351 | ? Effect.flatMap(res.text, (body) => |
| 352 | Effect.try({ |
| 353 | try: () => JSON.parse(body) as T, |
| 354 | catch: () => new Error(`non-json body: ${body}`), |
| 355 | }), |
| 356 | ) |
| 357 | : Effect.fail(new Error(`Worker not ready: ${res.status}`)), |
| 358 | ), |
| 359 | Effect.retry({ |
| 360 | // Capped interval, ~90s total budget (workers.dev / DO propagation). |
| 361 | schedule: Schedule.min([Schedule.exponential("500 millis"), Schedule.spaced("2 seconds")]), |
| 362 | times: 45, |
| 363 | }), |
| 364 | ); |
| 365 | }); |
| 366 | |
| 367 | const fetchJsonReady = <T>(url: string) => requestJsonReady<T>(HttpClientRequest.get(url)); |
| 368 | |
| 369 | class NamespaceStillExists extends Data.TaggedError("NamespaceStillExists") {} |
| 370 | |
| 371 | /** |
| 372 | * Poll until the KV namespace is gone from the cloud (bounded). Same |
| 373 | * pattern as Astro.test.ts. |
| 374 | */ |
| 375 | const waitForNamespaceToBeDeleted = Effect.fn(function* (namespaceId: string, accountId: string) { |
| 376 | yield* kv.getNamespace({ accountId, namespaceId }).pipe( |
| 377 | Effect.flatMap(() => Effect.fail(new NamespaceStillExists())), |
| 378 | Effect.retry({ |
| 379 | while: (e): e is NamespaceStillExists => e instanceof NamespaceStillExists, |
| 380 | schedule: Schedule.min([Schedule.exponential(250), Schedule.spaced("2 seconds")]), |
| 381 | times: 10, |
| 382 | }), |
| 383 | Effect.catchTag("NamespaceNotFound", () => Effect.void), |
| 384 | ); |
| 385 | }); |