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

dev-electron.mjs

207 lines4.4 KB

1import { spawn, spawnSync } from "node:child_process";
2import { watch } from "node:fs";
3import { join } from "node:path";
4import waitOn from "wait-on";
5​
6import { desktopDir, resolveElectronPath } from "./electron-launcher.mjs";
7​
8const port = Number(process.env.ELECTRON_RENDERER_PORT ?? 5733);
9const devServerUrl = `http://localhost:${port}`;
10const requiredFiles = ["dist-electron/main.js", "dist-electron/preload.js", "../server/dist/index.mjs"];
11const watchedDirectories = [
12 { directory: "dist-electron", files: new Set(["main.js", "preload.js"]) },
13 { directory: "../server/dist", files: new Set(["index.mjs"]) },
14];
15const forcedShutdownTimeoutMs = 1_500;
16const restartDebounceMs = 120;
17const childTreeGracePeriodMs = 1_200;
18​
19await waitOn({
20 resources: [`tcp:${port}`, ...requiredFiles.map((filePath) => `file:${filePath}`)],
21});
22​
23const childEnv = { ...process.env };
24delete childEnv.ELECTRON_RUN_AS_NODE;
25​
26let shuttingDown = false;
27let restartTimer = null;
28let currentApp = null;
29let restartQueue = Promise.resolve();
30const expectedExits = new WeakSet();
31const watchers = [];
32​
33function killChildTreeByPid(pid, signal) {
34 if (process.platform === "win32" || typeof pid !== "number") {
35 return;
36 }
37​
38 spawnSync("pkill", [`-${signal}`, "-P", String(pid)], { stdio: "ignore" });
40​
41function cleanupStaleDevApps() {
42 if (process.platform === "win32") {
43 return;
44 }
45​
46 spawnSync("pkill", ["-f", "--", `--t3code-dev-root=${desktopDir}`], { stdio: "ignore" });
48​
49function startApp() {
50 if (shuttingDown || currentApp !== null) {
51 return;
52 }
53​
54 const app = spawn(
55 resolveElectronPath(),
56 [`--t3code-dev-root=${desktopDir}`, "dist-electron/main.js"],
57 {
58 cwd: desktopDir,
59 env: {
60 ...childEnv,
61 VITE_DEV_SERVER_URL: devServerUrl,
62 },
63 stdio: "inherit",
64 },
65 );
66​
67 currentApp = app;
68​
69 app.once("error", () => {
70 if (currentApp === app) {
71 currentApp = null;
72 }
73​
74 if (!shuttingDown) {
75 scheduleRestart();
76 }
77 });
78​
79 app.once("exit", () => {
80 if (currentApp === app) {
81 currentApp = null;
82 }
83​
84 if (!shuttingDown && !expectedExits.has(app)) {
85 scheduleRestart();
86 }
87 });
89​
90async function stopApp() {
91 const app = currentApp;
92 if (!app) {
93 return;
94 }
95​
96 currentApp = null;
97 expectedExits.add(app);
98​
99 await new Promise((resolve) => {
100 let settled = false;
101​
102 const finish = () => {
103 if (settled) {
104 return;
105 }
106​
107 settled = true;
108 resolve();
109 };
110​
111 app.once("exit", finish);
112 app.kill("SIGTERM");
113 killChildTreeByPid(app.pid, "TERM");
114​
115 setTimeout(() => {
116 if (settled) {
117 return;
118 }
119​
120 app.kill("SIGKILL");
121 killChildTreeByPid(app.pid, "KILL");
122 finish();
123 }, forcedShutdownTimeoutMs).unref();
124 });
126​
127function scheduleRestart() {
128 if (shuttingDown) {
129 return;
130 }
131​
132 if (restartTimer) {
133 clearTimeout(restartTimer);
134 }
135​
136 restartTimer = setTimeout(() => {
137 restartTimer = null;
138 restartQueue = restartQueue
139 .catch(() => undefined)
140 .then(async () => {
141 await stopApp();
142 if (!shuttingDown) {
143 startApp();
144 }
145 });
146 }, restartDebounceMs);
148​
149function startWatchers() {
150 for (const { directory, files } of watchedDirectories) {
151 const watcher = watch(join(desktopDir, directory), { persistent: true }, (_eventType, filename) => {
152 if (typeof filename !== "string" || !files.has(filename)) {
153 return;
154 }
155​
156 scheduleRestart();
157 });
158​
159 watchers.push(watcher);
160 }
162​
163function killChildTree(signal) {
164 if (process.platform === "win32") {
165 return;
166 }
167​
168 // Kill direct children as a final fallback in case normal shutdown leaves stragglers.
169 spawnSync("pkill", [`-${signal}`, "-P", String(process.pid)], { stdio: "ignore" });
171​
172async function shutdown(exitCode) {
173 if (shuttingDown) return;
174 shuttingDown = true;
175​
176 if (restartTimer) {
177 clearTimeout(restartTimer);
178 restartTimer = null;
179 }
180​
181 for (const watcher of watchers) {
182 watcher.close();
183 }
184​
185 await stopApp();
186 killChildTree("TERM");
187 await new Promise((resolve) => {
188 setTimeout(resolve, childTreeGracePeriodMs);
189 });
190 killChildTree("KILL");
191​
192 process.exit(exitCode);
194​
195startWatchers();
196cleanupStaleDevApps();
197startApp();
198​
199process.once("SIGINT", () => {
200 void shutdown(130);
201});
202process.once("SIGTERM", () => {
203 void shutdown(143);
204});
205process.once("SIGHUP", () => {
206 void shutdown(129);
207});