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

main
ts 701 lines 30 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 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, expectUrlRedirect } 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", "sveltekit-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 const tempRoot = pathe.resolve(import.meta.dirname, "../../../.tmp");
29
30 const svelteKitProps = (rootDir: string) => ({
31 rootDir,
32 workersDev: { enabled: true, previewsEnabled: true },
33 memo: { include: ["src/**", "static/**", "package.json"] },
34 });
35
36 // Concurrent like the other Website suites: the SvelteKit source build
37 // runs in a child process with cwd = project root (core/BuildChild.ts),
38 // so nothing here mutates process-global state.
39 describe.concurrent(
40 "SvelteKit",
41 {
42 tags: [
43 "provider:cloudflare",
44 "provider:cloudflare:website",
45 "provider:cloudflare:worker",
46 "live",
47 ],
48 },
49 () => {
50 test.provider(
51 "SvelteKit: deploys SSR + bindings + static assets and memoizes unchanged rebuilds",
52 (stack) =>
53 Effect.gen(function* () {
54 const { accountId } = yield* yield* CloudflareEnvironment;
55
56 yield* stack.destroy();
57
58 const rootDir = yield* cloneFixture(fixtureDir, {
59 prefix: "alchemy-sveltekit-",
60 tempRoot,
61 entries: ["package.json", "src", "static"],
62 });
63
64 const bindingMarker = "sveltekit-binding-marker";
65
66 const deploy = () =>
67 stack.deploy(
68 Effect.gen(function* () {
69 // A REAL KV namespace bound into `platform.env.SITE_KV` — the
70 // /api/kv routes round-trip it server-side.
71 const siteKv = yield* Cloudflare.KV.Namespace("SiteKV");
72 const site = yield* Cloudflare.Website.SvelteKit("SvelteKitSite", {
73 ...svelteKitProps(rootDir),
74 env: {
75 TEST_BINDING: bindingMarker,
76 SITE_KV: siteKv,
77 VITE_SITE_MARKER: "SVELTEKIT_PUBLIC_ENV_MARKER",
78 },
79 });
80 return { site, siteKv };
81 }),
82 );
83
84 const { site: site1, siteKv } = yield* deploy();
85
86 expect(site1.url).toBeDefined();
87 expect(site1.hash?.input).toBeDefined();
88 yield* expectWorkerExists(site1.workerName, accountId);
89
90 // SSR route: the server `load` reads `platform.env.TEST_BINDING`.
91 yield* expectUrlContains(`${site1.url!}/`, `binding:${bindingMarker}`, {
92 timeout: "120 seconds",
93 label: "SSR home with platform.env binding",
94 });
95
96 // A declared public env value is inlined into the deployed client
97 // bundle at build time.
98 yield* expectClientChunkContains(
99 site1.url!,
100 pathe.join(rootDir, ".svelte-kit", "cloudflare"),
101 "SVELTEKIT_PUBLIC_ENV_MARKER",
102 {
103 timeout: "60 seconds",
104 label: "sveltekit public env",
105 },
106 );
107
108 // API endpoint: node:crypto under nodejs_compat + platform.env.
109 const hello = yield* fetchJsonReady<{ uuid: string; binding: string }>(
110 `${site1.url!}/api/hello`,
111 );
112 expect(hello.binding).toBe(bindingMarker);
113 expect(hello.uuid).toMatch(/^[0-9a-f-]{36}$/);
114
115 // Static asset from `static/`.
116 yield* expectUrlContains(`${site1.url!}/robots.txt`, "User-agent", {
117 timeout: "60 seconds",
118 label: "static asset",
119 });
120 // The same file read by a server route through the `ASSETS` binding.
121 yield* expectUrlContains(`${site1.url!}/api/asset`, "User-agent", {
122 timeout: "60 seconds",
123 label: "sveltekit ASSETS binding",
124 });
125
126 // Prerendered page served from assets.
127 yield* expectUrlContains(`${site1.url!}/prerendered`, "this-page-is-prerendered", {
128 timeout: "60 seconds",
129 label: "prerendered page",
130 });
131
132 // ── form action: the first non-GET against an alchemy-deployed
133 // framework worker. The urlencoded POST must route through the asset
134 // layer to the worker, run the `greet` action server-side, and
135 // observe `platform.env` ─────────────────────────────────────────────
136 const formBody = yield* postFormReady(
137 `${site1.url!}/form?/greet`,
138 new URL(site1.url!).origin,
139 { name: "alchemy" },
140 );
141 expect(formBody).toContain("result:hello alchemy");
142 expect(formBody).toContain(`form-binding:${bindingMarker}`);
143
144 // ── real KV binding: PUT writes through `platform.env.SITE_KV`,
145 // GET reads it back, and the cloud API sees the same value ──────────
146 expect(siteKv.namespaceId).toBeDefined();
147 const kvKey = "greeting";
148 const kvValue = `sveltekit-kv-${bindingMarker}`;
149 yield* putTextReady(`${site1.url!}/api/kv?key=${kvKey}`, kvValue);
150 const kvRead = yield* fetchJsonReady<{ value: string | null }>(
151 `${site1.url!}/api/kv?key=${kvKey}`,
152 ).pipe(
153 Effect.filterOrFail(
154 (r) => r.value === kvValue,
155 (r) => new Error(`kv value not visible yet: ${JSON.stringify(r)}`),
156 ),
157 Effect.retry({ schedule: Schedule.exponential("1 second", 1.5), times: 8 }),
158 );
159 expect(kvRead.value).toBe(kvValue);
160
161 // Out-of-band: the worker's write landed in the REAL namespace.
162 const cloudValue = yield* kv
163 .getNamespaceValue({ accountId, namespaceId: siteKv.namespaceId, keyName: kvKey })
164 .pipe(
165 Effect.flatMap((res) =>
166 Effect.tryPromise(() =>
167 new Response(Stream.toReadableStream(res.body) as BodyInit).text(),
168 ),
169 ),
170 Effect.retry({ schedule: Schedule.exponential("1 second", 1.5), times: 5 }),
171 );
172 expect(cloudValue).toBe(kvValue);
173
174 // ── deploy 2: no changes ⇒ the rebuild-free input hash matches and
175 // the deploy short-circuits without building ─────────────────────────
176 const { site: site2 } = yield* deploy();
177
178 expect(site2.hash?.input).toBeDefined();
179 expect(site2.hash?.input).toEqual(site1.hash?.input);
180 expect(site2.url).toBe(site1.url);
181
182 // ── deploy 3: edit a route ⇒ the input hash busts and the rebuilt
183 // page serves the new content ────────────────────────────────────────
184 const fs = yield* FileSystem.FileSystem;
185 const path = yield* Path.Path;
186 const pagePath = path.join(rootDir, "src", "routes", "+page.svelte");
187 const editedMarker = "sveltekit-edited-marker";
188 const page = yield* fs.readFileString(pagePath);
189 yield* fs.writeFileString(
190 pagePath,
191 page.replace("SvelteKit SSR home", `SvelteKit SSR home ${editedMarker}`),
192 );
193
194 const { site: site3 } = yield* deploy();
195
196 expect(site3.hash?.input).toBeDefined();
197 expect(site3.hash?.input).not.toEqual(site1.hash?.input);
198 yield* expectUrlContains(`${site3.url!}/`, editedMarker, {
199 timeout: "120 seconds",
200 label: "edited SSR home page",
201 });
202
203 yield* stack.destroy();
204 yield* waitForWorkerToBeDeleted(site1.workerName, accountId);
205 // Destroy must also delete the bound KV namespace from the cloud.
206 yield* waitForNamespaceToBeDeleted(siteKv.namespaceId, accountId);
207 }).pipe(logLevel),
208 { tags: ["provider:cloudflare:kv"], timeout: 360_000 },
209 );
210
211 // ─────────────────────────────────────────────────────────────────────
212 // SPA mode: `assets.notFoundHandling: "single-page-application"`
213 //
214 // Pages are `ssr = false`, so deep links and unknown routes must serve
215 // the generated app-shell `index.html` (identified by the fixture's
216 // shell marker), while `+server.ts` endpoints still execute server-side
217 // in the worker with access to `platform.env`.
218 // ─────────────────────────────────────────────────────────────────────
219
220 const spaFixtureDir = pathe.resolve(import.meta.dirname, "fixtures", "sveltekit-spa-app");
221
222 const SPA_SHELL_MARKER = "sveltekit-spa-shell";
223
224 test.provider(
225 "SvelteKit SPA: deep links and unknown routes serve the app shell; server endpoints still run in the worker",
226 (stack) =>
227 Effect.gen(function* () {
228 const { accountId } = yield* yield* CloudflareEnvironment;
229
230 yield* stack.destroy();
231
232 const rootDir = yield* cloneFixture(spaFixtureDir, {
233 prefix: "alchemy-sveltekit-spa-",
234 tempRoot,
235 entries: ["package.json", "src"],
236 });
237
238 const bindingMarker = "sveltekit-spa-binding-marker";
239
240 const site = yield* stack.deploy(
241 Effect.gen(function* () {
242 return yield* Cloudflare.Website.SvelteKit("SvelteKitSpaSite", {
243 rootDir,
244 workersDev: { enabled: true, previewsEnabled: true },
245 memo: { include: ["src/**", "package.json"] },
246 // The single platform-native knob: `assets.notFoundHandling`
247 // drives both the build-time app-shell fallback generation
248 // and the assets layer that serves it. This deploy pins that
249 // coupling — without it, unknown routes 404 with an empty
250 // body.
251 assets: { notFoundHandling: "single-page-application" },
252 env: { TEST_BINDING: bindingMarker },
253 });
254 }),
255 );
256
257 expect(site.url).toBeDefined();
258 // SPA mode still ships a worker: the kit server bundle serves the
259 // `+server.ts` endpoints.
260 expect(site.hash?.bundle).toBeDefined();
261 yield* expectWorkerExists(site.workerName, accountId);
262
263 // (a) A deep link to a CLIENT route serves the app shell — the
264 // shell marker is present and the widget markup (which only ever
265 // renders in the browser) is absent.
266 const widgetsBody = yield* expectSpaShell(`${site.url!}/widgets`);
267 expect(widgetsBody).toContain(SPA_SHELL_MARKER);
268 expect(widgetsBody).not.toContain("sveltekit-spa-widgets");
269 expect(widgetsBody).not.toContain("sprocket");
270
271 // (b) A route that doesn't exist at all serves the shell too — the
272 // client router owns 404 handling in SPA mode.
273 const unknownBody = yield* expectSpaShell(`${site.url!}/definitely/not/a/route`);
274 expect(unknownBody).toContain(SPA_SHELL_MARKER);
275
276 // (c) The server endpoint executes in the worker with the binding.
277 const widgets = yield* fetchJsonReady<{
278 server: boolean;
279 message: string | null;
280 widgets: Array<{ id: string; name: string }>;
281 }>(`${site.url!}/api/widgets`);
282 expect(widgets.server).toBe(true);
283 expect(widgets.message).toBe(bindingMarker);
284 expect(widgets.widgets.map((w) => w.name)).toEqual(["sprocket", "flange", "grommet"]);
285
286 yield* stack.destroy();
287 yield* waitForWorkerToBeDeleted(site.workerName, accountId);
288 }).pipe(logLevel),
289 { timeout: 360_000 },
290 );
291
292 // ─────────────────────────────────────────────────────────────────────
293 // 404-page mode: `assets.notFoundHandling: "404-page"`
294 //
295 // The build writes a `404.html` fallback asset that always renders the
296 // app shell (so kit's own error page shows), driven by the same
297 // platform-native knob that configures the assets layer serving it.
298 //
299 // Assets `404-page` semantics with a worker present: under the
300 // `assets_navigation_prefers_asset_serving` compat flag (default-on for
301 // compatibility dates >= 2025-04-01; the resource's default date is
302 // later), a navigation-shaped request (`Sec-Fetch-Mode: navigate`) that
303 // matches no asset is answered by the assets layer directly with the
304 // `404.html` body and status 404 — the worker is never invoked. Requests
305 // WITHOUT the navigate header still invoke the worker, where kit renders
306 // its own error page (the shim never defers in 404-page mode —
307 // upstream-parity, see WorkerShim.ts).
308 //
309 // ─────────────────────────────────────────────────────────────────────
310
311 const notFoundFixtureDir = pathe.resolve(import.meta.dirname, "fixtures", "sveltekit-404-app");
312
313 /** app.html marker — present in every response rendered through app.html. */
314 const SHELL_404_MARKER = "sveltekit-404-shell";
315 /** Root `+error.svelte` marker — present only when KIT renders the 404. */
316 const KIT_ERROR_MARKER = "sveltekit-404-kit-error-page";
317 /** Root page marker — present only when the home page renders. */
318 const HOME_404_MARKER = "sveltekit-404-home";
319
320 test.provider(
321 "SvelteKit 404-page + spa fallback: unmatched navigations serve the app-shell 404.html from assets; matched routes SSR; non-navigations keep kit's own 404",
322 (stack) =>
323 Effect.gen(function* () {
324 const { accountId } = yield* yield* CloudflareEnvironment;
325
326 yield* stack.destroy();
327
328 const rootDir = yield* cloneFixture(notFoundFixtureDir, {
329 prefix: "alchemy-sveltekit-404-spa-",
330 tempRoot,
331 entries: ["package.json", "src"],
332 });
333
334 const bindingMarker = "sveltekit-404-spa-binding-marker";
335
336 const site = yield* stack.deploy(
337 Effect.gen(function* () {
338 return yield* Cloudflare.Website.SvelteKit("SvelteKit404SpaSite", {
339 rootDir,
340 workersDev: { enabled: true, previewsEnabled: true },
341 memo: { include: ["src/**", "package.json"] },
342 // `404-page` writes `404.html` — the generated page always
343 // renders the app shell now, so kit's own error page shows
344 // on unmatched navigations.
345 assets: { notFoundHandling: "404-page" },
346 env: { TEST_BINDING: bindingMarker },
347 });
348 }),
349 );
350
351 expect(site.url).toBeDefined();
352 expect(site.hash?.bundle).toBeDefined();
353 yield* expectWorkerExists(site.workerName, accountId);
354
355 // (a) Matched route SSRs normally: a plain (non-navigation) fetch
356 // reaches the worker and the server `load` observes platform.env.
357 const homeBody = yield* expectUrlContains(`${site.url!}/`, `binding:${bindingMarker}`, {
358 timeout: "120 seconds",
359 label: "404-page spa: SSR home",
360 });
361 expect(homeBody).toContain(HOME_404_MARKER);
362
363 // (b) An unmatched route on a navigation-shaped request serves the
364 // generated app-shell 404.html from the assets layer with status
365 // 404 — no kit error-page markup (the worker never ran) and no
366 // page markup (the shell render has no page components).
367 const fallbackBody = yield* expectPageResponse(`${site.url!}/definitely/not/a/route`, {
368 label: "404-page spa: assets fallback (navigate)",
369 headers: { accept: "text/html", "sec-fetch-mode": "navigate" },
370 expected: `status 404 with app-shell marker "${SHELL_404_MARKER}" and no "${KIT_ERROR_MARKER}"`,
371 check: (res) =>
372 res.status === 404 &&
373 res.body.includes(SHELL_404_MARKER) &&
374 !res.body.includes(KIT_ERROR_MARKER),
375 });
376 expect(fallbackBody).not.toContain(HOME_404_MARKER);
377
378 // (c) The same unmatched route WITHOUT `Sec-Fetch-Mode: navigate`
379 // invokes the worker, and kit renders its own error page — the
380 // shim never defers in 404-page mode (upstream parity).
381 const kitErrorBody = yield* expectPageResponse(`${site.url!}/definitely/not/a/route`, {
382 label: "404-page spa: worker-rendered 404 (non-navigation)",
383 headers: { accept: "text/html" },
384 expected: `status 404 with kit error marker "${KIT_ERROR_MARKER}"`,
385 check: (res) => res.status === 404 && res.body.includes(KIT_ERROR_MARKER),
386 });
387 expect(kitErrorBody).toContain("status:404");
388
389 yield* stack.destroy();
390 yield* waitForWorkerToBeDeleted(site.workerName, accountId);
391 }).pipe(logLevel),
392 { timeout: 360_000 },
393 );
394
395 // ─────────────────────────────────────────────────────────────────────
396 // Fully-prerendered SvelteKit (the `adapter-static` equivalent):
397 // `export const prerender = true` in the root +layout renders every
398 // page to HTML at build time and deploys them as static assets.
399 // ─────────────────────────────────────────────────────────────────────
400
401 const staticFixtureDir = pathe.resolve(import.meta.dirname, "fixtures", "sveltekit-static-app");
402
403 test.provider(
404 "SvelteKit fully-prerendered: pages serve as static assets; the server bundle is still uploaded as a worker (behavior pin)",
405 (stack) =>
406 Effect.gen(function* () {
407 const { accountId } = yield* yield* CloudflareEnvironment;
408
409 yield* stack.destroy();
410
411 const rootDir = yield* cloneFixture(staticFixtureDir, {
412 prefix: "alchemy-sveltekit-static-",
413 tempRoot,
414 entries: ["package.json", "src"],
415 });
416
417 const site = yield* stack.deploy(
418 Effect.gen(function* () {
419 return yield* Cloudflare.Website.SvelteKit("SvelteKitStaticSite", {
420 rootDir,
421 workersDev: { enabled: true, previewsEnabled: true },
422 memo: { include: ["src/**", "package.json"] },
423 });
424 }),
425 );
426
427 expect(site.url).toBeDefined();
428
429 // ── BEHAVIOR PIN ─────────────────────────────────────────────────
430 // Even with every route prerendered, the resource TODAY still
431 // builds the kit server bundle and uploads it as a worker (the
432 // adapter always emits `_worker.js`; there is no assets-only fast
433 // path for fully-static builds). If these assertions start failing
434 // because the resource learned to skip the worker for fully-
435 // prerendered apps, update this pin to the new behavior.
436 expect(site.hash?.bundle).toBeDefined();
437 yield* expectWorkerExists(site.workerName, accountId);
438
439 // Every page serves its prerendered content.
440 yield* expectUrlContains(`${site.url!}/`, "sveltekit-static-home", {
441 timeout: "120 seconds",
442 label: "prerendered home",
443 });
444 yield* expectUrlContains(`${site.url!}/about`, "sveltekit-static-about", {
445 timeout: "60 seconds",
446 label: "prerendered about",
447 });
448 yield* expectUrlContains(`${site.url!}/docs`, "sveltekit-static-docs", {
449 timeout: "60 seconds",
450 label: "prerendered docs",
451 });
452
453 // Proof the pages come from the ASSETS layer, not a kit render:
454 // the assets router's `auto-trailing-slash` html_handling answers
455 // `/about/` with a 307 redirect to `/about`. Both kit's server
456 // (trailingSlash "never") and the worker shim's prerendered
457 // redirect use 308 — a 307 here fingerprints the assets layer.
458 yield* expectUrlRedirect(`${site.url!}/about/`, "/about", {
459 status: 307,
460 timeout: "60 seconds",
461 label: "assets-layer trailing-slash redirect",
462 });
463
464 yield* stack.destroy();
465 yield* waitForWorkerToBeDeleted(site.workerName, accountId);
466 }).pipe(logLevel),
467 { timeout: 360_000 },
468 );
469
470 class NamespaceStillExists extends Data.TaggedError("NamespaceStillExists") {}
471
472 const waitForNamespaceToBeDeleted = Effect.fn(function* (
473 namespaceId: string,
474 accountId: string,
475 ) {
476 yield* kv.getNamespace({ accountId, namespaceId }).pipe(
477 Effect.flatMap(() => Effect.fail(new NamespaceStillExists())),
478 Effect.retry({
479 while: (e): e is NamespaceStillExists => e instanceof NamespaceStillExists,
480 schedule: Schedule.min([Schedule.exponential(250), Schedule.spaced("2 seconds")]),
481 times: 10,
482 }),
483 Effect.catchTag("NamespaceNotFound", () => Effect.void),
484 );
485 });
486
487 class PageResponseMismatch extends Data.TaggedError("PageResponseMismatch")<{
488 url: string;
489 expected: string;
490 actual: string;
491 }> {
492 override get message() {
493 return `${this.url} :: expected ${this.expected} :: got ${this.actual}`;
494 }
495 }
496
497 interface PageResponse {
498 status: number;
499 body: string;
500 headers: Headers;
501 }
502
503 /**
504 * Fetch `url` (with optional extra request headers — e.g.
505 * `sec-fetch-mode: navigate` to exercise the assets layer's
506 * navigation-preference behavior) and assert `check` holds for the
507 * response. Retries through edge propagation with the same bounded
508 * schedule as `expectSpaShell`; returns the body for further (negative)
509 * assertions.
510 */
511 const expectPageResponse = (
512 url: string,
513 options: {
514 label: string;
515 headers?: Record<string, string>;
516 /** Human description of the expected response, for error messages. */
517 expected: string;
518 check: (res: PageResponse) => boolean;
519 },
520 ) =>
521 Effect.tryPromise({
522 try: async (signal) => {
523 const u = new URL(url);
524 u.searchParams.set("__alchemy_cb", String(Date.now()));
525 const res = await fetch(u, {
526 signal,
527 cache: "no-store",
528 headers: { "cache-control": "no-cache", accept: "*/*", ...options.headers },
529 });
530 const body = await res.text();
531 return { status: res.status, body, headers: res.headers };
532 },
533 catch: (e) =>
534 new PageResponseMismatch({
535 url,
536 expected: options.expected,
537 actual: e instanceof Error ? e.message : String(e),
538 }),
539 }).pipe(
540 Effect.filterOrFail(
541 (res): boolean => options.check(res),
542 (res) =>
543 new PageResponseMismatch({
544 url,
545 expected: options.expected,
546 actual: `${res.status} ${res.body.slice(0, 240)}`,
547 }),
548 ),
549 Effect.map((res) => res.body),
550 Effect.retry({
551 // Same ~127s budget as `expectSpaShell` (matches the 120s
552 // first-request convention used by `expectUrlContains`).
553 schedule: Schedule.max([
554 Schedule.min([Schedule.exponential("750 millis", 1.5), Schedule.spaced("8 seconds")]),
555 Schedule.recurs(20),
556 ]),
557 }),
558 Effect.tapError((error) =>
559 Effect.logError(`expectPageResponse(${options.label}) failed`, error),
560 ),
561 );
562
563 class SpaShellMismatch extends Data.TaggedError("SpaShellMismatch")<{
564 url: string;
565 actual: string;
566 }> {
567 override get message() {
568 return `${this.url} :: ${this.actual}`;
569 }
570 }
571
572 /**
573 * Assert `url` answers 200 with the SPA app-shell body (contains the
574 * fixture's shell marker). Retries through edge propagation with a
575 * bounded schedule; returns the body for further (negative) assertions.
576 */
577 const expectSpaShell = (url: string) =>
578 Effect.tryPromise({
579 try: async (signal) => {
580 const u = new URL(url);
581 u.searchParams.set("__alchemy_cb", String(Date.now()));
582 const res = await fetch(u, {
583 signal,
584 cache: "no-store",
585 headers: { "cache-control": "no-cache", accept: "text/html" },
586 });
587 const body = await res.text();
588 return { status: res.status, body };
589 },
590 catch: (e) =>
591 new SpaShellMismatch({ url, actual: e instanceof Error ? e.message : String(e) }),
592 }).pipe(
593 Effect.filterOrFail(
594 (res) => res.status === 200 && res.body.includes(SPA_SHELL_MARKER),
595 (res) => new SpaShellMismatch({ url, actual: `${res.status} ${res.body.slice(0, 240)}` }),
596 ),
597 Effect.map((res) => res.body),
598 Effect.retry({
599 // ~127s budget — matches the 120s first-request convention used by
600 // `expectUrlContains`: a fully concurrent suite creates dozens of
601 // fresh workers.dev subdomains at once and propagation slows down.
602 schedule: Schedule.max([
603 Schedule.min([Schedule.exponential("750 millis", 1.5), Schedule.spaced("8 seconds")]),
604 Schedule.recurs(20),
605 ]),
606 }),
607 );
608
609 /**
610 * POST an urlencoded form to a kit action URL (`/route?/action`) with an
611 * `origin` header matching the site (kit's CSRF check) and
612 * `accept: text/html` so the action result is server-rendered into the
613 * page. Retries until the route serves 200.
614 */
615 const postFormReady = (url: string, origin: string, form: Record<string, string>) =>
616 Effect.gen(function* () {
617 const client = yield* HttpClient.HttpClient;
618 return yield* client
619 .execute(
620 HttpClientRequest.post(url).pipe(
621 HttpClientRequest.setHeaders({ origin, accept: "text/html" }),
622 HttpClientRequest.bodyText(
623 new URLSearchParams(form).toString(),
624 "application/x-www-form-urlencoded",
625 ),
626 ),
627 )
628 .pipe(
629 Effect.flatMap((res) =>
630 res.status === 200
631 ? res.text
632 : Effect.fail(new Error(`form action not ready: ${res.status}`)),
633 ),
634 Effect.retry({
635 schedule: Schedule.min([
636 Schedule.exponential("500 millis"),
637 Schedule.spaced("4 seconds"),
638 ]),
639 times: 15,
640 }),
641 );
642 });
643
644 /**
645 * PUT a text body to `url`, retrying until the route serves 200. Kit's
646 * CSRF protection 403s form-like content types (`text/plain` included)
647 * on non-GET requests unless the `origin` header matches the site, so
648 * the site origin is sent explicitly.
649 */
650 const putTextReady = (url: string, body: string) =>
651 Effect.gen(function* () {
652 const client = yield* HttpClient.HttpClient;
653 yield* client
654 .execute(
655 HttpClientRequest.put(url).pipe(
656 HttpClientRequest.setHeaders({ origin: new URL(url).origin }),
657 HttpClientRequest.bodyText(body, "text/plain"),
658 ),
659 )
660 .pipe(
661 Effect.flatMap((res) =>
662 res.status === 200
663 ? Effect.void
664 : Effect.fail(new Error(`PUT not ready: ${res.status}`)),
665 ),
666 Effect.retry({
667 schedule: Schedule.min([
668 Schedule.exponential("500 millis"),
669 Schedule.spaced("4 seconds"),
670 ]),
671 times: 15,
672 }),
673 );
674 });
675
676 const fetchJsonReady = <T>(url: string) =>
677 Effect.gen(function* () {
678 const client = yield* HttpClient.HttpClient;
679 return yield* client.get(url).pipe(
680 Effect.flatMap((res) =>
681 res.status === 200
682 ? Effect.flatMap(res.text, (body) =>
683 Effect.try({
684 try: () => JSON.parse(body) as T,
685 catch: () => new Error(`non-json body: ${body}`),
686 }),
687 )
688 : Effect.fail(new Error(`Worker not ready: ${res.status}`)),
689 ),
690 Effect.retry({
691 // Capped interval, ~90s total budget (workers.dev / DO propagation).
692 schedule: Schedule.min([
693 Schedule.exponential("500 millis"),
694 Schedule.spaced("2 seconds"),
695 ]),
696 times: 45,
697 }),
698 );
699 });
700 },
701 );