@devries-cameron20 / t3code Mirror · read-only
Fork 0

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

main
ts 326 lines 13.4 KB
Raw
1 import * as Cloudflare from "@alchemy.run/cloudflare";
2 import { CloudflareEnvironment } from "@alchemy.run/cloudflare/CloudflareEnvironment";
3 import { isLocalId } from "@alchemy.run/cloudflare/LocalRuntime";
4 import { describe, expect } from "@alchemy.run/test";
5 import * as Test from "@alchemy.run/test/Alchemy";
6 import * as kv from "@distilled.cloud/cloudflare/kv";
7 import * as Alchemy from "alchemy";
8 import * as Effect from "effect/Effect";
9 import * as FileSystem from "effect/FileSystem";
10 import * as HttpClient from "effect/http/HttpClient";
11 import * as HttpClientRequest from "effect/http/HttpClientRequest";
12 import * as Path from "effect/Path";
13 import { MinimumLogLevel } from "effect/References";
14 import * as Schedule from "effect/Schedule";
15 import * as Stream from "effect/Stream";
16 import * as pathe from "pathe";
17 import { cloneFixture } from "../Utils/Fixture.ts";
18 import { expectUrlContains } from "../Utils/Http.ts";
19 import { prepareNextjsFixture } from "./TypeScriptCompat.ts";
20
21 const { test } = Test.make({ providers: Cloudflare.providers(), dev: true });
22
23 const logLevel = Effect.provideService(MinimumLogLevel, process.env.DEBUG ? "Debug" : "Info");
24
25 const fixtureDir = pathe.resolve(import.meta.dirname, "fixtures", "nextjs-app");
26
27 const fixtureEntries = [
28 "package.json",
29 "tsconfig.json",
30 "next.config.mjs",
31 "middleware.ts",
32 "app",
33 "pages",
34 "public",
35 ];
36
37 const memoInclude = [
38 "app/**",
39 "pages/**",
40 "public/**",
41 "package.json",
42 "tsconfig.json",
43 "middleware.ts",
44 "next.config.mjs",
45 ];
46
47 /** GET `url` until it answers 200 with a JSON body — bounded (~60s). */
48 const fetchJsonReady = <T>(url: string) =>
49 Effect.gen(function* () {
50 const client = yield* HttpClient.HttpClient;
51 return yield* client.get(url).pipe(
52 Effect.flatMap((res) =>
53 Effect.flatMap(res.text, (body) =>
54 res.status === 200
55 ? Effect.try({
56 try: () => JSON.parse(body) as T,
57 catch: () => new Error(`non-json body: ${body}`),
58 })
59 : Effect.fail(new Error(`Worker not ready (${res.status}): ${body.slice(0, 300)}`)),
60 ),
61 ),
62 Effect.retry({ schedule: Schedule.spaced("2 seconds"), times: 30 }),
63 );
64 });
65
66 /** PUT a JSON body to the fixture's /api/kv route — bounded (~60s). */
67 const putKv = (base: string, key: string, value: string) =>
68 HttpClient.execute(
69 HttpClientRequest.put(`${base}/api/kv`).pipe(HttpClientRequest.bodyJsonUnsafe({ key, value })),
70 ).pipe(
71 Effect.flatMap((res) =>
72 res.status === 200
73 ? res.json
74 : Effect.flatMap(res.text, (body) =>
75 Effect.fail(new Error(`kv put not ready (${res.status}): ${body.slice(0, 300)}`)),
76 ),
77 ),
78 Effect.retry({ schedule: Schedule.spaced("2 seconds"), times: 30 }),
79 );
80
81 // ─────────────────────────────────────────────────────────────────────
82 // Preview mode (the default): the OpenNext worker is built and served
83 // under workerd locally — production parity, no HMR.
84 // ─────────────────────────────────────────────────────────────────────
85
86 // Tests are independent (per-test scratch stacks, private fixture clones),
87 // so run them concurrently; suites are sequential by default.
88 describe.concurrent(
89 "Nextjs dev",
90 { tags: ["provider:cloudflare", "provider:cloudflare:website"] },
91 () => {
92 test.provider(
93 "Nextjs dev (preview): OpenNext worker under local workerd with emulated bindings",
94 (stack) =>
95 Effect.gen(function* () {
96 yield* stack.destroy();
97
98 // Clone outside the repo so Next does not treat the alchemy
99 // monorepo as the workspace root (that lookup hits typescript 7
100 // / tsgo, which has no `lib/typescript.js`).
101 const rootDir = yield* cloneFixture(fixtureDir, {
102 prefix: "alchemy-nextjs-dev-",
103 entries: fixtureEntries,
104 });
105 yield* prepareNextjsFixture(rootDir);
106
107 const bindingMarker = "nextjs-dev-binding-marker";
108
109 const deployed = yield* stack.deploy(
110 Effect.gen(function* () {
111 const siteKv = yield* Cloudflare.KV.Namespace("NextjsDevKV");
112 const site = yield* Cloudflare.Website.Nextjs("NextjsLocal", {
113 rootDir,
114 dev: { port: 0 },
115 memo: { include: memoInclude },
116 env: { TEST_TEXT: bindingMarker, FIXTURE_KV: siteKv },
117 });
118 return { site, siteKv };
119 }),
120 );
121 const site = deployed.site;
122
123 // Local identity: the url points at the alchemy dev proxy — no cloud
124 // Worker exists — and the KV namespace is emulated (`dev:` id, proof
125 // no cloud API call ran).
126 expect(site.url).toBeDefined();
127 expect(site.url).toMatch(/^http:\/\/localhost:\d+/);
128 expect(isLocalId(deployed.siteKv.namespaceId)).toBe(true);
129
130 // The SSR page rendered by the OpenNext worker under workerd.
131 yield* expectUrlContains(`${site.url!}/`, "NEXTJS_SSR_MARKER", {
132 timeout: "120 seconds",
133 label: "nextjs dev SSR home page",
134 });
135
136 // Binding read through OpenNext's getCloudflareContext().
137 const binding = yield* fetchJsonReady<{ value: string | null }>(
138 `${site.url!}/api/binding`,
139 );
140 expect(binding.value).toBe(bindingMarker);
141
142 // Prerendered ISR page serves from the read-only static-assets cache.
143 yield* expectUrlContains(`${site.url!}/isr`, "NEXTJS_ISR_MARKER", {
144 timeout: "60 seconds",
145 label: "nextjs dev prerendered ISR page",
146 });
147
148 // Static asset from public/.
149 yield* expectUrlContains(`${site.url!}/static.txt`, "NEXTJS_STATIC_ASSET_MARKER", {
150 timeout: "60 seconds",
151 label: "nextjs dev static asset",
152 });
153
154 // KV round-trip against the local simulator through the worker.
155 yield* putKv(site.url!, "dev-key", "dev-value");
156 const got = yield* fetchJsonReady<{ value: string | null }>(
157 `${site.url!}/api/kv?key=dev-key`,
158 );
159 expect(got.value).toBe("dev-value");
160
161 yield* stack.destroy();
162 }).pipe(logLevel),
163 { tags: ["provider:cloudflare:kv", "local"], timeout: 420_000 },
164 );
165
166 // ─────────────────────────────────────────────────────────────────────
167 // HMR mode: the real `next dev` (Turbopack) in Node, bindings proxied
168 // onto OpenNext's getCloudflareContext() contract.
169 // ─────────────────────────────────────────────────────────────────────
170
171 test.provider(
172 "Nextjs dev (hmr): real next dev serves edits without redeploying",
173 (stack) =>
174 Effect.gen(function* () {
175 const fs = yield* FileSystem.FileSystem;
176 const path = yield* Path.Path;
177
178 yield* stack.destroy();
179
180 const rootDir = yield* cloneFixture(fixtureDir, {
181 prefix: "alchemy-nextjs-dev-hmr-",
182 entries: fixtureEntries,
183 });
184 yield* prepareNextjsFixture(rootDir);
185
186 const bindingMarker = "nextjs-hmr-binding-marker";
187
188 const deployed = yield* stack.deploy(
189 Effect.gen(function* () {
190 const site = yield* Cloudflare.Website.Nextjs("NextjsHmrLocal", {
191 rootDir,
192 dev: { mode: "hmr", port: 0 },
193 memo: { include: memoInclude },
194 env: { TEST_TEXT: bindingMarker },
195 });
196 return { site };
197 }),
198 );
199 const site = deployed.site;
200
201 expect(site.url).toMatch(/^http:\/\/localhost:\d+/);
202
203 // The SSR page through the real `next dev` (Turbopack).
204 yield* expectUrlContains(`${site.url!}/`, "NEXTJS_SSR_MARKER", {
205 timeout: "180 seconds",
206 label: "nextjs hmr dev SSR home page",
207 });
208
209 // getCloudflareContext().env binding through the platform proxy.
210 const binding = yield* fetchJsonReady<{ value: string | null }>(
211 `${site.url!}/api/binding`,
212 );
213 expect(binding.value).toBe(bindingMarker);
214
215 // ── HMR: edit the page in place. The stack is NOT re-applied —
216 // Turbopack must recompile and serve the new marker through the
217 // same alchemy proxy ─────────────────────────────────────────────
218 const pagePath = path.join(rootDir, "app", "page.tsx");
219 const page = yield* fs.readFileString(pagePath);
220 yield* fs.writeFileString(
221 pagePath,
222 page.replace("NEXTJS_SSR_MARKER", "NEXTJS_SSR_MARKER_HMR"),
223 );
224 yield* expectUrlContains(`${site.url!}/`, "NEXTJS_SSR_MARKER_HMR", {
225 timeout: "120 seconds",
226 label: "nextjs hmr dev page after edit",
227 });
228
229 // The binding bridge survived the recompile.
230 const still = yield* fetchJsonReady<{ value: string | null }>(`${site.url!}/api/binding`);
231 expect(still.value).toBe(bindingMarker);
232
233 yield* stack.destroy();
234 }).pipe(logLevel),
235 { tags: ["local"], timeout: 420_000 },
236 );
237
238 // ─────────────────────────────────────────────────────────────────────
239 // Alchemy.remote(): the KV namespace opts OUT of local emulation — real
240 // cloud namespace behind the locally-served site.
241 // ─────────────────────────────────────────────────────────────────────
242
243 test.provider(
244 "Nextjs dev: Alchemy.remote() KV namespace runs live behind the dev server",
245 (stack) =>
246 Effect.gen(function* () {
247 yield* stack.destroy();
248
249 const rootDir = yield* cloneFixture(fixtureDir, {
250 prefix: "alchemy-nextjs-dev-remote-",
251 entries: fixtureEntries,
252 });
253 yield* prepareNextjsFixture(rootDir);
254
255 const deployed = yield* stack.deploy(
256 Effect.gen(function* () {
257 const siteKv = yield* Cloudflare.KV.Namespace("NextjsDevRemoteKV").pipe(
258 Alchemy.remote(),
259 );
260 const site = yield* Cloudflare.Website.Nextjs("NextjsRemoteKvLocal", {
261 rootDir,
262 dev: { port: 0 },
263 memo: { include: memoInclude },
264 env: { TEST_TEXT: "nextjs-dev-remote-marker", FIXTURE_KV: siteKv },
265 });
266 return { site, siteKv };
267 }),
268 );
269 const site = deployed.site;
270
271 // Served locally, but the remote() namespace is REAL — a live cloud
272 // id, not a `dev:` fabrication.
273 expect(site.url).toMatch(/^http:\/\/localhost:\d+/);
274 expect(deployed.siteKv.namespaceId).toBeDefined();
275 expect(deployed.siteKv.namespaceId).not.toMatch(/^dev:/);
276
277 // Write through the worker's remote-proxied binding.
278 yield* putKv(site.url!, "remote-key", "remote-value");
279 const got = yield* fetchJsonReady<{ value: string | null }>(
280 `${site.url!}/api/kv?key=remote-key`,
281 );
282 expect(got.value).toBe("remote-value");
283
284 // Out-of-band: the write is visible through the cloud KV API — the
285 // remote-proxied binding really hit the live namespace.
286 const { accountId } = yield* yield* CloudflareEnvironment;
287 const observed = yield* kv
288 .getNamespaceValue({
289 accountId,
290 namespaceId: deployed.siteKv.namespaceId,
291 keyName: "remote-key",
292 })
293 .pipe(
294 Effect.retry({
295 while: (e): boolean => e._tag === "KeyNotFound",
296 schedule: Schedule.min([
297 Schedule.exponential("1 second"),
298 Schedule.spaced("3 seconds"),
299 ]),
300 times: 8,
301 }),
302 Effect.flatMap((res) =>
303 Effect.tryPromise(() =>
304 new Response(Stream.toReadableStream(res.body) as BodyInit).text(),
305 ),
306 ),
307 );
308 expect(observed).toBe("remote-value");
309
310 yield* stack.destroy();
311
312 // The live namespace was deleted from the cloud on destroy (its
313 // state row is stamped live, so the live provider handles the
314 // delete even in a dev run).
315 const gone = yield* kv
316 .getNamespace({ accountId, namespaceId: deployed.siteKv.namespaceId })
317 .pipe(
318 Effect.as(false),
319 Effect.catchTag("NamespaceNotFound", () => Effect.succeed(true)),
320 );
321 expect(gone).toBe(true);
322 }).pipe(logLevel),
323 { tags: ["provider:cloudflare:kv", "live"], timeout: 420_000 },
324 );
325 },
326 );