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

main
ts 556 lines 21.6 KB
Raw
1 import * as Effect from "effect/Effect";
2 import * as FileSystem from "effect/FileSystem";
3 import * as Layer from "effect/Layer";
4 import * as Path from "effect/Path";
5 import * as Schedule from "effect/Schedule";
6 import * as FrameworkCore from "../core/index.ts";
7 import {
8 Framework,
9 FrameworkError,
10 type DeployTarget,
11 type DeployTargetInput,
12 } from "../core/index.ts";
13
14 /**
15 * The structural slice of the project's `vite` module this package drives.
16 * Typed structurally so the package carries no dependency on vite — the
17 * *project's* install is always the one loaded.
18 *
19 * `build` (not `createBuilder`) is the entry point: the integration drives a
20 * two-pass build — `vite build` for the `client` environment, then `vite
21 * build` with `build.ssr` for the server environment — which is what
22 * `react-router build` runs. React Router 8 always builds through the Vite
23 * Environment API, so the server pass's overrides are declared on the `ssr`
24 * environment as well (see {@link inlineServerBuildConfig}).
25 */
26 export interface ReactRouterViteModule {
27 readonly version?: string;
28 readonly build: (config: Record<string, unknown>) => Promise<unknown>;
29 readonly createServer: (config: Record<string, unknown>) => Promise<ReactRouterViteDevServer>;
30 }
31
32 /** The structural slice of a Vite dev server this package reads. */
33 export interface ReactRouterViteDevServer {
34 readonly listen: () => Promise<unknown>;
35 readonly close: () => Promise<void>;
36 readonly resolvedUrls?: { readonly local: ReadonlyArray<string> } | null | undefined;
37 }
38
39 /** The slice of a resolved Vite config the output-directory capture reads. */
40 export interface ResolvedViteBuildSlice {
41 readonly root: string;
42 readonly build: { readonly outDir: string };
43 }
44
45 /**
46 * The configuration this package assembles from {@link ReactRouterOptions}
47 * and hands to a deploy-target factory. The target treats it as its
48 * `DeployTarget.config`; the framework half never inspects a resolved
49 * target's config.
50 */
51 export interface ReactRouterTargetConfig {
52 /**
53 * Build output directory relative to the project root — the parent of
54 * `client/` and `server/`. Mirrors `react-router.config.ts`'s
55 * `buildDirectory`, and is only a FALLBACK: the integration prefers the
56 * directories it observes on the resolved Vite config.
57 * @default "build"
58 */
59 readonly buildDirectory?: string | undefined;
60 }
61
62 /**
63 * A deploy target for React Router: the generic `DeployTarget` seams plus
64 * the one framework-specific hook the build needs — the file name of the
65 * server entry the server build emits, which the target's finishing pass
66 * wraps.
67 */
68 export interface ReactRouterTarget extends DeployTarget<ReactRouterTargetConfig> {
69 /**
70 * The server entry file name within the server output directory. React
71 * Router names it after `react-router.config.ts`'s `serverBuildFile`
72 * (default `index.js`). Omitted targets fall back to
73 * {@link DEFAULT_SERVER_BUILD_FILE}, and a build that emits exactly one
74 * top-level module under the server directory uses that instead when the
75 * expected name is absent.
76 */
77 readonly serverEntryFileName?: string | undefined;
78 }
79
80 /**
81 * How a deploy target is passed to this package: a `ReactRouterTarget`
82 * value, a factory `(config) => ReactRouterTarget`, or a module specifier
83 * resolved from the *project's* `node_modules`.
84 */
85 export type ReactRouterTargetInput = DeployTargetInput<ReactRouterTarget, ReactRouterTargetConfig>;
86
87 /**
88 * The default deploy target: this package's own AWS Lambda target module,
89 * loaded from the project's dependency tree. (Cloudflare deploys React
90 * Router through its native Vite integration — `Cloudflare.Website.Vite` —
91 * so no Cloudflare target exists here.)
92 */
93 export const DEFAULT_TARGET_SPECIFIER = "@alchemy.run/frontend-frameworks/react-router/aws";
94
95 /** The Vite plugin package a React Router project must install. */
96 export const REACT_ROUTER_PLUGIN_SPECIFIER = "@react-router/dev";
97
98 /** The default root output directory (the parent of `client/` and `server/`). */
99 export const DEFAULT_BUILD_DIRECTORY = "build";
100
101 /** The default server entry file name inside the server output directory. */
102 export const DEFAULT_SERVER_BUILD_FILE = "index.js";
103
104 /**
105 * React Router's own virtual module holding the compiled server build — the
106 * `ServerBuild` manifest (`{ entry, routes, assets, basename, ... }`), NOT a
107 * request handler.
108 */
109 export const REACT_ROUTER_SERVER_BUILD_ID = "virtual:react-router/server-build";
110
111 /**
112 * The virtual module this integration makes the server build's rollup input:
113 * it turns the `ServerBuild` manifest into a web-standard fetch handler.
114 */
115 export const SERVER_ENTRY_ID = "virtual:alchemy/react-router-server-entry";
116
117 /** Rollup's convention for a plugin-owned virtual module id. */
118 const RESOLVED_SERVER_ENTRY_ID = `\0${SERVER_ENTRY_ID}`;
119
120 export interface ReactRouterOptions {
121 /**
122 * Project root (the directory containing `vite.config.*`).
123 * @default process.cwd()
124 */
125 readonly root?: string | undefined;
126 /**
127 * The deploy target the build is produced for. Accepts a target value, a
128 * `(config) => target` factory, or a module specifier string.
129 * @default "@alchemy.run/frontend-frameworks/react-router/aws"
130 */
131 readonly target?: ReactRouterTargetInput | undefined;
132 /**
133 * Build output directory relative to the project root — the parent of
134 * `client/` and `server/`. Mirrors `react-router.config.ts`'s
135 * `buildDirectory`; used only as a fallback when the resolved Vite config
136 * could not be observed.
137 * @default "build"
138 */
139 readonly buildDirectory?: string | undefined;
140 readonly dev?:
141 | {
142 /** Default dev-server port (overridden by `FrameworkDevOptions.port`). */
143 readonly port?: number | undefined;
144 }
145 | undefined;
146 }
147
148 const fail = (message: string, cause?: unknown) =>
149 new FrameworkError({ framework: "react-router", message, cause });
150
151 /**
152 * The source of the virtual server entry ({@link SERVER_ENTRY_ID}).
153 *
154 * React Router's server build is a manifest, not a handler: it has no
155 * default export and nothing to call. `createRequestHandler` from
156 * `react-router` turns it into `(request) => Promise<Response>`, and this
157 * module exposes that as the `{ fetch }` shape every deploy target's
158 * finishing pass already knows how to wrap.
159 *
160 * This wrapping happens at BUILD time (as the server build's rollup input)
161 * rather than as a file emitted afterwards, because `react-router` itself
162 * must be part of the emitted bundle — the deployed server directory ships
163 * without a `node_modules` tree.
164 */
165 export const serverEntrySource = (mode: string = "production"): string =>
166 `// Auto-generated by @alchemy.run/frontend-frameworks/react-router — do not edit.
167 import * as build from "${REACT_ROUTER_SERVER_BUILD_ID}";
168 import { createRequestHandler } from "react-router";
169
170 const handleRequest = createRequestHandler(build, ${JSON.stringify(mode)});
171
172 export default {
173 fetch(request) {
174 return handleRequest(request);
175 },
176 };
177 `;
178
179 /** The structural slice of a Vite plugin this integration constructs. */
180 export interface InlineVitePlugin {
181 readonly name: string;
182 readonly enforce?: "pre" | "post" | undefined;
183 readonly resolveId?: ((id: string) => string | undefined) | undefined;
184 readonly load?: ((id: string) => string | undefined) | undefined;
185 readonly configResolved?: ((config: ResolvedViteBuildSlice) => void) | undefined;
186 }
187
188 /**
189 * The Vite plugin serving {@link SERVER_ENTRY_ID}. `enforce: "pre"` so the
190 * virtual id resolves before any project plugin sees it.
191 */
192 export const serverEntryPlugin = (options?: {
193 readonly mode?: string | undefined;
194 }): InlineVitePlugin => ({
195 name: "alchemy:react-router-server-entry",
196 enforce: "pre",
197 resolveId: (id) => (id === SERVER_ENTRY_ID ? RESOLVED_SERVER_ENTRY_ID : undefined),
198 load: (id) => (id === RESOLVED_SERVER_ENTRY_ID ? serverEntrySource(options?.mode) : undefined),
199 });
200
201 /** A mutable slot the {@link captureOutDirPlugin} writes the resolved outDir into. */
202 export interface OutDirCapture {
203 outDir?: string | undefined;
204 }
205
206 /**
207 * The Vite plugin that observes the RESOLVED output directory of a build.
208 *
209 * React Router derives both output directories from `react-router.config.ts`
210 * (`buildDirectory`), which is TypeScript the integration must not evaluate
211 * itself. Reading them off the config Vite actually resolved is exact, free,
212 * and honors every project override.
213 */
214 export const captureOutDirPlugin = (capture: OutDirCapture): InlineVitePlugin => ({
215 name: "alchemy:react-router-capture-outdir",
216 enforce: "post",
217 configResolved: (config) => {
218 capture.outDir = config.build.outDir;
219 },
220 });
221
222 /**
223 * The inline config for the CLIENT pass, merged over the project's own
224 * `vite.config.*` (which loads natively, plugins included).
225 */
226 export const inlineClientBuildConfig = (
227 root: string,
228 plugins: ReadonlyArray<InlineVitePlugin>,
229 ): Record<string, unknown> => ({
230 root,
231 mode: "production",
232 // Warn-level: rolldown-vite's native progress reporter writes straight to
233 // the fd, corrupting hosting-process reporters that can only intercept
234 // JS-level writers.
235 logLevel: "warn",
236 plugins,
237 });
238
239 /**
240 * The inline config for the SERVER pass.
241 *
242 * Two overrides carry the whole AWS story:
243 *
244 * - `build.ssr` selects React Router's server environment (the flag its
245 * plugin branches on), and `build.rollupOptions.input` replaces the
246 * framework's `virtual:react-router/server-build` input with the fetch
247 * handler wrapper ({@link serverEntrySource}) — the plugin honors a
248 * user-provided input verbatim.
249 * - `noExternal` is load-bearing: Vite externalizes `node_modules` imports
250 * from SSR bundles by default, so a stock React Router server build emits
251 * `import { ServerRouter } from "react-router"` and is only runnable next
252 * to an installed dependency tree. A Lambda ships the server directory
253 * alone, so the bundle must be self-contained — only `node:` builtins
254 * stay external. Declared on both the legacy `ssr` key and the
255 * environment key so it holds across Vite majors.
256 */
257 export const inlineServerBuildConfig = (
258 root: string,
259 plugins: ReadonlyArray<InlineVitePlugin>,
260 ): Record<string, unknown> => ({
261 root,
262 mode: "production",
263 logLevel: "warn",
264 build: {
265 ssr: true,
266 rollupOptions: { input: SERVER_ENTRY_ID },
267 },
268 ssr: { noExternal: true },
269 // React Router 8 always builds through the Vite Environment API: its SSR
270 // environment reads its own `build.rollupOptions.input`, not the top-level
271 // one, so the wrapper input is declared there too.
272 environments: {
273 ssr: {
274 build: { rollupOptions: { input: SERVER_ENTRY_ID } },
275 resolve: { noExternal: true },
276 },
277 },
278 plugins,
279 });
280
281 /**
282 * Build the `Framework` service implementation for a React Router v7
283 * project (framework mode).
284 *
285 * - `build` resolves the deploy target, then either delegates wholesale
286 * (`target.build`) or drives the PROJECT's own Vite install
287 * programmatically, mirroring what `react-router build` does: the client
288 * pass first (it writes the asset manifest the server pass reads), then
289 * the server pass with `build.ssr`. `reactRouter()` in the project's
290 * `vite.config.ts` owns routing, typegen, and both environments — there
291 * is no adapter to select and no plugin to inject beyond the fetch-handler
292 * entry ({@link serverEntrySource}) and the self-contained SSR bundle
293 * ({@link inlineServerBuildConfig}). The `BuildOutput` is read from disk:
294 * `serverModules` entry-first from the server directory,
295 * `clientDirectory` = the client directory, both observed off the
296 * resolved Vite config.
297 * - `dev` runs the project's own Vite dev server (React Router's plugin
298 * serves SSR, resource routes, and typegen through it with native HMR),
299 * scoped — closing the Scope closes the server.
300 *
301 * NOT supported: React Server Components / multi-environment builds (React
302 * Router's `unstable` RSC plugin). Those
303 * emit more than one server environment, which this two-pass build does not
304 * assemble; the build fails with an actionable error when no single server
305 * entry is produced.
306 *
307 * This module is target-agnostic: everything AWS-specific lives in
308 * `@alchemy.run/frontend-frameworks/react-router/aws`.
309 */
310 export const make: (
311 options?: ReactRouterOptions,
312 ) => Effect.Effect<Framework["Service"], never, FileSystem.FileSystem | Path.Path> =
313 Effect.fnUntraced(function* (options?: ReactRouterOptions) {
314 const fs = yield* FileSystem.FileSystem;
315 const path = yield* Path.Path;
316 const baseRoot = options?.root ?? (yield* Effect.sync(() => process.cwd()));
317
318 const targetConfig: ReactRouterTargetConfig = {
319 buildDirectory: options?.buildDirectory,
320 };
321
322 const resolveTarget = (root: string) =>
323 FrameworkCore.resolveDeployTarget<ReactRouterTarget, ReactRouterTargetConfig>(
324 root,
325 options?.target ?? DEFAULT_TARGET_SPECIFIER,
326 targetConfig,
327 ).pipe(Effect.mapError((error) => fail(error.message, error.cause)));
328
329 const loadVite = (root: string) =>
330 FrameworkCore.loadProjectModule<ReactRouterViteModule>(root, "vite").pipe(
331 Effect.mapError((error) => fail("Failed to load the project's Vite install", error.cause)),
332 );
333
334 const removeViteManifests = (directories: ReadonlyArray<string>) =>
335 Effect.forEach(directories, (directory) =>
336 fs.remove(path.join(directory, ".vite"), { recursive: true }).pipe(Effect.ignore),
337 );
338
339 const build: Framework["Service"]["build"] = Effect.fn(function* (buildOptions) {
340 const root = buildOptions?.root ?? baseRoot;
341 const target = yield* resolveTarget(root);
342 const targetContext = {
343 root,
344 framework: "react-router",
345 env: buildOptions?.env,
346 };
347
348 // Wholesale build takeover (the AWS target uses this seam to run the
349 // build in a disposable child process — vite.config.* executes user
350 // plugins that must not touch the engine process, and React Router's
351 // config loader resolves `react-router.config.ts` from the cwd).
352 if (target.build !== undefined) {
353 return yield* target.build(targetContext).pipe(
354 Effect.mapError((error) => fail(error.message, error.cause)),
355 Effect.provideService(FileSystem.FileSystem, fs),
356 Effect.provideService(Path.Path, path),
357 );
358 }
359
360 const vite = yield* loadVite(root);
361 const clientCapture: OutDirCapture = {};
362 const serverCapture: OutDirCapture = {};
363
364 yield* Effect.tryPromise({
365 try: () => vite.build(inlineClientBuildConfig(root, [captureOutDirPlugin(clientCapture)])),
366 catch: (error) => fail("Failed to build the client", error),
367 });
368 yield* Effect.tryPromise({
369 try: () =>
370 vite.build(
371 inlineServerBuildConfig(root, [
372 serverEntryPlugin(),
373 captureOutDirPlugin(serverCapture),
374 ]),
375 ),
376 catch: (error) => fail("Failed to build the server", error),
377 });
378
379 const fallbackDir = path.resolve(root, options?.buildDirectory ?? DEFAULT_BUILD_DIRECTORY);
380 const clientDir =
381 clientCapture.outDir !== undefined
382 ? path.resolve(root, clientCapture.outDir)
383 : path.join(fallbackDir, "client");
384 const serverDir =
385 serverCapture.outDir !== undefined
386 ? path.resolve(root, serverCapture.outDir)
387 : path.join(fallbackDir, "server");
388
389 // `react-router build` deletes the per-environment Vite manifests once
390 // the server pass has consumed the client one; ours would otherwise
391 // ship to the CDN as a public `/.vite/manifest.json`.
392 yield* removeViteManifests([clientDir, serverDir]);
393
394 const output = yield* readReactRouterOutput({
395 dir: path.dirname(serverDir),
396 serverDir,
397 clientDir,
398 serverEntryFileName: target.serverEntryFileName,
399 }).pipe(Effect.provideService(FileSystem.FileSystem, fs));
400
401 const entryName = output.serverModules?.[0]?.name;
402 return yield* FrameworkCore.applyDeployTargetFinish(target, output, {
403 ...targetContext,
404 ...(entryName !== undefined
405 ? { entry: path.join(output.distDirectory ?? root, entryName) }
406 : undefined),
407 }).pipe(
408 Effect.mapError((error) => fail(error.message, error.cause)),
409 Effect.provideService(FileSystem.FileSystem, fs),
410 Effect.provideService(Path.Path, path),
411 );
412 });
413
414 const dev: Framework["Service"]["dev"] = Effect.fn(function* (devOptions) {
415 const root = devOptions?.root ?? baseRoot;
416 const vite = yield* loadVite(root);
417 // `port: 0` (true OS-assigned) on Vite >= 8.2.1, probed ephemeral port
418 // on older Vite — see `resolveViteDevPort`.
419 const port = yield* FrameworkCore.resolveViteDevPort(
420 vite.version,
421 devOptions?.port ?? options?.dev?.port,
422 );
423 const host = devOptions?.host;
424
425 const server = yield* Effect.acquireRelease(
426 Effect.tryPromise({
427 try: async () => {
428 const server = await vite.createServer({
429 root,
430 logLevel: "warn",
431 server: {
432 port,
433 ...(host !== undefined ? { host } : undefined),
434 },
435 });
436 await server.listen();
437 return server;
438 },
439 catch: (error) => fail("Failed to start the React Router dev server", error),
440 }),
441 (server) =>
442 Effect.promise(async () => {
443 try {
444 await server.close();
445 } catch {
446 // teardown is best-effort
447 }
448 }),
449 );
450
451 const resolved = server.resolvedUrls?.local[0];
452 if (resolved === undefined) {
453 return yield* fail("Could not determine the dev server URL");
454 }
455 // Vite reports its local URL with a trailing slash; hand back an origin
456 // that concatenates correctly (`${url}/about`, not `//about`).
457 const url = resolved.endsWith("/") ? resolved.slice(0, -1) : resolved;
458
459 // Bounded readiness probe: any HTTP response counts (vite serves
460 // lazily; we only need the listener to answer).
461 yield* Effect.tryPromise({
462 try: async () => {
463 const response = await fetch(url, { redirect: "manual" });
464 await response.arrayBuffer().catch(() => {});
465 },
466 catch: (error) => fail("The dev server did not become reachable", error),
467 }).pipe(Effect.retry({ schedule: Schedule.spaced("250 millis"), times: 40 }));
468
469 return { url };
470 });
471
472 return Framework.of({ build, dev });
473 });
474
475 /** The resolved React Router build output directories. */
476 export interface ReactRouterOutputDirs {
477 /** Root output directory (`<root>/build`) — the parent of both. */
478 readonly dir: string;
479 /** Server bundle directory (`<root>/build/server`). */
480 readonly serverDir: string;
481 /** Client assets directory (`<root>/build/client`), `public/` copied in. */
482 readonly clientDir: string;
483 /**
484 * The emitted server entry file name within `serverDir`.
485 * @default "index.js"
486 */
487 readonly serverEntryFileName?: string | undefined;
488 }
489
490 /**
491 * Pick the server entry among the modules read off disk.
492 *
493 * The expected name wins. Otherwise, a build whose server directory holds
494 * exactly one top-level module (chunks live under `assets/`) is
495 * unambiguous — that module is the entry, which covers a project that sets
496 * `serverBuildFile` to something other than `index.js`.
497 */
498 export const selectServerEntryName = (
499 moduleNames: ReadonlyArray<string>,
500 expected: string,
501 ): string | undefined => {
502 if (moduleNames.includes(expected)) return expected;
503 const topLevel = moduleNames.filter(
504 (name) =>
505 !name.slice("server/".length).includes("/") &&
506 (name.endsWith(".js") || name.endsWith(".mjs")),
507 );
508 return topLevel.length === 1 ? topLevel[0] : undefined;
509 };
510
511 /**
512 * Map React Router's on-disk build tree onto the `BuildOutput` contract:
513 * `serverModules` entry-first from `<buildDirectory>/server` (POSIX names,
514 * sha256-hashed), `clientDirectory` = `<buildDirectory>/client`. The server
515 * bundle is built with `noExternal`, so it is self-contained (only `node:`
516 * builtins external) and there are no external workspace roots to watch.
517 */
518 export const readReactRouterOutput = (
519 dirs: ReactRouterOutputDirs,
520 ): Effect.Effect<FrameworkCore.BuildOutput, FrameworkError, FileSystem.FileSystem> =>
521 Effect.gen(function* () {
522 const expected = `server/${dirs.serverEntryFileName ?? DEFAULT_SERVER_BUILD_FILE}`;
523 const modules = yield* FrameworkCore.readServerModulesFromDisk({
524 directory: dirs.serverDir,
525 prefix: "server",
526 }).pipe(Effect.mapError((error) => fail(error.message, error.cause)));
527 if (modules.length === 0) {
528 return yield* fail(`The React Router build produced no server modules in ${dirs.serverDir}`);
529 }
530 const entryName = selectServerEntryName(
531 modules.map((module) => module.name),
532 expected,
533 );
534 if (entryName === undefined) {
535 return yield* fail(
536 `The React Router build produced no "${expected}" entry in ${dirs.serverDir} — ` +
537 "React Server Components and multi-environment builds are not supported yet.",
538 );
539 }
540 return {
541 distDirectory: dirs.dir,
542 clientDirectory: dirs.clientDir,
543 serverModules: FrameworkCore.sortServerModules(modules, entryName),
544 externalWorkspaces: new Set<string>(),
545 } satisfies FrameworkCore.BuildOutput;
546 });
547
548 /**
549 * A `Layer` providing framework-core's `Framework` service for a React
550 * Router project — the fully-typed entrypoint for `e2e.config.ts` and
551 * alchemy's `AWS.Website.ReactRouter` composite.
552 */
553 export const layer = (
554 options?: ReactRouterOptions,
555 ): Layer.Layer<Framework, never, FileSystem.FileSystem | Path.Path> =>
556 Layer.effect(Framework, make(options));