forked from LenAnderson/SillyTavern-LALib
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
1419 lines (1315 loc) · 51.7 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { callPopup, characters, chat, chat_metadata, eventSource, event_types, getRequestHeaders, reloadMarkdownProcessor, sendSystemMessage } from '../../../../script.js';
import { getMessageTimeStamp } from '../../../RossAscends-mods.js';
import { extension_settings, getContext } from '../../../extensions.js';
import { findGroupMemberId, groups, selected_group } from '../../../group-chats.js';
import { executeSlashCommands, registerSlashCommand } from '../../../slash-commands.js';
import { debounce, delay, isTrueBoolean } from '../../../utils.js';
import { world_info } from '../../../world-info.js';
import { quickReplyApi } from '../../quick-reply/index.js';
/**
* Parses boolean operands from command arguments.
* @param {object} args Command arguments
* @returns {{a: string | number, b: string | number, rule: string}} Boolean operands
*/
function parseBooleanOperands(args) {
// Resolution order: numeric literal, local variable, global variable, string literal
/**
* @param {string} operand Boolean operand candidate
*/
function getOperand(operand) {
if (operand === undefined) {
return '';
}
const operandNumber = Number(operand);
if (!isNaN(operandNumber)) {
return operandNumber;
}
if (chat_metadata?.variables?.[operand] !== undefined) {
const operandLocalVariable = chat_metadata.variables[operand];
return operandLocalVariable ?? '';
}
if (extension_settings?.variables?.[operand] !== undefined) {
const operandGlobalVariable = extension_settings.variables[operand];
return operandGlobalVariable ?? '';
}
const stringLiteral = String(operand);
return stringLiteral || '';
}
const left = getOperand(args.a || args.left || args.first || args.x);
const right = getOperand(args.b || args.right || args.second || args.y);
const rule = args.rule;
return { a: left, b: right, rule };
}
/**
* Evaluates a boolean comparison rule.
* @param {string} rule Boolean comparison rule
* @param {string|number} a The left operand
* @param {string|number} b The right operand
* @returns {boolean} True if the rule yields true, false otherwise
*/
function evalBoolean(rule, a, b) {
if (!rule) {
toastr.warning('The rule must be specified for the boolean comparison.', 'Invalid command');
throw new Error('Invalid command.');
}
let result = false;
if (typeof a === 'string' && typeof b !== 'number') {
const aString = String(a).toLowerCase();
const bString = String(b).toLowerCase();
switch (rule) {
case 'in':
result = aString.includes(bString);
break;
case 'nin':
result = !aString.includes(bString);
break;
case 'eq':
result = aString === bString;
break;
case 'neq':
result = aString !== bString;
break;
default:
toastr.error('Unknown boolean comparison rule for type string.', 'Invalid /if command');
throw new Error('Invalid command.');
}
} else if (typeof a === 'number') {
const aNumber = Number(a);
const bNumber = Number(b);
switch (rule) {
case 'not':
result = !aNumber;
break;
case 'gt':
result = aNumber > bNumber;
break;
case 'gte':
result = aNumber >= bNumber;
break;
case 'lt':
result = aNumber < bNumber;
break;
case 'lte':
result = aNumber <= bNumber;
break;
case 'eq':
result = aNumber === bNumber;
break;
case 'neq':
result = aNumber !== bNumber;
break;
default:
toastr.error('Unknown boolean comparison rule for type number.', 'Invalid command');
throw new Error('Invalid command.');
}
}
return result;
}
function getListVar(local, global, literal) {
let list;
if (local) {
try {
list = JSON.parse(chat_metadata?.variables?.[local]);
} catch { /* empty */ }
}
if (!list && global) {
try {
list = JSON.parse(extension_settings.variables?.global?.[global]);
} catch { /* empty */ }
}
if (!list && literal) {
if (typeof literal == 'string') {
try {
list = JSON.parse(literal);
} catch { /* empty */ }
} else if (typeof literal == 'object') {
list = literal;
}
}
return list;
}
function getVar(local, global, literal) {
let value;
if (local) {
value = chat_metadata?.variables?.[local];
}
if (value === undefined && global) {
value = extension_settings.variables?.global?.[global];
}
if (value === undefined && literal) {
value = literal;
}
return value;
}
class Command {
/**@type {String} */ command;
/**@type {String} */ args;
/**@type {String} */ helpText;
constructor(command, helpText) {
this.command = command;
this.args = helpText.split(' – ')[0];
this.helpText = helpText.split(/(?=– )/)[1];
}
}
/**@type {Command[]} */
const commandList = [];
/**
* registerSlashCommand
* @param {String} command
* @param {Function} callback
* @param {String[]} aliasList
* @param {String} helpText
* @param {Boolean} a
* @param {Boolean} b
*/
const rsc = (command, callback, aliasList, helpText, a = true, b = true)=>{
registerSlashCommand(command, callback, aliasList, helpText, a, b);
commandList.push(new Command(command, helpText));
};
// GROUP: Help
rsc('lalib?',
async()=>{
const converter = reloadMarkdownProcessor();
const readme = await (await fetch('/scripts/extensions/third-party/SillyTavern-LALib/README.md')).text();
sendSystemMessage('generic', converter.makeHtml(readme));
},
[],
' – Lists LALib commands',
);
// GROUP: Boolean Operations
rsc('test',
(args)=>{
const { a, b, rule } = parseBooleanOperands(args);
return JSON.stringify(evalBoolean(rule, a, b));
},
[],
'<span class="monospace">left=val rule=rule right=val</span> – Returns true or false, depending on whether left and right adhere to rule. Available rules: gt => a > b, gte => a >= b, lt => a < b, lte => a <= b, eq => a == b, neq => a != b, not => !a, in (strings) => a includes b, nin (strings) => a not includes b',
true,
true,
);
rsc('and',
(args)=>{
let left = args.left;
try { left = JSON.parse(args.left); } catch { /* empty */ }
let right = args.right;
try { right = JSON.parse(args.right); } catch { /* empty */ }
return JSON.stringify((left && right) == true);
},
[],
'<span class="monospace">left=val right=val</span> – Returns true if both left and right are true, otherwise false.',
true,
true,
);
rsc('or',
(args)=>{
let left = args.left;
try { left = JSON.parse(args.left); } catch { /* empty */ }
let right = args.right;
try { right = JSON.parse(args.right); } catch { /* empty */ }
return JSON.stringify((left || right) == true);
},
[],
'<span class="monospace">left=val right=val</span> – Returns true if at least one of left and right are true, false if both are false.',
true,
true,
);
rsc('not',
(args, value)=>{
return JSON.stringify(isTrueBoolean(value) != true);
},
[],
'<span class="monospace">(value)</span> – Returns true if value is false, otherwise true.',
true,
true,
);
// GROUP: List Operations
rsc('foreach',
async(args, value)=>{
let list = getListVar(args.var, args.globalvar, args.list);
let result;
const isList = Array.isArray(list);
if (isList) {
list = list.map((it,idx)=>[idx,it]);
} else if (typeof list == 'object') {
list = Object.entries(list);
}
if (Array.isArray(list)) {
for (let [index,item] of list) {
if (typeof item == 'object') {
item = JSON.stringify(item);
}
result = (await executeSlashCommands(value.replace(/{{item}}/ig, item).replace(/{{index}}/ig, index)))?.pipe;
}
return result;
}
if (typeof result == 'object') {
result = JSON.stringify(result);
}
return result;
},
[],
'<span class="monospace">[optional list=[1,2,3]] [optional var=varname] [optional globalvar=globalvarname] (/command {{item}} {{index}})</span> – Executes command for each item of a list or dictionary.',
true,
true,
);
rsc('map',
async(args, value)=>{
let list = getListVar(args.var, args.globalvar, args.list);
let result;
const isList = Array.isArray(list);
if (isList) {
list = list.map((it,idx)=>[idx,it]);
result = [];
} else if (typeof list == 'object') {
list = Object.entries(list);
result = {};
}
if (Array.isArray(list)) {
for (let [index,item] of list) {
if (typeof item == 'object') {
item = JSON.stringify(item);
}
result[index] = (await executeSlashCommands(value.replace(/{{item}}/ig, item).replace(/{{index}}/ig, index)))?.pipe;
try { result[index] = JSON.parse(result[index]); } catch { /* empty */ }
}
} else {
result = list;
}
if (typeof result == 'object') {
result = JSON.stringify(result);
}
return result;
},
[],
'<span class="monospace">[optional list=[1,2,3]] [optional var=varname] [optional globalvar=globalvarname] (/command {{item}} {{index}})</span> – Executes command for each item of a list or dictionary and returns the list or dictionary of the command results.',
);
rsc('filter',
async(args, value)=>{
let list = getListVar(args.var, args.globalvar, args.list);
let result;
const isList = Array.isArray(list);
if (isList) {
list = list.map((it,idx)=>[idx,it]);
result = [];
} else if (typeof list == 'object') {
list = Object.entries(list);
result = {};
}
if (Array.isArray(list)) {
for (let [index,item] of list) {
if (typeof item == 'object') {
item = JSON.stringify(item);
}
if (isTrueBoolean((await executeSlashCommands(value.replace(/{{item}}/ig, item).replace(/{{index}}/ig, index)))?.pipe)) {
if (isList) {
result.push(item);
} else {
result[index] = item;
}
}
}
} else {
result = list;
}
if (typeof result == 'object') {
result = JSON.stringify(result);
}
return result;
},
[],
'<span class="monospace">[optional list=[1,2,3]] [optional var=varname] [optional globalvar=globalvarname] (/command {{item}} {{index}})</span> – Executes command for each item of a list or dictionary and returns the list or dictionary of only those items where the command returned true.',
);
rsc('find',
async(args, value)=>{
let list = getListVar(args.var, args.globalvar, args.list);
let result;
const isList = Array.isArray(list);
if (isList) {
list = list.map((it,idx)=>[idx,it]);
result = [];
} else if (typeof list == 'object') {
list = Object.entries(list);
result = {};
}
if (Array.isArray(list)) {
for (let [index,item] of list) {
if (typeof item == 'object') {
item = JSON.stringify(item);
}
if (isTrueBoolean((await executeSlashCommands(value.replace(/{{item}}/ig, item).replace(/{{index}}/ig, index)))?.pipe)) {
if (typeof result == 'object') {
return JSON.stringify(item);
}
return item;
}
}
return undefined;
}
return undefined;
},
[],
'<span class="monospace">[optional list=[1,2,3]] [optional var=varname] [optional globalvar=globalvarname] (/command {{item}} {{index}})</span> – Executes command for each item of a list or dictionary and returns the first item where the command returned true.',
);
rsc('slice',
(args, value)=>{
const list = getListVar(args.var, args.globalvar, value) ?? getVar(args.var, args.globalvar, value);
let end = args.end ?? (args.length ? Number(args.start) + Number(args.length) : undefined);
const result = list.slice(args.start, end);
if (typeof result == 'object') {
return JSON.stringify(result);
}
return result;
},
[],
'<span class="monospace">start=int [optional end=int] [optional length=int] [optional var=varname] [optional globalvar=globalvarname] (optional value)</span> – Retrieves a slice of a list or string.',
);
rsc('shuffle',
(args, value)=>{
const list = getListVar(null, null, value);
for (let i = list.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[list[i], list[j]] = [list[j], list[i]];
}
return JSON.stringify(list);
},
[],
'<span class="monospace">(list to shuffle)</span> – Returns a shuffled list.',
);
rsc('dict',
(args, value)=>{
const result = {};
const list = getListVar(args.var, args.globalvar, value);
for (const [key, val] of list) {
result[key] = val;
}
return JSON.stringify(result);
},
[],
'<span class="monospace">[optional var=varname] [optional globalvar=globalvarname] (list of lists)</span> – Takes a list of lists (each item must be a list of at least two items) and creates a dictionary by using each items first item as key and each items second item as value.',
);
// GROUP: Split & Join
rsc('split',
(args, value)=>{
value = getListVar(args.var, args.globalvar, value) ?? getVar(args.var, args.globalvar, value);
let find = args.find ?? ',';
if (find.match(/^\/.+\/[a-z]*$/)) {
find = new RegExp(find.replace(/^\/(.+)\/([a-z]*)$/, '$1'), find.replace(/^\/(.+)\/([a-z]*)$/, '$2'));
}
return JSON.stringify(value.split(find).map(it=>isTrueBoolean(args.trim ?? 'true') ? it.trim() : it));
},
[],
'<span class="monospace">[optional find=","] [optional trim=true|false] [optional var=varname] [optional globalvar=globalvarname] (value)</span> – Splits value into list at every occurrence of find. Supports regex <code>find=/\\s/</code>',
true,
true,
);
rsc('join',
(args, value)=>{
let list = getListVar(args.var, args.globalvar, value);
if (Array.isArray(list)) {
const glue = (args.glue ?? ', ')
.replace(/{{space}}/g, ' ')
;
return list.join(glue);
}
},
[],
'<span class="monospace">[optional glue=", "] [optional var=varname] [optional globalvar=globalvarname] (optional list)</span> – Joins the items of a list with glue into a single string. Use <code>glue={{space}}</code> to join with a space.',
true,
true,
);
// GROUP: Text Operations
rsc('trim',
(args, value)=>{
return value?.trim();
},
[],
'<span class="monospace">(text to trim)</span> – Removes whitespace at the start and end of the text.',
);
rsc('replace',
(args, value) => {
let find = args.find;
const replace = args.replace;
const target = getVar(args.var, args.globalvar, value);
if (find.match(/^\/.+\/[a-z]*$/)) {
find = new RegExp(find.replace(/^\/(.+)\/([a-z]*)$/, '$1'), find.replace(/^\/(.+)\/([a-z]*)$/, '$2'));
}
return target.replace(find, replace);
},
[],
'<span class="monospace">[find=string_or_regex] [replace=string] [optional var=varname] [optional globalvar=globalvarname] (optional value)</span> – Replaces the first occurrence of "find" with "replace" in the given value or variable.',
);
rsc('replaceAll',
(args, value) => {
let find = args.find;
const replace = args.replace;
const target = getVar(args.var, args.globalvar, value);
if (find.match(/^\/.+\/[a-z]*$/)) {
find = new RegExp(find.replace(/^\/(.+)\/([a-z]*)$/, '$1'), find.replace(/^\/(.+)\/([a-z]*)$/, '$2'));
} else {
find = new RegExp(find, 'g');
}
return target.replace(find, replace);
},
[],
'<span class="monospace">[find=string_or_regex] [replace=string] [optional var=varname] [optional globalvar=globalvarname] (optional value)</span> – Replaces all occurrences of "find" with "replace" in the given value or variable.',
);
rsc('diff',
async (args, value)=>{
/**@type {HTMLScriptElement} */
let script = document.querySelector('script[src*="SillyTavern-LALib/lib/wiked-diff.js"]');
if (!script) {
await new Promise(resolve=>{
script = document.createElement('script');
script.addEventListener('load', resolve);
script.src = '/scripts/extensions/third-party/SillyTavern-LALib/lib/wiked-diff.js';
document.body.append(script);
});
const style = document.createElement('style');
style.innerHTML = `
html > body {
#dialogue_popup.wide_dialogue_popup.large_dialogue_popup:has(.lalib--diffContainer) {
aspect-ratio: unset;
}
.lalib--diffWrapper {
display: flex;
flex-direction: column;
height: 100%;
overflow: hidden;
align-items: stretch;
gap: 1em;
> .lalib--diffNotes {
flex: 0 0 auto;
align-self: center;
max-height: 20vh;
overflow: auto;
text-align: left;
font-size: 88%;
white-space: pre-wrap;
}
.lalib--diffContainer {
display: flex;
flex-direction: row;
gap: 1em;
text-align: left;
overflow: hidden;
flex: 1 1 auto;
> .lalib--diffOld, > .lalib--diffNew {
font-size: 88%;
line-height: 1.6;
white-space: pre-wrap;
}
> .lalib--diffOld, > .lalib--diffNew, .lalib--diffDiff {
flex: 1 1 0;
overflow: auto;
background-color: var(--greyCAIbg);
}
}
.lalib--diffButtons {
display: flex;
flex-direction: row;
gap: 1em;
justify-content: center;
> .lalib--diffButton {
white-space: nowrap;
}
}
}
.wikEdDiffFragment {
background-color: transparent;
border: none;
box-shadow: none;
padding: 0;
text-align: left;
* {
text-shadow: none !important;
}
.wikEdDiffInsert {
font-weight: normal;
background-color: rgb(200, 255, 200);
}
.wikEdDiffDelete {
font-weight: normal;
background-color: rgb(255, 150, 150);
text-decoration: line-through;
}
.wikEdDiffBlock {
font-weight: normal;
color: rgb(0, 0, 0);
}
}
}
`;
document.body.append(style);
}
const makeDiffer = ()=>{
const differ = new WikEdDiff();
window.wikEdDiffConfig = window.wikEdDiffConfig ?? {};
differ.config.fullDiff = true;
differ.config.charDiff = false;
// differ.config.unlinkMax = 50;
return differ;
};
let oldText = args.old;
let newText = args.new;
if (isTrueBoolean(args.stripcode)) {
const stripcode = (text)=>text.split('```').filter((_,idx)=>idx % 2 == 0).join('');
oldText = stripcode(oldText);
newText = stripcode(newText);
}
const differ = makeDiffer();
const diffHtml = differ.diff(oldText, newText);
let diff;
const updateDebounced = debounce((newText)=>diff.innerHTML = makeDiffer().diff(oldText, newText));
const dom = document.createElement('div'); {
dom.classList.add('lalib--diffWrapper');
if (args.notes && args.notes.length) {
const notes = document.createElement('div'); {
notes.classList.add('lalib--diffNotes');
notes.textContent = args.notes;
dom.append(notes);
}
}
const container = document.createElement('div'); {
container.classList.add('lalib--diffContainer');
if (isTrueBoolean(args.all)) {
const old = document.createElement('div'); {
old.classList.add('lalib--diffOld');
old.textContent = oldText;
container.append(old);
}
const ne = document.createElement('textarea'); {
ne.classList.add('lalib--diffNew');
ne.value = newText;
ne.addEventListener('input', ()=>{
newText = ne.value;
updateDebounced(ne.value);
});
container.append(ne);
}
}
diff = document.createElement('div'); {
diff.classList.add('lalib--diffDiff');
diff.innerHTML = diffHtml;
container.append(diff);
}
dom.append(container);
}
if (isTrueBoolean(args.buttons)) {
const buttons = document.createElement('div'); {
buttons.classList.add('lalib--diffButtons');
const btnOld = document.createElement('div'); {
btnOld.classList.add('lalib--diffButton');
btnOld.classList.add('menu_button');
btnOld.textContent = 'Use Old Text';
btnOld.addEventListener('click', ()=>{
result = oldText;
document.querySelector('#dialogue_popup_ok').click();
});
buttons.append(btnOld);
}
const btnNew = document.createElement('div'); {
btnNew.classList.add('lalib--diffButton');
btnNew.classList.add('menu_button');
btnNew.textContent = 'Use New Text';
btnNew.addEventListener('click', ()=>{
result = newText;
document.querySelector('#dialogue_popup_ok').click();
});
buttons.append(btnNew);
}
dom.append(buttons);
}
}
}
let result = '';
await callPopup(dom, 'text', null, { wide:true, large:true, okButton:'Close' });
return result;
},
[],
'<span class="monospace">[optional all=true] [optional buttons=true] [optional stripcode=true] [optional notes=text] [old=oldText] [new=newText]</span> – Compares old text vs new text and displays the difference between the two. Use <code>all=true</code> to show new, old, and diff side by side. Use <code>buttons=true</code> to add buttons to pick which text to return. Use <code>stripcode=true</code> to remove all codeblocks before diffing. Use <code>notes="some text"</code> to show additional notes or comments above the comparison.',
);
rsc('json-pretty',
(args, value)=>{
return JSON.stringify(JSON.parse(value), null, 4);
},
[],
'<span class="monospace">(JSON)</span> – Pretty print JSON.',
);
// GROUP: Accessing & Manipulating Structured Data
rsc('getat',
(args, value)=>{
let index = getListVar(null, null, args.index) ?? [args.index];
if (!Array.isArray(index)) {
index = [index];
}
const list = getListVar(args.var, args.globalvar, value);
let result = list;
while (index.length > 0 && result !== undefined) {
const ci = index.shift();
result = Array.isArray(result) ? result.slice(ci)[0] : result[ci];
try { result = JSON.parse(result); } catch { /* empty */ }
}
if (typeof result == 'object') {
return JSON.stringify(result);
}
return result;
},
[],
'<span class="monospace">index=int|fieldname|list [optional var=varname] [optional globalvar=globalvarname] (optional value)</span> – Retrieves an item from a list or a property from a dictionary.',
);
rsc('setat',
async(args, value)=>{
try { value = JSON.parse(value); } catch { /* empty */ }
let index = getListVar(null, null, args.index) ?? [args.index];
const list = getListVar(args.var, args.globalvar, args.value) ?? (Number.isNaN(Number(index[0])) ? {} : []);
if (!Array.isArray(index)) {
index = [index];
}
let current = list;
while (index.length > 0) {
const ci = index.shift();
if (index.length > 0 && current[ci] === undefined) {
if (Number.isNaN(Number(index[0]))) {
current[ci] = {};
} else {
current[ci] = [];
}
}
if (index.length == 0) {
current[ci] = value;
}
const prev = current;
current = current[ci];
try {
current = JSON.parse(current);
prev[ci] = current;
} catch { /* empty */ }
}
if (list !== undefined) {
let result = (typeof list == 'object') ? JSON.stringify(list) : list;
if (args.var) {
await executeSlashCommands(`/setvar key="${args.var}" ${result.replace(/\|/g, '\\|')}`);
}
if (args.globalvar) {
await executeSlashCommands(`/setglobalvar key="${args.globalvar}" ${result.replace(/\|/g, '\\|')}`);
}
return result;
}
},
[],
'<span class="monospace">index=int|fieldname|list [optional var=varname] [optional globalvar=globalvarname] [optional value=list|dictionary] (value)</span> – Sets an item in a list or a property in a dictionary. Example: <code>/setat value=[1,2,3] index=1 X</code> returns <code>[1,"X",3]</code>, <code>/setat var=myVariable index=[1,2,"somePropery"] foobar</code> sets the value of <code>myVariable[1][2].someProperty</code> to "foobar" (the variable will be updated and the resulting value of myVariable will be returned). Can be used to create structures that do not already exist.',
);
// GROUP: Exception Handling
rsc('try',
async(args, value)=>{
try {
const result = await executeSlashCommands(value);
return JSON.stringify({
isException: false,
result: result.pipe,
});
} catch (ex) {
return JSON.stringify({
isException: true,
exception: ex?.message ?? ex,
});
}
},
[],
'<span class="monospace">(command)</span> – try catch.',
);
rsc('catch',
async(args, value)=>{
if (args.pipe) {
let data;
try {
data = JSON.parse(args.pipe);
} catch (ex) {
console.warn('[LALIB]', '[CATCH]', 'failed to parse args.pipe', args.pipe, ex);
}
if (data?.isException) {
const result = await executeSlashCommands(value.replace(/{{(exception|error)}}/ig, data.exception));
return result.pipe;
} else {
return data?.result;
}
}
},
[],
'<span class="monospace">[pipe={{pipe}}] (command)</span> – try catch. You must always set <code>pipe={{pipe}}</code> and /catch must always be called right after /try. Use <code>{{exception}}</code> or <code>{{error}}</code> to get the exception\'s message.',
);
// GROUP: Copy & Download
rsc('copy',
(args, value)=>{
const ta = document.createElement('textarea'); {
ta.value = value;
ta.style.position = 'fixed';
ta.style.inset = '0';
document.body.append(ta);
ta.focus();
ta.select();
try {
document.execCommand('copy');
} catch (err) {
console.error('Unable to copy to clipboard', err);
}
ta.remove();
}
},
[],
'<span class="monospace">(value)</span> – Copies value into clipboard.',
true,
true,
);
rsc('download',
(args, value)=>{
const blob = new Blob([value], { type:'text' });
const url = URL.createObjectURL(blob);
const a = document.createElement('a'); {
a.href = url;
const name = args.name ?? `SillyTavern-${new Date().toISOString()}`;
const ext = args.ext ?? 'txt';
a.download = `${name}.${ext}`;
a.click();
}
},
[],
'<span class="monospace">[optional name=filename] [optional ext=extension] (value)</span> – Downloads value as a text file.',
true,
true,
);
// GROUP: DOM Interaction
rsc('dom',
(args, query)=>{
/**@type {HTMLElement} */
let target;
try {
target = document.querySelector(query);
} catch (ex) {
toastr.error(ex?.message ?? ex);
}
if (!target) {
toastr.warning(`No element found for query: ${query}`);
return;
}
switch (args.action) {
case 'click': {
target.click();
break;
}
case 'value': {
if (target.value === undefined) {
toastr.warning(`Cannot set value on ${target.tagName}`);
return;
}
target.value = args.value;
target.dispatchEvent(new Event('change', { bubbles:true }));
return;
}
case 'property': {
if (target[args.property] === undefined) {
toastr.warning(`Property does not exist: ${target.tagName}`);
return;
}
return target[args.property];
}
case 'attribute': {
return target.getAttribute(args.attribute);
}
}
},
[],
'<span class="monospace">[action=click|value|property] [optional value=newValue] [optional property=propertyName] [optional attribute=attributeName] (CSS selector)</span> – Click on an element, change its value, retrieve a property, or retrieve an attribute. To select the targeted element, use CSS selectors. Example: <code>/dom action=click #expandMessageActions</code> or <code>/dom action=value value=0 #avatar_style</code>',
);
// GROUP: Group Chats
rsc('memberpos',
async(args, value)=>{
if (!selected_group) {
toastr.warning('Cannot run /memberpos command outside of a group chat.');
return '';
}
const group = groups.find(it=>it.id == selected_group);
const name = value.replace(/^(.+?)(\s+(\d+))?$/, '$1');
const char = characters[findGroupMemberId(name)];
let index = value.replace(/^(.+?)(\s+(\d+))?$/, '$2');
let currentIndex = group.members.findIndex(it=>it == char.avatar);
if (index === null) {
return currentIndex;
}
index = Math.min(group.members.length - 1, parseInt(index));
while (currentIndex < index) {
await executeSlashCommands(`/memberdown ${name}`);
currentIndex++;
}
while (currentIndex > index) {
await executeSlashCommands(`/memberup ${name}`);
currentIndex--;
}
return currentIndex;
},
[],
'<span class="monospace">(name) (position)</span> – Move group member to position (index starts with 0).</code>',
);
// GROUP: Conditionals - switch
rsc('switch',
(args, value)=>{
const val = getVar(args.var, args.globalvar, value);
return JSON.stringify({
switch: val,
});
},
[],
'<span class="monospace">[optional var=varname] [optional globalvar=globalvarname] (optional value)</span> – Use with /case.',
);
rsc('case',
async (args, value)=>{
if (args.pipe) {
let data;
try {
data = JSON.parse(args.pipe);
} catch (ex) {
console.warn('[LALIB]', '[CASE]', 'failed to parse args.pipe', args.value, ex);
}
if (data?.switch !== undefined) {
if (data.switch == args.value) {
return (await executeSlashCommands(value.replace(/{{value}}/ig, data.switch)))?.pipe;
}
}
return args.pipe;
}
},
[],
'<span class="monospace">[pipe={{pipe}}] [value=comparisonValue] (/command)</span> – Execute command and break out of the switch if the value given in /switch matches the value given here.',
);
// GROUP: Conditionals - if
rsc('ife',
async(args, value)=>{
const result = await executeSlashCommands(value);
return JSON.stringify({
if: isTrueBoolean(result?.pipe),
});
},
[],
'<span class="monospace">(/command)</span> – Use with /then, /elseif, and /else. The provided command must return true or false.',
);
rsc('elseif',
async(args, value)=>{
if (args.pipe) {
let data;
try {
data = JSON.parse(args.pipe);
} catch (ex) {
console.warn('[LALIB]', '[ELSEIF]', 'failed to parse args.pipe', args.value, ex);
}
if (data?.if !== undefined) {
if (!data.if) {
const result = await executeSlashCommands(value);
return JSON.stringify({
if: isTrueBoolean(result?.pipe),
});
}
}
}
return args.pipe;
},
[],
'<span class="monospace">[pipe={{pipe}}] (/command)</span> – Use with /ife, /then, and /else. The provided command must return true or false.',
);
rsc('else',
async(args, value)=>{
if (args.pipe) {
let data;
try {
data = JSON.parse(args.pipe);
} catch (ex) {
console.warn('[LALIB]', '[ELSE]', 'failed to parse args.pipe', args.value, ex);
}
if (data?.if !== undefined) {