Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

dev-electron.mjs

290 lines6.0 KB

1import { spawn, spawnSync } from "node:child_process";
2import { watch } from "node:fs";
3import { join } from "node:path";
4​
5import { desktopDir, resolveElectronPath } from "./electron-launcher.mjs";
6import { waitForResources } from "./wait-for-resources.mjs";
7​
8const devServerUrl = process.env.VITE_DEV_SERVER_URL?.trim();
9if (!devServerUrl) {
10 throw new Error("VITE_DEV_SERVER_URL is required for desktop development.");
12​
13const devServer = new URL(devServerUrl);
14const port = Number.parseInt(devServer.port, 10);
15if (!Number.isInteger(port) || port <= 0) {
16 throw new Error(`VITE_DEV_SERVER_URL must include an explicit port: ${devServerUrl}`);
18​
19const requiredFiles = [
20 "dist-electron/main.cjs",
21 "dist-electron/preload.cjs",
22 "../server/dist/bin.mjs",
23];
24const serverDir = join(desktopDir, "../server");
25const watchedDirectories = [
26 { directory: "dist-electron", files: new Set(["main.cjs", "preload.cjs"]) },
27 { directory: "../server/dist", files: new Set(["bin.mjs"]) },
28];
29const forcedShutdownTimeoutMs = 1_500;
30const restartDebounceMs = 120;
31const childTreeGracePeriodMs = 1_200;
32​
33await waitForResources({
34 baseDir: desktopDir,
35 files: requiredFiles,
36 tcpHost: devServer.hostname,
37 tcpPort: port,
38});
39​
40const childEnv = { ...process.env };
41delete childEnv.ELECTRON_RUN_AS_NODE;
42​
43let shuttingDown = false;
44let restartTimer = null;
45let currentApp = null;
46let currentServerWatcher = null;
47let restartQueue = Promise.resolve();
48const expectedExits = new WeakSet();
49const watchers = [];
50​
51function killChildTreeByPid(pid, signal) {
52 if (process.platform === "win32" || typeof pid !== "number") {
53 return;
54 }
55​
56 spawnSync("pkill", [`-${signal}`, "-P", String(pid)], { stdio: "ignore" });
58​
59function cleanupStaleDevApps() {
60 if (process.platform === "win32") {
61 return;
62 }
63​
64 spawnSync("pkill", ["-f", "--", `--t3code-dev-root=${desktopDir}`], { stdio: "ignore" });
66​
67function startApp() {
68 if (shuttingDown || currentApp !== null) {
69 return;
70 }
71​
72 const app = spawn(
73 resolveElectronPath(),
74 [`--t3code-dev-root=${desktopDir}`, "dist-electron/main.cjs"],
75 {
76 cwd: desktopDir,
77 env: childEnv,
78 stdio: "inherit",
79 },
80 );
81​
82 currentApp = app;
83​
84 app.once("error", () => {
85 if (currentApp === app) {
86 currentApp = null;
87 }
88​
89 if (!shuttingDown) {
90 scheduleRestart();
91 }
92 });
93​
94 app.once("exit", (code, signal) => {
95 if (currentApp === app) {
96 currentApp = null;
97 }
98​
99 const exitedAbnormally = signal !== null || code !== 0;
100 if (!shuttingDown && !expectedExits.has(app) && exitedAbnormally) {
101 scheduleRestart();
102 }
103 });
105​
106function startServerBundleWatcher() {
107 if (shuttingDown || currentServerWatcher !== null) {
108 return;
109 }
110​
111 const watcher = spawn("bun", ["run", "build:bundle", "--", "--watch"], {
112 cwd: serverDir,
113 env: childEnv,
114 stdio: "inherit",
115 });
116​
117 currentServerWatcher = watcher;
118​
119 watcher.once("error", () => {
120 if (currentServerWatcher === watcher) {
121 currentServerWatcher = null;
122 }
123 });
124​
125 watcher.once("exit", () => {
126 if (currentServerWatcher === watcher) {
127 currentServerWatcher = null;
128 }
129 });
131​
132async function stopApp() {
133 const app = currentApp;
134 if (!app) {
135 return;
136 }
137​
138 currentApp = null;
139 expectedExits.add(app);
140​
141 await new Promise((resolve) => {
142 let settled = false;
143​
144 const finish = () => {
145 if (settled) {
146 return;
147 }
148​
149 settled = true;
150 resolve();
151 };
152​
153 app.once("exit", finish);
154 app.kill("SIGTERM");
155 killChildTreeByPid(app.pid, "TERM");
156​
157 setTimeout(() => {
158 if (settled) {
159 return;
160 }
161​
162 app.kill("SIGKILL");
163 killChildTreeByPid(app.pid, "KILL");
164 finish();
165 }, forcedShutdownTimeoutMs).unref();
166 });
168​
169async function stopServerBundleWatcher() {
170 const watcher = currentServerWatcher;
171 if (!watcher) {
172 return;
173 }
174​
175 currentServerWatcher = null;
176 expectedExits.add(watcher);
177​
178 await new Promise((resolve) => {
179 let settled = false;
180​
181 const finish = () => {
182 if (settled) {
183 return;
184 }
185​
186 settled = true;
187 resolve();
188 };
189​
190 watcher.once("exit", finish);
191 watcher.kill("SIGTERM");
192​
193 setTimeout(() => {
194 if (settled) {
195 return;
196 }
197​
198 watcher.kill("SIGKILL");
199 finish();
200 }, forcedShutdownTimeoutMs).unref();
201 });
203​
204function scheduleRestart() {
205 if (shuttingDown) {
206 return;
207 }
208​
209 if (restartTimer) {
210 clearTimeout(restartTimer);
211 }
212​
213 restartTimer = setTimeout(() => {
214 restartTimer = null;
215 restartQueue = restartQueue
216 .catch(() => undefined)
217 .then(async () => {
218 await stopApp();
219 if (!shuttingDown) {
220 startApp();
221 }
222 });
223 }, restartDebounceMs);
225​
226function startWatchers() {
227 for (const { directory, files } of watchedDirectories) {
228 const watcher = watch(
229 join(desktopDir, directory),
230 { persistent: true },
231 (_eventType, filename) => {
232 if (typeof filename !== "string" || !files.has(filename)) {
233 return;
234 }
235​
236 scheduleRestart();
237 },
238 );
239​
240 watchers.push(watcher);
241 }
243​
244function killChildTree(signal) {
245 if (process.platform === "win32") {
246 return;
247 }
248​
249 // Kill direct children as a final fallback in case normal shutdown leaves stragglers.
250 spawnSync("pkill", [`-${signal}`, "-P", String(process.pid)], { stdio: "ignore" });
252​
253async function shutdown(exitCode) {
254 if (shuttingDown) return;
255 shuttingDown = true;
256​
257 if (restartTimer) {
258 clearTimeout(restartTimer);
259 restartTimer = null;
260 }
261​
262 for (const watcher of watchers) {
263 watcher.close();
264 }
265​
266 await stopApp();
267 await stopServerBundleWatcher();
268 killChildTree("TERM");
269 await new Promise((resolve) => {
270 setTimeout(resolve, childTreeGracePeriodMs);
271 });
272 killChildTree("KILL");
273​
274 process.exit(exitCode);
276​
277startWatchers();
278cleanupStaleDevApps();
279startServerBundleWatcher();
280startApp();
281​
282process.once("SIGINT", () => {
283 void shutdown(130);
284});
285process.once("SIGTERM", () => {
286 void shutdown(143);
287});
288process.once("SIGHUP", () => {
289 void shutdown(129);
290});