@devries-cameron20 / t3code Mirror · read-only
Fork 0

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

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 06:00 UTC

main
ts 185 lines 7.05 KB
Raw
1 import { createRequire } from "node:module";
2 import { pathToFileURL } from "node:url";
3 import * as Effect from "effect/Effect";
4 import * as FileSystem from "effect/FileSystem";
5 import * as Layer from "effect/Layer";
6 import * as Path from "effect/Path";
7 import type { Plugin } from "vite";
8 import { runBuildChild } from "../core/BuildChild.ts";
9 import type { BuildOutput } from "../core/BuildOutput.ts";
10 import { DeployTargetError } from "../core/DeployTarget.ts";
11 import { isInsideDevChild, runDevChild } from "../core/DevChild.ts";
12 import { FrameworkError, type FrameworkDevOptions } from "../core/Framework.ts";
13 import { Framework } from "../core/Framework.ts";
14 import { finishNeonOutput, makeNeonTarget } from "../core/NeonServe.ts";
15 import { makeNodeTarget, type VocsNodeFrameworkOptions } from "./node.ts";
16 import { make as makeVocsLayer } from "./Vocs.ts";
17
18 // Preserve config imports and closures; only the dev-only Vite loader is removed.
19 const runtimeConfigPlugin = (): Plugin => ({
20 name: "alchemy:vocs-neon-runtime-config",
21 enforce: "post",
22 transform(code, id) {
23 const file = id.replaceAll("\\", "/").split("?")[0];
24 if (file?.endsWith("/vocs/dist/internal/mdx.js")) {
25 const logger =
26 /const logger = createLogger\(undefined, \{ allowClearScreen: false, prefix: '\[vocs\]' \}\);/;
27 if (!logger.test(code) || !code.includes("import { createLogger } from 'vite';"))
28 throw new Error("Vocs MDX logger changed; update the Neon runtime bridge.");
29 return code
30 .replace("import { createLogger } from 'vite';", "")
31 .replace(
32 logger,
33 'const logger = { warn: (message) => console.warn("[vocs]", message), error: (message) => console.error("[vocs]", message) };',
34 );
35 }
36 if (!file?.endsWith("/vocs/dist/internal/config.js")) return;
37 const pattern =
38 /export async function resolve\(options = \{\}\) \{[\s\S]*?\n\}\n(?=export let global;)/;
39 if (!pattern.test(code))
40 throw new Error("Vocs runtime config shape changed; update the Neon config bridge.");
41 return code.replace(
42 pattern,
43 "export async function resolve() {\n" +
44 ' const resolved = (await import("virtual:alchemy-vocs/user-config")).default;\n' +
45 " return define(resolved);\n}\n",
46 );
47 },
48 });
49
50 export const buildInChild = (config: { root: string }) =>
51 Effect.gen(function* () {
52 const node = makeNodeTarget();
53 const framework = yield* Framework.pipe(
54 Effect.provide(
55 makeVocsLayer({
56 root: config.root,
57 target: {
58 ...node,
59 build: undefined,
60 vitePlugins: (context) =>
61 node
62 .vitePlugins(context)
63 .pipe(Effect.map((plugins) => [...plugins, runtimeConfigPlugin()])),
64 },
65 }),
66 ),
67 );
68 return yield* framework.build({ root: config.root }).pipe(Effect.flatMap(finishNeonOutput));
69 });
70
71 /** Vocs production output served by a Neon Fetch handler. */
72 export const target = (config?: Parameters<typeof makeNodeTarget>[0]) => ({
73 ...makeNeonTarget(makeNodeTarget(config)),
74 build: (context: Parameters<NonNullable<ReturnType<typeof makeNodeTarget>["build"]>>[0]) =>
75 runBuildChild({
76 runtime: "node",
77 module: import.meta.url,
78 rootDir: context.root,
79 config: { root: context.root },
80 framework: "vocs",
81 env: context.env,
82 }).pipe(
83 Effect.mapError(
84 (cause) =>
85 new DeployTargetError({
86 platform: "neon",
87 message: cause.message,
88 cause,
89 }),
90 ),
91 ),
92 });
93 export default target;
94
95 /** Native Vocs development with Neon-compatible production output. */
96 export const make = Effect.fn(function* (options: VocsNodeFrameworkOptions = {}) {
97 const fs = yield* FileSystem.FileSystem;
98 const path = yield* Path.Path;
99 const services = Layer.mergeAll(
100 Layer.succeed(FileSystem.FileSystem)(fs),
101 Layer.succeed(Path.Path)(path),
102 );
103 return {
104 dev: Effect.fn(function* (devOptions?: FrameworkDevOptions) {
105 const root = yield* Effect.sync(() =>
106 path.resolve(devOptions?.root ?? options.root ?? process.cwd()),
107 );
108 if (isInsideDevChild()) {
109 const fail = (cause: unknown) =>
110 new FrameworkError({
111 framework: "vocs",
112 message: "Failed to start the native Vocs dev server",
113 cause,
114 });
115 const modules = yield* Effect.try({
116 try: () => {
117 const project = createRequire(path.join(root, "package.json"));
118 const vocs = project.resolve("vocs/vite");
119 const require = createRequire(vocs);
120 return {
121 vocs: pathToFileURL(vocs).href,
122 vite: pathToFileURL(require.resolve("vite")).href,
123 react: pathToFileURL(require.resolve("@vitejs/plugin-react")).href,
124 };
125 },
126 catch: fail,
127 });
128 // All plugins must share Vocs's Vite instance for runnable SSR environments.
129 const vite = yield* Effect.tryPromise({
130 try: () => import(modules.vite) as Promise<typeof import("vite")>,
131 catch: fail,
132 });
133 const react = yield* Effect.tryPromise({
134 try: () => import(modules.react) as Promise<typeof import("@vitejs/plugin-react")>,
135 catch: fail,
136 });
137 const vocs = yield* Effect.tryPromise({
138 try: () => import(modules.vocs) as Promise<typeof import("vocs/vite")>,
139 catch: fail,
140 });
141 const server = yield* Effect.acquireRelease(
142 Effect.tryPromise({
143 try: () =>
144 vite.createServer({
145 root,
146 configFile: false,
147 plugins: [react.default(), vocs.vocs()],
148 server: {
149 host: devOptions?.host,
150 port: devOptions?.port,
151 strictPort: devOptions?.port !== undefined,
152 },
153 }),
154 catch: fail,
155 }),
156 (server) => Effect.promise(() => server.close()),
157 );
158 yield* Effect.tryPromise({ try: () => server.listen(), catch: fail });
159 const url = server.resolvedUrls?.local[0] ?? server.resolvedUrls?.network[0];
160 if (!url) return yield* fail(new Error("Vocs did not report a dev URL"));
161 return { url };
162 }
163 return yield* runDevChild({
164 // Vocs's Vite dev server (like its build) exhausts memory under
165 // Bun; run the dev child under Node from PATH.
166 runtime: "node",
167 framework: "vocs",
168 module: import.meta.url,
169 callerUrl: import.meta.url,
170 rootDir: root,
171 makeOptions: { ...options, root },
172 devOptions: { ...devOptions, root },
173 });
174 }),
175 build: (buildOptions?: {
176 readonly root?: string;
177 }): Effect.Effect<BuildOutput, FrameworkError | DeployTargetError> =>
178 Effect.gen(function* () {
179 const root = yield* Effect.sync(() =>
180 path.resolve(buildOptions?.root ?? options.root ?? process.cwd()),
181 );
182 return yield* target().build({ root, framework: "vocs" });
183 }).pipe(Effect.provide(services)),
184 };
185 });