@lvce-editor/chat-storage-worker 1.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) 2025 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,3 @@
1
+ # Chat Storage Worker
2
+
3
+ WebWorker for the Chat Storage functionality in Lvce Editor.
@@ -0,0 +1,912 @@
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;
9
+ };
10
+ const getCombinedMessage = (error, message) => {
11
+ const stringifiedError = normalizeLine(`${error}`);
12
+ if (message) {
13
+ return `${message}: ${stringifiedError}`;
14
+ }
15
+ return stringifiedError;
16
+ };
17
+ const NewLine$2 = '\n';
18
+ const getNewLineIndex$1 = (string, startIndex = undefined) => {
19
+ return string.indexOf(NewLine$2, startIndex);
20
+ };
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;
37
+ };
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;
59
+ };
60
+ const isMessagePortMain = value => {
61
+ return value && value.constructor && value.constructor.name === 'MessagePortMain';
62
+ };
63
+ const isOffscreenCanvas = value => {
64
+ return typeof OffscreenCanvas !== 'undefined' && value instanceof OffscreenCanvas;
65
+ };
66
+ const isInstanceOf = (value, constructorName) => {
67
+ return value?.constructor?.name === constructorName;
68
+ };
69
+ const isSocket = value => {
70
+ return isInstanceOf(value, 'Socket');
71
+ };
72
+ const transferrables = [isMessagePort, isMessagePortMain, isOffscreenCanvas, isSocket];
73
+ const isTransferrable = value => {
74
+ for (const fn of transferrables) {
75
+ if (fn(value)) {
76
+ return true;
77
+ }
78
+ }
79
+ return false;
80
+ };
81
+ const walkValue = (value, transferrables, isTransferrable) => {
82
+ if (!value) {
83
+ return;
84
+ }
85
+ if (isTransferrable(value)) {
86
+ transferrables.push(value);
87
+ return;
88
+ }
89
+ if (Array.isArray(value)) {
90
+ for (const item of value) {
91
+ walkValue(item, transferrables, isTransferrable);
92
+ }
93
+ return;
94
+ }
95
+ if (typeof value === 'object') {
96
+ for (const property of Object.values(value)) {
97
+ walkValue(property, transferrables, isTransferrable);
98
+ }
99
+ return;
100
+ }
101
+ };
102
+ const getTransferrables = value => {
103
+ const transferrables = [];
104
+ walkValue(value, transferrables, isTransferrable);
105
+ return transferrables;
106
+ };
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);
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';
131
+ const joinLines$1 = lines => {
132
+ return lines.join(NewLine$1);
133
+ };
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);
138
+ };
139
+ const getDetails = lines => {
140
+ const index = lines.findIndex(isNormalStackLine);
141
+ if (index === -1) {
142
+ return {
143
+ actualMessage: joinLines$1(lines),
144
+ rest: []
145
+ };
146
+ }
147
+ let lastIndex = index - 1;
148
+ while (++lastIndex < lines.length) {
149
+ if (!isNormalStackLine(lines[lastIndex])) {
150
+ break;
151
+ }
152
+ }
153
+ return {
154
+ actualMessage: lines[index - 1],
155
+ rest: lines.slice(index, lastIndex)
156
+ };
157
+ };
158
+ const splitLines$1 = lines => {
159
+ return lines.split(NewLine$1);
160
+ };
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
+ code: ERR_MODULE_NOT_FOUND,
186
+ message
187
+ };
188
+ };
189
+ const isModuleNotFoundError = stderr => {
190
+ if (!stderr) {
191
+ return false;
192
+ }
193
+ return stderr.includes('ERR_MODULE_NOT_FOUND');
194
+ };
195
+ const isModulesSyntaxError = stderr => {
196
+ if (!stderr) {
197
+ return false;
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);
208
+ return {
209
+ code: E_INCOMPATIBLE_NATIVE_MODULE,
210
+ message: `Incompatible native node module: ${message}`
211
+ };
212
+ };
213
+ const getModuleSyntaxError = () => {
214
+ return {
215
+ code: E_MODULES_NOT_SUPPORTED_IN_ELECTRON,
216
+ message: `ES Modules are not supported in electron`
217
+ };
218
+ };
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);
234
+ return {
235
+ code: '',
236
+ message: actualMessage,
237
+ stack: rest
238
+ };
239
+ };
240
+ class IpcError extends VError {
241
+ // @ts-ignore
242
+ constructor(betterMessage, stdout = '', stderr = '') {
243
+ if (stdout || stderr) {
244
+ // @ts-ignore
245
+ const {
246
+ code,
247
+ message,
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;
264
+ }
265
+ }
266
+ const readyMessage = 'ready';
267
+ const getData$2 = event => {
268
+ return event.data;
269
+ };
270
+ const listen$8 = ({
271
+ port
272
+ }) => {
273
+ return port;
274
+ };
275
+ const signal$9 = port => {
276
+ port.postMessage(readyMessage);
277
+ };
278
+ class IpcChildWithMessagePort extends Ipc {
279
+ getData(event) {
280
+ return getData$2(event);
281
+ }
282
+ send(message) {
283
+ this._rawIpc.postMessage(message);
284
+ }
285
+ sendAndTransfer(message) {
286
+ const transfer = getTransferrables(message);
287
+ this._rawIpc.postMessage(message, transfer);
288
+ }
289
+ dispose() {
290
+ // ignore
291
+ }
292
+ onClose(callback) {
293
+ // ignore
294
+ }
295
+ onMessage(callback) {
296
+ this._rawIpc.addEventListener('message', callback);
297
+ this._rawIpc.start();
298
+ }
299
+ }
300
+ const wrap$g = port => {
301
+ return new IpcChildWithMessagePort(port);
302
+ };
303
+ const IpcChildWithMessagePort$1 = {
304
+ __proto__: null,
305
+ listen: listen$8,
306
+ signal: signal$9,
307
+ wrap: wrap$g
308
+ };
309
+ const listen$7 = () => {
310
+ // @ts-ignore
311
+ if (typeof WorkerGlobalScope === 'undefined') {
312
+ throw new TypeError('module is not in web worker scope');
313
+ }
314
+ return globalThis;
315
+ };
316
+ const signal$8 = global => {
317
+ global.postMessage(readyMessage);
318
+ };
319
+ class IpcChildWithModuleWorker extends Ipc {
320
+ getData(event) {
321
+ return getData$2(event);
322
+ }
323
+ send(message) {
324
+ // @ts-ignore
325
+ this._rawIpc.postMessage(message);
326
+ }
327
+ sendAndTransfer(message) {
328
+ const transfer = getTransferrables(message);
329
+ // @ts-ignore
330
+ this._rawIpc.postMessage(message, transfer);
331
+ }
332
+ dispose() {
333
+ // ignore
334
+ }
335
+ onClose(callback) {
336
+ // ignore
337
+ }
338
+ onMessage(callback) {
339
+ this._rawIpc.addEventListener('message', callback);
340
+ }
341
+ }
342
+ const wrap$f = global => {
343
+ return new IpcChildWithModuleWorker(global);
344
+ };
345
+ const waitForFirstMessage = async port => {
346
+ const {
347
+ promise,
348
+ resolve
349
+ } = Promise.withResolvers();
350
+ port.addEventListener('message', resolve, {
351
+ once: true
352
+ });
353
+ const event = await promise;
354
+ // @ts-ignore
355
+ return event.data;
356
+ };
357
+ const listen$6 = async () => {
358
+ const parentIpcRaw = listen$7();
359
+ signal$8(parentIpcRaw);
360
+ const parentIpc = wrap$f(parentIpcRaw);
361
+ const firstMessage = await waitForFirstMessage(parentIpc);
362
+ if (firstMessage.method !== 'initialize') {
363
+ throw new IpcError('unexpected first message');
364
+ }
365
+ const type = firstMessage.params[0];
366
+ if (type === 'message-port') {
367
+ parentIpc.send({
368
+ id: firstMessage.id,
369
+ jsonrpc: '2.0',
370
+ result: null
371
+ });
372
+ parentIpc.dispose();
373
+ const port = firstMessage.params[1];
374
+ return port;
375
+ }
376
+ return globalThis;
377
+ };
378
+ class IpcChildWithModuleWorkerAndMessagePort extends Ipc {
379
+ getData(event) {
380
+ return getData$2(event);
381
+ }
382
+ send(message) {
383
+ this._rawIpc.postMessage(message);
384
+ }
385
+ sendAndTransfer(message) {
386
+ const transfer = getTransferrables(message);
387
+ this._rawIpc.postMessage(message, transfer);
388
+ }
389
+ dispose() {
390
+ if (this._rawIpc.close) {
391
+ this._rawIpc.close();
392
+ }
393
+ }
394
+ onClose(callback) {
395
+ // ignore
396
+ }
397
+ onMessage(callback) {
398
+ this._rawIpc.addEventListener('message', callback);
399
+ this._rawIpc.start();
400
+ }
401
+ }
402
+ const wrap$e = port => {
403
+ return new IpcChildWithModuleWorkerAndMessagePort(port);
404
+ };
405
+ const IpcChildWithModuleWorkerAndMessagePort$1 = {
406
+ __proto__: null,
407
+ listen: listen$6,
408
+ wrap: wrap$e
409
+ };
410
+
411
+ class CommandNotFoundError extends Error {
412
+ constructor(command) {
413
+ super(`Command not found ${command}`);
414
+ this.name = 'CommandNotFoundError';
415
+ }
416
+ }
417
+ const commands = Object.create(null);
418
+ const register = commandMap => {
419
+ Object.assign(commands, commandMap);
420
+ };
421
+ const getCommand = key => {
422
+ return commands[key];
423
+ };
424
+ const execute = (command, ...args) => {
425
+ const fn = getCommand(command);
426
+ if (!fn) {
427
+ throw new CommandNotFoundError(command);
428
+ }
429
+ return fn(...args);
430
+ };
431
+
432
+ const Two$1 = '2.0';
433
+ const callbacks = Object.create(null);
434
+ const get = id => {
435
+ return callbacks[id];
436
+ };
437
+ const remove = id => {
438
+ delete callbacks[id];
439
+ };
440
+ class JsonRpcError extends Error {
441
+ constructor(message) {
442
+ super(message);
443
+ this.name = 'JsonRpcError';
444
+ }
445
+ }
446
+ const NewLine = '\n';
447
+ const DomException = 'DOMException';
448
+ const ReferenceError$1 = 'ReferenceError';
449
+ const SyntaxError$1 = 'SyntaxError';
450
+ const TypeError$1 = 'TypeError';
451
+ const getErrorConstructor = (message, type) => {
452
+ if (type) {
453
+ switch (type) {
454
+ case DomException:
455
+ return DOMException;
456
+ case ReferenceError$1:
457
+ return ReferenceError;
458
+ case SyntaxError$1:
459
+ return SyntaxError;
460
+ case TypeError$1:
461
+ return TypeError;
462
+ default:
463
+ return Error;
464
+ }
465
+ }
466
+ if (message.startsWith('TypeError: ')) {
467
+ return TypeError;
468
+ }
469
+ if (message.startsWith('SyntaxError: ')) {
470
+ return SyntaxError;
471
+ }
472
+ if (message.startsWith('ReferenceError: ')) {
473
+ return ReferenceError;
474
+ }
475
+ return Error;
476
+ };
477
+ const constructError = (message, type, name) => {
478
+ const ErrorConstructor = getErrorConstructor(message, type);
479
+ if (ErrorConstructor === DOMException && name) {
480
+ return new ErrorConstructor(message, name);
481
+ }
482
+ if (ErrorConstructor === Error) {
483
+ const error = new Error(message);
484
+ if (name && name !== 'VError') {
485
+ error.name = name;
486
+ }
487
+ return error;
488
+ }
489
+ return new ErrorConstructor(message);
490
+ };
491
+ const joinLines = lines => {
492
+ return lines.join(NewLine);
493
+ };
494
+ const splitLines = lines => {
495
+ return lines.split(NewLine);
496
+ };
497
+ const getCurrentStack = () => {
498
+ const stackLinesToSkip = 3;
499
+ const currentStack = joinLines(splitLines(new Error().stack || '').slice(stackLinesToSkip));
500
+ return currentStack;
501
+ };
502
+ const getNewLineIndex = (string, startIndex = undefined) => {
503
+ return string.indexOf(NewLine, startIndex);
504
+ };
505
+ const getParentStack = error => {
506
+ let parentStack = error.stack || error.data || error.message || '';
507
+ if (parentStack.startsWith(' at')) {
508
+ parentStack = error.message + NewLine + parentStack;
509
+ }
510
+ return parentStack;
511
+ };
512
+ const MethodNotFound = -32601;
513
+ const Custom = -32001;
514
+ const restoreJsonRpcError = error => {
515
+ const currentStack = getCurrentStack();
516
+ if (error && error instanceof Error) {
517
+ if (typeof error.stack === 'string') {
518
+ error.stack = error.stack + NewLine + currentStack;
519
+ }
520
+ return error;
521
+ }
522
+ if (error && error.code && error.code === MethodNotFound) {
523
+ const restoredError = new JsonRpcError(error.message);
524
+ const parentStack = getParentStack(error);
525
+ restoredError.stack = parentStack + NewLine + currentStack;
526
+ return restoredError;
527
+ }
528
+ if (error && error.message) {
529
+ const restoredError = constructError(error.message, error.type, error.name);
530
+ if (error.data) {
531
+ if (error.data.stack && error.data.type && error.message) {
532
+ restoredError.stack = error.data.type + ': ' + error.message + NewLine + error.data.stack + NewLine + currentStack;
533
+ } else if (error.data.stack) {
534
+ restoredError.stack = error.data.stack;
535
+ }
536
+ if (error.data.codeFrame) {
537
+ // @ts-ignore
538
+ restoredError.codeFrame = error.data.codeFrame;
539
+ }
540
+ if (error.data.code) {
541
+ // @ts-ignore
542
+ restoredError.code = error.data.code;
543
+ }
544
+ if (error.data.type) {
545
+ // @ts-ignore
546
+ restoredError.name = error.data.type;
547
+ }
548
+ } else {
549
+ if (error.stack) {
550
+ const lowerStack = restoredError.stack || '';
551
+ // @ts-ignore
552
+ const indexNewLine = getNewLineIndex(lowerStack);
553
+ const parentStack = getParentStack(error);
554
+ // @ts-ignore
555
+ restoredError.stack = parentStack + lowerStack.slice(indexNewLine);
556
+ }
557
+ if (error.codeFrame) {
558
+ // @ts-ignore
559
+ restoredError.codeFrame = error.codeFrame;
560
+ }
561
+ }
562
+ return restoredError;
563
+ }
564
+ if (typeof error === 'string') {
565
+ return new Error(`JsonRpc Error: ${error}`);
566
+ }
567
+ return new Error(`JsonRpc Error: ${error}`);
568
+ };
569
+ const unwrapJsonRpcResult = responseMessage => {
570
+ if ('error' in responseMessage) {
571
+ const restoredError = restoreJsonRpcError(responseMessage.error);
572
+ throw restoredError;
573
+ }
574
+ if ('result' in responseMessage) {
575
+ return responseMessage.result;
576
+ }
577
+ throw new JsonRpcError('unexpected response message');
578
+ };
579
+ const warn = (...args) => {
580
+ console.warn(...args);
581
+ };
582
+ const resolve = (id, response) => {
583
+ const fn = get(id);
584
+ if (!fn) {
585
+ console.log(response);
586
+ warn(`callback ${id} may already be disposed`);
587
+ return;
588
+ }
589
+ fn(response);
590
+ remove(id);
591
+ };
592
+ const E_COMMAND_NOT_FOUND = 'E_COMMAND_NOT_FOUND';
593
+ const getErrorType = prettyError => {
594
+ if (prettyError && prettyError.type) {
595
+ return prettyError.type;
596
+ }
597
+ if (prettyError && prettyError.constructor && prettyError.constructor.name) {
598
+ return prettyError.constructor.name;
599
+ }
600
+ return undefined;
601
+ };
602
+ const isAlreadyStack = line => {
603
+ return line.trim().startsWith('at ');
604
+ };
605
+ const getStack = prettyError => {
606
+ const stackString = prettyError.stack || '';
607
+ const newLineIndex = stackString.indexOf('\n');
608
+ if (newLineIndex !== -1 && !isAlreadyStack(stackString.slice(0, newLineIndex))) {
609
+ return stackString.slice(newLineIndex + 1);
610
+ }
611
+ return stackString;
612
+ };
613
+ const getErrorProperty = (error, prettyError) => {
614
+ if (error && error.code === E_COMMAND_NOT_FOUND) {
615
+ return {
616
+ code: MethodNotFound,
617
+ data: error.stack,
618
+ message: error.message
619
+ };
620
+ }
621
+ return {
622
+ code: Custom,
623
+ data: {
624
+ code: prettyError.code,
625
+ codeFrame: prettyError.codeFrame,
626
+ name: prettyError.name,
627
+ stack: getStack(prettyError),
628
+ type: getErrorType(prettyError)
629
+ },
630
+ message: prettyError.message
631
+ };
632
+ };
633
+ const create$1$1 = (id, error) => {
634
+ return {
635
+ error,
636
+ id,
637
+ jsonrpc: Two$1
638
+ };
639
+ };
640
+ const getErrorResponse = (id, error, preparePrettyError, logError) => {
641
+ const prettyError = preparePrettyError(error);
642
+ logError(error, prettyError);
643
+ const errorProperty = getErrorProperty(error, prettyError);
644
+ return create$1$1(id, errorProperty);
645
+ };
646
+ const create$5 = (message, result) => {
647
+ return {
648
+ id: message.id,
649
+ jsonrpc: Two$1,
650
+ result: result ?? null
651
+ };
652
+ };
653
+ const getSuccessResponse = (message, result) => {
654
+ const resultProperty = result ?? null;
655
+ return create$5(message, resultProperty);
656
+ };
657
+ const getErrorResponseSimple = (id, error) => {
658
+ return {
659
+ error: {
660
+ code: Custom,
661
+ data: error,
662
+ // @ts-ignore
663
+ message: error.message
664
+ },
665
+ id,
666
+ jsonrpc: Two$1
667
+ };
668
+ };
669
+ const getResponse = async (message, ipc, execute, preparePrettyError, logError, requiresSocket) => {
670
+ try {
671
+ const result = requiresSocket(message.method) ? await execute(message.method, ipc, ...message.params) : await execute(message.method, ...message.params);
672
+ return getSuccessResponse(message, result);
673
+ } catch (error) {
674
+ if (ipc.canUseSimpleErrorResponse) {
675
+ return getErrorResponseSimple(message.id, error);
676
+ }
677
+ return getErrorResponse(message.id, error, preparePrettyError, logError);
678
+ }
679
+ };
680
+ const defaultPreparePrettyError = error => {
681
+ return error;
682
+ };
683
+ const defaultLogError = () => {
684
+ // ignore
685
+ };
686
+ const defaultRequiresSocket = () => {
687
+ return false;
688
+ };
689
+ const defaultResolve = resolve;
690
+
691
+ // TODO maybe remove this in v6 or v7, only accept options object to simplify the code
692
+ const normalizeParams = args => {
693
+ if (args.length === 1) {
694
+ const options = args[0];
695
+ return {
696
+ execute: options.execute,
697
+ ipc: options.ipc,
698
+ logError: options.logError || defaultLogError,
699
+ message: options.message,
700
+ preparePrettyError: options.preparePrettyError || defaultPreparePrettyError,
701
+ requiresSocket: options.requiresSocket || defaultRequiresSocket,
702
+ resolve: options.resolve || defaultResolve
703
+ };
704
+ }
705
+ return {
706
+ execute: args[2],
707
+ ipc: args[0],
708
+ logError: args[5],
709
+ message: args[1],
710
+ preparePrettyError: args[4],
711
+ requiresSocket: args[6],
712
+ resolve: args[3]
713
+ };
714
+ };
715
+ const handleJsonRpcMessage = async (...args) => {
716
+ const options = normalizeParams(args);
717
+ const {
718
+ execute,
719
+ ipc,
720
+ logError,
721
+ message,
722
+ preparePrettyError,
723
+ requiresSocket,
724
+ resolve
725
+ } = options;
726
+ if ('id' in message) {
727
+ if ('method' in message) {
728
+ const response = await getResponse(message, ipc, execute, preparePrettyError, logError, requiresSocket);
729
+ try {
730
+ ipc.send(response);
731
+ } catch (error) {
732
+ const errorResponse = getErrorResponse(message.id, error, preparePrettyError, logError);
733
+ ipc.send(errorResponse);
734
+ }
735
+ return;
736
+ }
737
+ resolve(message.id, message);
738
+ return;
739
+ }
740
+ if ('method' in message) {
741
+ await getResponse(message, ipc, execute, preparePrettyError, logError, requiresSocket);
742
+ return;
743
+ }
744
+ throw new JsonRpcError('unexpected message');
745
+ };
746
+
747
+ const Two = '2.0';
748
+
749
+ const create$4 = (method, params) => {
750
+ return {
751
+ jsonrpc: Two,
752
+ method,
753
+ params
754
+ };
755
+ };
756
+
757
+ const create$3 = (id, method, params) => {
758
+ const message = {
759
+ id,
760
+ jsonrpc: Two,
761
+ method,
762
+ params
763
+ };
764
+ return message;
765
+ };
766
+
767
+ let id = 0;
768
+ const create$2 = () => {
769
+ return ++id;
770
+ };
771
+
772
+ const registerPromise = map => {
773
+ const id = create$2();
774
+ const {
775
+ promise,
776
+ resolve
777
+ } = Promise.withResolvers();
778
+ map[id] = resolve;
779
+ return {
780
+ id,
781
+ promise
782
+ };
783
+ };
784
+
785
+ const invokeHelper = async (callbacks, ipc, method, params, useSendAndTransfer) => {
786
+ const {
787
+ id,
788
+ promise
789
+ } = registerPromise(callbacks);
790
+ const message = create$3(id, method, params);
791
+ if (useSendAndTransfer && ipc.sendAndTransfer) {
792
+ ipc.sendAndTransfer(message);
793
+ } else {
794
+ ipc.send(message);
795
+ }
796
+ const responseMessage = await promise;
797
+ return unwrapJsonRpcResult(responseMessage);
798
+ };
799
+ const createRpc = ipc => {
800
+ const callbacks = Object.create(null);
801
+ ipc._resolve = (id, response) => {
802
+ const fn = callbacks[id];
803
+ if (!fn) {
804
+ console.warn(`callback ${id} may already be disposed`);
805
+ return;
806
+ }
807
+ fn(response);
808
+ delete callbacks[id];
809
+ };
810
+ const rpc = {
811
+ async dispose() {
812
+ await ipc?.dispose();
813
+ },
814
+ invoke(method, ...params) {
815
+ return invokeHelper(callbacks, ipc, method, params, false);
816
+ },
817
+ invokeAndTransfer(method, ...params) {
818
+ return invokeHelper(callbacks, ipc, method, params, true);
819
+ },
820
+ // @ts-ignore
821
+ ipc,
822
+ /**
823
+ * @deprecated
824
+ */
825
+ send(method, ...params) {
826
+ const message = create$4(method, params);
827
+ ipc.send(message);
828
+ }
829
+ };
830
+ return rpc;
831
+ };
832
+
833
+ const requiresSocket = () => {
834
+ return false;
835
+ };
836
+ const preparePrettyError = error => {
837
+ return error;
838
+ };
839
+ const logError = () => {
840
+ // handled by renderer worker
841
+ };
842
+ const handleMessage = event => {
843
+ const actualRequiresSocket = event?.target?.requiresSocket || requiresSocket;
844
+ const actualExecute = event?.target?.execute || execute;
845
+ return handleJsonRpcMessage(event.target, event.data, actualExecute, event.target._resolve, preparePrettyError, logError, actualRequiresSocket);
846
+ };
847
+
848
+ const handleIpc = ipc => {
849
+ if ('addEventListener' in ipc) {
850
+ ipc.addEventListener('message', handleMessage);
851
+ } else if ('on' in ipc) {
852
+ // deprecated
853
+ ipc.on('message', handleMessage);
854
+ }
855
+ };
856
+
857
+ const listen$1 = async (module, options) => {
858
+ const rawIpc = await module.listen(options);
859
+ if (module.signal) {
860
+ module.signal(rawIpc);
861
+ }
862
+ const ipc = module.wrap(rawIpc);
863
+ return ipc;
864
+ };
865
+
866
+ const create$1 = async ({
867
+ commandMap,
868
+ messagePort
869
+ }) => {
870
+ // TODO create a commandMap per rpc instance
871
+ register(commandMap);
872
+ const ipc = await listen$1(IpcChildWithMessagePort$1, {
873
+ port: messagePort
874
+ });
875
+ handleIpc(ipc);
876
+ const rpc = createRpc(ipc);
877
+ return rpc;
878
+ };
879
+
880
+ const create = async ({
881
+ commandMap
882
+ }) => {
883
+ // TODO create a commandMap per rpc instance
884
+ register(commandMap);
885
+ const ipc = await listen$1(IpcChildWithModuleWorkerAndMessagePort$1);
886
+ handleIpc(ipc);
887
+ const rpc = createRpc(ipc);
888
+ return rpc;
889
+ };
890
+
891
+ const handleMessagePort = async port => {
892
+ await create$1({
893
+ commandMap: commandMap,
894
+ messagePort: port
895
+ });
896
+ };
897
+
898
+ const commandMap = {
899
+ 'HandleMessagePort.handleMessagePort': handleMessagePort
900
+ };
901
+
902
+ const listen = async () => {
903
+ await create({
904
+ commandMap: commandMap
905
+ });
906
+ };
907
+
908
+ const main = async () => {
909
+ await listen();
910
+ };
911
+
912
+ main();
package/package.json ADDED
@@ -0,0 +1,13 @@
1
+ {
2
+ "name": "@lvce-editor/chat-storage-worker",
3
+ "version": "1.0.0",
4
+ "description": "Chat Storage Worker",
5
+ "repository": {
6
+ "type": "git",
7
+ "url": "git+https://github.com/lvce-editor/chat-storage-worker.git"
8
+ },
9
+ "license": "MIT",
10
+ "author": "Lvce Editor",
11
+ "type": "module",
12
+ "main": "dist/chatStorageWorkerMain.js"
13
+ }