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

electron-launcher.mjs

426 lines14.2 KB

1// This file mostly exists because we want dev mode to say "T3 Code (Dev)" instead of "electron"
2​
3import * as NodeChildProcess from "node:child_process";
4import * as NodeFS from "node:fs";
5import * as NodeModule from "node:module";
6import * as NodeOS from "node:os";
7import * as NodePath from "node:path";
8import * as NodeURL from "node:url";
9import { ensureElectronRuntime } from "./ensure-electron-runtime.mjs";
10​
11const isDevelopment = Boolean(process.env.VITE_DEV_SERVER_URL);
12const __dirname = NodePath.dirname(NodeURL.fileURLToPath(import.meta.url));
13export const desktopDir = NodePath.resolve(__dirname, "..");
14const repoRoot = NodePath.resolve(desktopDir, "..", "..");
15const devBundleIdSuffix = NodePath.basename(repoRoot)
16 .toLowerCase()
17 .replaceAll(/[^a-z0-9]+/g, "");
18export const APP_DISPLAY_NAME = isDevelopment ? "T3 Code (Dev)" : "T3 Code (Alpha)";
19export const APP_BUNDLE_ID = isDevelopment
20 ? `com.t3tools.t3code.dev.${devBundleIdSuffix || "local"}`
21 : "com.t3tools.t3code";
22const APP_PROTOCOL_SCHEMES = isDevelopment ? ["t3code-dev"] : ["t3code"];
23const LAUNCHER_VERSION = 15;
24const developmentMacIconPngPath = NodePath.join(
25 repoRoot,
26 "assets",
27 "dev",
28 "blueprint-macos-1024.png",
29);
30const productionMacIconPngPath = NodePath.join(repoRoot, "assets", "prod", "black-macos-1024.png");
31// oxlint-disable-next-line t3code/no-global-process-runtime -- Standalone launcher script has no Effect runtime.
32const hostPlatform = NodeOS.platform();
33​
34function setPlistString(plistPath, key, value) {
35 const replaceResult = NodeChildProcess.spawnSync(
36 "plutil",
37 ["-replace", key, "-string", value, plistPath],
38 {
39 encoding: "utf8",
40 },
41 );
42 if (replaceResult.status === 0) {
43 return;
44 }
45​
46 const insertResult = NodeChildProcess.spawnSync(
47 "plutil",
48 ["-insert", key, "-string", value, plistPath],
49 {
50 encoding: "utf8",
51 },
52 );
53 if (insertResult.status === 0) {
54 return;
55 }
56​
57 const details = [replaceResult.stderr, insertResult.stderr].filter(Boolean).join("\n");
58 throw new Error(`Failed to update plist key "${key}" at ${plistPath}: ${details}`.trim());
60​
61function setPlistJson(plistPath, key, value) {
62 const serialized = JSON.stringify(value);
63 const replaceResult = NodeChildProcess.spawnSync(
64 "plutil",
65 ["-replace", key, "-json", serialized, plistPath],
66 {
67 encoding: "utf8",
68 },
69 );
70 if (replaceResult.status === 0) {
71 return;
72 }
73​
74 const insertResult = NodeChildProcess.spawnSync(
75 "plutil",
76 ["-insert", key, "-json", serialized, plistPath],
77 {
78 encoding: "utf8",
79 },
80 );
81 if (insertResult.status === 0) {
82 return;
83 }
84​
85 const details = [replaceResult.stderr, insertResult.stderr].filter(Boolean).join("\n");
86 throw new Error(`Failed to update plist key "${key}" at ${plistPath}: ${details}`.trim());
88​
89function runChecked(command, args) {
90 const result = NodeChildProcess.spawnSync(command, args, { encoding: "utf8" });
91 if (result.status === 0) {
92 return;
93 }
94​
95 const details = [result.stdout, result.stderr].filter(Boolean).join("\n");
96 throw new Error(`Failed to run ${command} ${args.join(" ")}: ${details}`.trim());
98​
99function shellSingleQuote(value) {
100 return `'${value.replaceAll("'", "'\\''")}'`;
102​
103export function makeDevelopmentLauncherScript({
104 electronBinaryPath,
105 mainEntryPath,
106 desktopRoot,
107 environment,
108}) {
109 const envEntries = [
110 ["VITE_DEV_SERVER_URL", environment.VITE_DEV_SERVER_URL],
111 ["T3CODE_PORT", environment.T3CODE_PORT],
112 ["T3CODE_HOME", environment.T3CODE_HOME],
113 ["T3CODE_COMMIT_HASH", environment.T3CODE_COMMIT_HASH],
114 ["T3CODE_OTLP_TRACES_URL", environment.T3CODE_OTLP_TRACES_URL],
115 ["T3CODE_OTLP_EXPORT_INTERVAL_MS", environment.T3CODE_OTLP_EXPORT_INTERVAL_MS],
116 ["T3CODE_DESKTOP_APP_USER_MODEL_ID", APP_BUNDLE_ID],
117 ].filter((entry) => typeof entry[1] === "string" && entry[1].trim().length > 0);
118 return [
119 "#!/bin/sh",
120 ...envEntries.map(
121 ([name, value]) =>
122 `if [ -z "\${${name}:-}" ]; then export ${name}=${shellSingleQuote(value)}; fi`,
123 ),
124 `exec ${shellSingleQuote(electronBinaryPath)} --t3code-dev-root=${shellSingleQuote(desktopRoot)} ${shellSingleQuote(mainEntryPath)} "$@"`,
125 "",
126 ].join("\n");
128​
129function writeDevelopmentLauncherScript(targetBinaryPath, electronBinaryPath) {
130 NodeFS.writeFileSync(
131 targetBinaryPath,
132 makeDevelopmentLauncherScript({
133 electronBinaryPath,
134 mainEntryPath: NodePath.join(desktopDir, "dist-electron", "main.cjs"),
135 desktopRoot: desktopDir,
136 environment: process.env,
137 }),
138 );
139 NodeFS.chmodSync(targetBinaryPath, 0o755);
141​
142function registerMacLauncherBundle(appBundlePath) {
143 runChecked(
144 "/System/Library/Frameworks/CoreServices.framework/Frameworks/LaunchServices.framework/Support/lsregister",
145 ["-f", appBundlePath],
146 );
147​
148 if (!isDevelopment) {
149 return;
150 }
151​
152 for (const scheme of APP_PROTOCOL_SCHEMES) {
153 runChecked("osascript", [
154 "-l",
155 "JavaScript",
156 "-e",
157 [
158 'ObjC.import("CoreServices");',
159 `const scheme = $.NSString.alloc.initWithUTF8String(${JSON.stringify(scheme)});`,
160 `const bundle = $.NSString.alloc.initWithUTF8String(${JSON.stringify(APP_BUNDLE_ID)});`,
161 "const status = $.LSSetDefaultHandlerForURLScheme(scheme, bundle);",
162 "if (status !== 0) throw new Error(`LSSetDefaultHandlerForURLScheme failed: ${status}`);",
163 ].join(" "),
164 ]);
165 }
167​
168export function resolveMacLauncherIconPaths(runtimeDir, development = isDevelopment) {
169 return {
170 sourceIconPath: development ? developmentMacIconPngPath : productionMacIconPngPath,
171 generatedIconPath: NodePath.join(runtimeDir, development ? "icon-dev.icns" : "icon-prod.icns"),
172 };
174​
175function ensureMacIconIcns(runtimeDir) {
176 const { sourceIconPath, generatedIconPath } = resolveMacLauncherIconPaths(runtimeDir);
177 NodeFS.mkdirSync(runtimeDir, { recursive: true });
178​
179 if (!NodeFS.existsSync(sourceIconPath)) {
180 throw new Error(`Desktop macOS icon source is missing at ${sourceIconPath}`);
181 }
182​
183 const sourceMtimeMs = NodeFS.statSync(sourceIconPath).mtimeMs;
184 if (
185 NodeFS.existsSync(generatedIconPath) &&
186 NodeFS.statSync(generatedIconPath).mtimeMs >= sourceMtimeMs
187 ) {
188 return generatedIconPath;
189 }
190​
191 const iconsetRoot = NodeFS.mkdtempSync(NodePath.join(runtimeDir, "dev-iconset-"));
192 const iconsetDir = NodePath.join(iconsetRoot, "icon.iconset");
193 NodeFS.mkdirSync(iconsetDir, { recursive: true });
194​
195 try {
196 for (const size of [16, 32, 128, 256, 512]) {
197 runChecked("sips", [
198 "-z",
199 String(size),
200 String(size),
201 sourceIconPath,
202 "--out",
203 NodePath.join(iconsetDir, `icon_${size}x${size}.png`),
204 ]);
205​
206 const retinaSize = size * 2;
207 runChecked("sips", [
208 "-z",
209 String(retinaSize),
210 String(retinaSize),
211 sourceIconPath,
212 "--out",
213 NodePath.join(iconsetDir, `icon_${size}x${size}@2x.png`),
214 ]);
215 }
216​
217 runChecked("iconutil", ["-c", "icns", iconsetDir, "-o", generatedIconPath]);
218 return generatedIconPath;
219 } finally {
220 NodeFS.rmSync(iconsetRoot, { recursive: true, force: true });
221 }
223​
224function patchMainBundleInfoPlist(appBundlePath, iconPath, executableName) {
225 const infoPlistPath = NodePath.join(appBundlePath, "Contents", "Info.plist");
226 setPlistString(infoPlistPath, "CFBundleDisplayName", APP_DISPLAY_NAME);
227 setPlistString(infoPlistPath, "CFBundleName", APP_DISPLAY_NAME);
228 setPlistString(infoPlistPath, "CFBundleIdentifier", APP_BUNDLE_ID);
229 setPlistString(infoPlistPath, "CFBundleExecutable", executableName);
230 setPlistString(infoPlistPath, "CFBundleIconFile", "icon.icns");
231 setPlistJson(infoPlistPath, "CFBundleURLTypes", [
232 {
233 CFBundleURLName: APP_BUNDLE_ID,
234 CFBundleURLSchemes: APP_PROTOCOL_SCHEMES,
235 },
236 ]);
237​
238 const resourcesDir = NodePath.join(appBundlePath, "Contents", "Resources");
239 NodeFS.copyFileSync(iconPath, NodePath.join(resourcesDir, "icon.icns"));
240 NodeFS.copyFileSync(iconPath, NodePath.join(resourcesDir, "electron.icns"));
242​
243function patchHelperBundleInfoPlists(appBundlePath) {
244 const helperBundleNames = [
245 ["Electron Helper.app", "helper", `${APP_DISPLAY_NAME} Helper`],
246 ["Electron Helper (GPU).app", "helper.gpu", `${APP_DISPLAY_NAME} Helper (GPU)`],
247 ["Electron Helper (Plugin).app", "helper.plugin", `${APP_DISPLAY_NAME} Helper (Plugin)`],
248 ["Electron Helper (Renderer).app", "helper.renderer", `${APP_DISPLAY_NAME} Helper (Renderer)`],
249 ];
250​
251 for (const [bundleName, bundleIdentifierSuffix, bundleDisplayName] of helperBundleNames) {
252 const infoPlistPath = NodePath.join(
253 appBundlePath,
254 "Contents",
255 "Frameworks",
256 bundleName,
257 "Contents",
258 "Info.plist",
259 );
260 if (!NodeFS.existsSync(infoPlistPath)) {
261 continue;
262 }
263​
264 setPlistString(infoPlistPath, "CFBundleDisplayName", bundleDisplayName);
265 setPlistString(infoPlistPath, "CFBundleName", bundleDisplayName);
266 setPlistString(
267 infoPlistPath,
268 "CFBundleIdentifier",
269 `${APP_BUNDLE_ID}.${bundleIdentifierSuffix}`,
270 );
271 }
273​
274function readJson(path) {
275 try {
276 return JSON.parse(NodeFS.readFileSync(path, "utf8"));
277 } catch {
278 return null;
279 }
281​
282export function resolveMacLauncherPaths(appBundlePath, displayName = APP_DISPLAY_NAME) {
283 const executableDir = NodePath.join(appBundlePath, "Contents", "MacOS");
284 const launcherExecutableName = `${displayName} Launcher`;
285 return {
286 launcherExecutableName,
287 launcherBinaryPath: NodePath.join(executableDir, launcherExecutableName),
288 runtimeElectronBinaryPath: NodePath.join(executableDir, "Electron"),
289 };
291​
292function buildMacLauncher(electronBinaryPath) {
293 const sourceAppBundlePath = NodePath.resolve(NodePath.dirname(electronBinaryPath), "../..");
294 const runtimeDir = NodePath.join(desktopDir, ".electron-runtime");
295 const targetAppBundlePath = NodePath.join(runtimeDir, `${APP_DISPLAY_NAME}.app`);
296 const developmentPaths = resolveMacLauncherPaths(targetAppBundlePath);
297 const runtimeElectronBinaryPath = developmentPaths.runtimeElectronBinaryPath;
298 const launcherBinaryPath = isDevelopment
299 ? developmentPaths.launcherBinaryPath
300 : runtimeElectronBinaryPath;
301 const iconPath = ensureMacIconIcns(runtimeDir);
302 const metadataPath = NodePath.join(runtimeDir, "metadata.json");
303​
304 NodeFS.mkdirSync(runtimeDir, { recursive: true });
305​
306 const expectedMetadata = {
307 launcherVersion: LAUNCHER_VERSION,
308 sourceAppBundlePath,
309 sourceAppMtimeMs: NodeFS.statSync(sourceAppBundlePath).mtimeMs,
310 iconMtimeMs: NodeFS.statSync(iconPath).mtimeMs,
311 appBundleId: APP_BUNDLE_ID,
312 appProtocolSchemes: APP_PROTOCOL_SCHEMES,
313 };
314​
315 const currentMetadata = readJson(metadataPath);
316 if (
317 NodeFS.existsSync(launcherBinaryPath) &&
318 (!isDevelopment || NodeFS.existsSync(runtimeElectronBinaryPath)) &&
319 currentMetadata &&
320 JSON.stringify(currentMetadata) === JSON.stringify(expectedMetadata)
321 ) {
322 if (isDevelopment) {
323 // The launcher also handles protocol activations outside the dev runner,
324 // so refresh its fallback environment on every launch. Never let a value
325 // captured by an older parent app override the live dev-runner environment.
326 writeDevelopmentLauncherScript(launcherBinaryPath, runtimeElectronBinaryPath);
327 }
328 registerMacLauncherBundle(targetAppBundlePath);
329 return launcherBinaryPath;
330 }
331​
332 NodeFS.rmSync(targetAppBundlePath, { recursive: true, force: true });
333 // verbatimSymlinks keeps the framework's relative symlinks intact
334 // (e.g. Resources -> Versions/Current/Resources). Without it cpSync
335 // rewrites them to absolute paths into node_modules, which escape the
336 // bundle and crash sandboxed helper processes (icudtl.dat not found).
337 NodeFS.cpSync(sourceAppBundlePath, targetAppBundlePath, {
338 recursive: true,
339 verbatimSymlinks: true,
340 });
341 patchMainBundleInfoPlist(
342 targetAppBundlePath,
343 iconPath,
344 isDevelopment ? developmentPaths.launcherExecutableName : "Electron",
345 );
346 patchHelperBundleInfoPlists(targetAppBundlePath);
347 if (isDevelopment) {
348 // Keep Electron's native executable inside the branded bundle. Launching the
349 // node_modules copy makes macOS associate the process (and Dock label) with
350 // Electron.app even though this bundle's Info.plist has the T3 Code name.
351 // Its conventional executable name also keeps Electron's default-app runtime
352 // in development mode instead of making app.isPackaged report true.
353 writeDevelopmentLauncherScript(launcherBinaryPath, runtimeElectronBinaryPath);
354 }
355 NodeFS.writeFileSync(metadataPath, `${JSON.stringify(expectedMetadata, null, 2)}\n`);
356 registerMacLauncherBundle(targetAppBundlePath);
357​
358 return launcherBinaryPath;
360​
361function isLinuxSetuidSandboxConfigured(electronBinaryPath) {
362 if (hostPlatform !== "linux") {
363 return true;
364 }
365​
366 const sandboxPath = NodePath.join(NodePath.dirname(electronBinaryPath), "chrome-sandbox");
367 try {
368 const sandboxStat = NodeFS.statSync(sandboxPath);
369 return sandboxStat.uid === 0 && (sandboxStat.mode & 0o4777) === 0o4755;
370 } catch {
371 return false;
372 }
374​
375function resolveLinuxSandboxArgs(electronBinaryPath) {
376 if (isLinuxSetuidSandboxConfigured(electronBinaryPath)) {
377 return [];
378 }
379​
380 console.warn(
381 "[desktop-launcher] Electron chrome-sandbox is not root-owned with mode 4755; launching local Electron with --no-sandbox.",
382 );
383 return ["--no-sandbox"];
385​
386export function resolveElectronPath() {
387 const electronBinaryPath = resolveElectronBinaryPath();
388​
389 if (hostPlatform !== "darwin") {
390 return electronBinaryPath;
391 }
392​
393 return buildMacLauncher(electronBinaryPath);
395​
396export function resolveElectronLaunchCommand(args = []) {
397 const electronPath = resolveElectronPath();
398 return {
399 electronPath,
400 args: [...resolveLinuxSandboxArgs(electronPath), ...args],
401 };
403​
404export function resolveElectronBinaryPath({
405 ensureRuntime = ensureElectronRuntime,
406 createRequire = NodeModule.createRequire,
407 moduleUrl = import.meta.url,
408} = {}) {
409 ensureRuntime();
410​
411 const require = createRequire(moduleUrl);
412 return require("electron");
414​
415export function resolveDevProtocolClient() {
416 if (hostPlatform !== "darwin" || !isDevelopment) {
417 return null;
418 }
419​
420 const electronBinaryPath = resolveElectronBinaryPath();
421 const launcherBinaryPath = buildMacLauncher(electronBinaryPath);
422 return {
423 appBundlePath: NodePath.resolve(launcherBinaryPath, "..", "..", ".."),
424 appBundleId: APP_BUNDLE_ID,
425 };