@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 1,651 lines 67.6 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 { assert, describe, expect } from "@alchemy.run/test";
5 import * as Test from "@alchemy.run/test/Alchemy";
6 import * as r2 from "@distilled.cloud/cloudflare/r2";
7 import { initialCwd } from "alchemy/Util/Node";
8 import * as Cause from "effect/Cause";
9 import * as Data from "effect/Data";
10 import * as Effect from "effect/Effect";
11 import * as Exit from "effect/Exit";
12 import * as FileSystem from "effect/FileSystem";
13 import * as HttpClient from "effect/http/HttpClient";
14 import * as HttpClientRequest from "effect/http/HttpClientRequest";
15 import * as Path from "effect/Path";
16 import { MinimumLogLevel } from "effect/References";
17 import * as Schedule from "effect/Schedule";
18 import * as pathe from "pathe";
19 import { cloneFixture } from "../Utils/Fixture.ts";
20 import { expectUrlContains, expectUrlHeader } from "../Utils/Http.ts";
21 import { expectWorkerExists, waitForWorkerToBeDeleted } from "../Utils/Worker.ts";
22 import type { Counter as ViteDoCounter } from "./vite-do-fixture/src/worker.ts";
23
24 const { test } = Test.make({ providers: Cloudflare.providers() });
25 const { test: devTest } = Test.make({ providers: Cloudflare.providers(), dev: true });
26
27 const logLevel = Effect.provideService(MinimumLogLevel, process.env.DEBUG ? "Debug" : "Info");
28
29 const fixtureDir = pathe.resolve(import.meta.dirname, "vite-fixture");
30 const spaFixtureDir = pathe.resolve(import.meta.dirname, "vite-spa-fixture");
31 const assetsFixtureDir = pathe.resolve(import.meta.dirname, "vite-assets-fixture");
32 const foldkitFixtureDir = pathe.resolve(import.meta.dirname, "foldkit-fixture");
33 const doFixtureDir = pathe.resolve(import.meta.dirname, "vite-do-fixture");
34 const containerFixtureDir = pathe.resolve(import.meta.dirname, "vite-container-fixture");
35 const workerFirstFixtureDir = pathe.resolve(import.meta.dirname, "worker-first-fixture");
36 const reactRouterRscFixtureDir = pathe.resolve(import.meta.dirname, "react-router-rsc-fixture");
37 const tanstackDevBindingsFixtureDir = pathe.resolve(
38 import.meta.dirname,
39 "tanstack-dev-bindings-fixture",
40 );
41 const viteChildFixtureDir = pathe.resolve(import.meta.dirname, "vite-child-fixture");
42 const buildErrorFixtureDir = pathe.resolve(import.meta.dirname, "vite-build-error-fixture");
43
44 // Vite/Rollup's `vite:build-html` plugin chokes when the project root
45 // is outside the current working directory because it tries to express
46 // the emitted asset path relative to `cwd`. To keep the temp clone
47 // reachable via a sane relative path, allocate the temp dir *inside*
48 // the alchemy package's `.tmp/` so it sits under the same workspace
49 // root as `cwd`.
50 const tempRoot = pathe.resolve(import.meta.dirname, "../../../.tmp");
51
52 // Suites are sequential by default; every test here deploys its own
53 // scratch stack with its own worker names and fixture clone, so they are
54 // independent and can run concurrently. Builds run in per-project child
55 // processes (`runViteBuildChild`), so concurrent builds can't race each
56 // other's working directory.
57 describe.concurrent(
58 "Vite",
59 { tags: ["provider:cloudflare", "provider:cloudflare:website"] },
60 () => {
61 test.provider(
62 "Vite: editing a source file republishes the assets in a single deploy",
63 (stack) =>
64 Effect.gen(function* () {
65 const { accountId } = yield* yield* CloudflareEnvironment;
66 const fs = yield* FileSystem.FileSystem;
67 const path = yield* Path.Path;
68
69 yield* stack.destroy();
70
71 const rootDir = yield* cloneFixture(fixtureDir, {
72 prefix: "alchemy-vite-fix-",
73 tempRoot,
74 entries: ["index.html", "package.json", "vite.config.ts", "src"],
75 });
76 const indexPath = path.join(rootDir, "index.html");
77
78 // Restrict the input memo to fixture sources so the test isn't
79 // re-hashing the whole monorepo on every deploy.
80 const memoInclude = ["index.html", "src/**", "package.json", "vite.config.ts"];
81
82 const v1Marker = `vite-v1-${Date.now()}`;
83 yield* fs.writeFileString(indexPath, htmlPage(v1Marker));
84
85 const site1 = yield* stack.deploy(
86 Effect.gen(function* () {
87 return yield* Cloudflare.Website.Vite("FixVite", viteProps(rootDir, memoInclude));
88 }),
89 );
90
91 expect(site1.url).toBeDefined();
92 expect(site1.hash?.input).toBeDefined();
93 yield* expectWorkerExists(site1.workerName, accountId);
94 yield* expectUrlContains(`${site1.url!}/`, v1Marker, {
95 timeout: "120 seconds",
96 label: "deploy1 v1 marker",
97 });
98
99 // ── deploy 2: edit fixture, redeploy once ──────────────────────────
100 const v2Marker = `vite-v2-${Date.now()}`;
101 yield* fs.writeFileString(indexPath, htmlPage(v2Marker));
102
103 const site2 = yield* stack.deploy(
104 Effect.gen(function* () {
105 return yield* Cloudflare.Website.Vite("FixVite", viteProps(rootDir, memoInclude));
106 }),
107 );
108
109 expect(site2.hash?.input).toBeDefined();
110 expect(site2.hash?.input).not.toEqual(site1.hash?.input);
111 yield* expectUrlContains(`${site2.url!}/`, v2Marker, {
112 timeout: "60 seconds",
113 label: "deploy2 v2 marker",
114 });
115
116 yield* stack.destroy();
117 yield* waitForWorkerToBeDeleted(site1.workerName, accountId);
118 }).pipe(logLevel),
119 { tags: ["provider:cloudflare:worker", "live"], timeout: 360_000 },
120 );
121
122 // Regression test for https://github.com/alchemy-run/alchemy/issues/1996.
123 //
124 // A failed build used to report only the exit code and vite's
125 // `✗ Build failed in …` line; the actual error never left the child.
126 test.provider(
127 "Vite: a failed build reports the exit code and the child's stderr",
128 (stack) =>
129 Effect.gen(function* () {
130 yield* stack.destroy();
131
132 const rootDir = yield* cloneFixture(buildErrorFixtureDir, {
133 prefix: "alchemy-vite-build-error-",
134 tempRoot,
135 entries: ["package.json", "vite.config.ts", "src"],
136 });
137
138 const exit = yield* stack
139 .deploy(
140 Effect.gen(function* () {
141 return yield* Cloudflare.Website.Vite("ViteBuildError", {
142 ...viteProps(rootDir, ["src/**", "package.json", "vite.config.ts"]),
143 main: "./src/worker.ts",
144 });
145 }),
146 )
147 .pipe(Effect.exit);
148
149 assert(Exit.isFailure(exit));
150 const message = Cause.pretty(exit.cause);
151 expect(message).toContain("Vite build child exited with code 1.\nstderr:");
152 expect(message).toContain("MISSING_EXPORT");
153 expect(message).toContain(`"missing" is not exported by "src/lib.ts"`);
154
155 yield* stack.destroy();
156 }).pipe(logLevel),
157 { tags: ["provider:cloudflare:worker", "local"], timeout: 180_000 },
158 );
159
160 // Regression test for https://github.com/alchemy-run/alchemy/issues/1016.
161 //
162 // `hashViteInput` used to pass a relative root as both the directory and its
163 // base, resolving `app` as `<cwd>/app/app`. The empty match produced a constant
164 // input hash, so source edits were incorrectly treated as no-ops.
165 test.provider(
166 "Vite: a source edit changes the input hash when rootDir is relative",
167 (stack) =>
168 Effect.gen(function* () {
169 const { accountId } = yield* yield* CloudflareEnvironment;
170 const fs = yield* FileSystem.FileSystem;
171 const path = yield* Path.Path;
172
173 yield* stack.destroy();
174
175 const absoluteRoot = yield* cloneFixture(fixtureDir, {
176 prefix: "alchemy-vite-relative-root-",
177 tempRoot,
178 entries: ["index.html", "package.json", "vite.config.ts", "src"],
179 });
180 // Relative to the process's anchored cwd (what a relative rootDir
181 // means to the engine) — a live `process.cwd()` read can race a
182 // concurrent tool's transient chdir.
183 const rootDir = path.relative(initialCwd, absoluteRoot);
184 const indexPath = path.join(absoluteRoot, "index.html");
185 const memoInclude = ["index.html", "src/**", "package.json", "vite.config.ts"];
186
187 expect(path.isAbsolute(rootDir)).toBe(false);
188 yield* fs.writeFileString(indexPath, htmlPage("relative-root-v1"));
189
190 const site1 = yield* stack.deploy(
191 Effect.gen(function* () {
192 return yield* Cloudflare.Website.Vite(
193 "ViteRelativeRoot",
194 viteProps(rootDir, memoInclude),
195 );
196 }),
197 );
198 expect(site1.hash?.input).toBeDefined();
199
200 yield* fs.writeFileString(indexPath, htmlPage("relative-root-v2"));
201
202 const site2 = yield* stack.deploy(
203 Effect.gen(function* () {
204 return yield* Cloudflare.Website.Vite(
205 "ViteRelativeRoot",
206 viteProps(rootDir, memoInclude),
207 );
208 }),
209 );
210 expect(site2.hash?.input).toBeDefined();
211 expect(site2.hash?.input).not.toEqual(site1.hash?.input);
212
213 yield* stack.destroy();
214 yield* waitForWorkerToBeDeleted(site1.workerName, accountId);
215 }).pipe(logLevel),
216 { tags: ["provider:cloudflare:worker", "live"], timeout: 360_000 },
217 );
218
219 // Regression test for https://github.com/alchemy-run/alchemy/issues/792.
220 //
221 // A pure client-only Vite project (no vite.config.ts, no plugins, no worker
222 // entry) resolves as `appType: "spa"`, so the Cloudflare Vite plugin declares
223 // no `builder.buildApp`. On Vite 8, `builder.buildApp()` then runs post-order
224 // `buildApp` hooks *before* the default environment builds — which used to make
225 // our build-output plugin resolve while the client output was still undefined,
226 // so the deploy died with "Vite build produced neither assets nor server
227 // output". Detecting completion in `writeBundle` (per environment) instead of a
228 // post-order `buildApp` hook fixes it; this test proves the SPA path deploys.
229 test.provider(
230 "Vite: client-only SPA (no config, no plugins) builds and serves assets",
231 (stack) =>
232 Effect.gen(function* () {
233 const { accountId } = yield* yield* CloudflareEnvironment;
234 const fs = yield* FileSystem.FileSystem;
235 const path = yield* Path.Path;
236
237 yield* stack.destroy();
238
239 const rootDir = yield* cloneFixture(spaFixtureDir, {
240 prefix: "alchemy-vite-spa-",
241 tempRoot,
242 entries: ["index.html", "package.json", "src"],
243 });
244 const indexPath = path.join(rootDir, "index.html");
245 const memoInclude = ["index.html", "src/**", "package.json"];
246
247 const marker = `vite-spa-${Date.now()}`;
248 yield* fs.writeFileString(indexPath, htmlPage(marker));
249
250 const site = yield* stack.deploy(
251 Effect.gen(function* () {
252 return yield* Cloudflare.Website.Vite("FixViteSpa", viteProps(rootDir, memoInclude));
253 }),
254 );
255
256 expect(site.url).toBeDefined();
257 expect(site.hash?.input).toBeDefined();
258 yield* expectWorkerExists(site.workerName, accountId);
259 yield* expectUrlContains(`${site.url!}/`, marker, {
260 timeout: "120 seconds",
261 label: "spa marker",
262 });
263
264 yield* stack.destroy();
265 yield* waitForWorkerToBeDeleted(site.workerName, accountId);
266 }).pipe(logLevel),
267 { tags: ["provider:cloudflare:worker", "live"], timeout: 360_000 },
268 );
269
270 // `vite-assets-fixture` mirrors `@cloudflare/vite-plugin`'s
271 // `playground/assets` (plus the asset cases of `build-output`,
272 // `deps-assets-importing` and `spa-with-api`), and each variant below
273 // mirrors one of its Vite configs. Like the plugin's specs, the variants
274 // that serve assets run deployed and under `alchemy dev`.
275 const prepareAssetsFixture = (options: {
276 readonly config?: string;
277 readonly removePublic?: boolean;
278 readonly removeSrc?: boolean;
279 }) =>
280 Effect.gen(function* () {
281 const fs = yield* FileSystem.FileSystem;
282 const rootDir = yield* cloneFixture(assetsFixtureDir, {
283 prefix: "alchemy-vite-assets-",
284 tempRoot,
285 entries: ["package.json", "vite.config.ts", "configs", "html-page.html", "src", "public"],
286 });
287 if (options.config) {
288 yield* fs.copyFile(
289 pathe.join(rootDir, "configs", `${options.config}.ts`),
290 pathe.join(rootDir, "vite.config.ts"),
291 );
292 }
293 yield* fs.remove(pathe.join(rootDir, "configs"), { recursive: true });
294 if (options.removePublic)
295 yield* fs.remove(pathe.join(rootDir, "public"), { recursive: true });
296 if (options.removeSrc) yield* fs.remove(pathe.join(rootDir, "src"), { recursive: true });
297 return rootDir;
298 });
299
300 const assetsSite = (id: string, rootDir: string, main: string | undefined, dev = false) =>
301 Cloudflare.Website.Vite(id, {
302 ...viteProps(rootDir, ["src/**", "public/**", "package.json", "vite.config.ts", "*.html"]),
303 main,
304 ...(dev ? { dev: { port: 0 } } : {}),
305 });
306
307 const expectNoHeader = (url: string, header: string) =>
308 Effect.gen(function* () {
309 const client = yield* HttpClient.HttpClient;
310 const response = yield* client.get(url);
311 expect(response.status).toBe(200);
312 expect(response.headers[header]).toBeUndefined();
313 });
314
315 // `playground/assets/__tests__/base-tests.ts`.
316 const expectWorkerAssets = (url: string) =>
317 Effect.all(
318 [
319 expectUrlHeader(`${url}/public-directory-asset`, "content-type", "image/svg+xml"),
320 expectUrlHeader(
321 `${url}/public-directory-asset`,
322 "additional-header",
323 "public-directory-asset",
324 ),
325 expectUrlHeader(`${url}/imported-asset`, "content-type", "image/svg+xml"),
326 expectUrlHeader(`${url}/imported-asset`, "additional-header", "imported-asset"),
327 expectUrlContains(
328 `${url}/imported-asset-url-suffix`,
329 'The text content is "Text content"',
330 ),
331 expectUrlHeader(`${url}/inline-asset`, "content-type", "image/svg+xml"),
332 expectUrlHeader(`${url}/inline-asset`, "additional-header", "inline-asset"),
333 // `playground/spa-with-api`: `?no-inline`.
334 expectUrlContains(`${url}/no-inline-asset`, "Modified: No-inline content"),
335 // `playground/build-output`: a `.txt` import stays a Worker module.
336 expectUrlContains(`${url}/additional-module`, "hello from additional module"),
337 // `playground/deps-assets-importing`.
338 // The URL is `/@fs/...` in dev and `/assets/...` once built.
339 expectUrlContains(`${url}/dependency-asset-raw`, "dependency:vite url:/"),
340 expectUrlContains(`${url}/dependency-asset`, '"name": "vite"'),
341 ],
342 { concurrency: 4 },
343 );
344
345 // Public files serve directly, ahead of the Worker, nested directories
346 // included. `public/_headers` applies once deployed (the plugin checks it
347 // in build mode only).
348 const expectPublicAssets = (url: string, mode: Mode) =>
349 Effect.all(
350 [
351 expectUrlHeader(`${url}/public-image.svg`, "content-type", "image/svg+xml"),
352 expectUrlContains(`${url}/nested/file.txt`, "vite-nested-public-marker"),
353 ...(mode === "live"
354 ? [expectUrlHeader(`${url}/public-image.svg`, "x-header", "splat-header")]
355 : []),
356 ],
357 { concurrency: 3 },
358 );
359
360 type Mode = "live" | "dev";
361 type Check = (url: string, mode: Mode) => Effect.Effect<void, unknown, HttpClient.HttpClient>;
362
363 const liveAssetsTest = (
364 name: string,
365 id: string,
366 options: Parameters<typeof prepareAssetsFixture>[0] & { readonly main?: string | null },
367 check: Check,
368 ) =>
369 test.provider(
370 name,
371 (stack) =>
372 Effect.gen(function* () {
373 const { accountId } = yield* yield* CloudflareEnvironment;
374 yield* stack.destroy();
375 const rootDir = yield* prepareAssetsFixture(options);
376 const main = options.main === null ? undefined : (options.main ?? "./src/index.ts");
377 const site = yield* stack.deploy(assetsSite(id, rootDir, main));
378 yield* expectWorkerExists(site.workerName, accountId);
379 yield* check(site.url!, "live");
380 yield* stack.destroy();
381 yield* waitForWorkerToBeDeleted(site.workerName, accountId);
382 }).pipe(logLevel),
383 { tags: ["provider:cloudflare:worker", "live"], timeout: 360_000 },
384 );
385
386 const devAssetsTest = (
387 name: string,
388 id: string,
389 options: Parameters<typeof prepareAssetsFixture>[0] & { readonly main?: string | null },
390 check: Check,
391 ) =>
392 devTest.provider(
393 name,
394 (stack) =>
395 Effect.gen(function* () {
396 yield* stack.destroy();
397 const rootDir = yield* prepareAssetsFixture(options);
398 const main = options.main === null ? undefined : (options.main ?? "./src/index.ts");
399 const site = yield* stack.deploy(assetsSite(id, rootDir, main, true));
400 yield* check(site.url!.replace(/\/$/, ""), "dev");
401 }).pipe(Effect.ensuring(stack.destroy().pipe(Effect.ignore)), logLevel),
402 { tags: ["provider:cloudflare:worker", "local"], timeout: 120_000 },
403 );
404
405 // `playground/assets/__tests__/no-client-entry`.
406 const noClientEntry: Check = (url, mode) =>
407 Effect.gen(function* () {
408 yield* expectWorkerAssets(url);
409 yield* expectPublicAssets(url, mode);
410 yield* expectNoHeader(`${url}/public-image.svg`, "additional-header");
411 if (mode === "live") {
412 // `.assetsignore` keeps `*.bak` out of the uploaded assets, so the
413 // Worker answers instead.
414 yield* expectUrlContains(`${url}/ignored.bak`, "vite-assets-worker");
415 }
416 });
417 liveAssetsTest(
418 "Vite assets: no client entry uploads public/ and Worker-imported assets",
419 "FixViteNoClientEntry",
420 {},
421 noClientEntry,
422 );
423 devAssetsTest(
424 "Vite assets dev: no client entry serves public/ and Worker-imported assets",
425 "FixViteNoClientEntryDev",
426 {},
427 noClientEntry,
428 );
429
430 // `playground/assets/__tests__/assets.spec.ts`.
431 const clientEntry: Check = (url, mode) =>
432 Effect.gen(function* () {
433 yield* expectWorkerAssets(url);
434 yield* expectPublicAssets(url, mode);
435 yield* expectUrlContains(`${url}/transformed-html-asset`, "Modified content");
436 yield* expectNoHeader(`${url}/public-image.svg`, "additional-header");
437 yield* expectUrlContains(`${url}/html-page`, "Original content");
438 });
439 liveAssetsTest(
440 "Vite assets: a client entry that isn't index.html keeps Worker-imported assets",
441 "FixViteClientEntry",
442 { config: "client-entry" },
443 clientEntry,
444 );
445 devAssetsTest(
446 "Vite assets dev: a client entry that isn't index.html keeps Worker-imported assets",
447 "FixViteClientEntryDev",
448 { config: "client-entry" },
449 clientEntry,
450 );
451
452 // `playground/assets/__tests__/public-dir-only`.
453 const publicDirOnly: Check = (url, mode) => expectPublicAssets(url, mode);
454 liveAssetsTest(
455 "Vite assets: public/ only, no Worker entry, deploys assets-only",
456 "FixVitePublicDirOnly",
457 { removeSrc: true, main: null },
458 publicDirOnly,
459 );
460 devAssetsTest(
461 "Vite assets dev: public/ only, no Worker entry, serves assets-only",
462 "FixVitePublicDirOnlyDev",
463 { removeSrc: true, main: null },
464 publicDirOnly,
465 );
466
467 // `playground/spa-with-api/__tests__/custom-output-directories`.
468 liveAssetsTest(
469 "Vite assets: custom output directories keep public/ and Worker-imported assets",
470 "FixViteCustomOutputDirs",
471 { config: "custom-output-directories" },
472 (url, mode) => Effect.all([expectWorkerAssets(url), expectPublicAssets(url, mode)]),
473 );
474
475 // The plugin's `buildApp` skips the client build when nothing would land
476 // in it: the Worker deploys without `ASSETS`.
477 const noAssets: Check = (url) => expectUrlContains(url, `"assets":false`);
478 liveAssetsTest(
479 "Vite assets: no public/ and no imported assets deploys without ASSETS",
480 "FixViteNoAssets",
481 { removePublic: true, main: "./src/no-assets.ts" },
482 noAssets,
483 );
484 liveAssetsTest(
485 "Vite assets: publicDir: false deploys without ASSETS",
486 "FixVitePublicDirOff",
487 { config: "public-dir-off", main: "./src/no-assets.ts" },
488 noAssets,
489 );
490
491 // Foldkit (foldkit.dev) is an Effect-native Elm-architecture frontend
492 // framework. Its apps are plain client-only Vite projects (the Foldkit Vite
493 // plugin only adds HMR/devtools wiring), so `Cloudflare.Website.Vite` deploys
494 // them as-is. This pins that the Foldkit plugin composes with the injected
495 // Cloudflare Vite plugin and that deep links fall back to `index.html` via
496 // `single-page-application` not-found handling.
497 test.provider(
498 "Vite: Foldkit SPA deploys and serves with SPA fallback",
499 (stack) =>
500 Effect.gen(function* () {
501 const { accountId } = yield* yield* CloudflareEnvironment;
502
503 yield* stack.destroy();
504
505 const rootDir = yield* cloneFixture(foldkitFixtureDir, {
506 prefix: "alchemy-vite-foldkit-",
507 tempRoot,
508 entries: ["index.html", "package.json", "vite.config.ts", "src"],
509 });
510 const memoInclude = ["index.html", "src/**", "package.json", "vite.config.ts"];
511
512 const site = yield* stack.deploy(
513 Effect.gen(function* () {
514 return yield* Cloudflare.Website.Vite("FixViteFoldkit", {
515 ...viteProps(rootDir, memoInclude),
516 assets: { notFoundHandling: "single-page-application" },
517 });
518 }),
519 );
520
521 expect(site.url).toBeDefined();
522 expect(site.hash?.input).toBeDefined();
523 yield* expectWorkerExists(site.workerName, accountId);
524 yield* expectUrlContains(`${site.url!}/`, "Foldkit Fixture", {
525 timeout: "120 seconds",
526 label: "foldkit index",
527 });
528 // Deep link falls back to index.html so client-side routing can boot.
529 yield* expectUrlContains(`${site.url!}/counter/42`, "Foldkit Fixture", {
530 timeout: "60 seconds",
531 label: "foldkit spa fallback",
532 });
533
534 yield* stack.destroy();
535 yield* waitForWorkerToBeDeleted(site.workerName, accountId);
536 }).pipe(logLevel),
537 { tags: ["provider:cloudflare:worker", "live"], timeout: 360_000 },
538 );
539
540 test.provider(
541 "Vite: class form deploys and serves the built assets",
542 (stack) =>
543 Effect.gen(function* () {
544 const { accountId } = yield* yield* CloudflareEnvironment;
545 const fs = yield* FileSystem.FileSystem;
546 const path = yield* Path.Path;
547
548 yield* stack.destroy();
549
550 const rootDir = yield* cloneFixture(fixtureDir, {
551 prefix: "alchemy-vite-class-",
552 tempRoot,
553 entries: ["index.html", "package.json", "vite.config.ts", "src"],
554 });
555 const indexPath = path.join(rootDir, "index.html");
556 const memoInclude = ["index.html", "src/**", "package.json", "vite.config.ts"];
557
558 const marker = `vite-class-${Date.now()}`;
559 yield* fs.writeFileString(indexPath, htmlPage(marker));
560
561 const site1 = yield* stack.deploy(
562 Effect.gen(function* () {
563 return yield* class FixVite extends Cloudflare.Website.Vite<FixVite>()(
564 "FixVite",
565 viteProps(rootDir, memoInclude),
566 ) {};
567 }),
568 );
569
570 expect(site1.url).toBeDefined();
571 expect(site1.hash?.input).toBeDefined();
572 yield* expectWorkerExists(site1.workerName, accountId);
573 yield* expectUrlContains(`${site1.url!}/`, marker, {
574 timeout: "120 seconds",
575 label: "class form marker",
576 });
577
578 yield* stack.destroy();
579 yield* waitForWorkerToBeDeleted(site1.workerName, accountId);
580 }).pipe(logLevel),
581 { tags: ["provider:cloudflare:worker", "live"], timeout: 360_000 },
582 );
583
584 // ─────────────────────────────────────────────────────────────────────
585 // Path-relocation behavior for the vite path
586 //
587 // `Cloudflare.Website.Vite` stores a path-insensitive `hash.input` made from
588 // the memo'd input tree plus build-affecting Vite options. The diff is:
589 //
590 // `input !== output.hash?.input`
591 //
592 // — a pure content comparison that must be stable across rootDir
593 // moves. We delete the original rootDir between deploys to make the
594 // test fail loudly if anything still depends on the recorded path.
595 // ─────────────────────────────────────────────────────────────────────
596
597 test.provider(
598 "Vite: relocating rootDir (and deleting the old one) is a no-op when sources are identical",
599 (stack) =>
600 Effect.gen(function* () {
601 const { accountId } = yield* yield* CloudflareEnvironment;
602 const fs = yield* FileSystem.FileSystem;
603 const path = yield* Path.Path;
604
605 yield* stack.destroy();
606
607 const memoInclude = ["index.html", "src/**", "package.json", "vite.config.ts"];
608 const marker = `vite-relocate-${Date.now()}`;
609
610 const rootA = yield* cloneFixture(fixtureDir, {
611 prefix: "alchemy-vite-relocate-a-",
612 tempRoot,
613 entries: ["index.html", "package.json", "vite.config.ts", "src"],
614 });
615 yield* fs.writeFileString(path.join(rootA, "index.html"), htmlPage(marker));
616
617 const site1 = yield* stack.deploy(
618 Effect.gen(function* () {
619 return yield* Cloudflare.Website.Vite("ViteReloc", viteProps(rootA, memoInclude));
620 }),
621 );
622 expect(site1.hash?.input).toBeDefined();
623 yield* expectUrlContains(`${site1.url!}/`, marker, {
624 timeout: "120 seconds",
625 label: "deploy1 marker",
626 });
627
628 // Drop rootA so a stale path comparison can't quietly succeed.
629 yield* fs.remove(rootA, { recursive: true });
630
631 const rootB = yield* cloneFixture(fixtureDir, {
632 prefix: "alchemy-vite-relocate-b-",
633 tempRoot,
634 entries: ["index.html", "package.json", "vite.config.ts", "src"],
635 });
636 yield* fs.writeFileString(path.join(rootB, "index.html"), htmlPage(marker));
637
638 const site2 = yield* stack.deploy(
639 Effect.gen(function* () {
640 return yield* Cloudflare.Website.Vite("ViteReloc", viteProps(rootB, memoInclude));
641 }),
642 );
643
644 // Identical sources ⇒ identical input hash ⇒ diff says
645 // unchanged ⇒ no rebuild required for the apply to succeed.
646 expect(site2.hash?.input).toEqual(site1.hash?.input);
647 yield* expectUrlContains(`${site2.url!}/`, marker, {
648 timeout: "60 seconds",
649 label: "deploy2 marker",
650 });
651
652 yield* stack.destroy();
653 yield* waitForWorkerToBeDeleted(site1.workerName, accountId);
654 }).pipe(logLevel),
655 { tags: ["provider:cloudflare:worker", "live"], timeout: 360_000 },
656 );
657
658 // ─────────────────────────────────────────────────────────────────────
659 // Workspace-aware memoization
660 //
661 // A Vite project in a monorepo can bundle source from sibling workspace
662 // packages. Those directories are discovered from the module graph at
663 // build time, persisted in `hash.workspaces` (relative to the Vite
664 // root), and included in the `hash.input` computation — so editing only
665 // a sibling package busts the memo and triggers a rebuild.
666 // ─────────────────────────────────────────────────────────────────────
667
668 test.provider(
669 "Vite: edits in a sibling workspace package bust the build memo",
670 (stack) =>
671 Effect.gen(function* () {
672 const { accountId } = yield* yield* CloudflareEnvironment;
673 const fs = yield* FileSystem.FileSystem;
674 const path = yield* Path.Path;
675
676 yield* stack.destroy();
677
678 // Hand-rolled two-package workspace: `app` is the Vite root and
679 // `shared` is a sibling package whose source the client bundle
680 // imports directly (escaping the Vite root).
681 yield* fs.makeDirectory(tempRoot, { recursive: true });
682 const parent = yield* fs.makeTempDirectory({
683 prefix: "alchemy-vite-ws-",
684 directory: tempRoot,
685 });
686 yield* Effect.addFinalizer(
687 Exit.match({
688 onSuccess: () => Effect.ignore(fs.remove(parent, { recursive: true })),
689 onFailure: () => Effect.void,
690 }),
691 );
692 const rootDir = path.join(parent, "app");
693 const sharedDir = path.join(parent, "shared");
694
695 const writeShared = (marker: string) =>
696 fs.writeFileString(
697 path.join(sharedDir, "src/message.ts"),
698 `export const message = ${JSON.stringify(marker)};\n`,
699 );
700
701 yield* fs.makeDirectory(path.join(rootDir, "src"), { recursive: true });
702 yield* fs.makeDirectory(path.join(sharedDir, "src"), { recursive: true });
703 yield* fs.writeFileString(
704 path.join(rootDir, "index.html"),
705 htmlPage("vite-workspace-fixture"),
706 );
707 yield* fs.writeFileString(
708 path.join(rootDir, "package.json"),
709 JSON.stringify({
710 name: "alchemy-vite-workspace-app",
711 version: "0.0.0",
712 private: true,
713 type: "module",
714 }),
715 );
716 // Same shape as vite-fixture/vite.config.ts: point the SSR build at
717 // the minimal worker entry so the cloudflare-vite-plugin can wrap it.
718 yield* fs.writeFileString(
719 path.join(rootDir, "vite.config.ts"),
720 `import { defineConfig } from "vite";
721 export default defineConfig({
722 environments: {
723 ssr: { build: { rollupOptions: { input: "./src/worker.ts" } } },
724 },
725 });
726 `,
727 );
728 yield* fs.writeFileString(
729 path.join(rootDir, "src/worker.ts"),
730 `type Env = { ASSETS: { fetch: (req: Request) => Promise<Response> } };
731 export default {
732 fetch(request: Request, env: Env): Promise<Response> {
733 return env.ASSETS.fetch(request);
734 },
735 };
736 `,
737 );
738 // The client entry imports across the Vite root boundary into the
739 // sibling package's source.
740 yield* fs.writeFileString(
741 path.join(rootDir, "src/main.ts"),
742 `import { message } from "../../shared/src/message.ts";
743 const el = document.getElementById("app");
744 if (el) {
745 el.textContent = message;
746 }
747 `,
748 );
749 yield* fs.writeFileString(
750 path.join(sharedDir, "package.json"),
751 JSON.stringify({
752 name: "alchemy-vite-workspace-shared",
753 version: "0.0.0",
754 private: true,
755 type: "module",
756 }),
757 );
758
759 const memoInclude = ["index.html", "src/**", "package.json", "vite.config.ts"];
760
761 const marker1 = `vite-ws-1-${Date.now()}`;
762 yield* writeShared(marker1);
763
764 const site1 = yield* stack.deploy(
765 Effect.gen(function* () {
766 return yield* Cloudflare.Website.Vite(
767 "ViteWorkspace",
768 viteProps(rootDir, memoInclude),
769 );
770 }),
771 );
772
773 expect(site1.url).toBeDefined();
774 expect(site1.hash?.input).toBeDefined();
775 // The sibling package was discovered from the module graph and
776 // persisted relative to the Vite root.
777 expect(site1.hash?.additionalWorkspaces).toContain("../shared");
778 yield* expectWorkerExists(site1.workerName, accountId);
779 yield* expectBundleContains(site1.url!, marker1, {
780 label: "workspace marker v1 in client bundle",
781 });
782
783 // ── deploy 2: edit ONLY the sibling package ────────────────────────
784 const marker2 = `vite-ws-2-${Date.now()}`;
785 yield* writeShared(marker2);
786
787 const site2 = yield* stack.deploy(
788 Effect.gen(function* () {
789 return yield* Cloudflare.Website.Vite(
790 "ViteWorkspace",
791 viteProps(rootDir, memoInclude),
792 );
793 }),
794 );
795
796 // Nothing under `rootDir` changed — only the sibling workspace did.
797 // The workspace-aware input hash must still bust the memo.
798 expect(site2.hash?.input).toBeDefined();
799 expect(site2.hash?.input).not.toEqual(site1.hash?.input);
800 expect(site2.hash?.additionalWorkspaces).toContain("../shared");
801 yield* expectBundleContains(site2.url!, marker2, {
802 label: "workspace marker v2 in client bundle",
803 });
804
805 // ── deploy 3: no changes anywhere ⇒ memo hit ───────────────────────
806 const site3 = yield* stack.deploy(
807 Effect.gen(function* () {
808 return yield* Cloudflare.Website.Vite(
809 "ViteWorkspace",
810 viteProps(rootDir, memoInclude),
811 );
812 }),
813 );
814
815 expect(site3.hash?.input).toEqual(site2.hash?.input);
816 expect(site3.hash?.additionalWorkspaces).toEqual(site2.hash?.additionalWorkspaces);
817
818 yield* stack.destroy();
819 yield* waitForWorkerToBeDeleted(site1.workerName, accountId);
820 }).pipe(logLevel),
821 { tags: ["provider:cloudflare:worker", "live"], timeout: 360_000 },
822 );
823
824 test.provider(
825 "Vite: `env` props are inlined and env-only changes redeploy",
826 (stack) =>
827 Effect.gen(function* () {
828 const { accountId } = yield* yield* CloudflareEnvironment;
829
830 yield* stack.destroy();
831
832 const rootDir = yield* cloneFixture(fixtureDir, {
833 prefix: "alchemy-vite-env-",
834 tempRoot,
835 entries: ["index.html", "package.json", "vite.config.ts", "src"],
836 });
837 const memoInclude = ["index.html", "src/**", "package.json"];
838 const marker1 = `vite-env-1-${Date.now()}`;
839
840 const site1 = yield* stack.deploy(
841 Effect.gen(function* () {
842 return yield* Cloudflare.Website.Vite("FixViteEnv", {
843 ...viteProps(rootDir, memoInclude),
844 env: { VITE_TEST_MARKER: marker1 },
845 });
846 }),
847 );
848
849 expect(site1.url).toBeDefined();
850 expect(site1.hash?.input).toBeDefined();
851 // Resolve the hashed bundle URL by reading the deployed HTML, then
852 // assert the marker that `main.ts` references via
853 // `import.meta.env.VITE_TEST_MARKER` was actually inlined into the
854 // served JS asset by `Cloudflare.Website.Vite`'s `env`-→-`define` plumbing.
855 yield* expectBundleContains(site1.url!, marker1, {
856 label: "VITE_TEST_MARKER v1 inlined into client bundle",
857 });
858
859 const marker2 = `vite-env-2-${Date.now()}`;
860 const site2 = yield* stack.deploy(
861 Effect.gen(function* () {
862 return yield* Cloudflare.Website.Vite("FixViteEnv", {
863 ...viteProps(rootDir, memoInclude),
864 env: { VITE_TEST_MARKER: marker2 },
865 });
866 }),
867 );
868
869 expect(site2.hash?.input).toBeDefined();
870 yield* expectBundleContains(site2.url!, marker2, {
871 label: "VITE_TEST_MARKER v2 inlined into client bundle",
872 });
873
874 yield* stack.destroy();
875 yield* waitForWorkerToBeDeleted(site1.workerName, accountId);
876 }).pipe(logLevel),
877 { tags: ["provider:cloudflare:worker", "live"], timeout: 360_000 },
878 );
879
880 test.provider(
881 "Vite: worker entry can host a local Durable Object binding",
882 (stack) =>
883 Effect.gen(function* () {
884 const { accountId } = yield* yield* CloudflareEnvironment;
885
886 yield* stack.destroy();
887
888 const rootDir = yield* cloneFixture(doFixtureDir, {
889 prefix: "alchemy-vite-do-",
890 tempRoot,
891 // Keep the fixture's real stack file available for local
892 // `alchemy dev` smoke tests. The live deploy below uses an inline
893 // stack so cleanup stays under the provider test harness.
894 entries: ["alchemy.run.ts", "index.html", "package.json", "vite.config.ts", "src"],
895 });
896 const memoInclude = ["index.html", "src/**", "package.json", "vite.config.ts"];
897
898 const site = yield* stack.deploy(
899 Effect.gen(function* () {
900 return yield* Cloudflare.Website.Vite("ViteDo", {
901 ...viteProps(rootDir, memoInclude),
902 compatibility: { date: "2026-03-17", flags: ["nodejs_compat"] },
903 // The documented SPA + Worker-API pattern (vite.mdx): the SPA
904 // fallback owns unmatched paths while the glob pins the API
905 // namespace to the Worker regardless of request mode.
906 assets: { notFoundHandling: "single-page-application", runWorkerFirst: ["/api/*"] },
907 env: {
908 Counter: Cloudflare.DurableObject<ViteDoCounter>("Counter", {
909 className: "Counter",
910 }),
911 },
912 });
913 }),
914 );
915
916 expect(site.url).toBeDefined();
917 yield* expectWorkerExists(site.workerName, accountId);
918 yield* expectUrlContains(`${site.url!}/`, "Vite DO fixture", {
919 timeout: "120 seconds",
920 label: "vite do fixture assets",
921 });
922
923 // A deep link matches no asset: the SPA fallback serves the shell
924 // (static routing applies it to every request mode, so a plain GET
925 // with no Sec-Fetch-Mode header gets the shell too).
926 yield* expectUrlContains(`${site.url!}/deep/link`, "Vite DO fixture", {
927 timeout: "60 seconds",
928 label: "vite do spa deep link",
929 });
930
931 const reset = yield* fetchJsonReady<{ ok: boolean }>(`${site.url!}/api/reset`);
932 expect(reset.ok).toBe(true);
933
934 const first = yield* fetchJsonReady<{ count: number }>(`${site.url!}/api/count`);
935 expect(first.count).toBe(1);
936
937 const second = yield* fetchJsonReady<{ count: number }>(`${site.url!}/api/count`);
938 expect(second.count).toBe(2);
939
940 yield* stack.destroy();
941 yield* waitForWorkerToBeDeleted(site.workerName, accountId);
942 }).pipe(logLevel),
943 { tags: ["provider:cloudflare:worker", "live"], timeout: 360_000 },
944 );
945
946 test.provider(
947 "Vite: Container binding on env deploys a container-backed DO class",
948 (stack) =>
949 Effect.gen(function* () {
950 const { accountId } = yield* yield* CloudflareEnvironment;
951
952 yield* stack.destroy();
953
954 const rootDir = yield* cloneFixture(containerFixtureDir, {
955 prefix: "alchemy-vite-container-",
956 tempRoot,
957 entries: ["index.html", "package.json", "vite.config.ts", "src"],
958 });
959 const memoInclude = ["index.html", "src/**", "package.json", "vite.config.ts"];
960
961 // A `Cloudflare.Container` declaration on `env` is Effect-shaped —
962 // before #997 the Vite build's env resolution ran it as an inlined
963 // env Effect and the deploy died before the build started.
964 const site = yield* stack.deploy(
965 Effect.gen(function* () {
966 return yield* Cloudflare.Website.Vite("ViteContainer", {
967 ...viteProps(rootDir, memoInclude),
968 compatibility: { date: "2026-03-17", flags: ["nodejs_compat"] },
969 assets: { runWorkerFirst: ["/api/*"] },
970 env: {
971 ECHO: Cloudflare.Container("ViteEchoContainer", {
972 className: "EchoObject",
973 image: "mendhak/http-https-echo:latest",
974 observability: { logs: { enabled: true } },
975 }),
976 },
977 });
978 }),
979 );
980
981 expect(site.url).toBeDefined();
982 yield* expectWorkerExists(site.workerName, accountId);
983 yield* expectUrlContains(`${site.url!}/`, "Vite Container fixture", {
984 timeout: "120 seconds",
985 label: "vite container fixture assets",
986 });
987
988 // The echo image reflects the request as JSON ("method" only appears
989 // in a real echo response, never in an error page) — proof the request
990 // went Worker → DO class → container port 8080 and back.
991 const echo = yield* fetchContainerReady(`${site.url!}/api/echo`, "method");
992 expect(echo).toContain("method");
993
994 yield* stack.destroy();
995 yield* waitForWorkerToBeDeleted(site.workerName, accountId);
996 }).pipe(logLevel),
997 // Container image pull + push + rollout comfortably exceeds the plain
998 // Vite deploy budget (mirrors Container.test.ts).
999 {
1000 tags: ["provider:cloudflare:container", "provider:cloudflare:worker", "live"],
1001 timeout: 600_000,
1002 },
1003 );
1004
1005 // The documented interception pattern (solidstart.mdx hand-rolled SSR /
1006 // static-site.mdx docs-site worker): the client build emits an index.html
1007 // that would shadow `/` under assets-first routing, so the worker runs
1008 // first, renders every page, and delegates real static files to the
1009 // ASSETS binding itself.
1010 test.provider(
1011 "Vite: runWorkerFirst true intercepts asset paths and delegates to ASSETS",
1012 (stack) =>
1013 Effect.gen(function* () {
1014 const { accountId } = yield* yield* CloudflareEnvironment;
1015
1016 yield* stack.destroy();
1017
1018 const rootDir = yield* cloneFixture(workerFirstFixtureDir, {
1019 prefix: "alchemy-vite-worker-first-",
1020 tempRoot,
1021 entries: ["index.html", "package.json", "public", "src", "vite.config.ts", "worker.ts"],
1022 });
1023 const memoInclude = [
1024 "index.html",
1025 "public/**",
1026 "src/**",
1027 "package.json",
1028 "vite.config.ts",
1029 "worker.ts",
1030 ];
1031
1032 const site = yield* stack.deploy(
1033 Effect.gen(function* () {
1034 return yield* Cloudflare.Website.Vite("ViteWorkerFirst", {
1035 ...viteProps(rootDir, memoInclude),
1036 main: "worker.ts",
1037 assets: { runWorkerFirst: true },
1038 });
1039 }),
1040 );
1041
1042 expect(site.url).toBeDefined();
1043 yield* expectWorkerExists(site.workerName, accountId);
1044
1045 // `/` matches the built index.html asset, but the worker runs first
1046 // and renders — the raw template must never serve.
1047 yield* expectUrlContains(`${site.url!}/`, "worker-first-rendered:/", {
1048 timeout: "120 seconds",
1049 label: "worker-first render at /",
1050 });
1051 const home = yield* fetchTextReady(`${site.url!}/`);
1052 expect(home).not.toContain("worker-first-raw-template");
1053
1054 // Any other route renders too — the worker sees every request.
1055 yield* expectUrlContains(`${site.url!}/some/page`, "worker-first-rendered:/some/page", {
1056 timeout: "60 seconds",
1057 label: "worker-first render deep",
1058 });
1059
1060 // Real static files still serve, through the worker's own ASSETS
1061 // delegation.
1062 yield* expectUrlContains(`${site.url!}/robots.txt`, "worker-first-static-asset", {
1063 timeout: "60 seconds",
1064 label: "worker-first ASSETS delegation",
1065 });
1066
1067 yield* stack.destroy();
1068 yield* waitForWorkerToBeDeleted(site.workerName, accountId);
1069 }).pipe(logLevel),
1070 { tags: ["provider:cloudflare:worker", "live"], timeout: 360_000 },
1071 );
1072
1073 test.provider(
1074 "Vite: main overrides the worker entry from the Vite config",
1075 (stack) =>
1076 Effect.gen(function* () {
1077 const { accountId } = yield* yield* CloudflareEnvironment;
1078
1079 yield* stack.destroy();
1080
1081 const rootDir = yield* cloneFixture(doFixtureDir, {
1082 prefix: "alchemy-vite-main-",
1083 tempRoot,
1084 entries: ["alchemy.run.ts", "index.html", "package.json", "vite.config.ts", "src"],
1085 });
1086 const memoInclude = ["index.html", "src/**", "package.json", "vite.config.ts"];
1087
1088 // The fixture's vite.config.ts points the ssr environment at
1089 // `src/worker.ts`. `main` must take precedence and deploy
1090 // `src/worker-main.ts`, which re-exports the Durable Object and
1091 // additionally answers `/api/entry`.
1092 const site = yield* stack.deploy(
1093 Effect.gen(function* () {
1094 return yield* Cloudflare.Website.Vite("ViteMain", {
1095 ...viteProps(rootDir, memoInclude),
1096 main: "src/worker-main.ts",
1097 compatibility: { date: "2026-03-17", flags: ["nodejs_compat"] },
1098 assets: { runWorkerFirst: ["/api/*"] },
1099 env: {
1100 Counter: Cloudflare.DurableObject<ViteDoCounter>("Counter", {
1101 className: "Counter",
1102 }),
1103 },
1104 });
1105 }),
1106 );
1107
1108 expect(site.url).toBeDefined();
1109 yield* expectWorkerExists(site.workerName, accountId);
1110
1111 const entry = yield* fetchJsonReady<{ entry: string }>(`${site.url!}/api/entry`);
1112 expect(entry.entry).toBe("worker-main");
1113
1114 const reset = yield* fetchJsonReady<{ ok: boolean }>(`${site.url!}/api/reset`);
1115 expect(reset.ok).toBe(true);
1116
1117 const first = yield* fetchJsonReady<{ count: number }>(`${site.url!}/api/count`);
1118 expect(first.count).toBe(1);
1119
1120 yield* stack.destroy();
1121 yield* waitForWorkerToBeDeleted(site.workerName, accountId);
1122 }).pipe(logLevel),
1123 { tags: ["provider:cloudflare:worker", "live"], timeout: 360_000 },
1124 );
1125
1126 test.provider(
1127 "Vite: React Router RSC deploys from a distilled manifest",
1128 (stack) =>
1129 Effect.gen(function* () {
1130 const { accountId } = yield* yield* CloudflareEnvironment;
1131
1132 yield* stack.destroy();
1133
1134 const rootDir = yield* cloneFixture(reactRouterRscFixtureDir, {
1135 prefix: "alchemy-vite-rsc-",
1136 tempRoot,
1137 // Keep the fixture's stack file available for local `alchemy dev`
1138 // smoke tests. The live deploy below uses an inline stack so cleanup
1139 // stays under the provider test harness.
1140 entries: [
1141 "alchemy.run.ts",
1142 "app",
1143 "package.json",
1144 "react-router-vite",
1145 "tsconfig.json",
1146 "vite.config.ts",
1147 ],
1148 });
1149 const memoInclude = [
1150 "app/**",
1151 "react-router-vite/**",
1152 "package.json",
1153 "tsconfig.json",
1154 "vite.config.ts",
1155 ];
1156 const compatibility = { date: "2026-03-10", flags: ["nodejs_compat"] };
1157 const viteEnvironments = { entry: "rsc", children: ["ssr"] };
1158
1159 const site = yield* stack.deploy(
1160 Effect.gen(function* () {
1161 return yield* Cloudflare.Website.Vite("ReactRouterRsc", {
1162 ...viteProps(rootDir, memoInclude),
1163 // No `assets` config: the RSC build emits no index.html (HTML
1164 // is server-rendered), so SSR routes fall through to the RSC
1165 // handler while hydration assets serve from the asset layer.
1166 // `runWorkerFirst: true` would route `/assets/*` into the RSC
1167 // handler, which cannot serve them.
1168 compatibility,
1169 viteEnvironments,
1170 });
1171 }),
1172 );
1173
1174 expect(site.url).toBeDefined();
1175 yield* expectWorkerExists(site.workerName, accountId);
1176 yield* expectUrlContains(`${site.url!}/`, "React Router Vite", {
1177 timeout: "120 seconds",
1178 label: "react router rsc home route",
1179 });
1180 yield* expectUrlContains(`${site.url!}/about`, "About", {
1181 timeout: "60 seconds",
1182 label: "react router rsc client route",
1183 });
1184
1185 // The hydration bundle the SSR HTML references must serve from the
1186 // asset layer — the routing gap that let `runWorkerFirst: true`
1187 // masquerade as live-tested (the old test never fetched an asset).
1188 const home = yield* fetchTextReady(`${site.url!}/`);
1189 const assetPath = home.match(/\/assets\/[^"']+\.js/)?.[0];
1190 expect(assetPath).toBeDefined();
1191 const bundle = yield* fetchTextReady(`${site.url!}${assetPath}`);
1192 expect(bundle.length).toBeGreaterThan(0);
1193 // Not the HTML page served in its place. (React Router's bundled
1194 // source mentions `<html>` in its doc comments.)
1195 expect(bundle.trimStart()).not.toMatch(/^<(!doctype|html)/i);
1196
1197 const render = yield* fetchJsonReady<{ ok: boolean; html: string }>(
1198 `${site.url!}/worker-render`,
1199 );
1200 expect(render.ok).toBe(true);
1201 expect(render.html).toContain("Worker render via the ssr environment.");
1202
1203 yield* stack.destroy();
1204 yield* waitForWorkerToBeDeleted(site.workerName, accountId);
1205 }).pipe(logLevel),
1206 { tags: ["provider:cloudflare:worker", "live"], timeout: 360_000 },
1207 );
1208
1209 devTest.provider(
1210 "Vite dev: each app runs in a child rooted at its own cwd",
1211 (stack) =>
1212 Effect.gen(function* () {
1213 const fs = yield* FileSystem.FileSystem;
1214 const path = yield* Path.Path;
1215 yield* stack.destroy();
1216
1217 const entries = ["index.html", "package.json", "vite.config.ts", "worker.ts"];
1218 const clone = (prefix: string) =>
1219 cloneFixture(viteChildFixtureDir, { prefix, tempRoot, entries });
1220 const [rootA, rootB] = yield* Effect.all(
1221 [clone("alchemy-vite-child-a-"), clone("alchemy-vite-child-b-")],
1222 { concurrency: "unbounded" },
1223 );
1224 yield* Effect.all([
1225 fs.writeFileString(path.join(rootA, "index.html"), htmlPage("child-app-a")),
1226 fs.writeFileString(path.join(rootB, "index.html"), htmlPage("child-app-b")),
1227 ]);
1228
1229 const deployed = yield* stack.deploy(
1230 Effect.gen(function* () {
1231 const props = (rootDir: string) => ({
1232 ...viteProps(rootDir, entries),
1233 main: "worker.ts",
1234 assets: { notFoundHandling: "single-page-application" as const },
1235 dev: { port: 0 },
1236 });
1237 const appA = yield* Cloudflare.Website.Vite("ViteChildA", props(rootA));
1238 const appB = yield* Cloudflare.Website.Vite("ViteChildB", props(rootB));
1239 const defaultPortWorker = yield* Cloudflare.Worker("ViteChildDefaultPortWorker", {
1240 script: 'export default { fetch: () => new Response("default-port-worker") };',
1241 });
1242 return { appA, appB, defaultPortWorker };
1243 }),
1244 );
1245
1246 expect(deployed.appA.url).not.toBe(deployed.appB.url);
1247 yield* Effect.all(
1248 [
1249 expectUrlContains(deployed.defaultPortWorker.url!, "default-port-worker", {
1250 timeout: "30 seconds",
1251 label: "default-port worker",
1252 }),
1253 expectUrlContains(deployed.appA.url!, "child-app-a", {
1254 timeout: "30 seconds",
1255 label: "child A HTML",
1256 }),
1257 expectUrlContains(deployed.appB.url!, "child-app-b", {
1258 timeout: "30 seconds",
1259 label: "child B HTML",
1260 }),
1261 expectUrlContains(deployed.appA.url!, rootA, {
1262 timeout: "30 seconds",
1263 label: "child A cwd",
1264 }),
1265 expectUrlContains(deployed.appB.url!, rootB, {
1266 timeout: "30 seconds",
1267 label: "child B cwd",
1268 }),
1269 ],
1270 { concurrency: "unbounded" },
1271 );
1272 }).pipe(Effect.ensuring(stack.destroy().pipe(Effect.orDie).pipe(Effect.ignore)), logLevel),
1273 { tags: ["provider:cloudflare:worker", "local"], timeout: 120_000 },
1274 );
1275
1276 devTest.provider(
1277 "Vite dev: client-only SPA serves the shell for deep links",
1278 (stack) =>
1279 Effect.gen(function* () {
1280 const fs = yield* FileSystem.FileSystem;
1281 const path = yield* Path.Path;
1282 yield* stack.destroy();
1283
1284 const rootDir = yield* cloneFixture(spaFixtureDir, {
1285 prefix: "alchemy-vite-spa-dev-",
1286 tempRoot,
1287 entries: ["index.html", "package.json", "src"],
1288 });
1289 const marker = "vite-spa-dev-marker";
1290 yield* fs.writeFileString(path.join(rootDir, "index.html"), htmlPage(marker));
1291
1292 const site = yield* stack.deploy(
1293 Effect.gen(function* () {
1294 return yield* Cloudflare.Website.Vite("ViteSpaDev", {
1295 ...viteProps(rootDir, ["index.html", "src/**", "package.json"]),
1296 assets: { notFoundHandling: "single-page-application" as const },
1297 dev: { port: 0 },
1298 });
1299 }),
1300 );
1301
1302 // Local identity: the url points at the alchemy dev proxy — no
1303 // cloud Worker exists.
1304 expect(site.url).toBeDefined();
1305 expect(site.url).toMatch(/^http:\/\/localhost:\d+/);
1306
1307 // The SPA shell serves at the root...
1308 yield* expectUrlContains(`${site.url!}/`, marker, {
1309 timeout: "60 seconds",
1310 label: "spa dev shell",
1311 });
1312 // ...and a deep link to an unregistered route falls back to the
1313 // shell so client-side routing can boot.
1314 yield* expectUrlContains(`${site.url!}/deep/link/route`, marker, {
1315 timeout: "30 seconds",
1316 label: "spa dev deep link fallback",
1317 });
1318 // The dev server serves the client module the shell references.
1319 yield* expectUrlContains(`${site.url!}/src/main.ts`, "hydrated", {
1320 timeout: "30 seconds",
1321 label: "spa dev module asset",
1322 });
1323 }).pipe(Effect.ensuring(stack.destroy().pipe(Effect.orDie).pipe(Effect.ignore)), logLevel),
1324 { tags: ["local"], timeout: 180_000 },
1325 );
1326
1327 devTest.provider(
1328 "Vite dev: TanStack Start keeps Alchemy-managed R2 bindings",
1329 (stack) =>
1330 Effect.gen(function* () {
1331 const { accountId } = yield* yield* CloudflareEnvironment;
1332 const fs = yield* FileSystem.FileSystem;
1333 const path = yield* Path.Path;
1334 const bucketNames = new Set<string>();
1335
1336 const cleanup = Effect.gen(function* () {
1337 yield* stack.destroy();
1338 for (const bucketName of bucketNames) {
1339 yield* waitForBucketToBeDeleted(bucketName, accountId);
1340 }
1341 });
1342
1343 const body = Effect.gen(function* () {
1344 yield* stack.destroy();
1345
1346 const rootDir = yield* cloneFixture(tanstackDevBindingsFixtureDir, {
1347 prefix: "alchemy-tanstack-dev-bindings-",
1348 tempRoot,
1349 entries: ["alchemy.run.ts", "package.json", "tsconfig.json", "vite.config.ts", "src"],
1350 });
1351 const indexRoutePath = path.join(rootDir, "src/routes/index.tsx");
1352 const memoInclude = [
1353 "src/**",
1354 "package.json",
1355 "tsconfig.json",
1356 "vite.config.ts",
1357 "alchemy.run.ts",
1358 ];
1359 const key = `dev-binding-${Date.now()}.txt`;
1360
1361 yield* fs.writeFileString(indexRoutePath, tanstackIndexRouteSource("hmr-marker-v1"));
1362
1363 const deploy = (bucketId: string, marker: string) =>
1364 stack.deploy(
1365 Effect.gen(function* () {
1366 const bucket = yield* Cloudflare.R2.Bucket(bucketId, { forceDestroy: true });
1367 const worker = yield* Cloudflare.Website.Vite("TanStackDevBindings", {
1368 ...viteProps(rootDir, memoInclude),
1369 assets: { runWorkerFirst: true },
1370 dev: { port: 0 },
1371 env: { BUCKET: bucket, DEV_MARKER: marker },
1372 });
1373 return { bucket, worker };
1374 }),
1375 );
1376
1377 const first = yield* deploy("DevBucketA", "dev-marker-v1");
1378 bucketNames.add(first.bucket.bucketName);
1379 expect(first.worker.url).toBeDefined();
1380 const r2Url = (base: string) => joinUrl(base, `/api/r2?key=${encodeURIComponent(key)}`);
1381 yield* expectUrlContains(joinUrl(first.worker.url!, "/"), "hmr-marker-v1", {
1382 timeout: "30 seconds",
1383 label: "tanstack dev initial route",
1384 });
1385
1386 const env1 = yield* fetchJsonReady<{ marker: string }>(r2Url(first.worker.url!));
1387 expect(env1.marker).toBe("dev-marker-v1");
1388
1389 const put1 = yield* putTextJsonReady<{ ok: boolean }>(
1390 r2Url(first.worker.url!),
1391 "from-a",
1392 );
1393 expect(put1.ok).toBe(true);
1394
1395 const get1 = yield* fetchJsonReady<{ value: string | null }>(r2Url(first.worker.url!));
1396 expect(get1.value).toBe("from-a");
1397
1398 // Change only a TanStack route file. The stack is not re-applied; the
1399 // local Vite server should render the updated route through the same
1400 // Alchemy proxy.
1401 yield* fs.writeFileString(indexRoutePath, tanstackIndexRouteSource("hmr-marker-v2"));
1402 yield* expectUrlContains(joinUrl(first.worker.url!, "/"), "hmr-marker-v2", {
1403 timeout: "30 seconds",
1404 label: "tanstack dev updated route",
1405 });
1406
1407 const second = yield* deploy("DevBucketB", "dev-marker-v2");
1408 bucketNames.add(second.bucket.bucketName);
1409 expect(second.worker.url).toBe(first.worker.url);
1410
1411 const env2 = yield* fetchJsonReady<{ marker: string }>(r2Url(second.worker.url!));
1412 expect(env2.marker).toBe("dev-marker-v2");
1413
1414 // The Worker was rebound to DevBucketB. The object written through
1415 // DevBucketA should not be visible through the new binding.
1416 const reboundRead = yield* fetchJsonReady<{ value: string | null }>(
1417 r2Url(second.worker.url!),
1418 );
1419 expect(reboundRead.value).toBeNull();
1420
1421 const put2 = yield* putTextJsonReady<{ ok: boolean }>(
1422 r2Url(second.worker.url!),
1423 "from-b",
1424 );
1425 expect(put2.ok).toBe(true);
1426
1427 const get2 = yield* fetchJsonReady<{ value: string | null }>(r2Url(second.worker.url!));
1428 expect(get2.value).toBe("from-b");
1429 });
1430
1431 const exit = yield* Effect.exit(body);
1432 if (Exit.isSuccess(exit)) {
1433 yield* cleanup;
1434 return exit.value;
1435 }
1436
1437 yield* cleanup.pipe(
1438 Effect.tapError((error) => Effect.logError("Vite dev live test cleanup failed", error)),
1439 Effect.ignore,
1440 );
1441 return yield* Effect.failCause(exit.cause);
1442 }).pipe(logLevel),
1443 { tags: ["provider:cloudflare:r2", "local"], timeout: 360_000 },
1444 );
1445 },
1446 );
1447
1448 const freshConn = HttpClient.mapRequest(HttpClientRequest.setHeader("connection", "close"));
1449
1450 // Both providers return `worker.url` as a bare origin these days, but an
1451 // external dev server URL parsed from stdout can still carry a trailing
1452 // slash. Join without producing a `//` path that the dev server's router
1453 // won't match.
1454 const joinUrl = (base: string, path: string) => `${base.replace(/\/+$/, "")}${path}`;
1455
1456 const fetchTextReady = (url: string) =>
1457 Effect.gen(function* () {
1458 const client = freshConn(yield* HttpClient.HttpClient);
1459 return yield* client.get(url).pipe(
1460 Effect.flatMap((res) =>
1461 res.status === 200 ? res.text : Effect.fail(new Error(`Worker not ready: ${res.status}`)),
1462 ),
1463 Effect.retry({
1464 // Capped interval, ~90s total budget (workers.dev propagation).
1465 schedule: Schedule.min([Schedule.exponential("500 millis"), Schedule.spaced("2 seconds")]),
1466 times: 45,
1467 }),
1468 Effect.orDie,
1469 );
1470 });
1471
1472 const fetchJsonReady = <T>(url: string) =>
1473 Effect.gen(function* () {
1474 const client = freshConn(yield* HttpClient.HttpClient);
1475 return yield* client.get(url).pipe(
1476 Effect.flatMap((res) =>
1477 res.status === 200
1478 ? Effect.flatMap(res.text, (body) =>
1479 Effect.try({
1480 try: () => JSON.parse(body) as T,
1481 catch: () => new Error(`non-json body: ${body}`),
1482 }),
1483 )
1484 : Effect.fail(new Error(`Worker not ready: ${res.status}`)),
1485 ),
1486 Effect.retry({
1487 // Capped interval, ~90s total budget (workers.dev / DO propagation).
1488 schedule: Schedule.min([Schedule.exponential("500 millis"), Schedule.spaced("2 seconds")]),
1489 times: 45,
1490 }),
1491 );
1492 });
1493
1494 // Retry a container-backed route until it answers 200 with a body containing
1495 // `expected` — the container's first request rides through image provisioning
1496 // and instance cold start, which comfortably outlasts fetchJsonReady's budget
1497 // (mirrors Container.test.ts's readiness poll).
1498 const fetchContainerReady = (url: string, expected: string) =>
1499 Effect.gen(function* () {
1500 const client = freshConn(yield* HttpClient.HttpClient);
1501 return yield* client.get(url).pipe(
1502 Effect.flatMap((res) =>
1503 res.text.pipe(
1504 Effect.flatMap((body) =>
1505 res.status === 200 && body.includes(expected)
1506 ? Effect.succeed(body)
1507 : Effect.fail(new Error(`container not ready: ${res.status} ${body.slice(0, 200)}`)),
1508 ),
1509 ),
1510 ),
1511 Effect.timeout("10 seconds"),
1512 Effect.retry({
1513 // Cap exponential backoff at 3s — snappy fast path without the
1514 // geometric blow-up dominating wall time on a slow rollout.
1515 schedule: Schedule.min([Schedule.exponential("500 millis"), Schedule.spaced("3 seconds")]),
1516 times: 60,
1517 }),
1518 );
1519 });
1520
1521 const putTextJsonReady = <T>(url: string, body: string) =>
1522 Effect.gen(function* () {
1523 return yield* HttpClient.execute(
1524 HttpClientRequest.put(url).pipe(HttpClientRequest.bodyText(body, "text/plain")),
1525 ).pipe(
1526 Effect.flatMap((res) =>
1527 res.status === 200
1528 ? Effect.flatMap(res.text, (responseBody) =>
1529 Effect.try({
1530 try: () => JSON.parse(responseBody) as T,
1531 catch: () => new Error(`non-json body: ${responseBody}`),
1532 }),
1533 )
1534 : Effect.fail(new Error(`Worker not ready: ${res.status}`)),
1535 ),
1536 Effect.retry({
1537 // Capped interval, ~90s total budget (workers.dev / DO propagation).
1538 schedule: Schedule.min([Schedule.exponential("500 millis"), Schedule.spaced("2 seconds")]),
1539 times: 45,
1540 }),
1541 );
1542 });
1543
1544 // Assert that the site's *current* client bundle contains `marker`.
1545 //
1546 // The bundle filename is content-addressed, so an env-only redeploy changes
1547 // the bundle URL referenced by `index.html`. A PoP can keep serving the
1548 // previous deployment's `index.html` for a while after the version flip
1549 // (cache-busting query params don't help when the whole deployment is stale
1550 // at that edge) — so discovering the bundle URL *once* and then polling that
1551 // asset latches onto the old, immutable bundle and times out waiting for a
1552 // marker that will never appear there. Instead, re-discover the bundle URL
1553 // from `index.html` on every attempt so the assertion converges as soon as
1554 // the new deployment propagates.
1555 const expectBundleContains = (siteUrl: string, marker: string, options: { label?: string } = {}) =>
1556 Effect.gen(function* () {
1557 const client = HttpClient.filterStatusOk(yield* HttpClient.HttpClient);
1558 yield* Effect.gen(function* () {
1559 // Cache-bust the index fetch — the unique query string defeats the
1560 // CDN cache key for caches that respect it.
1561 const res = yield* client.get(`${siteUrl}/`, {
1562 urlParams: { __alchemy_cb: String(Date.now()) },
1563 headers: { "cache-control": "no-cache", pragma: "no-cache" },
1564 });
1565 const html = yield* res.text;
1566 const match = html.match(/<script[^>]+src="(\/assets\/[^"]+\.js)"[^>]*>/i);
1567 if (!match) {
1568 // Fresh deploys can briefly return Cloudflare's "There is
1569 // nothing here yet" HTML page instead of the SPA index — retry.
1570 return yield* Effect.fail(
1571 new Error(`Could not find /assets/*.js script tag in HTML: ${html.slice(0, 200)}`),
1572 );
1573 }
1574 const bundleRes = yield* client.get(`${siteUrl}${match[1]}`, {
1575 urlParams: { __alchemy_cb: String(Date.now()) },
1576 headers: { "cache-control": "no-cache", pragma: "no-cache" },
1577 });
1578 const bundle = yield* bundleRes.text;
1579 if (!bundle.includes(marker)) {
1580 return yield* Effect.fail(
1581 new Error(`bundle ${match[1]} does not (yet) contain marker "${marker}"`),
1582 );
1583 }
1584 }).pipe(
1585 Effect.retry({
1586 // ~2 minutes total: capped exponential sampling through edge
1587 // propagation of both the fresh index.html and the new asset.
1588 schedule: Schedule.max([
1589 Schedule.min([Schedule.exponential("500 millis", 1.5), Schedule.spaced("5 seconds")]),
1590 Schedule.recurs(30),
1591 ]),
1592 }),
1593 Effect.tapError((error) =>
1594 Effect.logError(`expectBundleContains(${options.label ?? marker}) failed`, error),
1595 ),
1596 );
1597 });
1598
1599 const viteProps = (rootDir: string, memoInclude: string[]) => ({
1600 rootDir,
1601 workersDev: true,
1602 compatibility: { date: "2024-09-23", flags: ["nodejs_compat"] },
1603 memo: { include: memoInclude },
1604 });
1605
1606 const htmlPage = (marker: string) => `<!doctype html>
1607 <html lang="en">
1608 <head>
1609 <meta charset="UTF-8" />
1610 <title>${marker}</title>
1611 </head>
1612 <body>
1613 <div id="app">${marker}</div>
1614 <script type="module" src="/src/main.ts"></script>
1615 </body>
1616 </html>
1617 `;
1618
1619 const tanstackIndexRouteSource = (marker: string) => `
1620 /** @jsxImportSource react */
1621 import { createFileRoute } from "@tanstack/react-router";
1622
1623 const marker = ${JSON.stringify(marker)};
1624
1625 export const Route = createFileRoute("/")({
1626 component: Home,
1627 });
1628
1629 function Home() {
1630 return <main>{marker}</main>;
1631 }
1632 `;
1633
1634 const waitForBucketToBeDeleted = Effect.fn(function* (bucketName: string, accountId: string) {
1635 // Dev-mode buckets are purely virtual (`dev:`-prefixed identity) — there
1636 // is no cloud bucket to wait on, and the real API rejects the name.
1637 if (isLocalId(bucketName)) return;
1638 yield* r2.getBucket({ accountId, bucketName }).pipe(
1639 Effect.flatMap(() => Effect.fail(new BucketStillExists())),
1640 Effect.retry({
1641 while: (error): error is BucketStillExists => error instanceof BucketStillExists,
1642 schedule: Schedule.max([
1643 Schedule.min([Schedule.exponential("200 millis"), Schedule.spaced("2 seconds")]),
1644 Schedule.recurs(20),
1645 ]),
1646 }),
1647 Effect.catchTag("NoSuchBucket", () => Effect.void),
1648 );
1649 });
1650
1651 class BucketStillExists extends Data.TaggedError("BucketStillExists") {}