@lvce-editor/typescript-compile-process 3.2.0 → 4.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/README.md CHANGED
@@ -1,3 +1,5 @@
1
1
  # typescript-compile-process
2
2
 
3
3
  TypeScript compile process
4
+
5
+ <!-- -->
File without changes
package/dist/index.js CHANGED
@@ -1,8 +1,1150 @@
1
- import { object, string } from '@lvce-editor/assert';
2
- import { WebSocketRpcParent, ElectronMessagePortRpcClient, ElectronUtilityProcessRpcClient, NodeForkedProcessRpcClient } from '@lvce-editor/rpc';
3
- import { VError } from '@lvce-editor/verror';
4
1
  import { readFile, writeFile } from 'node:fs/promises';
5
2
 
3
+ class AssertionError extends Error {
4
+ constructor(message) {
5
+ super(message);
6
+ this.name = 'AssertionError';
7
+ }
8
+ }
9
+ const Object$1 = 1;
10
+ const Number = 2;
11
+ const Array$1 = 3;
12
+ const String = 4;
13
+ const Boolean = 5;
14
+ const Function = 6;
15
+ const Null = 7;
16
+ const Unknown = 8;
17
+ const getType = value => {
18
+ switch (typeof value) {
19
+ case 'number':
20
+ return Number;
21
+ case 'function':
22
+ return Function;
23
+ case 'string':
24
+ return String;
25
+ case 'object':
26
+ if (value === null) {
27
+ return Null;
28
+ }
29
+ if (Array.isArray(value)) {
30
+ return Array$1;
31
+ }
32
+ return Object$1;
33
+ case 'boolean':
34
+ return Boolean;
35
+ default:
36
+ return Unknown;
37
+ }
38
+ };
39
+ const object = value => {
40
+ const type = getType(value);
41
+ if (type !== Object$1) {
42
+ throw new AssertionError('expected value to be of type object');
43
+ }
44
+ };
45
+ const string = value => {
46
+ const type = getType(value);
47
+ if (type !== String) {
48
+ throw new AssertionError('expected value to be of type string');
49
+ }
50
+ };
51
+
52
+ const normalizeLine = line => {
53
+ if (line.startsWith('Error: ')) {
54
+ return line.slice('Error: '.length);
55
+ }
56
+ if (line.startsWith('VError: ')) {
57
+ return line.slice('VError: '.length);
58
+ }
59
+ return line;
60
+ };
61
+ const getCombinedMessage = (error, message) => {
62
+ const stringifiedError = normalizeLine(`${error}`);
63
+ if (message) {
64
+ return `${message}: ${stringifiedError}`;
65
+ }
66
+ return stringifiedError;
67
+ };
68
+ const NewLine$2 = '\n';
69
+ const getNewLineIndex$1 = (string, startIndex = undefined) => {
70
+ return string.indexOf(NewLine$2, startIndex);
71
+ };
72
+ const mergeStacks = (parent, child) => {
73
+ if (!child) {
74
+ return parent;
75
+ }
76
+ const parentNewLineIndex = getNewLineIndex$1(parent);
77
+ const childNewLineIndex = getNewLineIndex$1(child);
78
+ if (childNewLineIndex === -1) {
79
+ return parent;
80
+ }
81
+ const parentFirstLine = parent.slice(0, parentNewLineIndex);
82
+ const childRest = child.slice(childNewLineIndex);
83
+ const childFirstLine = normalizeLine(child.slice(0, childNewLineIndex));
84
+ if (parentFirstLine.includes(childFirstLine)) {
85
+ return parentFirstLine + childRest;
86
+ }
87
+ return child;
88
+ };
89
+ class VError extends Error {
90
+ constructor(error, message) {
91
+ const combinedMessage = getCombinedMessage(error, message);
92
+ super(combinedMessage);
93
+ this.name = 'VError';
94
+ if (error instanceof Error) {
95
+ this.stack = mergeStacks(this.stack, error.stack);
96
+ }
97
+ if (error.codeFrame) {
98
+ // @ts-ignore
99
+ this.codeFrame = error.codeFrame;
100
+ }
101
+ if (error.code) {
102
+ // @ts-ignore
103
+ this.code = error.code;
104
+ }
105
+ }
106
+ }
107
+
108
+ const isMessagePort = value => {
109
+ return value && value instanceof MessagePort;
110
+ };
111
+ const isMessagePortMain = value => {
112
+ return value && value.constructor && value.constructor.name === 'MessagePortMain';
113
+ };
114
+ const isOffscreenCanvas = value => {
115
+ return typeof OffscreenCanvas !== 'undefined' && value instanceof OffscreenCanvas;
116
+ };
117
+ const isInstanceOf = (value, constructorName) => {
118
+ return value?.constructor?.name === constructorName;
119
+ };
120
+ const isSocket = value => {
121
+ return isInstanceOf(value, 'Socket');
122
+ };
123
+ const transferrables = [isMessagePort, isMessagePortMain, isOffscreenCanvas, isSocket];
124
+ const isTransferrable = value => {
125
+ for (const fn of transferrables) {
126
+ if (fn(value)) {
127
+ return true;
128
+ }
129
+ }
130
+ return false;
131
+ };
132
+ const walkValue = (value, transferrables, isTransferrable) => {
133
+ if (!value) {
134
+ return;
135
+ }
136
+ if (isTransferrable(value)) {
137
+ transferrables.push(value);
138
+ return;
139
+ }
140
+ if (Array.isArray(value)) {
141
+ for (const item of value) {
142
+ walkValue(item, transferrables, isTransferrable);
143
+ }
144
+ return;
145
+ }
146
+ if (typeof value === 'object') {
147
+ for (const property of Object.values(value)) {
148
+ walkValue(property, transferrables, isTransferrable);
149
+ }
150
+ return;
151
+ }
152
+ };
153
+ const getTransferrables = value => {
154
+ const transferrables = [];
155
+ walkValue(value, transferrables, isTransferrable);
156
+ return transferrables;
157
+ };
158
+ const removeValues = (value, toRemove) => {
159
+ if (!value) {
160
+ return value;
161
+ }
162
+ if (Array.isArray(value)) {
163
+ const newItems = [];
164
+ for (const item of value) {
165
+ if (!toRemove.includes(item)) {
166
+ newItems.push(removeValues(item, toRemove));
167
+ }
168
+ }
169
+ return newItems;
170
+ }
171
+ if (typeof value === 'object') {
172
+ const newObject = Object.create(null);
173
+ for (const [key, property] of Object.entries(value)) {
174
+ if (!toRemove.includes(property)) {
175
+ newObject[key] = removeValues(property, toRemove);
176
+ }
177
+ }
178
+ return newObject;
179
+ }
180
+ return value;
181
+ };
182
+
183
+ // workaround for electron not supporting transferrable objects
184
+ // as parameters. If the transferrable object is a parameter, in electron
185
+ // only an empty objected is received in the main process
186
+ const fixElectronParameters = value => {
187
+ const transfer = getTransferrables(value);
188
+ const newValue = removeValues(value, transfer);
189
+ return {
190
+ newValue,
191
+ transfer
192
+ };
193
+ };
194
+ const getActualDataElectron = event => {
195
+ const {
196
+ data,
197
+ ports
198
+ } = event;
199
+ if (ports.length === 0) {
200
+ return data;
201
+ }
202
+ return {
203
+ ...data,
204
+ params: [...ports, ...data.params]
205
+ };
206
+ };
207
+ const attachEvents = that => {
208
+ const handleMessage = (...args) => {
209
+ const data = that.getData(...args);
210
+ that.dispatchEvent(new MessageEvent('message', {
211
+ data
212
+ }));
213
+ };
214
+ that.onMessage(handleMessage);
215
+ const handleClose = event => {
216
+ that.dispatchEvent(new Event('close'));
217
+ };
218
+ that.onClose(handleClose);
219
+ };
220
+ class Ipc extends EventTarget {
221
+ constructor(rawIpc) {
222
+ super();
223
+ this._rawIpc = rawIpc;
224
+ attachEvents(this);
225
+ }
226
+ }
227
+ const E_INCOMPATIBLE_NATIVE_MODULE = 'E_INCOMPATIBLE_NATIVE_MODULE';
228
+ const E_MODULES_NOT_SUPPORTED_IN_ELECTRON = 'E_MODULES_NOT_SUPPORTED_IN_ELECTRON';
229
+ const ERR_MODULE_NOT_FOUND = 'ERR_MODULE_NOT_FOUND';
230
+ const NewLine$1 = '\n';
231
+ const joinLines$1 = lines => {
232
+ return lines.join(NewLine$1);
233
+ };
234
+ const RE_AT = /^\s+at/;
235
+ const RE_AT_PROMISE_INDEX = /^\s*at async Promise.all \(index \d+\)$/;
236
+ const isNormalStackLine = line => {
237
+ return RE_AT.test(line) && !RE_AT_PROMISE_INDEX.test(line);
238
+ };
239
+ const getDetails = lines => {
240
+ const index = lines.findIndex(isNormalStackLine);
241
+ if (index === -1) {
242
+ return {
243
+ actualMessage: joinLines$1(lines),
244
+ rest: []
245
+ };
246
+ }
247
+ let lastIndex = index - 1;
248
+ while (++lastIndex < lines.length) {
249
+ if (!isNormalStackLine(lines[lastIndex])) {
250
+ break;
251
+ }
252
+ }
253
+ return {
254
+ actualMessage: lines[index - 1],
255
+ rest: lines.slice(index, lastIndex)
256
+ };
257
+ };
258
+ const splitLines$1 = lines => {
259
+ return lines.split(NewLine$1);
260
+ };
261
+ const RE_MESSAGE_CODE_BLOCK_START = /^Error: The module '.*'$/;
262
+ const RE_MESSAGE_CODE_BLOCK_END = /^\s* at/;
263
+ const isMessageCodeBlockStartIndex = line => {
264
+ return RE_MESSAGE_CODE_BLOCK_START.test(line);
265
+ };
266
+ const isMessageCodeBlockEndIndex = line => {
267
+ return RE_MESSAGE_CODE_BLOCK_END.test(line);
268
+ };
269
+ const getMessageCodeBlock = stderr => {
270
+ const lines = splitLines$1(stderr);
271
+ const startIndex = lines.findIndex(isMessageCodeBlockStartIndex);
272
+ const endIndex = startIndex + lines.slice(startIndex).findIndex(isMessageCodeBlockEndIndex, startIndex);
273
+ const relevantLines = lines.slice(startIndex, endIndex);
274
+ const relevantMessage = relevantLines.join(' ').slice('Error: '.length);
275
+ return relevantMessage;
276
+ };
277
+ const isModuleNotFoundMessage = line => {
278
+ return line.includes('[ERR_MODULE_NOT_FOUND]');
279
+ };
280
+ const getModuleNotFoundError = stderr => {
281
+ const lines = splitLines$1(stderr);
282
+ const messageIndex = lines.findIndex(isModuleNotFoundMessage);
283
+ const message = lines[messageIndex];
284
+ return {
285
+ message,
286
+ code: ERR_MODULE_NOT_FOUND
287
+ };
288
+ };
289
+ const isModuleNotFoundError$1 = stderr => {
290
+ if (!stderr) {
291
+ return false;
292
+ }
293
+ return stderr.includes('ERR_MODULE_NOT_FOUND');
294
+ };
295
+ const isModulesSyntaxError = stderr => {
296
+ if (!stderr) {
297
+ return false;
298
+ }
299
+ return stderr.includes('SyntaxError: Cannot use import statement outside a module');
300
+ };
301
+ const RE_NATIVE_MODULE_ERROR = /^innerError Error: Cannot find module '.*.node'/;
302
+ const RE_NATIVE_MODULE_ERROR_2 = /was compiled against a different Node.js version/;
303
+ const isUnhelpfulNativeModuleError = stderr => {
304
+ return RE_NATIVE_MODULE_ERROR.test(stderr) && RE_NATIVE_MODULE_ERROR_2.test(stderr);
305
+ };
306
+ const getNativeModuleErrorMessage = stderr => {
307
+ const message = getMessageCodeBlock(stderr);
308
+ return {
309
+ message: `Incompatible native node module: ${message}`,
310
+ code: E_INCOMPATIBLE_NATIVE_MODULE
311
+ };
312
+ };
313
+ const getModuleSyntaxError = () => {
314
+ return {
315
+ message: `ES Modules are not supported in electron`,
316
+ code: E_MODULES_NOT_SUPPORTED_IN_ELECTRON
317
+ };
318
+ };
319
+ const getHelpfulChildProcessError = (stdout, stderr) => {
320
+ if (isUnhelpfulNativeModuleError(stderr)) {
321
+ return getNativeModuleErrorMessage(stderr);
322
+ }
323
+ if (isModulesSyntaxError(stderr)) {
324
+ return getModuleSyntaxError();
325
+ }
326
+ if (isModuleNotFoundError$1(stderr)) {
327
+ return getModuleNotFoundError(stderr);
328
+ }
329
+ const lines = splitLines$1(stderr);
330
+ const {
331
+ actualMessage,
332
+ rest
333
+ } = getDetails(lines);
334
+ return {
335
+ message: actualMessage,
336
+ code: '',
337
+ stack: rest
338
+ };
339
+ };
340
+ class IpcError extends VError {
341
+ // @ts-ignore
342
+ constructor(betterMessage, stdout = '', stderr = '') {
343
+ if (stdout || stderr) {
344
+ // @ts-ignore
345
+ const {
346
+ message,
347
+ code,
348
+ stack
349
+ } = getHelpfulChildProcessError(stdout, stderr);
350
+ const cause = new Error(message);
351
+ // @ts-ignore
352
+ cause.code = code;
353
+ cause.stack = stack;
354
+ super(cause, betterMessage);
355
+ } else {
356
+ super(betterMessage);
357
+ }
358
+ // @ts-ignore
359
+ this.name = 'IpcError';
360
+ // @ts-ignore
361
+ this.stdout = stdout;
362
+ // @ts-ignore
363
+ this.stderr = stderr;
364
+ }
365
+ }
366
+ const listen$b = ({
367
+ messagePort
368
+ }) => {
369
+ if (!isMessagePortMain(messagePort)) {
370
+ throw new IpcError('port must be of type MessagePortMain');
371
+ }
372
+ return messagePort;
373
+ };
374
+ const signal$c = messagePort => {
375
+ messagePort.start();
376
+ };
377
+ class IpcChildWithElectronMessagePort extends Ipc {
378
+ getData = getActualDataElectron;
379
+ send(message) {
380
+ this._rawIpc.postMessage(message);
381
+ }
382
+ sendAndTransfer(message) {
383
+ const {
384
+ newValue,
385
+ transfer
386
+ } = fixElectronParameters(message);
387
+ this._rawIpc.postMessage(newValue, transfer);
388
+ }
389
+ dispose() {
390
+ this._rawIpc.close();
391
+ }
392
+ onMessage(callback) {
393
+ this._rawIpc.on('message', callback);
394
+ }
395
+ onClose(callback) {
396
+ this._rawIpc.on('close', callback);
397
+ }
398
+ }
399
+ const wrap$j = messagePort => {
400
+ return new IpcChildWithElectronMessagePort(messagePort);
401
+ };
402
+ const IpcChildWithElectronMessagePort$1 = {
403
+ __proto__: null,
404
+ listen: listen$b,
405
+ signal: signal$c,
406
+ wrap: wrap$j
407
+ };
408
+
409
+ // @ts-ignore
410
+ const getUtilityProcessPortData = event => {
411
+ const {
412
+ data,
413
+ ports
414
+ } = event;
415
+ if (ports.length === 0) {
416
+ return data;
417
+ }
418
+ return {
419
+ ...data,
420
+ params: [...ports, ...data.params]
421
+ };
422
+ };
423
+ const readyMessage = 'ready';
424
+ const listen$a = () => {
425
+ // @ts-ignore
426
+ const {
427
+ parentPort
428
+ } = process;
429
+ if (!parentPort) {
430
+ throw new Error('parent port must be defined');
431
+ }
432
+ return parentPort;
433
+ };
434
+ const signal$b = parentPort => {
435
+ parentPort.postMessage(readyMessage);
436
+ };
437
+ class IpcChildWithElectronUtilityProcess extends Ipc {
438
+ getData(event) {
439
+ return getUtilityProcessPortData(event);
440
+ }
441
+ send(message) {
442
+ this._rawIpc.postMessage(message);
443
+ }
444
+ sendAndTransfer(message) {
445
+ const {
446
+ newValue,
447
+ transfer
448
+ } = fixElectronParameters(message);
449
+ this._rawIpc.postMessage(newValue, transfer);
450
+ }
451
+ dispose() {
452
+ this._rawIpc.close();
453
+ }
454
+ onClose(callback) {
455
+ this._rawIpc.on('close', callback);
456
+ }
457
+ onMessage(callback) {
458
+ this._rawIpc.on('message', callback);
459
+ }
460
+ }
461
+ const wrap$i = parentPort => {
462
+ return new IpcChildWithElectronUtilityProcess(parentPort);
463
+ };
464
+ const IpcChildWithElectronUtilityProcess$1 = {
465
+ __proto__: null,
466
+ listen: listen$a,
467
+ signal: signal$b,
468
+ wrap: wrap$i
469
+ };
470
+ const getActualData = (message, handle) => {
471
+ if (handle) {
472
+ return {
473
+ ...message,
474
+ params: [handle, ...message.params]
475
+ };
476
+ }
477
+ return message;
478
+ };
479
+ const getTransferrablesNode = value => {
480
+ const transferrables = getTransferrables(value);
481
+ if (transferrables.length === 0) {
482
+ throw new Error(`no transferrables found`);
483
+ }
484
+ return transferrables[0];
485
+ };
486
+ const listen$5 = async () => {
487
+ if (!process.send) {
488
+ throw new Error('process.send must be defined');
489
+ }
490
+ return process;
491
+ };
492
+ const signal$7 = process => {
493
+ process.send(readyMessage);
494
+ };
495
+ class IpcChildWithNodeForkedProcess extends Ipc {
496
+ getData(message, handle) {
497
+ return getActualData(message, handle);
498
+ }
499
+ onClose(callback) {
500
+ this._rawIpc.on('close', callback);
501
+ }
502
+ send(message) {
503
+ this._rawIpc.send(message);
504
+ }
505
+ onMessage(callback) {
506
+ this._rawIpc.on('message', callback);
507
+ }
508
+ sendAndTransfer(message) {
509
+ const transfer = getTransferrablesNode(message);
510
+ this._rawIpc.send(message, transfer);
511
+ }
512
+ dispose() {
513
+ // ignore
514
+ }
515
+ }
516
+ const wrap$d = process => {
517
+ return new IpcChildWithNodeForkedProcess(process);
518
+ };
519
+ const IpcChildWithNodeForkedProcess$1 = {
520
+ __proto__: null,
521
+ listen: listen$5,
522
+ signal: signal$7,
523
+ wrap: wrap$d
524
+ };
525
+ const Error$3 = 1;
526
+ const Open = 2;
527
+ const Close = 3;
528
+ const addListener = (emitter, type, callback) => {
529
+ if ('addEventListener' in emitter) {
530
+ emitter.addEventListener(type, callback);
531
+ } else {
532
+ emitter.on(type, callback);
533
+ }
534
+ };
535
+ const removeListener = (emitter, type, callback) => {
536
+ if ('removeEventListener' in emitter) {
537
+ emitter.removeEventListener(type, callback);
538
+ } else {
539
+ emitter.off(type, callback);
540
+ }
541
+ };
542
+ const getFirstEvent = (eventEmitter, eventMap) => {
543
+ const {
544
+ resolve,
545
+ promise
546
+ } = Promise.withResolvers();
547
+ const listenerMap = Object.create(null);
548
+ const cleanup = value => {
549
+ for (const event of Object.keys(eventMap)) {
550
+ removeListener(eventEmitter, event, listenerMap[event]);
551
+ }
552
+ resolve(value);
553
+ };
554
+ for (const [event, type] of Object.entries(eventMap)) {
555
+ const listener = event => {
556
+ cleanup({
557
+ type,
558
+ event
559
+ });
560
+ };
561
+ addListener(eventEmitter, event, listener);
562
+ listenerMap[event] = listener;
563
+ }
564
+ return promise;
565
+ };
566
+ const stringifyCompact = value => {
567
+ return JSON.stringify(value);
568
+ };
569
+ const parse = content => {
570
+ if (content === 'undefined') {
571
+ return null;
572
+ }
573
+ try {
574
+ return JSON.parse(content);
575
+ } catch (error) {
576
+ throw new VError(error, 'failed to parse json');
577
+ }
578
+ };
579
+ const waitForWebSocketToBeOpen = webSocket => {
580
+ return getFirstEvent(webSocket, {
581
+ open: Open,
582
+ close: Close,
583
+ error: Error$3
584
+ });
585
+ };
586
+ const create$5 = async ({
587
+ webSocket
588
+ }) => {
589
+ const firstWebSocketEvent = await waitForWebSocketToBeOpen(webSocket);
590
+ if (firstWebSocketEvent.type === Error$3) {
591
+ throw new IpcError(`WebSocket connection error`);
592
+ }
593
+ if (firstWebSocketEvent.type === Close) {
594
+ throw new IpcError('Websocket connection was immediately closed');
595
+ }
596
+ return webSocket;
597
+ };
598
+ class IpcParentWithWebSocket extends Ipc {
599
+ getData(event) {
600
+ return parse(event.data);
601
+ }
602
+ send(message) {
603
+ this._rawIpc.send(stringifyCompact(message));
604
+ }
605
+ sendAndTransfer(message) {
606
+ throw new Error('sendAndTransfer not supported');
607
+ }
608
+ dispose() {
609
+ this._rawIpc.close();
610
+ }
611
+ onClose(callback) {
612
+ this._rawIpc.addEventListener('close', callback);
613
+ }
614
+ onMessage(callback) {
615
+ this._rawIpc.addEventListener('message', callback);
616
+ }
617
+ }
618
+ const wrap = webSocket => {
619
+ return new IpcParentWithWebSocket(webSocket);
620
+ };
621
+ const IpcParentWithWebSocket$1 = {
622
+ __proto__: null,
623
+ create: create$5,
624
+ wrap
625
+ };
626
+
627
+ const Two = '2.0';
628
+ const create$4 = (method, params) => {
629
+ return {
630
+ jsonrpc: Two,
631
+ method,
632
+ params
633
+ };
634
+ };
635
+ const callbacks = Object.create(null);
636
+ const set$1 = (id, fn) => {
637
+ callbacks[id] = fn;
638
+ };
639
+ const get$1 = id => {
640
+ return callbacks[id];
641
+ };
642
+ const remove = id => {
643
+ delete callbacks[id];
644
+ };
645
+ let id = 0;
646
+ const create$3 = () => {
647
+ return ++id;
648
+ };
649
+ const registerPromise = () => {
650
+ const id = create$3();
651
+ const {
652
+ resolve,
653
+ promise
654
+ } = Promise.withResolvers();
655
+ set$1(id, resolve);
656
+ return {
657
+ id,
658
+ promise
659
+ };
660
+ };
661
+ const create$2$1 = (method, params) => {
662
+ const {
663
+ id,
664
+ promise
665
+ } = registerPromise();
666
+ const message = {
667
+ jsonrpc: Two,
668
+ method,
669
+ params,
670
+ id
671
+ };
672
+ return {
673
+ message,
674
+ promise
675
+ };
676
+ };
677
+ class JsonRpcError extends Error {
678
+ constructor(message) {
679
+ super(message);
680
+ this.name = 'JsonRpcError';
681
+ }
682
+ }
683
+ const NewLine = '\n';
684
+ const DomException = 'DOMException';
685
+ const ReferenceError$1 = 'ReferenceError';
686
+ const SyntaxError$1 = 'SyntaxError';
687
+ const TypeError$1 = 'TypeError';
688
+ const getErrorConstructor = (message, type) => {
689
+ if (type) {
690
+ switch (type) {
691
+ case DomException:
692
+ return DOMException;
693
+ case TypeError$1:
694
+ return TypeError;
695
+ case SyntaxError$1:
696
+ return SyntaxError;
697
+ case ReferenceError$1:
698
+ return ReferenceError;
699
+ default:
700
+ return Error;
701
+ }
702
+ }
703
+ if (message.startsWith('TypeError: ')) {
704
+ return TypeError;
705
+ }
706
+ if (message.startsWith('SyntaxError: ')) {
707
+ return SyntaxError;
708
+ }
709
+ if (message.startsWith('ReferenceError: ')) {
710
+ return ReferenceError;
711
+ }
712
+ return Error;
713
+ };
714
+ const constructError = (message, type, name) => {
715
+ const ErrorConstructor = getErrorConstructor(message, type);
716
+ if (ErrorConstructor === DOMException && name) {
717
+ return new ErrorConstructor(message, name);
718
+ }
719
+ if (ErrorConstructor === Error) {
720
+ const error = new Error(message);
721
+ if (name && name !== 'VError') {
722
+ error.name = name;
723
+ }
724
+ return error;
725
+ }
726
+ return new ErrorConstructor(message);
727
+ };
728
+ const joinLines = lines => {
729
+ return lines.join(NewLine);
730
+ };
731
+ const splitLines = lines => {
732
+ return lines.split(NewLine);
733
+ };
734
+ const getCurrentStack = () => {
735
+ const stackLinesToSkip = 3;
736
+ const currentStack = joinLines(splitLines(new Error().stack || '').slice(stackLinesToSkip));
737
+ return currentStack;
738
+ };
739
+ const getNewLineIndex = (string, startIndex = undefined) => {
740
+ return string.indexOf(NewLine, startIndex);
741
+ };
742
+ const getParentStack = error => {
743
+ let parentStack = error.stack || error.data || error.message || '';
744
+ if (parentStack.startsWith(' at')) {
745
+ parentStack = error.message + NewLine + parentStack;
746
+ }
747
+ return parentStack;
748
+ };
749
+ const MethodNotFound = -32601;
750
+ const Custom = -32001;
751
+ const restoreJsonRpcError = error => {
752
+ const currentStack = getCurrentStack();
753
+ if (error && error instanceof Error) {
754
+ if (typeof error.stack === 'string') {
755
+ error.stack = error.stack + NewLine + currentStack;
756
+ }
757
+ return error;
758
+ }
759
+ if (error && error.code && error.code === MethodNotFound) {
760
+ const restoredError = new JsonRpcError(error.message);
761
+ const parentStack = getParentStack(error);
762
+ restoredError.stack = parentStack + NewLine + currentStack;
763
+ return restoredError;
764
+ }
765
+ if (error && error.message) {
766
+ const restoredError = constructError(error.message, error.type, error.name);
767
+ if (error.data) {
768
+ if (error.data.stack && error.data.type && error.message) {
769
+ restoredError.stack = error.data.type + ': ' + error.message + NewLine + error.data.stack + NewLine + currentStack;
770
+ } else if (error.data.stack) {
771
+ restoredError.stack = error.data.stack;
772
+ }
773
+ if (error.data.codeFrame) {
774
+ // @ts-ignore
775
+ restoredError.codeFrame = error.data.codeFrame;
776
+ }
777
+ if (error.data.code) {
778
+ // @ts-ignore
779
+ restoredError.code = error.data.code;
780
+ }
781
+ if (error.data.type) {
782
+ // @ts-ignore
783
+ restoredError.name = error.data.type;
784
+ }
785
+ } else {
786
+ if (error.stack) {
787
+ const lowerStack = restoredError.stack || '';
788
+ // @ts-ignore
789
+ const indexNewLine = getNewLineIndex(lowerStack);
790
+ const parentStack = getParentStack(error);
791
+ // @ts-ignore
792
+ restoredError.stack = parentStack + lowerStack.slice(indexNewLine);
793
+ }
794
+ if (error.codeFrame) {
795
+ // @ts-ignore
796
+ restoredError.codeFrame = error.codeFrame;
797
+ }
798
+ }
799
+ return restoredError;
800
+ }
801
+ if (typeof error === 'string') {
802
+ return new Error(`JsonRpc Error: ${error}`);
803
+ }
804
+ return new Error(`JsonRpc Error: ${error}`);
805
+ };
806
+ const unwrapJsonRpcResult = responseMessage => {
807
+ if ('error' in responseMessage) {
808
+ const restoredError = restoreJsonRpcError(responseMessage.error);
809
+ throw restoredError;
810
+ }
811
+ if ('result' in responseMessage) {
812
+ return responseMessage.result;
813
+ }
814
+ throw new JsonRpcError('unexpected response message');
815
+ };
816
+ const warn = (...args) => {
817
+ console.warn(...args);
818
+ };
819
+ const resolve = (id, response) => {
820
+ const fn = get$1(id);
821
+ if (!fn) {
822
+ console.log(response);
823
+ warn(`callback ${id} may already be disposed`);
824
+ return;
825
+ }
826
+ fn(response);
827
+ remove(id);
828
+ };
829
+ const E_COMMAND_NOT_FOUND = 'E_COMMAND_NOT_FOUND';
830
+ const getErrorType = prettyError => {
831
+ if (prettyError && prettyError.type) {
832
+ return prettyError.type;
833
+ }
834
+ if (prettyError && prettyError.constructor && prettyError.constructor.name) {
835
+ return prettyError.constructor.name;
836
+ }
837
+ return undefined;
838
+ };
839
+ const isAlreadyStack = line => {
840
+ return line.trim().startsWith('at ');
841
+ };
842
+ const getStack = prettyError => {
843
+ const stackString = prettyError.stack || '';
844
+ const newLineIndex = stackString.indexOf('\n');
845
+ if (newLineIndex !== -1 && !isAlreadyStack(stackString.slice(0, newLineIndex))) {
846
+ return stackString.slice(newLineIndex + 1);
847
+ }
848
+ return stackString;
849
+ };
850
+ const getErrorProperty = (error, prettyError) => {
851
+ if (error && error.code === E_COMMAND_NOT_FOUND) {
852
+ return {
853
+ code: MethodNotFound,
854
+ message: error.message,
855
+ data: error.stack
856
+ };
857
+ }
858
+ return {
859
+ code: Custom,
860
+ message: prettyError.message,
861
+ data: {
862
+ stack: getStack(prettyError),
863
+ codeFrame: prettyError.codeFrame,
864
+ type: getErrorType(prettyError),
865
+ code: prettyError.code,
866
+ name: prettyError.name
867
+ }
868
+ };
869
+ };
870
+ const create$1 = (id, error) => {
871
+ return {
872
+ jsonrpc: Two,
873
+ id,
874
+ error
875
+ };
876
+ };
877
+ const getErrorResponse = (id, error, preparePrettyError, logError) => {
878
+ const prettyError = preparePrettyError(error);
879
+ logError(error, prettyError);
880
+ const errorProperty = getErrorProperty(error, prettyError);
881
+ return create$1(id, errorProperty);
882
+ };
883
+ const create = (message, result) => {
884
+ return {
885
+ jsonrpc: Two,
886
+ id: message.id,
887
+ result: result ?? null
888
+ };
889
+ };
890
+ const getSuccessResponse = (message, result) => {
891
+ const resultProperty = result ?? null;
892
+ return create(message, resultProperty);
893
+ };
894
+ const getErrorResponseSimple = (id, error) => {
895
+ return {
896
+ jsonrpc: Two,
897
+ id,
898
+ error: {
899
+ code: Custom,
900
+ // @ts-ignore
901
+ message: error.message,
902
+ data: error
903
+ }
904
+ };
905
+ };
906
+ const getResponse = async (message, ipc, execute, preparePrettyError, logError, requiresSocket) => {
907
+ try {
908
+ const result = requiresSocket(message.method) ? await execute(message.method, ipc, ...message.params) : await execute(message.method, ...message.params);
909
+ return getSuccessResponse(message, result);
910
+ } catch (error) {
911
+ if (ipc.canUseSimpleErrorResponse) {
912
+ return getErrorResponseSimple(message.id, error);
913
+ }
914
+ return getErrorResponse(message.id, error, preparePrettyError, logError);
915
+ }
916
+ };
917
+ const defaultPreparePrettyError = error => {
918
+ return error;
919
+ };
920
+ const defaultLogError = () => {
921
+ // ignore
922
+ };
923
+ const defaultRequiresSocket = () => {
924
+ return false;
925
+ };
926
+ const defaultResolve = resolve;
927
+
928
+ // TODO maybe remove this in v6 or v7, only accept options object to simplify the code
929
+ const normalizeParams = args => {
930
+ if (args.length === 1) {
931
+ const options = args[0];
932
+ return {
933
+ ipc: options.ipc,
934
+ message: options.message,
935
+ execute: options.execute,
936
+ resolve: options.resolve || defaultResolve,
937
+ preparePrettyError: options.preparePrettyError || defaultPreparePrettyError,
938
+ logError: options.logError || defaultLogError,
939
+ requiresSocket: options.requiresSocket || defaultRequiresSocket
940
+ };
941
+ }
942
+ return {
943
+ ipc: args[0],
944
+ message: args[1],
945
+ execute: args[2],
946
+ resolve: args[3],
947
+ preparePrettyError: args[4],
948
+ logError: args[5],
949
+ requiresSocket: args[6]
950
+ };
951
+ };
952
+ const handleJsonRpcMessage = async (...args) => {
953
+ const options = normalizeParams(args);
954
+ const {
955
+ message,
956
+ ipc,
957
+ execute,
958
+ resolve,
959
+ preparePrettyError,
960
+ logError,
961
+ requiresSocket
962
+ } = options;
963
+ if ('id' in message) {
964
+ if ('method' in message) {
965
+ const response = await getResponse(message, ipc, execute, preparePrettyError, logError, requiresSocket);
966
+ try {
967
+ ipc.send(response);
968
+ } catch (error) {
969
+ const errorResponse = getErrorResponse(message.id, error, preparePrettyError, logError);
970
+ ipc.send(errorResponse);
971
+ }
972
+ return;
973
+ }
974
+ resolve(message.id, message);
975
+ return;
976
+ }
977
+ if ('method' in message) {
978
+ await getResponse(message, ipc, execute, preparePrettyError, logError, requiresSocket);
979
+ return;
980
+ }
981
+ throw new JsonRpcError('unexpected message');
982
+ };
983
+ const invokeHelper = async (ipc, method, params, useSendAndTransfer) => {
984
+ const {
985
+ message,
986
+ promise
987
+ } = create$2$1(method, params);
988
+ if (useSendAndTransfer && ipc.sendAndTransfer) {
989
+ ipc.sendAndTransfer(message);
990
+ } else {
991
+ ipc.send(message);
992
+ }
993
+ const responseMessage = await promise;
994
+ return unwrapJsonRpcResult(responseMessage);
995
+ };
996
+ const send = (transport, method, ...params) => {
997
+ const message = create$4(method, params);
998
+ transport.send(message);
999
+ };
1000
+ const invoke = (ipc, method, ...params) => {
1001
+ return invokeHelper(ipc, method, params, false);
1002
+ };
1003
+ const invokeAndTransfer = (ipc, method, ...params) => {
1004
+ return invokeHelper(ipc, method, params, true);
1005
+ };
1006
+
1007
+ class CommandNotFoundError extends Error {
1008
+ constructor(command) {
1009
+ super(`Command not found ${command}`);
1010
+ this.name = 'CommandNotFoundError';
1011
+ }
1012
+ }
1013
+ const commands = Object.create(null);
1014
+ const register = commandMap => {
1015
+ Object.assign(commands, commandMap);
1016
+ };
1017
+ const getCommand = key => {
1018
+ return commands[key];
1019
+ };
1020
+ const execute = (command, ...args) => {
1021
+ const fn = getCommand(command);
1022
+ if (!fn) {
1023
+ throw new CommandNotFoundError(command);
1024
+ }
1025
+ return fn(...args);
1026
+ };
1027
+
1028
+ const createRpc = ipc => {
1029
+ const rpc = {
1030
+ // @ts-ignore
1031
+ ipc,
1032
+ /**
1033
+ * @deprecated
1034
+ */
1035
+ send(method, ...params) {
1036
+ send(ipc, method, ...params);
1037
+ },
1038
+ invoke(method, ...params) {
1039
+ return invoke(ipc, method, ...params);
1040
+ },
1041
+ invokeAndTransfer(method, ...params) {
1042
+ return invokeAndTransfer(ipc, method, ...params);
1043
+ },
1044
+ async dispose() {
1045
+ await ipc?.dispose();
1046
+ }
1047
+ };
1048
+ return rpc;
1049
+ };
1050
+ const requiresSocket = () => {
1051
+ return false;
1052
+ };
1053
+ const preparePrettyError = error => {
1054
+ return error;
1055
+ };
1056
+ const logError = () => {
1057
+ // handled by renderer worker
1058
+ };
1059
+ const handleMessage = event => {
1060
+ const actualRequiresSocket = event?.target?.requiresSocket || requiresSocket;
1061
+ const actualExecute = event?.target?.execute || execute;
1062
+ return handleJsonRpcMessage(event.target, event.data, actualExecute, resolve, preparePrettyError, logError, actualRequiresSocket);
1063
+ };
1064
+ const handleIpc = ipc => {
1065
+ if ('addEventListener' in ipc) {
1066
+ ipc.addEventListener('message', handleMessage);
1067
+ } else if ('on' in ipc) {
1068
+ // deprecated
1069
+ ipc.on('message', handleMessage);
1070
+ }
1071
+ };
1072
+ const listen$2 = async (module, options) => {
1073
+ const rawIpc = await module.listen(options);
1074
+ if (module.signal) {
1075
+ module.signal(rawIpc);
1076
+ }
1077
+ const ipc = module.wrap(rawIpc);
1078
+ return ipc;
1079
+ };
1080
+ const create$k = async ({
1081
+ commandMap,
1082
+ messagePort,
1083
+ requiresSocket
1084
+ }) => {
1085
+ // TODO create a commandMap per rpc instance
1086
+ register(commandMap);
1087
+ const ipc = await listen$2(IpcChildWithElectronMessagePort$1, {
1088
+ messagePort
1089
+ });
1090
+ if (requiresSocket) {
1091
+ ipc.requiresSocket = requiresSocket;
1092
+ }
1093
+ handleIpc(ipc);
1094
+ const rpc = createRpc(ipc);
1095
+ return rpc;
1096
+ };
1097
+ const ElectronMessagePortRpcClient = {
1098
+ __proto__: null,
1099
+ create: create$k
1100
+ };
1101
+ const create$j = async ({
1102
+ commandMap
1103
+ }) => {
1104
+ // TODO create a commandMap per rpc instance
1105
+ register(commandMap);
1106
+ const ipc = await listen$2(IpcChildWithElectronUtilityProcess$1);
1107
+ handleIpc(ipc);
1108
+ const rpc = createRpc(ipc);
1109
+ return rpc;
1110
+ };
1111
+ const ElectronUtilityProcessRpcClient = {
1112
+ __proto__: null,
1113
+ create: create$j
1114
+ };
1115
+ const create$a = async ({
1116
+ commandMap
1117
+ }) => {
1118
+ // TODO create a commandMap per rpc instance
1119
+ register(commandMap);
1120
+ const ipc = await listen$2(IpcChildWithNodeForkedProcess$1);
1121
+ handleIpc(ipc);
1122
+ const rpc = createRpc(ipc);
1123
+ return rpc;
1124
+ };
1125
+ const NodeForkedProcessRpcClient = {
1126
+ __proto__: null,
1127
+ create: create$a
1128
+ };
1129
+ const create$2 = async ({
1130
+ commandMap,
1131
+ webSocket
1132
+ }) => {
1133
+ // TODO create a commandMap per rpc instance
1134
+ register(commandMap);
1135
+ const rawIpc = await IpcParentWithWebSocket$1.create({
1136
+ webSocket
1137
+ });
1138
+ const ipc = IpcParentWithWebSocket$1.wrap(rawIpc);
1139
+ handleIpc(ipc);
1140
+ const rpc = createRpc(ipc);
1141
+ return rpc;
1142
+ };
1143
+ const WebSocketRpcParent = {
1144
+ __proto__: null,
1145
+ create: create$2
1146
+ };
1147
+
6
1148
  const NodeWorker = 1;
7
1149
  const NodeForkedProcess = 2;
8
1150
  const ElectronUtilityProcess = 3;
@@ -59,6 +1201,18 @@ const handleElectronMessagePort = async (messagePort, ipcId) => {
59
1201
  });
60
1202
  };
61
1203
 
1204
+ const transpileTypeScript2 = async code => {
1205
+ try {
1206
+ const {
1207
+ stripTypeScriptTypes
1208
+ } = await import('node:module');
1209
+ const transformed = stripTypeScriptTypes(code);
1210
+ return transformed;
1211
+ } catch (error) {
1212
+ throw new VError(error, `Failed to transpile typescript`);
1213
+ }
1214
+ };
1215
+
62
1216
  const importScript = async url => {
63
1217
  return await import(url);
64
1218
  };
@@ -127,10 +1281,11 @@ const transpileTypeScriptAtPath = async (inPath, outPath) => {
127
1281
  };
128
1282
 
129
1283
  const commandMap = {
1284
+ 'HandleElectronMessagePort.handleElectronMessagePort': handleElectronMessagePort,
130
1285
  'TranspileTypeScript.transpileTypeScript': transpileTypeScript,
1286
+ 'TranspileTypeScript.transpileTypeScript2': transpileTypeScript2,
131
1287
  'TranspileTypeScript.transpileTypeScriptAtPath': transpileTypeScriptAtPath,
132
- 'TypeScript.setTypeScriptPath': set,
133
- 'HandleElectronMessagePort.handleElectronMessagePort': handleElectronMessagePort
1288
+ 'TypeScript.setTypeScriptPath': set
134
1289
  };
135
1290
 
136
1291
  const listen = async () => {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lvce-editor/typescript-compile-process",
3
- "version": "3.2.0",
3
+ "version": "4.0.0",
4
4
  "description": "TypeScript Compile Process",
5
5
  "keywords": [
6
6
  "Lvce Editor"
@@ -14,55 +14,8 @@
14
14
  "type": "module",
15
15
  "main": "dist/index.js",
16
16
  "bin": "bin/typescriptCompileProcess.js",
17
- "xo": {
18
- "rules": {
19
- "unicorn/filename-case": "off",
20
- "indent": "off",
21
- "semi": "off",
22
- "no-unused-vars": "off",
23
- "unicorn/numeric-separators-style": "off",
24
- "no-extra-semi": "off",
25
- "arrow-body-style": "off",
26
- "padded-blocks": "off",
27
- "capitalized-comments": "off",
28
- "padding-line-between-statements": "off",
29
- "arrow-parens": "off",
30
- "no-warning-comments": "off",
31
- "array-bracket-spacing": "off",
32
- "comma-spacing": "off",
33
- "unicorn/no-array-callback-reference": "off",
34
- "comma-dangle": "off",
35
- "operator-linebreak": "off",
36
- "no-case-declarations": "off",
37
- "no-undef": "off",
38
- "object-curly-spacing": "off",
39
- "object-shorthand": "off",
40
- "complexity": "off",
41
- "no-labels": "off",
42
- "no-multi-assign": "off",
43
- "max-params": "off",
44
- "no-bitwise": "off",
45
- "unicorn/prefer-math-trunc": "off",
46
- "no-await-in-loop": "off",
47
- "unicorn/prefer-add-event-listener": "off",
48
- "no-unused-expressions": "off",
49
- "node/prefer-global/process": "off",
50
- "unicorn/prevent-abbreviations": "off",
51
- "unicorn/no-process-exit": "off",
52
- "quotes": "off",
53
- "n/prefer-global/process": [
54
- "error",
55
- "always"
56
- ]
57
- },
58
- "ignores": [
59
- "distmin"
60
- ]
61
- },
62
17
  "dependencies": {
63
- "@lvce-editor/assert": "^1.4.0",
64
- "@lvce-editor/rpc": "^4.13.0",
65
- "@lvce-editor/verror": "^1.7.0"
18
+ "ws": "^8.18.3"
66
19
  },
67
20
  "engines": {
68
21
  "node": ">=18"