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

main
ts 496 lines 20.2 KB
Raw
1 import { createRequire } from "node:module";
2 import nodePath from "node:path";
3 import { pathToFileURL } from "node:url";
4 import { viteSupportsPortZero } from "@alchemy.run/cloudflare-runtime/core/internal/Port";
5 import cloudflare, { type CloudflareVitePluginOptions } from "@alchemy.run/cloudflare-runtime/vite";
6 import { viteBuildOutputPlugin, type ViteBuildOutput } from "alchemy/Bundle/Vite";
7 import { hashDirectory, type MemoOptions } from "alchemy/Command/Memo";
8 import { findAvailablePort, initialCwd } from "alchemy/Util/Node";
9 import { makeResourceLogger } from "alchemy/Util/ResourceOutput";
10 import { sha256Object } from "alchemy/Util/sha256";
11 import type * as Context from "effect/Context";
12 import * as Effect from "effect/Effect";
13 import * as Path from "effect/Path";
14 import * as Redacted from "effect/Redacted";
15 import type * as vite from "vite";
16 import type { FoldkitBuildMetadata } from "../../Website/FoldkitBuild.ts";
17 import { readAssets } from "../Assets.ts";
18 import type { SourceDevHandle, SourceProvider } from "../Source.ts";
19 import { runViteBuildChild } from "../ViteChild.ts";
20 import { resolveViteMain } from "../ViteMain.ts";
21 import { isSelfUrl, type ViteOptions } from "../Worker.ts";
22 import { isContainerDecl } from "../WorkerAsyncBindings.ts";
23 import { isWorkerLoader } from "../WorkerLoader.ts";
24
25 /**
26 * This module statically imports `@alchemy.run/cloudflare-runtime/vite`
27 * (~0.5s to load), which is only needed for vite-based workers. Importers
28 * MUST load it lazily (`Effect.promise(() => import("./Sources/Vite.ts"))`
29 * from the dispatch in `Source.ts`, or the legacy vite arms in the
30 * Worker providers) so the module cost is only paid when a vite worker
31 * is actually built, hashed, or served.
32 */
33
34 /**
35 * Route Vite's logger into log records through the services of the Effect
36 * that built it, instead of its default stdout logger: the process that
37 * renders logs shows them (raw or stripped), JSON output carries them, and
38 * alchemy-test's per-test log capture sees them.
39 */
40 const makeViteLogger = (context: Context.Context<never>): vite.Logger => {
41 const loggedErrors = new WeakSet<object>();
42 let hasWarned = false;
43 const log = (effect: Effect.Effect<void>) => Effect.runSyncWith(context)(effect);
44 return {
45 info: (msg) => log(Effect.logInfo(msg)),
46 warn: (msg) => {
47 hasWarned = true;
48 log(Effect.logWarning(msg));
49 },
50 warnOnce: (msg) => {
51 hasWarned = true;
52 log(Effect.logWarning(msg));
53 },
54 error: (msg, options) => {
55 if (options?.error != null) loggedErrors.add(options.error);
56 log(Effect.logError(msg));
57 },
58 clearScreen: () => {},
59 hasErrorLogged: (error) => loggedErrors.has(error),
60 get hasWarned() {
61 return hasWarned;
62 },
63 };
64 };
65
66 /**
67 * Signals to the app's own Vite config that Alchemy is injecting its
68 * resource-aware Cloudflare plugin into this build/dev run.
69 *
70 * Apps that also build standalone (plain `vite build` in CI, no Alchemy)
71 * need the Cloudflare plugin in their `vite.config.ts`. Without a guard,
72 * an Alchemy-orchestrated run instantiates that config-file instance
73 * *alongside* the injected one: two same-named plugin stacks whose
74 * cross-plugin API lookups resolve by name, and — in dev — two workerd
75 * runtimes, only one of which carries the Worker's bindings. Guarding on
76 * this variable lets the config-file instance stand down:
77 *
78 * ```ts
79 * // vite.config.ts
80 * process.env.ALCHEMY_CLOUDFLARE_VITE_INJECTED === "1"
81 * ? null
82 * : cloudflare({ ... })
83 * ```
84 *
85 * The variable is set process-locally by `viteDev`/`viteBuild`, so it is
86 * correct regardless of which process hosts Vite (`alchemy dev` runs the
87 * dev server in the spawned local-provider host, not in the process that
88 * evaluates the user's alchemy.run.ts — an env variable set there never
89 * reaches the config).
90 *
91 * Contract: the value is `"1"` while the process is Alchemy-orchestrated;
92 * absence means not injected. It is deliberately never unset — Vite
93 * re-evaluates the app config on dev-server restarts long after
94 * `viteDev` returned, and concurrent `viteBuild`s in one process would
95 * race a save/restore. A process that ran an Alchemy build never also
96 * runs a standalone (non-Alchemy) Vite build, so the flag staying set is
97 * correct for the process lifetime.
98 */
99 const ALCHEMY_CLOUDFLARE_VITE_INJECTED = "ALCHEMY_CLOUDFLARE_VITE_INJECTED";
100
101 export const viteDev = (
102 rootDir: string = initialCwd,
103 env: Record<string, unknown>,
104 pluginOptions: CloudflareVitePluginOptions,
105 serverOptions: vite.ServerOptions,
106 ) =>
107 Effect.gen(function* () {
108 yield* Effect.sync(() => {
109 process.env[ALCHEMY_CLOUDFLARE_VITE_INJECTED] = "1";
110 });
111 const vite = yield* Effect.promise(() => loadVite(rootDir));
112 // `port: 0` is a true OS-assigned random port on Vite >= 8.2.1
113 // (vitejs/vite#23158); older Vite treats it as "no port given" and
114 // hunts upward from the 5173 default — colliding with (or
115 // IPv6-shadowing) user-facing dev ports. Substitute a probed
116 // ephemeral port there; `strictPort: false` handles the small
117 // probe→bind race by moving to the next ephemeral port.
118 const server =
119 serverOptions.port === 0 && !viteSupportsPortZero(vite.version)
120 ? {
121 ...serverOptions,
122 port: yield* findAvailablePort(
123 typeof serverOptions.host === "string" ? serverOptions.host : undefined,
124 ).pipe(Effect.orDie),
125 }
126 : serverOptions;
127 return yield* Effect.acquireRelease(
128 Effect.flatMap(Effect.context<never>(), (context) =>
129 Effect.promise(async () => {
130 const devServer = await vite.createServer({
131 root: rootDir,
132 define: getDefine(env),
133 plugins: [cloudflare(pluginOptions)],
134 server,
135 customLogger: makeViteLogger(context),
136 });
137 await devServer.listen();
138 return devServer;
139 }),
140 ),
141 (devServer) =>
142 Effect.promise(async () => {
143 await devServer.close();
144 }),
145 );
146 });
147
148 type ViteBuildOptions = CloudflareVitePluginOptions & Pick<ViteOptions, "framework">;
149
150 type ViteWorkerBuildOutput = ViteBuildOutput & {
151 foldkit: FoldkitBuildMetadata | undefined;
152 };
153
154 /**
155 * Run a production Vite build in a child process rooted at the project
156 * directory and adapt the result to the in-process {@link ViteBuildOutput}
157 * shape.
158 *
159 * The child boundary is what makes concurrent builds safe: vite resolves a
160 * relative root against live `process.cwd()`, plugins read cwd freely, and
161 * build-time spawns chdir the hosting process transiently (cross-spawn's
162 * PATH resolution) — so an in-process build both breaks under and causes
163 * cwd races when the engine runs builds concurrently.
164 */
165 export const viteBuild = (
166 rootDir: string = initialCwd,
167 env: Record<string, unknown>,
168 pluginOptions: ViteBuildOptions,
169 fqn: string,
170 ) =>
171 Effect.gen(function* () {
172 const logResourceOutput = makeResourceLogger(fqn);
173 const result = yield* runViteBuildChild(
174 {
175 // Anchor to the initial cwd so the resolution itself can't race a
176 // transient chdir; the child's own cwd is this resolved root.
177 rootDir: nodePath.resolve(initialCwd, rootDir),
178 // Only `VITE_`-prefixed entries participate in the build (see
179 // `getDefine`); the rest may hold non-serializable values.
180 env: Object.fromEntries(Object.entries(env).filter(([key]) => key.startsWith("VITE_"))),
181 main: pluginOptions.main,
182 framework: pluginOptions.framework,
183 compatibilityDate: pluginOptions.compatibilityDate,
184 compatibilityFlags: pluginOptions.compatibilityFlags,
185 viteEnvironments: pluginOptions.viteEnvironments,
186 },
187 logResourceOutput,
188 );
189 return {
190 clientDirectory: result.clientDirectory,
191 foldkit: result.foldkit,
192 base: result.base,
193 serverBundle: Effect.succeed(result.serverBundle),
194 externalWorkspaces: Effect.succeed(new Set(result.externalWorkspaces)),
195 } satisfies ViteWorkerBuildOutput;
196 });
197
198 /**
199 * The in-process build implementation. ONLY safe inside the dedicated
200 * build child (`ViteBuildChildRunner.ts`), whose cwd is the project root
201 * and which hosts no concurrent work — never call it from the engine
202 * process (see {@link viteBuild}).
203 */
204 export const viteBuildInProcess = (
205 rootDir: string,
206 env: Record<string, unknown>,
207 pluginOptions: ViteBuildOptions,
208 ) =>
209 Effect.gen(function* () {
210 const outputPlugin = yield* viteBuildOutputPlugin({
211 entryEnvironment: pluginOptions.viteEnvironments?.entry ?? "ssr",
212 });
213 const context = yield* Effect.context<never>();
214 const foldkit = yield* Effect.promise(async () => {
215 process.env[ALCHEMY_CLOUDFLARE_VITE_INJECTED] = "1";
216 const vite = await loadVite(rootDir);
217 const builder = await vite.createBuilder(
218 {
219 root: rootDir,
220 define: getDefine(env),
221 plugins: [cloudflare(pluginOptions), outputPlugin.plugin],
222 customLogger: makeViteLogger(context),
223 // Disables the NATIVE rolldown progress reporter ("transforming…",
224 // "rendering chunks…", "computing gzip size…"): it prints from
225 // Rust straight to fd 1 and cannot be intercepted from JS — vite
226 // only enables it when logLevel >= info. Info-level build
227 // summaries are suppressed with it; warnings and errors still
228 // reach the customLogger above.
229 logLevel: "warn",
230 },
231 // This is the `useLegacyBuilder` option. The Vite CLI implementation uses `null` here.
232 // Originally we used `undefined` here, but this caused the static site build to fail.
233 // https://github.com/vitejs/vite/blob/a07a4bd052ac75f916391c999c408ad5f2867e61/packages/vite/src/node/cli.ts#L367
234 null,
235 );
236 const readFoldkitMetadata =
237 pluginOptions.framework === "foldkit"
238 ? (await import("../../Website/FoldkitBuild.ts")).foldkitBuildMetadataReader(
239 builder.config.plugins,
240 pluginOptions.main,
241 )
242 : undefined;
243 await builder.buildApp();
244 return readFoldkitMetadata?.();
245 });
246 return { ...(yield* outputPlugin.output), foldkit };
247 });
248
249 // Emulate `vite build` env semantics for `props.env`: only
250 // keys with Vite's default `VITE_` prefix are inlined into
251 // the bundle as `import.meta.env.*`. `Redacted` values are
252 // unwrapped — by prefixing with `VITE_` the user is opting
253 // them into the public bundle.
254 const getDefine = (env: Record<string, unknown>) =>
255 Object.fromEntries(
256 Object.entries(env).flatMap(([key, raw]) => {
257 if (!key.startsWith("VITE_")) return [];
258 const value = Redacted.isRedacted(raw) ? Redacted.value(raw) : raw;
259 return [[`import.meta.env.${key}`, JSON.stringify(value)] as const];
260 }),
261 );
262
263 type ViteModule = typeof import("vite");
264
265 /**
266 * Dynamically load Vite from the project root. Falls back to the bundled
267 * copy if the project doesn't have its own Vite installation.
268 */
269 async function loadVite(projectRoot: string = initialCwd): Promise<ViteModule> {
270 try {
271 const require = createRequire(nodePath.join(projectRoot, "package.json"));
272 const vitePath = require.resolve("vite");
273 // On Windows, absolute paths must be file:// URLs for ESM import().
274 const viteUrl = pathToFileURL(vitePath);
275 return await import(/* @vite-ignore */ viteUrl.href);
276 } catch {
277 // Fallback: try to import vite from the global node_modules (works for non-linked installs)
278 // The fallback is a bare specifier and works as-is.
279 return await import("vite");
280 }
281 }
282
283 /**
284 * Resolve `props.env` to the literal values vite's `import.meta.env`
285 * defines are computed from: strings pass through, `Redacted<string>`s
286 * are unwrapped, env-bound Effects are evaluated, and `WorkerLoader`s
287 * (bindings that happen to be Effects) are skipped.
288 */
289 const resolveViteEnv = (env: Record<string, unknown>, selfUrl: string | undefined) =>
290 Effect.gen(function* () {
291 return Object.fromEntries(
292 (yield* Effect.forEach(
293 Object.entries(env),
294 Effect.fn(function* ([key, value]) {
295 return [
296 key,
297 typeof value === "string"
298 ? value
299 : Redacted.isRedacted(value) && typeof Redacted.value(value) === "string"
300 ? Redacted.value(value)
301 : // `Worker.URL` (bare tag or called) — resolved to this
302 // Worker's own URL. The bare tag is Effect-shaped, so
303 // check before `Effect.isEffect`.
304 isSelfUrl(value)
305 ? selfUrl
306 : // A `WorkerLoader` is a real Effect that also carries
307 // the `~alchemy/Kind` marker — it is a binding, not a
308 // runnable env value. Check it before `Effect.isEffect`
309 // so we don't execute it as an inlined env entry.
310 isWorkerLoader(value)
311 ? undefined
312 : // A `Cloudflare.Container` declaration is likewise
313 // Effect-shaped but is a binding (DO namespace +
314 // ContainerApplication) — yielding it would resolve
315 // the started-instance tag, which only exists inside
316 // a Durable Object (#997).
317 isContainerDecl(value)
318 ? undefined
319 : Effect.isEffect(value)
320 ? yield* value as any as Effect.Effect<any>
321 : undefined,
322 ];
323 }),
324 )).filter(([, value]) => value !== undefined),
325 );
326 });
327
328 /**
329 * Hash the vite project's input tree (root + workspaces + lockfiles) —
330 * the rebuild-free change signal for the `input` hash slot.
331 */
332 export const hashViteInput = Effect.fn(function* <E, R>(
333 rootDir: string = initialCwd,
334 options: ViteOptions["memo"],
335 additionalWorkspaces: Effect.Effect<Iterable<string>, E, R>,
336 ) {
337 const path = yield* Path.Path;
338 // Resolved once: every workspace cwd is relative to the Vite root, so
339 // the root must be an absolute base. Resolving it per call and passing
340 // `rootDir` as its own cwd would apply a relative root twice
341 // (`path.resolve("app", "app")` → `<cwd>/app/app`), hashing a
342 // directory that doesn't exist — a constant hash that never registers
343 // an edit, so the deploy no-ops forever. See issue #1016. Anchored to
344 // the initial cwd so a transient chdir can't skew the resolution.
345 const resolvedRoot = path.resolve(initialCwd, rootDir);
346 // Relative paths participate in memo hashes and surface in outputs;
347 // keep them POSIX so Windows and CI agree.
348 const relativeToRoot = (cwd: string) =>
349 path.relative(resolvedRoot, path.resolve(resolvedRoot, cwd)).replaceAll("\\", "/");
350 const hashWorkspaceDirectory = (cwd: string, memo?: MemoOptions) =>
351 hashDirectory({ cwd: path.resolve(resolvedRoot, cwd), memo }).pipe(
352 Effect.map((hash) => `${relativeToRoot(cwd)}:${hash}`),
353 );
354 // `"."` — the root itself, never re-applied on top of itself.
355 const hashRoot = hashWorkspaceDirectory(".", options);
356 if (Array.isArray(options?.workspaces)) {
357 return yield* Effect.all(
358 [
359 hashRoot,
360 ...options.workspaces.map(({ cwd, ...options }) => hashWorkspaceDirectory(cwd, options)),
361 ],
362 { concurrency: "unbounded" },
363 ).pipe(
364 Effect.flatMap(([root, ...workspaces]) => sha256Object([root, ...workspaces.sort()])),
365 Effect.map((hash) => ({ hash, workspaces: undefined })),
366 );
367 }
368 const [root, workspaces] = yield* Effect.all([hashRoot, additionalWorkspaces], {
369 concurrency: "unbounded",
370 });
371 const workspaceHashes = yield* Effect.forEach(workspaces, (cwd) => hashWorkspaceDirectory(cwd), {
372 concurrency: "unbounded",
373 });
374 const hash = yield* sha256Object([root, ...workspaceHashes.sort()]);
375 return { hash, workspaces: Array.from(workspaces).map(relativeToRoot) };
376 });
377
378 /**
379 * Source provider for vite-based workers (`props.vite`, set by
380 * `Website.Vite`): the vite builder produces the client assets and the
381 * server bundle in one pass; diff never builds — the `input` hash over
382 * the project tree is the change signal.
383 *
384 * This module is the lazy-import boundary for the vite toolchain (see
385 * the module note above): the dispatch in `Source.ts` dynamically
386 * imports it, so its ~0.5s module cost is only paid for vite-based
387 * workers.
388 */
389 export const makeViteSource = (vite: ViteOptions): SourceProvider => ({
390 ownsAssets: true,
391 build: Effect.fn(function* (ctx) {
392 const path = yield* Path.Path;
393 const env = yield* resolveViteEnv(ctx.env ?? {}, ctx.selfUrl);
394 const { clientDirectory, foldkit, base, serverBundle, externalWorkspaces } = yield* viteBuild(
395 vite.rootDir,
396 env,
397 {
398 // A relative `vite.main` is documented to resolve from the Vite
399 // root. The rolldown plugin resolves the worker entry with no
400 // importer (i.e. against `process.cwd()`), which breaks when the
401 // deploy runs from a different directory (e.g. a monorepo infra
402 // package) — absolutize before handing it over (#796).
403 // A package export or virtual module (`vike:server`) goes to Vite
404 // as is.
405 main: vite.main
406 ? yield* resolveViteMain(path.resolve(initialCwd, vite.rootDir ?? "."), vite.main)
407 : undefined,
408 compatibilityDate: ctx.compatibility.date,
409 compatibilityFlags: ctx.compatibility.flags,
410 viteEnvironments: vite.viteEnvironments,
411 framework: vite.framework,
412 },
413 ctx.fqn,
414 );
415 const declaredAssets = ctx.assets && typeof ctx.assets !== "string" ? ctx.assets : undefined;
416 // What the build itself says about its assets, filled in under what
417 // the resource declared: a framework that records which pages it
418 // prerendered knows the routing better than a default would, and the
419 // resource's own `assets` still has the last word.
420 const derivedAssets =
421 clientDirectory && vite.framework === "foldkit"
422 ? yield* Effect.promise(() => import("../../Website/FoldkitBuild.ts")).pipe(
423 Effect.map(({ foldkitAssetsFromManifest }) =>
424 foldkitAssetsFromManifest(foldkit?.manifest),
425 ),
426 )
427 : undefined;
428 const [assets, bundle, input] = yield* Effect.all(
429 [
430 clientDirectory
431 ? readAssets({
432 ...derivedAssets,
433 ...declaredAssets,
434 // `clientDirectory` from the build child is absolute; the
435 // rootDir only matters as a legacy fallback.
436 directory: path.resolve(initialCwd, vite.rootDir ?? ".", clientDirectory),
437 // The resolved Vite `base` is what rewrote the URLs in the
438 // emitted HTML, so it is the only prefix the manifest can
439 // agree with.
440 base,
441 })
442 : Effect.undefined,
443 serverBundle,
444 hashViteInput(vite.rootDir, vite.memo, externalWorkspaces),
445 ],
446 { concurrency: "unbounded" },
447 );
448 if (!assets && !bundle) {
449 return yield* Effect.die(new Error("Vite build produced neither assets nor server output"));
450 }
451 return {
452 bundle,
453 assets,
454 hash: {
455 bundle: bundle?.hash,
456 assets: assets?.hash,
457 input: input.hash,
458 additionalWorkspaces: input.workspaces,
459 },
460 };
461 }),
462 hash: Effect.fn(function* (_ctx, previous) {
463 const { hash, workspaces } = yield* hashViteInput(
464 vite.rootDir,
465 vite.memo,
466 Effect.succeed(previous?.additionalWorkspaces ?? []),
467 );
468 return { input: hash, additionalWorkspaces: workspaces };
469 }),
470 dev: Effect.fn(function* (ctx) {
471 const devServer = yield* viteDev(
472 vite.rootDir,
473 ctx.env ?? {},
474 {
475 main: vite.main,
476 compatibilityDate: ctx.compatibility.date,
477 compatibilityFlags: ctx.compatibility.flags,
478 viteEnvironments: vite.viteEnvironments,
479 worker: {
480 name: ctx.workerName,
481 bindings: ctx.worker.bindings,
482 durableObjectNamespaces: ctx.worker.durableObjectNamespaces,
483 hyperdrives: ctx.worker.hyperdrives,
484 queueConsumers: yield* ctx.worker.queueConsumers,
485 assets: ctx.worker.assets,
486 },
487 context: ctx.runtimeContext,
488 },
489 { port: 0 },
490 );
491 return {
492 mode: "server",
493 url: new URL(devServer.resolvedUrls!.local[0]),
494 } satisfies SourceDevHandle;
495 }),
496 });