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
| 1 | import * as Cloudflare from "@alchemy.run/cloudflare"; |
| 2 | /** |
| 3 | * Regression test for serving a Vite site on a zone route with a path |
| 4 | * prefix. |
| 5 | * |
| 6 | * Cloudflare matches static assets against the FULL request pathname |
| 7 | * (https://developers.cloudflare.com/workers/static-assets/routing/advanced/serving-a-subdirectory/): |
| 8 | * a Worker routed at `zone/prefix*` only serves an asset for |
| 9 | * `/prefix/index.html` if the uploaded asset manifest contains that key. |
| 10 | * Vite's `base` (from the app's own vite.config.ts) rewrites the URLs the |
| 11 | * build emits, and Alchemy keys the uploaded manifest with the same |
| 12 | * resolved base — both halves are required for the site to work behind |
| 13 | * the route. The SPA fallback shell is aliased back to `/index.html` |
| 14 | * (Cloudflare resolves it at the manifest root, hard-coded), pinned here |
| 15 | * by the deep-link probe. |
| 16 | */ |
| 17 | import { CloudflareEnvironment } from "@alchemy.run/cloudflare/CloudflareEnvironment"; |
| 18 | import { findZoneByName } from "@alchemy.run/cloudflare/Zone/lookup"; |
| 19 | import { describe, expect } from "@alchemy.run/test"; |
| 20 | import * as Test from "@alchemy.run/test/Alchemy"; |
| 21 | import * as dns from "@distilled.cloud/cloudflare/dns"; |
| 22 | import * as workers from "@distilled.cloud/cloudflare/workers"; |
| 23 | import * as Data from "effect/Data"; |
| 24 | import * as Effect from "effect/Effect"; |
| 25 | import * as FileSystem from "effect/FileSystem"; |
| 26 | import * as Path from "effect/Path"; |
| 27 | import { MinimumLogLevel } from "effect/References"; |
| 28 | import * as Schedule from "effect/Schedule"; |
| 29 | import * as Stream from "effect/Stream"; |
| 30 | import * as pathe from "pathe"; |
| 31 | import { stageSuffix } from "../../names.ts"; |
| 32 | import { cloneFixture } from "../Utils/Fixture.ts"; |
| 33 | import { waitForWorkerToBeDeleted } from "../Utils/Worker.ts"; |
| 34 | |
| 35 | const { test } = Test.make({ providers: Cloudflare.providers() }); |
| 36 | |
| 37 | const logLevel = Effect.provideService(MinimumLogLevel, process.env.DEBUG ? "Debug" : "Info"); |
| 38 | |
| 39 | const spaFixtureDir = pathe.resolve(import.meta.dirname, "vite-spa-fixture"); |
| 40 | const tempRoot = pathe.resolve(import.meta.dirname, "../../../.tmp"); |
| 41 | |
| 42 | const zoneName = process.env.CLOUDFLARE_TEST_WORKER_ROUTE_ZONE_NAME ?? "alchemy-test-2.us"; |
| 43 | |
| 44 | // Deterministic per-user path prefix on the zone apex (never Date.now()). |
| 45 | const routePrefix = `alchemy-vite-route-repro-${stageSuffix()}`; |
| 46 | const basePath = `/${routePrefix}/app`; |
| 47 | const routePattern = `${zoneName}${basePath}*`; |
| 48 | const routePageUrl = `https://${zoneName}${basePath}/`; |
| 49 | |
| 50 | const marker = "vite-route-prefix-repro"; |
| 51 | |
| 52 | const htmlPage = `<!doctype html> |
| 53 | <html lang="en"> |
| 54 | <head> |
| 55 | <meta charset="UTF-8" /> |
| 56 | <title>${marker}</title> |
| 57 | </head> |
| 58 | <body> |
| 59 | <div id="app">${marker}</div> |
| 60 | <script type="module" src="/src/main.ts"></script> |
| 61 | </body> |
| 62 | </html> |
| 63 | `; |
| 64 | |
| 65 | // Capped: an uncapped exponential over 8 recurs sums to ~2 minutes and turns |
| 66 | // a persistent 403 into an apparent hang. |
| 67 | const forbiddenRetrySchedule = Schedule.min([ |
| 68 | Schedule.exponential("500 millis"), |
| 69 | Schedule.spaced("2 seconds"), |
| 70 | ]); |
| 71 | |
| 72 | const resolveZoneId = Effect.gen(function* () { |
| 73 | const { accountId } = yield* yield* CloudflareEnvironment; |
| 74 | const zone = yield* findZoneByName({ accountId, name: zoneName }); |
| 75 | if (!zone) { |
| 76 | return yield* Effect.die(new Error(`zone "${zoneName}" not found in account`)); |
| 77 | } |
| 78 | return zone.id; |
| 79 | }); |
| 80 | |
| 81 | // Workers only run on proxied hostnames — the apex placeholder is standing |
| 82 | // test-zone infrastructure (see WorkerRoutes.test.ts); ensure, never delete. |
| 83 | const ensureApexPlaceholder = (zoneId: string) => |
| 84 | Effect.gen(function* () { |
| 85 | const existing = yield* dns.listRecords.items({ zoneId }).pipe( |
| 86 | Stream.filter((r) => r.name === zoneName && (r.type === "A" || r.type === "AAAA")), |
| 87 | Stream.runCollect, |
| 88 | Effect.map((chunk) => Array.from(chunk)[0]), |
| 89 | Effect.retry({ |
| 90 | while: (e) => e._tag === "Forbidden", |
| 91 | schedule: forbiddenRetrySchedule, |
| 92 | times: 8, |
| 93 | }), |
| 94 | ); |
| 95 | if (existing) return; |
| 96 | yield* dns.createRecord({ |
| 97 | zoneId, |
| 98 | name: zoneName, |
| 99 | type: "AAAA", |
| 100 | content: "100::", |
| 101 | proxied: true, |
| 102 | ttl: 1, |
| 103 | comment: "standing placeholder so Workers routes serve on the zone apex", |
| 104 | }); |
| 105 | }); |
| 106 | |
| 107 | const purgeRoutes = (zoneId: string, ...patterns: string[]) => |
| 108 | Effect.forEach(patterns, (pattern) => |
| 109 | workers.listRoutes.items({ zoneId }).pipe( |
| 110 | Stream.filter((r) => r.pattern === pattern), |
| 111 | Stream.runCollect, |
| 112 | Effect.flatMap( |
| 113 | Effect.forEach((r) => |
| 114 | workers.deleteRoute({ zoneId, routeId: r.id }).pipe(Effect.catch(() => Effect.void)), |
| 115 | ), |
| 116 | ), |
| 117 | Effect.retry({ |
| 118 | while: (e) => e._tag === "Forbidden", |
| 119 | schedule: forbiddenRetrySchedule, |
| 120 | times: 8, |
| 121 | }), |
| 122 | ), |
| 123 | ); |
| 124 | |
| 125 | class ProbeFailed extends Data.TaggedError("ProbeFailed")<{ url: string; message: string }> {} |
| 126 | |
| 127 | interface ProbeResult { |
| 128 | url: string; |
| 129 | status: number; |
| 130 | contentType: string | undefined; |
| 131 | body: string; |
| 132 | } |
| 133 | |
| 134 | // One GET with cache busting; retried below until the edge stops serving |
| 135 | // 5xx / Cloudflare error pages / stale-deploy 404s (route + worker + asset |
| 136 | // propagation). |
| 137 | const probeOnce = (url: string) => |
| 138 | Effect.tryPromise({ |
| 139 | try: async (signal): Promise<ProbeResult> => { |
| 140 | const u = new URL(url); |
| 141 | u.searchParams.set("__alchemy_cb", String(Date.now())); |
| 142 | const res = await fetch(u, { |
| 143 | signal, |
| 144 | cache: "no-store", |
| 145 | headers: { "cache-control": "no-cache", accept: "*/*" }, |
| 146 | }); |
| 147 | const body = await res.text(); |
| 148 | return { |
| 149 | url, |
| 150 | status: res.status, |
| 151 | contentType: res.headers.get("content-type") ?? undefined, |
| 152 | body, |
| 153 | }; |
| 154 | }, |
| 155 | catch: (e) => new ProbeFailed({ url, message: e instanceof Error ? e.message : String(e) }), |
| 156 | }); |
| 157 | |
| 158 | const isPropagating = (r: ProbeResult) => |
| 159 | r.status !== 200 || |
| 160 | r.body.includes("There is nothing here yet") || |
| 161 | /Error\s+1\d{3}/i.test(r.body); |
| 162 | |
| 163 | const probeStable = (url: string) => |
| 164 | probeOnce(url).pipe( |
| 165 | Effect.repeat({ |
| 166 | schedule: Schedule.spaced("3 seconds"), |
| 167 | until: (r: ProbeResult) => !isPropagating(r), |
| 168 | // ~90s: workers.dev/zone-route propagation slows down when many |
| 169 | // concurrent deploys enable fresh subdomains at once. |
| 170 | times: 30, |
| 171 | }), |
| 172 | Effect.retry({ |
| 173 | while: (e) => e._tag === "ProbeFailed", |
| 174 | schedule: Schedule.exponential("1 second"), |
| 175 | times: 5, |
| 176 | }), |
| 177 | ); |
| 178 | |
| 179 | const excerpt = (s: string) => s.replace(/\s+/g, " ").slice(0, 200); |
| 180 | |
| 181 | /** |
| 182 | * End-to-end "does the SPA actually work here" check: the page must serve |
| 183 | * the marker HTML AND the module script it references must be fetchable |
| 184 | * (as JavaScript) from the same host. |
| 185 | */ |
| 186 | const evaluateSite = Effect.fn(function* (pageUrl: string, label: string) { |
| 187 | const page = yield* probeStable(pageUrl); |
| 188 | yield* Effect.log( |
| 189 | `[${label}] page ${page.status} ${page.contentType ?? "-"} :: ${excerpt(page.body)}`, |
| 190 | ); |
| 191 | const src = page.body.match(/<script[^>]+src="([^"]+)"/)?.[1]; |
| 192 | let script: ProbeResult | undefined; |
| 193 | if (page.status === 200 && src) { |
| 194 | const scriptUrl = new URL(src, pageUrl).toString(); |
| 195 | script = yield* probeStable(scriptUrl); |
| 196 | yield* Effect.log( |
| 197 | `[${label}] script ${scriptUrl} -> ${script.status} ${script.contentType ?? "-"} :: ${excerpt(script.body)}`, |
| 198 | ); |
| 199 | } |
| 200 | return { page, src, script }; |
| 201 | }); |
| 202 | |
| 203 | // Tests are independent (per-test scratch stacks, private fixture clones), |
| 204 | // so run them concurrently; suites are sequential by default. |
| 205 | describe.concurrent( |
| 206 | "ViteRoutePrefix", |
| 207 | { |
| 208 | tags: [ |
| 209 | "provider:cloudflare", |
| 210 | "provider:cloudflare:dns", |
| 211 | "provider:cloudflare:website", |
| 212 | "provider:cloudflare:worker", |
| 213 | "provider:cloudflare:zone", |
| 214 | "live", |
| 215 | ], |
| 216 | }, |
| 217 | () => { |
| 218 | test.provider( |
| 219 | "Vite: base from vite.config.ts serves the site on a path-prefixed zone route", |
| 220 | (stack) => |
| 221 | Effect.gen(function* () { |
| 222 | const { accountId } = yield* yield* CloudflareEnvironment; |
| 223 | const fs = yield* FileSystem.FileSystem; |
| 224 | const path = yield* Path.Path; |
| 225 | const zoneId = yield* resolveZoneId; |
| 226 | |
| 227 | yield* stack.destroy(); |
| 228 | yield* purgeRoutes(zoneId, routePattern); |
| 229 | yield* ensureApexPlaceholder(zoneId); |
| 230 | |
| 231 | const rootDir = yield* cloneFixture(spaFixtureDir, { |
| 232 | prefix: "alchemy-vite-route-", |
| 233 | tempRoot, |
| 234 | entries: ["index.html", "package.json", "src"], |
| 235 | }); |
| 236 | yield* fs.writeFileString(path.join(rootDir, "index.html"), htmlPage); |
| 237 | // The base lives in the app's own Vite config — the deploy adopts |
| 238 | // the resolved value; nothing is configured on the alchemy side. |
| 239 | yield* fs.writeFileString( |
| 240 | path.join(rootDir, "vite.config.ts"), |
| 241 | `import { defineConfig } from "vite";\n\nexport default defineConfig({ base: "${basePath}/" });\n`, |
| 242 | ); |
| 243 | const memoInclude = ["index.html", "src/**", "package.json", "vite.config.ts"]; |
| 244 | |
| 245 | let workerName: string | undefined; |
| 246 | |
| 247 | yield* Effect.gen(function* () { |
| 248 | const site = yield* stack.deploy( |
| 249 | Effect.gen(function* () { |
| 250 | return yield* Cloudflare.Website.Vite("ViteRoutePrefix", { |
| 251 | rootDir, |
| 252 | workersDev: true, |
| 253 | compatibility: { date: "2024-09-23", flags: ["nodejs_compat"] }, |
| 254 | memo: { include: memoInclude }, |
| 255 | assets: { notFoundHandling: "single-page-application" }, |
| 256 | routes: [{ pattern: routePattern, zoneName }], |
| 257 | }); |
| 258 | }), |
| 259 | ); |
| 260 | workerName = site.workerName; |
| 261 | |
| 262 | expect(site.url).toBeDefined(); |
| 263 | expect(site.routes).toHaveLength(1); |
| 264 | expect(site.routes[0]?.pattern).toEqual(routePattern); |
| 265 | |
| 266 | // Control — the same manifest serves under the prefix on |
| 267 | // workers.dev too (the manifest is nested, not the route). |
| 268 | const control = yield* evaluateSite(`${site.url!}${basePath}/`, "workers.dev"); |
| 269 | expect(control.page.status).toBe(200); |
| 270 | expect(control.page.body).toContain(marker); |
| 271 | // Vite `base` bakes the prefix into the emitted script URL. |
| 272 | expect(control.src).toContain(`${basePath}/`); |
| 273 | expect(control.script?.status).toBe(200); |
| 274 | expect(control.script?.contentType).toContain("javascript"); |
| 275 | |
| 276 | // The point of the feature: the site works end-to-end behind the |
| 277 | // path-prefixed zone route — HTML serves AND the module script it |
| 278 | // references resolves under the prefix (inside the route). |
| 279 | const routed = yield* evaluateSite(routePageUrl, "zone route"); |
| 280 | expect(routed.page.status).toBe(200); |
| 281 | expect(routed.page.body).toContain(marker); |
| 282 | expect(routed.script?.status).toBe(200); |
| 283 | expect(routed.script?.contentType).toContain("javascript"); |
| 284 | // `(hydrated)` is a string literal in the fixture's client module, |
| 285 | // so it proves the response is the real script — a 404 here would |
| 286 | // be answered by the SPA fallback with the shell, which contains |
| 287 | // the marker but never that literal. |
| 288 | expect(routed.script?.body).toContain("(hydrated)"); |
| 289 | expect(routed.script?.url.startsWith(`https://${zoneName}${basePath}/`)).toBe(true); |
| 290 | |
| 291 | // Cloudflare's SPA fallback resolves `/index.html` at the manifest |
| 292 | // root, hard-coded — the shell is aliased back there so client-side |
| 293 | // routes under the base still boot the app. |
| 294 | const deep = yield* probeStable(`https://${zoneName}${basePath}/deep/route`); |
| 295 | yield* Effect.log( |
| 296 | `[spa deep link] ${deep.status} ${deep.contentType ?? "-"} :: ${excerpt(deep.body)}`, |
| 297 | ); |
| 298 | expect(deep.status).toBe(200); |
| 299 | expect(deep.body).toContain(marker); |
| 300 | }).pipe( |
| 301 | Effect.ensuring( |
| 302 | Effect.gen(function* () { |
| 303 | yield* stack.destroy().pipe(Effect.ignore); |
| 304 | yield* purgeRoutes(zoneId, routePattern).pipe(Effect.ignore); |
| 305 | if (workerName) { |
| 306 | yield* waitForWorkerToBeDeleted(workerName, accountId).pipe(Effect.ignore); |
| 307 | } |
| 308 | }), |
| 309 | ), |
| 310 | ); |
| 311 | }).pipe(logLevel), |
| 312 | { timeout: 360_000 }, |
| 313 | ); |
| 314 | }, |
| 315 | ); |