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

main
ts 224 lines 7.4 KB
Raw
1 import * as Effect from "effect/Effect";
2 import * as FileSystem from "effect/FileSystem";
3 import * as Path from "effect/Path";
4 import type * as Scope from "effect/Scope";
5 import { runBuildChild } from "../core/BuildChild.ts";
6 /**
7 * `@alchemy.run/frontend-frameworks/vinext/node` — vinext on a Node
8 * container (vinext's Vite build + vinext's production server).
9 *
10 * Unlike the Cloudflare integration (`./source`, Vite + the Alchemy
11 * Cloudflare plugin + `vinext/server/fetch-handler`), this module does
12 * **not** inject a Workers plugin. The container-optimal path is a
13 * long-running Node process:
14 *
15 * - **`build`** runs Vinext's Vite build in a disposable child
16 * (cwd = project root), then writes a serve entry that calls
17 * `startProdServer` from `vinext/server/prod-server`, answers
18 * `GET /health`, and listens on `PORT` (default 3000).
19 * - **`dev`** runs the real `vinext dev` CLI (plain Node), scoped.
20 *
21 * Composites should load this module as both the framework specifier and
22 * the deploy target (same shape as `nextjs/node`).
23 */
24 import * as FrameworkCore from "../core/index.ts";
25 import { DeployTargetError, makeDeployTarget, type DeployTarget } from "../core/index.ts";
26 import {
27 NODE_BUNDLE_CONDITIONS,
28 NODE_DEFAULT_PORT,
29 NODE_SERVE_ENTRY_FILE_NAME,
30 } from "../core/NodeServe.ts";
31 import {
32 awaitVinextDevReady,
33 collectVinextDist,
34 failFramework,
35 pickEphemeralPort,
36 pinServeModule,
37 resolveVinextCli,
38 runVinextBuild,
39 spawnVinextDev,
40 } from "./cli.ts";
41
42 const failTarget = (message: string, cause?: unknown) =>
43 new DeployTargetError({ platform: "node", message, cause });
44
45 /** Options for the vinext Node framework module / deploy target. */
46 export interface VinextNodeOptions {
47 readonly root?: string | undefined;
48 /**
49 * The deploy target module specifier the caller resolved this module as.
50 * This module IS the Node target — accepted and ignored (parity with
51 * `nextjs/node`).
52 */
53 readonly target?: string | undefined;
54 }
55
56 export interface VinextNodeTargetConfig {
57 readonly root?: string | undefined;
58 }
59
60 export interface VinextNodeTarget extends DeployTarget<VinextNodeTargetConfig> {}
61
62 /** Serve-entry module name relative to `dist/`. */
63 export const SERVER_ENTRY_NAME = `server/${NODE_SERVE_ENTRY_FILE_NAME}`;
64
65 /**
66 * Packages the Node image `npm install`s so `startProdServer` and the
67 * RSC externals vinext leaves unbundled resolve at runtime.
68 */
69 export const VINEXT_NODE_INSTALL = [
70 "vinext",
71 "react",
72 "react-dom",
73 "react-server-dom-webpack",
74 ] as const;
75
76 /**
77 * The generated vinext Node serve entry: starts vinext's official
78 * production server and answers `GET /health` on the same listener.
79 */
80 export const makeVinextServeEntrySource = (): string =>
81 `// Generated by @alchemy.run/frontend-frameworks/vinext/node.
82 import * as path from "node:path";
83 import { fileURLToPath } from "node:url";
84 import { startProdServer } from "vinext/server/prod-server";
85
86 const dir = path.dirname(fileURLToPath(import.meta.url));
87 const PORT = Number.parseInt(process.env.PORT ?? "${String(NODE_DEFAULT_PORT)}", 10);
88 const HOST = process.env.HOST ?? "0.0.0.0";
89
90 const { server } = await startProdServer({
91 port: PORT,
92 host: HOST,
93 outDir: path.resolve(dir, ".."),
94 });
95
96 const isHealth = (req) => {
97 const urlPath = (req.url ?? "/").split("?")[0];
98 return (req.method === "GET" || req.method === "HEAD") && urlPath === "/health";
99 };
100
101 const existing = server.listeners("request").slice();
102 server.removeAllListeners("request");
103 server.on("request", (req, res) => {
104 if (isHealth(req)) {
105 res.writeHead(200, { "content-type": "text/plain; charset=utf-8" });
106 res.end("ok");
107 return;
108 }
109 for (const listener of existing) listener.call(server, req, res);
110 });
111 `;
112
113 export interface VinextNodeBuildChildConfig {
114 readonly rootDir: string;
115 readonly config: VinextNodeTargetConfig;
116 }
117
118 export const buildInChild = (config: VinextNodeBuildChildConfig) =>
119 Effect.gen(function* () {
120 const root = config.rootDir;
121 yield* runVinextBuild({ root, cache: "redis" });
122 const dist = yield* collectVinextDist(root);
123 return yield* pinServeModule(dist, SERVER_ENTRY_NAME, makeVinextServeEntrySource());
124 });
125
126 const makeNodeChildTarget = (config: VinextNodeTargetConfig = {}): VinextNodeTarget =>
127 makeDeployTarget({
128 platform: "node",
129 config,
130 bundle: {
131 conditions: [...NODE_BUNDLE_CONDITIONS],
132 },
133 });
134
135 /**
136 * Create the Node {@link VinextNodeTarget}: run Vinext's Vite build in a
137 * child process, then vinext's production serve entry.
138 */
139 export const makeNodeTarget = (config: VinextNodeTargetConfig = {}): VinextNodeTarget => ({
140 ...makeNodeChildTarget(config),
141 build: (context) =>
142 runBuildChild({
143 runtime: "node",
144 module: import.meta.url,
145 rootDir: context.root,
146 env: context.env,
147 framework: "vinext",
148 config: {
149 rootDir: context.root,
150 config,
151 } satisfies VinextNodeBuildChildConfig,
152 }).pipe(Effect.mapError((error) => failTarget(error.message, error.cause))),
153 });
154
155 export const target = makeNodeTarget;
156
157 export default makeNodeTarget;
158
159 export interface VinextNodeService {
160 readonly build: (options?: FrameworkCore.FrameworkBuildOptions) => Effect.Effect<
161 {
162 readonly distDirectory: string;
163 readonly clientDirectory: string | undefined;
164 readonly serverModules: Array<{ readonly name: string }>;
165 },
166 FrameworkCore.FrameworkError
167 >;
168 readonly dev: (
169 options?: FrameworkCore.FrameworkDevOptions,
170 ) => Effect.Effect<FrameworkCore.FrameworkDevServer, FrameworkCore.FrameworkError, Scope.Scope>;
171 }
172
173 /**
174 * Build the vinext-on-Node framework service. See the module doc for the
175 * `build`/`dev` semantics.
176 */
177 export const make: (
178 options?: VinextNodeOptions,
179 ) => Effect.Effect<VinextNodeService, never, FileSystem.FileSystem | Path.Path> = Effect.fnUntraced(
180 function* (options?: VinextNodeOptions) {
181 const fs = yield* FileSystem.FileSystem;
182 const path = yield* Path.Path;
183 const resolveRoot = (override: string | undefined) =>
184 Effect.sync(() => path.resolve(override ?? options?.root ?? process.cwd()));
185
186 const build: VinextNodeService["build"] = Effect.fn(function* (
187 buildOptions?: FrameworkCore.FrameworkBuildOptions,
188 ) {
189 const root = yield* resolveRoot(buildOptions?.root);
190 const nodeTarget = makeNodeTarget({ root });
191 const output = yield* nodeTarget.build!({
192 root,
193 framework: "vinext",
194 env: buildOptions?.env,
195 }).pipe(
196 Effect.provideService(FileSystem.FileSystem, fs),
197 Effect.provideService(Path.Path, path),
198 Effect.mapError((error) => failFramework(error.message)(error.cause)),
199 );
200 return {
201 distDirectory: output.distDirectory ?? path.join(root, "dist"),
202 clientDirectory: output.clientDirectory,
203 serverModules: (output.serverModules ?? []).map((module_) => ({
204 name: module_.name,
205 })),
206 };
207 });
208
209 const dev: VinextNodeService["dev"] = Effect.fn(function* (
210 devOptions?: FrameworkCore.FrameworkDevOptions,
211 ) {
212 const root = yield* resolveRoot(devOptions?.root);
213 const port = devOptions?.port ?? (yield* pickEphemeralPort);
214 const cli = yield* resolveVinextCli(root);
215 const host = devOptions?.host ?? "127.0.0.1";
216 const child = yield* spawnVinextDev({ root, cli, port, host });
217 const url = `http://${host}:${port}`;
218 yield* awaitVinextDevReady({ url, child });
219 return { url };
220 });
221
222 return { build, dev };
223 },
224 );