@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/index.js CHANGED
@@ -48,7 +48,11 @@ export class PluginCore {
48
48
  };
49
49
  }
50
50
  static async load(input, options) {
51
- const bytes = typeof input === 'string' ? new TextEncoder().encode(input) : input instanceof ArrayBuffer ? new Uint8Array(input) : input;
51
+ const bytes = typeof input === 'string'
52
+ ? new TextEncoder().encode(input)
53
+ : input instanceof ArrayBuffer
54
+ ? new Uint8Array(input)
55
+ : input;
52
56
  const artifact = readArtifact(bytes);
53
57
  const core = new PluginCore(artifact, options);
54
58
  try {
@@ -65,42 +69,114 @@ export class PluginCore {
65
69
  context() {
66
70
  const context = {
67
71
  plugin: { id: this.manifest.id, version: this.manifest.version, manifest: this.manifest },
68
- host: { apiVersion: '2.0.0', libraries: { lodash: 'host', icons: 'host', assets: 'host' }, mode: 'production' },
69
- modules: { require: (name) => { throw new Error(`Host module ${name} must be supplied by the Host`); } },
72
+ host: {
73
+ apiVersion: '2.0.0',
74
+ libraries: { lodash: 'host', icons: 'host', assets: 'host' },
75
+ mode: 'production',
76
+ },
77
+ modules: {
78
+ require: (name) => {
79
+ throw new Error(`Host module ${name} must be supplied by the Host`);
80
+ },
81
+ },
70
82
  utils: { lodash: {} },
71
- icons: { list: () => [], url: async () => { throw new Error('Icon service is not connected'); } },
72
- assets: { list: () => [], url: async () => { throw new Error('Asset service is not connected'); } },
83
+ icons: {
84
+ list: () => [],
85
+ url: async () => {
86
+ throw new Error('Icon service is not connected');
87
+ },
88
+ },
89
+ assets: {
90
+ list: () => [],
91
+ url: async () => {
92
+ throw new Error('Asset service is not connected');
93
+ },
94
+ },
73
95
  config: { get: async () => this.config },
74
- providers: { register: (id, implementation) => this.registerProvider(id, implementation) },
75
- actions: { register: (id, handler) => this.registerAction(id, handler) },
76
- playlistImporters: { register: (id, implementation) => this.registerImporter(id, implementation) },
77
- lyricConverters: { register: (id, implementation) => {
78
- if (!this.manifest.contributes?.lyricConverters?.some(item => item.id === id))
96
+ providers: {
97
+ register: (id, implementation) => this.registerProvider(id, implementation),
98
+ },
99
+ actions: {
100
+ register: (id, handler) => this.registerAction(id, handler),
101
+ },
102
+ playlistImporters: {
103
+ register: (id, implementation) => this.registerImporter(id, implementation),
104
+ },
105
+ lyricConverters: {
106
+ register: (id, implementation) => {
107
+ if (!this.manifest.contributes?.lyricConverters?.some((item) => item.id === id))
79
108
  throw new Error('Undeclared lyric converter');
80
109
  this.converters.set(id, implementation);
81
110
  return () => this.converters.delete(id);
82
- } },
83
- effects: { add: (dispose) => { this.disposers.push(dispose); } },
111
+ },
112
+ },
113
+ effects: {
114
+ add: (dispose) => {
115
+ this.disposers.push(dispose);
116
+ },
117
+ },
84
118
  http: {
85
119
  request: (request) => this.request(request),
86
120
  create: (defaults = {}) => ({
87
121
  request: (url, input = {}) => this.request({ ...input, ...defaults, url: new URL(url, defaults.baseURL).href }),
88
122
  }),
89
123
  },
90
- permissions: { getGranted: async () => [], query: async () => ({ status: 'prompt' }), request: async () => ({ status: 'prompt' }), requestGroup: async () => ({ status: 'prompt', grants: [] }) },
124
+ permissions: {
125
+ getGranted: async () => [],
126
+ query: async () => ({ status: 'prompt' }),
127
+ request: async () => ({ status: 'prompt' }),
128
+ requestGroup: async () => ({ status: 'prompt', grants: [] }),
129
+ },
91
130
  playback: { failure: (error) => ({ ok: false, error }) },
92
- ui: { toast: async (message) => this.options.host.onNotice?.({ type: 'toast', data: message }), notify: async (message) => this.options.host.onNotice?.({ type: 'notify', data: message }) },
93
- log: { debug: () => undefined, info: () => undefined, warn: () => undefined, error: () => undefined },
131
+ ui: {
132
+ toast: async (message) => this.options.host.onNotice?.({ type: 'toast', data: message }),
133
+ notify: async (message) => this.options.host.onNotice?.({ type: 'notify', data: message }),
134
+ },
135
+ log: {
136
+ debug: () => undefined,
137
+ info: () => undefined,
138
+ warn: () => undefined,
139
+ error: () => undefined,
140
+ },
94
141
  };
95
142
  const services = this.options.host.services ?? {};
96
143
  for (const [key, value] of Object.entries(services)) {
97
- if (['plugin', 'providers', 'actions', 'playlistImporters', 'lyricConverters', 'effects'].includes(key))
144
+ if ([
145
+ 'plugin',
146
+ 'providers',
147
+ 'actions',
148
+ 'playlistImporters',
149
+ 'lyricConverters',
150
+ 'effects',
151
+ ].includes(key))
98
152
  throw new Error('Host cannot override Core registry: ' + key);
99
153
  context[key] = value;
100
154
  }
101
- for (const name of ['library', 'account', 'player', 'queue', 'downloads', 'files', 'clipboard', 'settings', 'window', 'sharing', 'rooms', 'ai', 'tasks', 'sockets', 'events', 'guests', 'storage']) {
155
+ for (const name of [
156
+ 'library',
157
+ 'account',
158
+ 'player',
159
+ 'queue',
160
+ 'downloads',
161
+ 'files',
162
+ 'clipboard',
163
+ 'settings',
164
+ 'window',
165
+ 'sharing',
166
+ 'rooms',
167
+ 'ai',
168
+ 'tasks',
169
+ 'sockets',
170
+ 'events',
171
+ 'guests',
172
+ 'storage',
173
+ ]) {
102
174
  if (!context[name])
103
- context[name] = new Proxy({}, { get: () => { throw new Error('Host service is not connected: ' + name); } });
175
+ context[name] = new Proxy({}, {
176
+ get: () => {
177
+ throw new Error('Host service is not connected: ' + name);
178
+ },
179
+ });
104
180
  }
105
181
  if (!services.http)
106
182
  context.http.create = (defaults) => createHttpClient(context, defaults);
@@ -133,7 +209,7 @@ export class PluginCore {
133
209
  async request(input) {
134
210
  if (!this.options.host.request)
135
211
  throw new Error('Host HTTP service is not connected');
136
- const declaration = this.manifest.permissions?.find(item => item.key === input.permissionKey && item.name === 'network.request');
212
+ const declaration = this.manifest.permissions?.find((item) => item.key === input.permissionKey && item.name === 'network.request');
137
213
  if (!declaration)
138
214
  throw new Error('Network permission is not declared');
139
215
  const permissions = this.options.host.services?.permissions;
@@ -142,7 +218,21 @@ export class PluginCore {
142
218
  return this.options.host.request({ ...input, operation: operationOrDefault(input.operation) });
143
219
  }
144
220
  async invokeProvider(providerId, method, args = [], operation) {
145
- const arities = { 'tracks.search': 1, 'tracks.resolve': 2, 'tracks.lyrics': 1, 'tracks.artwork': 1, 'tracks.suggest': 1, 'tracks.hotSearch': 0, 'playlists.search': 1, 'playlists.categories': 0, 'playlists.list': 2, 'playlists.get': 2, 'charts.list': 0, 'charts.getTracks': 2, 'sharing.describe': 2 };
221
+ const arities = {
222
+ 'tracks.search': 1,
223
+ 'tracks.resolve': 2,
224
+ 'tracks.lyrics': 1,
225
+ 'tracks.artwork': 1,
226
+ 'tracks.suggest': 1,
227
+ 'tracks.hotSearch': 0,
228
+ 'playlists.search': 1,
229
+ 'playlists.categories': 0,
230
+ 'playlists.list': 2,
231
+ 'playlists.get': 2,
232
+ 'charts.list': 0,
233
+ 'charts.getTracks': 2,
234
+ 'sharing.describe': 2,
235
+ };
146
236
  const arity = arities[method];
147
237
  if (arity === undefined || !Array.isArray(args) || args.length > arity)
148
238
  throw new Error(`Invalid ${method} arguments: expected ${arity ?? 'a supported method'}`);
@@ -163,7 +253,15 @@ export class PluginCore {
163
253
  assertResolveResult(result);
164
254
  else if (method === 'tracks.lyrics' || method === 'lyrics')
165
255
  assertLyricsDocument(result);
166
- else if (['tracks.search', 'playlists.search', 'playlists.categories', 'playlists.list', 'playlists.get', 'charts.list', 'charts.getTracks'].includes(method))
256
+ else if ([
257
+ 'tracks.search',
258
+ 'playlists.search',
259
+ 'playlists.categories',
260
+ 'playlists.list',
261
+ 'playlists.get',
262
+ 'charts.list',
263
+ 'charts.getTracks',
264
+ ].includes(method))
167
265
  assertContentPage(result);
168
266
  return result;
169
267
  }
@@ -180,12 +278,15 @@ export class PluginCore {
180
278
  throw new Error(`Playlist importer ${id} is not registered`);
181
279
  const result = await importer.getTracks({ value, cursor, limit }, operationOrDefault(operation));
182
280
  assertContentPage(result);
183
- if (result.items.some(item => item.ref.kind !== 'track'))
281
+ if (result.items.some((item) => item.ref.kind !== 'track'))
184
282
  throw new Error('Importers must return tracks');
185
283
  return result;
186
284
  }
187
285
  async dispose() {
188
- await Promise.allSettled(this.disposers.splice(0).reverse().map(dispose => Promise.resolve().then(dispose)));
286
+ await Promise.allSettled(this.disposers
287
+ .splice(0)
288
+ .reverse()
289
+ .map((dispose) => Promise.resolve().then(dispose)));
189
290
  this.providers.clear();
190
291
  this.actions.clear();
191
292
  this.importers.clear();
@@ -197,12 +298,18 @@ export class PluginCore {
197
298
  throw new Error('Lyric converter unavailable');
198
299
  if (method === 'export')
199
300
  assertLyricsDocument(request.document);
200
- else if (typeof request.text !== 'string' || request.text.length > 2 * 1024 * 1024)
301
+ else if (typeof request.text !== 'string' ||
302
+ request.text.length > 2 * 1024 * 1024)
201
303
  throw new Error('Invalid lyric input');
202
304
  const result = await converter[method](request, operationOrDefault(operation));
203
305
  if (method === 'parse')
204
306
  assertLyricsDocument(result);
205
- else if (!result || !['lrc', 'enhanced-lrc', 'yrc'].includes(result.format) || result.format !== request.format || typeof result.text !== 'string' || result.text.length > 2 * 1024 * 1024 || result.extension !== (result.format === 'enhanced-lrc' ? 'lrc' : result.format))
307
+ else if (!result ||
308
+ !['lrc', 'enhanced-lrc', 'yrc'].includes(result.format) ||
309
+ result.format !== request.format ||
310
+ typeof result.text !== 'string' ||
311
+ result.text.length > 2 * 1024 * 1024 ||
312
+ result.extension !== (result.format === 'enhanced-lrc' ? 'lrc' : result.format))
206
313
  throw new Error('Invalid exported lyric text');
207
314
  return result;
208
315
  }
@@ -218,7 +325,11 @@ export class PluginCore {
218
325
  }
219
326
  }
220
327
  export function readPluginArtifact(input) {
221
- const bytes = typeof input === 'string' ? new TextEncoder().encode(input) : input instanceof ArrayBuffer ? new Uint8Array(input) : input;
328
+ const bytes = typeof input === 'string'
329
+ ? new TextEncoder().encode(input)
330
+ : input instanceof ArrayBuffer
331
+ ? new Uint8Array(input)
332
+ : input;
222
333
  const artifact = readArtifact(bytes);
223
334
  return { header: artifact.header, artifact };
224
335
  }
package/dist/network.js CHANGED
@@ -9,23 +9,32 @@ export function isPrivateAddress(address) {
9
9
  const tail = value.slice(7);
10
10
  if (tail.includes('.'))
11
11
  return isPrivateAddress(tail);
12
- const words = tail.split(':').map(part => parseInt(part, 16));
12
+ const words = tail.split(':').map((part) => parseInt(part, 16));
13
13
  return isPrivateAddress([words[0] >> 8, words[0] & 255, words[1] >> 8, words[1] & 255].join('.'));
14
14
  }
15
15
  if (value.includes(':'))
16
16
  return !/^[23][0-9a-f]{3}:/.test(value);
17
17
  const [a, b] = value.split('.').map(Number);
18
- return a === 0 || a === 10 || a === 127 || a >= 224 || (a === 169 && b === 254) || (a === 172 && b >= 16 && b <= 31) || (a === 192 && b === 168) || (a === 100 && b >= 64 && b <= 127);
18
+ return (a === 0 ||
19
+ a === 10 ||
20
+ a === 127 ||
21
+ a >= 224 ||
22
+ (a === 169 && b === 254) ||
23
+ (a === 172 && b >= 16 && b <= 31) ||
24
+ (a === 192 && b === 168) ||
25
+ (a === 100 && b >= 64 && b <= 127));
19
26
  }
20
27
  export async function requestNetwork(input, privateAllowed, signal, redirects = 0) {
21
28
  const url = new URL(input.url);
22
29
  if (!['http:', 'https:'].includes(url.protocol) || url.username || url.password)
23
30
  throw new Error('只支持 HTTP/HTTPS 请求');
24
31
  const hostname = url.hostname.replace(/^\[|\]$/g, '');
25
- const addresses = isIP(hostname) ? [{ address: hostname, family: isIP(hostname) }] : await lookup(hostname, { all: true });
32
+ const addresses = isIP(hostname)
33
+ ? [{ address: hostname, family: isIP(hostname) }]
34
+ : await lookup(hostname, { all: true });
26
35
  if (!addresses.length)
27
36
  throw new Error('无法解析服务器地址');
28
- if (addresses.some(item => isPrivateAddress(item.address)) && !privateAllowed())
37
+ if (addresses.some((item) => isPrivateAddress(item.address)) && !privateAllowed())
29
38
  throw new Error('请先授予局域网访问权限');
30
39
  const chosen = addresses[0];
31
40
  const pin = ((_hostname, options, callback) => options?.all ? callback(null, [chosen]) : callback(null, chosen.address, chosen.family));
@@ -40,7 +49,22 @@ export async function requestNetwork(input, privateAllowed, signal, redirects =
40
49
  headers[name] = value;
41
50
  }
42
51
  try {
43
- const response = await axios.request({ url: url.href, method: input.method ?? 'GET', headers, data: input.body, httpAgent, httpsAgent, proxy: false, maxRedirects: 0, timeout: Math.min(60000, Math.max(1000, input.timeoutMs || 30000)), maxContentLength: 16 * 1024 * 1024, maxBodyLength: 4 * 1024 * 1024, responseType: 'arraybuffer', validateStatus: () => true, signal });
52
+ const response = await axios.request({
53
+ url: url.href,
54
+ method: input.method ?? 'GET',
55
+ headers,
56
+ data: input.body,
57
+ httpAgent,
58
+ httpsAgent,
59
+ proxy: false,
60
+ maxRedirects: 0,
61
+ timeout: Math.min(60000, Math.max(1000, input.timeoutMs || 30000)),
62
+ maxContentLength: 16 * 1024 * 1024,
63
+ maxBodyLength: 4 * 1024 * 1024,
64
+ responseType: 'arraybuffer',
65
+ validateStatus: () => true,
66
+ signal,
67
+ });
44
68
  if ([301, 302, 303, 307, 308].includes(response.status) && response.headers.location) {
45
69
  if (redirects >= 5)
46
70
  throw new Error('重定向次数过多');
@@ -49,8 +73,16 @@ export async function requestNetwork(input, privateAllowed, signal, redirects =
49
73
  for (const name of Object.keys(headers))
50
74
  if (/authorization|cookie|token|key/i.test(name))
51
75
  delete headers[name];
52
- const method = response.status === 303 || ([301, 302].includes(response.status) && input.method === 'POST') ? 'GET' : input.method;
53
- return requestNetwork({ ...input, url: next.href, headers, method, body: method === 'GET' ? undefined : input.body }, privateAllowed, signal, redirects + 1);
76
+ const method = response.status === 303 || ([301, 302].includes(response.status) && input.method === 'POST')
77
+ ? 'GET'
78
+ : input.method;
79
+ return requestNetwork({
80
+ ...input,
81
+ url: next.href,
82
+ headers,
83
+ method,
84
+ body: method === 'GET' ? undefined : input.body,
85
+ }, privateAllowed, signal, redirects + 1);
54
86
  }
55
87
  const raw = Buffer.from(response.data).toString('utf8');
56
88
  let body = raw;
@@ -58,7 +90,13 @@ export async function requestNetwork(input, privateAllowed, signal, redirects =
58
90
  body = JSON.parse(raw);
59
91
  }
60
92
  catch { }
61
- return { status: response.status, headers: Object.fromEntries(Object.entries(response.headers).filter(([, v]) => v != null).map(([k, v]) => [k, String(v)])), body };
93
+ return {
94
+ status: response.status,
95
+ headers: Object.fromEntries(Object.entries(response.headers)
96
+ .filter(([, v]) => v != null)
97
+ .map(([k, v]) => [k, String(v)])),
98
+ body,
99
+ };
62
100
  }
63
101
  catch (error) {
64
102
  if (axios.isAxiosError(error))
@@ -6,8 +6,14 @@ const timers = new Map();
6
6
  let context;
7
7
  let generation = '';
8
8
  let messages = 0;
9
- setInterval(() => { messages = 0; }, 1000).unref();
10
- const deliver = (value) => vm.runInContext('globalThis.__receive(' + JSON.stringify(JSON.stringify(value)) + ')', context, { timeout: 5000 });
9
+ let guestScript;
10
+ let guestStarted = false;
11
+ setInterval(() => {
12
+ messages = 0;
13
+ }, 1000).unref();
14
+ const deliver = (value) => vm.runInContext('globalThis.__receive(' + JSON.stringify(JSON.stringify(value)) + ')', context, {
15
+ timeout: 5000,
16
+ });
11
17
  parentPort.on('message', async (message) => {
12
18
  try {
13
19
  if (message.type !== 'boot') {
@@ -16,7 +22,9 @@ parentPort.on('message', async (message) => {
16
22
  return;
17
23
  }
18
24
  generation = message.generation;
19
- context = vm.createContext({ __bridge: (encoded) => {
25
+ guestScript = message.guest?.script;
26
+ context = vm.createContext({
27
+ __bridge: (encoded) => {
20
28
  try {
21
29
  if (typeof encoded !== 'string' || encoded.length > 8 * 1024 * 1024)
22
30
  throw new Error('Host message too large');
@@ -26,6 +34,21 @@ parentPort.on('message', async (message) => {
26
34
  if (++messages > 1000)
27
35
  throw new Error('Plugin message rate exceeded');
28
36
  parentPort.postMessage({ ...value, generation });
37
+ if (value.type === 'bootstrap-ready' && guestScript !== undefined && !guestStarted) {
38
+ guestStarted = true;
39
+ setImmediate(() => {
40
+ try {
41
+ vm.runInContext(guestScript, context, { timeout: 5000, filename: 'guest.js' });
42
+ }
43
+ catch (error) {
44
+ parentPort.postMessage({
45
+ type: 'failed',
46
+ generation,
47
+ data: { message: error instanceof Error ? error.message : String(error) },
48
+ });
49
+ }
50
+ });
51
+ }
29
52
  }
30
53
  else if (kind === 'random') {
31
54
  if (!Number.isInteger(value) || value < 0 || value > 65536)
@@ -36,11 +59,33 @@ parentPort.on('message', async (message) => {
36
59
  const url = new URL(value.url, value.base);
37
60
  if (value.search !== undefined)
38
61
  url.search = value.search;
39
- result = Object.fromEntries(['href', 'origin', 'protocol', 'hostname', 'host', 'port', 'username', 'password', 'pathname', 'hash', 'search'].map(key => [key, url[key]]));
62
+ result = Object.fromEntries([
63
+ 'href',
64
+ 'origin',
65
+ 'protocol',
66
+ 'hostname',
67
+ 'host',
68
+ 'port',
69
+ 'username',
70
+ 'password',
71
+ 'pathname',
72
+ 'hash',
73
+ 'search',
74
+ ].map((key) => [key, url[key]]));
40
75
  }
41
76
  else if (kind === 'params') {
42
77
  const params = new URLSearchParams(value.value);
43
- const allowed = ['get', 'getAll', 'has', 'set', 'append', 'delete', 'sort', 'entries', 'toString'];
78
+ const allowed = [
79
+ 'get',
80
+ 'getAll',
81
+ 'has',
82
+ 'set',
83
+ 'append',
84
+ 'delete',
85
+ 'sort',
86
+ 'entries',
87
+ 'toString',
88
+ ];
44
89
  if (!allowed.includes(value.method))
45
90
  throw new Error('Invalid URL operation');
46
91
  result = params[value.method](...value.args);
@@ -56,13 +101,20 @@ parentPort.on('message', async (message) => {
56
101
  else if (kind === 'timer') {
57
102
  if (timers.size >= 256)
58
103
  throw new Error('Plugin timer limit exceeded');
59
- const callback = () => { if (!value.repeat)
60
- timers.delete(value.id); try {
61
- deliver({ type: 'timer', id: value.id });
62
- }
63
- catch (error) {
64
- parentPort.postMessage({ type: 'failed', generation, data: { message: String(error) } });
65
- } };
104
+ const callback = () => {
105
+ if (!value.repeat)
106
+ timers.delete(value.id);
107
+ try {
108
+ deliver({ type: 'timer', id: value.id });
109
+ }
110
+ catch (error) {
111
+ parentPort.postMessage({
112
+ type: 'failed',
113
+ generation,
114
+ data: { message: String(error) },
115
+ });
116
+ }
117
+ };
66
118
  timers.set(value.id, (value.repeat ? setInterval : setTimeout)(callback, Math.max(value.repeat ? 10 : 0, Math.min(Number(value.ms) || 0, 2147483647))));
67
119
  }
68
120
  else if (kind === 'clearTimer') {
@@ -75,16 +127,39 @@ parentPort.on('message', async (message) => {
75
127
  return JSON.stringify({ value: result });
76
128
  }
77
129
  catch (error) {
78
- return JSON.stringify({ error: error instanceof Error ? error.message : 'Host operation failed' });
130
+ return JSON.stringify({
131
+ error: error instanceof Error ? error.message : 'Host operation failed',
132
+ });
79
133
  }
80
- } }, { codeGeneration: { strings: false, wasm: false } });
81
- const [globals, runtime, catalog] = await Promise.all(['node-globals.js', 'sandbox.js', 'catalog.json'].map(name => readFile(new URL('../assets/' + name, import.meta.url), 'utf8')));
134
+ },
135
+ }, { codeGeneration: { strings: false, wasm: false } });
136
+ const [globals, runtime, catalog] = await Promise.all(['node-globals.js', 'sandbox.js', 'catalog.json'].map((name) => readFile(new URL('../assets/' + name, import.meta.url), 'utf8')));
82
137
  vm.runInContext(globals, context, { timeout: 5000 });
83
138
  vm.runInContext(runtime, context, { timeout: 5000 });
84
- deliver({ type: 'init', data: { generation, kind: 'logic', mode: 'production', manifest: message.manifest, resources: message.resources, catalog: JSON.parse(catalog) } });
139
+ deliver({
140
+ type: 'init',
141
+ data: {
142
+ generation,
143
+ kind: message.guest ? 'guest' : 'logic',
144
+ guest: message.guest
145
+ ? {
146
+ id: message.guest.id,
147
+ info: { ...message.guest.info, rawScript: message.guest.script },
148
+ }
149
+ : undefined,
150
+ mode: 'production',
151
+ manifest: message.manifest,
152
+ resources: message.resources,
153
+ catalog: JSON.parse(catalog),
154
+ },
155
+ });
85
156
  vm.runInContext('globalThis.__ceruStart(' + message.entry + ')', context, { timeout: 5000 });
86
157
  }
87
158
  catch (error) {
88
- parentPort.postMessage({ type: 'failed', generation, data: { message: error instanceof Error ? error.message : String(error) } });
159
+ parentPort.postMessage({
160
+ type: 'failed',
161
+ generation,
162
+ data: { message: error instanceof Error ? error.message : String(error) },
163
+ });
89
164
  }
90
165
  });
package/dist/node.d.ts CHANGED
@@ -1,13 +1,25 @@
1
1
  import type { Artifact } from '@shiqianjiang/ceru-plugin-issuer';
2
+ export interface GuestBoot {
3
+ id: string;
4
+ script: string;
5
+ info: {
6
+ name: string;
7
+ version: string;
8
+ author?: string;
9
+ description?: string;
10
+ homepage?: string;
11
+ };
12
+ }
2
13
  /** Node worker + realm-local SDK. No Node modules or host objects enter plugin globals. */
3
14
  export declare class NodePluginSandbox {
4
15
  private readonly rpc;
5
16
  private readonly event;
6
17
  private worker?;
7
18
  private generation;
19
+ private failure?;
8
20
  private pending;
9
21
  constructor(rpc: (method: string, data: any) => Promise<any>, event: (type: string, data: any) => void);
10
- start(artifact: Artifact): Promise<void>;
22
+ start(artifact: Artifact, guest?: GuestBoot): Promise<void>;
11
23
  send(type: string, data: any): Promise<void>;
12
24
  invoke(kind: string, target: string, method: string, args: any[], signal?: AbortSignal, operationId?: string): Promise<any>;
13
25
  dispose(): void;
package/dist/node.js CHANGED
@@ -6,22 +6,39 @@ export class NodePluginSandbox {
6
6
  event;
7
7
  worker;
8
8
  generation = randomUUID();
9
+ failure;
9
10
  pending = new Map();
10
11
  constructor(rpc, event) {
11
12
  this.rpc = rpc;
12
13
  this.event = event;
13
14
  }
14
- async start(artifact) {
15
+ async start(artifact, guest) {
15
16
  const entry = artifact.header.manifest.modules.logic?.entry;
16
17
  if (!entry)
17
18
  return;
18
- const worker = new Worker(new URL('./node-worker.js', import.meta.url), { execArgv: [], resourceLimits: { maxOldGenerationSizeMb: 128, maxYoungGenerationSizeMb: 32, stackSizeMb: 4 } });
19
+ const worker = new Worker(new URL('./node-worker.js', import.meta.url), {
20
+ execArgv: [],
21
+ resourceLimits: { maxOldGenerationSizeMb: 128, maxYoungGenerationSizeMb: 32, stackSizeMb: 4 },
22
+ });
19
23
  this.worker = worker;
20
24
  await new Promise((resolve, reject) => {
21
- const timer = setTimeout(() => { reject(new Error('Plugin activation timed out')); this.dispose(); }, 30000);
22
- worker.on('error', error => { clearTimeout(timer); reject(error); this.dispose(); });
23
- worker.on('exit', () => { clearTimeout(timer); reject(new Error('Plugin runtime stopped')); this.dispose(); this.event('closed', {}); });
24
- worker.on('message', message => {
25
+ const timer = setTimeout(() => {
26
+ reject(new Error('Plugin activation timed out'));
27
+ this.dispose();
28
+ }, guest ? 120000 : 30000);
29
+ worker.on('error', (error) => {
30
+ this.failure = error.message;
31
+ clearTimeout(timer);
32
+ reject(error);
33
+ this.dispose();
34
+ });
35
+ worker.on('exit', () => {
36
+ clearTimeout(timer);
37
+ reject(new Error('Plugin runtime stopped'));
38
+ this.dispose();
39
+ this.event('closed', { reason: this.failure });
40
+ });
41
+ worker.on('message', (message) => {
25
42
  if (message?.generation !== this.generation)
26
43
  return;
27
44
  const { type, data } = message;
@@ -32,13 +49,19 @@ export class NodePluginSandbox {
32
49
  return;
33
50
  }
34
51
  if (type === 'failed') {
52
+ this.failure = String(data.message);
35
53
  clearTimeout(timer);
36
54
  reject(new Error(String(data.message)));
37
55
  this.dispose();
38
56
  return;
39
57
  }
40
58
  if (type === 'rpc') {
41
- 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(() => { });
59
+ void this.rpc(String(data.method), data.data)
60
+ .then((value) => this.send('rpc-result', { id: data.id, value }), (error) => this.send('rpc-result', {
61
+ id: data.id,
62
+ error: error instanceof Error ? error.message : 'Host request failed',
63
+ }))
64
+ .catch(() => { });
42
65
  return;
43
66
  }
44
67
  if (type === 'invoke-result') {
@@ -58,10 +81,19 @@ export class NodePluginSandbox {
58
81
  this.dispose();
59
82
  }
60
83
  });
61
- worker.postMessage({ type: 'boot', generation: this.generation, manifest: artifact.header.manifest, resources: artifact.resources, entry: artifact.modules[entry] });
84
+ worker.postMessage({
85
+ type: 'boot',
86
+ generation: this.generation,
87
+ manifest: artifact.header.manifest,
88
+ resources: artifact.resources,
89
+ entry: artifact.modules[entry],
90
+ guest,
91
+ });
62
92
  });
63
93
  }
64
- async send(type, data) { this.worker?.postMessage({ type, data, generation: this.generation }); }
94
+ async send(type, data) {
95
+ this.worker?.postMessage({ type, data, generation: this.generation });
96
+ }
65
97
  invoke(kind, target, method, args, signal, operationId) {
66
98
  const id = operationId ?? randomUUID();
67
99
  return new Promise((resolve, reject) => {
@@ -69,10 +101,31 @@ export class NodePluginSandbox {
69
101
  reject(new Error('Plugin runtime is not active'));
70
102
  return;
71
103
  }
72
- const cancel = () => { void this.send('cancel', { id }); done(); this.pending.delete(id); reject(new Error('Plugin operation cancelled')); };
73
- const timer = setTimeout(() => { cancel(); this.dispose(); }, 120000);
74
- const done = () => { clearTimeout(timer); signal?.removeEventListener('abort', cancel); };
75
- this.pending.set(id, { timer, resolve: value => { done(); resolve(value); }, reject: error => { done(); reject(error); } });
104
+ const cancel = () => {
105
+ void this.send('cancel', { id });
106
+ done();
107
+ this.pending.delete(id);
108
+ reject(new Error('Plugin operation cancelled'));
109
+ };
110
+ const timer = setTimeout(() => {
111
+ cancel();
112
+ this.dispose();
113
+ }, 120000);
114
+ const done = () => {
115
+ clearTimeout(timer);
116
+ signal?.removeEventListener('abort', cancel);
117
+ };
118
+ this.pending.set(id, {
119
+ timer,
120
+ resolve: (value) => {
121
+ done();
122
+ resolve(value);
123
+ },
124
+ reject: (error) => {
125
+ done();
126
+ reject(error);
127
+ },
128
+ });
76
129
  signal?.addEventListener('abort', cancel, { once: true });
77
130
  if (signal?.aborted) {
78
131
  cancel();