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

main
ts 536 lines 20.8 KB
Raw
1 import * as NodePath from "node:path";
2 import * as Effect from "effect/Effect";
3 import * as FileSystem from "effect/FileSystem";
4 import * as Layer from "effect/Layer";
5 import * as Path from "effect/Path";
6 import * as Schedule from "effect/Schedule";
7 import * as Semaphore from "effect/Semaphore";
8 import * as FrameworkCore from "../core/index.ts";
9 import {
10 Framework,
11 FrameworkError,
12 type DeployTarget,
13 type DeployTargetInput,
14 } from "../core/index.ts";
15 import {
16 findPresetConflict,
17 hasForeignNitroPlugin,
18 markInjectedPlugins,
19 pluginConflictMessage,
20 presetConflictMessage,
21 resolveNitroConfig,
22 resolveNitroOutputDirs,
23 type NitroConfigSlice,
24 } from "./UserConfig.ts";
25
26 /**
27 * The structural slice of the project's `vite` module this package drives.
28 * Typed structurally so the package carries no dependency on vite — the
29 * *project's* install is always the one loaded.
30 *
31 * `createBuilder` (not `build`) is the entry point: SolidStart declares a
32 * `builder.buildApp` that builds the client and SSR environments (and, with
33 * the nitro plugin, runs nitro over the SSR bundle). Vite's legacy `build()`
34 * only builds the default environment, so it would silently produce the
35 * client bundle and nothing else.
36 */
37 export interface SolidStartViteModule {
38 readonly version?: string;
39 readonly createBuilder: (config: Record<string, unknown>) => Promise<SolidStartViteBuilder>;
40 readonly createServer: (config: Record<string, unknown>) => Promise<SolidStartViteDevServer>;
41 }
42
43 /** The structural slice of a vite builder this package reads. */
44 export interface SolidStartViteBuilder {
45 readonly buildApp: () => Promise<unknown>;
46 }
47
48 /** The structural slice of a Vite dev server this package reads. */
49 export interface SolidStartViteDevServer {
50 readonly listen: () => Promise<unknown>;
51 readonly close: () => Promise<void>;
52 readonly resolvedUrls?: { readonly local: ReadonlyArray<string> } | null | undefined;
53 }
54
55 /**
56 * The structural slice of the project's `@solidjs/vite-plugin-nitro-2`
57 * module this package drives.
58 */
59 export interface SolidStartNitroPluginModule {
60 readonly nitroV2Plugin: (nitroConfig?: Record<string, unknown>) => unknown;
61 }
62
63 /** Inputs the framework passes when consulting the target's nitro hook. */
64 export interface SolidStartNitroContext {
65 /** Absolute project root. */
66 readonly root: string;
67 }
68
69 /**
70 * The configuration this package assembles from {@link SolidStartOptions}
71 * and hands to a deploy-target factory. The target treats it as its
72 * `DeployTarget.config`; the framework half never inspects a resolved
73 * target's config.
74 */
75 export interface SolidStartTargetConfig {
76 /**
77 * Nitro options forwarded into the appended `nitroV2Plugin(...)` instance
78 * (prerendering, route rules, storage, ...). `preset` is owned by the
79 * deploy target and may not be set here.
80 *
81 * Carried on the target config so wholesale targets that re-run the
82 * framework in a child process (the AWS target) can reconstruct the
83 * framework with the same options.
84 */
85 readonly nitro?: Record<string, unknown> | undefined;
86 }
87
88 /**
89 * A deploy target for SolidStart: the generic `DeployTarget` seams plus the
90 * nitro hooks the SolidStart build needs — the deployment preset to build
91 * with, and a last-word pass over the nitro config the integration hands to
92 * the SolidStart nitro plugin.
93 */
94 export interface SolidStartTarget extends DeployTarget<SolidStartTargetConfig> {
95 /** The nitro deployment preset this target builds with (e.g. `"aws-lambda"`). */
96 readonly nitroPreset: string;
97 /**
98 * Last-word mutation of the nitro config, run after the caller's `nitro`
99 * overrides and after the preset is enforced (e.g. the AWS target forces
100 * `awsLambda.streaming`).
101 */
102 readonly configureNitro?:
103 | ((nitroConfig: NitroConfigSlice, context: SolidStartNitroContext) => void)
104 | undefined;
105 }
106
107 /**
108 * How a deploy target is passed to this package: a `SolidStartTarget` value,
109 * a factory `(config) => SolidStartTarget`, or a module specifier resolved
110 * from the *project's* `node_modules`.
111 */
112 export type SolidStartTargetInput = DeployTargetInput<SolidStartTarget, SolidStartTargetConfig>;
113
114 /**
115 * The default deploy target: this package's own AWS Lambda target module,
116 * loaded from the project's dependency tree. (Cloudflare deploys SolidStart
117 * through its native Vite integration — `Cloudflare.Website.Vite` — so no
118 * Cloudflare target exists here.)
119 */
120 export const DEFAULT_TARGET_SPECIFIER = "@alchemy.run/frontend-frameworks/solidstart/aws";
121
122 /** The specifier the project's SolidStart nitro plugin is loaded from. */
123 export const NITRO_PLUGIN_SPECIFIER = "@solidjs/vite-plugin-nitro-2";
124
125 export interface SolidStartOptions {
126 /**
127 * Project root (the directory containing `vite.config.*`).
128 * @default process.cwd()
129 */
130 readonly root?: string | undefined;
131 /**
132 * The deploy target the build is produced for. Accepts a target value, a
133 * `(config) => target` factory, or a module specifier string.
134 * @default "@alchemy.run/frontend-frameworks/solidstart/aws"
135 */
136 readonly target?: SolidStartTargetInput | undefined;
137 /**
138 * Nitro options forwarded into the appended `nitroV2Plugin(...)` instance.
139 * `preset` is owned by the deploy target and may not be set here.
140 */
141 readonly nitro?: Record<string, unknown> | undefined;
142 readonly dev?:
143 | {
144 /** Default dev-server port (overridden by `FrameworkDevOptions.port`). */
145 readonly port?: number | undefined;
146 }
147 | undefined;
148 }
149
150 const fail = (message: string, cause?: unknown) =>
151 new FrameworkError({ framework: "solidstart", message, cause });
152
153 /**
154 * Serializes cwd swaps across concurrent dev-server starts in one process (the
155 * same discipline as the Waku framework's lock). Without it two interleaved
156 * acquire/release pairs leave the process cwd pointing at the wrong project:
157 * A chdir(/orig -> /a); B captures previous=/a, chdir(/b); A restores /orig;
158 * B restores /a.
159 */
160 const cwdLock = Semaphore.makeUnsafe(1);
161
162 /**
163 * Run `effect` with the process working directory set to the project root,
164 * restoring it afterwards. A no-op (and lock-free) when the cwd already is the
165 * root — the case for the isolated build child process.
166 *
167 * SolidStart 2's `solidStart()` plugin resolves the app root, the route
168 * directory, and the `~` alias from `process.cwd()` at config-load time —
169 * not from vite's `root` — so it only finds the app when the process is IN
170 * the project. Production builds are already isolated in a child process
171 * whose cwd IS the root (see `aws.ts`), which makes this a no-op there; the
172 * dev server runs in the caller's process (alchemy's dev sidecar), so the
173 * cwd is aligned only across the window in which vite evaluates the config
174 * module, and restored immediately after.
175 *
176 * Consequence, upstream and unavoidable while the plugin keys off the cwd:
177 * one process can host the dev server of ONE SolidStart project at a time.
178 */
179 const inProjectCwd = <A, E, R>(
180 root: string,
181 effect: Effect.Effect<A, E, R>,
182 ): Effect.Effect<A, E | FrameworkError, R> =>
183 Effect.flatMap(
184 Effect.sync(() => process.cwd() === NodePath.resolve(root)),
185 (isRoot) =>
186 isRoot
187 ? effect
188 : Semaphore.withPermits(
189 cwdLock,
190 1,
191 )(
192 Effect.acquireUseRelease(
193 Effect.try({
194 try: () => {
195 const previous = process.cwd();
196 process.chdir(root);
197 return previous;
198 },
199 catch: (error) => fail(`Failed to enter the project directory ${root}`, error),
200 }),
201 () => effect,
202 (previous) =>
203 Effect.sync(() => {
204 try {
205 if (process.cwd() !== previous) {
206 process.chdir(previous);
207 }
208 } catch {
209 // restoring the cwd is best-effort
210 }
211 }),
212 ),
213 ),
214 );
215
216 /**
217 * Build the `Framework` service implementation for a SolidStart project.
218 *
219 * - `build` resolves the deploy target, then either delegates wholesale
220 * (`target.build`) or drives the PROJECT's own Vite install
221 * programmatically: `createBuilder({ root, plugins: [nitroV2Plugin(...)] })`
222 * followed by `buildApp()`. The project's `vite.config.*` loads natively
223 * (its `solidStart()` plugin is untouched); the integration APPENDS a
224 * `nitroV2Plugin` instance — loaded from the project's own
225 * `node_modules` — carrying the deploy target's preset. Inline plugins are
226 * merged after the config file's, so the appended instance's
227 * `builder.buildApp` gets the last word. The `BuildOutput` is read from
228 * nitro's `.output`: `serverModules` entry-first from `.output/server`,
229 * `clientDirectory` = `.output/public` (prerendered pages included).
230 * - `dev` runs the project's own Vite dev server (SolidStart's dev-server
231 * plugin serves SSR through it, with native HMR), scoped — closing the
232 * Scope closes the server. Nitro plays no part in dev.
233 *
234 * This module is target-agnostic: everything AWS-specific lives in
235 * `@alchemy.run/frontend-frameworks/solidstart/aws`.
236 */
237 export const make: (
238 options?: SolidStartOptions,
239 ) => Effect.Effect<Framework["Service"], never, FileSystem.FileSystem | Path.Path> =
240 Effect.fnUntraced(function* (options?: SolidStartOptions) {
241 const fs = yield* FileSystem.FileSystem;
242 const path = yield* Path.Path;
243 const baseRoot = options?.root ?? (yield* Effect.sync(() => process.cwd()));
244
245 const targetConfig: SolidStartTargetConfig = { nitro: options?.nitro };
246
247 const resolveTarget = (root: string) =>
248 FrameworkCore.resolveDeployTarget<SolidStartTarget, SolidStartTargetConfig>(
249 root,
250 options?.target ?? DEFAULT_TARGET_SPECIFIER,
251 targetConfig,
252 ).pipe(Effect.mapError((error) => fail(error.message, error.cause)));
253
254 const requireNitroPreset = (target: SolidStartTarget) =>
255 typeof target.nitroPreset === "string" && target.nitroPreset.length > 0
256 ? Effect.succeed(target)
257 : Effect.fail(
258 fail(
259 `The resolved "${target.platform}" deploy target does not declare the nitro ` +
260 "preset hook (`nitroPreset`) and has no wholesale `build`",
261 ),
262 );
263
264 const loadVite = (root: string) =>
265 FrameworkCore.loadProjectModule<SolidStartViteModule>(root, "vite").pipe(
266 Effect.mapError((error) => fail("Failed to load the project's Vite install", error.cause)),
267 );
268
269 const loadNitroPlugin = (root: string) =>
270 FrameworkCore.loadProjectModule<SolidStartNitroPluginModule>(
271 root,
272 NITRO_PLUGIN_SPECIFIER,
273 ).pipe(
274 Effect.mapError((error) =>
275 fail(
276 `Failed to load the project's "${NITRO_PLUGIN_SPECIFIER}" — install it alongside ` +
277 "`@solidjs/start`; it is the server half of a SolidStart build",
278 error.cause,
279 ),
280 ),
281 );
282
283 const build: Framework["Service"]["build"] = Effect.fn(function* (buildOptions) {
284 const root = buildOptions?.root ?? baseRoot;
285 const target = yield* resolveTarget(root);
286 const targetContext = {
287 root,
288 framework: "solidstart",
289 env: buildOptions?.env,
290 };
291
292 // Wholesale build takeover (the AWS target uses this seam to run the
293 // build in a disposable child process — vite.config.* executes user
294 // plugins that must not touch the engine process).
295 if (target.build !== undefined) {
296 return yield* target.build(targetContext).pipe(
297 Effect.mapError((error) => fail(error.message, error.cause)),
298 Effect.provideService(FileSystem.FileSystem, fs),
299 Effect.provideService(Path.Path, path),
300 );
301 }
302
303 yield* requireNitroPreset(target);
304
305 // Conflict policy: the deploy target owns the preset, so a foreign one
306 // is rejected with an actionable error instead of being replaced — a
307 // build for a different preset would never be deployed.
308 const conflict = findPresetConflict(options?.nitro, target.nitroPreset);
309 if (conflict !== undefined) {
310 return yield* fail(presetConflictMessage(conflict, target.nitroPreset));
311 }
312
313 const vite = yield* loadVite(root);
314 const nitro = yield* loadNitroPlugin(root);
315
316 const nitroConfig = resolveNitroConfig({
317 preset: target.nitroPreset,
318 rootDir: root,
319 nitro: options?.nitro,
320 configure: (config) => target.configureNitro?.(config, { root }),
321 });
322
323 // Detected inside vite's own config resolution (the project's
324 // `vite.config.*` has been loaded and merged by then), reported as a
325 // FrameworkError once the build promise rejects.
326 const detected = { conflict: false };
327 const plugins = markInjectedPlugins([
328 {
329 name: "alchemy:solidstart-nitro-conflict",
330 enforce: "pre" as const,
331 config: (config: { readonly plugins?: unknown }) => {
332 if (hasForeignNitroPlugin(config.plugins)) {
333 detected.conflict = true;
334 throw new Error(pluginConflictMessage());
335 }
336 return null;
337 },
338 },
339 nitro.nitroV2Plugin(nitroConfig),
340 ]);
341
342 yield* inProjectCwd(
343 root,
344 Effect.tryPromise({
345 try: async () => {
346 const builder = await vite.createBuilder({
347 root,
348 // Fixture clones have no local node_modules, so Vite would
349 // otherwise share `packages/alchemy/node_modules/.vite` with
350 // every other website test. Vocs writes shiki there; the
351 // SolidStart nitro graph then emits 11MB of grammars and
352 // SSR GET `/` hangs. Pin the cache under this project.
353 cacheDir: path.join(root, "node_modules", ".vite"),
354 // Warn-level: rolldown-vite's native progress reporter writes
355 // straight to the fd, corrupting hosting-process reporters
356 // that can only intercept JS-level writers.
357 logLevel: "warn",
358 plugins,
359 });
360 return await builder.buildApp();
361 },
362 catch: (error) =>
363 detected.conflict
364 ? fail(pluginConflictMessage(), error)
365 : fail("Failed to build", error),
366 }),
367 );
368
369 const dirs = resolveNitroOutputDirs(nitroConfig, root, (...segments) =>
370 path.resolve(...segments),
371 );
372 const output = yield* readNitroOutput(dirs).pipe(
373 Effect.provideService(FileSystem.FileSystem, fs),
374 );
375
376 // The finishing-pass seam (none needed for the aws-lambda preset — the
377 // output is already a self-contained Node deployment unit — but the
378 // contract is honored for targets that do post-process).
379 return yield* FrameworkCore.applyDeployTargetFinish(target, output, {
380 ...targetContext,
381 entry: path.join(dirs.serverDir, "index.mjs"),
382 }).pipe(
383 Effect.mapError((error) => fail(error.message, error.cause)),
384 Effect.provideService(FileSystem.FileSystem, fs),
385 Effect.provideService(Path.Path, path),
386 );
387 });
388
389 const devInProcess: Framework["Service"]["dev"] = Effect.fn(function* (devOptions) {
390 const root = devOptions?.root ?? baseRoot;
391 const vite = yield* loadVite(root);
392 // `port: 0` (true OS-assigned) on Vite >= 8.2.1, probed ephemeral port
393 // on older Vite — see `resolveViteDevPort`.
394 const port = yield* FrameworkCore.resolveViteDevPort(
395 vite.version,
396 devOptions?.port ?? options?.dev?.port,
397 );
398 const host = devOptions?.host;
399
400 const server = yield* Effect.acquireRelease(
401 inProjectCwd(
402 root,
403 Effect.tryPromise({
404 try: async () => {
405 const server = await vite.createServer({
406 root,
407 cacheDir: path.join(root, "node_modules", ".vite"),
408 logLevel: "warn",
409 server: {
410 port,
411 ...(host !== undefined ? { host } : undefined),
412 },
413 });
414 await server.listen();
415 return server;
416 },
417 catch: (error) => fail("Failed to start the SolidStart dev server", error),
418 }),
419 ),
420 (server) =>
421 Effect.promise(async () => {
422 try {
423 await server.close();
424 } catch {
425 // teardown is best-effort
426 }
427 }),
428 );
429
430 const resolved = server.resolvedUrls?.local[0];
431 if (resolved === undefined) {
432 return yield* fail("Could not determine the dev server URL");
433 }
434 // Vite reports its local URL with a trailing slash. SolidStart runs with
435 // `appType: "custom"`, so its router sees the raw pathname and a caller
436 // that appends a path (`${url}/about`) would request `//about` and get a
437 // 404. Hand back an origin that concatenates correctly.
438 const url = resolved.endsWith("/") ? resolved.slice(0, -1) : resolved;
439
440 // Bounded readiness probe: any HTTP response counts (vite serves
441 // lazily; we only need the listener to answer).
442 yield* Effect.tryPromise({
443 try: async () => {
444 const response = await fetch(url, { redirect: "manual" });
445 await response.arrayBuffer().catch(() => {});
446 },
447 catch: (error) => fail("The dev server did not become reachable", error),
448 }).pipe(Effect.retry({ schedule: Schedule.spaced("250 millis"), times: 40 }));
449
450 return { url };
451 });
452
453 // SolidStart's `solidStart()` plugin resolves the app from `process.cwd()`
454 // at config-load time, so its startup needs `cwd === root`. That must not
455 // happen in a process hosting other sites (the alchemy dev sidecar) — run
456 // the dev server in a dedicated child whose cwd IS the root instead (see
457 // core/DevChild.ts). Inside that child (or when the options cannot cross
458 // the process boundary, e.g. a deploy-target VALUE from the e2e harness)
459 // the in-process path runs directly.
460 const dev: Framework["Service"]["dev"] = (devOptions) => {
461 const root = devOptions?.root ?? baseRoot;
462 const port = devOptions?.port ?? options?.dev?.port;
463 if (FrameworkCore.isInsideDevChild() || !FrameworkCore.isJsonSerializable(options)) {
464 return devInProcess(devOptions);
465 }
466 return FrameworkCore.runDevChild({
467 framework: "solidstart",
468 module: "@alchemy.run/frontend-frameworks/solidstart",
469 callerUrl: import.meta.url,
470 rootDir: root,
471 makeOptions: { ...options, root },
472 devOptions: {
473 root,
474 ...(port !== undefined ? { port } : {}),
475 ...(devOptions?.host !== undefined ? { host: devOptions.host } : {}),
476 },
477 });
478 };
479
480 return Framework.of({ build, dev });
481 });
482
483 /** The nitro server entry's module name within the `BuildOutput` (POSIX). */
484 export const SERVER_ENTRY_NAME = "server/index.mjs";
485
486 /** The resolved nitro output directories. */
487 export interface NitroOutputDirs {
488 /** Root output directory (`.output`). */
489 readonly dir: string;
490 /** Server bundle directory (`.output/server`). */
491 readonly serverDir: string;
492 /** Static assets directory (`.output/public`, prerendered pages included). */
493 readonly publicDir: string;
494 }
495
496 /**
497 * Map nitro's on-disk `.output` onto the `BuildOutput` contract:
498 * `serverModules` entry-first from the server directory (POSIX names,
499 * sha256-hashed), `clientDirectory` = the public directory. Nitro's output
500 * is self-contained (externals are copied into `.output/server/node_modules`),
501 * so there are no external workspace roots to watch.
502 */
503 export const readNitroOutput = (
504 dirs: NitroOutputDirs,
505 ): Effect.Effect<FrameworkCore.BuildOutput, FrameworkError, FileSystem.FileSystem> =>
506 Effect.gen(function* () {
507 const modules = yield* FrameworkCore.readServerModulesFromDisk({
508 directory: dirs.serverDir,
509 prefix: "server",
510 }).pipe(Effect.mapError((error) => fail(error.message, error.cause)));
511 if (modules.length === 0) {
512 return yield* fail(`The SolidStart build produced no server modules in ${dirs.serverDir}`);
513 }
514 const serverModules = FrameworkCore.sortServerModules(modules, SERVER_ENTRY_NAME);
515 if (serverModules[0]?.name !== SERVER_ENTRY_NAME) {
516 return yield* fail(
517 `The SolidStart build produced no "${SERVER_ENTRY_NAME}" entry in ${dirs.serverDir}`,
518 );
519 }
520 return {
521 distDirectory: dirs.dir,
522 clientDirectory: dirs.publicDir,
523 serverModules,
524 externalWorkspaces: new Set<string>(),
525 } satisfies FrameworkCore.BuildOutput;
526 });
527
528 /**
529 * A `Layer` providing framework-core's `Framework` service for a SolidStart
530 * project — the fully-typed entrypoint for `e2e.config.ts` and alchemy's
531 * `AWS.Website.SolidStart` composite.
532 */
533 export const layer = (
534 options?: SolidStartOptions,
535 ): Layer.Layer<Framework, never, FileSystem.FileSystem | Path.Path> =>
536 Layer.effect(Framework, make(options));