@lvce-editor/chat-view 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.
@@ -0,0 +1,2053 @@
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$7 = () => {
271
+ // @ts-ignore
272
+ if (typeof WorkerGlobalScope === 'undefined') {
273
+ throw new TypeError('module is not in web worker scope');
274
+ }
275
+ return globalThis;
276
+ };
277
+ const signal$8 = global => {
278
+ global.postMessage(readyMessage);
279
+ };
280
+ class IpcChildWithModuleWorker extends Ipc {
281
+ getData(event) {
282
+ return getData$2(event);
283
+ }
284
+ send(message) {
285
+ // @ts-ignore
286
+ this._rawIpc.postMessage(message);
287
+ }
288
+ sendAndTransfer(message) {
289
+ const transfer = getTransferrables(message);
290
+ // @ts-ignore
291
+ this._rawIpc.postMessage(message, transfer);
292
+ }
293
+ dispose() {
294
+ // ignore
295
+ }
296
+ onClose(callback) {
297
+ // ignore
298
+ }
299
+ onMessage(callback) {
300
+ this._rawIpc.addEventListener('message', callback);
301
+ }
302
+ }
303
+ const wrap$f = global => {
304
+ return new IpcChildWithModuleWorker(global);
305
+ };
306
+ const waitForFirstMessage = async port => {
307
+ const {
308
+ promise,
309
+ resolve
310
+ } = Promise.withResolvers();
311
+ port.addEventListener('message', resolve, {
312
+ once: true
313
+ });
314
+ const event = await promise;
315
+ // @ts-ignore
316
+ return event.data;
317
+ };
318
+ const listen$6 = async () => {
319
+ const parentIpcRaw = listen$7();
320
+ signal$8(parentIpcRaw);
321
+ const parentIpc = wrap$f(parentIpcRaw);
322
+ const firstMessage = await waitForFirstMessage(parentIpc);
323
+ if (firstMessage.method !== 'initialize') {
324
+ throw new IpcError('unexpected first message');
325
+ }
326
+ const type = firstMessage.params[0];
327
+ if (type === 'message-port') {
328
+ parentIpc.send({
329
+ id: firstMessage.id,
330
+ jsonrpc: '2.0',
331
+ result: null
332
+ });
333
+ parentIpc.dispose();
334
+ const port = firstMessage.params[1];
335
+ return port;
336
+ }
337
+ return globalThis;
338
+ };
339
+ class IpcChildWithModuleWorkerAndMessagePort extends Ipc {
340
+ getData(event) {
341
+ return getData$2(event);
342
+ }
343
+ send(message) {
344
+ this._rawIpc.postMessage(message);
345
+ }
346
+ sendAndTransfer(message) {
347
+ const transfer = getTransferrables(message);
348
+ this._rawIpc.postMessage(message, transfer);
349
+ }
350
+ dispose() {
351
+ if (this._rawIpc.close) {
352
+ this._rawIpc.close();
353
+ }
354
+ }
355
+ onClose(callback) {
356
+ // ignore
357
+ }
358
+ onMessage(callback) {
359
+ this._rawIpc.addEventListener('message', callback);
360
+ this._rawIpc.start();
361
+ }
362
+ }
363
+ const wrap$e = port => {
364
+ return new IpcChildWithModuleWorkerAndMessagePort(port);
365
+ };
366
+ const IpcChildWithModuleWorkerAndMessagePort$1 = {
367
+ __proto__: null,
368
+ listen: listen$6,
369
+ wrap: wrap$e
370
+ };
371
+ const addListener = (emitter, type, callback) => {
372
+ if ('addEventListener' in emitter) {
373
+ emitter.addEventListener(type, callback);
374
+ } else {
375
+ emitter.on(type, callback);
376
+ }
377
+ };
378
+ const removeListener = (emitter, type, callback) => {
379
+ if ('removeEventListener' in emitter) {
380
+ emitter.removeEventListener(type, callback);
381
+ } else {
382
+ emitter.off(type, callback);
383
+ }
384
+ };
385
+ const getFirstEvent = (eventEmitter, eventMap) => {
386
+ const {
387
+ promise,
388
+ resolve
389
+ } = Promise.withResolvers();
390
+ const listenerMap = Object.create(null);
391
+ const cleanup = value => {
392
+ for (const event of Object.keys(eventMap)) {
393
+ removeListener(eventEmitter, event, listenerMap[event]);
394
+ }
395
+ resolve(value);
396
+ };
397
+ for (const [event, type] of Object.entries(eventMap)) {
398
+ const listener = event => {
399
+ cleanup({
400
+ event,
401
+ type
402
+ });
403
+ };
404
+ addListener(eventEmitter, event, listener);
405
+ listenerMap[event] = listener;
406
+ }
407
+ return promise;
408
+ };
409
+ const Message$1 = 3;
410
+ const create$5$1 = async ({
411
+ isMessagePortOpen,
412
+ messagePort
413
+ }) => {
414
+ if (!isMessagePort(messagePort)) {
415
+ throw new IpcError('port must be of type MessagePort');
416
+ }
417
+ if (isMessagePortOpen) {
418
+ return messagePort;
419
+ }
420
+ const eventPromise = getFirstEvent(messagePort, {
421
+ message: Message$1
422
+ });
423
+ messagePort.start();
424
+ const {
425
+ event,
426
+ type
427
+ } = await eventPromise;
428
+ if (type !== Message$1) {
429
+ throw new IpcError('Failed to wait for ipc message');
430
+ }
431
+ if (event.data !== readyMessage) {
432
+ throw new IpcError('unexpected first message');
433
+ }
434
+ return messagePort;
435
+ };
436
+ const signal$1 = messagePort => {
437
+ messagePort.start();
438
+ };
439
+ class IpcParentWithMessagePort extends Ipc {
440
+ getData = getData$2;
441
+ send(message) {
442
+ this._rawIpc.postMessage(message);
443
+ }
444
+ sendAndTransfer(message) {
445
+ const transfer = getTransferrables(message);
446
+ this._rawIpc.postMessage(message, transfer);
447
+ }
448
+ dispose() {
449
+ this._rawIpc.close();
450
+ }
451
+ onMessage(callback) {
452
+ this._rawIpc.addEventListener('message', callback);
453
+ }
454
+ onClose(callback) {}
455
+ }
456
+ const wrap$5 = messagePort => {
457
+ return new IpcParentWithMessagePort(messagePort);
458
+ };
459
+ const IpcParentWithMessagePort$1 = {
460
+ __proto__: null,
461
+ create: create$5$1,
462
+ signal: signal$1,
463
+ wrap: wrap$5
464
+ };
465
+
466
+ class CommandNotFoundError extends Error {
467
+ constructor(command) {
468
+ super(`Command not found ${command}`);
469
+ this.name = 'CommandNotFoundError';
470
+ }
471
+ }
472
+ const commands = Object.create(null);
473
+ const register = commandMap => {
474
+ Object.assign(commands, commandMap);
475
+ };
476
+ const getCommand = key => {
477
+ return commands[key];
478
+ };
479
+ const execute = (command, ...args) => {
480
+ const fn = getCommand(command);
481
+ if (!fn) {
482
+ throw new CommandNotFoundError(command);
483
+ }
484
+ return fn(...args);
485
+ };
486
+
487
+ const Two$1 = '2.0';
488
+ const callbacks = Object.create(null);
489
+ const get$3 = id => {
490
+ return callbacks[id];
491
+ };
492
+ const remove$1 = id => {
493
+ delete callbacks[id];
494
+ };
495
+ class JsonRpcError extends Error {
496
+ constructor(message) {
497
+ super(message);
498
+ this.name = 'JsonRpcError';
499
+ }
500
+ }
501
+ const NewLine = '\n';
502
+ const DomException = 'DOMException';
503
+ const ReferenceError$1 = 'ReferenceError';
504
+ const SyntaxError$1 = 'SyntaxError';
505
+ const TypeError$1 = 'TypeError';
506
+ const getErrorConstructor = (message, type) => {
507
+ if (type) {
508
+ switch (type) {
509
+ case DomException:
510
+ return DOMException;
511
+ case ReferenceError$1:
512
+ return ReferenceError;
513
+ case SyntaxError$1:
514
+ return SyntaxError;
515
+ case TypeError$1:
516
+ return TypeError;
517
+ default:
518
+ return Error;
519
+ }
520
+ }
521
+ if (message.startsWith('TypeError: ')) {
522
+ return TypeError;
523
+ }
524
+ if (message.startsWith('SyntaxError: ')) {
525
+ return SyntaxError;
526
+ }
527
+ if (message.startsWith('ReferenceError: ')) {
528
+ return ReferenceError;
529
+ }
530
+ return Error;
531
+ };
532
+ const constructError = (message, type, name) => {
533
+ const ErrorConstructor = getErrorConstructor(message, type);
534
+ if (ErrorConstructor === DOMException && name) {
535
+ return new ErrorConstructor(message, name);
536
+ }
537
+ if (ErrorConstructor === Error) {
538
+ const error = new Error(message);
539
+ if (name && name !== 'VError') {
540
+ error.name = name;
541
+ }
542
+ return error;
543
+ }
544
+ return new ErrorConstructor(message);
545
+ };
546
+ const joinLines = lines => {
547
+ return lines.join(NewLine);
548
+ };
549
+ const splitLines = lines => {
550
+ return lines.split(NewLine);
551
+ };
552
+ const getCurrentStack = () => {
553
+ const stackLinesToSkip = 3;
554
+ const currentStack = joinLines(splitLines(new Error().stack || '').slice(stackLinesToSkip));
555
+ return currentStack;
556
+ };
557
+ const getNewLineIndex = (string, startIndex = undefined) => {
558
+ return string.indexOf(NewLine, startIndex);
559
+ };
560
+ const getParentStack = error => {
561
+ let parentStack = error.stack || error.data || error.message || '';
562
+ if (parentStack.startsWith(' at')) {
563
+ parentStack = error.message + NewLine + parentStack;
564
+ }
565
+ return parentStack;
566
+ };
567
+ const MethodNotFound = -32601;
568
+ const Custom = -32001;
569
+ const restoreJsonRpcError = error => {
570
+ const currentStack = getCurrentStack();
571
+ if (error && error instanceof Error) {
572
+ if (typeof error.stack === 'string') {
573
+ error.stack = error.stack + NewLine + currentStack;
574
+ }
575
+ return error;
576
+ }
577
+ if (error && error.code && error.code === MethodNotFound) {
578
+ const restoredError = new JsonRpcError(error.message);
579
+ const parentStack = getParentStack(error);
580
+ restoredError.stack = parentStack + NewLine + currentStack;
581
+ return restoredError;
582
+ }
583
+ if (error && error.message) {
584
+ const restoredError = constructError(error.message, error.type, error.name);
585
+ if (error.data) {
586
+ if (error.data.stack && error.data.type && error.message) {
587
+ restoredError.stack = error.data.type + ': ' + error.message + NewLine + error.data.stack + NewLine + currentStack;
588
+ } else if (error.data.stack) {
589
+ restoredError.stack = error.data.stack;
590
+ }
591
+ if (error.data.codeFrame) {
592
+ // @ts-ignore
593
+ restoredError.codeFrame = error.data.codeFrame;
594
+ }
595
+ if (error.data.code) {
596
+ // @ts-ignore
597
+ restoredError.code = error.data.code;
598
+ }
599
+ if (error.data.type) {
600
+ // @ts-ignore
601
+ restoredError.name = error.data.type;
602
+ }
603
+ } else {
604
+ if (error.stack) {
605
+ const lowerStack = restoredError.stack || '';
606
+ // @ts-ignore
607
+ const indexNewLine = getNewLineIndex(lowerStack);
608
+ const parentStack = getParentStack(error);
609
+ // @ts-ignore
610
+ restoredError.stack = parentStack + lowerStack.slice(indexNewLine);
611
+ }
612
+ if (error.codeFrame) {
613
+ // @ts-ignore
614
+ restoredError.codeFrame = error.codeFrame;
615
+ }
616
+ }
617
+ return restoredError;
618
+ }
619
+ if (typeof error === 'string') {
620
+ return new Error(`JsonRpc Error: ${error}`);
621
+ }
622
+ return new Error(`JsonRpc Error: ${error}`);
623
+ };
624
+ const unwrapJsonRpcResult = responseMessage => {
625
+ if ('error' in responseMessage) {
626
+ const restoredError = restoreJsonRpcError(responseMessage.error);
627
+ throw restoredError;
628
+ }
629
+ if ('result' in responseMessage) {
630
+ return responseMessage.result;
631
+ }
632
+ throw new JsonRpcError('unexpected response message');
633
+ };
634
+ const warn = (...args) => {
635
+ console.warn(...args);
636
+ };
637
+ const resolve = (id, response) => {
638
+ const fn = get$3(id);
639
+ if (!fn) {
640
+ console.log(response);
641
+ warn(`callback ${id} may already be disposed`);
642
+ return;
643
+ }
644
+ fn(response);
645
+ remove$1(id);
646
+ };
647
+ const E_COMMAND_NOT_FOUND = 'E_COMMAND_NOT_FOUND';
648
+ const getErrorType = prettyError => {
649
+ if (prettyError && prettyError.type) {
650
+ return prettyError.type;
651
+ }
652
+ if (prettyError && prettyError.constructor && prettyError.constructor.name) {
653
+ return prettyError.constructor.name;
654
+ }
655
+ return undefined;
656
+ };
657
+ const isAlreadyStack = line => {
658
+ return line.trim().startsWith('at ');
659
+ };
660
+ const getStack = prettyError => {
661
+ const stackString = prettyError.stack || '';
662
+ const newLineIndex = stackString.indexOf('\n');
663
+ if (newLineIndex !== -1 && !isAlreadyStack(stackString.slice(0, newLineIndex))) {
664
+ return stackString.slice(newLineIndex + 1);
665
+ }
666
+ return stackString;
667
+ };
668
+ const getErrorProperty = (error, prettyError) => {
669
+ if (error && error.code === E_COMMAND_NOT_FOUND) {
670
+ return {
671
+ code: MethodNotFound,
672
+ data: error.stack,
673
+ message: error.message
674
+ };
675
+ }
676
+ return {
677
+ code: Custom,
678
+ data: {
679
+ code: prettyError.code,
680
+ codeFrame: prettyError.codeFrame,
681
+ name: prettyError.name,
682
+ stack: getStack(prettyError),
683
+ type: getErrorType(prettyError)
684
+ },
685
+ message: prettyError.message
686
+ };
687
+ };
688
+ const create$1$1 = (id, error) => {
689
+ return {
690
+ error,
691
+ id,
692
+ jsonrpc: Two$1
693
+ };
694
+ };
695
+ const getErrorResponse = (id, error, preparePrettyError, logError) => {
696
+ const prettyError = preparePrettyError(error);
697
+ logError(error, prettyError);
698
+ const errorProperty = getErrorProperty(error, prettyError);
699
+ return create$1$1(id, errorProperty);
700
+ };
701
+ const create$9 = (message, result) => {
702
+ return {
703
+ id: message.id,
704
+ jsonrpc: Two$1,
705
+ result: result ?? null
706
+ };
707
+ };
708
+ const getSuccessResponse = (message, result) => {
709
+ const resultProperty = result ?? null;
710
+ return create$9(message, resultProperty);
711
+ };
712
+ const getErrorResponseSimple = (id, error) => {
713
+ return {
714
+ error: {
715
+ code: Custom,
716
+ data: error,
717
+ // @ts-ignore
718
+ message: error.message
719
+ },
720
+ id,
721
+ jsonrpc: Two$1
722
+ };
723
+ };
724
+ const getResponse = async (message, ipc, execute, preparePrettyError, logError, requiresSocket) => {
725
+ try {
726
+ const result = requiresSocket(message.method) ? await execute(message.method, ipc, ...message.params) : await execute(message.method, ...message.params);
727
+ return getSuccessResponse(message, result);
728
+ } catch (error) {
729
+ if (ipc.canUseSimpleErrorResponse) {
730
+ return getErrorResponseSimple(message.id, error);
731
+ }
732
+ return getErrorResponse(message.id, error, preparePrettyError, logError);
733
+ }
734
+ };
735
+ const defaultPreparePrettyError = error => {
736
+ return error;
737
+ };
738
+ const defaultLogError = () => {
739
+ // ignore
740
+ };
741
+ const defaultRequiresSocket = () => {
742
+ return false;
743
+ };
744
+ const defaultResolve = resolve;
745
+
746
+ // TODO maybe remove this in v6 or v7, only accept options object to simplify the code
747
+ const normalizeParams = args => {
748
+ if (args.length === 1) {
749
+ const options = args[0];
750
+ return {
751
+ execute: options.execute,
752
+ ipc: options.ipc,
753
+ logError: options.logError || defaultLogError,
754
+ message: options.message,
755
+ preparePrettyError: options.preparePrettyError || defaultPreparePrettyError,
756
+ requiresSocket: options.requiresSocket || defaultRequiresSocket,
757
+ resolve: options.resolve || defaultResolve
758
+ };
759
+ }
760
+ return {
761
+ execute: args[2],
762
+ ipc: args[0],
763
+ logError: args[5],
764
+ message: args[1],
765
+ preparePrettyError: args[4],
766
+ requiresSocket: args[6],
767
+ resolve: args[3]
768
+ };
769
+ };
770
+ const handleJsonRpcMessage = async (...args) => {
771
+ const options = normalizeParams(args);
772
+ const {
773
+ execute,
774
+ ipc,
775
+ logError,
776
+ message,
777
+ preparePrettyError,
778
+ requiresSocket,
779
+ resolve
780
+ } = options;
781
+ if ('id' in message) {
782
+ if ('method' in message) {
783
+ const response = await getResponse(message, ipc, execute, preparePrettyError, logError, requiresSocket);
784
+ try {
785
+ ipc.send(response);
786
+ } catch (error) {
787
+ const errorResponse = getErrorResponse(message.id, error, preparePrettyError, logError);
788
+ ipc.send(errorResponse);
789
+ }
790
+ return;
791
+ }
792
+ resolve(message.id, message);
793
+ return;
794
+ }
795
+ if ('method' in message) {
796
+ await getResponse(message, ipc, execute, preparePrettyError, logError, requiresSocket);
797
+ return;
798
+ }
799
+ throw new JsonRpcError('unexpected message');
800
+ };
801
+
802
+ const Two = '2.0';
803
+
804
+ const create$8 = (method, params) => {
805
+ return {
806
+ jsonrpc: Two,
807
+ method,
808
+ params
809
+ };
810
+ };
811
+
812
+ const create$7 = (id, method, params) => {
813
+ const message = {
814
+ id,
815
+ jsonrpc: Two,
816
+ method,
817
+ params
818
+ };
819
+ return message;
820
+ };
821
+
822
+ let id$1 = 0;
823
+ const create$6 = () => {
824
+ return ++id$1;
825
+ };
826
+
827
+ const registerPromise = map => {
828
+ const id = create$6();
829
+ const {
830
+ promise,
831
+ resolve
832
+ } = Promise.withResolvers();
833
+ map[id] = resolve;
834
+ return {
835
+ id,
836
+ promise
837
+ };
838
+ };
839
+
840
+ const invokeHelper = async (callbacks, ipc, method, params, useSendAndTransfer) => {
841
+ const {
842
+ id,
843
+ promise
844
+ } = registerPromise(callbacks);
845
+ const message = create$7(id, method, params);
846
+ if (useSendAndTransfer && ipc.sendAndTransfer) {
847
+ ipc.sendAndTransfer(message);
848
+ } else {
849
+ ipc.send(message);
850
+ }
851
+ const responseMessage = await promise;
852
+ return unwrapJsonRpcResult(responseMessage);
853
+ };
854
+ const createRpc = ipc => {
855
+ const callbacks = Object.create(null);
856
+ ipc._resolve = (id, response) => {
857
+ const fn = callbacks[id];
858
+ if (!fn) {
859
+ console.warn(`callback ${id} may already be disposed`);
860
+ return;
861
+ }
862
+ fn(response);
863
+ delete callbacks[id];
864
+ };
865
+ const rpc = {
866
+ async dispose() {
867
+ await ipc?.dispose();
868
+ },
869
+ invoke(method, ...params) {
870
+ return invokeHelper(callbacks, ipc, method, params, false);
871
+ },
872
+ invokeAndTransfer(method, ...params) {
873
+ return invokeHelper(callbacks, ipc, method, params, true);
874
+ },
875
+ // @ts-ignore
876
+ ipc,
877
+ /**
878
+ * @deprecated
879
+ */
880
+ send(method, ...params) {
881
+ const message = create$8(method, params);
882
+ ipc.send(message);
883
+ }
884
+ };
885
+ return rpc;
886
+ };
887
+
888
+ const requiresSocket = () => {
889
+ return false;
890
+ };
891
+ const preparePrettyError = error => {
892
+ return error;
893
+ };
894
+ const logError = () => {
895
+ // handled by renderer worker
896
+ };
897
+ const handleMessage = event => {
898
+ const actualRequiresSocket = event?.target?.requiresSocket || requiresSocket;
899
+ const actualExecute = event?.target?.execute || execute;
900
+ return handleJsonRpcMessage(event.target, event.data, actualExecute, event.target._resolve, preparePrettyError, logError, actualRequiresSocket);
901
+ };
902
+
903
+ const handleIpc = ipc => {
904
+ if ('addEventListener' in ipc) {
905
+ ipc.addEventListener('message', handleMessage);
906
+ } else if ('on' in ipc) {
907
+ // deprecated
908
+ ipc.on('message', handleMessage);
909
+ }
910
+ };
911
+
912
+ const listen$1 = async (module, options) => {
913
+ const rawIpc = await module.listen(options);
914
+ if (module.signal) {
915
+ module.signal(rawIpc);
916
+ }
917
+ const ipc = module.wrap(rawIpc);
918
+ return ipc;
919
+ };
920
+
921
+ const create$5 = async ({
922
+ commandMap,
923
+ isMessagePortOpen = true,
924
+ messagePort
925
+ }) => {
926
+ // TODO create a commandMap per rpc instance
927
+ register(commandMap);
928
+ const rawIpc = await IpcParentWithMessagePort$1.create({
929
+ isMessagePortOpen,
930
+ messagePort
931
+ });
932
+ const ipc = IpcParentWithMessagePort$1.wrap(rawIpc);
933
+ handleIpc(ipc);
934
+ const rpc = createRpc(ipc);
935
+ messagePort.start();
936
+ return rpc;
937
+ };
938
+
939
+ const create$4 = async ({
940
+ commandMap,
941
+ isMessagePortOpen,
942
+ send
943
+ }) => {
944
+ const {
945
+ port1,
946
+ port2
947
+ } = new MessageChannel();
948
+ await send(port1);
949
+ return create$5({
950
+ commandMap,
951
+ isMessagePortOpen,
952
+ messagePort: port2
953
+ });
954
+ };
955
+
956
+ const create$3 = async ({
957
+ commandMap
958
+ }) => {
959
+ // TODO create a commandMap per rpc instance
960
+ register(commandMap);
961
+ const ipc = await listen$1(IpcChildWithModuleWorkerAndMessagePort$1);
962
+ handleIpc(ipc);
963
+ const rpc = createRpc(ipc);
964
+ return rpc;
965
+ };
966
+
967
+ const Button$1 = 'button';
968
+ const Status = 'status';
969
+
970
+ const MaskIcon = 'MaskIcon';
971
+
972
+ const Button = 1;
973
+ const Div = 4;
974
+ const Span = 8;
975
+ const Text = 12;
976
+ const Reference = 100;
977
+
978
+ const TargetName = 'event.target.name';
979
+
980
+ const ExtensionHostWorker = 44;
981
+ const RendererWorker = 1;
982
+
983
+ const SetDom2 = 'Viewlet.setDom2';
984
+ const SetPatches = 'Viewlet.setPatches';
985
+
986
+ const createMockRpc = ({
987
+ commandMap
988
+ }) => {
989
+ const invocations = [];
990
+ const invoke = (method, ...params) => {
991
+ invocations.push([method, ...params]);
992
+ const command = commandMap[method];
993
+ if (!command) {
994
+ throw new Error(`command ${method} not found`);
995
+ }
996
+ return command(...params);
997
+ };
998
+ const mockRpc = {
999
+ invocations,
1000
+ invoke,
1001
+ invokeAndTransfer: invoke
1002
+ };
1003
+ return mockRpc;
1004
+ };
1005
+
1006
+ const rpcs = Object.create(null);
1007
+ const set$3 = (id, rpc) => {
1008
+ rpcs[id] = rpc;
1009
+ };
1010
+ const get$2 = id => {
1011
+ return rpcs[id];
1012
+ };
1013
+ const remove = id => {
1014
+ delete rpcs[id];
1015
+ };
1016
+
1017
+ /* eslint-disable @typescript-eslint/explicit-function-return-type */
1018
+ const create$2 = rpcId => {
1019
+ return {
1020
+ async dispose() {
1021
+ const rpc = get$2(rpcId);
1022
+ await rpc.dispose();
1023
+ },
1024
+ // @ts-ignore
1025
+ invoke(method, ...params) {
1026
+ const rpc = get$2(rpcId);
1027
+ // @ts-ignore
1028
+ return rpc.invoke(method, ...params);
1029
+ },
1030
+ // @ts-ignore
1031
+ invokeAndTransfer(method, ...params) {
1032
+ const rpc = get$2(rpcId);
1033
+ // @ts-ignore
1034
+ return rpc.invokeAndTransfer(method, ...params);
1035
+ },
1036
+ registerMockRpc(commandMap) {
1037
+ const mockRpc = createMockRpc({
1038
+ commandMap
1039
+ });
1040
+ set$3(rpcId, mockRpc);
1041
+ // @ts-ignore
1042
+ mockRpc[Symbol.dispose] = () => {
1043
+ remove(rpcId);
1044
+ };
1045
+ // @ts-ignore
1046
+ return mockRpc;
1047
+ },
1048
+ set(rpc) {
1049
+ set$3(rpcId, rpc);
1050
+ }
1051
+ };
1052
+ };
1053
+
1054
+ const {
1055
+ invoke: invoke$1,
1056
+ set: set$2
1057
+ } = create$2(ExtensionHostWorker);
1058
+
1059
+ const {
1060
+ invoke,
1061
+ invokeAndTransfer,
1062
+ set: set$1
1063
+ } = create$2(RendererWorker);
1064
+ const sendMessagePortToExtensionHostWorker$1 = async (port, rpcId = 0) => {
1065
+ const command = 'HandleMessagePort.handleMessagePort2';
1066
+ await invokeAndTransfer('SendMessagePortToExtensionHostWorker.sendMessagePortToExtensionHostWorker', port, command, rpcId);
1067
+ };
1068
+ const activateByEvent$1 = (event, assetDir, platform) => {
1069
+ return invoke('ExtensionHostManagement.activateByEvent', event, assetDir, platform);
1070
+ };
1071
+ const getPreference = async key => {
1072
+ return await invoke('Preferences.get', key);
1073
+ };
1074
+
1075
+ const toCommandId = key => {
1076
+ const dotIndex = key.indexOf('.');
1077
+ return key.slice(dotIndex + 1);
1078
+ };
1079
+ const create$1 = () => {
1080
+ const states = Object.create(null);
1081
+ const commandMapRef = {};
1082
+ return {
1083
+ clear() {
1084
+ for (const key of Object.keys(states)) {
1085
+ delete states[key];
1086
+ }
1087
+ },
1088
+ diff(uid, modules, numbers) {
1089
+ const {
1090
+ newState,
1091
+ oldState
1092
+ } = states[uid];
1093
+ const diffResult = [];
1094
+ for (let i = 0; i < modules.length; i++) {
1095
+ const fn = modules[i];
1096
+ if (!fn(oldState, newState)) {
1097
+ diffResult.push(numbers[i]);
1098
+ }
1099
+ }
1100
+ return diffResult;
1101
+ },
1102
+ dispose(uid) {
1103
+ delete states[uid];
1104
+ },
1105
+ get(uid) {
1106
+ return states[uid];
1107
+ },
1108
+ getCommandIds() {
1109
+ const keys = Object.keys(commandMapRef);
1110
+ const ids = keys.map(toCommandId);
1111
+ return ids;
1112
+ },
1113
+ getKeys() {
1114
+ return Object.keys(states).map(key => {
1115
+ return Number.parseFloat(key);
1116
+ });
1117
+ },
1118
+ registerCommands(commandMap) {
1119
+ Object.assign(commandMapRef, commandMap);
1120
+ },
1121
+ set(uid, oldState, newState) {
1122
+ states[uid] = {
1123
+ newState,
1124
+ oldState
1125
+ };
1126
+ },
1127
+ wrapCommand(fn) {
1128
+ const wrapped = async (uid, ...args) => {
1129
+ const {
1130
+ newState,
1131
+ oldState
1132
+ } = states[uid];
1133
+ const newerState = await fn(newState, ...args);
1134
+ if (oldState === newerState || newState === newerState) {
1135
+ return;
1136
+ }
1137
+ const latestOld = states[uid];
1138
+ const latestNew = {
1139
+ ...latestOld.newState,
1140
+ ...newerState
1141
+ };
1142
+ states[uid] = {
1143
+ newState: latestNew,
1144
+ oldState: latestOld.oldState
1145
+ };
1146
+ };
1147
+ return wrapped;
1148
+ },
1149
+ wrapGetter(fn) {
1150
+ const wrapped = (uid, ...args) => {
1151
+ const {
1152
+ newState
1153
+ } = states[uid];
1154
+ return fn(newState, ...args);
1155
+ };
1156
+ return wrapped;
1157
+ },
1158
+ wrapLoadContent(fn) {
1159
+ const wrapped = async (uid, ...args) => {
1160
+ const {
1161
+ newState,
1162
+ oldState
1163
+ } = states[uid];
1164
+ const result = await fn(newState, ...args);
1165
+ const {
1166
+ error,
1167
+ state
1168
+ } = result;
1169
+ if (oldState === state || newState === state) {
1170
+ return {
1171
+ error
1172
+ };
1173
+ }
1174
+ const latestOld = states[uid];
1175
+ const latestNew = {
1176
+ ...latestOld.newState,
1177
+ ...state
1178
+ };
1179
+ states[uid] = {
1180
+ newState: latestNew,
1181
+ oldState: latestOld.oldState
1182
+ };
1183
+ return {
1184
+ error
1185
+ };
1186
+ };
1187
+ return wrapped;
1188
+ }
1189
+ };
1190
+ };
1191
+ const terminate = () => {
1192
+ globalThis.close();
1193
+ };
1194
+
1195
+ const {
1196
+ get: get$1,
1197
+ getCommandIds,
1198
+ registerCommands,
1199
+ set,
1200
+ wrapCommand,
1201
+ wrapGetter
1202
+ } = create$1();
1203
+
1204
+ const create = (uid, uri, x, y, width, height, platform, assetDir) => {
1205
+ const state = {
1206
+ assetDir,
1207
+ errorCount: 0,
1208
+ initial: true,
1209
+ platform,
1210
+ statusBarItemsLeft: [],
1211
+ statusBarItemsRight: [],
1212
+ uid,
1213
+ warningCount: 0
1214
+ };
1215
+ set(uid, state, state);
1216
+ };
1217
+
1218
+ const isEqual = (oldState, newState) => {
1219
+ return oldState.statusBarItemsLeft === newState.statusBarItemsLeft && oldState.statusBarItemsRight === newState.statusBarItemsRight;
1220
+ };
1221
+
1222
+ const RenderItems = 4;
1223
+ const RenderIncremental = 11;
1224
+
1225
+ const modules = [isEqual];
1226
+ const numbers = [RenderIncremental];
1227
+
1228
+ const diff = (oldState, newState) => {
1229
+ const diffResult = [];
1230
+ for (let i = 0; i < modules.length; i++) {
1231
+ const fn = modules[i];
1232
+ if (!fn(oldState, newState)) {
1233
+ diffResult.push(numbers[i]);
1234
+ }
1235
+ }
1236
+ return diffResult;
1237
+ };
1238
+
1239
+ const diff2 = uid => {
1240
+ const {
1241
+ newState,
1242
+ oldState
1243
+ } = get$1(uid);
1244
+ const result = diff(oldState, newState);
1245
+ return result;
1246
+ };
1247
+
1248
+ const getMatchingItem = (itemsLeft, itemsRight, name) => {
1249
+ for (const item of itemsLeft) {
1250
+ if (item.name === name) {
1251
+ return item;
1252
+ }
1253
+ }
1254
+ for (const item of itemsRight) {
1255
+ if (item.name === name) {
1256
+ return item;
1257
+ }
1258
+ }
1259
+ return undefined;
1260
+ };
1261
+
1262
+ const handleClickExtensionStatusBarItem = async name => {
1263
+ // @ts-ignore
1264
+ await invoke$1(`ExtensionHostStatusBar.executeCommand`, name);
1265
+ };
1266
+
1267
+ const handleClickNotification = async () => {
1268
+ // TODO toggle notifications
1269
+ };
1270
+
1271
+ const handleClickProblems = async () => {
1272
+ // @ts-ignore
1273
+ await invoke('Layout.showPanel');
1274
+ // @ts-ignore
1275
+ await invoke('Panel.toggleView', 'Problems');
1276
+ };
1277
+
1278
+ const Notifications = 'Notifications';
1279
+ const Problems = 'Problems';
1280
+
1281
+ const handleClick = async (state, name) => {
1282
+ if (!name) {
1283
+ return state;
1284
+ }
1285
+ const {
1286
+ statusBarItemsLeft,
1287
+ statusBarItemsRight
1288
+ } = state;
1289
+ const item = getMatchingItem(statusBarItemsLeft, statusBarItemsRight, name);
1290
+ if (!item) {
1291
+ return state;
1292
+ }
1293
+ if (item.name === Notifications) {
1294
+ await handleClickNotification();
1295
+ } else if (item.name === Problems) {
1296
+ await handleClickProblems();
1297
+ } else {
1298
+ await handleClickExtensionStatusBarItem(name);
1299
+ }
1300
+ // TODO
1301
+ // sendExtensionWorker([/* statusBarItemHandleClick */ 7657, /* name */ name])
1302
+ return state;
1303
+ };
1304
+
1305
+ const id = 7201;
1306
+ const sendMessagePortToExtensionHostWorker = async port => {
1307
+ await sendMessagePortToExtensionHostWorker$1(port, id);
1308
+ };
1309
+
1310
+ const createExtensionHostRpc = async () => {
1311
+ try {
1312
+ const rpc = await create$4({
1313
+ commandMap: {},
1314
+ send: sendMessagePortToExtensionHostWorker
1315
+ });
1316
+ return rpc;
1317
+ } catch (error) {
1318
+ throw new VError(error, `Failed to create extension host rpc`);
1319
+ }
1320
+ };
1321
+
1322
+ const initialize = async () => {
1323
+ const rpc = await createExtensionHostRpc();
1324
+ set$2(rpc);
1325
+ };
1326
+
1327
+ const getIndex = (items, item) => {
1328
+ for (let i = 0; i < items.length; i++) {
1329
+ if (items[i].name === item.name) {
1330
+ return i;
1331
+ }
1332
+ }
1333
+ return -1;
1334
+ };
1335
+
1336
+ const updateArray = (items, newItem) => {
1337
+ const index = getIndex(items, newItem);
1338
+ const before = items.slice(0, index);
1339
+ const after = items.slice(index + 1);
1340
+ return [...before, newItem, ...after];
1341
+ };
1342
+
1343
+ const itemLeftUpdate = (state, newItem) => {
1344
+ return {
1345
+ ...state,
1346
+ statusBarItemsLeft: updateArray([...state.statusBarItemsLeft], newItem)
1347
+ };
1348
+ };
1349
+
1350
+ const itemRightCreate = (state, newItem) => {
1351
+ const {
1352
+ statusBarItemsRight
1353
+ } = state;
1354
+ const newStatusBarItemsRight = [...statusBarItemsRight, newItem];
1355
+ return {
1356
+ ...state,
1357
+ statusBarItemsRight: newStatusBarItemsRight
1358
+ };
1359
+ };
1360
+
1361
+ const itemRightUpdate = (state, newItem) => {
1362
+ const {
1363
+ statusBarItemsRight
1364
+ } = state;
1365
+ const newStatusBarItemsRight = updateArray([...statusBarItemsRight], newItem);
1366
+ return {
1367
+ ...state,
1368
+ statusBarItemsRight: newStatusBarItemsRight
1369
+ };
1370
+ };
1371
+
1372
+ const OnStatusBarItem = 'onStatusBarItem';
1373
+
1374
+ const GetStatusBarItems = 'ExtensionHost.getStatusBarItems2';
1375
+
1376
+ const activateByEvent = (event, assetDir, platform) => {
1377
+ // @ts-ignore
1378
+ return activateByEvent$1(event, assetDir, platform);
1379
+ };
1380
+
1381
+ const executeProviders = async ({
1382
+ assetDir,
1383
+ combineResults,
1384
+ event,
1385
+ method,
1386
+ noProviderFoundMessage = 'No provider found',
1387
+ noProviderFoundResult,
1388
+ params,
1389
+ platform
1390
+ }) => {
1391
+ await activateByEvent(event, assetDir, platform);
1392
+ // @ts-ignore
1393
+ const result = await invoke$1(method, ...params);
1394
+ return result;
1395
+ };
1396
+
1397
+ const combineResults = results => {
1398
+ return results.flat();
1399
+ };
1400
+ const getStatusBarItems$1 = (assetDir, platform) => {
1401
+ return executeProviders({
1402
+ assetDir,
1403
+ combineResults,
1404
+ event: OnStatusBarItem,
1405
+ method: GetStatusBarItems,
1406
+ noProviderFoundMessage: 'No status bar item provider found',
1407
+ noProviderFoundResult: [],
1408
+ params: [],
1409
+ platform
1410
+ });
1411
+ };
1412
+
1413
+ const ProblemsErrorIcon = 'ProblemsErrorIcon';
1414
+ const ProblemsWarningIcon = 'ProblemsWarningIcon';
1415
+ const StatusBarItem = 'StatusBarItem';
1416
+ const StatusBarItemsLeft = 'StatusBarItemsLeft';
1417
+ const StatusBarItemsRight = 'StatusBarItemsRight';
1418
+
1419
+ const getProblemsAriaLabel = (errorCount, warningCount) => {
1420
+ const parts = [];
1421
+ if (errorCount > 0) {
1422
+ parts.push(`${errorCount} ${errorCount === 1 ? 'Problem' : 'Problems'}`);
1423
+ }
1424
+ if (warningCount > 0) {
1425
+ parts.push(`${warningCount} ${warningCount === 1 ? 'Warning' : 'Warnings'}`);
1426
+ }
1427
+ if (parts.length === 0) {
1428
+ return 'No Problems';
1429
+ }
1430
+ return parts.join(', ');
1431
+ };
1432
+ const getBuiltinStatusBarItems = async (errorCount, warningCount) => {
1433
+ const extraItems = [{
1434
+ ariaLabel: 'Notifications',
1435
+ command: '',
1436
+ // TODO should show notifications center
1437
+ elements: [{
1438
+ type: 'text',
1439
+ value: 'Notifications'
1440
+ }],
1441
+ name: Notifications,
1442
+ tooltip: 'Notifications'
1443
+ }, {
1444
+ ariaLabel: getProblemsAriaLabel(errorCount, warningCount),
1445
+ command: '',
1446
+ // TODO should show problems view
1447
+ elements: [{
1448
+ type: 'icon',
1449
+ value: ProblemsErrorIcon
1450
+ }, {
1451
+ type: 'text',
1452
+ value: `${errorCount}`
1453
+ }, {
1454
+ type: 'icon',
1455
+ value: ProblemsWarningIcon
1456
+ }, {
1457
+ type: 'text',
1458
+ value: `${warningCount}`
1459
+ }],
1460
+ name: Problems,
1461
+ tooltip: 'Problems'
1462
+ }];
1463
+ return extraItems;
1464
+ };
1465
+
1466
+ const toStatusBarItem = uiStatusBarItem => {
1467
+ const elements = [];
1468
+ if (uiStatusBarItem.icon) {
1469
+ elements.push({
1470
+ type: 'icon',
1471
+ value: uiStatusBarItem.icon
1472
+ });
1473
+ }
1474
+ if (uiStatusBarItem.text) {
1475
+ elements.push({
1476
+ type: 'text',
1477
+ value: uiStatusBarItem.text
1478
+ });
1479
+ }
1480
+ if (elements.length === 0) {
1481
+ elements.push({
1482
+ type: 'text',
1483
+ value: ''
1484
+ });
1485
+ }
1486
+ const ariaLabel = uiStatusBarItem.text || uiStatusBarItem.tooltip || uiStatusBarItem.name;
1487
+ return {
1488
+ ariaLabel,
1489
+ command: uiStatusBarItem.command || undefined,
1490
+ elements,
1491
+ name: uiStatusBarItem.name,
1492
+ tooltip: uiStatusBarItem.tooltip
1493
+ };
1494
+ };
1495
+
1496
+ const getActualIcon = extensionHostStatusBarItem => {
1497
+ if (extensionHostStatusBarItem.icon === 'branch') {
1498
+ return 'Branch';
1499
+ }
1500
+ return extensionHostStatusBarItem.icon || '';
1501
+ };
1502
+ const toUiStatusBarItem = extensionHostStatusBarItem => {
1503
+ return {
1504
+ command: extensionHostStatusBarItem.command || '',
1505
+ icon: getActualIcon(extensionHostStatusBarItem),
1506
+ name: extensionHostStatusBarItem.id || extensionHostStatusBarItem.name || '',
1507
+ text: extensionHostStatusBarItem.text || '',
1508
+ tooltip: extensionHostStatusBarItem.tooltip || ''
1509
+ };
1510
+ };
1511
+
1512
+ const toUiStatusBarItems = statusBarItems => {
1513
+ if (!statusBarItems) {
1514
+ return [];
1515
+ }
1516
+ return statusBarItems.map(toUiStatusBarItem);
1517
+ };
1518
+
1519
+ const getStatusBarItems = async (showItems, assetDir, platform, errorCount, warningCount) => {
1520
+ if (!showItems) {
1521
+ return [];
1522
+ }
1523
+ await activateByEvent('onSourceControl', assetDir, platform);
1524
+ const extensionStatusBarItems = await getStatusBarItems$1(assetDir, platform);
1525
+ const uiStatusBarItems = toUiStatusBarItems(extensionStatusBarItems);
1526
+ const extraItems = await getBuiltinStatusBarItems(errorCount, warningCount);
1527
+ return [...uiStatusBarItems.map(toStatusBarItem), ...extraItems];
1528
+ };
1529
+
1530
+ const get = async key => {
1531
+ return getPreference(key);
1532
+ };
1533
+
1534
+ const itemsVisible = async () => {
1535
+ const statusBarItemsPreference = (await get('statusBar.itemsVisible')) ?? true;
1536
+ return statusBarItemsPreference;
1537
+ };
1538
+
1539
+ const loadContent = async state => {
1540
+ const {
1541
+ assetDir,
1542
+ errorCount,
1543
+ platform,
1544
+ warningCount
1545
+ } = state;
1546
+ const statusBarItemsPreference = await itemsVisible();
1547
+ const statusBarItems = await getStatusBarItems(statusBarItemsPreference, assetDir, platform, errorCount, warningCount);
1548
+ return {
1549
+ ...state,
1550
+ errorCount: 0,
1551
+ initial: false,
1552
+ statusBarItemsLeft: [...statusBarItems],
1553
+ statusBarItemsRight: [],
1554
+ warningCount: 0
1555
+ };
1556
+ };
1557
+
1558
+ const mergeClassNames = (...classNames) => {
1559
+ return classNames.filter(Boolean).join(' ');
1560
+ };
1561
+
1562
+ const text = data => {
1563
+ return {
1564
+ childCount: 0,
1565
+ text: data,
1566
+ type: Text
1567
+ };
1568
+ };
1569
+
1570
+ const SetText = 1;
1571
+ const Replace = 2;
1572
+ const SetAttribute = 3;
1573
+ const RemoveAttribute = 4;
1574
+ const Add = 6;
1575
+ const NavigateChild = 7;
1576
+ const NavigateParent = 8;
1577
+ const RemoveChild = 9;
1578
+ const NavigateSibling = 10;
1579
+ const SetReferenceNodeUid = 11;
1580
+
1581
+ const isKey = key => {
1582
+ return key !== 'type' && key !== 'childCount';
1583
+ };
1584
+
1585
+ const getKeys = node => {
1586
+ const keys = Object.keys(node).filter(isKey);
1587
+ return keys;
1588
+ };
1589
+
1590
+ const arrayToTree = nodes => {
1591
+ const result = [];
1592
+ let i = 0;
1593
+ while (i < nodes.length) {
1594
+ const node = nodes[i];
1595
+ const {
1596
+ children,
1597
+ nodesConsumed
1598
+ } = getChildrenWithCount(nodes, i + 1, node.childCount || 0);
1599
+ result.push({
1600
+ node,
1601
+ children
1602
+ });
1603
+ i += 1 + nodesConsumed;
1604
+ }
1605
+ return result;
1606
+ };
1607
+ const getChildrenWithCount = (nodes, startIndex, childCount) => {
1608
+ if (childCount === 0) {
1609
+ return {
1610
+ children: [],
1611
+ nodesConsumed: 0
1612
+ };
1613
+ }
1614
+ const children = [];
1615
+ let i = startIndex;
1616
+ let remaining = childCount;
1617
+ let totalConsumed = 0;
1618
+ while (remaining > 0 && i < nodes.length) {
1619
+ const node = nodes[i];
1620
+ const nodeChildCount = node.childCount || 0;
1621
+ const {
1622
+ children: nodeChildren,
1623
+ nodesConsumed
1624
+ } = getChildrenWithCount(nodes, i + 1, nodeChildCount);
1625
+ children.push({
1626
+ node,
1627
+ children: nodeChildren
1628
+ });
1629
+ const nodeSize = 1 + nodesConsumed;
1630
+ i += nodeSize;
1631
+ totalConsumed += nodeSize;
1632
+ remaining--;
1633
+ }
1634
+ return {
1635
+ children,
1636
+ nodesConsumed: totalConsumed
1637
+ };
1638
+ };
1639
+
1640
+ const compareNodes = (oldNode, newNode) => {
1641
+ const patches = [];
1642
+ // Check if node type changed - return null to signal incompatible nodes
1643
+ // (caller should handle this with a Replace operation)
1644
+ if (oldNode.type !== newNode.type) {
1645
+ return null;
1646
+ }
1647
+ // Handle reference nodes - special handling for uid changes
1648
+ if (oldNode.type === Reference) {
1649
+ if (oldNode.uid !== newNode.uid) {
1650
+ patches.push({
1651
+ type: SetReferenceNodeUid,
1652
+ uid: newNode.uid
1653
+ });
1654
+ }
1655
+ return patches;
1656
+ }
1657
+ // Handle text nodes
1658
+ if (oldNode.type === Text && newNode.type === Text) {
1659
+ if (oldNode.text !== newNode.text) {
1660
+ patches.push({
1661
+ type: SetText,
1662
+ value: newNode.text
1663
+ });
1664
+ }
1665
+ return patches;
1666
+ }
1667
+ // Compare attributes
1668
+ const oldKeys = getKeys(oldNode);
1669
+ const newKeys = getKeys(newNode);
1670
+ // Check for attribute changes
1671
+ for (const key of newKeys) {
1672
+ if (oldNode[key] !== newNode[key]) {
1673
+ patches.push({
1674
+ type: SetAttribute,
1675
+ key,
1676
+ value: newNode[key]
1677
+ });
1678
+ }
1679
+ }
1680
+ // Check for removed attributes
1681
+ for (const key of oldKeys) {
1682
+ if (!(key in newNode)) {
1683
+ patches.push({
1684
+ type: RemoveAttribute,
1685
+ key
1686
+ });
1687
+ }
1688
+ }
1689
+ return patches;
1690
+ };
1691
+
1692
+ const treeToArray = node => {
1693
+ const result = [node.node];
1694
+ for (const child of node.children) {
1695
+ result.push(...treeToArray(child));
1696
+ }
1697
+ return result;
1698
+ };
1699
+
1700
+ const diffChildren = (oldChildren, newChildren, patches) => {
1701
+ const maxLength = Math.max(oldChildren.length, newChildren.length);
1702
+ // Track where we are: -1 means at parent, >= 0 means at child index
1703
+ let currentChildIndex = -1;
1704
+ // Collect indices of children to remove (we'll add these patches at the end in reverse order)
1705
+ const indicesToRemove = [];
1706
+ for (let i = 0; i < maxLength; i++) {
1707
+ const oldNode = oldChildren[i];
1708
+ const newNode = newChildren[i];
1709
+ if (!oldNode && !newNode) {
1710
+ continue;
1711
+ }
1712
+ if (!oldNode) {
1713
+ // Add new node - we should be at the parent
1714
+ if (currentChildIndex >= 0) {
1715
+ // Navigate back to parent
1716
+ patches.push({
1717
+ type: NavigateParent
1718
+ });
1719
+ currentChildIndex = -1;
1720
+ }
1721
+ // Flatten the entire subtree so renderInternal can handle it
1722
+ const flatNodes = treeToArray(newNode);
1723
+ patches.push({
1724
+ type: Add,
1725
+ nodes: flatNodes
1726
+ });
1727
+ } else if (newNode) {
1728
+ // Compare nodes to see if we need any patches
1729
+ const nodePatches = compareNodes(oldNode.node, newNode.node);
1730
+ // If nodePatches is null, the node types are incompatible - need to replace
1731
+ if (nodePatches === null) {
1732
+ // Navigate to this child
1733
+ if (currentChildIndex === -1) {
1734
+ patches.push({
1735
+ type: NavigateChild,
1736
+ index: i
1737
+ });
1738
+ currentChildIndex = i;
1739
+ } else if (currentChildIndex !== i) {
1740
+ patches.push({
1741
+ type: NavigateSibling,
1742
+ index: i
1743
+ });
1744
+ currentChildIndex = i;
1745
+ }
1746
+ // Replace the entire subtree
1747
+ const flatNodes = treeToArray(newNode);
1748
+ patches.push({
1749
+ type: Replace,
1750
+ nodes: flatNodes
1751
+ });
1752
+ // After replace, we're at the new element (same position)
1753
+ continue;
1754
+ }
1755
+ // Check if we need to recurse into children
1756
+ const hasChildrenToCompare = oldNode.children.length > 0 || newNode.children.length > 0;
1757
+ // Only navigate to this element if we need to do something
1758
+ if (nodePatches.length > 0 || hasChildrenToCompare) {
1759
+ // Navigate to this child if not already there
1760
+ if (currentChildIndex === -1) {
1761
+ patches.push({
1762
+ type: NavigateChild,
1763
+ index: i
1764
+ });
1765
+ currentChildIndex = i;
1766
+ } else if (currentChildIndex !== i) {
1767
+ patches.push({
1768
+ type: NavigateSibling,
1769
+ index: i
1770
+ });
1771
+ currentChildIndex = i;
1772
+ }
1773
+ // Apply node patches (these apply to the current element, not children)
1774
+ if (nodePatches.length > 0) {
1775
+ patches.push(...nodePatches);
1776
+ }
1777
+ // Compare children recursively
1778
+ if (hasChildrenToCompare) {
1779
+ diffChildren(oldNode.children, newNode.children, patches);
1780
+ }
1781
+ }
1782
+ } else {
1783
+ // Remove old node - collect the index for later removal
1784
+ indicesToRemove.push(i);
1785
+ }
1786
+ }
1787
+ // Navigate back to parent if we ended at a child
1788
+ if (currentChildIndex >= 0) {
1789
+ patches.push({
1790
+ type: NavigateParent
1791
+ });
1792
+ currentChildIndex = -1;
1793
+ }
1794
+ // Add remove patches in reverse order (highest index first)
1795
+ // This ensures indices remain valid as we remove
1796
+ for (let j = indicesToRemove.length - 1; j >= 0; j--) {
1797
+ patches.push({
1798
+ type: RemoveChild,
1799
+ index: indicesToRemove[j]
1800
+ });
1801
+ }
1802
+ };
1803
+ const diffTrees = (oldTree, newTree, patches, path) => {
1804
+ // At the root level (path.length === 0), we're already AT the element
1805
+ // So we compare the root node directly, then compare its children
1806
+ if (path.length === 0 && oldTree.length === 1 && newTree.length === 1) {
1807
+ const oldNode = oldTree[0];
1808
+ const newNode = newTree[0];
1809
+ // Compare root nodes
1810
+ const nodePatches = compareNodes(oldNode.node, newNode.node);
1811
+ // If nodePatches is null, the root node types are incompatible - need to replace
1812
+ if (nodePatches === null) {
1813
+ const flatNodes = treeToArray(newNode);
1814
+ patches.push({
1815
+ type: Replace,
1816
+ nodes: flatNodes
1817
+ });
1818
+ return;
1819
+ }
1820
+ if (nodePatches.length > 0) {
1821
+ patches.push(...nodePatches);
1822
+ }
1823
+ // Compare children
1824
+ if (oldNode.children.length > 0 || newNode.children.length > 0) {
1825
+ diffChildren(oldNode.children, newNode.children, patches);
1826
+ }
1827
+ } else {
1828
+ // Non-root level or multiple root elements - use the regular comparison
1829
+ diffChildren(oldTree, newTree, patches);
1830
+ }
1831
+ };
1832
+
1833
+ const removeTrailingNavigationPatches = patches => {
1834
+ // Find the last non-navigation patch
1835
+ let lastNonNavigationIndex = -1;
1836
+ for (let i = patches.length - 1; i >= 0; i--) {
1837
+ const patch = patches[i];
1838
+ if (patch.type !== NavigateChild && patch.type !== NavigateParent && patch.type !== NavigateSibling) {
1839
+ lastNonNavigationIndex = i;
1840
+ break;
1841
+ }
1842
+ }
1843
+ // Return patches up to and including the last non-navigation patch
1844
+ return lastNonNavigationIndex === -1 ? [] : patches.slice(0, lastNonNavigationIndex + 1);
1845
+ };
1846
+
1847
+ const diffTree = (oldNodes, newNodes) => {
1848
+ // Step 1: Convert flat arrays to tree structures
1849
+ const oldTree = arrayToTree(oldNodes);
1850
+ const newTree = arrayToTree(newNodes);
1851
+ // Step 3: Compare the trees
1852
+ const patches = [];
1853
+ diffTrees(oldTree, newTree, patches, []);
1854
+ // Remove trailing navigation patches since they serve no purpose
1855
+ return removeTrailingNavigationPatches(patches);
1856
+ };
1857
+
1858
+ const HandleClick = 11;
1859
+
1860
+ const getTextVirtualDom = element => {
1861
+ return [{
1862
+ childCount: 1,
1863
+ className: 'StatusBarItemLabel',
1864
+ type: Span
1865
+ }, text(element.value)];
1866
+ };
1867
+ const getIconVirtualDom = element => {
1868
+ return [{
1869
+ childCount: 0,
1870
+ className: mergeClassNames(MaskIcon, element.value),
1871
+ type: Div
1872
+ }];
1873
+ };
1874
+ const getStatusBarItemElementVirtualDom = element => {
1875
+ if (element.type === 'text') {
1876
+ return getTextVirtualDom(element);
1877
+ }
1878
+ if (element.type === 'icon') {
1879
+ return getIconVirtualDom(element);
1880
+ }
1881
+ return [];
1882
+ };
1883
+
1884
+ const getStatusBarItemVirtualDom = statusBarItem => {
1885
+ const {
1886
+ ariaLabel,
1887
+ elements,
1888
+ name,
1889
+ tooltip
1890
+ } = statusBarItem;
1891
+ const elementNodes = elements.flatMap(getStatusBarItemElementVirtualDom);
1892
+ const buttonNode = {
1893
+ ariaLabel,
1894
+ childCount: elements.length,
1895
+ className: StatusBarItem,
1896
+ name,
1897
+ role: Button$1,
1898
+ tabIndex: -1,
1899
+ title: tooltip,
1900
+ type: Button
1901
+ };
1902
+ return [buttonNode, ...elementNodes];
1903
+ };
1904
+
1905
+ const getStatusBarItemsVirtualDom = (items, className) => {
1906
+ if (items.length === 0) {
1907
+ return [];
1908
+ }
1909
+ return [{
1910
+ childCount: items.length,
1911
+ className,
1912
+ type: Div
1913
+ }, ...items.flatMap(getStatusBarItemVirtualDom)];
1914
+ };
1915
+
1916
+ const getStatusBarItemsLeftDom = statusBarItemsLeft => {
1917
+ return getStatusBarItemsVirtualDom(statusBarItemsLeft, StatusBarItemsLeft);
1918
+ };
1919
+
1920
+ const getStatusBarItemsRightDom = statusBarItemsRight => {
1921
+ return getStatusBarItemsVirtualDom(statusBarItemsRight, StatusBarItemsRight);
1922
+ };
1923
+
1924
+ const getChildCount = (leftCount, rightCount) => {
1925
+ let count = 0;
1926
+ if (leftCount > 0) {
1927
+ count++;
1928
+ }
1929
+ if (rightCount > 0) {
1930
+ count++;
1931
+ }
1932
+ return count;
1933
+ };
1934
+ const getStatusBarVirtualDom = (statusBarItemsLeft, statusBarItemsRight) => {
1935
+ const dom = [{
1936
+ childCount: getChildCount(statusBarItemsLeft.length, statusBarItemsRight.length),
1937
+ className: 'StatusBar',
1938
+ onClick: HandleClick,
1939
+ role: Status,
1940
+ type: Div
1941
+ }, ...getStatusBarItemsLeftDom(statusBarItemsLeft), ...getStatusBarItemsRightDom(statusBarItemsRight)];
1942
+ return dom;
1943
+ };
1944
+
1945
+ const renderItems = (oldState, newState) => {
1946
+ const {
1947
+ initial,
1948
+ statusBarItemsLeft,
1949
+ statusBarItemsRight,
1950
+ uid
1951
+ } = newState;
1952
+ if (initial) {
1953
+ return [SetDom2, uid, []];
1954
+ }
1955
+ const dom = getStatusBarVirtualDom(statusBarItemsLeft, statusBarItemsRight);
1956
+ return [SetDom2, uid, dom];
1957
+ };
1958
+
1959
+ const renderIncremental = (oldState, newState) => {
1960
+ const oldDom = renderItems(oldState, oldState)[2];
1961
+ const newDom = renderItems(newState, newState)[2];
1962
+ const patches = diffTree(oldDom, newDom);
1963
+ return [SetPatches, newState.uid, patches];
1964
+ };
1965
+
1966
+ const getRenderer = diffType => {
1967
+ switch (diffType) {
1968
+ case RenderIncremental:
1969
+ return renderIncremental;
1970
+ case RenderItems:
1971
+ return renderItems;
1972
+ default:
1973
+ throw new Error('unknown renderer');
1974
+ }
1975
+ };
1976
+
1977
+ const applyRender = (oldState, newState, diffResult) => {
1978
+ const commands = [];
1979
+ for (const item of diffResult) {
1980
+ const fn = getRenderer(item);
1981
+ const result = fn(oldState, newState);
1982
+ if (result.length > 0) {
1983
+ commands.push(result);
1984
+ }
1985
+ }
1986
+ return commands;
1987
+ };
1988
+
1989
+ const render2 = (uid, diffResult) => {
1990
+ const {
1991
+ newState,
1992
+ oldState
1993
+ } = get$1(uid);
1994
+ set(uid, newState, newState);
1995
+ const commands = applyRender(oldState, newState, diffResult);
1996
+ return commands;
1997
+ };
1998
+
1999
+ const renderEventListeners = () => {
2000
+ return [{
2001
+ name: HandleClick,
2002
+ params: ['handleClick', TargetName]
2003
+ }];
2004
+ };
2005
+
2006
+ const resize = (state, dimensions) => {
2007
+ return {
2008
+ ...state,
2009
+ ...dimensions
2010
+ };
2011
+ };
2012
+
2013
+ const saveState = state => {
2014
+ const {
2015
+ statusBarItemsLeft,
2016
+ statusBarItemsRight
2017
+ } = state;
2018
+ return {
2019
+ itemsLeft: statusBarItemsLeft,
2020
+ itemsRight: statusBarItemsRight
2021
+ };
2022
+ };
2023
+
2024
+ const commandMap = {
2025
+ 'StatusBar.create': create,
2026
+ 'StatusBar.diff2': diff2,
2027
+ 'StatusBar.getCommandIds': getCommandIds,
2028
+ 'StatusBar.handleClick': wrapCommand(handleClick),
2029
+ 'StatusBar.initialize': initialize,
2030
+ 'StatusBar.itemLeftUpdate': wrapCommand(itemLeftUpdate),
2031
+ 'StatusBar.itemRightCreate': wrapCommand(itemRightCreate),
2032
+ 'StatusBar.itemRightUpdate': wrapCommand(itemRightUpdate),
2033
+ 'StatusBar.loadContent': wrapCommand(loadContent),
2034
+ 'StatusBar.render2': render2,
2035
+ 'StatusBar.renderEventListeners': renderEventListeners,
2036
+ 'StatusBar.resize': wrapCommand(resize),
2037
+ 'StatusBar.saveState': wrapGetter(saveState),
2038
+ 'StatusBar.terminate': terminate
2039
+ };
2040
+
2041
+ const listen = async () => {
2042
+ registerCommands(commandMap);
2043
+ const rpc = await create$3({
2044
+ commandMap: commandMap
2045
+ });
2046
+ set$1(rpc);
2047
+ };
2048
+
2049
+ const main = async () => {
2050
+ await listen();
2051
+ };
2052
+
2053
+ main();