@lvce-editor/embeds-worker 2.0.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.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2024 Lvce Editor
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1 @@
1
+ # embeds-worker
@@ -0,0 +1,1061 @@
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)
11
+ };
12
+ const set = (id, fn) => {
13
+ state$3.callbacks[id] = fn;
14
+ };
15
+ const get = id => {
16
+ return state$3.callbacks[id];
17
+ };
18
+ const remove = id => {
19
+ delete state$3.callbacks[id];
20
+ };
21
+ let id = 0;
22
+ const create$3 = () => {
23
+ return ++id;
24
+ };
25
+ const warn = (...args) => {
26
+ console.warn(...args);
27
+ };
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
+ };
39
+ };
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);
49
+ };
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
+ };
65
+ };
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;
90
+ }
91
+ }
92
+ if (message.startsWith('TypeError: ')) {
93
+ return TypeError;
94
+ }
95
+ if (message.startsWith('SyntaxError: ')) {
96
+ return SyntaxError;
97
+ }
98
+ if (message.startsWith('ReferenceError: ')) {
99
+ return ReferenceError;
100
+ }
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);
107
+ }
108
+ if (ErrorConstructor === Error) {
109
+ const error = new Error(message);
110
+ if (name && name !== 'VError') {
111
+ error.name = name;
112
+ }
113
+ return error;
114
+ }
115
+ return new ErrorConstructor(message);
116
+ };
117
+ const getNewLineIndex$1 = (string, startIndex = undefined) => {
118
+ return string.indexOf(NewLine$2, startIndex);
119
+ };
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;
126
+ };
127
+ const joinLines$1 = lines => {
128
+ return lines.join(NewLine$2);
129
+ };
130
+ const MethodNotFound = -32601;
131
+ const Custom = -32001;
132
+ const splitLines$1 = lines => {
133
+ return lines.split(NewLine$2);
134
+ };
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;
145
+ }
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
+ }
179
+ }
180
+ return restoredError;
181
+ }
182
+ if (typeof error === 'string') {
183
+ return new Error(`JsonRpc Error: ${error}`);
184
+ }
185
+ return new Error(`JsonRpc Error: ${error}`);
186
+ };
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');
196
+ };
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;
204
+ }
205
+ return undefined;
206
+ };
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
+ };
214
+ }
215
+ 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
+ }
225
+ };
226
+ };
227
+ const create$1$2 = (message, error) => {
228
+ return {
229
+ jsonrpc: Two,
230
+ id: message.id,
231
+ error
232
+ };
233
+ };
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) => {
241
+ return {
242
+ jsonrpc: Two,
243
+ id: message.id,
244
+ result: result ?? null
245
+ };
246
+ };
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);
257
+ }
258
+ };
259
+ const defaultPreparePrettyError = error => {
260
+ return error;
261
+ };
262
+ const defaultLogError = () => {
263
+ // ignore
264
+ };
265
+ const defaultRequiresSocket = () => {
266
+ return false;
267
+ };
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
+ };
283
+ }
284
+ 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]
292
+ };
293
+ };
294
+ const handleJsonRpcMessage = async (...args) => {
295
+ const options = normalizeParams(args);
296
+ const {
297
+ message,
298
+ ipc,
299
+ execute,
300
+ 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;
318
+ }
319
+ if ('method' in message) {
320
+ await getResponse(message, ipc, execute, preparePrettyError, logError, requiresSocket);
321
+ return;
322
+ }
323
+ throw new JsonRpcError('unexpected message');
324
+ };
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);
334
+ }
335
+ const responseMessage = await promise;
336
+ return unwrapJsonRpcResult(responseMessage);
337
+ };
338
+ const send$1 = (transport, method, ...params) => {
339
+ const message = create$4(method, params);
340
+ transport.send(message);
341
+ };
342
+ const invoke$1 = (ipc, method, ...params) => {
343
+ return invokeHelper(ipc, method, params, false);
344
+ };
345
+ const invokeAndTransfer$1 = (ipc, method, ...params) => {
346
+ return invokeHelper(ipc, method, params, true);
347
+ };
348
+
349
+ const commands = Object.create(null);
350
+ const register = commandMap => {
351
+ Object.assign(commands, commandMap);
352
+ };
353
+ const getCommand$1 = key => {
354
+ return commands[key];
355
+ };
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);
362
+ };
363
+
364
+ const getData$1 = event => {
365
+ return event.data;
366
+ };
367
+ const attachEvents = that => {
368
+ const handleMessage = (...args) => {
369
+ const data = that.getData(...args);
370
+ that.dispatchEvent(new MessageEvent('message', {
371
+ data
372
+ }));
373
+ };
374
+ that.onMessage(handleMessage);
375
+ const handleClose = event => {
376
+ that.dispatchEvent(new Event('close'));
377
+ };
378
+ that.onClose(handleClose);
379
+ };
380
+ class Ipc extends EventTarget {
381
+ constructor(rawIpc) {
382
+ super();
383
+ this._rawIpc = rawIpc;
384
+ attachEvents(this);
385
+ }
386
+ }
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);
399
+ }
400
+ return;
401
+ }
402
+ if (typeof value === 'object') {
403
+ for (const property of Object.values(value)) {
404
+ walkValue(property, transferrables, isTransferrable);
405
+ }
406
+ return;
407
+ }
408
+ };
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;
429
+ }
430
+ }
431
+ return false;
432
+ };
433
+ const getTransferrables = value => {
434
+ const transferrables = [];
435
+ walkValue(value, transferrables, isTransferrable);
436
+ return transferrables;
437
+ };
438
+ const listen$2 = () => {
439
+ // @ts-ignore
440
+ if (typeof WorkerGlobalScope === 'undefined') {
441
+ throw new TypeError('module is not in web worker scope');
442
+ }
443
+ return globalThis;
444
+ };
445
+ const signal$2 = global => {
446
+ global.postMessage(readyMessage);
447
+ };
448
+ class IpcChildWithModuleWorker extends Ipc {
449
+ getData(event) {
450
+ return getData$1(event);
451
+ }
452
+ send(message) {
453
+ // @ts-ignore
454
+ this._rawIpc.postMessage(message);
455
+ }
456
+ sendAndTransfer(message) {
457
+ const transfer = getTransferrables(message);
458
+ // @ts-ignore
459
+ this._rawIpc.postMessage(message, transfer);
460
+ }
461
+ dispose() {
462
+ // ignore
463
+ }
464
+ onClose(callback) {
465
+ // ignore
466
+ }
467
+ onMessage(callback) {
468
+ this._rawIpc.addEventListener('message', callback);
469
+ }
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;
518
+ };
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
+ };
525
+ };
526
+ const isModulesSyntaxError = stderr => {
527
+ if (!stderr) {
528
+ return false;
529
+ }
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
+ };
537
+ };
538
+ const isModuleNotFoundError = stderr => {
539
+ if (!stderr) {
540
+ return false;
541
+ }
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);
546
+ };
547
+ const getDetails = lines => {
548
+ const index = lines.findIndex(isNormalStackLine);
549
+ if (index === -1) {
550
+ return {
551
+ actualMessage: joinLines(lines),
552
+ rest: []
553
+ };
554
+ }
555
+ let lastIndex = index - 1;
556
+ while (++lastIndex < lines.length) {
557
+ if (!isNormalStackLine(lines[lastIndex])) {
558
+ break;
559
+ }
560
+ }
561
+ return {
562
+ actualMessage: lines[index - 1],
563
+ rest: lines.slice(index, lastIndex)
564
+ };
565
+ };
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);
581
+ return {
582
+ message: `${actualMessage}`,
583
+ code: '',
584
+ stack: rest
585
+ };
586
+ };
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;
595
+ };
596
+ const getCombinedMessage = (error, message) => {
597
+ const stringifiedError = normalizeLine(`${error}`);
598
+ if (message) {
599
+ return `${message}: ${stringifiedError}`;
600
+ }
601
+ return stringifiedError;
602
+ };
603
+ const NewLine = '\n';
604
+ const getNewLineIndex = (string, startIndex = undefined) => {
605
+ return string.indexOf(NewLine, startIndex);
606
+ };
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;
623
+ };
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;
666
+ }
667
+ }
668
+ const withResolvers = () => {
669
+ let _resolve;
670
+ const promise = new Promise(resolve => {
671
+ _resolve = resolve;
672
+ });
673
+ return {
674
+ resolve: _resolve,
675
+ promise
676
+ };
677
+ };
678
+ const waitForFirstMessage = async port => {
679
+ const {
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();
728
+ }
729
+ }
730
+ onClose(callback) {
731
+ // ignore
732
+ }
733
+ onMessage(callback) {
734
+ this._rawIpc.addEventListener('message', callback);
735
+ this._rawIpc.start();
736
+ }
737
+ }
738
+ const wrap$4 = port => {
739
+ return new IpcChildWithModuleWorkerAndMessagePort(port);
740
+ };
741
+ const IpcChildWithModuleWorkerAndMessagePort$1 = {
742
+ __proto__: null,
743
+ listen: listen$1$1,
744
+ wrap: wrap$4
745
+ };
746
+
747
+ const createRpc = ipc => {
748
+ const rpc = {
749
+ /**
750
+ * @deprecated
751
+ */
752
+ send(method, ...params) {
753
+ send$1(ipc, method, ...params);
754
+ },
755
+ invoke(method, ...params) {
756
+ return invoke$1(ipc, method, ...params);
757
+ },
758
+ invokeAndTransfer(method, ...params) {
759
+ return invokeAndTransfer$1(ipc, method, ...params);
760
+ }
761
+ };
762
+ return rpc;
763
+ };
764
+ const requiresSocket$1 = () => {
765
+ return false;
766
+ };
767
+ const preparePrettyError$1 = error => {
768
+ return error;
769
+ };
770
+ const logError$1 = () => {
771
+ // handled by renderer worker
772
+ };
773
+ const handleMessage$1 = event => {
774
+ return handleJsonRpcMessage(event.target, event.data, execute$1, resolve, preparePrettyError$1, logError$1, requiresSocket$1);
775
+ };
776
+ const handleIpc$1 = ipc => {
777
+ ipc.addEventListener('message', handleMessage$1);
778
+ };
779
+
780
+ // @ts-ignore
781
+ const listen$1 = async () => {
782
+ const module = IpcChildWithModuleWorkerAndMessagePort$1;
783
+ const rawIpc = await module.listen();
784
+ const ipc = module.wrap(rawIpc);
785
+ return ipc;
786
+ };
787
+ const create$1$1 = async ({
788
+ commandMap
789
+ }) => {
790
+ // TODO create a commandMap per rpc instance
791
+ register(commandMap);
792
+ const ipc = await listen$1();
793
+ handleIpc$1(ipc);
794
+ const rpc = createRpc(ipc);
795
+ return rpc;
796
+ };
797
+ const WebWorkerRpcClient = {
798
+ __proto__: null,
799
+ create: create$1$1
800
+ };
801
+
802
+ const state$2 = {
803
+ commands: Object.create(null)
804
+ };
805
+ const getCommand = key => {
806
+ return state$2.commands[key];
807
+ };
808
+
809
+ const processName = 'embeds-worker';
810
+
811
+ const execute = (command, ...args) => {
812
+ const fn = getCommand(command);
813
+ if (!fn) {
814
+ throw new Error(`[${processName}] command not found ${command}`);
815
+ }
816
+ return fn(...args);
817
+ };
818
+
819
+ const requiresSocket = () => {
820
+ return false;
821
+ };
822
+ const preparePrettyError = error => {
823
+ return error;
824
+ };
825
+ const logError = error => {
826
+ console.error(error);
827
+ };
828
+ const handleMessage = event => {
829
+ return handleJsonRpcMessage(event.target, event.data, execute, resolve, preparePrettyError, logError, requiresSocket);
830
+ };
831
+ const handleIpc = ipc => {
832
+ ipc.onmessage = handleMessage;
833
+ };
834
+
835
+ const getPortTuple = () => {
836
+ const {
837
+ port1,
838
+ port2
839
+ } = new MessageChannel();
840
+ return {
841
+ port1,
842
+ port2
843
+ };
844
+ };
845
+
846
+ const EmbedsWorker = 77;
847
+
848
+ const state$1 = {
849
+ rpc: undefined
850
+ };
851
+ const send = (method, ...params) => {
852
+ const rpc = state$1.rpc;
853
+ // @ts-ignore
854
+ return rpc.send(method, ...params);
855
+ };
856
+ const invokeAndTransfer = (method, ...params) => {
857
+ const rpc = state$1.rpc;
858
+ // @ts-ignore
859
+ return rpc.invokeAndTransfer(method, ...params);
860
+ };
861
+ const setRpc = rpc => {
862
+ state$1.rpc = rpc;
863
+ };
864
+
865
+ const create$1 = async ({
866
+ initialCommand
867
+ }) => {
868
+ const {
869
+ port1,
870
+ port2
871
+ } = getPortTuple();
872
+ // TODO call sendMessagePortToSharedProcess function instead
873
+ await invokeAndTransfer('IpcParent.create', [port1], {
874
+ method: 8,
875
+ type: 1,
876
+ initialCommand,
877
+ port: port1,
878
+ raw: true,
879
+ ipcId: EmbedsWorker
880
+ });
881
+ return port2;
882
+ };
883
+ const wrap = port => {
884
+ return {
885
+ port,
886
+ send(message) {
887
+ port.postMessage(message);
888
+ },
889
+ set onmessage(listener) {
890
+ const wrappedListener = event => {
891
+ const syntheticEvent = {
892
+ target: this,
893
+ data: event.data
894
+ };
895
+ listener(syntheticEvent);
896
+ };
897
+ this.port.onmessage = wrappedListener;
898
+ },
899
+ dispose() {
900
+ }
901
+ };
902
+ };
903
+
904
+ const create = async options => {
905
+ const rawIpc = await create$1(options);
906
+ const ipc = wrap(rawIpc);
907
+ return ipc;
908
+ };
909
+
910
+ const launchEmbedsProcessIpc = async () => {
911
+ const ipc = await create({
912
+ initialCommand: 'HandleMessagePortForEmbedsProcess.handleMessagePortForEmbedsProcess'
913
+ });
914
+ handleIpc(ipc);
915
+ return ipc;
916
+ };
917
+
918
+ const state = {
919
+ workerPromise: undefined
920
+ };
921
+ const getOrCreate = () => {
922
+ state.workerPromise ||= launchEmbedsProcessIpc();
923
+ return state.workerPromise;
924
+ };
925
+ const invoke = async (method, ...params) => {
926
+ const ipc = await getOrCreate();
927
+ return invoke$1(ipc, method, ...params);
928
+ };
929
+
930
+ const ERR_ABORTED = 'ERR_ABORTED';
931
+ const ERR_FAILED = 'ERR_FAILED';
932
+
933
+ const createWebContentsView = async (restoreId, fallThroughKeyBindings) => {
934
+ const id = await invoke('ElectronWebContentsView.createWebContentsView', restoreId, fallThroughKeyBindings);
935
+ return id;
936
+ };
937
+ const disposeWebContentsView = id => {
938
+ return invoke('ElectronWebContentsView.disposeWebContentsView', id);
939
+ };
940
+ const resizeWebContentsView = (id, x, y, width, height) => {
941
+ return invoke('ElectronWebContentsView.resizeBrowserView', id, x, y, width, height);
942
+ };
943
+ const setIframeSrcFallback = async (id, error) => {
944
+ const {
945
+ code,
946
+ message
947
+ } = error;
948
+ await invoke('ElectronWebContentsView.setIframeSrcFallback', id, code, message);
949
+ };
950
+ const setIframeSrc = async (id, iframeSrc) => {
951
+ try {
952
+ await invoke('ElectronWebContentsView.setIframeSrc', id, iframeSrc);
953
+ } catch (error) {
954
+ console.log({
955
+ error
956
+ });
957
+ // TODO send error back to embeds worker,
958
+ // embeds worker decides how to handle error
959
+ // @ts-ignore
960
+ if (error && error.code === ERR_ABORTED) {
961
+ console.info(`[embeds worker] navigation to ${iframeSrc} aborted`);
962
+ return;
963
+ }
964
+ // @ts-ignore
965
+ if (error && error.code === ERR_FAILED) {
966
+ console.info(`[embeds worker] navigation to ${iframeSrc} canceled`);
967
+ // ElectronWebContentsViewState.removeCanceled(webContents.id)
968
+ return;
969
+ }
970
+ try {
971
+ await setIframeSrcFallback(id, error);
972
+ } catch (error) {
973
+ console.warn(`Failed to set iframe src`, error);
974
+ }
975
+ }
976
+ };
977
+ const focus = id => {
978
+ return invoke('ElectronWebContentsView.focus', id);
979
+ };
980
+ const openDevtools = id => {
981
+ return invoke('ElectronWebContentsView.openDevtools', id);
982
+ };
983
+ const reload = id => {
984
+ return invoke('ElectronWebContentsView.reload', id);
985
+ };
986
+ const show = id => {
987
+ return invoke('ElectronWebContentsView.show', id);
988
+ };
989
+ const hide = id => {
990
+ return invoke('ElectronWebContentsView.hide', id);
991
+ };
992
+ const forward = id => {
993
+ return invoke('ElectronWebContentsView.forward', id);
994
+ };
995
+ const backward = id => {
996
+ return invoke('ElectronWebContentsView.backward', id);
997
+ };
998
+ const cancelNavigation = id => {
999
+ return invoke('ElectronWebContentsView.cancelNavigation', id);
1000
+ };
1001
+ const inspectElement = (id, x, y) => {
1002
+ return invoke('ElectronWebContentsView.inspectElement', id, x, y);
1003
+ };
1004
+ const copyImageAt = (id, x, y) => {
1005
+ return invoke('ElectronWebContentsView.copyImageAt', id, x, y);
1006
+ };
1007
+ const setFallthroughKeyBindings = (id, fallthroughKeybindings) => {
1008
+ // TODO
1009
+ // return EmbedsProcess.invoke('ElectronWebContentsView.setFallthroughKeyBindings', id, fallthroughKeybindings)
1010
+ };
1011
+ const getStats = (id, fallthroughKeybindings) => {
1012
+ return invoke('ElectronWebContentsView.getStats', id, fallthroughKeybindings);
1013
+ };
1014
+ const forwardEvent = key => (id, ...args) => {
1015
+ send(key, ...args);
1016
+ };
1017
+ const handleDidNavigate = forwardEvent('ElectronBrowserView.handleDidNavigate');
1018
+ const handleTitleUpdated = forwardEvent('ElectronBrowserView.handleTitleUpdated');
1019
+ const handleWillNavigate = forwardEvent('ElectronBrowserView.handleWillNavigate');
1020
+ const handleContextMenu = forwardEvent('ElectronBrowserView.handleContextMenu');
1021
+
1022
+ const exit = () => {
1023
+ self.close();
1024
+ };
1025
+
1026
+ const commandMap = {
1027
+ 'ElectronWebContentsView.backward': backward,
1028
+ 'ElectronWebContentsView.cancelNavigation': cancelNavigation,
1029
+ 'ElectronWebContentsView.copyImageAt': copyImageAt,
1030
+ 'ElectronWebContentsView.createWebContentsView': createWebContentsView,
1031
+ 'ElectronWebContentsView.disposeWebContentsView': disposeWebContentsView,
1032
+ 'ElectronWebContentsView.focus': focus,
1033
+ 'ElectronWebContentsView.forward': forward,
1034
+ 'ElectronWebContentsView.getStats': getStats,
1035
+ 'ElectronWebContentsView.handleContextMenu': handleContextMenu,
1036
+ 'ElectronWebContentsView.handleDidNavigate': handleDidNavigate,
1037
+ 'ElectronWebContentsView.handleTitleUpdated': handleTitleUpdated,
1038
+ 'ElectronWebContentsView.handleWillNavigate': handleWillNavigate,
1039
+ 'ElectronWebContentsView.hide': hide,
1040
+ 'ElectronWebContentsView.inspectElement': inspectElement,
1041
+ 'ElectronWebContentsView.openDevtools': openDevtools,
1042
+ 'ElectronWebContentsView.reload': reload,
1043
+ 'ElectronWebContentsView.resizeWebContentsView': resizeWebContentsView,
1044
+ 'ElectronWebContentsView.setFallthroughKeyBindings': setFallthroughKeyBindings,
1045
+ 'ElectronWebContentsView.setIframeSrc': setIframeSrc,
1046
+ 'ElectronWebContentsView.show': show,
1047
+ 'Exit.exit': exit
1048
+ };
1049
+
1050
+ const listen = async () => {
1051
+ const rpc = await WebWorkerRpcClient.create({
1052
+ commandMap: commandMap
1053
+ });
1054
+ setRpc(rpc);
1055
+ };
1056
+
1057
+ const main = async () => {
1058
+ await listen();
1059
+ };
1060
+
1061
+ main();
package/package.json ADDED
@@ -0,0 +1,10 @@
1
+ {
2
+ "name": "@lvce-editor/embeds-worker",
3
+ "version": "2.0.0",
4
+ "description": "",
5
+ "main": "dist/embedsWorkerMain.js",
6
+ "type": "module",
7
+ "keywords": [],
8
+ "author": "",
9
+ "license": "MIT"
10
+ }