@lvce-editor/chat-debug-view 2.1.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,1599 @@
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
+
372
+ class CommandNotFoundError extends Error {
373
+ constructor(command) {
374
+ super(`Command not found ${command}`);
375
+ this.name = 'CommandNotFoundError';
376
+ }
377
+ }
378
+ const commands = Object.create(null);
379
+ const register = commandMap => {
380
+ Object.assign(commands, commandMap);
381
+ };
382
+ const getCommand = key => {
383
+ return commands[key];
384
+ };
385
+ const execute = (command, ...args) => {
386
+ const fn = getCommand(command);
387
+ if (!fn) {
388
+ throw new CommandNotFoundError(command);
389
+ }
390
+ return fn(...args);
391
+ };
392
+
393
+ const Two$1 = '2.0';
394
+ const callbacks = Object.create(null);
395
+ const get$1 = id => {
396
+ return callbacks[id];
397
+ };
398
+ const remove = id => {
399
+ delete callbacks[id];
400
+ };
401
+ class JsonRpcError extends Error {
402
+ constructor(message) {
403
+ super(message);
404
+ this.name = 'JsonRpcError';
405
+ }
406
+ }
407
+ const NewLine = '\n';
408
+ const DomException = 'DOMException';
409
+ const ReferenceError$1 = 'ReferenceError';
410
+ const SyntaxError$1 = 'SyntaxError';
411
+ const TypeError$1 = 'TypeError';
412
+ const getErrorConstructor = (message, type) => {
413
+ if (type) {
414
+ switch (type) {
415
+ case DomException:
416
+ return DOMException;
417
+ case ReferenceError$1:
418
+ return ReferenceError;
419
+ case SyntaxError$1:
420
+ return SyntaxError;
421
+ case TypeError$1:
422
+ return TypeError;
423
+ default:
424
+ return Error;
425
+ }
426
+ }
427
+ if (message.startsWith('TypeError: ')) {
428
+ return TypeError;
429
+ }
430
+ if (message.startsWith('SyntaxError: ')) {
431
+ return SyntaxError;
432
+ }
433
+ if (message.startsWith('ReferenceError: ')) {
434
+ return ReferenceError;
435
+ }
436
+ return Error;
437
+ };
438
+ const constructError = (message, type, name) => {
439
+ const ErrorConstructor = getErrorConstructor(message, type);
440
+ if (ErrorConstructor === DOMException && name) {
441
+ return new ErrorConstructor(message, name);
442
+ }
443
+ if (ErrorConstructor === Error) {
444
+ const error = new Error(message);
445
+ if (name && name !== 'VError') {
446
+ error.name = name;
447
+ }
448
+ return error;
449
+ }
450
+ return new ErrorConstructor(message);
451
+ };
452
+ const joinLines = lines => {
453
+ return lines.join(NewLine);
454
+ };
455
+ const splitLines = lines => {
456
+ return lines.split(NewLine);
457
+ };
458
+ const getCurrentStack = () => {
459
+ const stackLinesToSkip = 3;
460
+ const currentStack = joinLines(splitLines(new Error().stack || '').slice(stackLinesToSkip));
461
+ return currentStack;
462
+ };
463
+ const getNewLineIndex = (string, startIndex = undefined) => {
464
+ return string.indexOf(NewLine, startIndex);
465
+ };
466
+ const getParentStack = error => {
467
+ let parentStack = error.stack || error.data || error.message || '';
468
+ if (parentStack.startsWith(' at')) {
469
+ parentStack = error.message + NewLine + parentStack;
470
+ }
471
+ return parentStack;
472
+ };
473
+ const MethodNotFound = -32601;
474
+ const Custom = -32001;
475
+ const restoreJsonRpcError = error => {
476
+ const currentStack = getCurrentStack();
477
+ if (error && error instanceof Error) {
478
+ if (typeof error.stack === 'string') {
479
+ error.stack = error.stack + NewLine + currentStack;
480
+ }
481
+ return error;
482
+ }
483
+ if (error && error.code && error.code === MethodNotFound) {
484
+ const restoredError = new JsonRpcError(error.message);
485
+ const parentStack = getParentStack(error);
486
+ restoredError.stack = parentStack + NewLine + currentStack;
487
+ return restoredError;
488
+ }
489
+ if (error && error.message) {
490
+ const restoredError = constructError(error.message, error.type, error.name);
491
+ if (error.data) {
492
+ if (error.data.stack && error.data.type && error.message) {
493
+ restoredError.stack = error.data.type + ': ' + error.message + NewLine + error.data.stack + NewLine + currentStack;
494
+ } else if (error.data.stack) {
495
+ restoredError.stack = error.data.stack;
496
+ }
497
+ if (error.data.codeFrame) {
498
+ // @ts-ignore
499
+ restoredError.codeFrame = error.data.codeFrame;
500
+ }
501
+ if (error.data.code) {
502
+ // @ts-ignore
503
+ restoredError.code = error.data.code;
504
+ }
505
+ if (error.data.type) {
506
+ // @ts-ignore
507
+ restoredError.name = error.data.type;
508
+ }
509
+ } else {
510
+ if (error.stack) {
511
+ const lowerStack = restoredError.stack || '';
512
+ // @ts-ignore
513
+ const indexNewLine = getNewLineIndex(lowerStack);
514
+ const parentStack = getParentStack(error);
515
+ // @ts-ignore
516
+ restoredError.stack = parentStack + lowerStack.slice(indexNewLine);
517
+ }
518
+ if (error.codeFrame) {
519
+ // @ts-ignore
520
+ restoredError.codeFrame = error.codeFrame;
521
+ }
522
+ }
523
+ return restoredError;
524
+ }
525
+ if (typeof error === 'string') {
526
+ return new Error(`JsonRpc Error: ${error}`);
527
+ }
528
+ return new Error(`JsonRpc Error: ${error}`);
529
+ };
530
+ const unwrapJsonRpcResult = responseMessage => {
531
+ if ('error' in responseMessage) {
532
+ const restoredError = restoreJsonRpcError(responseMessage.error);
533
+ throw restoredError;
534
+ }
535
+ if ('result' in responseMessage) {
536
+ return responseMessage.result;
537
+ }
538
+ throw new JsonRpcError('unexpected response message');
539
+ };
540
+ const warn = (...args) => {
541
+ console.warn(...args);
542
+ };
543
+ const resolve = (id, response) => {
544
+ const fn = get$1(id);
545
+ if (!fn) {
546
+ console.log(response);
547
+ warn(`callback ${id} may already be disposed`);
548
+ return;
549
+ }
550
+ fn(response);
551
+ remove(id);
552
+ };
553
+ const E_COMMAND_NOT_FOUND = 'E_COMMAND_NOT_FOUND';
554
+ const getErrorType = prettyError => {
555
+ if (prettyError && prettyError.type) {
556
+ return prettyError.type;
557
+ }
558
+ if (prettyError && prettyError.constructor && prettyError.constructor.name) {
559
+ return prettyError.constructor.name;
560
+ }
561
+ return undefined;
562
+ };
563
+ const isAlreadyStack = line => {
564
+ return line.trim().startsWith('at ');
565
+ };
566
+ const getStack = prettyError => {
567
+ const stackString = prettyError.stack || '';
568
+ const newLineIndex = stackString.indexOf('\n');
569
+ if (newLineIndex !== -1 && !isAlreadyStack(stackString.slice(0, newLineIndex))) {
570
+ return stackString.slice(newLineIndex + 1);
571
+ }
572
+ return stackString;
573
+ };
574
+ const getErrorProperty = (error, prettyError) => {
575
+ if (error && error.code === E_COMMAND_NOT_FOUND) {
576
+ return {
577
+ code: MethodNotFound,
578
+ data: error.stack,
579
+ message: error.message
580
+ };
581
+ }
582
+ return {
583
+ code: Custom,
584
+ data: {
585
+ code: prettyError.code,
586
+ codeFrame: prettyError.codeFrame,
587
+ name: prettyError.name,
588
+ stack: getStack(prettyError),
589
+ type: getErrorType(prettyError)
590
+ },
591
+ message: prettyError.message
592
+ };
593
+ };
594
+ const create$1$1 = (id, error) => {
595
+ return {
596
+ error,
597
+ id,
598
+ jsonrpc: Two$1
599
+ };
600
+ };
601
+ const getErrorResponse = (id, error, preparePrettyError, logError) => {
602
+ const prettyError = preparePrettyError(error);
603
+ logError(error, prettyError);
604
+ const errorProperty = getErrorProperty(error, prettyError);
605
+ return create$1$1(id, errorProperty);
606
+ };
607
+ const create$6 = (message, result) => {
608
+ return {
609
+ id: message.id,
610
+ jsonrpc: Two$1,
611
+ result: result ?? null
612
+ };
613
+ };
614
+ const getSuccessResponse = (message, result) => {
615
+ const resultProperty = result ?? null;
616
+ return create$6(message, resultProperty);
617
+ };
618
+ const getErrorResponseSimple = (id, error) => {
619
+ return {
620
+ error: {
621
+ code: Custom,
622
+ data: error,
623
+ // @ts-ignore
624
+ message: error.message
625
+ },
626
+ id,
627
+ jsonrpc: Two$1
628
+ };
629
+ };
630
+ const getResponse = async (message, ipc, execute, preparePrettyError, logError, requiresSocket) => {
631
+ try {
632
+ const result = requiresSocket(message.method) ? await execute(message.method, ipc, ...message.params) : await execute(message.method, ...message.params);
633
+ return getSuccessResponse(message, result);
634
+ } catch (error) {
635
+ if (ipc.canUseSimpleErrorResponse) {
636
+ return getErrorResponseSimple(message.id, error);
637
+ }
638
+ return getErrorResponse(message.id, error, preparePrettyError, logError);
639
+ }
640
+ };
641
+ const defaultPreparePrettyError = error => {
642
+ return error;
643
+ };
644
+ const defaultLogError = () => {
645
+ // ignore
646
+ };
647
+ const defaultRequiresSocket = () => {
648
+ return false;
649
+ };
650
+ const defaultResolve = resolve;
651
+
652
+ // TODO maybe remove this in v6 or v7, only accept options object to simplify the code
653
+ const normalizeParams = args => {
654
+ if (args.length === 1) {
655
+ const options = args[0];
656
+ return {
657
+ execute: options.execute,
658
+ ipc: options.ipc,
659
+ logError: options.logError || defaultLogError,
660
+ message: options.message,
661
+ preparePrettyError: options.preparePrettyError || defaultPreparePrettyError,
662
+ requiresSocket: options.requiresSocket || defaultRequiresSocket,
663
+ resolve: options.resolve || defaultResolve
664
+ };
665
+ }
666
+ return {
667
+ execute: args[2],
668
+ ipc: args[0],
669
+ logError: args[5],
670
+ message: args[1],
671
+ preparePrettyError: args[4],
672
+ requiresSocket: args[6],
673
+ resolve: args[3]
674
+ };
675
+ };
676
+ const handleJsonRpcMessage = async (...args) => {
677
+ const options = normalizeParams(args);
678
+ const {
679
+ execute,
680
+ ipc,
681
+ logError,
682
+ message,
683
+ preparePrettyError,
684
+ requiresSocket,
685
+ resolve
686
+ } = options;
687
+ if ('id' in message) {
688
+ if ('method' in message) {
689
+ const response = await getResponse(message, ipc, execute, preparePrettyError, logError, requiresSocket);
690
+ try {
691
+ ipc.send(response);
692
+ } catch (error) {
693
+ const errorResponse = getErrorResponse(message.id, error, preparePrettyError, logError);
694
+ ipc.send(errorResponse);
695
+ }
696
+ return;
697
+ }
698
+ resolve(message.id, message);
699
+ return;
700
+ }
701
+ if ('method' in message) {
702
+ await getResponse(message, ipc, execute, preparePrettyError, logError, requiresSocket);
703
+ return;
704
+ }
705
+ throw new JsonRpcError('unexpected message');
706
+ };
707
+
708
+ const Two = '2.0';
709
+
710
+ const create$5 = (method, params) => {
711
+ return {
712
+ jsonrpc: Two,
713
+ method,
714
+ params
715
+ };
716
+ };
717
+
718
+ const create$4 = (id, method, params) => {
719
+ const message = {
720
+ id,
721
+ jsonrpc: Two,
722
+ method,
723
+ params
724
+ };
725
+ return message;
726
+ };
727
+
728
+ let id = 0;
729
+ const create$3 = () => {
730
+ return ++id;
731
+ };
732
+
733
+ const registerPromise = map => {
734
+ const id = create$3();
735
+ const {
736
+ promise,
737
+ resolve
738
+ } = Promise.withResolvers();
739
+ map[id] = resolve;
740
+ return {
741
+ id,
742
+ promise
743
+ };
744
+ };
745
+
746
+ const invokeHelper = async (callbacks, ipc, method, params, useSendAndTransfer) => {
747
+ const {
748
+ id,
749
+ promise
750
+ } = registerPromise(callbacks);
751
+ const message = create$4(id, method, params);
752
+ if (useSendAndTransfer && ipc.sendAndTransfer) {
753
+ ipc.sendAndTransfer(message);
754
+ } else {
755
+ ipc.send(message);
756
+ }
757
+ const responseMessage = await promise;
758
+ return unwrapJsonRpcResult(responseMessage);
759
+ };
760
+ const createRpc = ipc => {
761
+ const callbacks = Object.create(null);
762
+ ipc._resolve = (id, response) => {
763
+ const fn = callbacks[id];
764
+ if (!fn) {
765
+ console.warn(`callback ${id} may already be disposed`);
766
+ return;
767
+ }
768
+ fn(response);
769
+ delete callbacks[id];
770
+ };
771
+ const rpc = {
772
+ async dispose() {
773
+ await ipc?.dispose();
774
+ },
775
+ invoke(method, ...params) {
776
+ return invokeHelper(callbacks, ipc, method, params, false);
777
+ },
778
+ invokeAndTransfer(method, ...params) {
779
+ return invokeHelper(callbacks, ipc, method, params, true);
780
+ },
781
+ // @ts-ignore
782
+ ipc,
783
+ /**
784
+ * @deprecated
785
+ */
786
+ send(method, ...params) {
787
+ const message = create$5(method, params);
788
+ ipc.send(message);
789
+ }
790
+ };
791
+ return rpc;
792
+ };
793
+
794
+ const requiresSocket = () => {
795
+ return false;
796
+ };
797
+ const preparePrettyError = error => {
798
+ return error;
799
+ };
800
+ const logError = () => {
801
+ // handled by renderer worker
802
+ };
803
+ const handleMessage = event => {
804
+ const actualRequiresSocket = event?.target?.requiresSocket || requiresSocket;
805
+ const actualExecute = event?.target?.execute || execute;
806
+ return handleJsonRpcMessage(event.target, event.data, actualExecute, event.target._resolve, preparePrettyError, logError, actualRequiresSocket);
807
+ };
808
+
809
+ const handleIpc = ipc => {
810
+ if ('addEventListener' in ipc) {
811
+ ipc.addEventListener('message', handleMessage);
812
+ } else if ('on' in ipc) {
813
+ // deprecated
814
+ ipc.on('message', handleMessage);
815
+ }
816
+ };
817
+
818
+ const listen$1 = async (module, options) => {
819
+ const rawIpc = await module.listen(options);
820
+ if (module.signal) {
821
+ module.signal(rawIpc);
822
+ }
823
+ const ipc = module.wrap(rawIpc);
824
+ return ipc;
825
+ };
826
+
827
+ const create$2 = async ({
828
+ commandMap
829
+ }) => {
830
+ // TODO create a commandMap per rpc instance
831
+ register(commandMap);
832
+ const ipc = await listen$1(IpcChildWithModuleWorkerAndMessagePort$1);
833
+ handleIpc(ipc);
834
+ const rpc = createRpc(ipc);
835
+ return rpc;
836
+ };
837
+
838
+ const toCommandId = key => {
839
+ const dotIndex = key.indexOf('.');
840
+ return key.slice(dotIndex + 1);
841
+ };
842
+ const create$1 = () => {
843
+ const states = Object.create(null);
844
+ const commandMapRef = {};
845
+ return {
846
+ clear() {
847
+ for (const key of Object.keys(states)) {
848
+ delete states[key];
849
+ }
850
+ },
851
+ diff(uid, modules, numbers) {
852
+ const {
853
+ newState,
854
+ oldState
855
+ } = states[uid];
856
+ const diffResult = [];
857
+ for (let i = 0; i < modules.length; i++) {
858
+ const fn = modules[i];
859
+ if (!fn(oldState, newState)) {
860
+ diffResult.push(numbers[i]);
861
+ }
862
+ }
863
+ return diffResult;
864
+ },
865
+ dispose(uid) {
866
+ delete states[uid];
867
+ },
868
+ get(uid) {
869
+ return states[uid];
870
+ },
871
+ getCommandIds() {
872
+ const keys = Object.keys(commandMapRef);
873
+ const ids = keys.map(toCommandId);
874
+ return ids;
875
+ },
876
+ getKeys() {
877
+ return Object.keys(states).map(key => {
878
+ return Number.parseFloat(key);
879
+ });
880
+ },
881
+ registerCommands(commandMap) {
882
+ Object.assign(commandMapRef, commandMap);
883
+ },
884
+ set(uid, oldState, newState) {
885
+ states[uid] = {
886
+ newState,
887
+ oldState
888
+ };
889
+ },
890
+ wrapCommand(fn) {
891
+ const wrapped = async (uid, ...args) => {
892
+ const {
893
+ newState,
894
+ oldState
895
+ } = states[uid];
896
+ const newerState = await fn(newState, ...args);
897
+ if (oldState === newerState || newState === newerState) {
898
+ return;
899
+ }
900
+ const latestOld = states[uid];
901
+ const latestNew = {
902
+ ...latestOld.newState,
903
+ ...newerState
904
+ };
905
+ states[uid] = {
906
+ newState: latestNew,
907
+ oldState: latestOld.oldState
908
+ };
909
+ };
910
+ return wrapped;
911
+ },
912
+ wrapGetter(fn) {
913
+ const wrapped = (uid, ...args) => {
914
+ const {
915
+ newState
916
+ } = states[uid];
917
+ return fn(newState, ...args);
918
+ };
919
+ return wrapped;
920
+ },
921
+ wrapLoadContent(fn) {
922
+ const wrapped = async (uid, ...args) => {
923
+ const {
924
+ newState,
925
+ oldState
926
+ } = states[uid];
927
+ const result = await fn(newState, ...args);
928
+ const {
929
+ error,
930
+ state
931
+ } = result;
932
+ if (oldState === state || newState === state) {
933
+ return {
934
+ error
935
+ };
936
+ }
937
+ const latestOld = states[uid];
938
+ const latestNew = {
939
+ ...latestOld.newState,
940
+ ...state
941
+ };
942
+ states[uid] = {
943
+ newState: latestNew,
944
+ oldState: latestOld.oldState
945
+ };
946
+ return {
947
+ error
948
+ };
949
+ };
950
+ return wrapped;
951
+ }
952
+ };
953
+ };
954
+ const terminate = () => {
955
+ globalThis.close();
956
+ };
957
+
958
+ const {
959
+ get,
960
+ getCommandIds,
961
+ registerCommands,
962
+ set,
963
+ wrapCommand,
964
+ wrapGetter
965
+ } = create$1();
966
+
967
+ const createDefaultState = () => {
968
+ return {
969
+ assetDir: '',
970
+ databaseName: 'lvce-chat-view-sessions',
971
+ dataBaseVersion: 2,
972
+ errorMessage: '',
973
+ events: [],
974
+ eventStoreName: 'chat-view-events',
975
+ filterValue: '',
976
+ height: 0,
977
+ initial: true,
978
+ platform: 0,
979
+ sessionId: '',
980
+ sessionIdIndexName: 'sessionId',
981
+ showInputEvents: true,
982
+ uid: 0,
983
+ uri: '',
984
+ width: 0,
985
+ x: 0,
986
+ y: 0
987
+ };
988
+ };
989
+
990
+ const create = (uid, uri, x, y, width, height, platform, assetDir, sessionId = '', databaseName = 'lvce-chat-view-sessions', dataBaseVersion = 2, eventStoreName = 'chat-view-events', sessionIdIndexName = 'sessionId') => {
991
+ const state = {
992
+ ...createDefaultState(),
993
+ assetDir,
994
+ databaseName,
995
+ dataBaseVersion,
996
+ eventStoreName,
997
+ height,
998
+ platform,
999
+ sessionId,
1000
+ sessionIdIndexName,
1001
+ uid,
1002
+ uri,
1003
+ width,
1004
+ x,
1005
+ y
1006
+ };
1007
+ set(uid, state, state);
1008
+ };
1009
+
1010
+ const RenderItems = 1;
1011
+ const RenderCss = 2;
1012
+
1013
+ const diff = (oldState, newState) => {
1014
+ if (oldState.initial !== newState.initial) {
1015
+ return [RenderCss, RenderItems];
1016
+ }
1017
+ if (oldState.errorMessage !== newState.errorMessage || oldState.events !== newState.events || oldState.filterValue !== newState.filterValue || oldState.sessionId !== newState.sessionId || oldState.showInputEvents !== newState.showInputEvents || oldState.uid !== newState.uid) {
1018
+ return [RenderItems];
1019
+ }
1020
+ return [];
1021
+ };
1022
+
1023
+ const diff2 = uid => {
1024
+ const {
1025
+ newState,
1026
+ oldState
1027
+ } = get(uid);
1028
+ return diff(oldState, newState);
1029
+ };
1030
+
1031
+ const Filter = 'filter';
1032
+ const ShowInputEvents = 'showInputEvents';
1033
+
1034
+ const getBoolean = value => {
1035
+ return value === true || value === 'true' || value === 'on' || value === '1';
1036
+ };
1037
+ const handleInput = (state, name, value, checked) => {
1038
+ if (name === Filter) {
1039
+ return {
1040
+ ...state,
1041
+ filterValue: value
1042
+ };
1043
+ }
1044
+ if (name === ShowInputEvents) {
1045
+ return {
1046
+ ...state,
1047
+ showInputEvents: getBoolean(checked)
1048
+ };
1049
+ }
1050
+ return state;
1051
+ };
1052
+
1053
+ const requestToPromise = async createRequest => {
1054
+ const request = createRequest();
1055
+ const {
1056
+ promise,
1057
+ reject,
1058
+ resolve
1059
+ } = Promise.withResolvers();
1060
+ request.addEventListener('success', () => {
1061
+ resolve(request.result);
1062
+ });
1063
+ request.addEventListener('error', () => {
1064
+ reject(request.error || new Error('IndexedDB request failed'));
1065
+ });
1066
+ return promise;
1067
+ };
1068
+
1069
+ /* eslint-disable @typescript-eslint/prefer-readonly-parameter-types */
1070
+
1071
+ const openDatabase = async (databaseName, dataBaseVersion) => {
1072
+ const request = indexedDB.open(databaseName, dataBaseVersion);
1073
+ return requestToPromise(() => request);
1074
+ };
1075
+ const getAllEvents = async store => {
1076
+ const all = await requestToPromise(() => store.getAll());
1077
+ return all;
1078
+ };
1079
+ const filterEventsBySessionId = (events, sessionId) => {
1080
+ return events.filter(event => event.sessionId === sessionId);
1081
+ };
1082
+ const getEventsBySessionId = async (store, sessionId, sessionIdIndexName) => {
1083
+ if (store.indexNames.contains(sessionIdIndexName)) {
1084
+ const index = store.index(sessionIdIndexName);
1085
+ const events = await requestToPromise(() => index.getAll(IDBKeyRange.only(sessionId)));
1086
+ return filterEventsBySessionId(events, sessionId);
1087
+ }
1088
+ const all = await getAllEvents(store);
1089
+ return filterEventsBySessionId(all, sessionId);
1090
+ };
1091
+ const listChatViewEvents = async (sessionId, databaseName, dataBaseVersion, eventStoreName, sessionIdIndexName) => {
1092
+ if (typeof indexedDB === 'undefined') {
1093
+ return [];
1094
+ }
1095
+ const database = await openDatabase(databaseName, dataBaseVersion);
1096
+ try {
1097
+ if (!database.objectStoreNames.contains(eventStoreName)) {
1098
+ return [];
1099
+ }
1100
+ const transaction = database.transaction(eventStoreName, 'readonly');
1101
+ const store = transaction.objectStore(eventStoreName);
1102
+ if (!sessionId) {
1103
+ return [];
1104
+ }
1105
+ return getEventsBySessionId(store, sessionId, sessionIdIndexName);
1106
+ } finally {
1107
+ database.close();
1108
+ }
1109
+ };
1110
+
1111
+ const chatDebugUriPattern = /^chat-debug:\/\/([^/?#]+)$/;
1112
+ const parseChatDebugUri = uri => {
1113
+ if (!uri) {
1114
+ throw new Error('Missing URI');
1115
+ }
1116
+ const match = uri.match(chatDebugUriPattern);
1117
+ if (!match) {
1118
+ throw new Error('Invalid URI format');
1119
+ }
1120
+ const encodedSessionId = match[1];
1121
+ let sessionId;
1122
+ try {
1123
+ sessionId = decodeURIComponent(encodedSessionId);
1124
+ } catch {
1125
+ throw new Error('Invalid URI encoding');
1126
+ }
1127
+ if (!sessionId || /[/?#]/.test(sessionId)) {
1128
+ throw new Error('Invalid session id');
1129
+ }
1130
+ return sessionId;
1131
+ };
1132
+
1133
+ const getInvalidUriMessage = uri => {
1134
+ if (!uri) {
1135
+ return 'Unable to load debug session: missing URI. Expected format: chat-debug://<sessionId>.';
1136
+ }
1137
+ return `Unable to load debug session: invalid URI "${uri}". Expected format: chat-debug://<sessionId>.`;
1138
+ };
1139
+ const getSessionNotFoundMessage = sessionId => {
1140
+ return `No chat session found for sessionId "${sessionId}".`;
1141
+ };
1142
+ const getFailedToLoadMessage = sessionId => {
1143
+ return `Failed to load chat debug session "${sessionId}". Please try again.`;
1144
+ };
1145
+ const loadContent = async state => {
1146
+ const {
1147
+ databaseName,
1148
+ dataBaseVersion,
1149
+ eventStoreName,
1150
+ sessionIdIndexName,
1151
+ uri
1152
+ } = state;
1153
+ let sessionId = '';
1154
+ try {
1155
+ sessionId = parseChatDebugUri(uri);
1156
+ } catch {
1157
+ return {
1158
+ ...state,
1159
+ errorMessage: getInvalidUriMessage(uri),
1160
+ events: [],
1161
+ initial: false,
1162
+ sessionId
1163
+ };
1164
+ }
1165
+ try {
1166
+ const events = await listChatViewEvents(sessionId, databaseName, dataBaseVersion, eventStoreName, sessionIdIndexName);
1167
+ if (events.length === 0) {
1168
+ return {
1169
+ ...state,
1170
+ errorMessage: getSessionNotFoundMessage(sessionId),
1171
+ events: [],
1172
+ initial: false,
1173
+ sessionId
1174
+ };
1175
+ }
1176
+ return {
1177
+ ...state,
1178
+ errorMessage: '',
1179
+ events,
1180
+ initial: false,
1181
+ sessionId
1182
+ };
1183
+ } catch {
1184
+ return {
1185
+ ...state,
1186
+ errorMessage: getFailedToLoadMessage(sessionId),
1187
+ events: [],
1188
+ initial: false,
1189
+ sessionId
1190
+ };
1191
+ }
1192
+ };
1193
+
1194
+ const refresh = async state => {
1195
+ const events = await listChatViewEvents(state.sessionId, state.databaseName, state.dataBaseVersion, state.eventStoreName, state.sessionIdIndexName);
1196
+ return {
1197
+ ...state,
1198
+ errorMessage: '',
1199
+ events,
1200
+ initial: false
1201
+ };
1202
+ };
1203
+
1204
+ const TargetChecked = 'event.target.checked';
1205
+ const TargetName = 'event.target.name';
1206
+ const TargetValue = 'event.target.value';
1207
+
1208
+ const SetCss = 'Viewlet.setCss';
1209
+ const SetDom2 = 'Viewlet.setDom2';
1210
+
1211
+ const getCss = () => {
1212
+ return `
1213
+ .ChatDebugView {
1214
+ padding: 8px;
1215
+ display: grid;
1216
+ grid-template-rows: auto auto 1fr;
1217
+ height: 100%;
1218
+ box-sizing: border-box;
1219
+ gap: 8px;
1220
+ }
1221
+
1222
+ .ChatDebugViewTop {
1223
+ display: flex;
1224
+ align-items: center;
1225
+ gap: 12px;
1226
+ }
1227
+
1228
+ .ChatDebugViewTop .InputBox {
1229
+ flex: 1;
1230
+ }
1231
+
1232
+ .ChatDebugViewToggle {
1233
+ display: flex;
1234
+ align-items: center;
1235
+ gap: 6px;
1236
+ white-space: nowrap;
1237
+ }
1238
+
1239
+ .ChatDebugViewSession {
1240
+ font-size: 12px;
1241
+ opacity: 0.8;
1242
+ }
1243
+
1244
+ .ChatDebugViewEvents {
1245
+ overflow: auto;
1246
+ }
1247
+
1248
+ .ChatDebugViewEvent {
1249
+ margin: 0;
1250
+ padding: 8px;
1251
+ border: 1px solid var(--vscode-editorWidget-border, #454545);
1252
+ border-radius: 6px;
1253
+ margin-bottom: 8px;
1254
+ white-space: pre-wrap;
1255
+ word-break: break-word;
1256
+ font-family: var(--vscode-editor-font-family, monospace);
1257
+ font-size: 12px;
1258
+ }
1259
+
1260
+ .ChatDebugViewEmpty {
1261
+ opacity: 0.8;
1262
+ }
1263
+
1264
+ .ChatDebugViewError {
1265
+ color: var(--vscode-errorForeground, #f14c4c);
1266
+ white-space: normal;
1267
+ }
1268
+
1269
+ .TokenText {
1270
+ color: var(--vscode-editor-foreground, inherit);
1271
+ }
1272
+
1273
+ .TokenKey {
1274
+ color: var(--vscode-symbolIcon-propertyForeground, var(--vscode-editor-foreground, inherit));
1275
+ }
1276
+
1277
+ .TokenString {
1278
+ color: var(--vscode-debugTokenExpression-string, var(--vscode-charts-green, #89d185));
1279
+ }
1280
+
1281
+ .TokenNumeric {
1282
+ color: var(--vscode-debugTokenExpression-number, var(--vscode-charts-blue, #75beff));
1283
+ }
1284
+
1285
+ .TokenBoolean {
1286
+ color: var(--vscode-debugTokenExpression-boolean, var(--vscode-charts-yellow, #dcdcaa));
1287
+ }
1288
+ `;
1289
+ };
1290
+
1291
+ const renderCss = (oldState, newState) => {
1292
+ const css = getCss();
1293
+ return [SetCss, newState.uid, css];
1294
+ };
1295
+
1296
+ const Div = 4;
1297
+ const Input = 6;
1298
+ const Span = 8;
1299
+ const Text = 12;
1300
+ const Pre = 51;
1301
+
1302
+ const text = data => {
1303
+ return {
1304
+ childCount: 0,
1305
+ text: data,
1306
+ type: Text
1307
+ };
1308
+ };
1309
+
1310
+ const HandleInput = 4;
1311
+
1312
+ const numberRegex = /^-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+-]?\d+)?/;
1313
+ const getTokenSegments = json => {
1314
+ const segments = [];
1315
+ const pushToken = (className, value) => {
1316
+ if (!value) {
1317
+ return;
1318
+ }
1319
+ const lastSegment = segments.at(-1);
1320
+ if (lastSegment && lastSegment.className === className) {
1321
+ const merged = {
1322
+ className,
1323
+ value: lastSegment.value + value
1324
+ };
1325
+ segments[segments.length - 1] = merged;
1326
+ return;
1327
+ }
1328
+ segments.push({
1329
+ className,
1330
+ value
1331
+ });
1332
+ };
1333
+ let i = 0;
1334
+ while (i < json.length) {
1335
+ const character = json[i];
1336
+ if (character === '"') {
1337
+ const start = i;
1338
+ i++;
1339
+ while (i < json.length) {
1340
+ const currentCharacter = json[i];
1341
+ if (currentCharacter === '\\') {
1342
+ i += 2;
1343
+ continue;
1344
+ }
1345
+ if (currentCharacter === '"') {
1346
+ i++;
1347
+ break;
1348
+ }
1349
+ i++;
1350
+ }
1351
+ const tokenValue = json.slice(start, i);
1352
+ let lookAheadIndex = i;
1353
+ while (lookAheadIndex < json.length && /\s/u.test(json[lookAheadIndex])) {
1354
+ lookAheadIndex++;
1355
+ }
1356
+ const className = json[lookAheadIndex] === ':' ? 'TokenKey' : 'TokenString';
1357
+ pushToken(className, tokenValue);
1358
+ continue;
1359
+ }
1360
+ const numberMatch = numberRegex.exec(json.slice(i));
1361
+ if (numberMatch) {
1362
+ pushToken('TokenNumeric', numberMatch[0]);
1363
+ i += numberMatch[0].length;
1364
+ continue;
1365
+ }
1366
+ if (json.startsWith('true', i)) {
1367
+ pushToken('TokenBoolean', 'true');
1368
+ i += 4;
1369
+ continue;
1370
+ }
1371
+ if (json.startsWith('false', i)) {
1372
+ pushToken('TokenBoolean', 'false');
1373
+ i += 5;
1374
+ continue;
1375
+ }
1376
+ if (json.startsWith('null', i)) {
1377
+ pushToken('TokenBoolean', 'null');
1378
+ i += 4;
1379
+ continue;
1380
+ }
1381
+ pushToken('TokenText', character);
1382
+ i++;
1383
+ }
1384
+ return segments;
1385
+ };
1386
+ const getJsonTokenNodes = value => {
1387
+ const json = JSON.stringify(value, null, 2);
1388
+ if (!json) {
1389
+ return [{
1390
+ childCount: 1,
1391
+ className: 'TokenText',
1392
+ type: Span
1393
+ }, text(String(json))];
1394
+ }
1395
+ const segments = getTokenSegments(json);
1396
+ return segments.flatMap(segment => {
1397
+ return [{
1398
+ childCount: 1,
1399
+ className: segment.className,
1400
+ type: Span
1401
+ }, text(segment.value)];
1402
+ });
1403
+ };
1404
+
1405
+ const getEventNode = event => {
1406
+ const tokenNodes = getJsonTokenNodes(event);
1407
+ return [{
1408
+ childCount: tokenNodes.length / 2,
1409
+ className: 'ChatDebugViewEvent',
1410
+ type: Pre
1411
+ }, ...tokenNodes];
1412
+ };
1413
+ const getChatDebugViewDom = (sessionId, errorMessage, filterValue, showInputEvents, events) => {
1414
+ if (errorMessage) {
1415
+ return [{
1416
+ childCount: 1,
1417
+ className: 'ChatDebugView',
1418
+ type: Div
1419
+ }, {
1420
+ childCount: 1,
1421
+ className: 'ChatDebugViewError',
1422
+ type: Div
1423
+ }, text(errorMessage)];
1424
+ }
1425
+ const eventNodes = events.flatMap(getEventNode);
1426
+ return [{
1427
+ childCount: 3,
1428
+ className: 'ChatDebugView',
1429
+ type: Div
1430
+ }, {
1431
+ childCount: 2,
1432
+ className: 'ChatDebugViewTop',
1433
+ type: Div
1434
+ }, {
1435
+ childCount: 0,
1436
+ className: 'InputBox',
1437
+ name: Filter,
1438
+ onInput: HandleInput,
1439
+ placeholder: 'Filter events',
1440
+ type: Input,
1441
+ value: filterValue
1442
+ }, {
1443
+ childCount: 2,
1444
+ className: 'ChatDebugViewToggle',
1445
+ type: Div
1446
+ }, {
1447
+ checked: showInputEvents,
1448
+ childCount: 0,
1449
+ inputType: 'checkbox',
1450
+ name: ShowInputEvents,
1451
+ onChange: HandleInput,
1452
+ type: Input
1453
+ }, text('Show input events'), {
1454
+ childCount: 1,
1455
+ className: 'ChatDebugViewSession',
1456
+ type: Div
1457
+ }, text(`sessionId: ${sessionId || '(none)'}`), {
1458
+ childCount: eventNodes.length === 0 ? 1 : eventNodes.length,
1459
+ className: 'ChatDebugViewEvents',
1460
+ type: Div
1461
+ }, ...(eventNodes.length === 0 ? [{
1462
+ childCount: 1,
1463
+ className: errorMessage ? 'ChatDebugViewError' : 'ChatDebugViewEmpty',
1464
+ type: Div
1465
+ }, text(errorMessage || 'No events')] : eventNodes)];
1466
+ };
1467
+
1468
+ const getVisibleEvents = (events, showInputEvents) => {
1469
+ if (showInputEvents) {
1470
+ return events;
1471
+ }
1472
+ return events.filter(event => event.type !== 'handle-input');
1473
+ };
1474
+ const getFilteredEvents = (events, filterValue, showInputEvents) => {
1475
+ const visibleEvents = getVisibleEvents(events, showInputEvents);
1476
+ const normalizedFilter = filterValue.trim().toLowerCase();
1477
+ if (!normalizedFilter) {
1478
+ return visibleEvents;
1479
+ }
1480
+ return visibleEvents.filter(event => JSON.stringify(event).toLowerCase().includes(normalizedFilter));
1481
+ };
1482
+
1483
+ const renderItems = (oldState, newState) => {
1484
+ const filteredEvents = getFilteredEvents(newState.events, newState.filterValue, newState.showInputEvents);
1485
+ const dom = getChatDebugViewDom(newState.sessionId, newState.errorMessage, newState.filterValue, newState.showInputEvents, filteredEvents);
1486
+ return [SetDom2, newState.uid, dom];
1487
+ };
1488
+
1489
+ const getRenderer = diffType => {
1490
+ switch (diffType) {
1491
+ case RenderCss:
1492
+ return renderCss;
1493
+ case RenderItems:
1494
+ return renderItems;
1495
+ default:
1496
+ throw new Error('unknown renderer');
1497
+ }
1498
+ };
1499
+
1500
+ const applyRender = (oldState, newState, diffResult) => {
1501
+ const commands = [];
1502
+ for (const item of diffResult) {
1503
+ const fn = getRenderer(item);
1504
+ const result = fn(oldState, newState);
1505
+ if (result.length > 0) {
1506
+ commands.push(result);
1507
+ }
1508
+ }
1509
+ return commands;
1510
+ };
1511
+
1512
+ const render2 = (uid, diffResult) => {
1513
+ const {
1514
+ newState,
1515
+ oldState
1516
+ } = get(uid);
1517
+ set(uid, newState, newState);
1518
+ return applyRender(oldState, newState, diffResult);
1519
+ };
1520
+
1521
+ const renderEventListeners = () => {
1522
+ return [{
1523
+ name: HandleInput,
1524
+ params: ['handleInput', TargetName, TargetValue, TargetChecked]
1525
+ }];
1526
+ };
1527
+
1528
+ const rerender = state => {
1529
+ return structuredClone(state);
1530
+ };
1531
+
1532
+ const resize = (state, dimensions) => {
1533
+ return {
1534
+ ...state,
1535
+ ...dimensions
1536
+ };
1537
+ };
1538
+
1539
+ const saveState = state => {
1540
+ const {
1541
+ filterValue,
1542
+ height,
1543
+ sessionId,
1544
+ showInputEvents,
1545
+ width,
1546
+ x,
1547
+ y
1548
+ } = state;
1549
+ return {
1550
+ filterValue,
1551
+ height,
1552
+ sessionId,
1553
+ showInputEvents,
1554
+ width,
1555
+ x,
1556
+ y
1557
+ };
1558
+ };
1559
+
1560
+ const setSessionId = async (state, sessionId) => {
1561
+ const events = await listChatViewEvents(sessionId, state.databaseName, state.dataBaseVersion, state.eventStoreName, state.sessionIdIndexName);
1562
+ return {
1563
+ ...state,
1564
+ errorMessage: '',
1565
+ events,
1566
+ initial: false,
1567
+ sessionId
1568
+ };
1569
+ };
1570
+
1571
+ const commandMap = {
1572
+ 'ChatDebug.create': create,
1573
+ 'ChatDebug.diff2': diff2,
1574
+ 'ChatDebug.getCommandIds': getCommandIds,
1575
+ 'ChatDebug.handleInput': wrapCommand(handleInput),
1576
+ 'ChatDebug.loadContent': wrapCommand(loadContent),
1577
+ 'ChatDebug.loadContent2': wrapCommand(loadContent),
1578
+ 'ChatDebug.refresh': wrapCommand(refresh),
1579
+ 'ChatDebug.render2': render2,
1580
+ 'ChatDebug.renderEventListeners': renderEventListeners,
1581
+ 'ChatDebug.rerender': wrapCommand(rerender),
1582
+ 'ChatDebug.resize': wrapCommand(resize),
1583
+ 'ChatDebug.saveState': wrapGetter(saveState),
1584
+ 'ChatDebug.setSessionId': wrapCommand(setSessionId),
1585
+ 'ChatDebug.terminate': terminate
1586
+ };
1587
+
1588
+ const listen = async () => {
1589
+ registerCommands(commandMap);
1590
+ await create$2({
1591
+ commandMap: commandMap
1592
+ });
1593
+ };
1594
+
1595
+ const main = async () => {
1596
+ await listen();
1597
+ };
1598
+
1599
+ main();