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

main
ts 278 lines 10.3 KB
Raw
1 import { DurableObject } from "cloudflare:workers";
2 import { ModuleRunner, ssrDynamicImportKey, ssrModuleExportsKey } from "vite/module-runner";
3 import {
4 ENVIRONMENT_NAME_HEADER,
5 EXPORT_TYPES_EVENT,
6 INIT_PATH,
7 REQUEST_EXPORT_TYPES_EVENT,
8 } from "./constants.shared.ts";
9 import { getEntryEnvironment, stripInternalEnv, type Env } from "./env.worker.ts";
10
11 declare global {
12 // This global variable is accessed by `@vitejs/plugin-rsc`
13 var __VITE_ENVIRONMENT_RUNNER_IMPORT__: (environmentName: string, id: string) => Promise<unknown>;
14 }
15
16 /**
17 * Module imports have to run inside the module runner Durable Object's
18 * `IoContext`, but they are requested from other contexts (a Worker request,
19 * a dynamic `import()`). The requesting side registers the callback here,
20 * asks the object to run it over RPC by id, and reads the result by id once
21 * the RPC returns. Both sides share this module because they share one V8
22 * isolate.
23 *
24 * Every entry is removed once the caller has read its result, whether the
25 * callback succeeded or failed. A result is a module namespace, and a
26 * namespace keeps every module it (transitively) imported alive. Retaining
27 * the results would pin each previous module graph after an HMR update or a
28 * full runner reload until the isolate ran out of heap.
29 */
30 export class CallbackRegistry {
31 private nextId = 0;
32 private readonly pending = new Map<number, () => Promise<unknown>>();
33 private readonly results = new Map<number, unknown>();
34
35 /**
36 * Registers `callback` and asks `execute` to run it under its id. Resolves
37 * with the callback's result once `execute` returns.
38 */
39 async run<T>(execute: (id: number) => Promise<void>, callback: () => Promise<T>): Promise<T> {
40 const id = this.nextId++;
41 this.pending.set(id, callback);
42 try {
43 await execute(id);
44 return this.results.get(id) as T;
45 } finally {
46 this.pending.delete(id);
47 this.results.delete(id);
48 }
49 }
50
51 /** Runs the callback registered under `id` and stores its result. */
52 async execute(id: number): Promise<void> {
53 const callback = this.pending.get(id);
54 if (!callback) {
55 throw new Error(`No pending callback with id ${id}`);
56 }
57 this.results.set(id, await callback());
58 }
59
60 /** Entries still registered. Zero whenever no `run` is in flight. */
61 get size(): number {
62 return this.pending.size + this.results.size;
63 }
64 }
65
66 const callbacks = new CallbackRegistry();
67
68 /** Runs `callback` inside the module runner Durable Object's `IoContext`. */
69 const runInModuleRunner = <T>(env: Env, callback: () => Promise<T>): Promise<T> =>
70 callbacks.run(
71 (id) => env.__DISTILLED_MODULE_RUNNER__.get("singleton").executeCallback(id),
72 callback,
73 );
74
75 /**
76 * Retrieves a specific export from a Worker entry module using the module runner.
77 */
78 export async function getWorkerEntryExport<T>(env: Env, exportName: string): Promise<T> {
79 const module = await globalThis.__VITE_ENVIRONMENT_RUNNER_IMPORT__(
80 getEntryEnvironment().environmentName,
81 getEntryEnvironment().entryId,
82 );
83
84 const exportValue =
85 typeof module === "object" &&
86 module !== null &&
87 exportName in module &&
88 (module as Record<string, unknown>)[exportName];
89
90 if (!exportValue) {
91 throw new Error(
92 `"${getEntryEnvironment().entryName}" does not define a "${exportName}" export.`,
93 );
94 }
95
96 return exportValue as T;
97 }
98
99 export class ModuleRunnerDO extends DurableObject<Env> {
100 private webSockets = new Map<string, WebSocket>();
101 private moduleRunners = new Map<string, ModuleRunner>();
102
103 async fetch(request: Request) {
104 const { pathname } = new URL(request.url);
105 if (pathname !== INIT_PATH) {
106 throw new Error(`Invalid path: ${pathname}`);
107 }
108 globalThis.__VITE_ENVIRONMENT_RUNNER_IMPORT__ = async (environmentName: string, id: string) => {
109 const moduleRunner = this.moduleRunners.get(environmentName);
110 if (!moduleRunner) {
111 throw new NotInitializedError(environmentName);
112 }
113 return runInModuleRunner(this.env, () => moduleRunner.import(id));
114 };
115 const environmentName = request.headers.get(ENVIRONMENT_NAME_HEADER);
116 if (!environmentName) {
117 throw new Error(`Missing ${ENVIRONMENT_NAME_HEADER} header`);
118 }
119 const { 0: client, 1: server } = new WebSocketPair();
120 server.accept();
121
122 const moduleRunner = this.makeModuleRunner(server, environmentName);
123 this.moduleRunners.set(environmentName, moduleRunner);
124 // `send()` writes to this socket, which is how `import.meta.hot.send()` in
125 // user code reaches the dev server.
126 this.webSockets.set(environmentName, server);
127 server.addEventListener("message", ({ data }) => {
128 if (isRequestExportTypes(data)) {
129 void this.reportExportTypes(environmentName);
130 }
131 });
132 return new Response(null, { status: 101, webSocket: client });
133 }
134
135 send(environmentName: string, data: string): void {
136 const webSocket = this.webSockets.get(environmentName);
137 if (!webSocket) {
138 throw new NotInitializedError(environmentName);
139 }
140 webSocket.send(data);
141 }
142
143 /**
144 * Evaluates the Worker entry and reports how each of its exports should be
145 * wrapped. The dev server needs this before it can serve a request, so the
146 * import runs here rather than being driven from user code.
147 */
148 private async reportExportTypes(environmentName: string): Promise<void> {
149 const { entryId, exportTypesId } = getEntryEnvironment();
150 let data: unknown;
151 try {
152 // Both imports run inside this object's IoContext, so they can go
153 // straight to the module runner instead of through `runInModuleRunner`.
154 const { getExportTypes } = (await this.import(environmentName, exportTypesId)) as {
155 getExportTypes: (module: unknown) => Record<string, string>;
156 };
157 data = getExportTypes(await this.import(environmentName, entryId));
158 } catch (error) {
159 // A reply still goes out so the dev server does not wait out its timeout.
160 // The entry failing to evaluate is reported to the user through the
161 // request that triggered it; the dev server keeps its current export
162 // types.
163 console.error("Failed to determine the Worker entry's export types:", error);
164 data = null;
165 }
166 this.send(environmentName, JSON.stringify({ type: "custom", event: EXPORT_TYPES_EVENT, data }));
167 }
168
169 private async import(environmentName: string, id: string): Promise<unknown> {
170 const moduleRunner = this.moduleRunners.get(environmentName);
171 if (!moduleRunner) {
172 throw new NotInitializedError(environmentName);
173 }
174 return await moduleRunner.import(id);
175 }
176
177 async executeCallback(id: number): Promise<void> {
178 await callbacks.execute(id);
179 }
180
181 makeModuleRunner(webSocket: WebSocket, environmentName: string) {
182 const env = this.env;
183 return new ModuleRunner(
184 {
185 sourcemapInterceptor: "prepareStackTrace",
186 transport: {
187 connect({ onMessage }) {
188 webSocket.addEventListener("message", async ({ data }) => {
189 onMessage(JSON.parse(data.toString()));
190 });
191
192 onMessage({ type: "custom", event: "vite:ws:connect", data: { webSocket } });
193 },
194 disconnect() {
195 webSocket.close();
196 },
197 async send(data) {
198 // We send messages via a binding to the Durable Object.
199 // This is because `import.meta.send` may be called within a Worker's request context.
200 // Directly using a WebSocket created in another context would be forbidden.
201 const stub = env.__DISTILLED_MODULE_RUNNER__.get("singleton");
202 stub.send(environmentName, JSON.stringify(data));
203 },
204 invoke: async (data) => {
205 const response = await env.__DISTILLED_INVOKE_MODULE__.fetch(
206 new Request("http://localhost", {
207 method: "POST",
208 headers: {
209 "content-type": "application/json",
210 [ENVIRONMENT_NAME_HEADER]: environmentName,
211 },
212 body: JSON.stringify(data),
213 }),
214 );
215 const result = await response.json<{ result: unknown } | { error: unknown }>();
216
217 return result;
218 },
219 },
220 hmr: true,
221 },
222 {
223 runInlinedModule: async (context, transformed, module) => {
224 // Wrap dynamic imports to route deferred dynamic imports
225 // through the DO's IoContext.
226 const originalDynamicImport = context[ssrDynamicImportKey];
227 context[ssrDynamicImportKey] = (dep) =>
228 runInModuleRunner(env, () => originalDynamicImport(dep));
229
230 // The trailing newline ensures a `//` comment on the last line of
231 // `transformed` (e.g. a sourceMappingURL comment preserved by
232 // vite-plus) cannot swallow the closing brace.
233 const code = `"use strict";async (${Object.keys(context).join(",")})=>{${transformed}\n}`;
234 try {
235 const fn = env.__DISTILLED_UNSAFE_EVAL__.eval(code, module.id);
236 await fn(...Object.values(context));
237 Object.seal(context[ssrModuleExportsKey]);
238 } catch (error) {
239 console.error(`[vite-plugin] Failed to evaluate inlined module "${module.id}":`, error);
240 throw error;
241 }
242 },
243 runExternalModule: async (filepath) => {
244 if (filepath === "cloudflare:workers") {
245 const { env, ...mod } = await import("cloudflare:workers");
246 return Object.seal({ ...mod, env: stripInternalEnv(env as Env) });
247 }
248 return await import(filepath);
249 },
250 },
251 );
252 }
253 }
254
255 function isRequestExportTypes(data: string | ArrayBuffer): boolean {
256 if (typeof data !== "string" || !data.includes(REQUEST_EXPORT_TYPES_EVENT)) {
257 return false;
258 }
259 try {
260 const payload: unknown = JSON.parse(data);
261 return (
262 typeof payload === "object" &&
263 payload !== null &&
264 (payload as { event?: unknown }).event === REQUEST_EXPORT_TYPES_EVENT
265 );
266 } catch {
267 return false;
268 }
269 }
270
271 // oxlint-disable-next-line effecttsgo/extends-native-error -- plain workerd script (no Effect); thrown to the Vite module runner
272 class NotInitializedError extends Error {
273 constructor(environmentName: string) {
274 super(
275 `Module runner not initialized for environment: "${environmentName}". If this is a child environment, make sure to set \`childEnvironments: ["${environmentName}"]\` in the plugin config.`,
276 );
277 }
278 }