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

main
ts 894 lines 38.6 KB
Raw
1 import * as Cloudflare from "@alchemy.run/cloudflare";
2 import { CloudflareEnvironment } from "@alchemy.run/cloudflare/CloudflareEnvironment";
3 import { describe, expect } from "@alchemy.run/test";
4 import * as Test from "@alchemy.run/test/Alchemy";
5 import * as Command from "alchemy/Command";
6 import * as Output from "alchemy/Output";
7 import type * as Plan from "alchemy/Plan";
8 import { Stack } from "alchemy/Stack";
9 import { encodeState, type ResourceState, reviveState, State } from "alchemy/State";
10 import * as Config from "effect/Config";
11 import * as Duration from "effect/Duration";
12 import * as Effect from "effect/Effect";
13 import * as FileSystem from "effect/FileSystem";
14 import * as Path from "effect/Path";
15 import { MinimumLogLevel } from "effect/References";
16 import * as Schedule from "effect/Schedule";
17 import * as pathe from "pathe";
18 import { cloneFixture } from "../Utils/Fixture.ts";
19 import { expectUrlContains, expectUrlHeader } from "../Utils/Http.ts";
20 import { expectWorkerExists, waitForWorkerToBeDeleted } from "../Utils/Worker.ts";
21
22 const { test } = Test.make({ providers: Cloudflare.providers() });
23
24 const logLevel = Effect.provideService(MinimumLogLevel, process.env.DEBUG ? "Debug" : "Info");
25
26 const fixtureDir = pathe.resolve(import.meta.dirname, "staticsite-fixture");
27 const workerEntry = pathe.resolve(import.meta.dirname, "fixtures/worker.ts");
28
29 // Read back through `Config.String` by the #796 test below. Set at module
30 // load (collection time): `ConfigProvider.fromEnv` snapshots `process.env`
31 // when the test harness constructs the provider — BEFORE a test body runs —
32 // so setting this inside the test only ever satisfied the NEXT attempt
33 // (the failure was masked by the runner's default retry).
34 process.env.STATICSITE_ENV_TEST = "from-config";
35
36 describe.concurrent(
37 "StaticSite",
38 { tags: ["provider:cloudflare", "provider:cloudflare:website", "live"] },
39 () => {
40 test.provider(
41 "StaticSite: editing a source file republishes the assets in a single deploy",
42 (stack) =>
43 Effect.gen(function* () {
44 const { accountId } = yield* yield* CloudflareEnvironment;
45 const fs = yield* FileSystem.FileSystem;
46 const path = yield* Path.Path;
47
48 yield* stack.destroy();
49
50 const cwd = yield* cloneFixture(fixtureDir, {
51 prefix: "alchemy-staticsite-fix-",
52 entries: ["src", "build.sh"],
53 });
54 const indexPath = path.join(cwd, "src", "index.html");
55
56 // ── deploy 1: initial publish ──────────────────────────────────────
57 const v1Marker = `staticsite-v1-${Date.now()}`;
58 yield* fs.writeFileString(indexPath, htmlPage(v1Marker));
59
60 const site1 = yield* stack.deploy(
61 Effect.gen(function* () {
62 return yield* Cloudflare.Website.StaticSite("FixSite", staticSiteProps(cwd));
63 }),
64 );
65
66 expect(site1.url).toBeDefined();
67 expect(site1.hash?.assets).toBeDefined();
68 yield* expectWorkerExists(site1.workerName, accountId);
69 // End-to-end: the worker URL actually serves the v1 marker.
70 // Use a long timeout because workers.dev subdomains can take 60s+
71 // to propagate the very first time they're enabled.
72 yield* expectUrlContains(`${site1.url!}/index.html`, v1Marker, {
73 timeout: "120 seconds",
74 label: "deploy1 v1 marker",
75 });
76
77 // ── deploy 2: edit fixture, redeploy once ──────────────────────────
78 const v2Marker = `staticsite-v2-${Date.now()}`;
79 yield* fs.writeFileString(indexPath, htmlPage(v2Marker));
80
81 const site2 = yield* stack.deploy(
82 Effect.gen(function* () {
83 return yield* Cloudflare.Website.StaticSite("FixSite", staticSiteProps(cwd));
84 }),
85 );
86
87 expect(site2.hash?.assets).toBeDefined();
88 expect(site2.hash?.assets).not.toEqual(site1.hash?.assets);
89
90 // The single-deploy guarantee: after one redeploy, the new
91 // marker is reachable over HTTP. Before the fix, this failure
92 // mode is what users were hitting — the worker version finalized
93 // pointing at the previous asset manifest because the initial
94 // Worker.update read dist mid-write.
95 yield* expectUrlContains(`${site2.url!}/index.html`, v2Marker, {
96 timeout: "60 seconds",
97 label: "deploy2 v2 marker",
98 });
99 // And the v1 marker should be gone — i.e. the new deploy fully
100 // replaced the previous content rather than coexisting with it.
101 yield* expectUrlAbsent(`${site2.url!}/index.html`, v1Marker, { timeout: "30 seconds" });
102
103 yield* stack.destroy();
104 yield* waitForWorkerToBeDeleted(site1.workerName, accountId);
105 }).pipe(logLevel),
106 { tags: ["provider:cloudflare:worker"], timeout: 360_000 },
107 );
108
109 test.provider(
110 "StaticSite: class form deploys and serves the built assets",
111 (stack) =>
112 Effect.gen(function* () {
113 const { accountId } = yield* yield* CloudflareEnvironment;
114 const fs = yield* FileSystem.FileSystem;
115 const path = yield* Path.Path;
116
117 yield* stack.destroy();
118
119 const cwd = yield* cloneFixture(fixtureDir, {
120 prefix: "alchemy-staticsite-class-",
121 entries: ["src", "build.sh"],
122 });
123 const indexPath = path.join(cwd, "src", "index.html");
124
125 const marker = `staticsite-class-${Date.now()}`;
126 yield* fs.writeFileString(indexPath, htmlPage(marker));
127
128 const site1 = yield* stack.deploy(
129 Effect.gen(function* () {
130 return yield* class FixSite extends Cloudflare.Website.StaticSite<FixSite>()(
131 "FixSite",
132 staticSiteProps(cwd),
133 ) {};
134 }),
135 );
136
137 expect(site1.url).toBeDefined();
138 expect(site1.hash?.assets).toBeDefined();
139 yield* expectWorkerExists(site1.workerName, accountId);
140 yield* expectUrlContains(`${site1.url!}/index.html`, marker, {
141 timeout: "120 seconds",
142 label: "class form marker",
143 });
144
145 yield* stack.destroy();
146 yield* waitForWorkerToBeDeleted(site1.workerName, accountId);
147 }).pipe(logLevel),
148 { tags: ["provider:cloudflare:worker"], timeout: 360_000 },
149 );
150
151 // ─────────────────────────────────────────────────────────────────────
152 // Path-relocation / cross-machine state behavior
153 //
154 // `StaticSite` builds via `Build.Command` and hands its `outdir` +
155 // content hash to `Worker` as `AssetsWithHash`. The hash is the only
156 // thing the diff/keepAssets logic should care about — the recorded
157 // `path` is *not* an input. These tests pin that down so that:
158 //
159 // 1. State produced on machine A (e.g. a CI runner) can be
160 // re-applied on machine B without `NotFound` failures from a
161 // stale `path` lurking in state.
162 // 2. A worker-only edit, with `src/` byte-identical, keeps the
163 // asset manifest in place instead of re-uploading.
164 // 3. A genuine source edit (already covered above) bumps the
165 // hash and ships new bytes — repeated here for symmetry.
166 // ─────────────────────────────────────────────────────────────────────
167
168 test.provider(
169 "StaticSite: relocating the project (and deleting the old one) preserves hash.assets",
170 (stack) =>
171 Effect.gen(function* () {
172 const { accountId } = yield* yield* CloudflareEnvironment;
173 const fs = yield* FileSystem.FileSystem;
174 const path = yield* Path.Path;
175
176 yield* stack.destroy();
177
178 // Include `.gitignore` so `Build.Command`'s default memo skips
179 // `dist/` between deploys; without it, the build output from
180 // deploy 1 would shift the input hash on deploy 2 and force an
181 // unnecessary rebuild that defeats the test.
182 const cwdA = yield* cloneFixture(fixtureDir, {
183 prefix: "alchemy-staticsite-relocate-a-",
184 entries: ["src", "build.sh", ".gitignore"],
185 });
186
187 // Pin a deterministic marker so both deploys hash to the same
188 // bytes regardless of timestamps.
189 const marker = `staticsite-relocate-${Date.now()}`;
190 yield* fs.writeFileString(path.join(cwdA, "src", "index.html"), htmlPage(marker));
191
192 const site1 = yield* stack.deploy(
193 Effect.gen(function* () {
194 return yield* Cloudflare.Website.StaticSite("RelocSite", staticSiteProps(cwdA));
195 }),
196 );
197 expect(site1.hash?.assets).toBeDefined();
198 yield* expectUrlContains(`${site1.url!}/index.html`, marker, {
199 timeout: "120 seconds",
200 label: "deploy1 marker",
201 });
202
203 // Simulate the CI→local handoff: throw away the directory the
204 // first deploy ran in. Anything that still tries to readDir the
205 // recorded `outdir` will blow up here — the keepAssets path
206 // must not require it.
207 yield* fs.remove(cwdA, { recursive: true });
208
209 const cwdB = yield* cloneFixture(fixtureDir, {
210 prefix: "alchemy-staticsite-relocate-b-",
211 entries: ["src", "build.sh", ".gitignore"],
212 });
213 yield* fs.writeFileString(path.join(cwdB, "src", "index.html"), htmlPage(marker));
214
215 const site2 = yield* stack.deploy(
216 Effect.gen(function* () {
217 return yield* Cloudflare.Website.StaticSite("RelocSite", staticSiteProps(cwdB));
218 }),
219 );
220
221 // The build still runs (Build.Command always re-runs its
222 // command), but the resulting content hash is identical, so
223 // Worker takes the keepAssets path and the recorded
224 // `hash.assets` is stable.
225 expect(site2.hash?.assets).toEqual(site1.hash?.assets);
226 // And the URL keeps serving — i.e. we didn't lose the asset
227 // binding in the process.
228 yield* expectUrlContains(`${site2.url!}/index.html`, marker, {
229 timeout: "60 seconds",
230 label: "deploy2 marker",
231 });
232
233 yield* stack.destroy();
234 yield* waitForWorkerToBeDeleted(site1.workerName, accountId);
235 }).pipe(logLevel),
236 { tags: ["provider:cloudflare:worker"], timeout: 360_000 },
237 );
238
239 test.provider(
240 "StaticSite: a bundle-only change keeps the asset manifest (hash.assets stable)",
241 (stack) =>
242 Effect.gen(function* () {
243 const { accountId } = yield* yield* CloudflareEnvironment;
244 const fs = yield* FileSystem.FileSystem;
245 const path = yield* Path.Path;
246
247 yield* stack.destroy();
248
249 // Include `.gitignore` so the memo (which falls back to gitignore
250 // when not explicitly configured) skips `dist/` between deploys —
251 // otherwise the second `hashDirectory` would observe the build
252 // output from deploy 1 and produce a different input hash.
253 const cwd = yield* cloneFixture(fixtureDir, {
254 prefix: "alchemy-staticsite-bundle-only-",
255 entries: ["src", "build.sh", ".gitignore"],
256 });
257 const marker = `staticsite-bundle-only-${Date.now()}`;
258 yield* fs.writeFileString(path.join(cwd, "src", "index.html"), htmlPage(marker));
259 // Use a temp worker entry so we can edit it between deploys to
260 // shift `hash.bundle` without touching `src/`.
261 const workerDir = yield* fs.makeTempDirectory({
262 prefix: "alchemy-staticsite-bundle-only-entry-",
263 });
264 const workerPath = path.join(workerDir, "worker.ts");
265 const writeWorker = (variant: string) =>
266 fs.writeFileString(
267 workerPath,
268 `export default {
269 fetch: async () => new Response(${JSON.stringify(`bundle-only ${variant}`)}),
270 };
271 `,
272 );
273
274 const deploy = () =>
275 stack.deploy(
276 Effect.gen(function* () {
277 return yield* Cloudflare.Website.StaticSite("BundleOnlyStaticSite", {
278 ...staticSiteProps(cwd),
279 main: workerPath,
280 });
281 }),
282 );
283
284 yield* writeWorker("v1");
285 const v1 = yield* deploy();
286 expect(v1.hash?.assets).toBeDefined();
287 expect(v1.hash?.bundle).toBeDefined();
288 yield* expectUrlContains(`${v1.url!}/index.html`, marker, {
289 timeout: "120 seconds",
290 label: "v1 marker",
291 });
292
293 yield* writeWorker("v2");
294 const v2 = yield* deploy();
295 expect(v2.hash?.bundle).not.toEqual(v1.hash?.bundle);
296 expect(v2.hash?.assets).toEqual(v1.hash?.assets);
297 yield* expectUrlContains(`${v2.url!}/index.html`, marker, {
298 timeout: "60 seconds",
299 label: "v2 marker (assets unchanged)",
300 });
301
302 yield* stack.destroy();
303 yield* waitForWorkerToBeDeleted(v1.workerName, accountId);
304 }).pipe(logLevel),
305 { tags: ["provider:cloudflare:worker"], timeout: 360_000 },
306 );
307
308 test.provider(
309 "StaticSite: rebuilds when the build output is missing despite unchanged inputs",
310 (stack) =>
311 Effect.gen(function* () {
312 const { accountId } = yield* yield* CloudflareEnvironment;
313 const fs = yield* FileSystem.FileSystem;
314 const path = yield* Path.Path;
315
316 yield* stack.destroy();
317
318 const cwd = yield* cloneFixture(fixtureDir, {
319 prefix: "alchemy-staticsite-missing-output-",
320 entries: ["src", "build.sh", ".gitignore"],
321 });
322 const marker = `staticsite-missing-output-${Date.now()}`;
323 yield* fs.writeFileString(path.join(cwd, "src", "index.html"), htmlPage(marker));
324 const outdir = path.join(cwd, "dist");
325
326 const deploy = () =>
327 stack.deploy(
328 Effect.gen(function* () {
329 return yield* Cloudflare.Website.StaticSite(
330 "MissingOutputStaticSite",
331 staticSiteProps(cwd),
332 );
333 }),
334 );
335
336 const v1 = yield* deploy();
337 expect(v1.hash?.assets).toBeDefined();
338 expect(yield* fs.exists(outdir)).toBe(true);
339 yield* expectUrlContains(`${v1.url!}/index.html`, marker, {
340 timeout: "120 seconds",
341 label: "v1 marker",
342 });
343
344 // Blow away the build output without touching any inputs. The input
345 // hash is unchanged, so memoization alone would skip the rebuild — but
346 // the Build provider also detects the missing output and forces an
347 // update, otherwise the Worker would have no assets to publish.
348 yield* fs.remove(outdir, { recursive: true });
349 expect(yield* fs.exists(outdir)).toBe(false);
350
351 const v2 = yield* deploy();
352 // The build re-ran: the output directory is back and the asset hash is
353 // identical (same source content reproduced the same manifest).
354 expect(yield* fs.exists(outdir)).toBe(true);
355 expect(v2.hash?.assets).toEqual(v1.hash?.assets);
356 yield* expectUrlContains(`${v2.url!}/index.html`, marker, {
357 timeout: "60 seconds",
358 label: "v2 marker (output rebuilt)",
359 });
360
361 yield* stack.destroy();
362 yield* waitForWorkerToBeDeleted(v1.workerName, accountId);
363 }).pipe(logLevel),
364 { tags: ["provider:cloudflare:worker"], timeout: 360_000 },
365 );
366
367 // ─────────────────────────────────────────────────────────────────────
368 // #1056: the assets hash must be a string
369 //
370 // `Command.Build.hash` is a `{ input, output }` pair; `AssetsWithHash.hash`
371 // is a single `string` that the Worker compares with `!==` against the value
372 // it persisted. Handing the pair through made every redeploy dirty and
373 // re-uploaded the whole asset directory, because state round-trips through
374 // JSON and a freshly built object is never `===` its deserialized self.
375 // ─────────────────────────────────────────────────────────────────────
376
377 /**
378 * Round-trip every state row through JSON, exactly like a real state store.
379 *
380 * `test.provider`'s scratch store keeps rows in memory *by reference*, so an
381 * object-valued hash compares `===` against itself and this bug is invisible.
382 * `localState` (and R2, and the HTTP store) serialize on write and revive on
383 * read — that is what production plans diff against, so reproduce it here.
384 */
385 const roundTripState = Effect.gen(function* () {
386 const state = yield* yield* State;
387 const stk = yield* Stack;
388 const fqns = yield* state.list({ stack: stk.name, stage: stk.stage });
389 yield* Effect.forEach(fqns, (fqn) =>
390 Effect.gen(function* () {
391 const row = yield* state.get({ stack: stk.name, stage: stk.stage, fqn });
392 if (row === undefined) return;
393 yield* state.set({
394 stack: stk.name,
395 stage: stk.stage,
396 fqn,
397 value: JSON.parse(JSON.stringify(encodeState(row)), reviveState) as ResourceState,
398 });
399 }),
400 );
401 });
402
403 const actionOf = (plan: Plan.Plan, fqn: string) => plan.resources[fqn]?.action;
404
405 test.provider(
406 "StaticSite: redeploying an unchanged site is a noop (#1056)",
407 (stack) =>
408 Effect.gen(function* () {
409 const { accountId } = yield* yield* CloudflareEnvironment;
410 const fs = yield* FileSystem.FileSystem;
411 const path = yield* Path.Path;
412
413 yield* stack.destroy();
414
415 // `.gitignore` keeps `dist/` out of the build's input hash, so the
416 // second pass sees byte-identical inputs.
417 const cwd = yield* cloneFixture(fixtureDir, {
418 prefix: "alchemy-staticsite-noop-",
419 entries: ["src", "build.sh", ".gitignore"],
420 });
421 const marker = `staticsite-noop-${Date.now()}`;
422 yield* fs.writeFileString(path.join(cwd, "src", "index.html"), htmlPage(marker));
423
424 const program = () =>
425 Effect.gen(function* () {
426 return yield* Cloudflare.Website.StaticSite("NoopSite", staticSiteProps(cwd));
427 });
428
429 const site = yield* stack.deploy(program());
430 yield* expectWorkerExists(site.workerName, accountId);
431
432 yield* roundTripState;
433
434 // Zero source changes between the two passes, so nothing may plan as
435 // changed. This is the user-visible defect: before the fix the Worker
436 // planned `update` on every single deploy and re-uploaded the whole
437 // asset directory, forever.
438 const settled = yield* stack.plan(program());
439 expect(actionOf(settled, "NoopSite/Build")).toBe("noop");
440 // The Worker is declared at the site's own id (only Build/Dev are
441 // namespaced under it), so its plan row is keyed `NoopSite`.
442 expect(actionOf(settled, "NoopSite")).toBe("noop");
443
444 // ...because the persisted hash is the build's `output` hash — the
445 // content hash of the uploaded bytes — and not the `{ input, output }`
446 // pair, which never compares equal to its own deserialized self.
447 expect(typeof site.hash?.assets).toBe("string");
448
449 yield* stack.destroy();
450 yield* waitForWorkerToBeDeleted(site.workerName, accountId);
451 }).pipe(logLevel),
452 { tags: ["provider:cloudflare:worker"], timeout: 360_000 },
453 );
454
455 test.provider(
456 "StaticSite: a memo:false build has no hash and still uploads the assets",
457 (stack) =>
458 Effect.gen(function* () {
459 const { accountId } = yield* yield* CloudflareEnvironment;
460 const fs = yield* FileSystem.FileSystem;
461 const path = yield* Path.Path;
462
463 yield* stack.destroy();
464
465 const cwd = yield* cloneFixture(fixtureDir, {
466 prefix: "alchemy-staticsite-no-memo-",
467 entries: ["src", "build.sh", ".gitignore"],
468 });
469 const marker = `staticsite-no-memo-${Date.now()}`;
470 yield* fs.writeFileString(path.join(cwd, "src", "index.html"), htmlPage(marker));
471
472 const site = yield* stack.deploy(
473 Effect.gen(function* () {
474 return yield* Cloudflare.Website.StaticSite("NoMemoSite", {
475 ...staticSiteProps(cwd),
476 memo: false,
477 });
478 }),
479 );
480
481 // `memo: false` computes no hashes, so the site hands the Worker
482 // `hash: undefined` — the hash-*less* shape, which must make the
483 // Worker hash `outdir` itself. Reading an explicit `undefined` as a
484 // supplied hash instead makes a greenfield create compare `undefined
485 // === undefined`, set `skip`, and publish a Worker with no assets.
486 expect(site.hash?.assets).toBeDefined();
487 yield* expectWorkerExists(site.workerName, accountId);
488 yield* expectUrlContains(`${site.url!}/index.html`, marker, {
489 timeout: "120 seconds",
490 label: "memo:false marker",
491 });
492
493 yield* stack.destroy();
494 yield* waitForWorkerToBeDeleted(site.workerName, accountId);
495 }).pipe(logLevel),
496 { tags: ["provider:cloudflare:worker"], timeout: 360_000 },
497 );
498
499 // ─────────────────────────────────────────────────────────────────────
500 // Legacy state migration
501 //
502 // `StaticSite`'s build sub-resource was renamed `Build.Command` →
503 // `Command.Build` and its `attr.hash` shape changed from a bare `string`
504 // to `{ input, output }`. An existing deployment upgrading across the
505 // rename has the old row on disk. Deploying the new `StaticSite` over it
506 // must not error — it re-runs the build (the memoization shape changed)
507 // and republishes the assets, migrating the row to the new type.
508 // ─────────────────────────────────────────────────────────────────────
509 test.provider(
510 "StaticSite: deploys over legacy Build.Command state and republishes assets",
511 (stack) =>
512 Effect.gen(function* () {
513 const { accountId } = yield* yield* CloudflareEnvironment;
514 const fs = yield* FileSystem.FileSystem;
515 const path = yield* Path.Path;
516 const state = yield* yield* State;
517 const stk = yield* Stack;
518
519 yield* stack.destroy();
520
521 const cwd = yield* cloneFixture(fixtureDir, {
522 prefix: "alchemy-staticsite-migrate-",
523 entries: ["src", "build.sh", ".gitignore"],
524 });
525 const marker = `staticsite-migrate-${Date.now()}`;
526 yield* fs.writeFileString(path.join(cwd, "src", "index.html"), htmlPage(marker));
527
528 // Mirror `examples/.../Website__Build.json`: a pre-rename
529 // `Build.Command` row at the build sub-resource's FQN, carrying the
530 // legacy `attr.hash` string (pre-`{ input, output }`).
531 yield* state.set({
532 stack: stk.name,
533 stage: stk.stage,
534 fqn: "MigSite/Build",
535 value: {
536 status: "created",
537 fqn: "MigSite/Build",
538 logicalId: "Build",
539 instanceId: "606bcaf4c0a931156f5a314ba7b57fc3",
540 resourceType: "Build.Command",
541 props: { command: "bash build.sh", outdir: "dist", env: {} },
542 attr: {
543 outdir: "dist",
544 hash: "a41cbcecfdeb355f6f98130ca4ff8269d0ad5cc3a628f1918d956c71f859648c",
545 },
546 bindings: [],
547 providerVersion: 0,
548 downstream: ["MigSite/Worker"],
549 removalPolicy: "destroy",
550 namespace: { Id: "MigSite" },
551 } satisfies ResourceState,
552 });
553
554 const site = yield* stack.deploy(
555 Effect.gen(function* () {
556 return yield* Cloudflare.Website.StaticSite("MigSite", staticSiteProps(cwd));
557 }),
558 );
559
560 expect(site.url).toBeDefined();
561 expect(site.hash?.assets).toBeDefined();
562 yield* expectWorkerExists(site.workerName, accountId);
563 yield* expectUrlContains(`${site.url!}/index.html`, marker, {
564 timeout: "120 seconds",
565 label: "migrated site marker",
566 });
567
568 // The build sub-resource row migrated to the new resource type.
569 const build = (yield* state.get({
570 stack: stk.name,
571 stage: stk.stage,
572 fqn: "MigSite/Build",
573 })) as ResourceState | undefined;
574 expect(build?.resourceType).toBe("Command.Build");
575
576 yield* stack.destroy();
577 yield* waitForWorkerToBeDeleted(site.workerName, accountId);
578 }).pipe(logLevel),
579 { tags: ["provider:cloudflare:worker"], timeout: 360_000 },
580 );
581
582 // ─────────────────────────────────────────────────────────────────────
583 // Orphaned dev-server cleanup across the rename
584 //
585 // A prior `alchemy dev` run writes a `Build.DevServer` row at the
586 // StaticSite's `Dev` sub-resource FQN. A subsequent normal `deploy` never
587 // declares that dev resource, so the row is orphaned and must be torn
588 // down. Before the `Renamed("Build.DevServer" → "Command.Dev")` shim
589 // existed, that teardown failed: the engine couldn't resolve a provider
590 // for the now-nonexistent `Build.DevServer` type and the deploy errored.
591 // This guards that the deploy succeeds and the orphan is reaped.
592 // ─────────────────────────────────────────────────────────────────────
593 test.provider(
594 "StaticSite: deploys cleanly when a legacy Build.DevServer row is orphaned",
595 (stack) =>
596 Effect.gen(function* () {
597 const { accountId } = yield* yield* CloudflareEnvironment;
598 const fs = yield* FileSystem.FileSystem;
599 const path = yield* Path.Path;
600 const state = yield* yield* State;
601 const stk = yield* Stack;
602
603 yield* stack.destroy();
604
605 const cwd = yield* cloneFixture(fixtureDir, {
606 prefix: "alchemy-staticsite-orphan-dev-",
607 entries: ["src", "build.sh", ".gitignore"],
608 });
609 const marker = `staticsite-orphan-dev-${Date.now()}`;
610 yield* fs.writeFileString(path.join(cwd, "src", "index.html"), htmlPage(marker));
611
612 // Mirror `examples/.../Website__Dev.json`: a pre-rename
613 // `Build.DevServer` row left behind by an earlier `alchemy dev` run,
614 // sitting at the `Dev` sub-resource FQN that a normal deploy never
615 // declares.
616 yield* state.set({
617 stack: stk.name,
618 stage: stk.stage,
619 fqn: "MigSite/Dev",
620 value: {
621 status: "created",
622 fqn: "MigSite/Dev",
623 logicalId: "Dev",
624 instanceId: "b4ca740550ef6e2e409481cedf9314c7",
625 resourceType: "Build.DevServer",
626 props: { command: "zola serve", env: {} },
627 attr: { url: "http://127.0.0.1:1024" },
628 bindings: [],
629 providerVersion: 0,
630 downstream: ["MigSite/Worker"],
631 removalPolicy: "destroy",
632 namespace: { Id: "MigSite" },
633 } satisfies ResourceState,
634 });
635
636 const site = yield* stack.deploy(
637 Effect.gen(function* () {
638 return yield* Cloudflare.Website.StaticSite("MigSite", staticSiteProps(cwd));
639 }),
640 );
641
642 expect(site.url).toBeDefined();
643 yield* expectWorkerExists(site.workerName, accountId);
644 yield* expectUrlContains(`${site.url!}/index.html`, marker, {
645 timeout: "120 seconds",
646 label: "orphan-dev site marker",
647 });
648
649 // The orphaned dev-server row was reaped via the renamed provider.
650 const orphan = yield* state.get({
651 stack: stk.name,
652 stage: stk.stage,
653 fqn: "MigSite/Dev",
654 });
655 expect(orphan).toBeUndefined();
656
657 yield* stack.destroy();
658 yield* waitForWorkerToBeDeleted(site.workerName, accountId);
659 }).pipe(logLevel),
660 { tags: ["provider:cloudflare:worker"], timeout: 360_000 },
661 );
662
663 test.provider(
664 "StaticSite: build env resolves Config, Output, and JSON values (#796)",
665 (stack) =>
666 Effect.gen(function* () {
667 const fs = yield* FileSystem.FileSystem;
668 const path = yield* Path.Path;
669
670 yield* stack.destroy();
671
672 // A build that snapshots the env vars it receives into its output.
673 const cwd = yield* fs.makeTempDirectory({ prefix: "alchemy-staticsite-env-" });
674 yield* fs.writeFileString(
675 path.join(cwd, "build.sh"),
676 [
677 "#!/bin/bash",
678 "set -euo pipefail",
679 "mkdir -p dist",
680 "{",
681 ' echo "FROM_STRING=${FROM_STRING:-missing}"',
682 ' echo "FROM_CONFIG=${FROM_CONFIG:-missing}"',
683 ' echo "FROM_OUTPUT=${FROM_OUTPUT:-missing}"',
684 ' echo "FROM_OUTPUT_OBJECT=${FROM_OUTPUT_OBJECT:-missing}"',
685 ' echo "FROM_NULL=${FROM_NULL:-missing}"',
686 "} > dist/env.txt",
687 ].join("\n"),
688 );
689
690 // A sibling resource whose attributes provide real `Output` values.
691 const depCwd = yield* fs.makeTempDirectory({ prefix: "alchemy-staticsite-env-dep-" });
692 yield* fs.writeFileString(
693 path.join(depCwd, "build.sh"),
694 "#!/bin/bash\nmkdir -p dist\necho dep > dist/dep.txt\n",
695 );
696
697 // `STATICSITE_ENV_TEST` is set at module load (see top of file) —
698 // the harness's ConfigProvider snapshots process.env before the
699 // test body runs.
700 yield* stack.deploy(
701 Effect.gen(function* () {
702 const dep = yield* Command.Build("EnvDep", {
703 command: "bash build.sh",
704 shell: true,
705 cwd: depCwd,
706 outdir: "dist",
707 });
708 return yield* Cloudflare.Website.StaticSite("EnvSite", {
709 command: "bash build.sh",
710 shell: true,
711 cwd,
712 outdir: "dist",
713 workersDev: false,
714 env: {
715 FROM_STRING: "plain",
716 FROM_CONFIG: Config.String("STATICSITE_ENV_TEST"),
717 FROM_OUTPUT: dep.outdir,
718 FROM_OUTPUT_OBJECT: Output.map(dep.outdir, (dir) => ({ dir })),
719 // JS callers can pass `null`; it must serialize, not throw.
720 FROM_NULL: null as unknown as string,
721 },
722 });
723 }),
724 );
725
726 const envFile = yield* fs.readFileString(path.join(cwd, "dist", "env.txt"));
727 expect(envFile).toContain("FROM_STRING=plain");
728 expect(envFile).toContain("FROM_CONFIG=from-config");
729 // Resolved Output<string> — the dep's outdir path, not garbage.
730 const fromOutput = envFile.match(/FROM_OUTPUT=(.*)/)?.[1];
731 expect(fromOutput).toBeDefined();
732 expect(fromOutput).not.toBe("missing");
733 expect(fromOutput).toContain("dist");
734 expect(fromOutput).not.toContain("[object");
735 // Resolved Output<object> — serialized as JSON.
736 const fromOutputObject = envFile.match(/FROM_OUTPUT_OBJECT=(.*)/)?.[1];
737 expect(fromOutputObject).toContain('{"dir":');
738 expect(envFile).toContain("FROM_NULL=null");
739
740 yield* stack.destroy();
741 }).pipe(logLevel),
742 { timeout: 360_000 },
743 );
744
745 // ─────────────────────────────────────────────────────────────────────
746 // SPA fallback: `assets.notFoundHandling: "single-page-application"`
747 //
748 // An assets-only deploy (no `main`) where Cloudflare's asset layer
749 // answers every request itself: an unmatched deep link must fall back
750 // to `index.html` with a 200 so a client router can boot, while real
751 // assets keep serving their own bytes.
752 // ─────────────────────────────────────────────────────────────────────
753
754 test.provider(
755 "StaticSite: SPA not-found handling serves index.html for deep links",
756 (stack) =>
757 Effect.gen(function* () {
758 const { accountId } = yield* yield* CloudflareEnvironment;
759 const fs = yield* FileSystem.FileSystem;
760 const path = yield* Path.Path;
761
762 yield* stack.destroy();
763
764 const cwd = yield* cloneFixture(fixtureDir, {
765 prefix: "alchemy-staticsite-spa-",
766 entries: ["src", "build.sh", ".gitignore"],
767 });
768 // Deterministic marker: the shell content is the assertion target
769 // for both the direct fetch and the deep-link fallback.
770 const marker = "staticsite-spa-shell";
771 yield* fs.writeFileString(path.join(cwd, "src", "index.html"), htmlPage(marker));
772 // A sibling asset that must keep serving its own bytes, not the
773 // shell, under SPA handling.
774 yield* fs.writeFileString(
775 path.join(cwd, "src", "data.txt"),
776 "staticsite-spa-plain-asset",
777 );
778 // Binary assets whose uploads must carry real content types
779 // (avif/jpeg/webp/woff2 previously fell back to
780 // application/octet-stream).
781 for (const name of ["sample.avif", "sample.jpg", "sample.webp", "sample.woff2"]) {
782 yield* fs.writeFile(
783 path.join(cwd, "src", name),
784 new Uint8Array([0x00, 0x01, 0x02, 0x03]),
785 );
786 }
787
788 const site = yield* stack.deploy(
789 Effect.gen(function* () {
790 return yield* Cloudflare.Website.StaticSite("SpaSite", {
791 command: "bash build.sh",
792 shell: true,
793 cwd,
794 outdir: "dist",
795 workersDev: true,
796 compatibility: { date: "2024-01-01" },
797 // Assets-only (no `main`): with a Worker script in front,
798 // unmatched requests would invoke the Worker instead of the
799 // asset layer's not-found handling.
800 assets: { notFoundHandling: "single-page-application" },
801 });
802 }),
803 );
804
805 expect(site.url).toBeDefined();
806 expect(site.hash?.assets).toBeDefined();
807 yield* expectWorkerExists(site.workerName, accountId);
808
809 // The shell serves at its real path.
810 yield* expectUrlContains(`${site.url!}/index.html`, marker, {
811 timeout: "120 seconds",
812 label: "SPA shell at /index.html",
813 });
814
815 // A hard GET to a route that matches no asset falls back to the
816 // shell with a 200 — `expectUrlContains` requires `res.ok`, so a
817 // plain 404 can't satisfy this.
818 yield* expectUrlContains(`${site.url!}/app/deep/route`, marker, {
819 timeout: "60 seconds",
820 label: "deep link falls back to index.html",
821 });
822
823 // A real asset still serves its own bytes, not the shell.
824 const assetBody = yield* expectUrlContains(
825 `${site.url!}/data.txt`,
826 "staticsite-spa-plain-asset",
827 { timeout: "60 seconds", label: "plain asset with SPA handling" },
828 );
829 expect(assetBody).not.toContain(marker);
830
831 // Content types for common binary asset formats survive upload.
832 for (const [name, contentType] of [
833 ["sample.avif", "image/avif"],
834 ["sample.jpg", "image/jpeg"],
835 ["sample.webp", "image/webp"],
836 ["sample.woff2", "font/woff2"],
837 ] as const) {
838 yield* expectUrlHeader(`${site.url!}/${name}`, "content-type", contentType);
839 }
840
841 yield* stack.destroy();
842 yield* waitForWorkerToBeDeleted(site.workerName, accountId);
843 }).pipe(logLevel),
844 { tags: ["provider:cloudflare:worker"], timeout: 360_000 },
845 );
846 },
847 );
848
849 const staticSiteProps = (cwd: string): Cloudflare.Website.StaticSiteProps => ({
850 command: "bash build.sh",
851 shell: true,
852 cwd,
853 outdir: "dist",
854 main: workerEntry,
855 workersDev: true,
856 compatibility: { date: "2024-01-01" },
857 });
858
859 const htmlPage = (marker: string) => `<!doctype html>
860 <html>
861 <head><title>${marker}</title></head>
862 <body><h1>${marker}</h1></body>
863 </html>
864 `;
865
866 /**
867 * Inverse of `expectUrlContains`: succeeds once the marker is *absent*
868 * from the response, polling (bounded) for up to ~30s. A redeploy reaches
869 * Cloudflare's edge eventually: right after the new version first answers,
870 * an individual request can still land on a colo serving the previous
871 * version, so a single sample is not a valid "old content is gone" check.
872 */
873 const expectUrlAbsent = (url: string, marker: string, options: { timeout?: Duration.Input }) =>
874 Effect.gen(function* () {
875 yield* expectUrlContains(url, "<", { ...options, label: "page exists" });
876 const fetchBody = Effect.tryPromise(() => {
877 const u = new URL(url);
878 u.searchParams.set("__alchemy_cb", String(Date.now()));
879 return fetch(u, { cache: "no-store", headers: { "cache-control": "no-cache" } }).then((r) =>
880 r.text(),
881 );
882 }).pipe(Effect.retry({ schedule: Schedule.spaced("1 second"), times: 3 }));
883 const body = yield* fetchBody.pipe(
884 Effect.repeat({
885 schedule: Schedule.spaced("3 seconds"),
886 until: (b) => !b.includes(marker),
887 times: 10,
888 }),
889 );
890 expect(
891 body.includes(marker),
892 `expected URL ${url} to NOT contain "${marker}", but it did`,
893 ).toBe(false);
894 });