@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 439 lines 18.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 type * as vite from "vite";
6 /**
7 * `Framework` implementation driving Vocs on Cloudflare Workers.
8 *
9 * Vocs 2.x is built on waku (its `vocs()` vite plugin composes waku's own
10 * `waku/vite-plugins` — environments, adapter-alias, static-build, ... — with
11 * vocs's mdx/config/patch plugins), but it does NOT use waku's
12 * `unstable_combinedPlugins`, so `@alchemy.run/frontend-frameworks/waku`'s Framework layer
13 * cannot drive it directly. This layer mirrors that package's orchestration
14 * (see packages/frontend-frameworks/src/waku/Waku.ts) with vocs's plugin stack swapped in:
15 *
16 * - the deploy-target halves (wrangler-free adapter fork + cloudflare vite
17 * plugin pinned to waku's rsc entry) come from
18 * `@alchemy.run/frontend-frameworks/waku/cloudflare` — vocs uses waku's environments
19 * plugin, so the same rsc/ssr topology applies;
20 * - the plugin stack is the one vocs's own CLI assembles
21 * (`[react(), vocs()]`), with the target's plugins injected ahead of
22 * vocs/waku's (the position where the workerd proxy middleware registers
23 * before waku's Node request bridge) and the adapter selected via vocs's
24 * `unstable_adapter` passthrough;
25 * - the waku-parity vite config that `@alchemy.run/frontend-frameworks/waku` carries through
26 * the in-memory waku config (dedupe, workerd optimizeDeps, neutral rolldown
27 * platform) rides the inline vite config instead, since vocs owns the waku
28 * config it builds internally.
29 */
30 import * as FrameworkCore from "../core/index.ts";
31 import { WAKU_SERVER_ENTRY_MODULE } from "../waku/Waku.ts";
32 import { selectVocsTargetInput, type VocsTarget, type VocsTargetOption } from "./Target.ts";
33
34 type ReactPluginModule = typeof import("@vitejs/plugin-react");
35 type VocsViteModule = typeof import("vocs/vite");
36
37 interface VocsProjectModules {
38 readonly bundler: typeof vite;
39 readonly react: ReactPluginModule;
40 readonly vite: VocsViteModule;
41 }
42
43 export interface VocsFrameworkOptions {
44 /** Deploy target. Defaults to `@alchemy.run/frontend-frameworks/vocs/cloudflare`. */
45 readonly target?: VocsTargetOption | undefined;
46 /** @deprecated Target configuration alias retained for the E2E harness. */
47 readonly vite?: unknown;
48 /** Project root. Defaults to the operation root or current working directory. */
49 readonly root?: string;
50 /**
51 * Default dev-server port, used when `dev` is called without an explicit
52 * port (e.g. the Playwright dev fixture). Non-strict: if the port is taken,
53 * vite falls back to the next free one. A port passed to `dev` directly
54 * (`e2e dev --port N`) is strict and takes precedence.
55 */
56 readonly port?: number | undefined;
57 }
58
59 /**
60 * `NODE_ENV` as it was when this module first loaded (see
61 * packages/frontend-frameworks/src/waku/Waku.ts for the rationale: build and dev may run in the
62 * same long-lived playwright worker process).
63 */
64 const INITIAL_NODE_ENV = process.env.NODE_ENV;
65
66 const PREVIEW_SERVER_GLOBAL = "__WAKU_START_PREVIEW_SERVER__";
67
68 /** The shape waku's `unstable_startPreviewServer` expects the global to produce. */
69 interface WakuPreviewServer {
70 readonly baseUrl: string;
71 readonly middlewares: {
72 readonly use: (fn: (req: unknown, res: unknown, next: (err?: unknown) => void) => void) => void;
73 };
74 readonly close: () => Promise<void>;
75 }
76
77 /**
78 * Waku-parity inline vite config. `@alchemy.run/frontend-frameworks/waku` injects these via
79 * the in-memory waku config's `vite` field; vocs builds that config itself
80 * with `vite: {}`, so they ride the top-level inline config here (vite merges
81 * inline config with plugin-contributed config).
82 */
83 const sharedViteConfig = (): vite.InlineConfig => ({
84 resolve: {
85 dedupe: ["waku", "hono"],
86 },
87 environments: {
88 rsc: {
89 optimizeDeps: { include: ["hono/tiny"] },
90 build: { rolldownOptions: { platform: "neutral" } },
91 },
92 ssr: {
93 optimizeDeps: { include: ["waku > rsc-html-stream/server"] },
94 build: { rolldownOptions: { platform: "neutral" } },
95 },
96 },
97 });
98
99 const VIRTUAL_USER_CONFIG = "virtual:alchemy-vocs/user-config";
100 const RESOLVED_VIRTUAL_USER_CONFIG = `\0${VIRTUAL_USER_CONFIG}`;
101
102 /**
103 * Bridges vocs's runtime config resolution onto workerd.
104 *
105 * Vocs's server code calls `Config.resolve({ server: true })` at request time
106 * (middleware, api routes, the ssr entry). In production that branch assumes
107 * the Node server layout — `import.meta.dirname` + an on-disk
108 * `dist/server/vocs.config.js` — neither of which exists inside workerd
109 * (upstream vocs has node/vercel/netlify adapters only; there is no workers
110 * deploy path to mirror). This plugin:
111 *
112 * 1. asks Vocs to discover the project's `vocs.config.*` file;
113 * 2. exposes that file through a virtual module, so Vite loads and bundles
114 * the original config module (including its imports and functions);
115 * 3. transforms Vocs's Node-only runtime lookup to import the bundled module
116 * and guards the `process.cwd()` fallback for workerd.
117 *
118 * This follows Vocs's own production design, which emits the config as
119 * `dist/server/vocs.config.js`, without separately resolving or serializing
120 * the user's configuration in Alchemy.
121 */
122 const workerdConfigBridge = (configPath: string | undefined): vite.Plugin => ({
123 name: "@alchemy.run/frontend-frameworks/vocs:workerd-config-bridge",
124 resolveId(id) {
125 if (id === VIRTUAL_USER_CONFIG) return RESOLVED_VIRTUAL_USER_CONFIG;
126 return;
127 },
128 load(id) {
129 if (id === RESOLVED_VIRTUAL_USER_CONFIG) {
130 return configPath === undefined
131 ? "export default {};"
132 : `export { default } from ${JSON.stringify(configPath)};`;
133 }
134 return;
135 },
136 transform(code, id) {
137 // In the production build the modules are vocs's shipped
138 // `dist/internal/*.js`; in dev, vite serves vocs's TS sources
139 // (`src/internal/*.ts`) through the module runner, so both shapes (and
140 // the raw-TS formatting, which user plugins see before vite's esbuild
141 // transform) must match.
142 // Strip the query (dev serves ids like `.../config.js?v=<hash>`).
143 const normalized = (id.split("?")[0] ?? id).replaceAll("\\", "/");
144 const isVocsInternal = (name: string) =>
145 normalized.endsWith(`/vocs/dist/internal/${name}.js`) ||
146 normalized.endsWith(`/vocs/src/internal/${name}.ts`);
147 const mustReplace = (source: string, pattern: RegExp, replacement: string): string => {
148 if (!pattern.test(source)) {
149 throw new Error(
150 `@alchemy.run/frontend-frameworks/vocs: ${normalized} no longer matches the workerd config bridge ` +
151 `pattern ${pattern} — update the transform in packages/frontend-frameworks/src/vocs/Vocs.ts ` +
152 "for the installed vocs version",
153 );
154 }
155 return source.replace(pattern, replacement);
156 };
157 // `deserializeFunctions` revives `_vocs-fn_`-serialized config functions
158 // with `new Function`, which workerd forbids. Vocs' server runtime does
159 // not need the browser-side search callbacks that take this path, so
160 // degrade them to `undefined` when dynamic evaluation is unavailable.
161 // Node paths (SSG and dev tooling) still revive them normally.
162 if (isVocsInternal("config-serializer")) {
163 return mustReplace(
164 code,
165 // Avoid the escaped copy inside `deserializeFunctionsStringified`.
166 /return new Function\(`return \$\{value\.slice\(9\)\}`\)\(\);?/,
167 "try { return new Function(`return ${value.slice(9)}`)(); } catch { return undefined; }",
168 );
169 }
170 if (!isVocsInternal("config")) return;
171 let result = mustReplace(
172 code,
173 /const \{ server, rootDir = process\.cwd\(\) \} = options;?/,
174 "const { server } = options;\n" +
175 " const rootDir = options.rootDir ?? (() => { try { return process.cwd(); } catch { return '/'; } })();",
176 );
177 result = mustReplace(
178 result,
179 /if \(server && process\.env\['NODE_ENV'\] === 'production'\) \{\s*const configPath = path\.resolve\(import\.meta\.dirname, '\.\.\/vocs\.config\.js'\);?\s*const resolved = \(await import\(\/\* @vite-ignore \*\/ configPath\)\)\.default( as define\.Options)?;?\s*return define\(\{ \.\.\.resolved, rootDir \}\);?\s*\}/,
180 "if (server) {\n" +
181 ` const resolved = (await import(${JSON.stringify(VIRTUAL_USER_CONFIG)})).default;\n` +
182 " return define(resolved);\n" +
183 " }",
184 );
185 return result;
186 },
187 });
188
189 /**
190 * Replicates waku's `cmd-build.ts` `startPreviewServerImpl`: the SSG step of
191 * `builder.buildApp()` (the adapter's `build`) calls
192 * `unstable_startPreviewServer`, which throws unless this global is set. The
193 * preview config omits the cloudflare plugins, so SSG streams through the
194 * adapter's Node fallback middleware (upstream parity: identical to a vocs
195 * build without a platform vite plugin).
196 */
197 const setPreviewServerGlobal = (
198 root: string,
199 adapterPath: string,
200 configPath: string | undefined,
201 project: VocsProjectModules,
202 port: number,
203 ): void => {
204 (globalThis as Record<string, unknown>)[PREVIEW_SERVER_GLOBAL] =
205 async (): Promise<WakuPreviewServer> => {
206 const server = await project.bundler.preview({
207 configFile: false,
208 root,
209 ...sharedViteConfig(),
210 plugins: [
211 project.react.default(),
212 workerdConfigBridge(configPath),
213 project.vite.vocs({ unstable_adapter: adapterPath }),
214 ],
215 // localhost can resolve to another build's listener on the other IP family.
216 preview: { host: "127.0.0.1", port },
217 });
218 const baseUrl = server.resolvedUrls?.local[0];
219 if (!baseUrl) {
220 throw new Error("Could not determine the URL of the vocs SSG preview server");
221 }
222 return {
223 baseUrl,
224 middlewares: {
225 use: (fn) => server.middlewares.use(fn as never),
226 },
227 close: () => server.close(),
228 };
229 };
230 };
231
232 const clearPreviewServerGlobal = (): void => {
233 delete (globalThis as Record<string, unknown>)[PREVIEW_SERVER_GLOBAL];
234 };
235
236 /**
237 * The vocs implementation of framework-core's `Framework` service.
238 *
239 * - `build` replicates vocs's `vocs build` CLI command (`vite.createBuilder`
240 * with `[react(), vocs()]` + `buildApp`) with the cloudflare target's
241 * plugins/adapter wired in, and collects the `BuildOutput` with a
242 * post-`buildApp` disk re-read (waku writes `__waku_build_metadata.js` and
243 * prunes static-only chunks after the bundler finishes).
244 * - `dev` replicates `vocs dev` (`vite.createServer`) with the same plugin
245 * wiring, so the rsc environment runs in workerd.
246 */
247 export const make = (
248 options: VocsFrameworkOptions = {},
249 ): Layer.Layer<FrameworkCore.Framework, never, FileSystem.FileSystem | Path.Path> =>
250 Layer.effect(
251 FrameworkCore.Framework,
252 Effect.gen(function* () {
253 const fs = yield* FileSystem.FileSystem;
254 const path = yield* Path.Path;
255
256 const fail = (message: string) => (cause: unknown) =>
257 new FrameworkCore.FrameworkError({ framework: "vocs", message, cause });
258
259 const resolveRoot = (override: string | undefined) =>
260 Effect.sync(() => override ?? options.root ?? process.cwd());
261
262 const resolveTarget = (root: string) => {
263 const { input, config } = selectVocsTargetInput(options);
264 return FrameworkCore.resolveDeployTarget<VocsTarget, unknown>(root, input, config).pipe(
265 Effect.mapError(fail("Failed to resolve the deploy target")),
266 );
267 };
268
269 const findConfig = (root: string) =>
270 Effect.gen(function* () {
271 for (const name of [
272 "vocs.config.ts",
273 "vocs.config.js",
274 "vocs.config.mjs",
275 "vocs.config.mts",
276 ]) {
277 const candidate = path.join(root, name);
278 if (yield* fs.exists(candidate)) return candidate;
279 }
280 return undefined;
281 }).pipe(Effect.mapError(fail("Failed to locate the Vocs config")));
282
283 const loadProject = (root: string) =>
284 Effect.all(
285 {
286 bundler: FrameworkCore.loadProjectModule<typeof vite>(root, "vite"),
287 react: FrameworkCore.loadProjectModule<ReactPluginModule>(root, "@vitejs/plugin-react"),
288 vite: FrameworkCore.loadProjectModule<VocsViteModule>(root, "vocs/vite"),
289 },
290 { concurrency: "unbounded" },
291 ).pipe(Effect.mapError(fail("Failed to load Vocs from the project dependencies")));
292
293 /** Resolve the target's adapter module + vite plugins for one pass. */
294 const prepareTarget = Effect.fn(function* (
295 target: VocsTarget,
296 root: string,
297 phase: "build" | "dev",
298 ) {
299 const wakuDirectory = yield* FrameworkCore.resolveProjectPackageDirectory(
300 root,
301 "waku",
302 ).pipe(Effect.mapError(fail("Failed to resolve the project's waku package directory")));
303 const context = { root, wakuDirectory, phase } as const;
304 const [adapterPath, plugins] = yield* Effect.all(
305 [target.adapter(context), target.vitePlugins(context)],
306 { concurrency: "unbounded" },
307 ).pipe(Effect.mapError(fail(`The cloudflare target failed preparing the vocs ${phase}`)));
308 return { adapterPath, plugins, wakuDirectory };
309 });
310
311 return FrameworkCore.Framework.of({
312 build: Effect.fn(function* (buildOptions) {
313 const root = yield* resolveRoot(buildOptions?.root);
314 const target = yield* resolveTarget(root);
315 if (target.build !== undefined) {
316 return yield* target
317 .build({ root, framework: "vocs", env: buildOptions?.env })
318 .pipe(
319 Effect.provideService(FileSystem.FileSystem, fs),
320 Effect.provideService(Path.Path, path),
321 Effect.mapError(fail("The deploy target's build failed")),
322 );
323 }
324 const { adapterPath, plugins } = yield* prepareTarget(target, root, "build");
325 const project = yield* loadProject(root);
326 const configPath = yield* findConfig(root);
327 // vocs's CLI (like waku's) runs with NODE_ENV set before loading
328 // anything; waku's environmentsPlugin bakes it into `define`.
329 yield* Effect.sync(() => {
330 process.env.NODE_ENV = INITIAL_NODE_ENV ?? "production";
331 });
332 const collector = yield* FrameworkCore.makeBuildOutputCollector({
333 entryEnvironment: "rsc",
334 selectEntry: (chunk) => chunk.name === WAKU_SERVER_ENTRY_MODULE,
335 }).pipe(Effect.provideService(FileSystem.FileSystem, fs));
336 const previewPort = yield* FrameworkCore.resolveViteDevPort(project.bundler.version);
337 yield* Effect.tryPromise({
338 try: async () => {
339 const builder = await project.bundler.createBuilder(
340 {
341 configFile: false,
342 root,
343 ...sharedViteConfig(),
344 plugins: [
345 project.react.default(),
346 ...plugins,
347 workerdConfigBridge(configPath),
348 project.vite.vocs({ unstable_adapter: adapterPath }),
349 collector.plugin,
350 ],
351 },
352 null,
353 );
354 setPreviewServerGlobal(root, adapterPath, configPath, project, previewPort);
355 try {
356 await builder.buildApp();
357 } finally {
358 clearPreviewServerGlobal();
359 }
360 },
361 catch: fail("Failed to build"),
362 });
363 // Disk re-read: waku writes `__waku_build_metadata.js` and prunes
364 // static-only server chunks during `buildApp` hooks, after the
365 // in-memory `writeBundle` capture.
366 const output = yield* collector
367 .collect({ fromDisk: true })
368 .pipe(Effect.mapError((error) => fail(error.message)(error.cause)));
369 return yield* FrameworkCore.applyDeployTargetFinish(target, output, {
370 root,
371 framework: "vocs",
372 }).pipe(
373 Effect.provideService(FileSystem.FileSystem, fs),
374 Effect.provideService(Path.Path, path),
375 Effect.mapError(fail("The deploy target's finishing pass failed")),
376 );
377 }),
378 dev: Effect.fn(function* (devOptions) {
379 const root = yield* resolveRoot(devOptions?.root);
380 const target = yield* resolveTarget(root);
381 const { adapterPath, plugins } = yield* prepareTarget(target, root, "dev");
382 const project = yield* loadProject(root);
383 const configPath = yield* findConfig(root);
384 yield* Effect.sync(() => {
385 process.env.NODE_ENV = INITIAL_NODE_ENV ?? "development";
386 });
387 const port = devOptions?.port ?? options.port;
388 const server = yield* Effect.acquireRelease(
389 Effect.tryPromise({
390 try: async () => {
391 const server = await project.bundler.createServer({
392 configFile: false,
393 root,
394 ...sharedViteConfig(),
395 plugins: [
396 project.react.default(),
397 ...plugins,
398 workerdConfigBridge(configPath),
399 project.vite.vocs({ unstable_adapter: adapterPath }),
400 ],
401 ...(port !== undefined
402 ? {
403 server: {
404 port,
405 strictPort: devOptions?.port !== undefined,
406 },
407 }
408 : undefined),
409 });
410 return await server.listen();
411 },
412 catch: fail("Failed to start the vocs dev server"),
413 }),
414 (server) =>
415 Effect.promise(async () => {
416 try {
417 (
418 server.httpServer as { closeAllConnections?: () => void } | null | undefined
419 )?.closeAllConnections?.();
420 await server.close();
421 } catch {
422 // teardown is best-effort
423 }
424 }).pipe(
425 Effect.timeout("3 seconds"),
426 Effect.orElseSucceed(() => undefined),
427 ),
428 );
429 const url = server.resolvedUrls?.local[0];
430 if (url === undefined) {
431 return yield* fail("Could not determine the URL of the vocs dev server")(undefined);
432 }
433 return { url };
434 }),
435 });
436 }),
437 );
438
439 export default make;