Skip to content

Build your personal knowledge base with Trilium Notes

refactor(server): get rid of dependency to electron

Elian Doran40632451ec64
diff --git a/apps/desktop/src/main.ts b/apps/desktop/src/main.ts
index 72debe7d00..770ec7e53d 100644
--- a/apps/desktop/src/main.ts
+++ b/apps/desktop/src/main.ts
@@ -7,7 +7,7 @@ import NodejsInAppHelpProvider from "@triliumnext/server/src/in_app_help_provide
import ServerLogService from "@triliumnext/server/src/log_provider.js";
import dataDirs from "@triliumnext/server/src/services/data_dir.js";
import port from "@triliumnext/server/src/services/port.js";
-import NodeRequestProvider from "@triliumnext/server/src/services/request.js";
+import ElectronRequestProvider from "./services/request";
import { RESOURCE_DIR } from "@triliumnext/server/src/services/resource_dir.js";
import windowService, { setupWindowing } from "./services/window";
import BetterSqlite3Provider from "@triliumnext/server/src/sql_provider.js";
@@ -176,7 +176,7 @@ async function main() {
crypto: new NodejsCryptoProvider(),
zip: new NodejsZipProvider(),
zipExportProviderFactory: (await import("@triliumnext/server/src/services/export/zip/factory.js")).serverZipExportProviderFactory,
- request: new NodeRequestProvider(),
+ request: new ElectronRequestProvider(),
executionContext: new ClsHookedExecutionContext(),
messaging: ipcMessaging,
schema: loadCoreSchema(),
diff --git a/apps/desktop/src/platform_provider.ts b/apps/desktop/src/platform_provider.ts
index 72e9d6cb38..bb5fe6959c 100644
--- a/apps/desktop/src/platform_provider.ts
+++ b/apps/desktop/src/platform_provider.ts
@@ -14,4 +14,16 @@ export default class DesktopPlatformProvider implements PlatformProvider {
getEnv(key: string): string | undefined {
return process.env[key];
}
+
+ /**
+ * Tolerate `EADDRINUSE` when this process was either launched with
+ * `--new-window` (the primary instance handles it via `second-instance`)
+ * or lost the single-instance lock race. In both cases the port collision
+ * is expected and the process should just exit quietly instead of
+ * showing an error dialog.
+ */
+ shouldIgnoreStartupError(error: NodeJS.ErrnoException): boolean {
+ return error.code === "EADDRINUSE"
+ && (process.argv.includes("--new-window") || !electron.app.requestSingleInstanceLock());
+ }
}
diff --git a/apps/desktop/src/services/request.ts b/apps/desktop/src/services/request.ts
new file mode 100644
index 0000000000..8b56e928d6
--- /dev/null
+++ b/apps/desktop/src/services/request.ts
@@ -0,0 +1,21 @@
+import NodeRequestProvider, { type Client, type ClientOpts } from "@triliumnext/server/src/services/request.js";
+import electron from "electron";
+
+/**
+ * Desktop variant of NodeRequestProvider that prefers Electron's `net` module
+ * for requests without an explicit proxy. Electron's net respects the system
+ * proxy configuration (PAC, environment), whereas Node's http(s) does not —
+ * so the sync client gets transparent system-proxy support out of the box.
+ *
+ * When an explicit proxy IS set (sync options), we fall through to Node's
+ * http(s) since Electron's net has no straightforward way to be configured
+ * with a custom proxy.
+ */
+export default class ElectronRequestProvider extends NodeRequestProvider {
+ protected async getClient(opts: ClientOpts): Promise<Client> {
+ if (!opts.proxy) {
+ return electron.net as unknown as Client;
+ }
+ return super.getClient(opts);
+ }
+}
diff --git a/apps/server/package.json b/apps/server/package.json
index 9b349003d5..a4928064b4 100644
--- a/apps/server/package.json
+++ b/apps/server/package.json
@@ -79,7 +79,6 @@
"csrf-csrf": "4.0.3",
"debug": "4.4.3",
"ejs": "5.0.2",
- "electron": "41.7.0",
"express": "5.2.1",
"express-http-proxy": "2.1.2",
"express-openid-connect": "3.0.0",
diff --git a/apps/server/src/services/request.ts b/apps/server/src/services/request.ts
index 96fd8d8f7c..bdc02ebbae 100644
--- a/apps/server/src/services/request.ts
+++ b/apps/server/src/services/request.ts
@@ -1,15 +1,17 @@
"use strict";
import type { ExecOpts, RequestProvider } from "@triliumnext/core";
-import { isElectron } from "./utils.js";
-import log from "./log.js";
import url from "url";
+
+import log from "./log.js";
import syncOptions from "./sync_options.js";
-// this service provides abstraction over node's HTTP/HTTPS and electron net.client APIs
-// this allows supporting system proxy
+// this service provides abstraction over node's HTTP/HTTPS modules.
+// Subclasses (e.g. apps/desktop's ElectronRequestProvider) can override
+// `getClient` to plug in alternative transports such as `electron.net`
+// (which honours the system proxy).
-interface ClientOpts {
+export interface ClientOpts {
method: string;
url: string;
protocol?: string | null;
@@ -24,13 +26,13 @@ interface ClientOpts {
type RequestEvent = "error" | "response" | "abort";
-interface Request {
+interface NetRequest {
on(event: RequestEvent, cb: (e: any) => void): void;
end(payload?: string): void;
}
-interface Client {
- request(opts: ClientOpts): Request;
+export interface Client {
+ request(opts: ClientOpts): NetRequest;
}
const HTTP = "http:",
@@ -62,12 +64,14 @@ async function getProxyAgent(opts: ClientOpts) {
return new AgentClass(opts.proxy);
}
-async function getClient(opts: ClientOpts): Promise<Client> {
- // it's not clear how to explicitly configure proxy (as opposed to system proxy),
- // so in that case, we always use node's modules
- if (isElectron && !opts.proxy) {
- return (await import("electron")).net as unknown as Client;
- } else {
+export default class NodeRequestProvider implements RequestProvider {
+
+ /**
+ * Resolves the HTTP client for a given request. The default implementation
+ * picks Node's `http` or `https` module based on the URL scheme. Subclasses
+ * may override to provide a transport that supports system proxy etc.
+ */
+ protected async getClient(opts: ClientOpts): Promise<Client> {
const { protocol } = url.parse(opts.url);
if (protocol === "http:" || protocol === "https:") {
@@ -76,12 +80,9 @@ async function getClient(opts: ClientOpts): Promise<Client> {
throw new Error(`Unrecognized protocol '${protocol}'`);
}
}
-}
-
-export default class NodeRequestProvider implements RequestProvider {
async exec<T>(opts: ExecOpts): Promise<T> {
- const client = getClient(opts);
+ const client = this.getClient(opts);
// hack for cases where electron.net does not work, but we don't want to set proxy
if (opts.proxy === "noproxy") {
@@ -189,7 +190,7 @@ export default class NodeRequestProvider implements RequestProvider {
proxy: proxyConf !== "noproxy" ? proxyConf : null
};
- const client = await getClient(opts);
+ const client = await this.getClient(opts);
const proxyAgent = await getProxyAgent(opts);
const parsedTargetUrl = url.parse(opts.url);
diff --git a/apps/server/src/www.ts b/apps/server/src/www.ts
index 87463907e6..fdd0df3162 100644
--- a/apps/server/src/www.ts
+++ b/apps/server/src/www.ts
@@ -164,16 +164,11 @@ function startHttpServer(app: Express) {
}
}
- if (utils.isElectron()) {
- import("electron").then(({ app }) => {
- if ("code" in error && error.code === "EADDRINUSE" && (process.argv.includes("--new-window") || !app.requestSingleInstanceLock())) {
- console.error(message);
- } else {
- getPlatform().crash(`Error while initializing the server: ${message}`);
- }
- });
+ const platform = getPlatform();
+ if (platform.shouldIgnoreStartupError?.(error)) {
+ console.error(message);
} else {
- getPlatform().crash(message);
+ platform.crash(`Error while initializing the server: ${message}`);
}
});
diff --git a/packages/trilium-core/src/services/platform.ts b/packages/trilium-core/src/services/platform.ts
index 3a7fcfc6b8..269a99368c 100644
--- a/packages/trilium-core/src/services/platform.ts
+++ b/packages/trilium-core/src/services/platform.ts
@@ -8,6 +8,14 @@ export interface PlatformProvider {
readonly isElectron: boolean;
readonly isMac: boolean;
readonly isWindows: boolean;
+ /**
+ * Lets a platform decide whether an HTTP-server startup error should be
+ * swallowed (logged-only) rather than treated as fatal. The desktop uses
+ * this to tolerate `EADDRINUSE` when launched with `--new-window` or as a
+ * secondary instance — the primary handles the request via Electron's
+ * `second-instance` event. Optional; absent = always fatal.
+ */
+ shouldIgnoreStartupError?(error: NodeJS.ErrnoException): boolean;
}
let platformProvider: PlatformProvider | null = null;
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index ce1c61057e..1f123c63cc 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -729,9 +729,6 @@ importers:
ejs:
specifier: 5.0.2
version: 5.0.2
- electron:
- specifier: 41.7.0
- version: 41.7.0
express:
specifier: 5.2.1
version: 5.2.1