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

main
ts 245 lines 10.1 KB
Raw
1 import {
2 makeSourceContext,
3 type SourceHash,
4 type SourceServices,
5 } from "@alchemy.run/cloudflare/Workers/Source";
6 import { hashViteInput, makeViteSource } from "@alchemy.run/cloudflare/Workers/Sources/Vite";
7 import type { WorkerProps } from "@alchemy.run/cloudflare/Workers/Worker";
8 import { describe, expect, it } from "@alchemy.run/test";
9 import { NodeServices } from "@effect/platform-node";
10 import { Artifacts, createArtifactStore, makeScopedArtifacts } from "alchemy/Artifacts";
11 import * as Effect from "effect/Effect";
12 import * as FileSystem from "effect/FileSystem";
13 import * as Path from "effect/Path";
14 import * as pathe from "pathe";
15 import { cloneFixture } from "../Utils/Fixture.ts";
16
17 // ─────────────────────────────────────────────────────────────────────
18 // Workspace-aware input-hash memoization (no cloud, no build)
19 //
20 // The `fixtures/monorepo-workspace` fixture mirrors ct's
21 // `packages/frontend-frameworks/fixtures/monorepo-workspace`: `app/` is the Vite root and `lib/` is a
22 // sibling directory (its own package.json, NOT a package-manager
23 // workspace member) that `app/src` imports by relative path. At build
24 // time the toolchain discovers `lib/` from the module graph and reports
25 // it as an external workspace; alchemy persists it (relative to the
26 // root) in `hash.additionalWorkspaces` and folds it into `hash.input` —
27 // the rebuild-deciding memo signal.
28 //
29 // These tests pin the memo machinery itself — `hashViteInput` and the
30 // vite source's `hash()` slots — without deploying or building:
31 // cross-workspace-boundary edits MUST bust the memo, while untouched
32 // recomputes stay memoized. The live deploy-level behavior is covered by
33 // "Vite: edits in a sibling workspace package bust the build memo" in
34 // Vite.test.ts.
35 // ─────────────────────────────────────────────────────────────────────
36
37 const fixtureDir = pathe.resolve(import.meta.dirname, "fixtures/monorepo-workspace");
38
39 // Explicit include globs, same discipline as the live Vite tests: the
40 // hash stays pinned to fixture sources. The lib workspace is hashed with
41 // the default (whole-directory) scope, exactly like auto-discovered
42 // workspaces in production.
43 const memoInclude = ["src/**", "vite.config.ts", "package.json"];
44
45 const provide = <A, E>(effect: Effect.Effect<A, E, SourceServices>) =>
46 effect.pipe(
47 Effect.provideService(Artifacts, makeScopedArtifacts(createArtifactStore(), "test")),
48 Effect.provide(NodeServices.layer),
49 Effect.scoped,
50 );
51
52 /** Clone the two-directory fixture into a temp dir (outside the repo, so
53 * no ancestor gitignore/lockfile leaks into the hash) and return paths. */
54 const setup = Effect.gen(function* () {
55 const path = yield* Path.Path;
56 const dir = yield* cloneFixture(fixtureDir, {
57 prefix: "alchemy-ws-memo-",
58 entries: ["app", "lib"],
59 });
60 return {
61 dir,
62 appDir: path.join(dir, "app"),
63 libGreeting: path.join(dir, "lib", "src", "greeting.ts"),
64 appServer: path.join(dir, "app", "src", "server.ts"),
65 };
66 });
67
68 const editLib = (libGreeting: string, marker: string) =>
69 Effect.gen(function* () {
70 const fs = yield* FileSystem.FileSystem;
71 yield* fs.writeFileString(
72 libGreeting,
73 `export const LIB_VERSION = "1.0.0";\n\nexport const greeting = (name: string): string =>\n ${JSON.stringify(marker)} + name;\n`,
74 );
75 });
76
77 describe(
78 "workspace-aware input-hash memo",
79 {
80 tags: [
81 "unit",
82 "provider:cloudflare",
83 "provider:cloudflare:website",
84 "provider:cloudflare:worker",
85 "local",
86 ],
87 },
88 () => {
89 it.effect("cross-workspace edits bust the memo; untouched recomputes stay memoized", () =>
90 provide(
91 Effect.gen(function* () {
92 const fs = yield* FileSystem.FileSystem;
93 const { appDir, libGreeting, appServer } = yield* setup;
94 const original = yield* fs.readFileString(libGreeting);
95
96 // `additionalWorkspaces` is persisted relative to the Vite root
97 // (see the live test's "../shared") — feed it back the same way
98 // the WorkerProvider does from `output.hash.additionalWorkspaces`.
99 const hash = () =>
100 hashViteInput(appDir, { include: memoInclude }, Effect.succeed(["../lib"]));
101
102 const h1 = yield* hash();
103 expect(h1.hash).toBeDefined();
104 expect(h1.workspaces).toEqual(["../lib"]);
105
106 // Untouched recompute ⇒ identical hash ⇒ the deploy memo holds.
107 const h2 = yield* hash();
108 expect(h2.hash).toEqual(h1.hash);
109
110 // Edit ONLY the sibling workspace — nothing under the Vite root
111 // changes — and the input hash must still bust.
112 yield* editLib(libGreeting, "ws-memo-edit-1");
113 const h3 = yield* hash();
114 expect(h3.hash).not.toEqual(h1.hash);
115
116 // The hash is content-derived: restoring the original bytes
117 // restores the original hash (machine/path independence).
118 yield* fs.writeFileString(libGreeting, original);
119 const h4 = yield* hash();
120 expect(h4.hash).toEqual(h1.hash);
121
122 // Build↔diff parity: at build time workspaces are discovered as
123 // ABSOLUTE paths from the module graph; at diff time the
124 // persisted ROOT-RELATIVE spelling is fed back. Both spellings
125 // of the same directory must hash identically or the
126 // rebuild-free diff could never report "unchanged".
127 const path = yield* Path.Path;
128 const absolute = yield* hashViteInput(
129 appDir,
130 { include: memoInclude },
131 Effect.succeed([path.resolve(appDir, "../lib")]),
132 );
133 expect(absolute.hash).toEqual(h1.hash);
134 expect(absolute.workspaces).toEqual(["../lib"]);
135
136 // Root edits keep busting the memo too, independently of the
137 // workspace slot.
138 const server = yield* fs.readFileString(appServer);
139 yield* fs.writeFileString(appServer, server.replace("/api/greeting", "/api/greeting-v2"));
140 const h5 = yield* hash();
141 expect(h5.hash).not.toEqual(h1.hash);
142 }),
143 ),
144 );
145
146 it.effect(
147 "without the workspace in the hash set, cross-boundary edits are invisible (control)",
148 () =>
149 provide(
150 Effect.gen(function* () {
151 const { appDir, libGreeting } = yield* setup;
152
153 const hash = () => hashViteInput(appDir, { include: memoInclude }, Effect.succeed([]));
154
155 const before = yield* hash();
156 yield* editLib(libGreeting, "ws-memo-control-edit");
157 const after = yield* hash();
158
159 // The control proves the signal in the test above comes from
160 // folding `../lib` into the hash — not from anything under the
161 // Vite root.
162 expect(after.hash).toEqual(before.hash);
163 expect(after.workspaces).toEqual([]);
164 }),
165 ),
166 );
167
168 it.effect(
169 "an explicit memo.workspaces array pins the workspace set and still busts on edits",
170 () =>
171 provide(
172 Effect.gen(function* () {
173 const { appDir, libGreeting } = yield* setup;
174
175 const hash = () =>
176 hashViteInput(
177 appDir,
178 { include: memoInclude, workspaces: [{ cwd: "../lib" }] },
179 // With an explicit workspace list the auto-discovered set is
180 // ignored entirely.
181 Effect.succeed(["../does-not-exist"]),
182 );
183
184 const before = yield* hash();
185 // Pinned workspaces don't persist an auto-discovery list.
186 expect(before.workspaces).toBeUndefined();
187
188 yield* editLib(libGreeting, "ws-memo-pinned-edit");
189 const after = yield* hash();
190 expect(after.hash).not.toEqual(before.hash);
191 }),
192 ),
193 );
194
195 it.effect("the vite source's hash() slots carry the persisted workspaces through diff", () =>
196 provide(
197 Effect.gen(function* () {
198 const { appDir, libGreeting } = yield* setup;
199
200 const vite = { rootDir: appDir, memo: { include: memoInclude } };
201 const source = makeViteSource(vite);
202 const props: WorkerProps = { vite };
203 const ctx = makeSourceContext({
204 id: "MonorepoApp",
205 fqn: "MonorepoApp",
206 workerName: "stack-monorepoapp-test-abc123",
207 props,
208 compatibility: { date: "2024-09-23", flags: [] },
209 stack: { name: "stack", stage: "test" },
210 });
211
212 // `previous` is `output.hash` from state: a prior build
213 // discovered `../lib` from the module graph and persisted it.
214 const previous: SourceHash = {
215 bundle: undefined,
216 assets: undefined,
217 input: undefined,
218 additionalWorkspaces: ["../lib"],
219 };
220
221 const slots1 = yield* source.hash(ctx, previous);
222 expect(slots1.input).toBeDefined();
223 expect(slots1.additionalWorkspaces).toEqual(["../lib"]);
224
225 // Same recipe as calling the machinery directly.
226 const direct = yield* hashViteInput(appDir, vite.memo, Effect.succeed(["../lib"]));
227 expect(slots1.input).toEqual(direct.hash);
228
229 // A cross-boundary edit changes the recomputed input slot — the
230 // WorkerProvider's `slots.input !== output.hash.input` diff then
231 // reports the update that triggers the rebuild.
232 yield* editLib(libGreeting, "ws-memo-source-edit");
233 const slots2 = yield* source.hash(ctx, previous);
234 expect(slots2.input).not.toEqual(slots1.input);
235
236 // Without persisted workspaces (fresh state) the hash set is
237 // just the root — documented by a differing input slot.
238 const slotsNoWs = yield* source.hash(ctx, undefined);
239 expect(slotsNoWs.additionalWorkspaces).toEqual([]);
240 expect(slotsNoWs.input).not.toEqual(slots2.input);
241 }),
242 ),
243 );
244 },
245 );