@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, 04:45 UTC

main
ts 114 lines 4.93 KB
Raw
1 import * as NodeFs from "node:fs";
2 import * as NodePath from "node:path";
3 import type * as vite from "vite";
4 import { parseViteEnvironments } from "../rolldown/options.ts";
5 import type { OptionsApi } from "../rolldown/plugins/index.ts";
6 import { resolvePluginApi } from "../rolldown/utils.ts";
7 import type { CloudflareVitePluginOptions } from "./plugin.ts";
8 import { handleWebSocket } from "./websockets.ts";
9 import { forwardWorkerRequest, workerRequestUrl } from "./worker-request.ts";
10
11 /**
12 * Preview mode: serve the freshly built worker through workerd.
13 *
14 * `vite preview` (and any framework that drives it programmatically — e.g.
15 * waku's SSG step, which boots a preview server mid-`buildApp` and renders
16 * every static page through it) resolves the same plugins as the build. This
17 * plugin's `configurePreviewServer` hook reads the built worker output from
18 * the entry environment's `build.outDir`, boots workerd over it via
19 * `cloudflare-runtime`, and registers a proxy middleware ahead of Vite's
20 * internal middlewares so every request — static assets included, via the
21 * runtime's assets plugin — is handled exactly as on the deployed worker.
22 *
23 * This mirrors what upstream `@cloudflare/vite-plugin` provides via its own
24 * `configurePreviewServer` (miniflare over the built output), and is what
25 * makes SSG-in-workerd work: a top-level `import { env } from
26 * "cloudflare:workers"` in a prerendered page module loads fine, because the
27 * page renders inside workerd rather than the Node process.
28 */
29 export function preview(options: CloudflareVitePluginOptions): vite.Plugin {
30 return {
31 name: "distilled-cloudflare:preview",
32 async configurePreviewServer(server) {
33 const config = server.config;
34 const optionsApi = resolvePluginApi<OptionsApi>(
35 config.plugins,
36 "distilled-cloudflare:options",
37 );
38 if (!optionsApi) {
39 throw new Error("Cannot resolve the distilled-cloudflare:options plugin");
40 }
41 const input = optionsApi.input();
42 const inputNames = Object.keys(input);
43 if (inputNames.length === 0) {
44 // SPA mode: no worker entry — leave the preview server to Vite's
45 // static file serving.
46 return;
47 }
48 if (inputNames.length > 1) {
49 throw new Error(
50 `Expected exactly one entry in the input, got ${inputNames.length} entries: ${JSON.stringify(input)}`,
51 );
52 }
53 const [entryEnvironmentName] = parseViteEnvironments(options);
54 const entryEnvironment = config.environments[entryEnvironmentName!];
55 if (!entryEnvironment) {
56 throw new Error(
57 `Cannot resolve the "${entryEnvironmentName}" environment from the preview config`,
58 );
59 }
60 const directory = NodePath.resolve(config.root, entryEnvironment.build.outDir);
61 const entryModule = findEntryModule(directory, inputNames[0]!);
62 const clientEnvironment = config.environments["client"];
63 const assetsDirectory = clientEnvironment
64 ? NodePath.resolve(config.root, clientEnvironment.build.outDir)
65 : undefined;
66
67 const { startPreviewServer } = await import("./preview-server.ts");
68 const handle = await startPreviewServer(options, {
69 directory,
70 entryModule,
71 assetsDirectory:
72 assetsDirectory !== undefined && NodeFs.existsSync(assetsDirectory)
73 ? assetsDirectory
74 : undefined,
75 });
76 const address = handle.address;
77 const removeUpgradeListener = server.httpServer
78 ? handleWebSocket(server.httpServer, address, handle.proxySharedSecret)
79 : undefined;
80 const close = server.close.bind(server);
81 server.close = async () => {
82 removeUpgradeListener?.();
83 await handle.close();
84 await close();
85 };
86 // Registered directly (not via the returned post hook), so the proxy
87 // runs ahead of Vite's internal static-file middlewares and of any
88 // middleware a framework appends afterwards (e.g. waku's Node SSG
89 // fallback) — the worker handles every request, like in production.
90 server.middlewares.use(function distilledCloudflarePreviewMiddleware(req, res) {
91 const url = workerRequestUrl(req.url, address);
92 forwardWorkerRequest(req, res, url, handle.proxySharedSecret, server.config.logger);
93 });
94 },
95 };
96 }
97
98 /**
99 * Locate the built entry chunk for the (single) worker input. Entry chunks
100 * are emitted as `[name].js` (Vite's server-build default `entryFileNames`);
101 * `.mjs` is accepted for configs that override the extension.
102 */
103 const findEntryModule = (directory: string, inputName: string): string => {
104 const candidates = [`${inputName}.js`, `${inputName}.mjs`];
105 for (const candidate of candidates) {
106 if (NodeFs.existsSync(NodePath.join(directory, candidate))) {
107 return candidate;
108 }
109 }
110 throw new Error(
111 `Cannot find the built worker entry (${candidates.join(" or ")}) in "${directory}". ` +
112 "Run the build before starting the preview server.",
113 );
114 };