@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,576 lines 68 KB
Raw
1 import * as NodeHttp from "node:http";
2 import * as Cloudflare from "@alchemy.run/cloudflare";
3 import { CloudflareEnvironment } from "@alchemy.run/cloudflare/CloudflareEnvironment";
4 import { describe, expect } from "@alchemy.run/test";
5 import * as Test from "@alchemy.run/test/Alchemy";
6 import * as Cause from "effect/Cause";
7 import * as Effect from "effect/Effect";
8 import * as Exit from "effect/Exit";
9 import * as FileSystem from "effect/FileSystem";
10 import * as ChildProcess from "effect/process/ChildProcess";
11 import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";
12 import * as Redacted from "effect/Redacted";
13 import { MinimumLogLevel } from "effect/References";
14 import * as Schedule from "effect/Schedule";
15 import * as pathe from "pathe";
16 import { WebSocketServer } from "ws";
17 import { cloneFixture } from "../Utils/Fixture.ts";
18 import { expectResponse } from "../Utils/Http.ts";
19 import { expectWorkerExists, waitForWorkerToBeDeleted } from "../Utils/Worker.ts";
20
21 // Runtime features of a `Website.Vite` Worker, mirroring
22 // `@cloudflare/vite-plugin`'s runtime playgrounds (see
23 // `vite-runtime-fixture/src/index.ts` for the playground behind each route).
24 // Each spec runs deployed and under `alchemy dev`, as the plugin runs each in
25 // build and dev mode; checks of local-only endpoints run in dev only.
26
27 const { test } = Test.make({ providers: Cloudflare.providers() });
28 const { test: devTest } = Test.make({ providers: Cloudflare.providers(), dev: true });
29
30 const logLevel = Effect.provideService(MinimumLogLevel, process.env.DEBUG ? "Debug" : "Info");
31 const tempRoot = pathe.resolve(import.meta.dirname, "../../../.tmp");
32 const fixtureDir = pathe.resolve(import.meta.dirname, "vite-runtime-fixture");
33 const containerFixtureDir = pathe.resolve(import.meta.dirname, "vite-container-runtime-fixture");
34 const partyserverFixtureDir = pathe.resolve(import.meta.dirname, "vite-partyserver-fixture");
35 const sensitiveFilesFixtureDir = pathe.resolve(import.meta.dirname, "vite-sensitive-files-fixture");
36 const SENSITIVE_FILES = [
37 ".env",
38 ".env.staging",
39 ".dev.vars",
40 ".dev.vars.staging",
41 "worker-b/.env",
42 "worker-b/.env.staging",
43 "worker-b/.dev.vars",
44 "worker-b/.dev.vars.staging",
45 "alchemy.run.ts",
46 ".npmrc",
47 ".yarnrc",
48 ".yarnrc.yml",
49 "client.key",
50 "client.pfx",
51 "client.p12",
52 "client.p8",
53 "client.jks",
54 "custom-sensitive-file",
55 ];
56 const nodeEnvFixtureDir = pathe.resolve(import.meta.dirname, "vite-node-env-fixture");
57 const additionalModulesFixtureDir = pathe.resolve(
58 import.meta.dirname,
59 "vite-additional-modules-fixture",
60 );
61 const moduleResolutionFixtureDir = pathe.resolve(
62 import.meta.dirname,
63 "vite-module-resolution-fixture",
64 );
65 const mainResolutionFixtureDir = pathe.resolve(import.meta.dirname, "vite-main-resolution-fixture");
66 const workerFixtureDir = pathe.resolve(import.meta.dirname, "vite-worker-♫-fixture");
67 const childEnvironmentFixtureDir = pathe.resolve(
68 import.meta.dirname,
69 "vite-child-environment-fixture",
70 );
71 const errorsFixtureDir = pathe.resolve(import.meta.dirname, "vite-errors-fixture");
72 const multiWorkerFixtureDir = pathe.resolve(import.meta.dirname, "vite-multi-worker-fixture");
73 const customBuildAppFixtureDir = pathe.resolve(
74 import.meta.dirname,
75 "vite-custom-build-app-fixture",
76 );
77 const configChangesFixtureDir = pathe.resolve(import.meta.dirname, "vite-config-changes-fixture");
78 const hotChannelFixtureDir = pathe.resolve(import.meta.dirname, "vite-hot-channel-fixture");
79 const bundledDevFixtureDir = pathe.resolve(import.meta.dirname, "vite-bundled-dev-fixture");
80 const proxyFixtureDir = pathe.resolve(import.meta.dirname, "vite-proxy-fixture");
81 const pluginWebSocketFixtureDir = pathe.resolve(
82 import.meta.dirname,
83 "vite-plugin-websocket-fixture",
84 );
85
86 type Mode = "live" | "dev";
87
88 const deploySite = (stack: Test.ScratchStack, mode: Mode, options: { domain?: string } = {}) =>
89 Effect.gen(function* () {
90 const rootDir = yield* cloneFixture(fixtureDir, {
91 prefix: "alchemy-vite-runtime-",
92 tempRoot,
93 entries: ["package.json", "vite.config.ts", "src", "worker-b"],
94 });
95 return yield* stack.deploy(
96 Effect.gen(function* () {
97 const workerB = yield* Cloudflare.Worker(`ViteRuntimeWorkerB${mode}`, {
98 main: pathe.join(rootDir, "worker-b/index.ts"),
99 compatibility: { date: "2026-03-17" },
100 env: {
101 COUNTER: Cloudflare.DurableObject("Counter", { className: "Counter" }),
102 MY_WORKFLOW: Cloudflare.Workflow(`ViteRuntimeExternal${mode}`, {
103 className: "MyWorkflow",
104 }),
105 },
106 });
107 return yield* Cloudflare.Website.Vite(`ViteRuntime${mode}`, {
108 rootDir,
109 main: "./src/index.ts",
110 workersDev: true,
111 compatibility: { date: "2026-03-17", flags: ["nodejs_compat"] },
112 memo: { include: ["**/*"] },
113 crons: ["* * * * *"],
114 ...(options.domain ? { domain: options.domain } : {}),
115 env: {
116 KV: Cloudflare.KV.Namespace(`ViteRuntimeKv${mode}`),
117 IMAGES: Cloudflare.Images.Images(),
118 WAE: Cloudflare.AnalyticsEngine.Dataset("WAE", { dataset: "vite_runtime" }),
119 RATE_LIMITER: Cloudflare.RateLimit("RATE_LIMITER", {
120 namespaceId: 1001,
121 simple: { limit: 1, period: 60 },
122 }),
123 COUNTERS: Cloudflare.DurableObject("Counter", { className: "Counter" }),
124 LEGACY: Cloudflare.DurableObject("Legacy", { className: "Legacy" }),
125 // Cloudflare no longer creates key-value backed namespaces, so
126 // only the dev deploy declares one.
127 ...(mode === "dev"
128 ? {
129 KV_BACKED: Cloudflare.DurableObject("KvBacked", {
130 className: "KvBacked",
131 storage: "legacy-kv",
132 }),
133 }
134 : {}),
135 INITIALIZED: Cloudflare.DurableObject("BlockConcurrency", {
136 className: "BlockConcurrency",
137 }),
138 WEBSOCKET_SERVER: Cloudflare.DurableObject("WebSocketServer", {
139 className: "WebSocketServer",
140 }),
141 MY_WORKFLOW: Cloudflare.Workflow(`ViteRuntimeWorkflow${mode}`, {
142 className: "MyWorkflow",
143 }),
144 EXTERNAL_COUNTERS: Cloudflare.DurableObject("Counter", {
145 className: "Counter",
146 scriptName: workerB.workerName,
147 }),
148 EXTERNAL_WORKFLOW: Cloudflare.Workflow(`ViteRuntimeExternal${mode}`, {
149 className: "MyWorkflow",
150 scriptName: workerB.workerName,
151 }),
152 NAMED_ENTRYPOINT: Cloudflare.WorkerEntrypoint("NamedEntrypoint"),
153 LEGACY_ENTRYPOINT: Cloudflare.WorkerEntrypoint("legacy"),
154 STREAM: Cloudflare.Stream.Stream(),
155 EMAIL: Cloudflare.Email.SendEmail("EMAIL", {
156 allowedDestinationAddresses: ["recipient@example.com"],
157 }),
158 "importable-env_VAR": "my importable env variable",
159 "importable-env_SECRET": Redacted.make("my importable env secret"),
160 },
161 ...(mode === "dev" ? { dev: { port: 0 } } : {}),
162 });
163 }),
164 );
165 });
166
167 const runtimeTests = (
168 name: string,
169 check: (url: string, mode: Mode) => Effect.Effect<void, unknown>,
170 modes: ReadonlyArray<Mode> = ["live", "dev"],
171 ) => {
172 if (modes.includes("live")) {
173 test.provider(
174 name,
175 (stack) =>
176 Effect.gen(function* () {
177 const { accountId } = yield* yield* CloudflareEnvironment;
178 yield* stack.destroy();
179 const site = yield* deploySite(stack, "live");
180 yield* expectWorkerExists(site.workerName, accountId);
181 yield* check(site.url!.replace(/\/$/, ""), "live");
182 yield* stack.destroy();
183 yield* waitForWorkerToBeDeleted(site.workerName, accountId);
184 }).pipe(logLevel),
185 { tags: ["provider:cloudflare:worker", "live"], timeout: 360_000 },
186 );
187 }
188 if (modes.includes("dev")) {
189 devTest.provider(
190 `${name} (dev)`,
191 (stack) =>
192 Effect.gen(function* () {
193 yield* stack.destroy();
194 const site = yield* deploySite(stack, "dev");
195 yield* check(site.url!.replace(/\/$/, ""), "dev");
196 }).pipe(Effect.ensuring(stack.destroy().pipe(Effect.ignore)), logLevel),
197 { tags: ["provider:cloudflare:worker", "local"], timeout: 180_000 },
198 );
199 }
200 };
201
202 const expectText = (url: string, expected: string, init?: RequestInit) =>
203 expectResponse(
204 url,
205 (res) =>
206 res.status === 200 && res.body === expected
207 ? undefined
208 : `body ${JSON.stringify(res.body.slice(0, 120))}, expected ${JSON.stringify(expected)}`,
209 { label: `${url} → ${expected}`, ...(init?.headers ? { headers: init.headers as never } : {}) },
210 );
211
212 const expectJson = (url: string, expected: unknown) =>
213 expectResponse(
214 url,
215 (res) => {
216 if (res.status !== 200) return `status ${res.status}`;
217 try {
218 expect(JSON.parse(res.body)).toEqual(expected);
219 return undefined;
220 } catch {
221 return `json ${res.body.slice(0, 160)}`;
222 }
223 },
224 { label: `${url} → ${JSON.stringify(expected)}` },
225 );
226
227 // For calls that change state (increments): retries only a response that
228 // never reached the Worker (a Cloudflare HTML page while a fresh workers.dev
229 // URL propagates), so the Worker handles each call once.
230 const fetchText = (url: string, init?: RequestInit) =>
231 Effect.tryPromise(async () => {
232 const response = await fetch(url, init);
233 const body = await response.text();
234 if (/^\s*<(!DOCTYPE|html)/i.test(body))
235 throw new Error(`not from the Worker: ${response.status}`);
236 return { status: response.status, body };
237 }).pipe(Effect.retry({ times: 10, schedule: Schedule.spaced("2 seconds") }));
238
239 const unique = () => crypto.randomUUID().slice(0, 8);
240
241 // `workflows` and `external-workflows`: create an instance, then poll until
242 // it completes with the playground's output.
243 const expectWorkflow = (url: string, prefix: string) =>
244 Effect.gen(function* () {
245 const id = `vite-runtime-${unique()}`;
246 yield* expectResponse(`${url}${prefix}/create?id=${id}`, (res) =>
247 res.status === 200 ? undefined : `status ${res.status}`,
248 );
249 yield* expectResponse(
250 `${url}${prefix}/get?id=${id}`,
251 (res) => {
252 if (res.status !== 200) return `status ${res.status}`;
253 const status = JSON.parse(res.body) as { status: string; output?: unknown };
254 return status.status === "complete" && status.output === "Workflow output"
255 ? undefined
256 : `workflow ${res.body.slice(0, 160)}`;
257 },
258 { timeout: "120 seconds", label: `${prefix} completes` },
259 );
260 });
261
262 // `websockets`: a Durable Object answers string and ArrayBuffer messages.
263 const expectWebSocket = (url: string) =>
264 Effect.tryPromise(
265 () =>
266 new Promise<Array<string>>((resolve, reject) => {
267 const socket = new WebSocket(`${url.replace(/^http/, "ws")}/websocket`);
268 const received: Array<string> = [];
269 const timer = setTimeout(() => reject(new Error(`websocket: ${received}`)), 30_000);
270 socket.addEventListener("open", () => socket.send("Client event"));
271 socket.addEventListener("message", (event) => {
272 received.push(String(event.data));
273 if (received.length === 1) socket.send(new ArrayBuffer(10));
274 if (received.length === 2) {
275 clearTimeout(timer);
276 socket.close();
277 resolve(received);
278 }
279 });
280 socket.addEventListener("error", () => reject(new Error("websocket error")));
281 }),
282 ).pipe(
283 Effect.tap((received) =>
284 Effect.sync(() =>
285 expect(received).toEqual([
286 "Durable Object received client message: 'Client event' of type 'string'.",
287 "Durable Object received client message: '[object ArrayBuffer]' of type 'object'.",
288 ]),
289 ),
290 ),
291 Effect.retry({ times: 5, schedule: Schedule.spaced("3 seconds") }),
292 );
293
294 // Sends "hi" over a WebSocket and records what happens: `open`, the reply,
295 // and a `close` if the socket closes within half a second of the reply.
296 const echoOnce = (url: string) =>
297 Effect.tryPromise(
298 () =>
299 new Promise<Array<string>>((resolve, reject) => {
300 const socket = new WebSocket(url.replace(/^http/, "ws"));
301 const events: Array<string> = [];
302 const timer = setTimeout(() => reject(new Error(`echo: ${events}`)), 30_000);
303 const done = () => {
304 clearTimeout(timer);
305 resolve([...events]);
306 };
307 socket.addEventListener("open", () => {
308 events.push("open");
309 socket.send("hi");
310 });
311 socket.addEventListener("message", (event) => {
312 events.push(String(event.data));
313 setTimeout(() => {
314 // Bun's `close()` dispatches `close` synchronously.
315 done();
316 socket.close();
317 }, 500);
318 });
319 socket.addEventListener("close", (event) => {
320 events.push(`close ${event.code}`);
321 done();
322 });
323 }),
324 );
325
326 describe.concurrent(
327 "Vite runtime",
328 { tags: ["provider:cloudflare", "provider:cloudflare:website"] },
329 () => {
330 // `bindings/__tests__/worker.spec.ts`
331 runtimeTests(
332 "Vite runtime: KV, Images, Analytics Engine and Rate Limiting bindings",
333 (url, mode) =>
334 Effect.gen(function* () {
335 yield* expectText(`${url}/kv`, "KV binding works");
336 yield* expectText(`${url}/images`, "Images binding works");
337 yield* expectText(`${url}/ae`, "AE binding works");
338 // The limit is per key, so a fresh key starts with a full quota.
339 // Deployed, rate limiting is eventually consistent (counts are not
340 // shared at once), so the second call is only checked in dev, where
341 // the plugin's spec runs.
342 const limited = yield* fetchText(`${url}/rate-limit?key=${unique()}`);
343 expect(limited.body).toMatch(
344 mode === "dev"
345 ? /^Rate limit binding works: first: true, second: false$/
346 : /^Rate limit binding works: first: true, second: (true|false)$/,
347 );
348 }),
349 );
350
351 // `durable-objects` and `block-concurrency-while`
352 runtimeTests("Vite runtime: Durable Objects", (url, mode) =>
353 Effect.gen(function* () {
354 const name = `my-do-${unique()}`;
355 yield* expectText(`${url}/do?name=${name}`, `Durable Object '${name}' count: 0`);
356 for (const [path, count] of [
357 ["/do/increment", 1],
358 ["/do/increment", 2],
359 ["/do/decrement", 1],
360 ] as const) {
361 expect((yield* fetchText(`${url}${path}?name=${name}`)).body).toBe(
362 `Durable Object '${name}' count: ${count}`,
363 );
364 }
365 yield* expectText(`${url}/do/legacy`, "Legacy Durable Object");
366 yield* expectJson(`${url}/do/block-concurrency`, { isInitialized: true });
367 if (mode === "dev") {
368 yield* expectJson(`${url}/do/rpc-ordering?name=${unique()}`, { inOrder: true });
369 yield* expectJson(`${url}/do/kv-backed`, { hasSql: false });
370 }
371 yield* expectWebSocket(url);
372 }),
373 );
374
375 // A class declared `storage: "legacy-kv"` deploys with that backend, so a
376 // new one reaches Cloudflare's own refusal (it no longer provisions
377 // key-value backed namespaces) rather than silently becoming SQLite.
378 test.provider(
379 "Vite runtime: a new legacy-kv Durable Object reports Cloudflare's refusal",
380 (stack) =>
381 Effect.gen(function* () {
382 yield* stack.destroy();
383 const rootDir = yield* cloneFixture(fixtureDir, {
384 prefix: "alchemy-vite-runtime-kv-",
385 tempRoot,
386 entries: ["package.json", "worker-b"],
387 });
388 const exit = yield* stack
389 .deploy(
390 Cloudflare.Worker("ViteRuntimeKvBacked", {
391 main: pathe.join(rootDir, "worker-b/index.ts"),
392 compatibility: { date: "2026-03-17" },
393 env: {
394 COUNTER: Cloudflare.DurableObject("Counter", {
395 className: "Counter",
396 storage: "legacy-kv",
397 }),
398 },
399 }),
400 )
401 .pipe(Effect.exit);
402 expect(Exit.isFailure(exit)).toBe(true);
403 expect(String(Cause.squash((exit as Exit.Failure<never, unknown>).cause))).toContain(
404 "new namespaces must use storage: 'sqlite'",
405 );
406 yield* stack.destroy();
407 }).pipe(logLevel),
408 { tags: ["provider:cloudflare:worker", "live"], timeout: 360_000 },
409 );
410
411 // `external-durable-objects`
412 runtimeTests("Vite runtime: a Durable Object defined in another Worker", (url) =>
413 Effect.gen(function* () {
414 const name = `my-do-${unique()}`;
415 const body = (count: number) => `From worker-a: ${JSON.stringify({ name, count })}`;
416 yield* expectText(`${url}/external-do?name=${name}`, body(0));
417 expect((yield* fetchText(`${url}/external-do/increment?name=${name}`)).body).toBe(body(1));
418 expect((yield* fetchText(`${url}/external-do/increment?name=${name}`)).body).toBe(body(2));
419 yield* expectText(`${url}/external-do?name=${name}`, body(2));
420 }),
421 );
422
423 // `workflows` and `external-workflows`
424 runtimeTests("Vite runtime: Workflows, in this Worker and in another", (url) =>
425 Effect.gen(function* () {
426 yield* expectWorkflow(url, "/workflow");
427 yield* expectWorkflow(url, "/external-workflow");
428 }),
429 );
430
431 // `ctx-exports`, `same-worker-service-bindings`, `importable-env` and
432 // `explicit-resource-management`
433 runtimeTests("Vite runtime: entrypoints, the importable env and `using`", (url) =>
434 Effect.gen(function* () {
435 yield* expectText(
436 `${url}/ctx-exports/worker-entrypoint`,
437 "Hello World from a Worker Entrypoint",
438 );
439 yield* expectJson(`${url}/service/named`, { result: 20 });
440 yield* expectText(`${url}/service/legacy`, "Legacy Worker entrypoint");
441 const env = [
442 { key: "importable-env_SECRET", value: "my importable env secret" },
443 { key: "importable-env_VAR", value: "my importable env variable" },
444 ];
445 yield* expectResponse(`${url}/importable-env`, (res) => {
446 const json = JSON.parse(res.body) as {
447 importedAtModuleScope: string;
448 handlerEnv: typeof env;
449 importedEnv: typeof env;
450 };
451 const sorted = (entries: typeof env) =>
452 [...entries].sort((a, b) => a.key.localeCompare(b.key));
453 return json.importedAtModuleScope === "my importable env variable" &&
454 JSON.stringify(sorted(json.handlerEnv)) === JSON.stringify(env) &&
455 JSON.stringify(sorted(json.importedEnv)) === JSON.stringify(env)
456 ? undefined
457 : res.body.slice(0, 200);
458 });
459 yield* expectJson(`${url}/explicit-resource-management`, ["socket", "session"]);
460 }),
461 );
462
463 // `cron-triggers` and `email-worker`: local trigger and email endpoints.
464 runtimeTests(
465 "Vite runtime: scheduled and email handlers via the local trigger endpoints",
466 (url) =>
467 Effect.gen(function* () {
468 expect((yield* fetchText(`${url}/cdn-cgi/local/scheduled`)).body).toBe("ok");
469 const email = yield* fetchText(
470 `${url}/cdn-cgi/local/email?from=sender@example.com&to=recipient@example.com`,
471 {
472 method: "POST",
473 body: [
474 'From: "John" <sender@example.com>',
475 "To: recipient@example.com",
476 "Subject: Testing Email Workers Local Dev",
477 "Date: Tue, 27 Aug 2024 08:49:44 -0700",
478 "Message-ID: <6114391943504294873000@example.com>",
479 "",
480 "Hi there",
481 ].join("\r\n"),
482 },
483 );
484 expect(email.body).toBe("Worker successfully processed email");
485 yield* expectJson(`${url}/handled`, {
486 scheduled: "manual",
487 email: "sender@example.com Hi there",
488 });
489 yield* expectText(`${url}/send`, "Email message sent successfully!");
490 }),
491 ["dev"],
492 );
493
494 // `cron-triggers/__tests__/cf-worker-header.spec.ts`: outbound fetches
495 // carry `CF-Worker` with the Worker's first custom domain. Attaching a
496 // domain deploys only to a zone the account owns, so this runs in dev.
497 devTest.provider(
498 "Vite runtime: outbound fetches carry the custom domain as CF-Worker (dev)",
499 (stack) =>
500 Effect.gen(function* () {
501 const seen: Array<string | undefined> = [];
502 const echo = NodeHttp.createServer((req, res) => {
503 seen.push(req.headers["cf-worker"] as string | undefined);
504 res.setHeader("content-type", "application/json");
505 res.end(JSON.stringify({ cfWorker: req.headers["cf-worker"] ?? null }));
506 });
507 yield* Effect.acquireRelease(
508 Effect.promise(
509 () => new Promise<void>((resolve) => echo.listen(0, "127.0.0.1", resolve)),
510 ),
511 () => Effect.promise(() => new Promise<void>((resolve) => echo.close(() => resolve()))),
512 );
513 const echoUrl = `http://127.0.0.1:${(echo.address() as { port: number }).port}/`;
514 yield* stack.destroy();
515 const site = yield* deploySite(stack, "dev", { domain: "vite-runtime.example.com" });
516 const url = site.url!.replace(/\/$/, "");
517 yield* expectJson(`${url}/cf-worker-header?echoUrl=${encodeURIComponent(echoUrl)}`, {
518 cfWorker: "vite-runtime.example.com",
519 });
520 }).pipe(Effect.scoped, Effect.ensuring(stack.destroy().pipe(Effect.ignore)), logLevel),
521 { tags: ["provider:cloudflare:worker", "local"], timeout: 180_000 },
522 );
523
524 // `hot-channel` (dev only): custom events between the dev server and
525 // the Worker, from its module scope and its request scope.
526 devTest.provider(
527 "Vite runtime: custom events cross the Worker's hot channel (dev)",
528 (stack) =>
529 Effect.gen(function* () {
530 yield* stack.destroy();
531 const rootDir = yield* cloneFixture(hotChannelFixtureDir, {
532 prefix: "alchemy-vite-hot-channel-",
533 tempRoot,
534 entries: ["package.json", "vite.config.ts", "src"],
535 });
536 const site = yield* stack.deploy(
537 Cloudflare.Website.Vite("ViteHotChannel", {
538 rootDir,
539 main: "./src/index.ts",
540 workersDev: true,
541 compatibility: { date: "2026-03-17" },
542 memo: { include: ["**/*"] },
543 dev: { port: 0 },
544 }),
545 );
546 yield* expectJson(site.url!, [
547 "__server-event-data-received__",
548 "__worker-module-event-data-received__",
549 "__worker-request-event-data-received__",
550 ]);
551 }).pipe(Effect.ensuring(stack.destroy().pipe(Effect.ignore)), logLevel),
552 { tags: ["provider:cloudflare:worker", "local"], timeout: 180_000 },
553 );
554
555 // Vite's `server.proxy` (dev only): paths it matches go to its target,
556 // HTTP and WebSocket alike, and everything else to the Worker. HTTP paths
557 // in `runWorkerFirst` reach the Worker before the proxy, as with
558 // `@cloudflare/vite-plugin`.
559 devTest.provider(
560 "Vite runtime: server.proxy serves the paths it matches (dev)",
561 (stack) =>
562 Effect.gen(function* () {
563 const backend = NodeHttp.createServer((req, res) =>
564 res.end(`backend ${new URL(req.url ?? "/", "http://backend").pathname}`),
565 );
566 const wss = new WebSocketServer({ noServer: true });
567 backend.on("upgrade", (request, socket, head) =>
568 wss.handleUpgrade(request, socket, head, (ws) =>
569 ws.on("message", (data) => ws.send(`backend ${data}`)),
570 ),
571 );
572 yield* Effect.acquireRelease(
573 Effect.promise(
574 () => new Promise<void>((resolve) => backend.listen(0, "127.0.0.1", resolve)),
575 ),
576 () =>
577 Effect.promise(
578 () =>
579 new Promise<void>((resolve) => {
580 for (const client of wss.clients) client.terminate();
581 backend.closeAllConnections();
582 backend.close(() => resolve());
583 }),
584 ),
585 );
586 const target = `http://127.0.0.1:${(backend.address() as { port: number }).port}`;
587
588 yield* stack.destroy();
589 const rootDir = yield* cloneFixture(proxyFixtureDir, {
590 prefix: "alchemy-vite-proxy-",
591 tempRoot,
592 entries: ["package.json", "vite.config.ts", "src"],
593 });
594 const fs = yield* FileSystem.FileSystem;
595 yield* fs.writeFileString(
596 pathe.join(rootDir, "backend.json"),
597 JSON.stringify({ target }),
598 );
599 const site = yield* stack.deploy(
600 Cloudflare.Website.Vite("ViteProxy", {
601 rootDir,
602 main: "./src/index.ts",
603 workersDev: true,
604 compatibility: { date: "2026-03-17" },
605 memo: { include: ["**/*"] },
606 assets: { runWorkerFirst: ["/api/worker-first/*"] },
607 dev: { port: 0 },
608 }),
609 );
610 const url = site.url!.replace(/\/$/, "");
611
612 yield* expectText(`${url}/api/hello`, "backend /api/hello");
613 yield* expectText(`${url}/other`, "worker /other");
614 yield* expectText(`${url}/api/worker-first/x`, "worker /api/worker-first/x");
615 expect(yield* echoOnce(`${url}/backend-ws`)).toEqual(["open", "backend hi"]);
616 expect(yield* echoOnce(`${url}/bypass-ws`)).toEqual(["open", "backend hi"]);
617 expect(yield* echoOnce(`${url}/worker-ws`)).toEqual(["open", "worker hi"]);
618 }).pipe(Effect.scoped, Effect.ensuring(stack.destroy().pipe(Effect.ignore)), logLevel),
619 { tags: ["provider:cloudflare:worker", "local"], timeout: 180_000 },
620 );
621
622 // A Vite plugin's own dev WebSocket (dev only): the Worker doesn't route
623 // the path, so its 404 must not reach a socket the plugin accepts, at once
624 // or only after an `await` (#2191).
625 devTest.provider(
626 "Vite runtime: a plugin's own WebSocket stays open (dev)",
627 (stack) =>
628 Effect.gen(function* () {
629 yield* stack.destroy();
630 const rootDir = yield* cloneFixture(pluginWebSocketFixtureDir, {
631 prefix: "alchemy-vite-plugin-websocket-",
632 tempRoot,
633 entries: ["package.json", "vite.config.ts", "src"],
634 });
635 const site = yield* stack.deploy(
636 Cloudflare.Website.Vite("VitePluginWebSocket", {
637 rootDir,
638 main: "./src/index.ts",
639 workersDev: true,
640 compatibility: { date: "2026-03-17" },
641 memo: { include: ["**/*"] },
642 dev: { port: 0 },
643 }),
644 );
645 const url = site.url!.replace(/\/$/, "");
646 expect(yield* echoOnce(`${url}/__echo`)).toEqual(["open", "echo hi"]);
647 expect(yield* echoOnce(`${url}/__echo-async`)).toEqual(["open", "echo hi"]);
648 }).pipe(Effect.ensuring(stack.destroy().pipe(Effect.ignore)), logLevel),
649 { tags: ["provider:cloudflare:worker", "local"], timeout: 180_000 },
650 );
651
652 // Vite's bundled dev mode (`experimental.bundledDev`, dev only): the
653 // HTML shell comes from Vite's in-memory bundle, the API from the Worker.
654 devTest.provider(
655 "Vite runtime: Vite's bundled dev mode serves the HTML shell (dev)",
656 (stack) =>
657 Effect.gen(function* () {
658 yield* stack.destroy();
659 const rootDir = yield* cloneFixture(bundledDevFixtureDir, {
660 prefix: "alchemy-vite-bundled-dev-",
661 tempRoot,
662 entries: ["package.json", "vite.config.ts", "index.html", "src"],
663 });
664 const site = yield* stack.deploy(
665 Cloudflare.Website.Vite("ViteBundledDev", {
666 rootDir,
667 main: "./src/worker.ts",
668 workersDev: true,
669 compatibility: { date: "2026-03-17" },
670 memo: { include: ["**/*"] },
671 assets: { runWorkerFirst: ["/api"] },
672 dev: { port: 0 },
673 }),
674 );
675 const url = site.url!.replace(/\/$/, "");
676 yield* expectResponse(url, (res) =>
677 res.status === 200 && res.body.includes("<h1>bundled-dev-shell</h1>")
678 ? undefined
679 : `${res.status} ${res.body.slice(0, 300)}`,
680 );
681 yield* expectJson(`${url}/api`, { worker: "bundled-dev" });
682 }).pipe(Effect.ensuring(stack.destroy().pipe(Effect.ignore)), logLevel),
683 { tags: ["provider:cloudflare:worker", "local"], timeout: 180_000 },
684 );
685
686 // `containers` (dev only, as the plugin's spec): Durable Objects drive
687 // containers built from a local Dockerfile through `ctx.container`, one
688 // as the class's own image and one as a named image.
689 devTest.provider(
690 "Vite runtime: containers built from a Dockerfile start and serve (dev)",
691 (stack) =>
692 Effect.gen(function* () {
693 yield* stack.destroy();
694 const rootDir = yield* cloneFixture(containerFixtureDir, {
695 prefix: "alchemy-vite-container-runtime-",
696 tempRoot,
697 entries: ["package.json", "Dockerfile", "container", "src"],
698 });
699 const site = yield* stack.deploy(
700 Cloudflare.Website.Vite("ViteContainerRuntime", {
701 rootDir,
702 main: "./src/index.ts",
703 workersDev: true,
704 compatibility: { date: "2026-03-17" },
705 memo: { include: ["**/*"] },
706 env: {
707 DOCKERFILE: Cloudflare.Container("DockerfileContainer", {
708 className: "DockerfileContainer",
709 context: rootDir,
710 maxInstances: 2,
711 }),
712 NAMED_IMAGES: Cloudflare.DurableObject("NamedImagesContainer", {
713 className: "NamedImagesContainer",
714 containers: [
715 Cloudflare.Container("app", {
716 schedulingPolicy: "durable_object",
717 context: rootDir,
718 }),
719 ],
720 }),
721 },
722 dev: { port: 0 },
723 }),
724 );
725 const url = site.url!.replace(/\/$/, "");
726 yield* expectJson(`${url}/named-images/images`, ["app"]);
727 for (const prefix of ["/dockerfile", "/named-images"]) {
728 yield* expectText(`${url}${prefix}/start`, "Container create request sent...");
729 yield* expectText(`${url}${prefix}/status`, "true");
730 yield* expectText(`${url}${prefix}/fetch`, "Hello World!");
731 }
732 // Deleting the site stops the containers its Workers started.
733 yield* stack.destroy();
734 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
735 const containers = yield* spawner.lines(
736 ChildProcess.make("docker", ["ps", "--all", "--format", "{{.Names}}"]),
737 );
738 expect(
739 containers.filter(
740 (name) =>
741 name.startsWith("workerd-cloudflare-website-viteruntime") &&
742 /-(DockerfileContainer|NamedImagesContainer)-/.test(name),
743 ),
744 ).toEqual([]);
745 }).pipe(Effect.ensuring(stack.destroy().pipe(Effect.ignore)), logLevel),
746 {
747 tags: ["provider:cloudflare:container", "provider:cloudflare:worker", "local"],
748 timeout: 300_000,
749 },
750 );
751
752 // `partyserver`: PartyServer routes a room's WebSocket to its Durable
753 // Object, which answers the client's message (the playground's React
754 // client, driven here over a raw WebSocket).
755 for (const mode of ["live", "dev"] as const) {
756 (mode === "live" ? test : devTest).provider(
757 `Vite runtime: PartyServer rooms answer over WebSockets${mode === "dev" ? " (dev)" : ""}`,
758 (stack) =>
759 Effect.gen(function* () {
760 yield* stack.destroy();
761 const rootDir = yield* cloneFixture(partyserverFixtureDir, {
762 prefix: "alchemy-vite-partyserver-",
763 tempRoot,
764 entries: ["package.json", "index.html", "worker"],
765 });
766 const site = yield* stack.deploy(
767 Cloudflare.Website.Vite(`VitePartyServer${mode}`, {
768 rootDir,
769 main: "./worker/index.ts",
770 workersDev: true,
771 compatibility: { date: "2024-12-30" },
772 memo: { include: ["**/*"] },
773 assets: { notFoundHandling: "single-page-application" },
774 env: {
775 MyServer: Cloudflare.DurableObject("MyServer", { className: "MyServer" }),
776 },
777 ...(mode === "dev" ? { dev: { port: 0 } } : {}),
778 }),
779 );
780 const url = site.url!.replace(/\/$/, "");
781 yield* expectResponse(`${url}/`, (res) =>
782 res.body.includes("Vite + PartyServer")
783 ? undefined
784 : `body ${res.body.slice(0, 120)}`,
785 );
786 const reply = yield* Effect.tryPromise(
787 () =>
788 new Promise<string>((resolve, reject) => {
789 const socket = new WebSocket(
790 `${url.replace(/^http/, "ws")}/parties/my-server/room1`,
791 );
792 const timer = setTimeout(() => reject(new Error("no reply")), 30_000);
793 socket.addEventListener("open", () => socket.send("Hello from the client!"));
794 socket.addEventListener("message", (event) => {
795 clearTimeout(timer);
796 socket.close();
797 resolve(String(event.data));
798 });
799 socket.addEventListener("error", () => reject(new Error("websocket error")));
800 }),
801 ).pipe(Effect.retry({ times: 5, schedule: Schedule.spaced("3 seconds") }));
802 expect(reply).toBe("Message from the server: received 'Hello from the client!'");
803 }).pipe(Effect.ensuring(stack.destroy().pipe(Effect.ignore)), logLevel),
804 {
805 tags: ["provider:cloudflare:worker", mode === "dev" ? "local" : "live"],
806 timeout: 300_000,
807 },
808 );
809 }
810
811 // `sensitive-files`: the dev server refuses secrets, credentials and
812 // the stack file (403), on top of a user's own `server.fs.deny`;
813 // deployed, they were never assets, so the Worker answers.
814 for (const mode of ["live", "dev"] as const) {
815 (mode === "live" ? test : devTest).provider(
816 `Vite runtime: sensitive files are never served${mode === "dev" ? " (dev)" : ""}`,
817 (stack) =>
818 Effect.gen(function* () {
819 yield* stack.destroy();
820 const rootDir = yield* cloneFixture(sensitiveFilesFixtureDir, {
821 prefix: "alchemy-vite-sensitive-files-",
822 tempRoot,
823 entries: [
824 "package.json",
825 "vite.config.ts",
826 "src",
827 "worker-b",
828 ...SENSITIVE_FILES.filter((file) => !file.startsWith("worker-b/")),
829 ],
830 });
831 const site = yield* stack.deploy(
832 Cloudflare.Website.Vite(`ViteSensitiveFiles${mode}`, {
833 rootDir,
834 main: "./src/index.ts",
835 workersDev: true,
836 compatibility: { date: "2024-12-30" },
837 memo: { include: ["**/*"] },
838 ...(mode === "dev" ? { dev: { port: 0 } } : {}),
839 }),
840 );
841 const url = site.url!.replace(/\/$/, "");
842 yield* expectText(`${url}/`, "Worker A response");
843 for (const file of SENSITIVE_FILES) {
844 yield* expectResponse(
845 `${url}/${file}`,
846 (res) =>
847 mode === "dev"
848 ? res.status === 403
849 ? undefined
850 : `status ${res.status}: ${res.body.slice(0, 80)}`
851 : res.body === "Worker A response"
852 ? undefined
853 : `body ${res.body.slice(0, 80)}`,
854 { label: `/${file}` },
855 );
856 }
857 }).pipe(Effect.ensuring(stack.destroy().pipe(Effect.ignore)), logLevel),
858 {
859 tags: ["provider:cloudflare:worker", mode === "dev" ? "local" : "live"],
860 timeout: 300_000,
861 },
862 );
863 }
864
865 // `node-env`: Vite replaces `process.env.NODE_ENV` in the Worker, with
866 // and without `nodejs_compat`; the build drops React's development code.
867 for (const mode of ["live", "dev"] as const) {
868 for (const nodejsCompat of [false, true]) {
869 const label = `${nodejsCompat ? " with nodejs_compat" : ""}${mode === "dev" ? " (dev)" : ""}`;
870 (mode === "live" ? test : devTest).provider(
871 `Vite runtime: process.env.NODE_ENV is replaced${label}`,
872 (stack) =>
873 Effect.gen(function* () {
874 yield* stack.destroy();
875 const rootDir = yield* cloneFixture(nodeEnvFixtureDir, {
876 prefix: "alchemy-vite-node-env-",
877 tempRoot,
878 entries: ["package.json", "src"],
879 });
880 const site = yield* stack.deploy(
881 Cloudflare.Website.Vite(`ViteNodeEnv${mode}${nodejsCompat ? "Compat" : ""}`, {
882 rootDir,
883 main: "./src/index.ts",
884 workersDev: true,
885 compatibility: {
886 date: "2024-12-30",
887 ...(nodejsCompat ? { flags: ["nodejs_compat"] } : {}),
888 },
889 memo: { include: ["**/*"] },
890 ...(mode === "dev" ? { dev: { port: 0 } } : {}),
891 }),
892 );
893 const nodeEnv = mode === "dev" ? "development" : "production";
894 yield* expectResponse(site.url!, (res) =>
895 res.body.includes("<h1>Server Side React</h1>") &&
896 res.body.includes(`The value of process.env.NODE_ENV is &quot;${nodeEnv}&quot;`)
897 ? undefined
898 : `body ${res.body.slice(0, 200)}`,
899 );
900 if (mode === "live") {
901 const fs = yield* FileSystem.FileSystem;
902 const files = yield* fs.readDirectory(rootDir, { recursive: true });
903 const bundles = files.filter(
904 (file) =>
905 /\.m?js$/.test(file) &&
906 !file.startsWith("src") &&
907 !file.includes("node_modules"),
908 );
909 expect(bundles.length).toBeGreaterThan(0);
910 for (const file of bundles) {
911 const code = yield* fs.readFileString(pathe.join(rootDir, file));
912 expect(code).not.toContain("react-dom.development.js");
913 expect(code).not.toContain("https://github.com/facebook/react");
914 }
915 }
916 }).pipe(Effect.ensuring(stack.destroy().pipe(Effect.ignore)), logLevel),
917 {
918 tags: ["provider:cloudflare:worker", mode === "dev" ? "local" : "live"],
919 timeout: 300_000,
920 },
921 );
922 }
923 }
924
925 // `additional-modules`: Data, Text and CompiledWasm modules by extension,
926 // through subpath imports, and on `new_module_registry` (dev, as the
927 // playground runs it).
928 for (const [mode, newModuleRegistry] of [
929 ["live", false],
930 ["dev", false],
931 ["dev", true],
932 ] as const) {
933 const label = `${newModuleRegistry ? " on new_module_registry" : ""}${mode === "dev" ? " (dev)" : ""}`;
934 (mode === "live" ? test : devTest).provider(
935 `Vite runtime: additional modules load${label}`,
936 (stack) =>
937 Effect.gen(function* () {
938 yield* stack.destroy();
939 const rootDir = yield* cloneFixture(additionalModulesFixtureDir, {
940 prefix: "alchemy-vite-additional-modules-",
941 tempRoot,
942 entries: ["package.json", "src"],
943 });
944 const site = yield* stack.deploy(
945 Cloudflare.Website.Vite(
946 `ViteAdditionalModules${mode}${newModuleRegistry ? "Registry" : ""}`,
947 {
948 rootDir,
949 main: "./src/index.ts",
950 workersDev: true,
951 compatibility: {
952 date: "2024-12-30",
953 ...(newModuleRegistry ? { flags: ["new_module_registry"] } : {}),
954 },
955 memo: { include: ["**/*"] },
956 ...(mode === "dev" ? { dev: { port: 0 } } : {}),
957 },
958 ),
959 );
960 const url = site.url!.replace(/\/$/, "");
961 const hello = (res: { body: string }) =>
962 res.body.includes("<h1>Hello world</h1>")
963 ? undefined
964 : `body ${res.body.slice(0, 120)}`;
965 yield* expectJson(`${url}/bin`, { byteLength: 342936 });
966 yield* expectResponse(`${url}/html`, hello);
967 yield* expectResponse(`${url}/subpath-html`, hello);
968 yield* expectResponse(`${url}/subpath-html-with-ext`, hello);
969 yield* expectText(`${url}/text`, "Example text content.\n");
970 yield* expectText(`${url}/sql`, "SELECT * FROM users;\n");
971 yield* expectText(`${url}/text2`, "Example text content 2");
972 yield* expectJson(`${url}/wasm`, { result: 7 });
973 yield* expectJson(`${url}/wasm-with-module-param`, { result: 11 });
974 yield* expectJson(`${url}/wasm-with-init-param`, { result: 15 });
975 }).pipe(Effect.ensuring(stack.destroy().pipe(Effect.ignore)), logLevel),
976 {
977 tags: ["provider:cloudflare:worker", mode === "dev" ? "local" : "live"],
978 timeout: 300_000,
979 },
980 );
981 }
982
983 // `module-resolution`: CommonJS `require` with and without extensions
984 // and of JSON, `cloudflare:*` imports from the Worker and from a package,
985 // a user alias, and an optimizeDeps-excluded package importing a virtual
986 // module, with and without `nodejs_compat`; `virtual-modules`: a
987 // plugin's virtual module imported by the Worker.
988 for (const mode of ["live", "dev"] as const) {
989 for (const nodejsCompat of [false, true]) {
990 const label = `${nodejsCompat ? " with nodejs_compat" : ""}${mode === "dev" ? " (dev)" : ""}`;
991 (mode === "live" ? test : devTest).provider(
992 `Vite runtime: modules resolve like the plugin${label}`,
993 (stack) =>
994 Effect.gen(function* () {
995 yield* stack.destroy();
996 const rootDir = yield* cloneFixture(moduleResolutionFixtureDir, {
997 prefix: "alchemy-vite-module-resolution-",
998 tempRoot,
999 entries: ["package.json", "vite.config.ts", "src", "packages"],
1000 });
1001 // The playground's `file:` dependencies, installed as pnpm
1002 // installs them: copied into `node_modules`.
1003 const fs = yield* FileSystem.FileSystem;
1004 for (const name of ["excludes", "imports", "requires"]) {
1005 yield* fs.copy(
1006 pathe.join(rootDir, "packages", name),
1007 pathe.join(rootDir, `node_modules/@playground/module-resolution-${name}`),
1008 );
1009 }
1010 const site = yield* stack.deploy(
1011 Cloudflare.Website.Vite(
1012 `ViteModuleResolution${mode}${nodejsCompat ? "Compat" : ""}`,
1013 {
1014 rootDir,
1015 main: "./src/index.ts",
1016 workersDev: true,
1017 compatibility: {
1018 date: "2024-12-30",
1019 ...(nodejsCompat ? { flags: ["nodejs_compat"] } : {}),
1020 },
1021 memo: { include: ["**/*"] },
1022 ...(mode === "dev" ? { dev: { port: 0 } } : {}),
1023 },
1024 ),
1025 );
1026 const url = site.url!.replace(/\/$/, "");
1027 yield* expectJson(`${url}/require-ext`, {
1028 "(requires/ext) hello.cjs (wrong-extension)": null,
1029 "(requires/ext) helloWorld": "hello (.js) world (.cjs)",
1030 "(requires/ext) world.js (wrong-extension)": null,
1031 });
1032 yield* expectJson(`${url}/require-no-ext`, {
1033 "(requires/no-ext) helloWorld": "hello (.js) world (.cjs)",
1034 });
1035 yield* expectJson(`${url}/require-json`, {
1036 "(requires/json) package name": "@playground/module-resolution-requires",
1037 "(requires/json) package version": "1.0.0",
1038 });
1039 // workerd names the built class `DurableObjectBase` (a workerd
1040 // quirk the playground notes for builds).
1041 const durableObjectName = (res: { status: number; body: string }) => {
1042 if (res.status !== 200) return `status ${res.status}`;
1043 const body = JSON.parse(res.body) as Record<string, string>;
1044 return Object.entries(body).every(([key, value]) =>
1045 key.includes("DurableObject.name") ? /^DurableObject(Base)?$/.test(value) : true,
1046 )
1047 ? undefined
1048 : `body ${res.body}`;
1049 };
1050 yield* expectResponse(`${url}/cloudflare-imports`, (res) => {
1051 const mismatch = durableObjectName(res);
1052 if (mismatch) return mismatch;
1053 const body = JSON.parse(res.body) as Record<string, string>;
1054 return body["(cloudflare:workers) WorkerEntrypoint.name"] === "WorkerEntrypoint" &&
1055 body["(cloudflare:sockets) typeof connect"] === "function"
1056 ? undefined
1057 : `body ${res.body}`;
1058 });
1059 yield* expectResponse(`${url}/external-cloudflare-imports`, (res) => {
1060 const mismatch = durableObjectName(res);
1061 if (mismatch) return mismatch;
1062 return "(EXTERNAL) (cloudflare:workers) DurableObject.name" in JSON.parse(res.body)
1063 ? undefined
1064 : `body ${res.body}`;
1065 });
1066 yield* expectText(`${url}/@alias/test`, "OK!");
1067 yield* expectText(`${url}/optimize-deps/exclude`, "Export from virtual module");
1068 yield* expectText(`${url}/virtual-module`, "virtual module");
1069 }).pipe(Effect.ensuring(stack.destroy().pipe(Effect.ignore)), logLevel),
1070 {
1071 tags: ["provider:cloudflare:worker", mode === "dev" ? "local" : "live"],
1072 timeout: 300_000,
1073 },
1074 );
1075 }
1076 }
1077
1078 // `main-resolution`: `main` as a path (with a custom entry file
1079 // extension), a package export, and a virtual module.
1080 for (const mode of ["live", "dev"] as const) {
1081 for (const variant of [
1082 { config: "default", main: "./src/index.ts", flags: [] },
1083 {
1084 config: "package-export-main",
1085 main: "@playground/main-resolution-package/entry",
1086 flags: ["nodejs_compat"],
1087 },
1088 { config: "virtual-module-main", main: "virtual:entry", flags: [] },
1089 ]) {
1090 (mode === "live" ? test : devTest).provider(
1091 `Vite runtime: main resolves as ${variant.config}${mode === "dev" ? " (dev)" : ""}`,
1092 (stack) =>
1093 Effect.gen(function* () {
1094 yield* stack.destroy();
1095 const rootDir = yield* cloneFixture(mainResolutionFixtureDir, {
1096 prefix: "alchemy-vite-main-resolution-",
1097 tempRoot,
1098 entries: ["package.json", "configs", "src", "package"],
1099 });
1100 const fs = yield* FileSystem.FileSystem;
1101 yield* fs.copyFile(
1102 pathe.join(rootDir, `configs/${variant.config}.ts`),
1103 pathe.join(rootDir, "vite.config.ts"),
1104 );
1105 // The playground's `file:` dependency, copied in as pnpm does.
1106 yield* fs.copy(
1107 pathe.join(rootDir, "package"),
1108 pathe.join(rootDir, "node_modules/@playground/main-resolution-package"),
1109 );
1110 const site = yield* stack.deploy(
1111 Cloudflare.Website.Vite(`ViteMainResolution${mode}${variant.config}`, {
1112 rootDir,
1113 main: variant.main,
1114 workersDev: true,
1115 compatibility: { date: "2024-12-30", flags: variant.flags },
1116 memo: { include: ["**/*"] },
1117 ...(mode === "dev" ? { dev: { port: 0 } } : {}),
1118 }),
1119 );
1120 if (variant.config === "default") {
1121 yield* expectJson(site.url!, {
1122 entry: "Root config",
1123 imported: "Root config import",
1124 });
1125 } else {
1126 yield* expectText(
1127 site.url!,
1128 variant.config === "package-export-main"
1129 ? "Package export as Worker entry file"
1130 : "Virtual module as Worker entry file",
1131 );
1132 }
1133 }).pipe(Effect.ensuring(stack.destroy().pipe(Effect.ignore)), logLevel),
1134 {
1135 tags: ["provider:cloudflare:worker", mode === "dev" ? "local" : "live"],
1136 timeout: 300_000,
1137 },
1138 );
1139 }
1140 }
1141
1142 // `worker-♫`: a project path with a non-ASCII character, Access
1143 // identity, forwarded host and protocol headers, logging, and a `base`
1144 // mount path.
1145 const deployWorkerSite = (stack: Test.ScratchStack, mode: Mode, config: "default" | "base") =>
1146 Effect.gen(function* () {
1147 const rootDir = yield* cloneFixture(workerFixtureDir, {
1148 prefix: "alchemy-vite-♫-",
1149 tempRoot,
1150 entries: ["package.json", "configs", "src"],
1151 });
1152 expect(rootDir).toContain("♫");
1153 const fs = yield* FileSystem.FileSystem;
1154 yield* fs.copyFile(
1155 pathe.join(rootDir, `configs/${config}.ts`),
1156 pathe.join(rootDir, "vite.config.ts"),
1157 );
1158 const site = yield* stack.deploy(
1159 Cloudflare.Website.Vite(`ViteWorker${mode}${config}`, {
1160 rootDir,
1161 main: "./src/index.ts",
1162 workersDev: true,
1163 compatibility: { date: "2024-12-30" },
1164 memo: { include: ["**/*"] },
1165 ...(mode === "dev"
1166 ? {
1167 dev: {
1168 port: 0,
1169 access: {
1170 aud: "vite-plugin-test-audience",
1171 identity: {
1172 email: "vite-plugin@example.com",
1173 name: "Vite Plugin Test User",
1174 },
1175 },
1176 },
1177 }
1178 : {}),
1179 }),
1180 );
1181 return site.url!.replace(/\/$/, "");
1182 });
1183
1184 test.provider(
1185 "Vite runtime: a Worker in a non-ASCII project path deploys",
1186 (stack) =>
1187 Effect.gen(function* () {
1188 yield* stack.destroy();
1189 const url = yield* deployWorkerSite(stack, "live", "default");
1190 yield* expectText(url, "Hello World!");
1191 }).pipe(Effect.ensuring(stack.destroy().pipe(Effect.ignore)), logLevel),
1192 { tags: ["provider:cloudflare:worker", "live"], timeout: 300_000 },
1193 );
1194
1195 devTest.provider(
1196 "Vite runtime: Worker request headers, Access and logs like the plugin (dev)",
1197 (stack) =>
1198 Effect.gen(function* () {
1199 yield* stack.destroy();
1200 const devLog = yield* Test.captureResourceLog("ViteWorkerdevdefault");
1201 const url = yield* deployWorkerSite(stack, "dev", "default");
1202 const host = new URL(url).host;
1203 yield* expectText(url, "Hello World!");
1204 yield* expectJson(`${url}/access`, {
1205 aud: "vite-plugin-test-audience",
1206 identity: { email: "vite-plugin@example.com", name: "Vite Plugin Test User" },
1207 });
1208 yield* expectText(`${url}/x-forwarded-host`, "example.com:8080", {
1209 headers: { "x-forwarded-host": "example.com:8080" },
1210 });
1211 yield* expectText(`${url}/x-forwarded-host`, host);
1212 yield* expectText(`${url}/host-header`, host);
1213 yield* expectResponse(
1214 `${url}/request-url`,
1215 (res) => (res.body.startsWith("https:") ? undefined : `url ${res.body}`),
1216 { headers: { "x-forwarded-proto": "https" } },
1217 );
1218 yield* expectResponse(`${url}/request-url`, (res) =>
1219 res.body.startsWith("http:") ? undefined : `url ${res.body}`,
1220 );
1221 // The Worker's console output reaches its resource log, including the
1222 // shared chunk's log that proves entry signatures are preserved,
1223 // and no unhandled rejection.
1224 yield* Effect.gen(function* () {
1225 const log = yield* devLog;
1226 for (const line of [
1227 "__preserves-entry-signatures__",
1228 "__console log__",
1229 "__console debug__",
1230 "__console warn__",
1231 "__console error__",
1232 ]) {
1233 expect(log).toContain(line);
1234 }
1235 expect(log).not.toContain("__unhandled rejection__");
1236 }).pipe(Effect.retry({ times: 10, schedule: Schedule.spaced("1 second") }));
1237 }).pipe(Effect.scoped, Effect.ensuring(stack.destroy().pipe(Effect.ignore)), logLevel),
1238 { tags: ["provider:cloudflare:worker", "local"], timeout: 300_000 },
1239 );
1240
1241 devTest.provider(
1242 "Vite runtime: a Worker serves under Vite's base path (dev)",
1243 (stack) =>
1244 Effect.gen(function* () {
1245 yield* stack.destroy();
1246 const url = yield* deployWorkerSite(stack, "dev", "base");
1247 yield* expectText(`${url}/custom-mount`, "Hello World!");
1248 yield* expectText(`${url}/custom-mount/a/b/c?path`, "/custom-mount/a/b/c");
1249 yield* expectText(`${url}/custom-mount/x-forwarded-host`, new URL(url).host);
1250 }).pipe(Effect.ensuring(stack.destroy().pipe(Effect.ignore)), logLevel),
1251 { tags: ["provider:cloudflare:worker", "local"], timeout: 300_000 },
1252 );
1253
1254 // `child-environment`: the Worker imports a module (with an additional
1255 // module and an environment-aware virtual module) from a child Vite
1256 // environment (dev only: the released plugin's build doesn't nest the
1257 // child output either; React Router RSC in Vite.test.ts covers builds).
1258 devTest.provider(
1259 `Vite runtime: a Worker imports its child environment (dev)`,
1260 (stack) =>
1261 Effect.gen(function* () {
1262 yield* stack.destroy();
1263 const rootDir = yield* cloneFixture(childEnvironmentFixtureDir, {
1264 prefix: "alchemy-vite-child-environment-",
1265 tempRoot,
1266 entries: ["package.json", "vite.config.ts", "src"],
1267 });
1268 const site = yield* stack.deploy(
1269 Cloudflare.Website.Vite("ViteChildEnvironment", {
1270 rootDir,
1271 main: "./src/index.ts",
1272 workersDev: true,
1273 compatibility: { date: "2024-12-30" },
1274 memo: { include: ["**/*"] },
1275 viteEnvironments: { entry: "parent", children: ["child"] },
1276 dev: { port: 0 },
1277 }),
1278 );
1279 const url = site.url!.replace(/\/$/, "");
1280 yield* expectText(url, "Hello from the child environment");
1281 yield* expectText(
1282 `${url}/additional-module`,
1283 "Hello from a child environment additional module\n",
1284 );
1285 }).pipe(Effect.ensuring(stack.destroy().pipe(Effect.ignore)), logLevel),
1286 {
1287 tags: ["provider:cloudflare:worker", "local"],
1288 timeout: 300_000,
1289 },
1290 );
1291
1292 // `errors` (dev only): an error thrown by the Worker comes back as Vite's
1293 // error page, whose overlay shows the message and the source-mapped
1294 // location.
1295 devTest.provider(
1296 "Vite runtime: Worker errors reach Vite's error page with source locations (dev)",
1297 (stack) =>
1298 Effect.gen(function* () {
1299 yield* stack.destroy();
1300 const rootDir = yield* cloneFixture(errorsFixtureDir, {
1301 prefix: "alchemy-vite-errors-",
1302 tempRoot,
1303 entries: ["package.json", "src"],
1304 });
1305 const site = yield* stack.deploy(
1306 Cloudflare.Website.Vite("ViteErrors", {
1307 rootDir,
1308 main: "./src/index.ts",
1309 workersDev: true,
1310 compatibility: { date: "2024-12-30" },
1311 memo: { include: ["**/*"] },
1312 env: { NAMED_ENTRYPOINT: Cloudflare.WorkerEntrypoint("NamedEntrypoint") },
1313 dev: { port: 0 },
1314 }),
1315 );
1316 const url = site.url!.replace(/\/$/, "");
1317 yield* expectText(url, "Fallback");
1318 for (const [path, message, location] of [
1319 ["/default-export", "a is not defined", "src/index.ts:24:"],
1320 // The stack shows where the entry called the named entrypoint
1321 // (as the plugin notes).
1322 ["/named-entrypoint", "b is not defined", "src/index.ts:"],
1323 ] as const) {
1324 const res = yield* Effect.tryPromise(async () => {
1325 const response = await fetch(`${url}${path}`, { headers: { accept: "text/html" } });
1326 return { status: response.status, body: await response.text() };
1327 });
1328 expect(res.status).toBe(500);
1329 expect(res.body).toContain(message);
1330 expect(res.body).toContain(location);
1331 }
1332 }).pipe(Effect.ensuring(stack.destroy().pipe(Effect.ignore)), logLevel),
1333 { tags: ["provider:cloudflare:worker", "local"], timeout: 300_000 },
1334 );
1335
1336 // `multi-worker`: a Vite Worker calls another Worker over service
1337 // bindings — fetch, RPC methods, promise pipelining, getters and a named
1338 // entrypoint.
1339 for (const mode of ["live", "dev"] as const) {
1340 (mode === "live" ? test : devTest).provider(
1341 `Vite runtime: a Vite Worker calls another Worker over service bindings${mode === "dev" ? " (dev)" : ""}`,
1342 (stack) =>
1343 Effect.gen(function* () {
1344 yield* stack.destroy();
1345 const rootDir = yield* cloneFixture(multiWorkerFixtureDir, {
1346 prefix: "alchemy-vite-multi-worker-",
1347 tempRoot,
1348 entries: ["package.json", "worker-a", "worker-b"],
1349 });
1350 const site = yield* stack.deploy(
1351 Effect.gen(function* () {
1352 const workerB = yield* Cloudflare.Worker(`ViteMultiWorkerB${mode}`, {
1353 main: pathe.join(rootDir, "worker-b/index.ts"),
1354 compatibility: { date: "2024-12-30" },
1355 });
1356 return yield* Cloudflare.Website.Vite(`ViteMultiWorkerA${mode}`, {
1357 rootDir,
1358 main: "./worker-a/index.ts",
1359 workersDev: true,
1360 compatibility: { date: "2024-12-30" },
1361 memo: { include: ["**/*"] },
1362 env: {
1363 WORKER_B: workerB,
1364 NAMED_ENTRYPOINT: Cloudflare.WorkerEntrypoint(workerB, "NamedEntrypoint"),
1365 },
1366 ...(mode === "dev" ? { dev: { port: 0 } } : {}),
1367 });
1368 }),
1369 );
1370 const url = site.url!.replace(/\/$/, "");
1371 yield* expectJson(url, { name: "Worker A" });
1372 yield* expectJson(`${url}/fetch`, { result: { name: "Worker B" } });
1373 yield* expectJson(`${url}/rpc-method`, { result: 9 });
1374 yield* expectJson(`${url}/rpc-method/promise-pipelining`, {
1375 result: "You made it! 🎉",
1376 });
1377 yield* expectJson(`${url}/rpc-getter`, { result: "Cloudflare" });
1378 yield* expectJson(`${url}/rpc-named-entrypoint`, { result: 20 });
1379 yield* expectJson(`${url}/rpc-named-entrypoint/promise-pipelining`, {
1380 result: "You made it! 🚀",
1381 });
1382 }).pipe(Effect.ensuring(stack.destroy().pipe(Effect.ignore)), logLevel),
1383 {
1384 tags: ["provider:cloudflare:worker", mode === "dev" ? "local" : "live"],
1385 timeout: 300_000,
1386 },
1387 );
1388 }
1389
1390 // `custom-build-app`: the user's own `buildApp` builds the site (the
1391 // Worker environment twice), which serves its page and its Worker.
1392 for (const mode of ["live", "dev"] as const) {
1393 (mode === "live" ? test : devTest).provider(
1394 `Vite runtime: a custom buildApp builds the site${mode === "dev" ? " (dev)" : ""}`,
1395 (stack) =>
1396 Effect.gen(function* () {
1397 yield* stack.destroy();
1398 const rootDir = yield* cloneFixture(customBuildAppFixtureDir, {
1399 prefix: "alchemy-vite-custom-build-app-",
1400 tempRoot,
1401 entries: ["package.json", "index.html", "vite.config.ts", "src"],
1402 });
1403 const site = yield* stack.deploy(
1404 Cloudflare.Website.Vite(`ViteCustomBuildApp${mode}`, {
1405 rootDir,
1406 main: "./src/index.ts",
1407 workersDev: true,
1408 compatibility: { date: "2024-12-30" },
1409 memo: { include: ["index.html", "src/**", "vite.config.ts", "package.json"] },
1410 ...(mode === "dev" ? { dev: { port: 0 } } : {}),
1411 }),
1412 );
1413 const url = site.url!.replace(/\/$/, "");
1414 yield* expectResponse(`${url}/`, (res) =>
1415 res.body.includes("<h1>HTML page</h1>")
1416 ? undefined
1417 : `body ${res.body.slice(0, 120)}`,
1418 );
1419 yield* expectText(`${url}/another-path`, "Worker response");
1420 if (mode === "live") {
1421 const fs = yield* FileSystem.FileSystem;
1422 expect(yield* fs.readFileString(pathe.join(rootDir, "build-app.log"))).toBe(
1423 "__before-build__\n__after-build__\n",
1424 );
1425 }
1426 }).pipe(Effect.ensuring(stack.destroy().pipe(Effect.ignore)), logLevel),
1427 {
1428 tags: ["provider:cloudflare:worker", mode === "dev" ? "local" : "live"],
1429 timeout: 300_000,
1430 },
1431 );
1432 }
1433
1434 // `config-changes` (dev only): a changed Worker config is served after
1435 // the next deploy, a broken one fails without wedging the next, and a
1436 // crashed workerd restarts.
1437 const deployConfigChanges = (
1438 stack: Test.ScratchStack,
1439 rootDir: string,
1440 myVar: string,
1441 main = "./src/index.ts",
1442 ) =>
1443 stack.deploy(
1444 Cloudflare.Website.Vite("ViteConfigChanges", {
1445 rootDir,
1446 main,
1447 workersDev: true,
1448 compatibility: { date: "2024-12-30" },
1449 memo: { include: ["**/*"] },
1450 env: { MY_VAR: myVar, MY_SECRET: Redacted.make("secret A") },
1451 dev: { port: 0 },
1452 }),
1453 );
1454 const configChangesBody = (myVar: string) =>
1455 `The value of MY_VAR is "${myVar}" and the value of MY_SECRET is "secret A"`;
1456
1457 devTest.provider(
1458 "Vite runtime: config changes are served after the next deploy (dev)",
1459 (stack) =>
1460 Effect.gen(function* () {
1461 yield* stack.destroy();
1462 const rootDir = yield* cloneFixture(configChangesFixtureDir, {
1463 prefix: "alchemy-vite-config-changes-",
1464 tempRoot,
1465 entries: ["package.json", "src"],
1466 });
1467 const one = yield* deployConfigChanges(stack, rootDir, "one");
1468 yield* expectText(one.url!, configChangesBody("one"));
1469 const two = yield* deployConfigChanges(stack, rootDir, "two");
1470 yield* expectText(two.url!, configChangesBody("two"));
1471 const broken = yield* deployConfigChanges(
1472 stack,
1473 rootDir,
1474 "two",
1475 "./src/missing-after-broken-update.ts",
1476 ).pipe(Effect.exit);
1477 expect(Exit.isFailure(broken)).toBe(true);
1478 expect(Cause.pretty((broken as Exit.Failure<never, unknown>).cause)).toContain(
1479 "Failed to resolve Worker entrypoint",
1480 );
1481 expect(Cause.pretty((broken as Exit.Failure<never, unknown>).cause)).toContain(
1482 'missing-after-broken-update.ts" for environment "ssr"',
1483 );
1484 const three = yield* deployConfigChanges(stack, rootDir, "three");
1485 yield* expectText(three.url!, configChangesBody("three"));
1486 }).pipe(Effect.ensuring(stack.destroy().pipe(Effect.ignore)), logLevel),
1487 { tags: ["provider:cloudflare:worker", "local"], timeout: 300_000 },
1488 );
1489
1490 devTest.provider(
1491 "Vite runtime: serves again after workerd crashes (dev)",
1492 (stack) =>
1493 Effect.gen(function* () {
1494 yield* stack.destroy();
1495 const rootDir = yield* cloneFixture(configChangesFixtureDir, {
1496 prefix: "alchemy-vite-config-changes-",
1497 tempRoot,
1498 entries: ["package.json", "src"],
1499 });
1500 const site = yield* deployConfigChanges(stack, rootDir, "one");
1501 const url = site.url!.replace(/\/$/, "");
1502 yield* expectText(url, configChangesBody("one"));
1503 const initialRuntimeId = (yield* fetchText(`${url}/__runtime-id`)).body;
1504 // The crashing request is not expected to complete.
1505 yield* Effect.promise(() =>
1506 fetch(`${url}/__crash-workerd`, { signal: AbortSignal.timeout(2_000) }).catch(
1507 () => undefined,
1508 ),
1509 );
1510 yield* expectResponse(`${url}/__runtime-id`, (res) =>
1511 res.status === 200 && res.body !== initialRuntimeId && res.body.length === 36
1512 ? undefined
1513 : `runtime ${res.status} ${res.body.slice(0, 80)}`,
1514 );
1515 yield* expectText(url, configChangesBody("one"));
1516 const two = yield* deployConfigChanges(stack, rootDir, "two");
1517 yield* expectText(two.url!, configChangesBody("two"));
1518 }).pipe(Effect.ensuring(stack.destroy().pipe(Effect.ignore)), logLevel),
1519 { tags: ["provider:cloudflare:worker", "local"], timeout: 300_000 },
1520 );
1521
1522 // Miniflare's outbound `cf.image` mock (dev only: deployed, `cf.image`
1523 // needs a zone with Image Transformations, which workers.dev lacks).
1524 devTest.provider(
1525 "Vite runtime: cf.image fetches are resized locally (dev)",
1526 (stack) =>
1527 Effect.gen(function* () {
1528 const fs = yield* FileSystem.FileSystem;
1529 // An 8x4 PNG, generated once with Sharp.
1530 const png = yield* fs.readFile(pathe.join(fixtureDir, "cf-image-source.png"));
1531 const origin = NodeHttp.createServer((_req, res) => {
1532 res.setHeader("content-type", "image/png");
1533 res.end(png);
1534 });
1535 yield* Effect.acquireRelease(
1536 Effect.promise(
1537 () => new Promise<void>((resolve) => origin.listen(0, "127.0.0.1", resolve)),
1538 ),
1539 () =>
1540 Effect.promise(() => new Promise<void>((resolve) => origin.close(() => resolve()))),
1541 );
1542 const imageUrl = `http://127.0.0.1:${(origin.address() as { port: number }).port}/a.png`;
1543 yield* stack.destroy();
1544 const site = yield* deploySite(stack, "dev");
1545 const response = yield* Effect.promise(() =>
1546 fetch(
1547 `${site.url!.replace(/\/$/, "")}/cf-image?imageUrl=${encodeURIComponent(imageUrl)}`,
1548 ),
1549 );
1550 const body = Buffer.from(yield* Effect.promise(() => response.arrayBuffer()));
1551 // A PNG's IHDR chunk holds its width and height at bytes 16-23.
1552 expect({
1553 resized: response.headers.get("cf-resized"),
1554 size: [body.readUInt32BE(16), body.readUInt32BE(20)],
1555 }).toEqual({ resized: "internal=ok/m", size: [4, 2] });
1556 }).pipe(Effect.scoped, Effect.ensuring(stack.destroy().pipe(Effect.ignore)), logLevel),
1557 { tags: ["provider:cloudflare:worker", "local"], timeout: 180_000 },
1558 );
1559
1560 // `stream-binding`: the preview URL is on the dev server's own origin
1561 // (the port it actually bound) under `/__cf_local/stream`.
1562 runtimeTests(
1563 "Vite runtime: Stream uploads return a local preview URL",
1564 (url) =>
1565 Effect.gen(function* () {
1566 const upload = yield* fetchText(`${url}/stream/upload`);
1567 const { preview, id } = JSON.parse(upload.body) as { preview: string; id: string };
1568 expect(id).toBeTruthy();
1569 expect(preview).toBe(`${new URL(url).origin}/__cf_local/stream/${id}/watch`);
1570 const video = yield* fetchText(preview);
1571 expect(video.status).toBe(200);
1572 }),
1573 ["dev"],
1574 );
1575 },
1576 );