The best way to control Claude Code, Codex and more from any computer or phone

main
ts 232 lines 9.13 KB
Raw
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 r2 from "@distilled.cloud/cloudflare/r2";
6 import * as Data from "effect/Data";
7 import * as Effect from "effect/Effect";
8 import * as HttpClient from "effect/http/HttpClient";
9 import * as HttpClientRequest from "effect/http/HttpClientRequest";
10 import { MinimumLogLevel } from "effect/References";
11 import * as Schedule from "effect/Schedule";
12 import * as pathe from "pathe";
13 import { cloneFixture } from "../Utils/Fixture.ts";
14 import { expectUrlContains } from "../Utils/Http.ts";
15 import { expectWorkerExists, waitForWorkerToBeDeleted } from "../Utils/Worker.ts";
16
17 const { test } = Test.make({ providers: Cloudflare.providers() });
18
19 const logLevel = Effect.provideService(MinimumLogLevel, process.env.DEBUG ? "Debug" : "Info");
20
21 const fixtureDir = pathe.resolve(import.meta.dirname, "tanstack-dev-bindings-fixture");
22
23 // Vite project roots must stay reachable via a sane relative path from the
24 // process cwd (see Vite.test.ts) — clone under the package's own `.tmp/`.
25 const tempRoot = pathe.resolve(import.meta.dirname, "../../../.tmp");
26
27 describe.concurrent(
28 "TanStack Start",
29 {
30 tags: [
31 "provider:cloudflare",
32 "provider:cloudflare:r2",
33 "provider:cloudflare:website",
34 "provider:cloudflare:worker",
35 "live",
36 ],
37 },
38 () => {
39 /**
40 * TanStack Start deploys through `Cloudflare.Website.Vite` (per the Vite
41 * resource's TanStack example) — the `tanstackStart()` plugin in the
42 * fixture's own `vite.config.ts` composes with the injected Cloudflare
43 * plugin. This is the live-deploy counterpart to the dev-mode coverage in
44 * Vite.test.ts: SSR HTML on a raw fetch, a server route answering, the
45 * client asset serving, and an R2 binding round-trip.
46 */
47 test.provider(
48 "TanStack Start: live deploy serves SSR, server routes, assets, and R2 bindings",
49 (stack) =>
50 Effect.gen(function* () {
51 const { accountId } = yield* yield* CloudflareEnvironment;
52
53 yield* stack.destroy();
54
55 const rootDir = yield* cloneFixture(fixtureDir, {
56 prefix: "alchemy-tanstack-live-",
57 tempRoot,
58 entries: ["alchemy.run.ts", "package.json", "tsconfig.json", "vite.config.ts", "src"],
59 });
60 const memoInclude = [
61 "src/**",
62 "package.json",
63 "tsconfig.json",
64 "vite.config.ts",
65 "alchemy.run.ts",
66 ];
67
68 const marker = "tanstack-live-marker";
69
70 const { site, bucket } = yield* stack.deploy(
71 Effect.gen(function* () {
72 const bucket = yield* Cloudflare.R2.Bucket("TanStackLiveBucket", {
73 forceDestroy: true,
74 });
75 const site = yield* Cloudflare.Website.Vite("TanStackStartLive", {
76 rootDir,
77 workersDev: true,
78 compatibility: { date: "2024-09-23", flags: ["nodejs_compat"] },
79 // No `assets` config (mirroring the Vite resource's TanStack
80 // example): client assets serve asset-first from the asset
81 // layer, everything else (SSR routes, /api/*) falls through
82 // to the TanStack server handler. `runWorkerFirst: true`
83 // would route `/assets/*` into the worker, which 404s them.
84 memo: { include: memoInclude },
85 env: { BUCKET: bucket, DEV_MARKER: marker },
86 });
87 return { site, bucket };
88 }),
89 );
90
91 expect(site.url).toBeDefined();
92 yield* expectWorkerExists(site.workerName, accountId);
93
94 // ── SSR: the index route's component renders server-side ─────────
95 // `hmr-marker-fixture` is the constant baked into the fixture's
96 // index route — a raw fetch (no client JS) must carry it.
97 yield* expectUrlContains(`${site.url!}/`, "hmr-marker-fixture", {
98 timeout: "120 seconds",
99 label: "tanstack ssr home",
100 });
101
102 // ── Server route + R2 binding round-trip ─────────────────────────
103 const key = "tanstack-live-key.txt";
104 const r2Url = `${site.url!}/api/r2?key=${encodeURIComponent(key)}`;
105
106 const put = yield* putTextJsonReady<{ ok: boolean; marker: string }>(
107 r2Url,
108 "tanstack-live-value",
109 );
110 expect(put.ok).toBe(true);
111 // The env binding reached the server route.
112 expect(put.marker).toBe(marker);
113
114 const get = yield* fetchJsonReady<{ marker: string; value: string | null }>(r2Url);
115 expect(get.value).toBe("tanstack-live-value");
116 expect(get.marker).toBe(marker);
117
118 // ── Static asset: the client bundle the SSR HTML references ──────
119 yield* expectClientScriptServes(site.url!);
120
121 yield* stack.destroy();
122 yield* waitForWorkerToBeDeleted(site.workerName, accountId);
123 yield* waitForBucketToBeDeleted(bucket.bucketName, accountId);
124 }).pipe(logLevel),
125 { timeout: 360_000 },
126 );
127 },
128 );
129
130 const freshConn = HttpClient.mapRequest(HttpClientRequest.setHeader("connection", "close"));
131
132 const fetchJsonReady = <T>(url: string) =>
133 Effect.gen(function* () {
134 const client = freshConn(yield* HttpClient.HttpClient);
135 return yield* client.get(url).pipe(
136 Effect.flatMap((res) =>
137 res.status === 200
138 ? Effect.flatMap(res.text, (body) =>
139 Effect.try({
140 try: () => JSON.parse(body) as T,
141 catch: () => new Error(`non-json body: ${body}`),
142 }),
143 )
144 : Effect.fail(new Error(`Worker not ready: ${res.status}`)),
145 ),
146 Effect.retry({
147 // Capped interval, ~90s total budget (workers.dev / DO propagation).
148 schedule: Schedule.min([Schedule.exponential("500 millis"), Schedule.spaced("2 seconds")]),
149 times: 45,
150 }),
151 );
152 });
153
154 const putTextJsonReady = <T>(url: string, body: string) =>
155 Effect.gen(function* () {
156 return yield* HttpClient.execute(
157 HttpClientRequest.put(url).pipe(HttpClientRequest.bodyText(body, "text/plain")),
158 ).pipe(
159 Effect.flatMap((res) =>
160 res.status === 200
161 ? Effect.flatMap(res.text, (responseBody) =>
162 Effect.try({
163 try: () => JSON.parse(responseBody) as T,
164 catch: () => new Error(`non-json body: ${responseBody}`),
165 }),
166 )
167 : Effect.fail(new Error(`Worker not ready: ${res.status}`)),
168 ),
169 Effect.retry({
170 // Capped interval, ~90s total budget (workers.dev / DO propagation).
171 schedule: Schedule.min([Schedule.exponential("500 millis"), Schedule.spaced("2 seconds")]),
172 times: 45,
173 }),
174 );
175 });
176
177 /**
178 * Discover a client `<script src="…​.js">` from the served SSR HTML and
179 * assert the referenced asset serves as JavaScript (not the Cloudflare
180 * placeholder page or an HTML error body). Re-discovers the script URL on
181 * every attempt — the bundle filename is content-addressed and the edge can
182 * briefly serve a stale index.
183 */
184 const expectClientScriptServes = (siteUrl: string) =>
185 Effect.gen(function* () {
186 const client = HttpClient.filterStatusOk(yield* HttpClient.HttpClient);
187 yield* Effect.gen(function* () {
188 const res = yield* client.get(`${siteUrl}/`, {
189 urlParams: { __alchemy_cb: String(Date.now()) },
190 headers: { "cache-control": "no-cache", pragma: "no-cache" },
191 });
192 const html = yield* res.text;
193 const match = html.match(/<script[^>]+src="(\/[^"]+\.js[^"]*)"/i);
194 if (!match) {
195 return yield* Effect.fail(
196 new Error(`no client script tag in SSR HTML: ${html.slice(0, 200)}`),
197 );
198 }
199 const assetRes = yield* client.get(`${siteUrl}${match[1]}`);
200 const contentType = assetRes.headers["content-type"] ?? "";
201 const body = yield* assetRes.text;
202 if (!contentType.includes("javascript") || body.includes("<html")) {
203 return yield* Effect.fail(
204 new Error(`asset ${match[1]} did not serve as JS: ${contentType} ${body.slice(0, 120)}`),
205 );
206 }
207 }).pipe(
208 Effect.retry({
209 schedule: Schedule.min([
210 Schedule.exponential("500 millis", 1.5),
211 Schedule.spaced("5 seconds"),
212 ]),
213 times: 30,
214 }),
215 );
216 });
217
218 const waitForBucketToBeDeleted = Effect.fn(function* (bucketName: string, accountId: string) {
219 yield* r2.getBucket({ accountId, bucketName }).pipe(
220 Effect.flatMap(() => Effect.fail(new BucketStillExists())),
221 Effect.retry({
222 while: (e): e is BucketStillExists => e instanceof BucketStillExists,
223 schedule: Schedule.max([
224 Schedule.min([Schedule.exponential("200 millis"), Schedule.spaced("2 seconds")]),
225 Schedule.recurs(20),
226 ]),
227 }),
228 Effect.catchTag("NoSuchBucket", () => Effect.void),
229 );
230 });
231
232 class BucketStillExists extends Data.TaggedError("BucketStillExists") {}