feat: improve electron sandbox (#14156)

This commit is contained in:
DarkSky
2025-12-27 03:23:28 +08:00
committed by GitHub
parent 3fe8923fc3
commit 4eed92cebf
32 changed files with 570 additions and 213 deletions
@@ -10,6 +10,7 @@ import { z } from 'zod';
import {
AFFINE_API_CHANNEL_NAME,
AFFINE_EVENT_CHANNEL_NAME,
AFFINE_EVENT_SUBSCRIBE_CHANNEL_NAME,
type ExposedMeta,
type HelperToRenderer,
type RendererToHelper,
@@ -83,6 +84,33 @@ function getMainAPIs() {
// channel -> callback[]
const listenersMap = new Map<string, ((...args: any[]) => void)[]>();
const subscribeCounts = new Map<string, number>();
const subscribe = (channel: string) => {
const count = (subscribeCounts.get(channel) ?? 0) + 1;
subscribeCounts.set(channel, count);
if (count === 1) {
ipcRenderer.send(
AFFINE_EVENT_SUBSCRIBE_CHANNEL_NAME,
'subscribe',
channel
);
}
};
const unsubscribe = (channel: string) => {
const count = (subscribeCounts.get(channel) ?? 0) - 1;
if (count <= 0) {
subscribeCounts.delete(channel);
ipcRenderer.send(
AFFINE_EVENT_SUBSCRIBE_CHANNEL_NAME,
'unsubscribe',
channel
);
} else {
subscribeCounts.set(channel, count);
}
};
ipcRenderer.on(AFFINE_EVENT_CHANNEL_NAME, (_event, channel, ...args) => {
if (typeof channel !== 'string') {
@@ -108,12 +136,20 @@ function getMainAPIs() {
...(listenersMap.get(channel) ?? []),
callback,
]);
subscribe(channel);
return () => {
const listeners = listenersMap.get(channel) ?? [];
const index = listeners.indexOf(callback);
if (index !== -1) {
listeners.splice(index, 1);
if (index === -1) {
return;
}
listeners.splice(index, 1);
unsubscribe(channel);
if (listeners.length === 0) {
listenersMap.delete(channel);
} else {
listenersMap.set(channel, listeners);
}
};
},