@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 186 lines 6.02 KB
Raw
1 import assert from "node:assert";
2 import { URL as NodeURL } from "node:url";
3 import * as vite from "vite";
4 import type { FetchFunctionOptions } from "vite/module-runner";
5 import type { ExportTypes } from "../rolldown/export-types.ts";
6 import { isExportTypes } from "../rolldown/export-types.ts";
7 import { MODULE_REFERENCE_REGEX } from "../rolldown/plugins/index.ts";
8 import {
9 ENVIRONMENT_NAME_HEADER,
10 EXPORT_TYPES_EVENT,
11 INIT_PATH,
12 REQUEST_EXPORT_TYPES_EVENT,
13 } from "./module-runner/constants.shared.ts";
14
15 /** How long to wait for the Worker to report its export types before giving up. */
16 const EXPORT_TYPES_TIMEOUT_MS = 10_000;
17
18 export class DistilledDevEnvironment extends vite.DevEnvironment {
19 transport: HotChannel;
20
21 constructor(name: string, config: vite.ResolvedConfig) {
22 const transport = new HotChannel();
23 super(name, config, {
24 hot: true,
25 transport,
26 });
27 this.transport = transport;
28 }
29
30 async connect(address: string | globalThis.URL) {
31 const url = new NodeURL(address.toString());
32 url.protocol = "ws";
33 url.pathname = INIT_PATH;
34 // The Worker ambient declaration hides Bun's headers overload when both
35 // runtime type libraries are loaded by the consolidated package config.
36 const ws = new (WebSocket as unknown as {
37 new (url: string, options: { headers: Record<string, string> }): WebSocket;
38 })(url.toString(), {
39 headers: { [ENVIRONMENT_NAME_HEADER]: this.name },
40 });
41 await new Promise<void>((resolve, reject) => {
42 ws.addEventListener("open", () => {
43 resolve();
44 });
45 ws.addEventListener("error", (event) => {
46 // Depending on which global WebSocket type wins (bun-types vs
47 // @types/node's undici), the event may or may not carry `error`.
48 reject("error" in event ? event.error : new Error("WebSocket connection error"));
49 });
50 });
51 this.transport.ws = ws;
52 }
53 override async close(): Promise<void> {
54 await super.close();
55 // `transport.close()` is idempotent; make sure the module-runner socket is
56 // released even if Vite didn't close the hot channel itself.
57 this.transport.close();
58 }
59
60 /**
61 * Asks the Worker to evaluate the entry module and classify its exports.
62 *
63 * Resolves to `undefined` if the Worker could not evaluate the entry — the
64 * error is surfaced to the user by whichever request hits the entry next, and
65 * the dev server keeps whatever export types it already has.
66 */
67 async requestExportTypes(
68 timeoutMs: number = EXPORT_TYPES_TIMEOUT_MS,
69 ): Promise<ExportTypes | undefined> {
70 return await new Promise<ExportTypes | undefined>((resolve) => {
71 let timer: ReturnType<typeof setTimeout>;
72 const listener = (data: unknown) => {
73 clearTimeout(timer);
74 this.transport.off(EXPORT_TYPES_EVENT, listener);
75 resolve(isExportTypes(data) ? data : undefined);
76 };
77 timer = setTimeout(() => {
78 this.transport.off(EXPORT_TYPES_EVENT, listener);
79 resolve(undefined);
80 }, timeoutMs);
81 this.transport.on(EXPORT_TYPES_EVENT, listener);
82 this.transport.send({
83 type: "custom",
84 event: REQUEST_EXPORT_TYPES_EVENT,
85 });
86 });
87 }
88
89 override async fetchModule(
90 id: string,
91 importer?: string,
92 options?: FetchFunctionOptions,
93 ): Promise<vite.FetchResult> {
94 // Additional modules (CompiledWasm, Data, Text) are resolved to
95 // `__CLOUDFLARE_MODULE__...` ids and must be externalized so the module
96 // runner loads them via native `import()` → workerd's module fallback.
97 if (MODULE_REFERENCE_REGEX.test(id)) {
98 return {
99 externalize: id,
100 type: "module",
101 };
102 }
103 return super.fetchModule(id, importer, options);
104 }
105 }
106
107 class HotChannel implements vite.HotChannel {
108 #ws?: WebSocket;
109 queue?: Array<string>;
110 listeners = new Map<string, Set<vite.HotChannelListener>>();
111
112 /**
113 * Replaces the socket, which also happens when the Worker runtime is
114 * restarted mid-session.
115 *
116 * Messages are dispatched from the moment a socket is attached rather than
117 * from `listen()`: the dev server queries the Worker for its export types
118 * during `configureServer`, which is before Vite calls `listen()`.
119 */
120 set ws(ws: WebSocket) {
121 this.#ws?.removeEventListener("message", this.boundDispatch);
122 this.#ws = ws;
123 ws.addEventListener("message", this.boundDispatch);
124 if (this.queue) {
125 for (const message of this.queue) {
126 ws.send(message);
127 }
128 this.queue = undefined;
129 }
130 }
131
132 send(payload: vite.CustomPayload) {
133 const json = JSON.stringify(payload);
134 if (this.#ws) {
135 this.#ws.send(json);
136 } else {
137 this.queue ??= [];
138 this.queue.push(json);
139 }
140 }
141
142 on(event: string, listener: vite.HotChannelListener) {
143 const listeners = this.listeners.get(event) ?? new Set();
144 listeners.add(listener);
145 this.listeners.set(event, listeners);
146 }
147
148 off(event: string, listener: vite.HotChannelListener) {
149 this.listeners.get(event)?.delete(listener);
150 }
151
152 private boundDispatch = this.dispatch.bind(this);
153
154 listen() {
155 assert(this.#ws, "WebSocket is not connected");
156 // Already dispatching — see the `ws` setter.
157 }
158
159 close() {
160 // The channel can be closed before a runner ever connected (e.g. a dev
161 // server created and torn down during a framework's type generation), so
162 // tolerate a missing socket — and close it so the runtime connection does
163 // not leak across server restarts.
164 if (!this.#ws) return;
165 this.#ws.removeEventListener("message", this.boundDispatch);
166 this.#ws.close();
167 this.#ws = undefined;
168 }
169
170 private dispatch(event: MessageEvent) {
171 const payload = JSON.parse(event.data.toString()) as vite.CustomPayload;
172
173 const listeners = this.listeners.get(payload.event) ?? new Set();
174 for (const listener of listeners) {
175 listener(payload.data, this.client);
176 }
177 }
178
179 private client: vite.HotChannelClient = {
180 send: (payload) => {
181 assert(this.#ws, "WebSocket is not connected");
182
183 this.#ws.send(JSON.stringify(payload));
184 },
185 };
186 }