@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 219 lines 8.91 KB
Raw
1 import * as NodeFs from "node:fs/promises";
2 import * as NodePath from "node:path";
3 import * as Credentials from "@distilled.cloud/cloudflare/Credentials";
4 import * as Effect from "effect/Effect";
5 import * as Exit from "effect/Exit";
6 import * as FetchHttpClient from "effect/http/FetchHttpClient";
7 import * as Layer from "effect/Layer";
8 import * as Scope from "effect/Scope";
9 import type { BindingHooks, Module } from "../core/index.ts";
10 import { DEFAULT_COMPATIBILITY_DATE } from "../core/internal/constants.ts";
11 import * as Runtime from "../core/Runtime.ts";
12 import * as RuntimeServices from "../core/RuntimeServices.ts";
13 import { PlatformServices } from "../Platform.ts";
14 import type { CloudflareVitePluginOptions } from "./plugin.ts";
15
16 /**
17 * The freshly built worker a preview server hosts: which directory holds the
18 * server modules, which of them is the entry, and where the client assets
19 * live. Derived by the preview plugin from the resolved Vite config.
20 */
21 export interface PreviewWorkerBuild {
22 /**
23 * Absolute directory containing the built server modules (the entry
24 * environment's `build.outDir`). Every file under it (recursively) is
25 * loaded into workerd as a module, so relative imports between chunks —
26 * including nested child-environment output like waku's `server/ssr` —
27 * resolve exactly as they would on the deployed worker.
28 */
29 readonly directory: string;
30 /** The entry module's name, relative to `directory` (POSIX separators). */
31 readonly entryModule: string;
32 /** Absolute directory of the built client assets, if any. */
33 readonly assetsDirectory?: string | undefined;
34 }
35
36 export interface PreviewServerHandle {
37 readonly address: URL;
38 readonly proxySharedSecret: string;
39 readonly close: () => Promise<void>;
40 }
41
42 /**
43 * Boot workerd (via `cloudflare-runtime`'s `Runtime.start`) over the built
44 * worker output on disk. Unlike the dev server there is no module runner and
45 * no module fallback: the build is self-contained, so every module is read
46 * from the output directory upfront (entry first — workerd treats the first
47 * module as the main module) and handed to workerd directly. Assets are
48 * served by the runtime's disk-backed assets plugin from the client build
49 * directory.
50 *
51 * When the plugin options carry no `context`, a runtime context is built
52 * into the preview's own scope and torn down by `close()` — unlike the dev
53 * server's process-lifetime cached context. This matters for build-time SSG
54 * (waku boots a preview server mid-`buildApp`): a lingering context's open
55 * handles would keep the build process alive after the build completes.
56 */
57 export const startPreviewServer = async <B extends BindingHooks = BindingHooks>(
58 options: CloudflareVitePluginOptions<B>,
59 build: PreviewWorkerBuild,
60 ): Promise<PreviewServerHandle> => {
61 const scope = Scope.makeUnsafe();
62 const proxySharedSecret = crypto.randomUUID();
63 // Only sweep handles for a context we build (and tear down) ourselves; a
64 // caller-provided context is process-lifetime by design (dev semantics).
65 const sweep = options.context === undefined ? makeHandleSweep() : undefined;
66 try {
67 const context =
68 options.context ??
69 (await makePreviewContext().pipe(Layer.buildWithScope(scope), Effect.runPromise));
70 const address = await serve(options, build, proxySharedSecret).pipe(
71 Effect.provide(context),
72 Scope.provide(scope),
73 Effect.runPromise,
74 );
75 return {
76 address,
77 proxySharedSecret,
78 close: async () => {
79 await closeScope(scope);
80 sweep?.();
81 },
82 };
83 } catch (error) {
84 await closeScope(scope);
85 sweep?.();
86 throw error;
87 }
88 };
89
90 /**
91 * Workaround for a `cloudflare-runtime` teardown gap: building the runtime
92 * context spawns a detached, uninterruptible fiber (`DockerLive`) that binds
93 * a Docker proxy server (`server.listen(0)`) and probes the local Docker
94 * daemon with no finalizer — so a build process that booted a preview server
95 * for SSG can never exit on its own, even after the runtime scope closes.
96 *
97 * Until the runtime tears that fiber down (or starts it lazily), snapshot
98 * the process's libuv handles before the context is built and, on close,
99 * `unref()` whatever appeared since and survived scope teardown. `unref` is
100 * strictly about process exit: leaked handles keep working for as long as
101 * the process lives, they just stop pinning the event loop. Handles we own
102 * are already closed by the scope; the caller's preview http server is
103 * closed by the caller immediately after, so unref-ing it is harmless.
104 */
105 const makeHandleSweep = (): (() => void) => {
106 const getHandles = (): Array<{ unref?: () => void }> => {
107 const process_ = process as unknown as {
108 _getActiveHandles?: () => Array<{ unref?: () => void }>;
109 };
110 try {
111 return process_._getActiveHandles?.() ?? [];
112 } catch {
113 return [];
114 }
115 };
116 const before = new Set(getHandles());
117 return () => {
118 for (const handle of getHandles()) {
119 if (before.has(handle)) continue;
120 try {
121 handle.unref?.();
122 } catch {
123 // best-effort: exiting cleanly matters more than the odd handle
124 }
125 }
126 };
127 };
128
129 const makePreviewContext = () =>
130 RuntimeServices.layerRuntime({ api: { accountId: process.env.CLOUDFLARE_ACCOUNT_ID! } }).pipe(
131 Layer.provideMerge(PlatformServices),
132 Layer.provide(Layer.merge(Credentials.fromEnv(), FetchHttpClient.layer)),
133 );
134
135 const closeScope = async (scope: Scope.Closeable) => {
136 await Effect.runPromiseExit(Scope.closeUnsafe(scope, Exit.void) ?? Effect.void);
137 };
138
139 // Deliberately non-generic: `CloudflareVitePluginOptions<BindingHooks>` is a
140 // supertype of every instantiation, and `BindingRequirements<BindingHooks>`
141 // collapses to `never`, so the effect's requirements are fully discharged by
142 // the provided runtime context + scope. Keeping the caller's `B` generic here
143 // would leave a deferred `BindingRequirements<B>` in the requirements that
144 // `Effect.runPromise` cannot prove away.
145 const serve = Effect.fn(function* (
146 options: CloudflareVitePluginOptions,
147 build: PreviewWorkerBuild,
148 proxySharedSecret: string,
149 ) {
150 const runtime = yield* Runtime.Runtime;
151 const modules = yield* Effect.promise(() => readWorkerModules(build));
152 const assetsDirectory = options.worker?.assets?.directory ?? build.assetsDirectory;
153 return yield* runtime.start({
154 // Everything the caller configured on the Worker reaches workerd; the
155 // fields below are the ones the preview server owns or extends.
156 ...options.worker,
157 name: options.worker?.name ?? `vite-preview-${crypto.randomUUID()}`,
158 modules,
159 proxySharedSecret,
160 compatibilityDate: options.compatibilityDate ?? DEFAULT_COMPATIBILITY_DATE,
161 compatibilityFlags: options.compatibilityFlags ?? [],
162 bindings: options.worker?.bindings ?? [],
163 assets:
164 options.worker?.assets !== undefined || assetsDirectory !== undefined
165 ? { ...options.worker?.assets, directory: assetsDirectory }
166 : undefined,
167 });
168 });
169
170 /**
171 * Read the built server output into workerd modules, entry first. Source maps
172 * are skipped; everything else is typed by extension so wasm/text/data
173 * modules emitted next to the chunks keep working.
174 */
175 export const readWorkerModules = async (build: PreviewWorkerBuild): Promise<Array<Module>> => {
176 const entries = await NodeFs.readdir(build.directory, { recursive: true, withFileTypes: true });
177 const modules = await Promise.all(
178 entries
179 .filter((entry) => entry.isFile())
180 .map((entry) => {
181 const file = NodePath.join(entry.parentPath, entry.name);
182 const name = NodePath.relative(build.directory, file).replaceAll("\\", "/");
183 return readWorkerModule(file, name);
184 }),
185 );
186 const found = modules.filter((module): module is Module => module !== undefined);
187 const entryIndex = found.findIndex((module) => module.name === build.entryModule);
188 if (entryIndex === -1) {
189 throw new Error(
190 `Cannot find the worker entry module "${build.entryModule}" in "${build.directory}". ` +
191 "Run the build before starting the preview server.",
192 );
193 }
194 const [entry] = found.splice(entryIndex, 1);
195 return [entry!, ...found];
196 };
197
198 const readWorkerModule = async (file: string, name: string): Promise<Module | undefined> => {
199 switch (NodePath.extname(file)) {
200 case ".map":
201 return undefined;
202 case ".js":
203 case ".mjs":
204 return { name, type: "ESModule", content: await NodeFs.readFile(file, "utf8") };
205 case ".cjs":
206 return { name, type: "CommonJsModule", content: await NodeFs.readFile(file, "utf8") };
207 case ".json":
208 return { name, type: "Json", content: await NodeFs.readFile(file, "utf8") };
209 case ".txt":
210 case ".html":
211 case ".css":
212 case ".sql":
213 return { name, type: "Text", content: await NodeFs.readFile(file, "utf8") };
214 case ".wasm":
215 return { name, type: "Wasm", content: new Uint8Array(await NodeFs.readFile(file)) };
216 default:
217 return { name, type: "Data", content: new Uint8Array(await NodeFs.readFile(file)) };
218 }
219 };