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 { expectClientChunkContains, expectUrlContains } from "../Utils/Http.ts"; |
| 18 | import { expectWorkerExists, waitForWorkerToBeDeleted } from "../Utils/Worker.ts"; |
| 19 | |
| 20 | const { test } = Test.make({ providers: Cloudflare.providers() }); |
| 21 | |
| 22 | const logLevel = Effect.provideService(MinimumLogLevel, process.env.DEBUG ? "Debug" : "Info"); |
| 23 | |
| 24 | const fixtureDir = pathe.resolve(import.meta.dirname, "fixtures", "octane-app"); |
| 25 | |
| 26 | // Keep the temp clone under the alchemy package (same convention as the |
| 27 | // Vite tests) so the project root stays representable relative to cwd — |
| 28 | // and so `octane`/`@octanejs/*` resolve from the workspace's hoisted |
| 29 | // node_modules when the fixture's own tree has none. |
| 30 | const tempRoot = pathe.resolve(import.meta.dirname, "../../../.tmp"); |
| 31 | |
| 32 | const fixtureEntries = [ |
| 33 | ".gitignore", |
| 34 | "package.json", |
| 35 | "octane.config.ts", |
| 36 | "vite.config.ts", |
| 37 | "index.html", |
| 38 | "src", |
| 39 | "public", |
| 40 | ]; |
| 41 | |
| 42 | const memoInclude = [ |
| 43 | "src/**", |
| 44 | "public/**", |
| 45 | "index.html", |
| 46 | "octane.config.ts", |
| 47 | "vite.config.ts", |
| 48 | "package.json", |
| 49 | ]; |
| 50 | |
| 51 | const octaneProps = (rootDir: string) => ({ |
| 52 | rootDir, |
| 53 | workersDev: { enabled: true, previewsEnabled: true }, |
| 54 | memo: { |
| 55 | include: memoInclude, |
| 56 | }, |
| 57 | }); |
| 58 | |
| 59 | class NamespaceStillExists extends Data.TaggedError("NamespaceStillExists") {} |
| 60 | |
| 61 | const waitForNamespaceToBeDeleted = Effect.fn(function* (namespaceId: string, accountId: string) { |
| 62 | yield* kv.getNamespace({ accountId, namespaceId }).pipe( |
| 63 | Effect.flatMap(() => Effect.fail(new NamespaceStillExists())), |
| 64 | Effect.retry({ |
| 65 | while: (e): e is NamespaceStillExists => e instanceof NamespaceStillExists, |
| 66 | schedule: Schedule.min([Schedule.exponential(250), Schedule.spaced("2 seconds")]), |
| 67 | times: 10, |
| 68 | }), |
| 69 | Effect.catchTag("NamespaceNotFound", () => Effect.void), |
| 70 | ); |
| 71 | }); |
| 72 | |
| 73 | /** |
| 74 | * Read `keyName` from the real cloud namespace via distilled's KV API, |
| 75 | * retrying through KV's brief read-after-write lag while the key is not |
| 76 | * yet visible. |
| 77 | */ |
| 78 | const readNamespaceValue = Effect.fn(function* (options: { |
| 79 | accountId: string; |
| 80 | namespaceId: string; |
| 81 | keyName: string; |
| 82 | }) { |
| 83 | const res = yield* kv.getNamespaceValue(options).pipe( |
| 84 | Effect.retry({ |
| 85 | while: (e): boolean => e._tag === "KeyNotFound", |
| 86 | schedule: Schedule.min([Schedule.exponential("1 second"), Schedule.spaced("3 seconds")]), |
| 87 | times: 8, |
| 88 | }), |
| 89 | ); |
| 90 | return yield* Effect.tryPromise(() => |
| 91 | new Response(Stream.toReadableStream(res.body) as BodyInit).text(), |
| 92 | ); |
| 93 | }); |
| 94 | |
| 95 | // Tests are independent (per-test scratch stacks, private fixture clones), |
| 96 | // so run them concurrently; suites are sequential by default. |
| 97 | describe.concurrent( |
| 98 | "Octane", |
| 99 | { |
| 100 | tags: [ |
| 101 | "provider:cloudflare", |
| 102 | "provider:cloudflare:kv", |
| 103 | "provider:cloudflare:website", |
| 104 | "provider:cloudflare:worker", |
| 105 | "live", |
| 106 | ], |
| 107 | }, |
| 108 | () => { |
| 109 | test.provider( |
| 110 | "Octane: deploys SSR + bindings + static assets and memoizes unchanged rebuilds", |
| 111 | (stack) => |
| 112 | Effect.gen(function* () { |
| 113 | const { accountId } = yield* yield* CloudflareEnvironment; |
| 114 | const fs = yield* FileSystem.FileSystem; |
| 115 | const path = yield* Path.Path; |
| 116 | |
| 117 | yield* stack.destroy(); |
| 118 | |
| 119 | const rootDir = yield* cloneFixture(fixtureDir, { |
| 120 | prefix: "alchemy-octane-", |
| 121 | tempRoot, |
| 122 | entries: fixtureEntries, |
| 123 | }); |
| 124 | |
| 125 | const bindingMarker = "octane-binding-marker"; |
| 126 | |
| 127 | const deploy = () => |
| 128 | stack.deploy( |
| 129 | Effect.gen(function* () { |
| 130 | const siteKv = yield* Cloudflare.KV.Namespace("SiteKV"); |
| 131 | const site = yield* Cloudflare.Website.Octane("OctaneSite", { |
| 132 | ...octaneProps(rootDir), |
| 133 | env: { |
| 134 | TEST_BINDING: bindingMarker, |
| 135 | SITE_KV: siteKv, |
| 136 | VITE_SITE_MARKER: "OCTANE_PUBLIC_ENV_MARKER", |
| 137 | }, |
| 138 | }); |
| 139 | return { site, siteKv }; |
| 140 | }), |
| 141 | ); |
| 142 | |
| 143 | const { site: site1, siteKv } = yield* deploy(); |
| 144 | |
| 145 | expect(site1.url).toBeDefined(); |
| 146 | expect(site1.hash?.input).toBeDefined(); |
| 147 | yield* expectWorkerExists(site1.workerName, accountId); |
| 148 | |
| 149 | // SSR page: the adapter-emitted worker renders on asset miss. |
| 150 | yield* expectUrlContains(`${site1.url!}/`, "OCTANE_PAGE_MARKER", { |
| 151 | timeout: "120 seconds", |
| 152 | label: "SSR home page", |
| 153 | }); |
| 154 | |
| 155 | // A declared public env value is inlined into the deployed client |
| 156 | // bundle at build time. |
| 157 | yield* expectClientChunkContains( |
| 158 | site1.url!, |
| 159 | pathe.join(rootDir, "dist", "client"), |
| 160 | "OCTANE_PUBLIC_ENV_MARKER", |
| 161 | { |
| 162 | timeout: "60 seconds", |
| 163 | label: "octane public env", |
| 164 | }, |
| 165 | ); |
| 166 | |
| 167 | // Server route: reads `context.platform` — the adapter-forwarded |
| 168 | // `{ env, ctx }` pair — proving bindings reach Octane's runtime |
| 169 | // contract. |
| 170 | const hello = yield* fetchJsonReady<{ |
| 171 | marker: string; |
| 172 | binding: string | null; |
| 173 | hasWaitUntil: boolean; |
| 174 | }>(`${site1.url!}/api/hello`); |
| 175 | expect(hello.marker).toBe("api-route-ok"); |
| 176 | expect(hello.binding).toBe(bindingMarker); |
| 177 | expect(hello.hasWaitUntil).toBe(true); |
| 178 | |
| 179 | // KV binding: the worker's PUT lands in the real namespace and the |
| 180 | // worker's GET reads it back through the native binding. |
| 181 | const kvKey = "octane-live-key"; |
| 182 | const kvValue = "octane-live-value"; |
| 183 | expect(siteKv.namespaceId).toBeDefined(); |
| 184 | const put = yield* putJsonReady<{ put: boolean; key: string }>( |
| 185 | `${site1.url!}/api/kv?key=${kvKey}&value=${kvValue}`, |
| 186 | ); |
| 187 | expect(put.put).toBe(true); |
| 188 | const got = yield* fetchJsonReady<{ |
| 189 | key: string; |
| 190 | value: string | null; |
| 191 | }>(`${site1.url!}/api/kv?key=${kvKey}`); |
| 192 | expect(got.value).toBe(kvValue); |
| 193 | |
| 194 | // Out-of-band: the write is visible through the cloud KV API — the |
| 195 | // binding really targeted the namespace this stack provisioned. |
| 196 | const observed = yield* readNamespaceValue({ |
| 197 | accountId, |
| 198 | namespaceId: siteKv.namespaceId, |
| 199 | keyName: kvKey, |
| 200 | }); |
| 201 | expect(observed).toBe(kvValue); |
| 202 | |
| 203 | // Static asset from `public/`, served asset-first. |
| 204 | yield* expectUrlContains(`${site1.url!}/robots.txt`, "User-agent", { |
| 205 | timeout: "60 seconds", |
| 206 | label: "static asset", |
| 207 | }); |
| 208 | |
| 209 | // ── deploy 2: no changes ⇒ the rebuild-free input hash matches and |
| 210 | // the deploy short-circuits without building ───────────────────────── |
| 211 | const { site: site2 } = yield* deploy(); |
| 212 | |
| 213 | expect(site2.hash?.input).toBeDefined(); |
| 214 | expect(site2.hash?.input).toEqual(site1.hash?.input); |
| 215 | expect(site2.url).toBe(site1.url); |
| 216 | |
| 217 | // ── deploy 3: edit the page ⇒ the input hash changes and the new |
| 218 | // content deploys. The edited marker is asserted on the *dynamic* |
| 219 | // SSR page (worker-rendered per request) — a changed static asset at |
| 220 | // the same URL can stay stale at a PoP far longer than a |
| 221 | // worker-version flip ──────────────────────────────────────────────── |
| 222 | const appPath = path.join(rootDir, "src/App.tsx"); |
| 223 | const app = yield* fs.readFileString(appPath); |
| 224 | yield* fs.writeFileString( |
| 225 | appPath, |
| 226 | app.replace("OCTANE_PAGE_MARKER", "OCTANE_PAGE_MARKER_V2"), |
| 227 | ); |
| 228 | |
| 229 | const { site: site3 } = yield* deploy(); |
| 230 | |
| 231 | expect(site3.hash?.input).toBeDefined(); |
| 232 | expect(site3.hash?.input).not.toEqual(site1.hash?.input); |
| 233 | yield* expectUrlContains(`${site3.url!}/`, "OCTANE_PAGE_MARKER_V2", { |
| 234 | timeout: "180 seconds", |
| 235 | label: "SSR page after edit", |
| 236 | }); |
| 237 | |
| 238 | yield* stack.destroy(); |
| 239 | yield* waitForWorkerToBeDeleted(site1.workerName, accountId); |
| 240 | |
| 241 | // Destroy must also delete the stack-provisioned KV namespace. |
| 242 | yield* waitForNamespaceToBeDeleted(siteKv.namespaceId, accountId); |
| 243 | }).pipe(logLevel), |
| 244 | { timeout: 600_000 }, |
| 245 | ); |
| 246 | }, |
| 247 | ); |
| 248 | |
| 249 | /** |
| 250 | * GET `url` until it answers 200 with a JSON body (fresh workers.dev URLs |
| 251 | * take a few seconds to start serving). Mirrors Nuxt.test.ts's helper of |
| 252 | * the same name. |
| 253 | */ |
| 254 | const fetchJsonReady = <T>(url: string) => |
| 255 | Effect.gen(function* () { |
| 256 | const client = yield* HttpClient.HttpClient; |
| 257 | return yield* client.get(url).pipe( |
| 258 | Effect.flatMap((res) => |
| 259 | res.status === 200 |
| 260 | ? Effect.flatMap(res.text, (body) => |
| 261 | Effect.try({ |
| 262 | try: () => JSON.parse(body) as T, |
| 263 | catch: () => new Error(`non-json body: ${body}`), |
| 264 | }), |
| 265 | ) |
| 266 | : Effect.fail(new Error(`Worker not ready: ${res.status}`)), |
| 267 | ), |
| 268 | Effect.retry({ |
| 269 | // Capped interval, ~90s total budget (workers.dev / DO propagation). |
| 270 | schedule: Schedule.min([Schedule.exponential("500 millis"), Schedule.spaced("2 seconds")]), |
| 271 | times: 45, |
| 272 | }), |
| 273 | ); |
| 274 | }); |
| 275 | |
| 276 | /** PUT (empty body) to `url` until it answers 200 with a JSON body. */ |
| 277 | const putJsonReady = <T>(url: string) => |
| 278 | HttpClient.execute(HttpClientRequest.put(url)).pipe( |
| 279 | Effect.flatMap((res) => |
| 280 | res.status === 200 |
| 281 | ? Effect.flatMap(res.text, (responseBody) => |
| 282 | Effect.try({ |
| 283 | try: () => JSON.parse(responseBody) as T, |
| 284 | catch: () => new Error(`non-json body: ${responseBody}`), |
| 285 | }), |
| 286 | ) |
| 287 | : Effect.fail(new Error(`Worker not ready: ${res.status}`)), |
| 288 | ), |
| 289 | Effect.retry({ |
| 290 | // Capped interval, ~90s total budget (workers.dev / DO propagation). |
| 291 | schedule: Schedule.min([Schedule.exponential("500 millis"), Schedule.spaced("2 seconds")]), |
| 292 | times: 45, |
| 293 | }), |
| 294 | ); |