@lvce-editor/embeds-worker 2.0.0 → 2.2.0

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.
@@ -1,751 +1,750 @@
1
- const Two = '2.0';
2
- const create$4 = (method, params) => {
3
- return {
4
- jsonrpc: Two,
5
- method,
6
- params
7
- };
8
- };
9
- const state$3 = {
10
- callbacks: Object.create(null)
1
+ const normalizeLine = line => {
2
+ if (line.startsWith('Error: ')) {
3
+ return line.slice('Error: '.length);
4
+ }
5
+ if (line.startsWith('VError: ')) {
6
+ return line.slice('VError: '.length);
7
+ }
8
+ return line;
11
9
  };
12
- const set = (id, fn) => {
13
- state$3.callbacks[id] = fn;
10
+ const getCombinedMessage = (error, message) => {
11
+ const stringifiedError = normalizeLine(`${error}`);
12
+ if (message) {
13
+ return `${message}: ${stringifiedError}`;
14
+ }
15
+ return stringifiedError;
14
16
  };
15
- const get = id => {
16
- return state$3.callbacks[id];
17
+ const NewLine$2 = '\n';
18
+ const getNewLineIndex$1 = (string, startIndex = undefined) => {
19
+ return string.indexOf(NewLine$2, startIndex);
17
20
  };
18
- const remove = id => {
19
- delete state$3.callbacks[id];
21
+ const mergeStacks = (parent, child) => {
22
+ if (!child) {
23
+ return parent;
24
+ }
25
+ const parentNewLineIndex = getNewLineIndex$1(parent);
26
+ const childNewLineIndex = getNewLineIndex$1(child);
27
+ if (childNewLineIndex === -1) {
28
+ return parent;
29
+ }
30
+ const parentFirstLine = parent.slice(0, parentNewLineIndex);
31
+ const childRest = child.slice(childNewLineIndex);
32
+ const childFirstLine = normalizeLine(child.slice(0, childNewLineIndex));
33
+ if (parentFirstLine.includes(childFirstLine)) {
34
+ return parentFirstLine + childRest;
35
+ }
36
+ return child;
20
37
  };
21
- let id = 0;
22
- const create$3 = () => {
23
- return ++id;
38
+ class VError extends Error {
39
+ constructor(error, message) {
40
+ const combinedMessage = getCombinedMessage(error, message);
41
+ super(combinedMessage);
42
+ this.name = 'VError';
43
+ if (error instanceof Error) {
44
+ this.stack = mergeStacks(this.stack, error.stack);
45
+ }
46
+ if (error.codeFrame) {
47
+ // @ts-ignore
48
+ this.codeFrame = error.codeFrame;
49
+ }
50
+ if (error.code) {
51
+ // @ts-ignore
52
+ this.code = error.code;
53
+ }
54
+ }
55
+ }
56
+
57
+ const isMessagePort = value => {
58
+ return value && value instanceof MessagePort;
24
59
  };
25
- const warn = (...args) => {
26
- console.warn(...args);
60
+ const isMessagePortMain = value => {
61
+ return value && value.constructor && value.constructor.name === 'MessagePortMain';
27
62
  };
28
- const registerPromise = () => {
29
- const id = create$3();
30
- const {
31
- resolve,
32
- promise
33
- } = Promise.withResolvers();
34
- set(id, resolve);
35
- return {
36
- id,
37
- promise
38
- };
63
+ const isOffscreenCanvas = value => {
64
+ return typeof OffscreenCanvas !== 'undefined' && value instanceof OffscreenCanvas;
39
65
  };
40
- const resolve = (id, response) => {
41
- const fn = get(id);
42
- if (!fn) {
43
- console.log(response);
44
- warn(`callback ${id} may already be disposed`);
45
- return;
46
- }
47
- fn(response);
48
- remove(id);
66
+ const isInstanceOf = (value, constructorName) => {
67
+ return value?.constructor?.name === constructorName;
49
68
  };
50
- const create$2 = (method, params) => {
51
- const {
52
- id,
53
- promise
54
- } = registerPromise();
55
- const message = {
56
- jsonrpc: Two,
57
- method,
58
- params,
59
- id
60
- };
61
- return {
62
- message,
63
- promise
64
- };
69
+ const isSocket = value => {
70
+ return isInstanceOf(value, 'Socket');
65
71
  };
66
- class JsonRpcError extends Error {
67
- constructor(message) {
68
- super(message);
69
- this.name = 'JsonRpcError';
70
- }
71
- }
72
- const NewLine$2 = '\n';
73
- const DomException = 'DOMException';
74
- const ReferenceError$1 = 'ReferenceError';
75
- const SyntaxError$1 = 'SyntaxError';
76
- const TypeError$1 = 'TypeError';
77
- const getErrorConstructor = (message, type) => {
78
- if (type) {
79
- switch (type) {
80
- case DomException:
81
- return DOMException;
82
- case TypeError$1:
83
- return TypeError;
84
- case SyntaxError$1:
85
- return SyntaxError;
86
- case ReferenceError$1:
87
- return ReferenceError;
88
- default:
89
- return Error;
72
+ const transferrables = [isMessagePort, isMessagePortMain, isOffscreenCanvas, isSocket];
73
+ const isTransferrable = value => {
74
+ for (const fn of transferrables) {
75
+ if (fn(value)) {
76
+ return true;
90
77
  }
91
78
  }
92
- if (message.startsWith('TypeError: ')) {
93
- return TypeError;
94
- }
95
- if (message.startsWith('SyntaxError: ')) {
96
- return SyntaxError;
79
+ return false;
80
+ };
81
+ const walkValue = (value, transferrables, isTransferrable) => {
82
+ if (!value) {
83
+ return;
97
84
  }
98
- if (message.startsWith('ReferenceError: ')) {
99
- return ReferenceError;
85
+ if (isTransferrable(value)) {
86
+ transferrables.push(value);
87
+ return;
100
88
  }
101
- return Error;
102
- };
103
- const constructError = (message, type, name) => {
104
- const ErrorConstructor = getErrorConstructor(message, type);
105
- if (ErrorConstructor === DOMException && name) {
106
- return new ErrorConstructor(message, name);
89
+ if (Array.isArray(value)) {
90
+ for (const item of value) {
91
+ walkValue(item, transferrables, isTransferrable);
92
+ }
93
+ return;
107
94
  }
108
- if (ErrorConstructor === Error) {
109
- const error = new Error(message);
110
- if (name && name !== 'VError') {
111
- error.name = name;
95
+ if (typeof value === 'object') {
96
+ for (const property of Object.values(value)) {
97
+ walkValue(property, transferrables, isTransferrable);
112
98
  }
113
- return error;
99
+ return;
114
100
  }
115
- return new ErrorConstructor(message);
116
101
  };
117
- const getNewLineIndex$1 = (string, startIndex = undefined) => {
118
- return string.indexOf(NewLine$2, startIndex);
102
+ const getTransferrables = value => {
103
+ const transferrables = [];
104
+ walkValue(value, transferrables, isTransferrable);
105
+ return transferrables;
119
106
  };
120
- const getParentStack = error => {
121
- let parentStack = error.stack || error.data || error.message || '';
122
- if (parentStack.startsWith(' at')) {
123
- parentStack = error.message + NewLine$2 + parentStack;
124
- }
125
- return parentStack;
107
+ const attachEvents = that => {
108
+ const handleMessage = (...args) => {
109
+ const data = that.getData(...args);
110
+ that.dispatchEvent(new MessageEvent('message', {
111
+ data
112
+ }));
113
+ };
114
+ that.onMessage(handleMessage);
115
+ const handleClose = event => {
116
+ that.dispatchEvent(new Event('close'));
117
+ };
118
+ that.onClose(handleClose);
126
119
  };
120
+ class Ipc extends EventTarget {
121
+ constructor(rawIpc) {
122
+ super();
123
+ this._rawIpc = rawIpc;
124
+ attachEvents(this);
125
+ }
126
+ }
127
+ const E_INCOMPATIBLE_NATIVE_MODULE = 'E_INCOMPATIBLE_NATIVE_MODULE';
128
+ const E_MODULES_NOT_SUPPORTED_IN_ELECTRON = 'E_MODULES_NOT_SUPPORTED_IN_ELECTRON';
129
+ const ERR_MODULE_NOT_FOUND = 'ERR_MODULE_NOT_FOUND';
130
+ const NewLine$1 = '\n';
127
131
  const joinLines$1 = lines => {
128
- return lines.join(NewLine$2);
132
+ return lines.join(NewLine$1);
129
133
  };
130
- const MethodNotFound = -32601;
131
- const Custom = -32001;
132
- const splitLines$1 = lines => {
133
- return lines.split(NewLine$2);
134
+ const RE_AT = /^\s+at/;
135
+ const RE_AT_PROMISE_INDEX = /^\s*at async Promise.all \(index \d+\)$/;
136
+ const isNormalStackLine = line => {
137
+ return RE_AT.test(line) && !RE_AT_PROMISE_INDEX.test(line);
134
138
  };
135
- const restoreJsonRpcError = error => {
136
- if (error && error instanceof Error) {
137
- return error;
138
- }
139
- const currentStack = joinLines$1(splitLines$1(new Error().stack || '').slice(1));
140
- if (error && error.code && error.code === MethodNotFound) {
141
- const restoredError = new JsonRpcError(error.message);
142
- const parentStack = getParentStack(error);
143
- restoredError.stack = parentStack + NewLine$2 + currentStack;
144
- return restoredError;
139
+ const getDetails = lines => {
140
+ const index = lines.findIndex(isNormalStackLine);
141
+ if (index === -1) {
142
+ return {
143
+ actualMessage: joinLines$1(lines),
144
+ rest: []
145
+ };
145
146
  }
146
- if (error && error.message) {
147
- const restoredError = constructError(error.message, error.type, error.name);
148
- if (error.data) {
149
- if (error.data.stack && error.data.type && error.message) {
150
- restoredError.stack = error.data.type + ': ' + error.message + NewLine$2 + error.data.stack + NewLine$2 + currentStack;
151
- } else if (error.data.stack) {
152
- restoredError.stack = error.data.stack;
153
- }
154
- if (error.data.codeFrame) {
155
- // @ts-ignore
156
- restoredError.codeFrame = error.data.codeFrame;
157
- }
158
- if (error.data.code) {
159
- // @ts-ignore
160
- restoredError.code = error.data.code;
161
- }
162
- if (error.data.type) {
163
- // @ts-ignore
164
- restoredError.name = error.data.type;
165
- }
166
- } else {
167
- if (error.stack) {
168
- const lowerStack = restoredError.stack || '';
169
- // @ts-ignore
170
- const indexNewLine = getNewLineIndex$1(lowerStack);
171
- const parentStack = getParentStack(error);
172
- // @ts-ignore
173
- restoredError.stack = parentStack + lowerStack.slice(indexNewLine);
174
- }
175
- if (error.codeFrame) {
176
- // @ts-ignore
177
- restoredError.codeFrame = error.codeFrame;
178
- }
147
+ let lastIndex = index - 1;
148
+ while (++lastIndex < lines.length) {
149
+ if (!isNormalStackLine(lines[lastIndex])) {
150
+ break;
179
151
  }
180
- return restoredError;
181
- }
182
- if (typeof error === 'string') {
183
- return new Error(`JsonRpc Error: ${error}`);
184
152
  }
185
- return new Error(`JsonRpc Error: ${error}`);
153
+ return {
154
+ actualMessage: lines[index - 1],
155
+ rest: lines.slice(index, lastIndex)
156
+ };
186
157
  };
187
- const unwrapJsonRpcResult = responseMessage => {
188
- if ('error' in responseMessage) {
189
- const restoredError = restoreJsonRpcError(responseMessage.error);
190
- throw restoredError;
191
- }
192
- if ('result' in responseMessage) {
193
- return responseMessage.result;
194
- }
195
- throw new JsonRpcError('unexpected response message');
158
+ const splitLines$1 = lines => {
159
+ return lines.split(NewLine$1);
196
160
  };
197
- const E_COMMAND_NOT_FOUND = 'E_COMMAND_NOT_FOUND';
198
- const getErrorType = prettyError => {
199
- if (prettyError && prettyError.type) {
200
- return prettyError.type;
201
- }
202
- if (prettyError && prettyError.constructor && prettyError.constructor.name) {
203
- return prettyError.constructor.name;
161
+ const RE_MESSAGE_CODE_BLOCK_START = /^Error: The module '.*'$/;
162
+ const RE_MESSAGE_CODE_BLOCK_END = /^\s* at/;
163
+ const isMessageCodeBlockStartIndex = line => {
164
+ return RE_MESSAGE_CODE_BLOCK_START.test(line);
165
+ };
166
+ const isMessageCodeBlockEndIndex = line => {
167
+ return RE_MESSAGE_CODE_BLOCK_END.test(line);
168
+ };
169
+ const getMessageCodeBlock = stderr => {
170
+ const lines = splitLines$1(stderr);
171
+ const startIndex = lines.findIndex(isMessageCodeBlockStartIndex);
172
+ const endIndex = startIndex + lines.slice(startIndex).findIndex(isMessageCodeBlockEndIndex, startIndex);
173
+ const relevantLines = lines.slice(startIndex, endIndex);
174
+ const relevantMessage = relevantLines.join(' ').slice('Error: '.length);
175
+ return relevantMessage;
176
+ };
177
+ const isModuleNotFoundMessage = line => {
178
+ return line.includes('[ERR_MODULE_NOT_FOUND]');
179
+ };
180
+ const getModuleNotFoundError = stderr => {
181
+ const lines = splitLines$1(stderr);
182
+ const messageIndex = lines.findIndex(isModuleNotFoundMessage);
183
+ const message = lines[messageIndex];
184
+ return {
185
+ message,
186
+ code: ERR_MODULE_NOT_FOUND
187
+ };
188
+ };
189
+ const isModuleNotFoundError = stderr => {
190
+ if (!stderr) {
191
+ return false;
204
192
  }
205
- return undefined;
193
+ return stderr.includes('ERR_MODULE_NOT_FOUND');
206
194
  };
207
- const getErrorProperty = (error, prettyError) => {
208
- if (error && error.code === E_COMMAND_NOT_FOUND) {
209
- return {
210
- code: MethodNotFound,
211
- message: error.message,
212
- data: error.stack
213
- };
195
+ const isModulesSyntaxError = stderr => {
196
+ if (!stderr) {
197
+ return false;
214
198
  }
199
+ return stderr.includes('SyntaxError: Cannot use import statement outside a module');
200
+ };
201
+ const RE_NATIVE_MODULE_ERROR = /^innerError Error: Cannot find module '.*.node'/;
202
+ const RE_NATIVE_MODULE_ERROR_2 = /was compiled against a different Node.js version/;
203
+ const isUnhelpfulNativeModuleError = stderr => {
204
+ return RE_NATIVE_MODULE_ERROR.test(stderr) && RE_NATIVE_MODULE_ERROR_2.test(stderr);
205
+ };
206
+ const getNativeModuleErrorMessage = stderr => {
207
+ const message = getMessageCodeBlock(stderr);
215
208
  return {
216
- code: Custom,
217
- message: prettyError.message,
218
- data: {
219
- stack: prettyError.stack,
220
- codeFrame: prettyError.codeFrame,
221
- type: getErrorType(prettyError),
222
- code: prettyError.code,
223
- name: prettyError.name
224
- }
209
+ message: `Incompatible native node module: ${message}`,
210
+ code: E_INCOMPATIBLE_NATIVE_MODULE
225
211
  };
226
212
  };
227
- const create$1$2 = (message, error) => {
213
+ const getModuleSyntaxError = () => {
228
214
  return {
229
- jsonrpc: Two,
230
- id: message.id,
231
- error
215
+ message: `ES Modules are not supported in electron`,
216
+ code: E_MODULES_NOT_SUPPORTED_IN_ELECTRON
232
217
  };
233
218
  };
234
- const getErrorResponse = (message, error, preparePrettyError, logError) => {
235
- const prettyError = preparePrettyError(error);
236
- logError(error, prettyError);
237
- const errorProperty = getErrorProperty(error, prettyError);
238
- return create$1$2(message, errorProperty);
239
- };
240
- const create$5 = (message, result) => {
219
+ const getHelpfulChildProcessError = (stdout, stderr) => {
220
+ if (isUnhelpfulNativeModuleError(stderr)) {
221
+ return getNativeModuleErrorMessage(stderr);
222
+ }
223
+ if (isModulesSyntaxError(stderr)) {
224
+ return getModuleSyntaxError();
225
+ }
226
+ if (isModuleNotFoundError(stderr)) {
227
+ return getModuleNotFoundError(stderr);
228
+ }
229
+ const lines = splitLines$1(stderr);
230
+ const {
231
+ actualMessage,
232
+ rest
233
+ } = getDetails(lines);
241
234
  return {
242
- jsonrpc: Two,
243
- id: message.id,
244
- result: result ?? null
235
+ message: actualMessage,
236
+ code: '',
237
+ stack: rest
245
238
  };
246
239
  };
247
- const getSuccessResponse = (message, result) => {
248
- const resultProperty = result ?? null;
249
- return create$5(message, resultProperty);
250
- };
251
- const getResponse = async (message, ipc, execute, preparePrettyError, logError, requiresSocket) => {
252
- try {
253
- const result = requiresSocket(message.method) ? await execute(message.method, ipc, ...message.params) : await execute(message.method, ...message.params);
254
- return getSuccessResponse(message, result);
255
- } catch (error) {
256
- return getErrorResponse(message, error, preparePrettyError, logError);
240
+ class IpcError extends VError {
241
+ // @ts-ignore
242
+ constructor(betterMessage, stdout = '', stderr = '') {
243
+ if (stdout || stderr) {
244
+ // @ts-ignore
245
+ const {
246
+ message,
247
+ code,
248
+ stack
249
+ } = getHelpfulChildProcessError(stdout, stderr);
250
+ const cause = new Error(message);
251
+ // @ts-ignore
252
+ cause.code = code;
253
+ cause.stack = stack;
254
+ super(cause, betterMessage);
255
+ } else {
256
+ super(betterMessage);
257
+ }
258
+ // @ts-ignore
259
+ this.name = 'IpcError';
260
+ // @ts-ignore
261
+ this.stdout = stdout;
262
+ // @ts-ignore
263
+ this.stderr = stderr;
257
264
  }
265
+ }
266
+ const readyMessage = 'ready';
267
+ const getData$2 = event => {
268
+ return event.data;
258
269
  };
259
- const defaultPreparePrettyError = error => {
260
- return error;
261
- };
262
- const defaultLogError = () => {
263
- // ignore
270
+ const listen$7 = () => {
271
+ // @ts-ignore
272
+ if (typeof WorkerGlobalScope === 'undefined') {
273
+ throw new TypeError('module is not in web worker scope');
274
+ }
275
+ return globalThis;
264
276
  };
265
- const defaultRequiresSocket = () => {
266
- return false;
277
+ const signal$8 = global => {
278
+ global.postMessage(readyMessage);
267
279
  };
268
- const defaultResolve = resolve;
269
-
270
- // TODO maybe remove this in v6 or v7, only accept options object to simplify the code
271
- const normalizeParams = args => {
272
- if (args.length === 1) {
273
- const options = args[0];
274
- return {
275
- ipc: options.ipc,
276
- message: options.message,
277
- execute: options.execute,
278
- resolve: options.resolve || defaultResolve,
279
- preparePrettyError: options.preparePrettyError || defaultPreparePrettyError,
280
- logError: options.logError || defaultLogError,
281
- requiresSocket: options.requiresSocket || defaultRequiresSocket
282
- };
280
+ class IpcChildWithModuleWorker extends Ipc {
281
+ getData(event) {
282
+ return getData$2(event);
283
+ }
284
+ send(message) {
285
+ // @ts-ignore
286
+ this._rawIpc.postMessage(message);
287
+ }
288
+ sendAndTransfer(message) {
289
+ const transfer = getTransferrables(message);
290
+ // @ts-ignore
291
+ this._rawIpc.postMessage(message, transfer);
292
+ }
293
+ dispose() {
294
+ // ignore
295
+ }
296
+ onClose(callback) {
297
+ // ignore
283
298
  }
299
+ onMessage(callback) {
300
+ this._rawIpc.addEventListener('message', callback);
301
+ }
302
+ }
303
+ const wrap$f = global => {
304
+ return new IpcChildWithModuleWorker(global);
305
+ };
306
+ const withResolvers = () => {
307
+ let _resolve;
308
+ const promise = new Promise(resolve => {
309
+ _resolve = resolve;
310
+ });
284
311
  return {
285
- ipc: args[0],
286
- message: args[1],
287
- execute: args[2],
288
- resolve: args[3],
289
- preparePrettyError: args[4],
290
- logError: args[5],
291
- requiresSocket: args[6]
312
+ // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
313
+ resolve: _resolve,
314
+ promise
292
315
  };
293
316
  };
294
- const handleJsonRpcMessage = async (...args) => {
295
- const options = normalizeParams(args);
317
+ const waitForFirstMessage = async port => {
296
318
  const {
297
- message,
298
- ipc,
299
- execute,
300
319
  resolve,
301
- preparePrettyError,
302
- logError,
303
- requiresSocket
304
- } = options;
305
- if ('id' in message) {
306
- if ('method' in message) {
307
- const response = await getResponse(message, ipc, execute, preparePrettyError, logError, requiresSocket);
308
- try {
309
- ipc.send(response);
310
- } catch (error) {
311
- const errorResponse = getErrorResponse(message, error, preparePrettyError, logError);
312
- ipc.send(errorResponse);
313
- }
314
- return;
315
- }
316
- resolve(message.id, message);
317
- return;
320
+ promise
321
+ } = withResolvers();
322
+ port.addEventListener('message', resolve, {
323
+ once: true
324
+ });
325
+ const event = await promise;
326
+ // @ts-ignore
327
+ return event.data;
328
+ };
329
+ const listen$6 = async () => {
330
+ const parentIpcRaw = listen$7();
331
+ signal$8(parentIpcRaw);
332
+ const parentIpc = wrap$f(parentIpcRaw);
333
+ const firstMessage = await waitForFirstMessage(parentIpc);
334
+ if (firstMessage.method !== 'initialize') {
335
+ throw new IpcError('unexpected first message');
318
336
  }
319
- if ('method' in message) {
320
- await getResponse(message, ipc, execute, preparePrettyError, logError, requiresSocket);
321
- return;
337
+ const type = firstMessage.params[0];
338
+ if (type === 'message-port') {
339
+ parentIpc.send({
340
+ jsonrpc: '2.0',
341
+ id: firstMessage.id,
342
+ result: null
343
+ });
344
+ parentIpc.dispose();
345
+ const port = firstMessage.params[1];
346
+ return port;
322
347
  }
323
- throw new JsonRpcError('unexpected message');
348
+ return globalThis;
324
349
  };
325
- const invokeHelper = async (ipc, method, params, useSendAndTransfer) => {
326
- const {
327
- message,
328
- promise
329
- } = create$2(method, params);
330
- if (useSendAndTransfer && ipc.sendAndTransfer) {
331
- ipc.sendAndTransfer(message);
332
- } else {
333
- ipc.send(message);
350
+ class IpcChildWithModuleWorkerAndMessagePort extends Ipc {
351
+ getData(event) {
352
+ return getData$2(event);
334
353
  }
335
- const responseMessage = await promise;
336
- return unwrapJsonRpcResult(responseMessage);
354
+ send(message) {
355
+ this._rawIpc.postMessage(message);
356
+ }
357
+ sendAndTransfer(message) {
358
+ const transfer = getTransferrables(message);
359
+ this._rawIpc.postMessage(message, transfer);
360
+ }
361
+ dispose() {
362
+ if (this._rawIpc.close) {
363
+ this._rawIpc.close();
364
+ }
365
+ }
366
+ onClose(callback) {
367
+ // ignore
368
+ }
369
+ onMessage(callback) {
370
+ this._rawIpc.addEventListener('message', callback);
371
+ this._rawIpc.start();
372
+ }
373
+ }
374
+ const wrap$e = port => {
375
+ return new IpcChildWithModuleWorkerAndMessagePort(port);
337
376
  };
338
- const send$1 = (transport, method, ...params) => {
339
- const message = create$4(method, params);
340
- transport.send(message);
377
+ const IpcChildWithModuleWorkerAndMessagePort$1 = {
378
+ __proto__: null,
379
+ listen: listen$6,
380
+ wrap: wrap$e
341
381
  };
342
- const invoke$1 = (ipc, method, ...params) => {
343
- return invokeHelper(ipc, method, params, false);
382
+
383
+ const Two = '2.0';
384
+ const create$4 = (method, params) => {
385
+ return {
386
+ jsonrpc: Two,
387
+ method,
388
+ params
389
+ };
344
390
  };
345
- const invokeAndTransfer$1 = (ipc, method, ...params) => {
346
- return invokeHelper(ipc, method, params, true);
391
+ const callbacks = Object.create(null);
392
+ const set = (id, fn) => {
393
+ callbacks[id] = fn;
347
394
  };
348
-
349
- const commands = Object.create(null);
350
- const register = commandMap => {
351
- Object.assign(commands, commandMap);
395
+ const get = id => {
396
+ return callbacks[id];
352
397
  };
353
- const getCommand$1 = key => {
354
- return commands[key];
398
+ const remove = id => {
399
+ delete callbacks[id];
355
400
  };
356
- const execute$1 = (command, ...args) => {
357
- const fn = getCommand$1(command);
358
- if (!fn) {
359
- throw new Error(`command not found ${command}`);
360
- }
361
- return fn(...args);
401
+ let id = 0;
402
+ const create$3 = () => {
403
+ return ++id;
362
404
  };
363
-
364
- const getData$1 = event => {
365
- return event.data;
405
+ const registerPromise = () => {
406
+ const id = create$3();
407
+ const {
408
+ resolve,
409
+ promise
410
+ } = Promise.withResolvers();
411
+ set(id, resolve);
412
+ return {
413
+ id,
414
+ promise
415
+ };
366
416
  };
367
- const attachEvents = that => {
368
- const handleMessage = (...args) => {
369
- const data = that.getData(...args);
370
- that.dispatchEvent(new MessageEvent('message', {
371
- data
372
- }));
417
+ const create$2$1 = (method, params) => {
418
+ const {
419
+ id,
420
+ promise
421
+ } = registerPromise();
422
+ const message = {
423
+ jsonrpc: Two,
424
+ method,
425
+ params,
426
+ id
373
427
  };
374
- that.onMessage(handleMessage);
375
- const handleClose = event => {
376
- that.dispatchEvent(new Event('close'));
428
+ return {
429
+ message,
430
+ promise
377
431
  };
378
- that.onClose(handleClose);
379
432
  };
380
- class Ipc extends EventTarget {
381
- constructor(rawIpc) {
382
- super();
383
- this._rawIpc = rawIpc;
384
- attachEvents(this);
433
+ class JsonRpcError extends Error {
434
+ constructor(message) {
435
+ super(message);
436
+ this.name = 'JsonRpcError';
385
437
  }
386
438
  }
387
- const readyMessage = 'ready';
388
- const walkValue = (value, transferrables, isTransferrable) => {
389
- if (!value) {
390
- return;
391
- }
392
- if (isTransferrable(value)) {
393
- transferrables.push(value);
394
- return;
395
- }
396
- if (Array.isArray(value)) {
397
- for (const item of value) {
398
- walkValue(item, transferrables, isTransferrable);
439
+ const NewLine = '\n';
440
+ const DomException = 'DOMException';
441
+ const ReferenceError$1 = 'ReferenceError';
442
+ const SyntaxError$1 = 'SyntaxError';
443
+ const TypeError$1 = 'TypeError';
444
+ const getErrorConstructor = (message, type) => {
445
+ if (type) {
446
+ switch (type) {
447
+ case DomException:
448
+ return DOMException;
449
+ case TypeError$1:
450
+ return TypeError;
451
+ case SyntaxError$1:
452
+ return SyntaxError;
453
+ case ReferenceError$1:
454
+ return ReferenceError;
455
+ default:
456
+ return Error;
399
457
  }
400
- return;
401
458
  }
402
- if (typeof value === 'object') {
403
- for (const property of Object.values(value)) {
404
- walkValue(property, transferrables, isTransferrable);
405
- }
406
- return;
459
+ if (message.startsWith('TypeError: ')) {
460
+ return TypeError;
407
461
  }
462
+ if (message.startsWith('SyntaxError: ')) {
463
+ return SyntaxError;
464
+ }
465
+ if (message.startsWith('ReferenceError: ')) {
466
+ return ReferenceError;
467
+ }
468
+ return Error;
408
469
  };
409
- const isMessagePort = value => {
410
- return value && value instanceof MessagePort;
411
- };
412
- const isMessagePortMain = value => {
413
- return value && value.constructor && value.constructor.name === 'MessagePortMain';
414
- };
415
- const isOffscreenCanvas = value => {
416
- return typeof OffscreenCanvas !== 'undefined' && value instanceof OffscreenCanvas;
417
- };
418
- const isInstanceOf = (value, constructorName) => {
419
- return value?.constructor?.name === constructorName;
420
- };
421
- const isSocket = value => {
422
- return isInstanceOf(value, 'Socket');
423
- };
424
- const transferrables = [isMessagePort, isMessagePortMain, isOffscreenCanvas, isSocket];
425
- const isTransferrable = value => {
426
- for (const fn of transferrables) {
427
- if (fn(value)) {
428
- return true;
470
+ const constructError = (message, type, name) => {
471
+ const ErrorConstructor = getErrorConstructor(message, type);
472
+ if (ErrorConstructor === DOMException && name) {
473
+ return new ErrorConstructor(message, name);
474
+ }
475
+ if (ErrorConstructor === Error) {
476
+ const error = new Error(message);
477
+ if (name && name !== 'VError') {
478
+ error.name = name;
429
479
  }
480
+ return error;
430
481
  }
431
- return false;
482
+ return new ErrorConstructor(message);
432
483
  };
433
- const getTransferrables = value => {
434
- const transferrables = [];
435
- walkValue(value, transferrables, isTransferrable);
436
- return transferrables;
484
+ const getNewLineIndex = (string, startIndex = undefined) => {
485
+ return string.indexOf(NewLine, startIndex);
437
486
  };
438
- const listen$2 = () => {
439
- // @ts-ignore
440
- if (typeof WorkerGlobalScope === 'undefined') {
441
- throw new TypeError('module is not in web worker scope');
487
+ const getParentStack = error => {
488
+ let parentStack = error.stack || error.data || error.message || '';
489
+ if (parentStack.startsWith(' at')) {
490
+ parentStack = error.message + NewLine + parentStack;
442
491
  }
443
- return globalThis;
492
+ return parentStack;
444
493
  };
445
- const signal$2 = global => {
446
- global.postMessage(readyMessage);
494
+ const joinLines = lines => {
495
+ return lines.join(NewLine);
447
496
  };
448
- class IpcChildWithModuleWorker extends Ipc {
449
- getData(event) {
450
- return getData$1(event);
497
+ const MethodNotFound = -32601;
498
+ const Custom = -32001;
499
+ const splitLines = lines => {
500
+ return lines.split(NewLine);
501
+ };
502
+ const restoreJsonRpcError = error => {
503
+ if (error && error instanceof Error) {
504
+ return error;
451
505
  }
452
- send(message) {
453
- // @ts-ignore
454
- this._rawIpc.postMessage(message);
506
+ const currentStack = joinLines(splitLines(new Error().stack || '').slice(1));
507
+ if (error && error.code && error.code === MethodNotFound) {
508
+ const restoredError = new JsonRpcError(error.message);
509
+ const parentStack = getParentStack(error);
510
+ restoredError.stack = parentStack + NewLine + currentStack;
511
+ return restoredError;
455
512
  }
456
- sendAndTransfer(message) {
457
- const transfer = getTransferrables(message);
458
- // @ts-ignore
459
- this._rawIpc.postMessage(message, transfer);
513
+ if (error && error.message) {
514
+ const restoredError = constructError(error.message, error.type, error.name);
515
+ if (error.data) {
516
+ if (error.data.stack && error.data.type && error.message) {
517
+ restoredError.stack = error.data.type + ': ' + error.message + NewLine + error.data.stack + NewLine + currentStack;
518
+ } else if (error.data.stack) {
519
+ restoredError.stack = error.data.stack;
520
+ }
521
+ if (error.data.codeFrame) {
522
+ // @ts-ignore
523
+ restoredError.codeFrame = error.data.codeFrame;
524
+ }
525
+ if (error.data.code) {
526
+ // @ts-ignore
527
+ restoredError.code = error.data.code;
528
+ }
529
+ if (error.data.type) {
530
+ // @ts-ignore
531
+ restoredError.name = error.data.type;
532
+ }
533
+ } else {
534
+ if (error.stack) {
535
+ const lowerStack = restoredError.stack || '';
536
+ // @ts-ignore
537
+ const indexNewLine = getNewLineIndex(lowerStack);
538
+ const parentStack = getParentStack(error);
539
+ // @ts-ignore
540
+ restoredError.stack = parentStack + lowerStack.slice(indexNewLine);
541
+ }
542
+ if (error.codeFrame) {
543
+ // @ts-ignore
544
+ restoredError.codeFrame = error.codeFrame;
545
+ }
546
+ }
547
+ return restoredError;
460
548
  }
461
- dispose() {
462
- // ignore
549
+ if (typeof error === 'string') {
550
+ return new Error(`JsonRpc Error: ${error}`);
463
551
  }
464
- onClose(callback) {
465
- // ignore
552
+ return new Error(`JsonRpc Error: ${error}`);
553
+ };
554
+ const unwrapJsonRpcResult = responseMessage => {
555
+ if ('error' in responseMessage) {
556
+ const restoredError = restoreJsonRpcError(responseMessage.error);
557
+ throw restoredError;
466
558
  }
467
- onMessage(callback) {
468
- this._rawIpc.addEventListener('message', callback);
559
+ if ('result' in responseMessage) {
560
+ return responseMessage.result;
469
561
  }
470
- }
471
- const wrap$5 = global => {
472
- return new IpcChildWithModuleWorker(global);
473
- };
474
- const E_INCOMPATIBLE_NATIVE_MODULE = 'E_INCOMPATIBLE_NATIVE_MODULE';
475
- const E_MODULES_NOT_SUPPORTED_IN_ELECTRON = 'E_MODULES_NOT_SUPPORTED_IN_ELECTRON';
476
- const ERR_MODULE_NOT_FOUND = 'ERR_MODULE_NOT_FOUND';
477
- const NewLine$1 = '\n';
478
- const joinLines = lines => {
479
- return lines.join(NewLine$1);
480
- };
481
- const splitLines = lines => {
482
- return lines.split(NewLine$1);
483
- };
484
- const isModuleNotFoundMessage = line => {
485
- return line.includes('[ERR_MODULE_NOT_FOUND]');
486
- };
487
- const getModuleNotFoundError = stderr => {
488
- const lines = splitLines(stderr);
489
- const messageIndex = lines.findIndex(isModuleNotFoundMessage);
490
- const message = lines[messageIndex];
491
- return {
492
- message,
493
- code: ERR_MODULE_NOT_FOUND
494
- };
495
- };
496
- const RE_NATIVE_MODULE_ERROR = /^innerError Error: Cannot find module '.*.node'/;
497
- const RE_NATIVE_MODULE_ERROR_2 = /was compiled against a different Node.js version/;
498
- const RE_MESSAGE_CODE_BLOCK_START = /^Error: The module '.*'$/;
499
- const RE_MESSAGE_CODE_BLOCK_END = /^\s* at/;
500
- const RE_AT = /^\s+at/;
501
- const RE_AT_PROMISE_INDEX = /^\s*at async Promise.all \(index \d+\)$/;
502
- const isUnhelpfulNativeModuleError = stderr => {
503
- return RE_NATIVE_MODULE_ERROR.test(stderr) && RE_NATIVE_MODULE_ERROR_2.test(stderr);
504
- };
505
- const isMessageCodeBlockStartIndex = line => {
506
- return RE_MESSAGE_CODE_BLOCK_START.test(line);
507
- };
508
- const isMessageCodeBlockEndIndex = line => {
509
- return RE_MESSAGE_CODE_BLOCK_END.test(line);
510
- };
511
- const getMessageCodeBlock = stderr => {
512
- const lines = splitLines(stderr);
513
- const startIndex = lines.findIndex(isMessageCodeBlockStartIndex);
514
- const endIndex = startIndex + lines.slice(startIndex).findIndex(isMessageCodeBlockEndIndex, startIndex);
515
- const relevantLines = lines.slice(startIndex, endIndex);
516
- const relevantMessage = relevantLines.join(' ').slice('Error: '.length);
517
- return relevantMessage;
562
+ throw new JsonRpcError('unexpected response message');
518
563
  };
519
- const getNativeModuleErrorMessage = stderr => {
520
- const message = getMessageCodeBlock(stderr);
521
- return {
522
- message: `Incompatible native node module: ${message}`,
523
- code: E_INCOMPATIBLE_NATIVE_MODULE
524
- };
564
+ const warn = (...args) => {
565
+ console.warn(...args);
525
566
  };
526
- const isModulesSyntaxError = stderr => {
527
- if (!stderr) {
528
- return false;
567
+ const resolve = (id, response) => {
568
+ const fn = get(id);
569
+ if (!fn) {
570
+ console.log(response);
571
+ warn(`callback ${id} may already be disposed`);
572
+ return;
529
573
  }
530
- return stderr.includes('SyntaxError: Cannot use import statement outside a module');
531
- };
532
- const getModuleSyntaxError = () => {
533
- return {
534
- message: `ES Modules are not supported in electron`,
535
- code: E_MODULES_NOT_SUPPORTED_IN_ELECTRON
536
- };
574
+ fn(response);
575
+ remove(id);
537
576
  };
538
- const isModuleNotFoundError = stderr => {
539
- if (!stderr) {
540
- return false;
577
+ const E_COMMAND_NOT_FOUND = 'E_COMMAND_NOT_FOUND';
578
+ const getErrorType = prettyError => {
579
+ if (prettyError && prettyError.type) {
580
+ return prettyError.type;
541
581
  }
542
- return stderr.includes('ERR_MODULE_NOT_FOUND');
543
- };
544
- const isNormalStackLine = line => {
545
- return RE_AT.test(line) && !RE_AT_PROMISE_INDEX.test(line);
582
+ if (prettyError && prettyError.constructor && prettyError.constructor.name) {
583
+ return prettyError.constructor.name;
584
+ }
585
+ return undefined;
546
586
  };
547
- const getDetails = lines => {
548
- const index = lines.findIndex(isNormalStackLine);
549
- if (index === -1) {
587
+ const getErrorProperty = (error, prettyError) => {
588
+ if (error && error.code === E_COMMAND_NOT_FOUND) {
550
589
  return {
551
- actualMessage: joinLines(lines),
552
- rest: []
590
+ code: MethodNotFound,
591
+ message: error.message,
592
+ data: error.stack
553
593
  };
554
594
  }
555
- let lastIndex = index - 1;
556
- while (++lastIndex < lines.length) {
557
- if (!isNormalStackLine(lines[lastIndex])) {
558
- break;
595
+ return {
596
+ code: Custom,
597
+ message: prettyError.message,
598
+ data: {
599
+ stack: prettyError.stack,
600
+ codeFrame: prettyError.codeFrame,
601
+ type: getErrorType(prettyError),
602
+ code: prettyError.code,
603
+ name: prettyError.name
559
604
  }
560
- }
605
+ };
606
+ };
607
+ const create$1$1 = (message, error) => {
561
608
  return {
562
- actualMessage: lines[index - 1],
563
- rest: lines.slice(index, lastIndex)
609
+ jsonrpc: Two,
610
+ id: message.id,
611
+ error
564
612
  };
565
613
  };
566
- const getHelpfulChildProcessError = (stdout, stderr) => {
567
- if (isUnhelpfulNativeModuleError(stderr)) {
568
- return getNativeModuleErrorMessage(stderr);
569
- }
570
- if (isModulesSyntaxError(stderr)) {
571
- return getModuleSyntaxError();
572
- }
573
- if (isModuleNotFoundError(stderr)) {
574
- return getModuleNotFoundError(stderr);
575
- }
576
- const lines = splitLines(stderr);
577
- const {
578
- actualMessage,
579
- rest
580
- } = getDetails(lines);
614
+ const getErrorResponse = (message, error, preparePrettyError, logError) => {
615
+ const prettyError = preparePrettyError(error);
616
+ logError(error, prettyError);
617
+ const errorProperty = getErrorProperty(error, prettyError);
618
+ return create$1$1(message, errorProperty);
619
+ };
620
+ const create$5 = (message, result) => {
581
621
  return {
582
- message: `${actualMessage}`,
583
- code: '',
584
- stack: rest
622
+ jsonrpc: Two,
623
+ id: message.id,
624
+ result: result ?? null
585
625
  };
586
626
  };
587
- const normalizeLine = line => {
588
- if (line.startsWith('Error: ')) {
589
- return line.slice('Error: '.length);
590
- }
591
- if (line.startsWith('VError: ')) {
592
- return line.slice('VError: '.length);
593
- }
594
- return line;
627
+ const getSuccessResponse = (message, result) => {
628
+ const resultProperty = result ?? null;
629
+ return create$5(message, resultProperty);
595
630
  };
596
- const getCombinedMessage = (error, message) => {
597
- const stringifiedError = normalizeLine(`${error}`);
598
- if (message) {
599
- return `${message}: ${stringifiedError}`;
631
+ const getResponse = async (message, ipc, execute, preparePrettyError, logError, requiresSocket) => {
632
+ try {
633
+ const result = requiresSocket(message.method) ? await execute(message.method, ipc, ...message.params) : await execute(message.method, ...message.params);
634
+ return getSuccessResponse(message, result);
635
+ } catch (error) {
636
+ return getErrorResponse(message, error, preparePrettyError, logError);
600
637
  }
601
- return stringifiedError;
602
638
  };
603
- const NewLine = '\n';
604
- const getNewLineIndex = (string, startIndex = undefined) => {
605
- return string.indexOf(NewLine, startIndex);
639
+ const defaultPreparePrettyError = error => {
640
+ return error;
606
641
  };
607
- const mergeStacks = (parent, child) => {
608
- if (!child) {
609
- return parent;
610
- }
611
- const parentNewLineIndex = getNewLineIndex(parent);
612
- const childNewLineIndex = getNewLineIndex(child);
613
- if (childNewLineIndex === -1) {
614
- return parent;
615
- }
616
- const parentFirstLine = parent.slice(0, parentNewLineIndex);
617
- const childRest = child.slice(childNewLineIndex);
618
- const childFirstLine = normalizeLine(child.slice(0, childNewLineIndex));
619
- if (parentFirstLine.includes(childFirstLine)) {
620
- return parentFirstLine + childRest;
621
- }
622
- return child;
642
+ const defaultLogError = () => {
643
+ // ignore
623
644
  };
624
- class VError extends Error {
625
- constructor(error, message) {
626
- const combinedMessage = getCombinedMessage(error, message);
627
- super(combinedMessage);
628
- this.name = 'VError';
629
- if (error instanceof Error) {
630
- this.stack = mergeStacks(this.stack, error.stack);
631
- }
632
- if (error.codeFrame) {
633
- // @ts-ignore
634
- this.codeFrame = error.codeFrame;
635
- }
636
- if (error.code) {
637
- // @ts-ignore
638
- this.code = error.code;
639
- }
640
- }
641
- }
642
- class IpcError extends VError {
643
- // @ts-ignore
644
- constructor(betterMessage, stdout = '', stderr = '') {
645
- if (stdout || stderr) {
646
- // @ts-ignore
647
- const {
648
- message,
649
- code,
650
- stack
651
- } = getHelpfulChildProcessError(stdout, stderr);
652
- const cause = new Error(message);
653
- // @ts-ignore
654
- cause.code = code;
655
- cause.stack = stack;
656
- super(cause, betterMessage);
657
- } else {
658
- super(betterMessage);
659
- }
660
- // @ts-ignore
661
- this.name = 'IpcError';
662
- // @ts-ignore
663
- this.stdout = stdout;
664
- // @ts-ignore
665
- this.stderr = stderr;
645
+ const defaultRequiresSocket = () => {
646
+ return false;
647
+ };
648
+ const defaultResolve = resolve;
649
+
650
+ // TODO maybe remove this in v6 or v7, only accept options object to simplify the code
651
+ const normalizeParams = args => {
652
+ if (args.length === 1) {
653
+ const options = args[0];
654
+ return {
655
+ ipc: options.ipc,
656
+ message: options.message,
657
+ execute: options.execute,
658
+ resolve: options.resolve || defaultResolve,
659
+ preparePrettyError: options.preparePrettyError || defaultPreparePrettyError,
660
+ logError: options.logError || defaultLogError,
661
+ requiresSocket: options.requiresSocket || defaultRequiresSocket
662
+ };
666
663
  }
667
- }
668
- const withResolvers = () => {
669
- let _resolve;
670
- const promise = new Promise(resolve => {
671
- _resolve = resolve;
672
- });
673
664
  return {
674
- resolve: _resolve,
675
- promise
665
+ ipc: args[0],
666
+ message: args[1],
667
+ execute: args[2],
668
+ resolve: args[3],
669
+ preparePrettyError: args[4],
670
+ logError: args[5],
671
+ requiresSocket: args[6]
676
672
  };
677
673
  };
678
- const waitForFirstMessage = async port => {
674
+ const handleJsonRpcMessage = async (...args) => {
675
+ const options = normalizeParams(args);
679
676
  const {
677
+ message,
678
+ ipc,
679
+ execute,
680
680
  resolve,
681
- promise
682
- } = withResolvers();
683
- port.addEventListener('message', resolve, {
684
- once: true
685
- });
686
- const event = await promise;
687
- // @ts-ignore
688
- return event.data;
689
- };
690
- const listen$1$1 = async () => {
691
- const parentIpcRaw = listen$2();
692
- signal$2(parentIpcRaw);
693
- const parentIpc = wrap$5(parentIpcRaw);
694
- const firstMessage = await waitForFirstMessage(parentIpc);
695
- if (firstMessage.method !== 'initialize') {
696
- throw new IpcError('unexpected first message');
697
- }
698
- const type = firstMessage.params[0];
699
- if (type === 'message-port') {
700
- parentIpc.send({
701
- jsonrpc: '2.0',
702
- id: firstMessage.id,
703
- result: null
704
- });
705
- parentIpc.dispose();
706
- const port = firstMessage.params[1];
707
- return port;
708
- }
709
- return globalThis;
710
- };
711
- class IpcChildWithModuleWorkerAndMessagePort extends Ipc {
712
- constructor(port) {
713
- super(port);
714
- }
715
- getData(event) {
716
- return getData$1(event);
717
- }
718
- send(message) {
719
- this._rawIpc.postMessage(message);
720
- }
721
- sendAndTransfer(message) {
722
- const transfer = getTransferrables(message);
723
- this._rawIpc.postMessage(message, transfer);
724
- }
725
- dispose() {
726
- if (this._rawIpc.close) {
727
- this._rawIpc.close();
681
+ preparePrettyError,
682
+ logError,
683
+ requiresSocket
684
+ } = options;
685
+ if ('id' in message) {
686
+ if ('method' in message) {
687
+ const response = await getResponse(message, ipc, execute, preparePrettyError, logError, requiresSocket);
688
+ try {
689
+ ipc.send(response);
690
+ } catch (error) {
691
+ const errorResponse = getErrorResponse(message, error, preparePrettyError, logError);
692
+ ipc.send(errorResponse);
693
+ }
694
+ return;
728
695
  }
696
+ resolve(message.id, message);
697
+ return;
729
698
  }
730
- onClose(callback) {
731
- // ignore
699
+ if ('method' in message) {
700
+ await getResponse(message, ipc, execute, preparePrettyError, logError, requiresSocket);
701
+ return;
732
702
  }
733
- onMessage(callback) {
734
- this._rawIpc.addEventListener('message', callback);
735
- this._rawIpc.start();
703
+ throw new JsonRpcError('unexpected message');
704
+ };
705
+ const invokeHelper = async (ipc, method, params, useSendAndTransfer) => {
706
+ const {
707
+ message,
708
+ promise
709
+ } = create$2$1(method, params);
710
+ if (useSendAndTransfer && ipc.sendAndTransfer) {
711
+ ipc.sendAndTransfer(message);
712
+ } else {
713
+ ipc.send(message);
736
714
  }
737
- }
738
- const wrap$4 = port => {
739
- return new IpcChildWithModuleWorkerAndMessagePort(port);
715
+ const responseMessage = await promise;
716
+ return unwrapJsonRpcResult(responseMessage);
740
717
  };
741
- const IpcChildWithModuleWorkerAndMessagePort$1 = {
742
- __proto__: null,
743
- listen: listen$1$1,
744
- wrap: wrap$4
718
+ const send$1 = (transport, method, ...params) => {
719
+ const message = create$4(method, params);
720
+ transport.send(message);
721
+ };
722
+ const invoke$1 = (ipc, method, ...params) => {
723
+ return invokeHelper(ipc, method, params, false);
724
+ };
725
+ const invokeAndTransfer$1 = (ipc, method, ...params) => {
726
+ return invokeHelper(ipc, method, params, true);
727
+ };
728
+
729
+ const commands = Object.create(null);
730
+ const register = commandMap => {
731
+ Object.assign(commands, commandMap);
732
+ };
733
+ const getCommand$1 = key => {
734
+ return commands[key];
735
+ };
736
+ const execute$1 = (command, ...args) => {
737
+ const fn = getCommand$1(command);
738
+ if (!fn) {
739
+ throw new Error(`command not found ${command}`);
740
+ }
741
+ return fn(...args);
745
742
  };
746
743
 
747
744
  const createRpc = ipc => {
748
745
  const rpc = {
746
+ // @ts-ignore
747
+ ipc,
749
748
  /**
750
749
  * @deprecated
751
750
  */
@@ -757,6 +756,9 @@ const createRpc = ipc => {
757
756
  },
758
757
  invokeAndTransfer(method, ...params) {
759
758
  return invokeAndTransfer$1(ipc, method, ...params);
759
+ },
760
+ async dispose() {
761
+ await ipc?.dispose();
760
762
  }
761
763
  };
762
764
  return rpc;
@@ -771,32 +773,39 @@ const logError$1 = () => {
771
773
  // handled by renderer worker
772
774
  };
773
775
  const handleMessage$1 = event => {
774
- return handleJsonRpcMessage(event.target, event.data, execute$1, resolve, preparePrettyError$1, logError$1, requiresSocket$1);
776
+ const actualRequiresSocket = event?.target?.requiresSocket || requiresSocket$1;
777
+ const actualExecute = event?.target?.execute || execute$1;
778
+ return handleJsonRpcMessage(event.target, event.data, actualExecute, resolve, preparePrettyError$1, logError$1, actualRequiresSocket);
775
779
  };
776
780
  const handleIpc$1 = ipc => {
777
- ipc.addEventListener('message', handleMessage$1);
781
+ if ('addEventListener' in ipc) {
782
+ ipc.addEventListener('message', handleMessage$1);
783
+ } else if ('on' in ipc) {
784
+ // deprecated
785
+ ipc.on('message', handleMessage$1);
786
+ }
778
787
  };
779
-
780
- // @ts-ignore
781
- const listen$1 = async () => {
782
- const module = IpcChildWithModuleWorkerAndMessagePort$1;
783
- const rawIpc = await module.listen();
788
+ const listen$1 = async (module, options) => {
789
+ const rawIpc = await module.listen(options);
790
+ if (module.signal) {
791
+ module.signal(rawIpc);
792
+ }
784
793
  const ipc = module.wrap(rawIpc);
785
794
  return ipc;
786
795
  };
787
- const create$1$1 = async ({
796
+ const create$2 = async ({
788
797
  commandMap
789
798
  }) => {
790
799
  // TODO create a commandMap per rpc instance
791
800
  register(commandMap);
792
- const ipc = await listen$1();
801
+ const ipc = await listen$1(IpcChildWithModuleWorkerAndMessagePort$1);
793
802
  handleIpc$1(ipc);
794
803
  const rpc = createRpc(ipc);
795
804
  return rpc;
796
805
  };
797
806
  const WebWorkerRpcClient = {
798
807
  __proto__: null,
799
- create: create$1$1
808
+ create: create$2
800
809
  };
801
810
 
802
811
  const state$2 = {