@shiqianjiang/ceru-plugin-core 0.2.1 → 0.3.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/electron.js CHANGED
@@ -4,16 +4,18 @@ import { readFile } from 'node:fs/promises';
4
4
  import { fileURLToPath } from 'node:url';
5
5
  let cachedAssets;
6
6
  function assets() {
7
- return cachedAssets ??= Promise.all([
7
+ return (cachedAssets ??= Promise.all([
8
8
  readFile(new URL('../assets/sandbox.js', import.meta.url), 'utf8'),
9
- readFile(new URL('../assets/catalog.json', import.meta.url), 'utf8')
10
- ]);
9
+ readFile(new URL('../assets/catalog.json', import.meta.url), 'utf8'),
10
+ ]));
11
11
  }
12
12
  /** Chromium's OS sandbox executes plugin code; only JSON messages cross IPC. */
13
13
  export class ElectronPluginSandbox {
14
14
  rpc;
15
15
  event;
16
- static async prewarm() { await assets(); }
16
+ static async prewarm() {
17
+ await assets();
18
+ }
17
19
  window;
18
20
  generation = randomUUID();
19
21
  pending = new Map();
@@ -23,7 +25,7 @@ export class ElectronPluginSandbox {
23
25
  this.event = event;
24
26
  }
25
27
  async start(artifact, surfaceId) {
26
- const surface = artifact.header.manifest.modules.surfaces?.find(item => item.id === surfaceId);
28
+ const surface = artifact.header.manifest.modules.surfaces?.find((item) => item.id === surfaceId);
27
29
  const moduleId = surfaceId ? surface?.entry : artifact.header.manifest.modules.logic?.entry;
28
30
  if (!moduleId) {
29
31
  if (surfaceId)
@@ -39,29 +41,59 @@ export class ElectronPluginSandbox {
39
41
  isolatedSession.setPermissionCheckHandler(() => false);
40
42
  isolatedSession.webRequest.onBeforeRequest((details, callback) => callback({ cancel: !/^(data:|about:)/.test(details.url) }));
41
43
  const win = new BrowserWindow({
42
- show: false, width: 1040, height: 760, title: artifact.header.manifest.name,
44
+ show: false,
45
+ width: 1040,
46
+ height: 760,
47
+ title: artifact.header.manifest.name,
43
48
  webPreferences: {
44
- session: isolatedSession, sandbox: true, contextIsolation: true, nodeIntegration: false,
45
- webviewTag: false, navigateOnDragDrop: false, backgroundThrottling: false,
46
- preload: fileURLToPath(new URL('../assets/preload.cjs', import.meta.url))
47
- }
49
+ session: isolatedSession,
50
+ sandbox: true,
51
+ contextIsolation: true,
52
+ nodeIntegration: false,
53
+ webviewTag: false,
54
+ navigateOnDragDrop: false,
55
+ backgroundThrottling: false,
56
+ preload: fileURLToPath(new URL('../assets/preload.cjs', import.meta.url)),
57
+ },
48
58
  });
49
59
  this.window = win;
50
- win.on('close', event => { event.preventDefault(); win.hide(); });
60
+ win.on('close', (event) => {
61
+ event.preventDefault();
62
+ win.hide();
63
+ });
51
64
  win.webContents.setWindowOpenHandler(() => ({ action: 'deny' }));
52
- win.webContents.on('will-navigate', event => event.preventDefault());
53
- win.on('closed', () => { this.window = undefined; this.dispose(); this.event('closed', {}); });
65
+ win.webContents.on('will-navigate', (event) => event.preventDefault());
66
+ win.on('closed', () => {
67
+ this.window = undefined;
68
+ this.dispose();
69
+ this.event('closed', {});
70
+ });
54
71
  win.webContents.on('render-process-gone', () => this.dispose());
55
- const htmlScript = (source) => '<script src="data:text/javascript;base64,' + Buffer.from(source).toString('base64') + '"></script>';
56
- const html = '<!doctype html><meta charset="utf-8"><meta http-equiv="Content-Security-Policy" content="default-src \'none\'; script-src data:; style-src \'unsafe-inline\'; img-src data: blob:; connect-src \'none\'; object-src \'none\'; frame-src \'none\'; form-action \'none\'; base-uri \'none\'"><div id="plugin-root"></div>' + htmlScript(runtime) + htmlScript('globalThis.__ceruStart(' + code + ');');
72
+ const htmlScript = (source) => '<script src="data:text/javascript;base64,' +
73
+ Buffer.from(source).toString('base64') +
74
+ '"></script>';
75
+ const html = "<!doctype html><meta charset=\"utf-8\"><meta http-equiv=\"Content-Security-Policy\" content=\"default-src 'none'; script-src data:; style-src 'unsafe-inline'; img-src data: blob:; connect-src 'none'; object-src 'none'; frame-src 'none'; form-action 'none'; base-uri 'none'\"><div id=\"plugin-root\"></div>" +
76
+ htmlScript(runtime) +
77
+ htmlScript('globalThis.__ceruStart(' + code + ');');
57
78
  await new Promise((resolve, reject) => {
58
- const timer = setTimeout(() => { reject(new Error('Plugin activation timed out')); this.dispose(); }, 30000);
79
+ const timer = setTimeout(() => {
80
+ reject(new Error('Plugin activation timed out'));
81
+ this.dispose();
82
+ }, 30000);
59
83
  this.listener = (event, message) => {
60
84
  if (event.sender !== win.webContents || !message || typeof message !== 'object')
61
85
  return;
62
86
  const { type, data } = message;
63
87
  if (type === 'ready') {
64
- void this.send('init', { generation: this.generation, mode: 'production', kind: surfaceId ? 'web' : 'logic', manifest: artifact.header.manifest, resources: artifact.resources, catalog: JSON.parse(catalog), mount: { kind: 'page' } });
88
+ void this.send('init', {
89
+ generation: this.generation,
90
+ mode: 'production',
91
+ kind: surfaceId ? 'web' : 'logic',
92
+ manifest: artifact.header.manifest,
93
+ resources: artifact.resources,
94
+ catalog: JSON.parse(catalog),
95
+ mount: { kind: 'page' },
96
+ });
65
97
  return;
66
98
  }
67
99
  if (message.generation !== this.generation)
@@ -88,38 +120,78 @@ export class ElectronPluginSandbox {
88
120
  return;
89
121
  }
90
122
  if (type === 'rpc') {
91
- void this.rpc(String(data?.method), data?.data).then(value => this.send('rpc-result', { id: data.id, value }), error => this.send('rpc-result', { id: data.id, error: error instanceof Error ? error.message : 'Host request failed' })).catch(() => { });
123
+ void this.rpc(String(data?.method), data?.data)
124
+ .then((value) => this.send('rpc-result', { id: data.id, value }), (error) => this.send('rpc-result', {
125
+ id: data.id,
126
+ error: error instanceof Error ? error.message : 'Host request failed',
127
+ }))
128
+ .catch(() => { });
92
129
  return;
93
130
  }
94
131
  this.event(type, data);
95
132
  };
96
133
  ipcMain.on('ceru:runtime', this.listener);
97
- void win.loadURL('data:text/html;base64,' + Buffer.from(html).toString('base64')).catch(error => { clearTimeout(timer); reject(error); });
98
- }).catch(error => { this.dispose(); throw error; });
134
+ void win
135
+ .loadURL('data:text/html;base64,' + Buffer.from(html).toString('base64'))
136
+ .catch((error) => {
137
+ clearTimeout(timer);
138
+ reject(error);
139
+ });
140
+ }).catch((error) => {
141
+ this.dispose();
142
+ throw error;
143
+ });
99
144
  }
100
145
  send(type, data) {
101
146
  if (!this.window || this.window.isDestroyed())
102
147
  return Promise.reject(new Error('Plugin is stopped'));
103
- return this.window.webContents.executeJavaScript('window.postMessage(' + JSON.stringify({ type, data, generation: this.generation }) + ', "*")').then(() => undefined);
148
+ return this.window.webContents
149
+ .executeJavaScript('window.postMessage(' +
150
+ JSON.stringify({ type, data, generation: this.generation }) +
151
+ ', "*")')
152
+ .then(() => undefined);
153
+ }
154
+ show() {
155
+ if (this.window && !this.window.isDestroyed()) {
156
+ this.window.show();
157
+ this.window.focus();
158
+ }
104
159
  }
105
- show() { if (this.window && !this.window.isDestroyed()) {
106
- this.window.show();
107
- this.window.focus();
108
- } }
109
160
  invoke(kind, target, method, args, signal) {
110
161
  const id = randomUUID();
111
162
  return new Promise((resolve, reject) => {
112
- const cancel = () => { this.pending.delete(id); void this.send('cancel', { id }).catch(() => { }); reject(new Error('Plugin operation cancelled')); };
163
+ const cancel = () => {
164
+ this.pending.delete(id);
165
+ void this.send('cancel', { id }).catch(() => { });
166
+ reject(new Error('Plugin operation cancelled'));
167
+ };
113
168
  const timer = setTimeout(cancel, 120000);
114
- const done = () => { clearTimeout(timer); signal?.removeEventListener('abort', cancel); };
115
- this.pending.set(id, { timer, resolve: value => { done(); resolve(value); }, reject: error => { done(); reject(error); } });
169
+ const done = () => {
170
+ clearTimeout(timer);
171
+ signal?.removeEventListener('abort', cancel);
172
+ };
173
+ this.pending.set(id, {
174
+ timer,
175
+ resolve: (value) => {
176
+ done();
177
+ resolve(value);
178
+ },
179
+ reject: (error) => {
180
+ done();
181
+ reject(error);
182
+ },
183
+ });
116
184
  signal?.addEventListener('abort', cancel, { once: true });
117
185
  if (signal?.aborted) {
118
186
  done();
119
187
  cancel();
120
188
  return;
121
189
  }
122
- void this.send('invoke', { id, kind, target, method, args }).catch(error => { this.pending.delete(id); done(); reject(error); });
190
+ void this.send('invoke', { id, kind, target, method, args }).catch((error) => {
191
+ this.pending.delete(id);
192
+ done();
193
+ reject(error);
194
+ });
123
195
  });
124
196
  }
125
197
  dispose() {
@@ -0,0 +1,63 @@
1
+ import type { Artifact } from '@shiqianjiang/ceru-plugin-issuer';
2
+ import type { GuestInfo } from '@shiqianjiang/ceru-plugin-sdk';
3
+ export interface GuestServices {
4
+ root: string;
5
+ artifact: Artifact;
6
+ approve(info: {
7
+ name: string;
8
+ version: string;
9
+ author?: string;
10
+ }): Promise<boolean>;
11
+ authorize(info: GuestInfo, permission: 'network' | 'network.private'): Promise<boolean>;
12
+ request(input: any, privateAllowed: () => boolean, signal: AbortSignal): Promise<any>;
13
+ changed(): void;
14
+ event(guest: GuestInfo, type: string, data: any): void;
15
+ }
16
+ export declare function readGuestInfo(script: string, fallback?: string): {
17
+ name: string;
18
+ version: string;
19
+ author: string | undefined;
20
+ description: string | undefined;
21
+ homepage: string | undefined;
22
+ };
23
+ /** Generic one-level Guest management. Platform semantics belong to the parent's bootstrap. */
24
+ export declare class GuestStore {
25
+ private services;
26
+ private saved;
27
+ private runtimes;
28
+ private starting;
29
+ private errors;
30
+ private requests;
31
+ private requestIds;
32
+ private grantPrompts;
33
+ private writes;
34
+ private selection;
35
+ private disposed;
36
+ private initialized?;
37
+ constructor(services: GuestServices);
38
+ initialize(): Promise<void>;
39
+ private adapter;
40
+ list(): GuestInfo[];
41
+ private info;
42
+ private find;
43
+ private script;
44
+ /** Only for a user-initiated Host export, never exposed through the parent's RPC. */
45
+ exportSelected(adapterId: string): Promise<{
46
+ script: string;
47
+ info: GuestInfo;
48
+ }>;
49
+ private persist;
50
+ install(adapterId: string, script: string, fallback?: string): Promise<GuestInfo | null>;
51
+ private grant;
52
+ private rpc;
53
+ private start;
54
+ select(id: string | null): Promise<void>;
55
+ private applySelection;
56
+ remove(id: string): Promise<void>;
57
+ replace(id: string, script: string): Promise<GuestInfo>;
58
+ permissions(id: string): string[];
59
+ setPermissions(id: string, keys: string[]): Promise<void>;
60
+ invoke(id: string, method: string, input: any): Promise<any>;
61
+ private stop;
62
+ dispose(): void;
63
+ }
@@ -0,0 +1,402 @@
1
+ import { mkdir, readFile, writeFile, rename, unlink } from 'node:fs/promises';
2
+ import { join } from 'node:path';
3
+ import { createHash, randomUUID } from 'node:crypto';
4
+ import { NodePluginSandbox } from './node.js';
5
+ const digest = (script) => createHash('sha256').update(script).digest('hex');
6
+ export function readGuestInfo(script, fallback = '自定义音源') {
7
+ if (Buffer.byteLength(script) > 2 * 1024 * 1024)
8
+ throw new Error('子插件超过 2 MiB');
9
+ const comment = /^\s*\/\*[\s\S]*?\*\//.exec(script)?.[0] ?? '';
10
+ const field = (key) => new RegExp('@' + key + '[ \t]+([^\r\n*]+)').exec(comment)?.[1]?.trim().slice(0, 500);
11
+ return {
12
+ name: field('name') || fallback,
13
+ version: field('version') || '0.0.0',
14
+ author: field('author'),
15
+ description: field('description'),
16
+ homepage: field('homepage'),
17
+ };
18
+ }
19
+ /** Generic one-level Guest management. Platform semantics belong to the parent's bootstrap. */
20
+ export class GuestStore {
21
+ services;
22
+ saved = [];
23
+ runtimes = new Map();
24
+ starting = new Map();
25
+ errors = new Map();
26
+ requests = new Map();
27
+ requestIds = new Map();
28
+ grantPrompts = new Map();
29
+ writes = Promise.resolve();
30
+ selection = Promise.resolve();
31
+ disposed = false;
32
+ initialized;
33
+ constructor(services) {
34
+ this.services = services;
35
+ }
36
+ initialize() {
37
+ return (this.initialized ??= (async () => {
38
+ await mkdir(this.services.root, { recursive: true });
39
+ try {
40
+ const value = JSON.parse(await readFile(join(this.services.root, 'index.json'), 'utf8'));
41
+ if (!Array.isArray(value) || value.length > 64)
42
+ throw new Error('子插件索引损坏');
43
+ this.saved = value.filter((item) => /^[a-f0-9]{32}$/.test(item.id) &&
44
+ typeof item.adapterId === 'string' &&
45
+ Array.isArray(item.providers) &&
46
+ Array.isArray(item.grants));
47
+ }
48
+ catch (error) {
49
+ if (error.code !== 'ENOENT')
50
+ throw error;
51
+ }
52
+ })());
53
+ }
54
+ adapter(id) {
55
+ const manifest = this.services.artifact.header.manifest;
56
+ const adapter = manifest.contributes?.guestAdapters?.find((item) => item.id === id);
57
+ if (!adapter || manifest.guestPolicy?.maxDepth !== 1)
58
+ throw new Error('兼容环境未声明此格式');
59
+ return adapter;
60
+ }
61
+ list() {
62
+ return this.saved.map((item) => this.info(item));
63
+ }
64
+ info(item) {
65
+ return {
66
+ id: item.id,
67
+ adapterId: item.adapterId,
68
+ name: item.name,
69
+ version: item.version,
70
+ author: item.author,
71
+ providers: structuredClone(item.providers),
72
+ selected: item.selected,
73
+ state: this.errors.has(item.id) ? 'error' : this.runtimes.has(item.id) ? 'ready' : 'stopped',
74
+ ...(this.errors.has(item.id) ? { error: this.errors.get(item.id) } : {}),
75
+ };
76
+ }
77
+ find(id) {
78
+ const item = this.saved.find((item) => item.id === id);
79
+ if (!item)
80
+ throw new Error('子插件不存在');
81
+ return item;
82
+ }
83
+ async script(item) {
84
+ const script = await readFile(join(this.services.root, item.id + '.js'), 'utf8');
85
+ if (digest(script) !== item.digest)
86
+ throw new Error('子插件文件校验失败,请重新导入');
87
+ return script;
88
+ }
89
+ /** Only for a user-initiated Host export, never exposed through the parent's RPC. */
90
+ async exportSelected(adapterId) {
91
+ const item = this.saved.find((item) => item.adapterId === adapterId && item.selected);
92
+ if (!item)
93
+ throw new Error('请先使用一个子音源再分享');
94
+ return { script: await this.script(item), info: this.info(item) };
95
+ }
96
+ async persist() {
97
+ const data = JSON.stringify(this.saved, null, 2);
98
+ const write = this.writes.then(async () => {
99
+ const temporary = join(this.services.root, 'index.' + randomUUID() + '.tmp');
100
+ await writeFile(temporary, data, { mode: 0o600 });
101
+ await rename(temporary, join(this.services.root, 'index.json'));
102
+ });
103
+ this.writes = write.catch(() => { });
104
+ await write;
105
+ }
106
+ async install(adapterId, script, fallback) {
107
+ await this.initialize();
108
+ this.adapter(adapterId);
109
+ if (this.disposed)
110
+ throw new Error('兼容环境已停止');
111
+ const metadata = readGuestInfo(script, fallback);
112
+ if (this.saved.some((item) => item.digest === digest(script)))
113
+ throw new Error('这个子插件已经安装');
114
+ if (this.saved.length >= 64)
115
+ throw new Error('子插件数量已达上限');
116
+ if (!(await this.services.approve(metadata)))
117
+ return null;
118
+ if (this.disposed)
119
+ throw new Error('兼容环境已停止');
120
+ const item = {
121
+ ...metadata,
122
+ id: randomUUID().replaceAll('-', ''),
123
+ adapterId,
124
+ digest: digest(script),
125
+ selected: false,
126
+ grants: [],
127
+ providers: [],
128
+ };
129
+ this.saved.push(item);
130
+ try {
131
+ await writeFile(join(this.services.root, item.id + '.js'), script, { mode: 0o600 });
132
+ await this.persist();
133
+ this.services.changed();
134
+ return this.info(item);
135
+ }
136
+ catch (error) {
137
+ this.saved = this.saved.filter((entry) => entry !== item);
138
+ this.stop(item.id);
139
+ this.errors.delete(item.id);
140
+ await unlink(join(this.services.root, item.id + '.js')).catch(() => { });
141
+ await this.persist();
142
+ throw error;
143
+ }
144
+ }
145
+ async grant(item, permission) {
146
+ const capability = permission === 'network' ? 'network.request' : 'network.private';
147
+ if (!this.services.artifact.header.manifest.guestPolicy?.allowedCapabilities.includes(capability))
148
+ throw new Error('兼容环境未声明该子插件能力');
149
+ if (item.grants.includes(permission))
150
+ return true;
151
+ if (item.grants.includes('deny:' + permission))
152
+ return false;
153
+ const key = item.id + ':' + permission;
154
+ let prompt = this.grantPrompts.get(key);
155
+ if (!prompt) {
156
+ prompt = this.services
157
+ .authorize(this.info(item), permission)
158
+ .then(async (allowed) => {
159
+ if (this.disposed || !this.saved.includes(item))
160
+ return false;
161
+ item.grants.push(allowed ? permission : 'deny:' + permission);
162
+ await this.persist();
163
+ return allowed;
164
+ })
165
+ .finally(() => this.grantPrompts.delete(key));
166
+ this.grantPrompts.set(key, prompt);
167
+ }
168
+ return prompt;
169
+ }
170
+ async rpc(item, method, input) {
171
+ if (this.disposed || !this.saved.includes(item))
172
+ throw new Error('子插件已停止');
173
+ if (method === 'guest.http.request') {
174
+ if (!(await this.grant(item, 'network')))
175
+ throw new Error('此子插件没有网络权限,请在插件权限中允许后重试');
176
+ const controller = new AbortController();
177
+ const key = item.id + ':' + String(input.requestId ?? randomUUID());
178
+ if (this.requestIds.has(key))
179
+ throw new Error('重复的子插件请求 ID');
180
+ const requests = this.requests.get(item.id) ?? new Set();
181
+ if (requests.size >= 16)
182
+ throw new Error('子插件并发请求过多');
183
+ requests.add(controller);
184
+ this.requests.set(item.id, requests);
185
+ this.requestIds.set(key, controller);
186
+ try {
187
+ try {
188
+ return await this.services.request(input, () => item.grants.includes('network.private'), controller.signal);
189
+ }
190
+ catch (error) {
191
+ if (error instanceof Error &&
192
+ /局域网/.test(error.message) &&
193
+ (await this.grant(item, 'network.private')))
194
+ return this.services.request(input, () => item.grants.includes('network.private'), controller.signal);
195
+ throw error;
196
+ }
197
+ }
198
+ finally {
199
+ requests.delete(controller);
200
+ this.requestIds.delete(key);
201
+ }
202
+ }
203
+ if (method === 'guest.http.cancel') {
204
+ this.requestIds.get(item.id + ':' + String(input.requestId))?.abort();
205
+ return null;
206
+ }
207
+ if (method === 'operations.cancel') {
208
+ for (const request of this.requests.get(item.id) ?? [])
209
+ request.abort();
210
+ return null;
211
+ }
212
+ if (method === 'guest.notify') {
213
+ this.services.event(this.info(item), 'notify', input);
214
+ return null;
215
+ }
216
+ throw new Error('子插件没有此宿主能力: ' + method);
217
+ }
218
+ async start(item) {
219
+ const pending = this.starting.get(item.id);
220
+ if (pending)
221
+ return pending;
222
+ const existing = this.runtimes.get(item.id);
223
+ if (existing)
224
+ return existing;
225
+ const job = (async () => {
226
+ const adapter = this.adapter(item.adapterId);
227
+ const script = await this.script(item);
228
+ let ready = false;
229
+ const runtime = new NodePluginSandbox((method, input) => this.rpc(item, method, input), (type, data) => {
230
+ if (type === 'guest-metadata') {
231
+ if (!Array.isArray(data?.providers) || data.providers.length > 32)
232
+ throw new Error('子插件没有有效的平台声明');
233
+ for (const provider of data.providers) {
234
+ if (!provider ||
235
+ typeof provider.id !== 'string' ||
236
+ !/^[\w.-]{1,64}$/.test(provider.id) ||
237
+ typeof provider.name !== 'string' ||
238
+ !Array.isArray(provider.qualities) ||
239
+ provider.qualities.length > 64 ||
240
+ provider.qualities.some((q) => typeof q !== 'string' || q.length > 64) ||
241
+ !Array.isArray(provider.protocols) ||
242
+ provider.protocols.some((p) => !adapter.projectableProtocols.includes(p)))
243
+ throw new Error('子插件能力超出兼容环境声明');
244
+ }
245
+ item.providers = data.providers;
246
+ ready = true;
247
+ }
248
+ else if (type === 'closed') {
249
+ if (this.runtimes.get(item.id) === runtime) {
250
+ this.runtimes.delete(item.id);
251
+ if (data?.reason)
252
+ this.errors.set(item.id, String(data.reason));
253
+ this.services.changed();
254
+ }
255
+ }
256
+ else if (type === 'log' || type === 'notify')
257
+ this.services.event(this.info(item), type, data);
258
+ });
259
+ this.runtimes.set(item.id, runtime);
260
+ try {
261
+ await runtime.start({
262
+ ...this.services.artifact,
263
+ header: {
264
+ ...this.services.artifact.header,
265
+ manifest: {
266
+ ...this.services.artifact.header.manifest,
267
+ modules: { logic: { entry: adapter.bootstrap } },
268
+ },
269
+ },
270
+ }, {
271
+ id: item.id,
272
+ script,
273
+ info: {
274
+ name: item.name,
275
+ version: item.version,
276
+ author: item.author,
277
+ description: item.description,
278
+ homepage: item.homepage,
279
+ },
280
+ });
281
+ if (!ready)
282
+ throw new Error('子插件未完成初始化');
283
+ if (this.disposed || !this.saved.includes(item) || this.runtimes.get(item.id) !== runtime)
284
+ throw new Error('兼容环境已停止');
285
+ this.errors.delete(item.id);
286
+ return runtime;
287
+ }
288
+ catch (error) {
289
+ this.stop(item.id);
290
+ this.errors.set(item.id, error instanceof Error ? error.message : String(error));
291
+ throw error;
292
+ }
293
+ })().finally(() => this.starting.delete(item.id));
294
+ this.starting.set(item.id, job);
295
+ return job;
296
+ }
297
+ async select(id) {
298
+ const next = this.selection.catch(() => { }).then(() => this.applySelection(id));
299
+ this.selection = next;
300
+ return next;
301
+ }
302
+ async applySelection(id) {
303
+ if (this.disposed)
304
+ throw new Error('兼容环境已停止');
305
+ if (id === null) {
306
+ for (const item of this.saved) {
307
+ item.selected = false;
308
+ this.stop(item.id);
309
+ }
310
+ await this.persist();
311
+ this.services.changed();
312
+ return;
313
+ }
314
+ const item = this.find(id);
315
+ const previous = this.saved.find((item) => item.selected);
316
+ for (const entry of this.saved)
317
+ if (entry.id !== id)
318
+ this.stop(entry.id);
319
+ try {
320
+ await this.start(item);
321
+ }
322
+ catch (error) {
323
+ if (previous && previous !== item && !this.disposed)
324
+ await this.start(previous).catch(() => { });
325
+ this.services.changed();
326
+ throw error;
327
+ }
328
+ for (const entry of this.saved)
329
+ entry.selected = entry.id === id;
330
+ await this.persist();
331
+ this.services.changed();
332
+ }
333
+ async remove(id) {
334
+ this.find(id);
335
+ this.stop(id);
336
+ this.saved = this.saved.filter((item) => item.id !== id);
337
+ await this.persist();
338
+ await unlink(join(this.services.root, id + '.js')).catch(() => { });
339
+ this.services.changed();
340
+ }
341
+ async replace(id, script) {
342
+ const item = this.find(id);
343
+ const metadata = readGuestInfo(script);
344
+ if (metadata.name !== item.name)
345
+ throw new Error('更新脚本名称与原子插件不一致');
346
+ const old = structuredClone(item);
347
+ const file = join(this.services.root, id + '.js');
348
+ const previous = await readFile(file, 'utf8');
349
+ this.stop(id);
350
+ try {
351
+ Object.assign(item, metadata, { digest: digest(script), providers: [] });
352
+ await writeFile(file, script, { mode: 0o600 });
353
+ if (item.selected)
354
+ await this.start(item);
355
+ await this.persist();
356
+ this.services.changed();
357
+ return this.info(item);
358
+ }
359
+ catch (error) {
360
+ this.stop(id);
361
+ Object.assign(item, old);
362
+ await writeFile(file, previous, { mode: 0o600 });
363
+ if (old.selected)
364
+ await this.start(item).catch(() => { });
365
+ await this.persist();
366
+ this.services.changed();
367
+ throw error;
368
+ }
369
+ }
370
+ permissions(id) {
371
+ return this.find(id).grants.filter((key) => !key.startsWith('deny:'));
372
+ }
373
+ async setPermissions(id, keys) {
374
+ if (!Array.isArray(keys) || keys.some((key) => !['network', 'network.private'].includes(key)))
375
+ throw new Error('无效的子插件权限');
376
+ const item = this.find(id);
377
+ item.grants = ['network', 'network.private'].map((key) => keys.includes(key) ? key : 'deny:' + key);
378
+ this.stop(id);
379
+ await this.persist();
380
+ this.services.changed();
381
+ }
382
+ async invoke(id, method, input) {
383
+ const item = this.find(id);
384
+ if (!item.selected)
385
+ throw new Error('请先选择使用此子插件');
386
+ if (!/^[a-zA-Z][\w.-]{0,127}$/.test(method))
387
+ throw new Error('无效的子插件方法');
388
+ return (await this.start(item)).invoke('guest', id, method, [input]);
389
+ }
390
+ stop(id) {
391
+ this.runtimes.get(id)?.dispose();
392
+ this.runtimes.delete(id);
393
+ for (const request of this.requests.get(id) ?? [])
394
+ request.abort();
395
+ this.requests.delete(id);
396
+ }
397
+ dispose() {
398
+ this.disposed = true;
399
+ for (const id of this.runtimes.keys())
400
+ this.stop(id);
401
+ }
402
+ }