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