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

main
ts 389 lines 16.9 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 Effect from "effect/Effect";
6 import * as FileSystem from "effect/FileSystem";
7 import * as HttpClient from "effect/http/HttpClient";
8 import * as HttpClientRequest from "effect/http/HttpClientRequest";
9 import * as Path from "effect/Path";
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 { expectClientChunkContains, expectUrlContains } from "../Utils/Http.ts";
15 import { expectWorkerExists, waitForWorkerToBeDeleted } from "../Utils/Worker.ts";
16 import { buildCommand as nativeBuildCommand } from "./fixtures/nextjs-app/open-next.native.config.ts";
17 import { prepareNextjsFixture } from "./TypeScriptCompat.ts";
18
19 const { test } = Test.make({ providers: Cloudflare.providers() });
20
21 const logLevel = Effect.provideService(MinimumLogLevel, process.env.DEBUG ? "Debug" : "Info");
22
23 const fixtureDir = pathe.resolve(import.meta.dirname, "fixtures", "nextjs-app");
24
25 const nextjsProps = (rootDir: string) => ({
26 rootDir,
27 workersDev: { enabled: true, previewsEnabled: true },
28 memo: {
29 include: [
30 "app/**",
31 "pages/**",
32 "public/**",
33 "package.json",
34 "tsconfig.json",
35 "middleware.ts",
36 "next.config.mjs",
37 ],
38 },
39 });
40
41 const fetchJsonReady = <T>(url: string) =>
42 Effect.gen(function* () {
43 const client = yield* HttpClient.HttpClient;
44 return yield* client.get(url).pipe(
45 Effect.flatMap((res) =>
46 Effect.flatMap(res.text, (body) =>
47 res.status === 200
48 ? Effect.try({
49 try: () => JSON.parse(body) as T,
50 catch: () => new Error(`non-json body: ${body}`),
51 })
52 : Effect.fail(new Error(`Worker not ready (${res.status}): ${body.slice(0, 300)}`)),
53 ),
54 ),
55 // Bounded: ~60s of edge propagation, then fail with the last body.
56 Effect.retry({ schedule: Schedule.spaced("2 seconds"), times: 30 }),
57 );
58 });
59
60 // Tests are independent (per-test scratch stacks, private fixture clones),
61 // so run them concurrently; suites are sequential by default.
62 describe.concurrent(
63 "Nextjs",
64 {
65 tags: [
66 "provider:cloudflare",
67 "provider:cloudflare:kv",
68 "provider:cloudflare:website",
69 "provider:cloudflare:worker",
70 "live",
71 ],
72 },
73 () => {
74 test.provider(
75 "Nextjs: deploys SSR + binding + static assets, serves prerendered ISR, and memoizes unchanged rebuilds",
76 (stack) =>
77 Effect.gen(function* () {
78 const { accountId } = yield* yield* CloudflareEnvironment;
79 const fs = yield* FileSystem.FileSystem;
80 const path = yield* Path.Path;
81
82 yield* stack.destroy();
83
84 // Clone outside the repo so Next does not treat the alchemy
85 // monorepo as the workspace root (that lookup hits typescript 7
86 // / tsgo, which has no `lib/typescript.js`).
87 const rootDir = yield* cloneFixture(fixtureDir, {
88 prefix: "alchemy-nextjs-",
89 entries: [
90 "package.json",
91 "tsconfig.json",
92 "next.config.mjs",
93 "middleware.ts",
94 "app",
95 "pages",
96 "public",
97 ],
98 });
99 yield* prepareNextjsFixture(rootDir);
100 const nextConfigPath = path.join(rootDir, "next.config.mjs");
101 const nextConfig = yield* fs.readFileString(nextConfigPath);
102 expect(yield* fs.exists(path.join(rootDir, "open-next.config.ts"))).toBe(false);
103
104 const bindingMarker = "nextjs-binding-marker";
105
106 const deploy = (buildCommand?: string) =>
107 stack.deploy(
108 Effect.gen(function* () {
109 const kv = yield* Cloudflare.KV.Namespace("NextjsFixtureKv");
110 return yield* Cloudflare.Website.Nextjs("NextjsSite", {
111 ...nextjsProps(rootDir),
112 openNext: buildCommand === undefined ? undefined : { buildCommand },
113 env: {
114 TEST_TEXT: bindingMarker,
115 FIXTURE_KV: kv,
116 NEXT_PUBLIC_SITE_MARKER: "NEXTJS_PUBLIC_ENV_MARKER",
117 },
118 });
119 }),
120 );
121
122 const site1 = yield* deploy();
123 expect(yield* fs.readFileString(nextConfigPath)).toBe(nextConfig);
124 expect(yield* fs.exists(path.join(rootDir, "open-next.config.ts"))).toBe(false);
125
126 expect(site1.url).toBeDefined();
127 expect(site1.hash?.input).toBeDefined();
128 yield* expectWorkerExists(site1.workerName, accountId);
129
130 // Dynamic (force-dynamic) app-router page rendered by the Worker.
131 yield* expectUrlContains(`${site1.url!}/`, "NEXTJS_SSR_MARKER", {
132 timeout: "120 seconds",
133 label: "nextjs SSR home page",
134 });
135
136 // A declared public env value is inlined into the deployed client
137 // bundle at build time.
138 yield* expectClientChunkContains(
139 site1.url!,
140 path.join(rootDir, ".open-next", "assets"),
141 "NEXTJS_PUBLIC_ENV_MARKER",
142 {
143 timeout: "60 seconds",
144 label: "nextjs public env",
145 },
146 );
147
148 // API route handler — the middleware matcher covers /api/*, so the
149 // pass-through header also proves middleware executes on deploy.
150 const client = yield* HttpClient.HttpClient;
151 const helloRes = yield* Test.getWhenReady(`${site1.url!}/api/hello`, { times: 6 });
152 expect(helloRes.status).toBe(200);
153 expect(helloRes.headers["x-fixture-middleware"]).toBe("passed");
154 const hello = (yield* helloRes.json) as { hello: string };
155 expect(hello.hello).toBe("world");
156
157 // Middleware rewrite: /mw-rewrite serves the API route's response.
158 const rewritten = yield* fetchJsonReady<{ hello: string }>(`${site1.url!}/mw-rewrite`);
159 expect(rewritten.hello).toBe("world");
160
161 // Binding read through OpenNext's `getCloudflareContext()`.
162 const binding = yield* fetchJsonReady<{ value: string | null }>(
163 `${site1.url!}/api/binding`,
164 );
165 expect(binding.value).toBe(bindingMarker);
166
167 // KV round-trip through a real resource binding: PUT then GET.
168 const kvKey = `nextjs-live-${site1.hash?.input?.slice(0, 8)}`;
169 const kvValue = `kv-value-${bindingMarker}`;
170 const putRes = yield* Test.executeWhenReady(
171 HttpClientRequest.put(`${site1.url!}/api/kv`).pipe(
172 HttpClientRequest.bodyJsonUnsafe({ key: kvKey, value: kvValue }),
173 ),
174 { times: 6 },
175 );
176 expect(putRes.status).toBe(200);
177 const kvRead = yield* fetchJsonReady<{ value: string | null }>(
178 `${site1.url!}/api/kv?key=${kvKey}`,
179 );
180 expect(kvRead.value).toBe(kvValue);
181
182 // Static asset from `public/`.
183 yield* expectUrlContains(`${site1.url!}/static.txt`, "NEXTJS_STATIC_ASSET_MARKER", {
184 timeout: "60 seconds",
185 label: "nextjs static asset",
186 });
187
188 // ISR page: the prerendered payload serves (read-only static-assets
189 // incremental cache; revalidation writes are a documented no-op).
190 yield* expectUrlContains(`${site1.url!}/isr`, "NEXTJS_ISR_MARKER", {
191 timeout: "60 seconds",
192 label: "nextjs prerendered ISR page",
193 });
194
195 // Dynamic segment prerendered by generateStaticParams (SSG).
196 yield* expectUrlContains(`${site1.url!}/products/alpha`, "product-slug:", {
197 timeout: "60 seconds",
198 label: "nextjs prerendered dynamic segment",
199 });
200 // Non-prerendered slug renders on demand in the Worker.
201 yield* expectUrlContains(`${site1.url!}/products/gamma`, "product-slug:", {
202 timeout: "60 seconds",
203 label: "nextjs on-demand dynamic segment",
204 });
205 // Catch-all dynamic segment.
206 yield* expectUrlContains(
207 `${site1.url!}/docs/guides/deploy/workers`,
208 "DOCS_CATCHALL_MARKER",
209 { timeout: "60 seconds", label: "nextjs catch-all segment" },
210 );
211
212 // Streaming SSR through the real edge: the shell (with the Suspense
213 // fallback) flushes before the slow segment resolves. identity
214 // encoding keeps intermediate proxies from buffering the stream.
215 const streamRes = yield* Test.executeWhenReady(
216 HttpClientRequest.get(`${site1.url!}/streaming`).pipe(
217 HttpClientRequest.setHeader("accept-encoding", "identity"),
218 ),
219 { times: 6 },
220 );
221 expect(streamRes.status).toBe(200);
222 const streamBody = yield* streamRes.text;
223 expect(streamBody).toContain("STREAMING_SUSPENSE_MARKER");
224 expect(streamBody).toContain("STREAMING_RESOLVED_MARKER");
225
226 // Custom not-found boundary: unmatched routes and notFound() calls
227 // both serve the custom 404 content with a 404 status. A colo that
228 // hasn't picked up the deployment yet serves Cloudflare's platform
229 // "Page not found" (also a 404), so retry until the response is the
230 // app's own boundary rather than asserting the first answer.
231 const expectCustom404 = (url: string, label: string) =>
232 client.get(url).pipe(
233 Effect.flatMap((res) =>
234 Effect.flatMap(res.text, (body) =>
235 res.status === 404 && body.includes("CUSTOM_NOT_FOUND_MARKER")
236 ? Effect.void
237 : Effect.fail(
238 new Error(`${label}: status=${res.status}, custom not-found marker absent`),
239 ),
240 ),
241 ),
242 Effect.retry({ schedule: Schedule.spaced("2 seconds"), times: 30 }),
243 );
244 yield* expectCustom404(`${site1.url!}/definitely/not/a/route`, "unmatched route");
245 yield* expectCustom404(`${site1.url!}/gone`, "notFound() page");
246
247 // next.config redirects / rewrites / headers. The fetch-backed
248 // client follows the 308, so assert the redirect lands on the home
249 // page's content — a broken redirect would 404 instead.
250 yield* expectUrlContains(`${site1.url!}/old-home`, "NEXTJS_SSR_MARKER", {
251 timeout: "60 seconds",
252 label: "nextjs next.config redirect (followed to home)",
253 });
254 const rewritten2 = yield* fetchJsonReady<{ hello: string }>(
255 `${site1.url!}/rewritten-hello`,
256 );
257 expect(rewritten2.hello).toBe("world");
258 const headered = yield* Test.getWhenReady(`${site1.url!}/api/hello`, { times: 6 });
259 expect(headered.headers["x-fixture-config-header"]).toBe("from-next-config");
260
261 // next/image (unoptimized): the page renders the img and the raw
262 // asset serves through the ASSETS binding. Real optimization needs
263 // a zone with Cloudflare Images — documented on the resource.
264 yield* expectUrlContains(`${site1.url!}/image`, "IMAGE_PAGE_MARKER", {
265 timeout: "60 seconds",
266 label: "nextjs next/image page",
267 });
268 const pixel = yield* Test.getWhenReady(`${site1.url!}/pixel.png`, { times: 6 });
269 expect(pixel.status).toBe(200);
270 expect(pixel.headers["content-type"]).toContain("image/png");
271
272 // Pages Router page (getServerSideProps) + API route, coexisting
273 // with the App Router.
274 yield* expectUrlContains(`${site1.url!}/legacy`, "PAGES_ROUTER_MARKER", {
275 timeout: "60 seconds",
276 label: "nextjs pages-router page",
277 });
278 const legacy = yield* fetchJsonReady<{ legacy: string }>(`${site1.url!}/api/legacy`);
279 expect(legacy.legacy).toBe("pages-api");
280
281 // ── deploy 2: no changes ⇒ the rebuild-free input hash matches and
282 // the deploy short-circuits without rebuilding ───────────────────────
283 const site2 = yield* deploy();
284
285 expect(site2.hash?.input).toBeDefined();
286 expect(site2.hash?.input).toEqual(site1.hash?.input);
287 expect(site2.url).toBe(site1.url);
288
289 // ── deploy 3: edit the SSR page ⇒ the input hash changes and the
290 // new content deploys ────────────────────────────────────────────────
291 const pagePath = path.join(rootDir, "app/page.tsx");
292 const page = yield* fs.readFileString(pagePath);
293 yield* fs.writeFileString(
294 pagePath,
295 page.replace("NEXTJS_SSR_MARKER", "NEXTJS_SSR_MARKER_V2"),
296 );
297
298 const site3 = yield* deploy();
299
300 expect(site3.hash?.input).toBeDefined();
301 expect(site3.hash?.input).not.toEqual(site1.hash?.input);
302 yield* expectUrlContains(`${site3.url!}/`, "NEXTJS_SSR_MARKER_V2", {
303 timeout: "120 seconds",
304 label: "nextjs SSR page after edit",
305 });
306
307 const configRoute = () =>
308 client.get(`${site1.url!}/api/config`).pipe(
309 Effect.flatMap((response) =>
310 response.text.pipe(Effect.as(response.headers["x-config-priority"])),
311 ),
312 Effect.repeat({
313 schedule: Schedule.spaced("1 second"),
314 times: 30,
315 until: (priority) => priority === "handler",
316 }),
317 );
318 const nativeConfigPath = path.join(rootDir, "open-next.config.ts");
319 const nativeConfig = yield* fs.readFileString(
320 path.join(fixtureDir, "open-next.native.config.ts"),
321 );
322 const nativeApp = path.join(rootDir, "native-output");
323 yield* fs.makeDirectory(nativeApp, { recursive: true });
324 for (const entry of [
325 "package.json",
326 "tsconfig.json",
327 "next.config.mjs",
328 "middleware.ts",
329 "app",
330 "pages",
331 "public",
332 ]) {
333 yield* fs.copy(path.join(rootDir, entry), path.join(nativeApp, entry));
334 }
335 yield* fs.writeFileString(nativeConfigPath, nativeConfig);
336 const site4 = yield* deploy();
337 expect(site4.hash?.input).not.toEqual(site3.hash?.input);
338 expect(yield* fs.readFileString(nativeConfigPath)).toBe(nativeConfig);
339 expect(yield* fs.readFileString(path.join(rootDir, "native-build-marker"))).toBe(
340 "native",
341 );
342 expect(
343 yield* fs.exists(path.join(rootDir, "native-output", ".open-next", "worker.js")),
344 ).toBe(true);
345 expect(yield* configRoute()).toBe("handler");
346 yield* expectUrlContains(`${site4.url!}/`, "NEXTJS_SSR_MARKER_V2");
347 yield* expectUrlContains(`${site4.url!}/static.txt`, "NEXTJS_STATIC_ASSET_MARKER");
348 expect((yield* deploy()).hash?.input).toEqual(site4.hash?.input);
349
350 const editedConfig = nativeConfig.replace('["/api/config"]', '["/other"]');
351 yield* fs.writeFileString(nativeConfigPath, editedConfig);
352 const site5 = yield* deploy();
353 expect(site5.hash?.input).not.toEqual(site4.hash?.input);
354 expect(yield* fs.readFileString(nativeConfigPath)).toBe(editedConfig);
355 expect(yield* fs.readFileString(path.join(rootDir, "native-build-marker"))).toBe(
356 "native",
357 );
358 const middlewarePriority = yield* client.get(`${site5.url!}/api/config`).pipe(
359 Effect.flatMap((response) =>
360 response.text.pipe(Effect.as(response.headers["x-config-priority"])),
361 ),
362 Effect.repeat({
363 schedule: Schedule.spaced("1 second"),
364 times: 30,
365 until: (priority) => priority === "middleware",
366 }),
367 );
368 expect(middlewarePriority).toBe("middleware");
369
370 const overrideSite = yield* deploy(nativeBuildCommand.replace("'native'", "'resource'"));
371 expect(overrideSite.hash?.input).not.toEqual(site5.hash?.input);
372 expect(yield* fs.readFileString(path.join(rootDir, "native-build-marker"))).toBe(
373 "resource",
374 );
375 expect(yield* fs.readFileString(nativeConfigPath)).toBe(editedConfig);
376
377 yield* fs.remove(nativeConfigPath);
378 const site6 = yield* deploy();
379 expect(site6.hash?.input).toEqual(site3.hash?.input);
380 expect(yield* fs.exists(nativeConfigPath)).toBe(false);
381 yield* expectUrlContains(`${site6.url!}/`, "NEXTJS_SSR_MARKER_V2");
382
383 yield* stack.destroy();
384 yield* waitForWorkerToBeDeleted(site1.workerName, accountId);
385 }).pipe(logLevel),
386 { timeout: 600_000 },
387 );
388 },
389 );