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

main
ts 295 lines 12.1 KB
Raw
1 import { fileURLToPath } from "node:url";
2 import * as NodeV8 from "node:v8";
3 import { AlchemyContext } from "alchemy/AlchemyContext";
4 import { BundleError } from "alchemy/Bundle/Bundle";
5 import {
6 fromProcessEnv,
7 RPC_SERVER_ENVIRONMENT_KEY,
8 type RpcServerEnvironment,
9 } from "alchemy/Local/RpcServerEnvironment";
10 import { Stack } from "alchemy/Stack";
11 import { unwrapRedacted } from "alchemy/Util";
12 import { nodeLoaderArgs } from "alchemy/Util/Node";
13 import { moduleExtension } from "alchemy/Util/Node";
14 import { pipedColorEnv } from "alchemy/Util/Terminal";
15 import * as Deferred from "effect/Deferred";
16 import * as Effect from "effect/Effect";
17 import * as Fiber from "effect/Fiber";
18 import * as FileSystem from "effect/FileSystem";
19 import * as Option from "effect/Option";
20 import * as Path from "effect/Path";
21 import * as ChildProcess from "effect/process/ChildProcess";
22 import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";
23 import * as Stream from "effect/Stream";
24 import {
25 type ViteBuildChildConfig,
26 type ViteBuildChildResult,
27 type ViteChildConfig,
28 VITE_CHILD_READY_PREFIX,
29 VITE_CHILD_READY_SUFFIX,
30 } from "./ViteChild.shared.ts";
31
32 export interface ViteChildHandle {
33 readonly url: URL;
34 readonly pid: number;
35 readonly exitCode: Effect.Effect<number>;
36 }
37
38 // Resolved lazily at spawn time, NOT at module load: this module can be
39 // carried into bundled user code (Workers), where `import.meta.resolve`
40 // does not exist (workerd) — a module-level call would crash the bundle
41 // at startup even though no child is ever spawned there. At spawn time
42 // we are guaranteed to be in Node/bun.
43 const resolveRunner = (basename: string) =>
44 fileURLToPath(import.meta.resolve(`./${basename}${moduleExtension(import.meta.url)}`));
45
46 // The runner for a Node child spawned from Bun. Bun runs a published
47 // install from `src/*.ts` (the `bun` export condition), but Node can't load
48 // that: `nodeLoaderArgs` pairs a `.ts` entry with the checkout-only
49 // `bin/register-dev-mode.js` (not published), and `bin/register-oxc.js`
50 // leaves `node_modules` untranspiled. The package ships `lib/` beside `src/`,
51 // so an installed copy hands Node the built runner (loaded under
52 // `bin/register-oxc.js`); a checkout keeps the source runner.
53 const resolveNodeRunner = (basename: string) => {
54 const runner = resolveRunner(basename);
55 return /[\\/]node_modules[\\/]/.test(runner) && runner.endsWith(".ts")
56 ? fileURLToPath(new URL(`../../lib/Workers/${basename}.js`, import.meta.url))
57 : runner;
58 };
59
60 export const startViteChild = (
61 config: ViteChildConfig,
62 onOutput: (channel: "stdout" | "stderr", line: string) => Effect.Effect<void>,
63 ) =>
64 Effect.gen(function* () {
65 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
66 const isBun = typeof globalThis.Bun !== "undefined";
67 // The dev server runs on node, as `@cloudflare/vite-plugin`'s does,
68 // whenever node is installed; otherwise on the engine's own runtime.
69 // Bun 1.3's `node:http` drops all but the last of repeated response
70 // headers and never delivers bytes written to an upgraded socket, so a
71 // Vite dev server on it loses `server.headers` arrays and WebSockets.
72 const nodeExecPath = isBun ? (globalThis.Bun.which("node") ?? undefined) : undefined;
73 const runner =
74 nodeExecPath !== undefined
75 ? resolveNodeRunner("ViteChildRunner")
76 : resolveRunner("ViteChildRunner");
77 // Redacted values can't cross the process boundary — the config is
78 // plain data once unwrapped. bun's `v8.serialize` output is not
79 // readable by real V8 (and vice versa), so a cross-runtime spawn
80 // sends JSON instead; the runner sniffs the encoding (V8 payloads
81 // start with 0xFF, JSON with `{`).
82 const serializedConfig =
83 nodeExecPath !== undefined
84 ? Buffer.from(JSON.stringify(unwrapRedacted(config)))
85 : NodeV8.serialize(unwrapRedacted(config));
86 // The Vite child boots the legacy single-stack environment
87 // (RpcServerEnvironment.fromEnv). The sidecar's own process env no
88 // longer carries a stack (one sidecar serves many stacks; sessions
89 // carry theirs), so pass the CURRENT session's stack explicitly, with
90 // profile/envFile taken from the sidecar's spawn-time env when present.
91 // Resolved via serviceOption so this helper's requirements stay
92 // unchanged; the provider context this runs in always carries both.
93 const alchemyContext = yield* Effect.serviceOption(AlchemyContext);
94 const stack = yield* Effect.serviceOption(Stack);
95 const base = yield* fromProcessEnv.pipe(
96 Effect.orElseSucceed((): RpcServerEnvironment => ({
97 profile: process.env.ALCHEMY_PROFILE,
98 envFile: undefined,
99 })),
100 );
101 const childEnvironment: RpcServerEnvironment = {
102 profile: base.profile,
103 envFile: base.envFile,
104 alchemyContext: Option.getOrElse(
105 alchemyContext,
106 () => base.alchemyContext as AlchemyContext["Service"],
107 ),
108 stack: Option.getOrElse(
109 Option.map(stack, (s) => ({ name: s.name, stage: s.stage })),
110 () => base.stack as { name: string; stage: string },
111 ),
112 };
113 const childEnv: Record<string, string | undefined> = {
114 ...process.env,
115 [RPC_SERVER_ENVIRONMENT_KEY]: JSON.stringify(childEnvironment),
116 };
117 // The parent CLI process sets NODE_ENV for its own React/renderer
118 // needs; that hack must not leak into the user's dev server (Vite
119 // derives its default mode from NODE_ENV, so an inherited value would
120 // silently override the project's own mode).
121 delete childEnv.NODE_ENV;
122 const child = yield* spawner.spawn(
123 ChildProcess.make(
124 nodeExecPath ?? process.execPath,
125 isBun && nodeExecPath === undefined ? ["run", runner] : [...nodeLoaderArgs(runner), runner],
126 {
127 cwd: config.rootDir,
128 stdin: Stream.succeed(serializedConfig),
129 stdout: "pipe",
130 stderr: "pipe",
131 env: childEnv,
132 extendEnv: false,
133 // SIGTERM lets the child close its runtime, whose finalizer removes
134 // the Docker containers its Workers started (`ctx.container`);
135 // SIGKILL would leave them running.
136 killSignal: "SIGTERM",
137 forceKillAfter: "10 seconds",
138 },
139 ),
140 );
141
142 const ready = yield* Deferred.make<URL>();
143 // The last output lines explain a child that dies before it is ready
144 // (an entry that can't be resolved, a broken Vite config).
145 const outputTail: Array<string> = [];
146 const recordOutput = (stream: "stdout" | "stderr", line: string) =>
147 Effect.sync(() => {
148 outputTail.push(line);
149 if (outputTail.length > STARTUP_ERROR_TAIL) outputTail.shift();
150 }).pipe(Effect.andThen(onOutput(stream, line)));
151 const stdout = yield* child.stdout.pipe(
152 Stream.decodeText,
153 Stream.splitLines,
154 Stream.runForEach((line) => {
155 const start = line.indexOf(VITE_CHILD_READY_PREFIX);
156 const end = line.indexOf(VITE_CHILD_READY_SUFFIX);
157 if (start !== -1 && end > start) {
158 const value = line.slice(start + VITE_CHILD_READY_PREFIX.length, end);
159 return Deferred.succeed(ready, new URL(value));
160 }
161 return recordOutput("stdout", line);
162 }),
163 Effect.forkScoped,
164 );
165 const stderr = yield* child.stderr.pipe(
166 Stream.decodeText,
167 Stream.splitLines,
168 Stream.runForEach((line) => recordOutput("stderr", line)),
169 Effect.forkScoped,
170 );
171
172 const exitCode = child.exitCode.pipe(Effect.orDie);
173 const url = yield* Effect.raceAllFirst([
174 Deferred.await(ready),
175 exitCode.pipe(
176 Effect.tap(() =>
177 Fiber.joinAll([stdout, stderr]).pipe(Effect.timeout("1 second"), Effect.ignore),
178 ),
179 Effect.flatMap((exitCode) =>
180 Effect.die(
181 new Error(
182 [`Vite child exited with code ${exitCode} before becoming ready`, ...outputTail].join(
183 "\n",
184 ),
185 ),
186 ),
187 ),
188 ),
189 ]);
190 return { url, pid: child.pid, exitCode } satisfies ViteChildHandle;
191 });
192
193 /** Number of trailing output lines echoed into a failed dev start's error. */
194 const STARTUP_ERROR_TAIL = 50;
195
196 /** Number of trailing stderr lines echoed into a failed build's error. */
197 const BUILD_ERROR_TAIL = 200;
198
199 /**
200 * Run a one-shot production Vite build in a child process whose working
201 * directory is the project root, and read back the serialized result.
202 *
203 * Isolation is the point (the dev server already runs this way): an
204 * in-process build both suffers from and causes transient `process.cwd()`
205 * changes — cross-spawn `process.chdir`s the hosting process while
206 * resolving a spawn's binary, and vite/plugins resolve relative paths
207 * against live cwd — which corrupts concurrent deploys sharing the
208 * process. See `ViteBuildChildRunner.ts` for the child side.
209 */
210 export const runViteBuildChild = (
211 config: Omit<ViteBuildChildConfig, "outputPath">,
212 onOutput: (channel: "stdout" | "stderr", line: string) => Effect.Effect<void>,
213 ) =>
214 Effect.scoped(
215 Effect.gen(function* () {
216 const fs = yield* FileSystem.FileSystem;
217 const path = yield* Path.Path;
218 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
219 const runner = resolveRunner("ViteBuildChildRunner");
220 const isBun = typeof globalThis.Bun !== "undefined";
221 const outputDir = yield* fs.makeTempDirectoryScoped({
222 prefix: "alchemy-vite-build-",
223 });
224 const outputPath = path.join(outputDir, "result.v8");
225 // Redacted values can't cross the process boundary — the config is
226 // plain data once unwrapped.
227 const serializedConfig = NodeV8.serialize(unwrapRedacted({ ...config, outputPath }));
228 const child = yield* spawner.spawn(
229 ChildProcess.make(
230 process.execPath,
231 isBun ? ["run", runner] : [...nodeLoaderArgs(runner), runner],
232 {
233 cwd: config.rootDir,
234 stdin: Stream.succeed(serializedConfig),
235 stdout: "pipe",
236 stderr: "pipe",
237 extendEnv: true,
238 // A production build must not inherit the parent's NODE_ENV: a
239 // deploy driven from a test process (`bun test` sets
240 // NODE_ENV=test) would otherwise bake `import.meta.env.DEV`
241 // into the server bundle (e.g. SolidStart then ships its
242 // dev-only manifest and every SSR request 500s).
243 env: { ...pipedColorEnv(), NODE_ENV: "production" },
244 killSignal: "SIGKILL",
245 },
246 ),
247 );
248
249 // stdout is build progress; the failure cause lands on stderr.
250 const stderrTail: string[] = [];
251 let stderrLines = 0;
252 const forward = (channel: "stdout" | "stderr") => (line: string) =>
253 Effect.sync(() => {
254 if (channel !== "stderr") return;
255 stderrLines++;
256 stderrTail.push(line);
257 if (stderrTail.length > BUILD_ERROR_TAIL) stderrTail.shift();
258 }).pipe(Effect.andThen(onOutput(channel, line)));
259 const stdoutFiber = yield* Effect.forkChild(
260 child.stdout.pipe(
261 Stream.decodeText,
262 Stream.splitLines,
263 Stream.runForEach(forward("stdout")),
264 ),
265 );
266 const stderrFiber = yield* Effect.forkChild(
267 child.stderr.pipe(
268 Stream.decodeText,
269 Stream.splitLines,
270 Stream.runForEach(forward("stderr")),
271 ),
272 );
273
274 const exitCode = yield* child.exitCode.pipe(Effect.orDie);
275 // Drain both pipes before reporting so the error tail is complete.
276 yield* Fiber.join(stdoutFiber).pipe(Effect.ignore);
277 yield* Fiber.join(stderrFiber).pipe(Effect.ignore);
278 if (exitCode !== 0) {
279 const truncated = stderrLines > stderrTail.length;
280 return yield* BundleError.make({
281 message: [
282 `Vite build child exited with code ${exitCode}.`,
283 ...(stderrTail.length === 0
284 ? []
285 : [
286 truncated ? `stderr (last ${stderrTail.length} lines):` : "stderr:",
287 ...stderrTail,
288 ]),
289 ].join("\n"),
290 });
291 }
292 const bytes = yield* fs.readFile(outputPath).pipe(Effect.orDie);
293 return NodeV8.deserialize(Buffer.from(bytes)) as ViteBuildChildResult;
294 }),
295 );