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

main
ts 414 lines 16.4 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 `@octanejs/vite-plugin` module this
16 * package drives. Typed structurally so the package carries no dependency on
17 * `@octanejs/vite-plugin` — the *project's* install is always the one loaded.
18 */
19 export interface OctaneVitePluginModule {
20 /**
21 * Load and resolve the project's `octane.config.ts` (spins a temporary
22 * Vite module runner internally when no dev server is supplied, so `.tsrx`
23 * imports in the config graph resolve).
24 */
25 readonly loadOctaneConfig: (
26 projectRoot: string,
27 options?: Record<string, unknown>,
28 ) => Promise<ResolvedOctaneConfigSlice | null>;
29 }
30
31 /** The structural slice of a resolved `octane.config.ts` this package reads. */
32 export interface ResolvedOctaneConfigSlice {
33 readonly router: { readonly routes: ReadonlyArray<unknown> };
34 readonly build: { readonly outDir: string };
35 readonly adapter?:
36 | {
37 readonly name?: string | undefined;
38 readonly serverTarget?: string | undefined;
39 }
40 | undefined;
41 }
42
43 /** The structural slice of the project's `vite` module this package drives. */
44 export interface OctaneViteModule {
45 readonly version?: string;
46 readonly build: (config: Record<string, unknown>) => Promise<unknown>;
47 readonly createServer: (config: Record<string, unknown>) => Promise<OctaneViteDevServer>;
48 }
49
50 /** The structural slice of a Vite dev server this package reads. */
51 export interface OctaneViteDevServer {
52 readonly listen: () => Promise<unknown>;
53 readonly close: () => Promise<void>;
54 readonly resolvedUrls?: { readonly local: ReadonlyArray<string> } | null | undefined;
55 }
56
57 /**
58 * The configuration this package assembles from {@link OctaneOptions} and
59 * hands to a deploy-target factory. The target treats it as its
60 * `DeployTarget.config`; the framework half never inspects a resolved
61 * target's config.
62 */
63 export interface OctaneTargetConfig {
64 /** Compatibility date the target carries for serve/deploy. */
65 readonly compatibilityDate?: string | undefined;
66 /** Compatibility flags the target carries for serve/deploy. */
67 readonly compatibilityFlags?: Array<string> | undefined;
68 }
69
70 /**
71 * A deploy target for Octane: the generic `DeployTarget` seams plus the one
72 * framework-specific requirements for native output and legacy adapters.
73 * Node and AWS targets wrap Octane's default Node output. Cloudflare still
74 * requires its native adapter in the project's `octane.config.ts`.
75 */
76 export interface OctaneTarget extends DeployTarget<OctaneTargetConfig> {
77 /**
78 * The `adapter.name` the resolved `octane.config.ts` must carry (the
79 * Cloudflare target requires `"cloudflare"` — Octane's
80 * `@octanejs/adapter-cloudflare`).
81 */
82 readonly adapterName: string;
83 /**
84 * The npm package providing that adapter — used in the actionable error
85 * when the project's config selects no (or a foreign) adapter.
86 */
87 readonly adapterPackage: string;
88 /** Whether this target needs an application-selected adapter rather than native Node output. */
89 readonly requiresAdapter?: boolean;
90 /**
91 * The Worker entry module the adapter emits, relative to the build's
92 * server output directory (Cloudflare: `worker.js`).
93 */
94 readonly serverEntryFileName: string;
95 }
96
97 /**
98 * How a deploy target is passed to this package: an `OctaneTarget` value, a
99 * factory `(config) => OctaneTarget`, or a module specifier resolved from the
100 * *project's* `node_modules` (default-export — or named export `target` — a
101 * value or factory).
102 */
103 export type OctaneTargetInput = DeployTargetInput<OctaneTarget, OctaneTargetConfig>;
104
105 /**
106 * The default deploy target: this package's own Cloudflare Workers target
107 * module (`src/cloudflare.ts`), loaded from the project's dependency tree.
108 */
109 export const DEFAULT_TARGET_SPECIFIER = "@alchemy.run/frontend-frameworks/octane/cloudflare";
110
111 /** The specifier the project's Octane Vite integration is loaded from. */
112 export const OCTANE_VITE_PLUGIN_SPECIFIER = "@octanejs/vite-plugin";
113
114 export interface OctaneOptions {
115 /**
116 * Project root (the directory containing `vite.config.ts` and
117 * `octane.config.ts`).
118 * @default process.cwd()
119 */
120 readonly root?: string | undefined;
121 /**
122 * The deploy target the build is produced for. Accepts a target value, a
123 * `(config) => target` factory, or a module specifier string.
124 * @default "@alchemy.run/frontend-frameworks/octane/cloudflare"
125 */
126 readonly target?: OctaneTargetInput | undefined;
127 /** Compatibility date forwarded to the target via its config. */
128 readonly compatibilityDate?: string | undefined;
129 /**
130 * Compatibility flags forwarded to the target via its config. Octane's
131 * server runtime needs synchronous SHA-256 and `AsyncLocalStorage`, so on
132 * workerd-style targets `nodejs_compat` is effectively required.
133 */
134 readonly compatibilityFlags?: Array<string> | undefined;
135 readonly dev?:
136 | {
137 /** Default dev-server port (overridden by `FrameworkDevOptions.port`). */
138 readonly port?: number | undefined;
139 }
140 | undefined;
141 }
142
143 const fail = (message: string, cause?: unknown) =>
144 new FrameworkError({ framework: "octane", message, cause });
145
146 /**
147 * Build the `Framework` service implementation for an Octane project.
148 *
149 * - `build` resolves the deploy target, then drives the PROJECT's own Vite
150 * install programmatically: Octane's `vite build` is the whole pipeline —
151 * `@octanejs/vite-plugin` builds the client bundle, launches the `ssr:
152 * true` server sub-build, and runs the config's deploy adapter, which
153 * emits the platform Worker entry (Cloudflare:
154 * `dist/server/worker.js`, self-contained ESM with only `node:`
155 * externals). The `BuildOutput` is then read from disk: `serverModules`
156 * entry-first from `<outDir>/server`, `clientDirectory` =
157 * `<outDir>/client`. Node and AWS accept adapterless native output;
158 * Cloudflare requires `adapter: cloudflare()`. Explicit incompatible
159 * adapters fail with an actionable error.
160 * - `dev` runs Octane's own Vite dev server programmatically (the plugin's
161 * dev SSR middleware serves rendering, server routes, and RPC in-process),
162 * scoped — closing the Scope closes the server. NOTE: Octane's dev
163 * middleware does not supply request-scoped platform bindings
164 * (`context.platform` is `undefined` in dev — an upstream limitation), so
165 * Cloudflare bindings are live/preview-only for now.
166 *
167 * This module is target-agnostic: everything Cloudflare-specific lives in
168 * `@alchemy.run/frontend-frameworks/octane/cloudflare`.
169 */
170 export const make: (
171 options?: OctaneOptions,
172 ) => Effect.Effect<Framework["Service"], never, FileSystem.FileSystem | Path.Path> =
173 Effect.fnUntraced(function* (options?: OctaneOptions) {
174 const fs = yield* FileSystem.FileSystem;
175 const path = yield* Path.Path;
176 const baseRoot = options?.root ?? (yield* Effect.sync(() => process.cwd()));
177
178 const targetConfig: OctaneTargetConfig = {
179 compatibilityDate: options?.compatibilityDate,
180 compatibilityFlags: options?.compatibilityFlags,
181 };
182
183 const resolveTarget = (root: string) =>
184 FrameworkCore.resolveDeployTarget<OctaneTarget, OctaneTargetConfig>(
185 root,
186 options?.target ?? DEFAULT_TARGET_SPECIFIER,
187 targetConfig,
188 ).pipe(Effect.mapError((error) => fail(error.message, error.cause)));
189
190 const loadVite = (root: string) =>
191 FrameworkCore.loadProjectModule<OctaneViteModule>(root, "vite").pipe(
192 Effect.mapError((error) => fail("Failed to load the project's Vite install", error.cause)),
193 );
194
195 const loadOctanePlugin = (root: string) =>
196 FrameworkCore.loadProjectModule<OctaneVitePluginModule>(
197 root,
198 OCTANE_VITE_PLUGIN_SPECIFIER,
199 ).pipe(
200 Effect.mapError((error) =>
201 fail(
202 `Failed to load the project's "${OCTANE_VITE_PLUGIN_SPECIFIER}" install — ` +
203 "is it added to the project's dependencies?",
204 error.cause,
205 ),
206 ),
207 );
208
209 const build: Framework["Service"]["build"] = Effect.fn(function* (buildOptions) {
210 const root = buildOptions?.root ?? baseRoot;
211 const target = yield* resolveTarget(root);
212 const targetContext = {
213 root,
214 framework: "octane",
215 env: buildOptions?.env,
216 };
217
218 // Wholesale build takeover (targets that own the entire pipeline).
219 if (target.build !== undefined) {
220 return yield* target.build(targetContext).pipe(
221 Effect.mapError((error) => fail(error.message, error.cause)),
222 Effect.provideService(FileSystem.FileSystem, fs),
223 Effect.provideService(Path.Path, path),
224 );
225 }
226
227 const octanePlugin = yield* loadOctanePlugin(root);
228 const config = yield* Effect.tryPromise({
229 try: async () => await octanePlugin.loadOctaneConfig(root),
230 catch: (error) => fail("Failed to load the project's octane.config.ts", error),
231 });
232 if (config === null || config.router.routes.length === 0) {
233 return yield* fail(
234 "The project has no octane.config.ts routes. A fullstack Octane app " +
235 "(routes + SSR) is required here; a client-only Octane SPA deploys " +
236 "through the plain Vite integration instead.",
237 );
238 }
239 if (
240 (config.adapter !== undefined || target.requiresAdapter) &&
241 config.adapter?.name !== target.adapterName
242 ) {
243 return yield* fail(
244 config.adapter?.name === undefined
245 ? `octane.config.ts selects no deploy adapter. Add the "${target.platform}" ` +
246 `adapter from ${target.adapterPackage}, e.g. ` +
247 `\`import { ${target.adapterName} } from "${target.adapterPackage}"\` ` +
248 `and \`adapter: ${target.adapterName}()\`.`
249 : `octane.config.ts selects the "${config.adapter.name}" deploy adapter, but ` +
250 `this build targets "${target.platform}" — use the "${target.adapterName}" ` +
251 `adapter from ${target.adapterPackage} instead.`,
252 );
253 }
254
255 // Octane's plugin (from the project's own vite.config.ts) drives the
256 // entire production pipeline inside this one call: client build,
257 // `ssr: true` server sub-build, and the adapter's adapt() pass.
258 const vite = yield* loadVite(root);
259 yield* Effect.tryPromise({
260 try: async () => await vite.build({ root, logLevel: "warn" }),
261 catch: (error) => fail("Failed to build", error),
262 });
263
264 const outDir = path.resolve(root, config.build.outDir);
265 const output = yield* readOctaneOutput({
266 dir: outDir,
267 serverDir: path.join(outDir, "server"),
268 clientDir: path.join(outDir, "client"),
269 serverEntryFileName: target.serverEntryFileName,
270 }).pipe(Effect.provideService(FileSystem.FileSystem, fs));
271
272 // The finishing-pass seam (none needed for Cloudflare — the adapter's
273 // worker.js is already self-contained workerd ESM — but the contract
274 // is honored for targets that do post-process).
275 return yield* FrameworkCore.applyDeployTargetFinish(target, output, {
276 ...targetContext,
277 entry: path.join(outDir, "server", target.serverEntryFileName),
278 }).pipe(
279 Effect.mapError((error) => fail(error.message, error.cause)),
280 Effect.provideService(FileSystem.FileSystem, fs),
281 Effect.provideService(Path.Path, path),
282 );
283 });
284
285 const dev: Framework["Service"]["dev"] = Effect.fn(function* (devOptions) {
286 const root = devOptions?.root ?? baseRoot;
287 const vite = yield* loadVite(root);
288 // `port: 0` (true OS-assigned) on Vite >= 8.2.1, probed ephemeral port
289 // on older Vite — see `resolveViteDevPort`.
290 const port = yield* FrameworkCore.resolveViteDevPort(
291 vite.version,
292 devOptions?.port ?? options?.dev?.port,
293 );
294 const host = devOptions?.host;
295
296 const server = yield* Effect.acquireRelease(
297 Effect.tryPromise({
298 try: async () => {
299 const server = await vite.createServer({
300 root,
301 server: {
302 port,
303 ...(host !== undefined ? { host } : undefined),
304 },
305 });
306 await server.listen();
307 return server;
308 },
309 catch: (error) => fail("Failed to start the Octane dev server", error),
310 }),
311 (server) =>
312 Effect.promise(async () => {
313 try {
314 await server.close();
315 } catch {
316 // teardown is best-effort
317 }
318 }),
319 );
320
321 const url = server.resolvedUrls?.local[0];
322 if (url === undefined) {
323 return yield* fail("Could not determine the dev server URL");
324 }
325
326 // Bounded readiness probe: any HTTP response counts (vite serves
327 // lazily; we only need the listener to answer).
328 yield* Effect.tryPromise({
329 try: async () => {
330 const response = await fetch(url, { redirect: "manual" });
331 await response.arrayBuffer().catch(() => {});
332 },
333 catch: (error) => fail("The dev server did not become reachable", error),
334 }).pipe(Effect.retry({ schedule: Schedule.spaced("250 millis"), times: 40 }));
335
336 return { url };
337 });
338
339 return Framework.of({ build, dev });
340 });
341
342 /**
343 * Build-output files under `<outDir>/server` that are inputs to the
344 * adapter's adapt() pass rather than runtime Worker modules: the SSR HTML
345 * template and Rsbuild's late client asset map are both EMBEDDED into the
346 * generated `worker.js`, so uploading them as Worker modules would be
347 * redundant (and `.html` is not a valid Worker module type).
348 */
349 const NON_MODULE_SERVER_FILES = new Set(["index.html", "octane-client-assets.json"]);
350
351 /** The resolved Octane build output directories. */
352 export interface OctaneOutputDirs {
353 /** Root output directory (`<root>/dist`). */
354 readonly dir: string;
355 /** Server bundle directory (`<root>/dist/server`). */
356 readonly serverDir: string;
357 /** Static assets directory (`<root>/dist/client`). */
358 readonly clientDir: string;
359 /**
360 * The adapter-emitted Worker entry file name within `serverDir`.
361 * @default "worker.js"
362 */
363 readonly serverEntryFileName?: string | undefined;
364 }
365
366 /**
367 * Map Octane's on-disk `dist` onto the `BuildOutput` contract:
368 * `serverModules` entry-first from the server directory (POSIX names,
369 * sha256-hashed, excluding the embedded-template inputs), `clientDirectory`
370 * = the client directory. The adapter's server output is already
371 * self-contained ESM (only `node:` externals) — no finishing pass, and no
372 * external workspace roots (the server sub-build bundles with
373 * `noExternal: true`, so workspace imports are inlined).
374 */
375 export const readOctaneOutput = (
376 dirs: OctaneOutputDirs,
377 ): Effect.Effect<FrameworkCore.BuildOutput, FrameworkError, FileSystem.FileSystem> =>
378 Effect.gen(function* () {
379 const entryFileName = dirs.serverEntryFileName ?? "worker.js";
380 const entryName = `server/${entryFileName}`;
381 const modules = yield* FrameworkCore.readServerModulesFromDisk({
382 directory: dirs.serverDir,
383 prefix: "server",
384 }).pipe(Effect.mapError((error) => fail(error.message, error.cause)));
385 const serverModules = FrameworkCore.sortServerModules(
386 modules.filter((module) => !NON_MODULE_SERVER_FILES.has(module.name.slice("server/".length))),
387 entryName,
388 );
389 if (serverModules.length === 0) {
390 return yield* fail(`The Octane build produced no server modules in ${dirs.serverDir}`);
391 }
392 if (serverModules[0]?.name !== entryName) {
393 return yield* fail(
394 `The Octane build produced no "${entryName}" entry in ${dirs.serverDir} — ` +
395 "did the deploy adapter's adapt() pass run?",
396 );
397 }
398 return {
399 distDirectory: dirs.dir,
400 clientDirectory: dirs.clientDir,
401 serverModules,
402 externalWorkspaces: new Set<string>(),
403 } satisfies FrameworkCore.BuildOutput;
404 });
405
406 /**
407 * A `Layer` providing framework-core's `Framework` service for an Octane
408 * project — the fully-typed entrypoint for `e2e.config.ts` (harness form 4)
409 * and alchemy's `Website.Octane` composite.
410 */
411 export const layer = (
412 options?: OctaneOptions,
413 ): Layer.Layer<Framework, never, FileSystem.FileSystem | Path.Path> =>
414 Layer.effect(Framework, make(options));