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

dev-electron.mjs

273 lines6.4 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/electron/WindowsForegroundFocusWorker.cjs",
27 "dist-electron/preload.cjs",
28 "dist-electron/snapShot/GlobalShiftShortcutWorker.cjs",
29 "dist-electron/snapShot/RegionSnapShotWorker.cjs",
30 "dist-electron/snapShot/SnapShotAccessibilityWorker.cjs",
31 "../server/dist/bin.mjs",
32];
33const watchedDirectories = [
34 { directory: "dist-electron", files: new Set(["main.cjs", "preload.cjs"]) },
35 {
36 directory: "dist-electron/electron",
37 files: new Set(["WindowsForegroundFocusWorker.cjs"]),
38 },
39 {
40 directory: "dist-electron/snapShot",
41 files: new Set([
42 "GlobalShiftShortcutWorker.cjs",
43 "RegionSnapShotWorker.cjs",
44 "SnapShotAccessibilityWorker.cjs",
45 ]),
46 },
47 { directory: "../server/dist", files: new Set(["bin.mjs"]) },
48];
49const forcedShutdownTimeoutMs = 1_500;
50const restartDebounceMs = 120;
51const childTreeGracePeriodMs = 1_200;
52const remoteDebuggingPort = process.env.T3CODE_DESKTOP_REMOTE_DEBUGGING_PORT?.trim();
53// oxlint-disable-next-line t3code/no-global-process-runtime -- Standalone dev script has no Effect runtime.
54const hostPlatform = NodeOS.platform();
55​
56NodeChildProcess.execFileSync(
57 process.execPath,
58 [NodePath.join(desktopDir, "scripts/build-browser-secret.mjs")],
59 { stdio: "inherit" },
60);
61​
62await waitForResources({
63 baseDir: desktopDir,
64 files: requiredFiles,
65 tcpHost: devServer.hostname,
66 tcpPort: port,
67});
68​
69const childEnv = { ...process.env };
70delete childEnv.ELECTRON_RUN_AS_NODE;
71const devProtocolClient = resolveDevProtocolClient();
72if (devProtocolClient) {
73 childEnv.T3CODE_DESKTOP_APP_USER_MODEL_ID = devProtocolClient.appBundleId;
74 childEnv.T3CODE_DESKTOP_PROTOCOL_REGISTRATION_MANAGED = "1";
76​
77let shuttingDown = false;
78let restartTimer = null;
79let currentApp = null;
80let restartQueue = Promise.resolve();
81const expectedExits = new WeakSet();
82const watchers = [];
83​
84function killChildTreeByPid(pid, signal) {
85 if (hostPlatform === "win32" || typeof pid !== "number") {
86 return;
87 }
88​
89 NodeChildProcess.spawnSync("pkill", [`-${signal}`, "-P", String(pid)], { stdio: "ignore" });
91​
92function cleanupStaleDevApps() {
93 if (hostPlatform === "win32") {
94 return;
95 }
96​
97 const escapedDesktopDir = desktopDir.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
98 NodeChildProcess.spawnSync(
99 "pkill",
100 ["-f", "--", `(^| )--t3code-dev-root=${escapedDesktopDir}( |$)`],
101 {
102 stdio: "ignore",
103 },
104 );
106​
107function startApp() {
108 if (shuttingDown || currentApp !== null) {
109 return;
110 }
111​
112 const electronArgs = remoteDebuggingPort
113 ? [`--remote-debugging-port=${remoteDebuggingPort}`]
114 : [];
115 const launchArgs = devProtocolClient
116 ? electronArgs
117 : [...electronArgs, `--t3code-dev-root=${desktopDir}`, "dist-electron/main.cjs"];
118 const electronCommand = resolveElectronLaunchCommand(launchArgs);
119 const app = NodeChildProcess.spawn(electronCommand.electronPath, electronCommand.args, {
120 cwd: desktopDir,
121 env: childEnv,
122 stdio: "inherit",
123 });
124​
125 currentApp = app;
126​
127 app.once("error", () => {
128 if (currentApp === app) {
129 currentApp = null;
130 }
131​
132 if (!shuttingDown) {
133 scheduleRestart();
134 }
135 });
136​
137 app.once("exit", (code, signal) => {
138 if (currentApp === app) {
139 currentApp = null;
140 }
141​
142 const exitedAbnormally = signal !== null || code !== 0;
143 if (!shuttingDown && !expectedExits.has(app) && exitedAbnormally) {
144 scheduleRestart();
145 }
146 });
148​
149async function stopApp() {
150 const app = currentApp;
151 if (!app) {
152 return;
153 }
154​
155 currentApp = null;
156 expectedExits.add(app);
157​
158 await new Promise((resolve) => {
159 let settled = false;
160​
161 const finish = () => {
162 if (settled) {
163 return;
164 }
165​
166 settled = true;
167 resolve();
168 };
169​
170 app.once("exit", finish);
171 app.kill("SIGTERM");
172 killChildTreeByPid(app.pid, "TERM");
173 cleanupStaleDevApps();
174​
175 setTimeout(() => {
176 if (settled) {
177 return;
178 }
179​
180 app.kill("SIGKILL");
181 killChildTreeByPid(app.pid, "KILL");
182 cleanupStaleDevApps();
183 finish();
184 }, forcedShutdownTimeoutMs).unref();
185 });
187​
188function scheduleRestart() {
189 if (shuttingDown) {
190 return;
191 }
192​
193 if (restartTimer) {
194 clearTimeout(restartTimer);
195 }
196​
197 restartTimer = setTimeout(() => {
198 restartTimer = null;
199 restartQueue = restartQueue
200 .catch(() => undefined)
201 .then(async () => {
202 await stopApp();
203 if (!shuttingDown) {
204 startApp();
205 }
206 });
207 }, restartDebounceMs);
209​
210function startWatchers() {
211 for (const { directory, files } of watchedDirectories) {
212 const watcher = NodeFS.watch(
213 NodePath.join(desktopDir, directory),
214 { persistent: true },
215 (_eventType, filename) => {
216 if (typeof filename !== "string" || !files.has(filename)) {
217 return;
218 }
219​
220 scheduleRestart();
221 },
222 );
223​
224 watchers.push(watcher);
225 }
227​
228function killChildTree(signal) {
229 if (hostPlatform === "win32") {
230 return;
231 }
232​
233 NodeChildProcess.spawnSync("pkill", [`-${signal}`, "-P", String(process.pid)], {
234 stdio: "ignore",
235 });
237​
238async function shutdown(exitCode) {
239 if (shuttingDown) return;
240 shuttingDown = true;
241​
242 if (restartTimer) {
243 clearTimeout(restartTimer);
244 restartTimer = null;
245 }
246​
247 for (const watcher of watchers) {
248 watcher.close();
249 }
250​
251 await stopApp();
252 killChildTree("TERM");
253 await new Promise((resolve) => {
254 setTimeout(resolve, childTreeGracePeriodMs);
255 });
256 killChildTree("KILL");
257​
258 process.exit(exitCode);
260​
261startWatchers();
262cleanupStaleDevApps();
263startApp();
264​
265process.once("SIGINT", () => {
266 void shutdown(130);
267});
268process.once("SIGTERM", () => {
269 void shutdown(143);
270});
271process.once("SIGHUP", () => {
272 void shutdown(129);
273});