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

dev-electron.mjs

247 lines5.7 KB

1import * as NodeChildProcess from "node:child_process";
2import * as NodeFS from "node:fs";
3import * as NodeOS from "node:os";
4import * as NodePath from "node:path";
5​
6import {
7 desktopDir,
8 resolveDevProtocolClient,
9 resolveElectronLaunchCommand,
10} from "./electron-launcher.mjs";
11import { waitForResources } from "./wait-for-resources.mjs";
12​
13const devServerUrl = process.env.VITE_DEV_SERVER_URL?.trim();
14if (!devServerUrl) {
15 throw new Error("VITE_DEV_SERVER_URL is required for desktop development.");
17​
18const devServer = new URL(devServerUrl);
19const port = Number.parseInt(devServer.port, 10);
20if (!Number.isInteger(port) || port <= 0) {
21 throw new Error(`VITE_DEV_SERVER_URL must include an explicit port: ${devServerUrl}`);
23​
24const requiredFiles = [
25 "dist-electron/main.cjs",
26 "dist-electron/preload.cjs",
27 "../server/dist/bin.mjs",
28];
29const watchedDirectories = [
30 { directory: "dist-electron", files: new Set(["main.cjs", "preload.cjs"]) },
31 { directory: "../server/dist", files: new Set(["bin.mjs"]) },
32];
33const forcedShutdownTimeoutMs = 1_500;
34const restartDebounceMs = 120;
35const childTreeGracePeriodMs = 1_200;
36const remoteDebuggingPort = process.env.V12_DESKTOP_REMOTE_DEBUGGING_PORT?.trim();
37// oxlint-disable-next-line v12/no-global-process-runtime -- Standalone dev script has no Effect runtime.
38const hostPlatform = NodeOS.platform();
39​
40await waitForResources({
41 baseDir: desktopDir,
42 files: requiredFiles,
43 tcpHost: devServer.hostname,
44 tcpPort: port,
45});
46​
47const childEnv = { ...process.env };
48delete childEnv.ELECTRON_RUN_AS_NODE;
49const devProtocolClient = resolveDevProtocolClient();
50if (devProtocolClient) {
51 childEnv.V12_DESKTOP_APP_USER_MODEL_ID = devProtocolClient.appBundleId;
52 childEnv.V12_DESKTOP_PROTOCOL_REGISTRATION_MANAGED = "1";
54​
55let shuttingDown = false;
56let restartTimer = null;
57let currentApp = null;
58let restartQueue = Promise.resolve();
59const expectedExits = new WeakSet();
60const watchers = [];
61​
62function killChildTreeByPid(pid, signal) {
63 if (hostPlatform === "win32" || typeof pid !== "number") {
64 return;
65 }
66​
67 NodeChildProcess.spawnSync("pkill", [`-${signal}`, "-P", String(pid)], { stdio: "ignore" });
69​
70function cleanupStaleDevApps() {
71 if (hostPlatform === "win32") {
72 return;
73 }
74​
75 NodeChildProcess.spawnSync("pkill", ["-f", "--", `--v12-dev-root=${desktopDir}`], {
76 stdio: "ignore",
77 });
79​
80function startApp() {
81 if (shuttingDown || currentApp !== null) {
82 return;
83 }
84​
85 const electronArgs = remoteDebuggingPort
86 ? [`--remote-debugging-port=${remoteDebuggingPort}`]
87 : [];
88 const launchArgs = devProtocolClient
89 ? electronArgs
90 : [...electronArgs, `--v12-dev-root=${desktopDir}`, "dist-electron/main.cjs"];
91 const electronCommand = resolveElectronLaunchCommand(launchArgs);
92 const app = NodeChildProcess.spawn(electronCommand.electronPath, electronCommand.args, {
93 cwd: desktopDir,
94 env: childEnv,
95 stdio: "inherit",
96 });
97​
98 currentApp = app;
99​
100 app.once("error", () => {
101 if (currentApp === app) {
102 currentApp = null;
103 }
104​
105 if (!shuttingDown) {
106 scheduleRestart();
107 }
108 });
109​
110 app.once("exit", (code, signal) => {
111 if (currentApp === app) {
112 currentApp = null;
113 }
114​
115 const exitedAbnormally = signal !== null || code !== 0;
116 if (!shuttingDown && !expectedExits.has(app) && exitedAbnormally) {
117 scheduleRestart();
118 }
119 });
121​
122async function stopApp() {
123 const app = currentApp;
124 if (!app) {
125 return;
126 }
127​
128 currentApp = null;
129 expectedExits.add(app);
130​
131 await new Promise((resolve) => {
132 let settled = false;
133​
134 const finish = () => {
135 if (settled) {
136 return;
137 }
138​
139 settled = true;
140 resolve();
141 };
142​
143 app.once("exit", finish);
144 app.kill("SIGTERM");
145 killChildTreeByPid(app.pid, "TERM");
146 cleanupStaleDevApps();
147​
148 setTimeout(() => {
149 if (settled) {
150 return;
151 }
152​
153 app.kill("SIGKILL");
154 killChildTreeByPid(app.pid, "KILL");
155 cleanupStaleDevApps();
156 finish();
157 }, forcedShutdownTimeoutMs).unref();
158 });
160​
161function scheduleRestart() {
162 if (shuttingDown) {
163 return;
164 }
165​
166 if (restartTimer) {
167 clearTimeout(restartTimer);
168 }
169​
170 restartTimer = setTimeout(() => {
171 restartTimer = null;
172 restartQueue = restartQueue
173 .catch(() => undefined)
174 .then(async () => {
175 await stopApp();
176 if (!shuttingDown) {
177 startApp();
178 }
179 });
180 }, restartDebounceMs);
182​
183function startWatchers() {
184 for (const { directory, files } of watchedDirectories) {
185 const watcher = NodeFS.watch(
186 NodePath.join(desktopDir, directory),
187 { persistent: true },
188 (_eventType, filename) => {
189 if (typeof filename !== "string" || !files.has(filename)) {
190 return;
191 }
192​
193 scheduleRestart();
194 },
195 );
196​
197 watchers.push(watcher);
198 }
200​
201function killChildTree(signal) {
202 if (hostPlatform === "win32") {
203 return;
204 }
205​
206 // Kill direct children as a final fallback in case normal shutdown leaves stragglers.
207 NodeChildProcess.spawnSync("pkill", [`-${signal}`, "-P", String(process.pid)], {
208 stdio: "ignore",
209 });
211​
212async function shutdown(exitCode) {
213 if (shuttingDown) return;
214 shuttingDown = true;
215​
216 if (restartTimer) {
217 clearTimeout(restartTimer);
218 restartTimer = null;
219 }
220​
221 for (const watcher of watchers) {
222 watcher.close();
223 }
224​
225 await stopApp();
226 killChildTree("TERM");
227 await new Promise((resolve) => {
228 setTimeout(resolve, childTreeGracePeriodMs);
229 });
230 killChildTree("KILL");
231​
232 process.exit(exitCode);
234​
235startWatchers();
236cleanupStaleDevApps();
237startApp();
238​
239process.once("SIGINT", () => {
240 void shutdown(130);
241});
242process.once("SIGTERM", () => {
243 void shutdown(143);
244});
245process.once("SIGHUP", () => {
246 void shutdown(129);
247});