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

main
ts 380 lines 15 KB
Raw
1 import { createRequire } from "node:module";
2 /*!
3 * Client metadata collection adapted from @octanejs/vite-plugin 0.5.0.
4 * MIT License
5 * Copyright (c) 2026 Dominic Gannaway
6 *
7 * Permission is hereby granted, free of charge, to any person obtaining a copy
8 * of this software and associated documentation files (the "Software"), to deal
9 * in the Software without restriction, including without limitation the rights
10 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
11 * copies of the Software, and to permit persons to whom the Software is
12 * furnished to do so, subject to the following conditions:
13 *
14 * The above copyright notice and this permission notice shall be included in all
15 * copies or substantial portions of the Software.
16 *
17 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
20 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
22 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
23 * SOFTWARE.
24 */
25 import * as Effect from "effect/Effect";
26 import * as FileSystem from "effect/FileSystem";
27 import * as Path from "effect/Path";
28 import type { InlineConfig, Plugin, PluginOption, ResolvedConfig } from "vite";
29 import {
30 FrameworkError,
31 loadProjectModule,
32 resolveProjectPackageDirectory,
33 } from "../core/index.ts";
34 import { readOctaneOutput } from "./Octane.ts";
35
36 interface OctaneConfig {
37 readonly adapter?: { readonly name?: string };
38 readonly router: {
39 readonly routes: ReadonlyArray<{
40 readonly type: string;
41 readonly entry?: unknown;
42 readonly layout?: string;
43 }>;
44 readonly preHydrate?: string;
45 };
46 readonly rootBoundary: {
47 readonly pending?: unknown;
48 readonly catch?: unknown;
49 };
50 readonly build: {
51 readonly outDir: string;
52 readonly minify?: boolean;
53 readonly target?: string;
54 };
55 }
56
57 interface OctanePluginModule {
58 readonly loadOctaneConfig: (root: string) => Promise<OctaneConfig | null>;
59 readonly getOctaneConfigPath: (root: string) => string;
60 readonly get_route_entry_path: (entry: unknown) => string | undefined;
61 }
62
63 interface ManifestEntry {
64 readonly file: string;
65 readonly src?: string;
66 readonly css?: string[];
67 readonly imports?: string[];
68 readonly dynamicImports?: string[];
69 }
70
71 type ClientAssets = Record<string, { js: string; css: string[] }>;
72
73 const fail = (message: string, cause?: unknown) =>
74 new FrameworkError({ framework: "octane", message, cause });
75
76 /** Keep Octane's compiler and client hooks; Alchemy builds the server separately. */
77 export const clientPlugins = (
78 options: ReadonlyArray<PluginOption>,
79 ): Effect.Effect<Plugin[], FrameworkError> =>
80 Effect.gen(function* () {
81 const plugins: Plugin[] = [];
82 const visit = (option: PluginOption): Effect.Effect<void, FrameworkError> =>
83 Effect.gen(function* () {
84 const resolved = yield* Effect.tryPromise({
85 try: () => Promise.resolve(option),
86 catch: (cause) => fail("Failed to resolve a Vite plugin", cause),
87 });
88 if (Array.isArray(resolved)) {
89 for (const child of resolved) yield* visit(child);
90 } else if (resolved) {
91 plugins.push(resolved);
92 }
93 });
94 for (const option of options) yield* visit(option);
95 const octane = plugins.filter((plugin) => plugin.name === "@octanejs/vite-plugin");
96 if (octane.length !== 1 || octane[0]?.closeBundle === undefined) {
97 return yield* fail("Expected one native octane() Vite plugin with a server build hook");
98 }
99 return plugins.map((plugin) =>
100 plugin === octane[0] ? { ...plugin, closeBundle: undefined } : plugin,
101 );
102 });
103
104 /** Generate the Worker entry without importing build-time adapter code. */
105 export const workerEntry = (options: {
106 readonly manifest: string;
107 readonly production: string;
108 readonly htmlTemplate: string;
109 }) => `import { manifest, rendererDeps } from ${JSON.stringify(options.manifest)};
110 import { createHandler } from ${JSON.stringify(options.production)};
111
112 let handler;
113 export default {
114 fetch(request, env, ctx) {
115 handler ??= createHandler(manifest, {
116 ...rendererDeps,
117 htmlTemplate: ${JSON.stringify(options.htmlTemplate)},
118 });
119 return handler(request, { env, ctx });
120 },
121 };
122 `;
123
124 export const buildCloudflare = (rootDirectory: string) =>
125 Effect.scoped(
126 Effect.gen(function* () {
127 const fs = yield* FileSystem.FileSystem;
128 const path = yield* Path.Path;
129 const root = path.resolve(rootDirectory);
130 const vite = yield* loadProjectModule<typeof import("vite")>(root, "vite");
131 const pluginDirectory = yield* resolveProjectPackageDirectory(
132 root,
133 "@octanejs/vite-plugin",
134 ).pipe(Effect.flatMap((directory) => fs.realPath(directory)));
135 const resolveModule = yield* Effect.sync(
136 () => createRequire(path.join(pluginDirectory, "package.json")).resolve,
137 );
138 const octane = yield* loadProjectModule<OctanePluginModule>(root, "@octanejs/vite-plugin");
139 const codegen = yield* loadProjectModule<{
140 generateServerEntry: (options: Record<string, unknown>) => string;
141 }>(pluginDirectory, "@octanejs/app-core/codegen");
142 const assetHelper = yield* loadProjectModule<{
143 createClientAssetMap: (
144 manifest: Record<string, ManifestEntry>,
145 entries: string[],
146 files: Record<string, string>,
147 ) => ClientAssets;
148 }>(pluginDirectory, path.join(pluginDirectory, "src/client-assets.js"));
149 const config = yield* Effect.tryPromise({
150 try: () => octane.loadOctaneConfig(root),
151 catch: (cause) => fail("Failed to load octane.config.ts", cause),
152 });
153 if (config === null || config.router.routes.length === 0) {
154 return yield* fail("A fullstack Octane app with octane.config.ts routes is required");
155 }
156 if (config.adapter !== undefined && config.adapter.name !== "cloudflare") {
157 return yield* fail(
158 `The Octane adapter "${config.adapter.name}" is incompatible with Cloudflare`,
159 );
160 }
161 const entries = yield* Effect.sync(() => [
162 ...new Set(
163 [
164 ...config.router.routes
165 .filter((route) => route.type === "render")
166 .flatMap((route) => [octane.get_route_entry_path(route.entry), route.layout]),
167 config.router.preHydrate,
168 octane.get_route_entry_path(config.rootBoundary.pending),
169 octane.get_route_entry_path(config.rootBoundary.catch),
170 ].filter((entry): entry is string => typeof entry === "string"),
171 ),
172 ]);
173 const loadConfig = (ssr: boolean) =>
174 Effect.tryPromise({
175 try: () =>
176 vite.loadConfigFromFile(
177 { command: "build", mode: "production", isSsrBuild: ssr },
178 undefined,
179 root,
180 "warn",
181 ),
182 catch: (cause) => fail("Failed to load vite.config", cause),
183 }).pipe(Effect.map((loaded) => loaded?.config ?? {}));
184 const clientConfig = yield* loadConfig(false);
185 const plugins = yield* clientPlugins(clientConfig.plugins ?? []);
186 if (clientConfig.root !== undefined && path.resolve(root, clientConfig.root) !== root) {
187 return yield* fail("Set rootDir to the Octane app root instead of overriding Vite root");
188 }
189 let clientDir = path.resolve(root, config.build.outDir, "client");
190 let islandsEntry: string | null = null;
191 let resolvedConfig: ResolvedConfig | undefined;
192 const rpcModules = new Set<string>();
193 const entryFiles: Record<string, string> = {};
194 const collect: Plugin = {
195 name: "alchemy:octane-client-metadata",
196 configResolved(config) {
197 clientDir = path.resolve(config.root, config.build.outDir);
198 resolvedConfig = config;
199 },
200 transform(code, id, options) {
201 const file = id.split("?")[0]!;
202 if (options?.ssr || !/\.(tsrx|tsx)$/.test(file) || !code.includes("_$__serverRpc"))
203 return;
204 const relative = path.relative(root, file);
205 rpcModules.add(
206 relative === ".." || relative.startsWith(`..${path.sep}`) || path.isAbsolute(relative)
207 ? file
208 : `/${relative.replaceAll("\\", "/")}`,
209 );
210 },
211 generateBundle(_options, bundle) {
212 for (const output of Object.values(bundle)) {
213 if (output.type !== "chunk") continue;
214 if (output.facadeModuleId === "\0virtual:octane-islands") {
215 islandsEntry = hydrationEntryUrl(output.fileName, resolvedConfig!);
216 }
217 for (const entry of entries) {
218 const id = path
219 .resolve(root, entry.startsWith("/") ? `.${entry}` : entry)
220 .replaceAll("\\", "/");
221 if (output.moduleIds.some((module) => module.replaceAll("\\", "/") === id)) {
222 entryFiles[entry] ??= output.fileName;
223 }
224 }
225 }
226 },
227 };
228 const serverDir = path.resolve(root, config.build.outDir, "server");
229 yield* Effect.tryPromise({
230 try: () =>
231 vite.build({
232 ...clientConfig,
233 root,
234 configFile: false,
235 plugins: plugins.flatMap((plugin) =>
236 plugin.name === "@octanejs/vite-plugin" ? [plugin, collect] : [plugin],
237 ),
238 logLevel: "warn",
239 }),
240 catch: (cause) => fail("Failed to build the Octane client", cause),
241 });
242 const manifest = yield* fs.readFileString(path.join(clientDir, ".vite/manifest.json")).pipe(
243 Effect.flatMap((source) =>
244 Effect.try({
245 try: () => JSON.parse(source) as Record<string, ManifestEntry>,
246 catch: (cause) => fail("Invalid Octane client manifest", cause),
247 }),
248 ),
249 );
250 const readJson = (file: string) =>
251 fs.readFileString(path.join(clientDir, file)).pipe(
252 Effect.flatMap((source) =>
253 Effect.try({
254 try: () => JSON.parse(source) as unknown,
255 catch: (cause) => fail(`Invalid Octane client build file ${file}`, cause),
256 }),
257 ),
258 );
259 const clientBuild = yield* readJson("octane-client-build.json");
260 const independentHydrationFile = "octane-independent-hydration.json";
261 const independentHydrationManifest = (yield* fs.exists(
262 path.join(clientDir, independentHydrationFile),
263 ))
264 ? yield* readJson(independentHydrationFile)
265 : null;
266 const clientAssets = yield* Effect.sync(() =>
267 assetHelper.createClientAssetMap(manifest, entries, entryFiles),
268 );
269 const htmlTemplate = yield* fs.readFileString(path.join(clientDir, "index.html"));
270 const directory = yield* fs.makeTempDirectoryScoped({
271 directory: root,
272 prefix: ".alchemy-octane-worker-",
273 });
274 const manifestFile = path.join(directory, "manifest.mjs");
275 const workerFile = path.join(directory, "worker.mjs");
276 const production = yield* Effect.try(() => resolveModule("@octanejs/app-core/production"));
277 const source = yield* Effect.try({
278 try: () =>
279 codegen.generateServerEntry({
280 routes: config.router.routes,
281 rootBoundary: config.rootBoundary,
282 octaneConfigPath: octane.getOctaneConfigPath(root),
283 rpcModulePaths: [...rpcModules],
284 clientAssetMap: clientAssets,
285 clientBuild,
286 independentHydrationManifest,
287 islandsEntry,
288 mode: "manifest",
289 configModuleId: resolveModule("@octanejs/app-core/config"),
290 generatedBy: "@alchemy.run/frontend-frameworks",
291 }),
292 catch: (cause) => fail("Failed to generate the Octane server manifest", cause),
293 });
294 yield* fs.writeFileString(manifestFile, source);
295 const workerSource = yield* Effect.sync(() =>
296 workerEntry({ manifest: manifestFile, production, htmlTemplate }),
297 );
298 yield* fs.writeFileString(workerFile, workerSource);
299 const serverConfig = yield* loadConfig(true);
300 const serverOptions: InlineConfig = yield* Effect.sync(() =>
301 vite.mergeConfig(serverConfig, {
302 root,
303 configFile: false,
304 appType: "custom",
305 logLevel: "warn",
306 define: { "process.env.NODE_ENV": JSON.stringify("production") },
307 resolve: {
308 conditions: ["workerd", "worker", "module", "browser", "production"],
309 alias: [
310 {
311 find: /^@octanejs\/vite-plugin$/,
312 replacement: path.join(pluginDirectory, "src/config-entry.js"),
313 },
314 ],
315 },
316 build: {
317 outDir: serverDir,
318 emptyOutDir: true,
319 ssr: true,
320 target: config.build.target,
321 minify: config.build.minify ?? false,
322 rollupOptions: {
323 input: workerFile,
324 external: [/^(node|cloudflare):/],
325 output: { entryFileNames: "worker.js", format: "esm" },
326 },
327 },
328 ssr: {
329 target: "webworker",
330 noExternal: true,
331 external: ["vite"],
332 resolve: {
333 conditions: ["workerd", "worker", "module", "browser", "production"],
334 },
335 },
336 } satisfies InlineConfig),
337 );
338 yield* Effect.tryPromise({
339 try: () => vite.build(serverOptions),
340 catch: (cause) => fail("Failed to build the Octane Worker", cause),
341 });
342 yield* fs.remove(path.join(clientDir, "index.html"));
343 yield* fs.remove(path.join(clientDir, ".vite"), { recursive: true });
344 yield* fs.remove(path.join(clientDir, "octane-client-build.json"));
345 yield* fs.remove(path.join(clientDir, independentHydrationFile), { force: true });
346 return yield* readOctaneOutput({
347 dir: path.resolve(root, config.build.outDir),
348 clientDir,
349 serverDir,
350 serverEntryFileName: "worker.js",
351 });
352 }).pipe(
353 Effect.mapError((cause) =>
354 cause instanceof FrameworkError
355 ? cause
356 : fail("Failed to build Octane for Cloudflare", cause),
357 ),
358 ),
359 );
360
361 /**
362 * Mirrors `@octanejs/vite-plugin`'s `hydrationEntryUrl`: the islands bootstrap
363 * URL honors `base` and `experimental.renderBuiltUrl` like Vite's HTML assets.
364 */
365 const hydrationEntryUrl = (filename: string, config: ResolvedConfig): string => {
366 let relative = config.base === "" || config.base === "./";
367 const rendered = config.experimental.renderBuiltUrl?.(filename, {
368 hostId: "index.html",
369 hostType: "html",
370 type: "asset",
371 ssr: false,
372 });
373 if (typeof rendered === "string") return rendered;
374 if (rendered?.runtime) {
375 throw new Error("[@octanejs/vite-plugin] Runtime asset URLs are not supported in HTML.");
376 }
377 if (typeof rendered?.relative === "boolean") relative = rendered.relative;
378 if (relative) return `./${filename}`;
379 return `${decodeURI(config.base).replace(/\/$/, "")}/${filename}`;
380 };