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

main
ts 323 lines 13.8 KB
Raw
1 import * as Cause from "effect/Cause";
2 import * as Effect from "effect/Effect";
3 import * as FileSystem from "effect/FileSystem";
4 import * as Path from "effect/Path";
5 import type { PlatformError } from "effect/PlatformError";
6 import type * as vite from "vite";
7 import { cachedFunction } from "../Util/cached-function.ts";
8 import { sha256 } from "../Util/index.ts";
9 import {
10 BundleError,
11 bundleErrorFromUnknown,
12 bundleOutputFromFiles,
13 type BundleFile,
14 type BundleOutput,
15 } from "./Bundle.ts";
16
17 export interface ViteBuildOutput {
18 readonly clientDirectory: string | undefined;
19 /**
20 * The client environment's resolved Vite `base`. The build rewrites
21 * every emitted asset URL with it, so the uploaded asset manifest must
22 * be keyed with the same prefix to agree with the HTML.
23 */
24 readonly base: string | undefined;
25 // This is emitted as an Effect instead of a value so we can process it in parallel with reading the client assets.
26 readonly serverBundle: Effect.Effect<BundleOutput | undefined, BundleError>;
27 readonly externalWorkspaces: Effect.Effect<Set<string>, PlatformError>;
28 }
29
30 // `@vitejs/plugin-rsc` writes these modules separately after build completes instead of emitting them as chunks.
31 // So, we need to detect them and read them from the file system manually.
32 const RSC_MANIFEST = {
33 "virtual:vite-rsc/assets-manifest": "__vite_rsc_assets_manifest.js",
34 "virtual:vite-rsc/environment-imports": "__vite_rsc_env_imports_manifest.js",
35 } as const;
36
37 /**
38 * Structural subset of `vite.Environment` used by the bundling helpers.
39 * Typed structurally rather than as `vite.Environment` so plugin hooks whose
40 * `this` context is typed against a different vite copy in the install graph
41 * (bun peer-variant duplication) still assign.
42 */
43 interface EnvironmentLike {
44 readonly name: string;
45 readonly config: {
46 readonly base: string;
47 readonly root: string;
48 readonly build: { readonly outDir: string };
49 };
50 }
51
52 /** Whether `directory` exists and is not empty. */
53 const isNonEmptyDirectory = Effect.fn(function* (
54 fs: FileSystem.FileSystem,
55 directory: string | undefined,
56 ) {
57 if (!directory || !(yield* fs.exists(directory))) return false;
58 return (yield* fs.readDirectory(directory)).length > 0;
59 });
60
61 /**
62 * A Vite plugin that collects the output of the build and makes it available as an Effect.
63 * @param entryEnvironment - The environment to use as the entry point for the server bundle. Defaults to "ssr".
64 */
65 export const viteBuildOutputPlugin = Effect.fn(function* ({
66 entryEnvironment = "ssr",
67 }: {
68 entryEnvironment?: string;
69 }) {
70 const fs = yield* FileSystem.FileSystem;
71 const path = yield* Path.Path;
72 let clientDirectory: string | undefined;
73 let base: string | undefined;
74 // Where the client build writes, and the `public/` it would copy. Read from
75 // the resolved config because the client environment may never build.
76 let clientOutDir: string | undefined;
77 let publicDir: string | undefined;
78 // Assets the entry environment imports by URL (`import url from
79 // "./logo.png"`), keyed by output file name. They belong with the static
80 // assets, not in the Worker bundle.
81 const importedAssets = new Map<string, string>();
82 let serverEntry: string | undefined;
83 // `undefined` for an output a plugin removed after writing it (Vike deletes
84 // its `.vite/manifest.json`): it isn't deployed, as with Wrangler.
85 const serverChunks = new Map<string, Effect.Effect<BundleFile | undefined, BundleError>>();
86 const maybeExternalWorkspaces = new Set<string>();
87
88 const findUp = yield* cachedFunction(
89 (dir: string, filenames: Array<string>): Effect.Effect<string | undefined, PlatformError> =>
90 Effect.filter(
91 filenames.map((filename) => path.join(dir, filename)),
92 fs.exists,
93 { concurrency: "unbounded" },
94 ).pipe(
95 Effect.flatMap(([match]) => {
96 if (match) {
97 return Effect.succeed(match);
98 }
99 const parent = path.dirname(dir);
100 if (parent === dir) {
101 return Effect.undefined;
102 }
103 return findUp(parent, filenames);
104 }),
105 ),
106 );
107 const collectExternalWorkspaces = (): Effect.Effect<Set<string>, PlatformError> =>
108 Effect.forEach(maybeExternalWorkspaces, (directory) =>
109 findUp(directory, ["package.json"]),
110 ).pipe(
111 Effect.map((paths) => new Set(paths.filter((file) => file !== undefined).map(path.dirname))),
112 );
113 const plugin: vite.Plugin = {
114 name: "alchemy:build-output",
115 sharedDuringBuild: true,
116 configResolved(config) {
117 const outDir = config.environments?.client?.build.outDir;
118 clientOutDir = outDir === undefined ? undefined : path.resolve(config.root, outDir);
119 publicDir = config.publicDir || undefined;
120 },
121 // Collect the client output directory and server chunks as each
122 // environment writes its bundle. We deliberately do NOT resolve the build
123 // result from a `buildApp` hook: on Vite 8, when a project declares no
124 // `builder.buildApp` (e.g. a plain client-only SPA), `builder.buildApp()`
125 // runs post-order `buildApp` hooks *before* the default environment builds,
126 // so a hook fires while the output is still empty (issue #792). Instead,
127 // `viteBuild` reads `output` *after* `builder.buildApp()` resolves — by
128 // which point every environment that actually built has run `writeBundle`.
129 async writeBundle(_, bundle) {
130 const root = path.resolve(this.environment.config.root);
131 for (const id of this.getModuleIds()) {
132 if (!path.isAbsolute(id) || id.includes("node_modules") || id.startsWith(root)) {
133 continue;
134 }
135 maybeExternalWorkspaces.add(path.dirname(id));
136 }
137 if (this.environment.name === "client") {
138 clientDirectory = path.resolve(root, this.environment.config.build.outDir);
139 base = this.environment.config.base;
140 return;
141 }
142 const files = Object.values(bundle);
143 if (this.environment.name === entryEnvironment) {
144 // Frameworks can add entries of their own (Vike's export-less
145 // `entry.mjs`), so prefer the `index` entry the Cloudflare plugin
146 // names the Worker, then one with exports.
147 const entryChunks = files.filter(
148 (file): file is vite.Rolldown.OutputChunk => file.type === "chunk" && file.isEntry,
149 );
150 const entryChunk =
151 entryChunks.find((chunk) => chunk.name === "index") ??
152 entryChunks.find((chunk) => chunk.exports.length > 0) ??
153 entryChunks[0];
154 if (!entryChunk) {
155 throw new Error(`Entry chunk not found for environment "${this.environment.name}"`);
156 }
157 serverEntry = fileName(entryChunk.fileName, this.environment);
158 }
159 const outDir = path.resolve(root, this.environment.config.build.outDir);
160 const urlAssets = new Set<string>();
161 for (const file of files) {
162 if (file.type !== "chunk" || this.environment.name !== entryEnvironment) continue;
163 const metadata = (file as { viteMetadata?: { importedAssets?: Set<string> } }).viteMetadata;
164 for (const asset of metadata?.importedAssets ?? []) {
165 urlAssets.add(asset);
166 importedAssets.set(asset, path.join(outDir, asset));
167 }
168 }
169 await Promise.all(
170 files.map(async (file) => {
171 if (file.type === "asset" && urlAssets.has(file.fileName)) return;
172 // Vite's build metadata (`.vite/manifest.json`), not a Worker module.
173 if (file.fileName.startsWith(".vite/")) return;
174 if (file.type === "chunk") {
175 file.imports
176 .filter((self): self is keyof typeof RSC_MANIFEST => self in RSC_MANIFEST)
177 .forEach((id) => {
178 // Key by the environment-prefixed path, NOT the bare manifest
179 // filename. `@vitejs/plugin-rsc` emits a copy of the same-named
180 // manifest into every environment's outDir (e.g. both
181 // `dist/rsc/__vite_rsc_assets_manifest.js` and
182 // `dist/ssr/__vite_rsc_assets_manifest.js`), and each
183 // environment's chunks import their own copy via a relative
184 // specifier. Keying by the bare filename collapses them into a
185 // single entry, dropping every copy but the last — so the
186 // entry worker's `import "../__vite_rsc_assets_manifest.js"`
187 // resolves to a module that isn't in the bundle and the
188 // deployed Worker fails at startup.
189 serverChunks.set(
190 fileName(RSC_MANIFEST[id], this.environment),
191 readOutputFile(RSC_MANIFEST[id], this.environment),
192 );
193 });
194 }
195 // Read back from disk once the build completes, as Wrangler deploys
196 // the output directory: plugins can rewrite written chunks in their
197 // own `writeBundle` (Vike inlines its assets manifest there).
198 serverChunks.set(
199 fileName(file.fileName, this.environment),
200 readOutputFile(file.fileName, this.environment),
201 );
202 }),
203 );
204 },
205 };
206
207 // The server bundle may include chunks from more than one Vite environment, so we need to prefix them with the environment-specific output directory.
208 // Flattening them doesn't work because of relative imports between environments.
209 //
210 // `build.outDir` can be resolved to an absolute path (e.g. `@vitejs/plugin-rsc`
211 // does this), which would leak the build machine's filesystem path into the
212 // worker module names and produce non-portable, leading-`/` specifiers that
213 // Cloudflare rejects. Normalize it back to a path relative to the project root
214 // so module names match the single-environment case (`dist/ssr/worker.js`).
215 const fileName = (name: string, environment: EnvironmentLike) => {
216 const outDir = environment.config.build.outDir;
217 const relativeOutDir = path.isAbsolute(outDir)
218 ? path.relative(environment.config.root, outDir)
219 : outDir;
220 // `path.relative` (and user-configured outDirs) yield backslashes on
221 // Windows; worker module names are import specifiers, so a name like
222 // `dist\ssr/index.js` deploys fine but can never be resolved by the
223 // entry's `import "ssr/index.js"` — the worker 1101s at request time.
224 return `${relativeOutDir.replaceAll("\\", "/")}/${name}`;
225 };
226
227 // Read an output file from the file system.
228 // This is only safe to run *after* the build has completed.
229 const readOutputFile = (name: string, environment: EnvironmentLike) => {
230 const file = path.resolve(environment.config.root, environment.config.build.outDir, name);
231 return fs.exists(file).pipe(
232 Effect.flatMap((exists) => (exists ? readFile(file, name, environment) : Effect.undefined)),
233 Effect.mapError(bundleErrorFromUnknown),
234 );
235 };
236
237 const readFile = (file: string, name: string, environment: EnvironmentLike) =>
238 fs.readFile(file).pipe(
239 Effect.flatMap((content) =>
240 sha256(content).pipe(
241 Effect.map((hash): BundleFile => ({
242 path: fileName(name, environment),
243 content,
244 hash,
245 })),
246 ),
247 ),
248 Effect.mapError(bundleErrorFromUnknown),
249 );
250
251 const makeServerBundle = () => {
252 if (!serverEntry && !serverChunks.size) return Effect.undefined;
253 if (!serverEntry) return Effect.die(new Cause.NoSuchElementError("Missing server entry"));
254 const filePaths = Array.from(serverChunks.keys()).sort((a, b) => a.localeCompare(b));
255 const entry = getChunk(serverEntry).pipe(
256 Effect.flatMap((file) =>
257 file
258 ? Effect.succeed(file)
259 : Effect.die(new Cause.NoSuchElementError(`Chunk ${serverEntry} not found`)),
260 ),
261 );
262 const rest = filePaths
263 .filter((filePath) => filePath !== serverEntry)
264 .map((filePath) => getChunk(filePath));
265 return Effect.all([entry, ...rest], { concurrency: "unbounded" }).pipe(
266 Effect.flatMap(([entryFile, ...files]) =>
267 bundleOutputFromFiles([
268 entryFile,
269 ...files.filter((file): file is BundleFile => file !== undefined),
270 ]),
271 ),
272 );
273 };
274
275 // Mirrors `@cloudflare/vite-plugin`: assets the Worker imports move to the
276 // client output. Without a client build (no `index.html`), Vite never copies
277 // `public/` (the Worker builds with `copyPublicDir: false`), so the client
278 // output is created from `public/` plus those assets, as the plugin's
279 // fallback client build does.
280 const collectAssets = Effect.fn(function* () {
281 let directory = clientDirectory;
282 if (directory === undefined) {
283 const hasPublic = yield* isNonEmptyDirectory(fs, publicDir);
284 if (clientOutDir === undefined || (!hasPublic && importedAssets.size === 0)) {
285 return undefined;
286 }
287 directory = clientOutDir;
288 yield* fs.remove(directory, { recursive: true, force: true });
289 yield* fs.makeDirectory(directory, { recursive: true });
290 if (hasPublic) yield* fs.copy(publicDir!, directory);
291 }
292 for (const [asset, source] of importedAssets) {
293 const destination = path.join(directory, asset);
294 if (yield* fs.exists(destination)) continue;
295 yield* fs.makeDirectory(path.dirname(destination), { recursive: true });
296 yield* fs.copyFile(source, destination);
297 }
298 return directory;
299 });
300
301 const getChunk = (path: string) => {
302 const chunk = serverChunks.get(path);
303 if (!chunk) {
304 return Effect.die(new Cause.NoSuchElementError(`Chunk ${path} not found`));
305 }
306 return chunk;
307 };
308
309 return {
310 plugin,
311 // Read lazily so callers observe the state collected during the build.
312 // Only safe to await *after* `builder.buildApp()` has resolved.
313 output: Effect.gen(function* () {
314 const assetsDirectory = yield* collectAssets();
315 return {
316 clientDirectory: assetsDirectory,
317 base,
318 serverBundle: makeServerBundle(),
319 externalWorkspaces: collectExternalWorkspaces(),
320 };
321 }),
322 };
323 });