Open History to see the last commit
1// @effect-diagnostics nodeBuiltinImport:off -- Runs the same shell command electron-updater would, without blocking.
2import * as NodeChildProcess from "node:child_process";
3
4import * as Context from "effect/Context";
5import * as Effect from "effect/Effect";
6import * as Layer from "effect/Layer";
7import * as Schema from "effect/Schema";
8import * as Scope from "effect/Scope";
9
10import { AppImageUpdater, autoUpdater, DebUpdater } from "electron-updater";
11
12type AutoUpdater = typeof autoUpdater;
13type SpawnLog = (cmd: string, args?: Array<string>, ...rest: Array<unknown>) => Promise<boolean>;
14
15// Electron holds the AppImage runtime's keepalive pipe and some files without O_CLOEXEC; a
16// relaunched AppImage inherits them, so old runtimes and FUSE mounts never exit. bash (AppRun
17// already needs it; dash cannot close multi-digit fds) closes them before exec'ing the AppImage.
18// -p skips BASH_ENV and exported functions in the helper only; the AppImage still receives both.
19const CLOSE_INHERITED_FDS_THEN_EXEC =
20 'for fd in /proc/self/fd/*; do fd=${fd##*/}; case $fd in *[!0-9]*|[012]) ;; *) eval "exec $fd>&-" ;; esac; done; exec "$@"';
21
22const relaunchWithoutInheritedDescriptors = (updater: AppImageUpdater) => {
23 const spawnLog = (AppImageUpdater.prototype as unknown as { spawnLog: SpawnLog }).spawnLog;
24 (updater as unknown as { spawnLog: SpawnLog }).spawnLog = function (cmd, args = [], ...rest) {
25 return spawnLog.call(
26 this,
27 "bash",
28 ["-p", "-c", CLOSE_INHERITED_FDS_THEN_EXEC, cmd, cmd, ...args],
29 ...rest,
30 );
31 };
32};
33
34interface DebUpdaterInternals {
35 readonly installerPath: string | null;
36 readonly downloadedUpdateHelper: { readonly downloadedFileInfo: unknown } | null;
37 quitAndInstallCalled: boolean;
38 readonly app: { relaunch: () => void };
39 readonly _logger: {
40 info: (message: string) => void;
41 warn: (message: string) => void;
42 error: (message: string) => void;
43 };
44 hasCommand: (cmd: string) => boolean;
45 detectPackageManager: (pms: Array<string>) => string;
46 runCommandWithSudoIfNeeded: (commandWithArgs: Array<string>) => string;
47 spawnSyncLog: (cmd: string, args?: Array<string>, env?: object) => string;
48 sanitizeEnvPath: (envPath: string) => string;
49 doInstall: (options: { readonly isForceRunAfter: boolean }) => boolean;
50}
51
52// DebUpdater runs pkexec/sudo and dpkg through spawnSync, which freezes the main thread for the
53// whole polkit prompt and install. This resolves the exact command it would run (sudo choice,
54// quoting, PATH sanitizing) and runs it asynchronously instead.
55const runWithSudoInBackground = (updater: DebUpdaterInternals, commandWithArgs: Array<string>) => {
56 let resolved: { cmd: string; args: Array<string> } | undefined;
57 updater.spawnSyncLog = function (cmd, args = [], env) {
58 if (cmd === "command") return DebUpdater.prototype["spawnSyncLog"].call(this, cmd, args, env);
59 resolved = { cmd, args };
60 return "";
61 };
62 try {
63 updater.runCommandWithSudoIfNeeded(commandWithArgs);
64 } finally {
65 delete (updater as Partial<DebUpdaterInternals>).spawnSyncLog;
66 }
67 const { cmd, args } = resolved!;
68 updater._logger.info(`Executing: ${cmd} with args: ${args}`);
69 return new Promise<void>((resolve, reject) => {
70 const child = NodeChildProcess.spawn(cmd, args, {
71 env: { ...process.env, PATH: updater.sanitizeEnvPath(process.env.PATH ?? "") },
72 shell: true,
73 stdio: ["ignore", "ignore", "pipe"],
74 });
75 let stderr = "";
76 child.stderr?.on("data", (chunk) => {
77 stderr += String(chunk);
78 });
79 child.once("error", reject);
80 child.once("close", (status) => {
81 if (status === 0) return resolve();
82 updater._logger.error(stderr);
83 reject(new Error(`Command ${cmd} exited with code ${status}`));
84 });
85 });
86};
87
88const installDebInBackground = async (
89 updater: DebUpdaterInternals,
90 isSilent: boolean,
91 isForceRunAfter: boolean,
92) => {
93 if (updater.quitAndInstallCalled) return;
94 const installerPath = updater.installerPath;
95 if (installerPath === null || updater.downloadedUpdateHelper?.downloadedFileInfo == null) {
96 throw new Error("No update filepath provided, can't quit and install");
97 }
98 if (!updater.hasCommand("dpkg") && !updater.hasCommand("apt")) {
99 throw new Error("Neither dpkg nor apt command found. Cannot install .deb package.");
100 }
101 // Only the first command is recorded: the runner never throws, so upstream's fallback never runs.
102 let install: Array<string> | undefined;
103 DebUpdater.installWithCommandRunner(
104 updater.detectPackageManager(["dpkg", "apt"]) as "dpkg" | "apt",
105 installerPath,
106 (commandWithArgs) => {
107 install ??= commandWithArgs;
108 },
109 updater._logger,
110 );
111 updater.quitAndInstallCalled = true;
112 try {
113 await runWithSudoInBackground(updater, install!).catch((error) => {
114 if (install![0] !== "dpkg") throw error;
115 updater._logger.warn(String(error instanceof Error ? error.message : error));
116 updater._logger.warn(
117 "dpkg installation failed, trying to fix broken dependencies with apt-get",
118 );
119 return runWithSudoInBackground(updater, ["apt-get", "install", "-f", "-y"]);
120 });
121 } finally {
122 updater.quitAndInstallCalled = false;
123 }
124 // The package is installed; let electron-updater's own quitAndInstall relaunch and quit.
125 updater.doInstall = function ({ isForceRunAfter }) {
126 if (isForceRunAfter) this.app.relaunch();
127 return true;
128 };
129 try {
130 (updater as unknown as DebUpdater).quitAndInstall(isSilent, isForceRunAfter);
131 } finally {
132 delete (updater as Partial<DebUpdaterInternals>).doInstall;
133 }
134};
135
136export type ElectronUpdaterFeedUrl = Parameters<AutoUpdater["setFeedURL"]>[0];
137
138export class ElectronUpdaterCheckForUpdatesError extends Schema.TaggedError<ElectronUpdaterCheckForUpdatesError>()(
139 "ElectronUpdaterCheckForUpdatesError",
140 {
141 channel: Schema.NullOr(Schema.String),
142 cause: Schema.Defect(),
143 },
144) {
145 override get message(): string {
146 return `Electron updater failed to check for updates on channel ${this.channel ?? "default"}.`;
147 }
148}
149
150export class ElectronUpdaterDownloadUpdateError extends Schema.TaggedError<ElectronUpdaterDownloadUpdateError>()(
151 "ElectronUpdaterDownloadUpdateError",
152 {
153 channel: Schema.NullOr(Schema.String),
154 cause: Schema.Defect(),
155 },
156) {
157 override get message(): string {
158 return `Electron updater failed to download the update on channel ${this.channel ?? "default"}.`;
159 }
160}
161
162export class ElectronUpdaterQuitAndInstallError extends Schema.TaggedError<ElectronUpdaterQuitAndInstallError>()(
163 "ElectronUpdaterQuitAndInstallError",
164 {
165 channel: Schema.NullOr(Schema.String),
166 isSilent: Schema.Boolean,
167 isForceRunAfter: Schema.Boolean,
168 cause: Schema.Defect(),
169 },
170) {
171 override get message(): string {
172 return `Electron updater failed to quit and install the update on channel ${this.channel ?? "default"} (silent: ${this.isSilent}, force run after: ${this.isForceRunAfter}).`;
173 }
174}
175
176export const ElectronUpdaterError = Schema.Union([
177 ElectronUpdaterCheckForUpdatesError,
178 ElectronUpdaterDownloadUpdateError,
179 ElectronUpdaterQuitAndInstallError,
180]);
181export type ElectronUpdaterError = typeof ElectronUpdaterError.Type;
182
183export class ElectronUpdater extends Context.Service<
184 ElectronUpdater,
185 {
186 readonly setFeedURL: (options: ElectronUpdaterFeedUrl) => Effect.Effect<void>;
187 readonly setAutoDownload: (value: boolean) => Effect.Effect<void>;
188 readonly setAutoInstallOnAppQuit: (value: boolean) => Effect.Effect<void>;
189 readonly setChannel: (channel: string) => Effect.Effect<void>;
190 readonly setAllowPrerelease: (value: boolean) => Effect.Effect<void>;
191 readonly allowDowngrade: Effect.Effect<boolean>;
192 readonly setAllowDowngrade: (value: boolean) => Effect.Effect<void>;
193 readonly setFullChangelog: (value: boolean) => Effect.Effect<void>;
194 readonly setDisableDifferentialDownload: (value: boolean) => Effect.Effect<void>;
195 readonly checkForUpdates: Effect.Effect<void, ElectronUpdaterCheckForUpdatesError>;
196 readonly downloadUpdate: Effect.Effect<void, ElectronUpdaterDownloadUpdateError>;
197 readonly quitAndInstall: (options: {
198 readonly isSilent: boolean;
199 readonly isForceRunAfter: boolean;
200 }) => Effect.Effect<void, ElectronUpdaterQuitAndInstallError>;
201 readonly on: <Args extends ReadonlyArray<unknown>>(
202 eventName: string,
203 listener: (...args: Args) => void,
204 ) => Effect.Effect<void, never, Scope.Scope>;
205 }
206>()("@t3tools/desktop/electron/ElectronUpdater") {}
207
208/** @public */
209export const make = ElectronUpdater.of({
210 setFeedURL: Effect.fn("ElectronUpdater.setFeedURL")(function (options) {
211 return Effect.suspend(() => {
212 autoUpdater.setFeedURL(options);
213 return Effect.void;
214 });
215 }),
216 setAutoDownload: Effect.fn("ElectronUpdater.setAutoDownload")(function (value) {
217 return Effect.suspend(() => {
218 autoUpdater.autoDownload = value;
219 return Effect.void;
220 });
221 }),
222 setAutoInstallOnAppQuit: Effect.fn("ElectronUpdater.setAutoInstallOnAppQuit")(function (value) {
223 return Effect.suspend(() => {
224 autoUpdater.autoInstallOnAppQuit = value;
225 return Effect.void;
226 });
227 }),
228 setChannel: Effect.fn("ElectronUpdater.setChannel")(function (channel) {
229 return Effect.suspend(() => {
230 autoUpdater.channel = channel;
231 return Effect.void;
232 });
233 }),
234 setAllowPrerelease: Effect.fn("ElectronUpdater.setAllowPrerelease")(function (value) {
235 return Effect.suspend(() => {
236 autoUpdater.allowPrerelease = value;
237 return Effect.void;
238 });
239 }),
240 allowDowngrade: Effect.sync(() => autoUpdater.allowDowngrade),
241 setAllowDowngrade: Effect.fn("ElectronUpdater.setAllowDowngrade")(function (value) {
242 return Effect.suspend(() => {
243 autoUpdater.allowDowngrade = value;
244 return Effect.void;
245 });
246 }),
247 setFullChangelog: Effect.fn("ElectronUpdater.setFullChangelog")(function (value) {
248 return Effect.suspend(() => {
249 autoUpdater.fullChangelog = value;
250 return Effect.void;
251 });
252 }),
253 setDisableDifferentialDownload: Effect.fn("ElectronUpdater.setDisableDifferentialDownload")(
254 function (value) {
255 return Effect.suspend(() => {
256 autoUpdater.disableDifferentialDownload = value;
257 return Effect.void;
258 });
259 },
260 ),
261 checkForUpdates: Effect.suspend(() => {
262 const channel = autoUpdater.channel;
263 return Effect.tryPromise({
264 try: () => autoUpdater.checkForUpdates(),
265 catch: (cause) => new ElectronUpdaterCheckForUpdatesError({ channel, cause }),
266 }).pipe(Effect.asVoid);
267 }),
268 downloadUpdate: Effect.suspend(() => {
269 const channel = autoUpdater.channel;
270 return Effect.tryPromise({
271 try: () => autoUpdater.downloadUpdate(),
272 catch: (cause) => new ElectronUpdaterDownloadUpdateError({ channel, cause }),
273 }).pipe(Effect.asVoid);
274 }),
275 quitAndInstall: Effect.fn("ElectronUpdater.quitAndInstall")(function ({
276 isSilent,
277 isForceRunAfter,
278 }) {
279 return Effect.suspend(() => {
280 const channel = autoUpdater.channel;
281 if (autoUpdater instanceof AppImageUpdater) relaunchWithoutInheritedDescriptors(autoUpdater);
282 if (autoUpdater instanceof DebUpdater) {
283 const updater = autoUpdater as unknown as DebUpdaterInternals;
284 return Effect.tryPromise({
285 try: () => installDebInBackground(updater, isSilent, isForceRunAfter),
286 catch: (cause) =>
287 new ElectronUpdaterQuitAndInstallError({
288 channel,
289 isSilent,
290 isForceRunAfter,
291 cause,
292 }),
293 });
294 }
295 return Effect.try({
296 try: () => autoUpdater.quitAndInstall(isSilent, isForceRunAfter),
297 catch: (cause) =>
298 new ElectronUpdaterQuitAndInstallError({
299 channel,
300 isSilent,
301 isForceRunAfter,
302 cause,
303 }),
304 });
305 });
306 }),
307 on: Effect.fn("ElectronUpdater.on")(function (eventName, listener) {
308 const eventTarget = autoUpdater as unknown as {
309 on: (eventName: string, listener: (...args: Array<unknown>) => void) => void;
310 removeListener: (eventName: string, listener: (...args: Array<unknown>) => void) => void;
311 };
312 const untypedListener = listener as unknown as (...args: Array<unknown>) => void;
313 return Effect.acquireRelease(
314 Effect.sync(() => {
315 eventTarget.on(eventName, untypedListener);
316 }),
317 () =>
318 Effect.sync(() => {
319 eventTarget.removeListener(eventName, untypedListener);
320 }),
321 ).pipe(Effect.asVoid);
322 }),
323});
324
325export const layer = Layer.succeed(ElectronUpdater, make);