-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
7695 lines (7069 loc) · 392 KB
/
Copy pathindex.js
File metadata and controls
7695 lines (7069 loc) · 392 KB
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 { POPUP_RESULT, POPUP_TYPE, Popup } from '../../../popup.js';
/*
* 지도 — SillyTavern UI Extension
* Universal enchanted parchment map for roleplay scenes.
*
* - Spell flavor remains English.
* - Map contents and controls are Korean.
* - Map state is stored per chat and backed up to a character-shared notebook for cross-device continuity.
* - RP reflection uses SillyTavern extension prompt injection, not the input box.
*/
const MODULE_NAME = 'marauders_map';
const METADATA_KEY = 'marauders_map_state';
const EXTENSION_ROOT_ID = 'mma-root';
const EXTENSION_PROMPT_KEY = 'marauders_map_active_context';
const FOOTSTEP_LIMIT = 10;
const FOOTSTEP_TARGET_MIN = 6;
const FOOTSTEP_REPAIR_MAX_TOKENS = 1600;
const LOCATION_ICON_REVIEW_MAX_TOKENS = 600;
const DEBUG_LOG_LIMIT = 40;
const memoryDebugLogs = [];
const EXTENSION_VERSION = '3.1.2';
const SHARED_NOTEBOOK_KEYS = Object.freeze(['managedItems', 'footstepProfiles', 'trackedPeople', 'recommendations', 'searchResults']);
const SHARED_NOTEBOOK_MIGRATION_VERSION = 1;
const DISCOVERY_HISTORY_LIMIT = 30;
const UNCOLLECTED_RECOMMENDATION_LIMIT = 24;
const OUTPUT_MODE_CONFIGS = Object.freeze({
basic: Object.freeze({
key: 'basic',
label: '기본',
mapMaxTokens: 8000,
locationRange: '6~9',
situationRange: '8~12',
detailsRange: '4~6',
questRange: '3~5',
discoveryRange: '5~7',
discoveryMaxTokens: 5000,
personSearchMaxTokens: 2500,
}),
saver: Object.freeze({
key: 'saver',
label: '절약',
mapMaxTokens: 4000,
locationRange: '4~7',
situationRange: '4~10',
detailsRange: '3~4',
questRange: '2~3',
discoveryRange: '3~5',
discoveryMaxTokens: 2500,
personSearchMaxTokens: 1500,
}),
});
const SETTINGS_DEFAULTS = Object.freeze({
enabled: true,
connectionProfile: 'main',
outputMode: 'basic',
fontScale: 100,
theme: 'marauder',
});
const THEME_OPTIONS = Object.freeze({
marauder: {
key: 'marauder',
label: "Marauder's Map (HP AU)",
shortLabel: "Marauder's Map",
menuIcon: '📜',
menuTitle: "Marauder's Map",
activationVariant: 'spell',
closeText: 'Mischief Managed.',
idleNote: '낡은 양피지가 조용히 펼쳐진다.',
activateText: 'I solemnly swear that I am up to no good.',
castingText: '잉크가 양피지에 스며드는 중...',
completeText: '지도가 모두 그려졌습니다.',
readyHint: '주문을 한 번 누르면 지도가 활성화된다.',
loaderTitle: "Marauder's Map",
locationInfoIcon: '🎨',
discoveryUi: {
icon: '🪄',
name: 'Revelio',
question: 'Revelio를 외울까요?',
confirm: 'Revelio',
loader: '지도에 감춰진 것을 드러내는 중…',
panelTitle: 'Revelio로 드러난 것',
},
},
modern: {
key: 'modern',
label: 'S.H.I.E.L.D. Field Locator (MCU AU)',
shortLabel: 'S.H.I.E.L.D. LOCATOR',
menuIcon: '📍',
menuTitle: 'S.H.I.E.L.D. Field Locator',
activationVariant: 'warning',
closeText: '×',
idleNote: '내부 위협 경계가 유지되고 있습니다. 요원 신원과 임무 권한을 확인한 뒤 위치 신호망에 접속하십시오.',
activateText: '보안 인증 후 신호망 접속',
castingText: '요원 신원과 임무 권한을 교차 확인하는 중...',
completeText: '인증이 완료되었습니다. 현장 위치 신호망을 개방합니다.',
readyHint: '',
loaderTitle: 'S.H.I.E.L.D. LOCATOR',
locationInfoIcon: '⌖',
discoveryUi: {
icon: '📡',
name: '주변 상황 탐색',
question: '주변 상황을 탐색할까요?',
confirm: '탐색',
loader: '주변의 존재와 변화를 포착하는 중…',
panelTitle: '주변에서 포착된 것',
},
},
bonbon: {
key: 'bonbon',
label: 'Bonbon Board',
shortLabel: 'BONBON BOARD',
menuIcon: '🎲',
menuTitle: 'Bonbon Board',
activationVariant: 'game-box',
closeText: '×',
idleNote: '',
activateText: '봉봉보드 시작하기',
castingText: '게임을 준비하는 중...',
completeText: '게임판 준비가 끝났습니다.',
readyHint: '',
loaderTitle: 'Bonbon Board',
locationInfoIcon: '🎨',
discoveryUi: {
icon: '🔑',
name: '열쇠 카드',
question: '열쇠 카드를 사용할까요?',
confirm: '사용하기',
loader: '보드에 숨은 것을 찾는 중...',
panelTitle: '열쇠 카드로 찾은 것',
},
},
});
const EMPTY_MEMORY = Object.freeze({
map: null,
// A single per-chat rollback snapshot. This is deliberately not shared
// through the character notebook: ↩️ means the map immediately before the
// current chat's latest map-changing refresh, never another chat's map.
previousMap: null,
selectedLocationId: null,
managedItems: [],
footstepProfiles: {},
trackedPeople: {},
recommendations: [],
searchResults: [],
discoveries: [],
discoveryHistory: [],
discoveryGeneratedAt: null,
generatedAt: null,
mapRevision: null,
lastAction: null,
});
let spellCasting = false;
let initialized = false;
let lifecycleEnabled = true;
let initDomReadyHandler = null;
let appLifecycleHooksBound = false;
let appLifecycleHandlers = [];
let chatChangedHooked = false;
let lastKnownChatSignature = '';
let profileSwitchDepth = 0;
let suppressChatChangeUntil = 0;
let mapResizeState = null;
// Serialize metadata writes so fast consecutive UI actions cannot finish out of order.
let saveMemoryQueue = Promise.resolve();
let saveMemorySequence = 0;
let mapRevisionSequence = 0;
// Only one map/selected-location generation may commit at a time.
let activeMapGeneration = null;
let activeDiscoveryConfirm = null;
const attachedNotebookMemories = new WeakSet();
const attachedNotebookFingerprints = new WeakMap();
const sharedNotebookMigrationSaveQueued = new WeakSet();
function shouldIgnoreChatChanged() {
return profileSwitchDepth > 0 || Date.now() < suppressChatChangeUntil;
}
function markProfileSwitchSuppression(ms = 2500) {
suppressChatChangeUntil = Math.max(suppressChatChangeUntil, Date.now() + ms);
}
function getStableChatSignature() {
try {
const ctx = safeContext();
const id = ctx?.chatId;
if (typeof id === 'string' && id.trim()) return `chatId:${id.trim()}`;
if (typeof id === 'number' && Number.isFinite(id)) return `chatId:${id}`;
return '';
} catch {
return '';
}
}
function rememberCurrentChatSignature() {
const signature = getStableChatSignature();
if (signature) lastKnownChatSignature = signature;
return signature;
}
function assertChatSignatureUnchanged(startSignature, operation = 'request') {
const endSignature = getStableChatSignature();
if (startSignature && endSignature && startSignature !== endSignature) {
pushDebugLog(`${operation}.cancelled.chat_changed`, '요청 중 채팅이 바뀌어 결과를 저장하지 않았습니다.', {
startChatSignature: startSignature,
endChatSignature: endSignature,
});
throw createMapGenerationCancelledError('chat changed during request');
}
}
function assertMapSnapshotUnchanged(startMap, operation = 'request', footstepSnapshot = null) {
const currentMap = ensureMemory().map;
let changed = Boolean(startMap && currentMap !== startMap);
if (!changed && footstepSnapshot) {
const live = currentMap?.footsteps?.find(item => String(item.id) === String(footstepSnapshot.id));
changed = !live
|| String(live.locationId || '') !== String(footstepSnapshot.locationId || '')
|| String(live.status || '').replace(/\s+/g, ' ').trim() !== String(footstepSnapshot.status || '').replace(/\s+/g, ' ').trim();
}
if (!changed) return;
pushDebugLog(`${operation}.cancelled.map_changed`, '요청 중 지도가 갱신되어 이전 지도 기준 결과를 저장하지 않았습니다.', {
expectedFootstepId: footstepSnapshot?.id || '',
});
throw createMapGenerationCancelledError('map changed during request');
}
function assertMapStateUnchanged(startMap, startRevision, operation = 'request') {
const memory = ensureMemory();
const currentRevision = String(memory.mapRevision || '');
const expectedRevision = String(startRevision || '');
if (memory.map === startMap && currentRevision === expectedRevision) return;
pushDebugLog(`${operation}.cancelled.map_changed`, '요청 중 지도가 갱신되어 이전 지도 기준 결과를 저장하지 않았습니다.', {
expectedRevision,
currentRevision,
});
throw createMapGenerationCancelledError('map changed during request');
}
function createMapRevisionToken() {
mapRevisionSequence += 1;
return `map-${Date.now().toString(36)}-${mapRevisionSequence.toString(36)}`;
}
function serializeForDebug(value) {
try {
if (value instanceof Error) return { name: value.name, message: value.message, stack: value.stack };
if (typeof value === 'string') return value;
return JSON.parse(JSON.stringify(value));
} catch {
return String(value);
}
}
function sanitizeDebugData(value) {
const data = serializeForDebug(value);
const clean = (input, depth = 0) => {
if (input == null) return input;
if (depth > 3) return '[omitted]';
if (typeof input === 'string') return input.length > 220 ? `${input.slice(0, 220)}…` : input;
if (typeof input !== 'object') return input;
if (Array.isArray(input)) return input.slice(0, 8).map(item => clean(item, depth + 1));
const out = {};
for (const [key, raw] of Object.entries(input)) {
if (/preview|raw|prompt|stack|available/i.test(key)) continue;
if (/profileId|connectionProfile|selectedProfile|target/i.test(key)) {
out[key] = raw ? '[selected]' : '';
continue;
}
if (/profileName/i.test(key)) {
out[key] = raw ? '[selected profile]' : '';
continue;
}
if (/filename|url|href/i.test(key)) continue;
out[key] = clean(raw, depth + 1);
}
return out;
};
return clean(data);
}
function getDebugLogs() {
return memoryDebugLogs.slice();
}
function pushDebugLog(type, message, data = null) {
const entry = {
at: nowStamp(),
version: EXTENSION_VERSION,
type: String(type || 'info'),
message: String(message || ''),
theme: (() => { try { return getThemeKey(); } catch { return 'unknown'; } })(),
chat: (() => { try { return safeContext()?.chatId ? 'active' : (safeContext()?.chat?.length ? 'active' : ''); } catch { return ''; } })(),
data: sanitizeDebugData(data),
};
memoryDebugLogs.unshift(entry);
if (memoryDebugLogs.length > DEBUG_LOG_LIMIT) memoryDebugLogs.length = DEBUG_LOG_LIMIT;
}
function clearDebugLogs() {
memoryDebugLogs.length = 0;
}
function shouldPrintDebugToConsole() {
return false;
}
function copyDebugLogsToClipboard() {
const payload = {
extension: '지도',
version: EXTENSION_VERSION,
time: nowStamp(),
theme: (() => { try { return getThemeKey(); } catch { return 'unknown'; } })(),
logs: getDebugLogs().slice(0, 40),
};
const text = JSON.stringify(payload, null, 2);
if (navigator.clipboard?.writeText) {
return navigator.clipboard.writeText(text).then(() => toast('디버그 로그를 복사했습니다.', 'success'));
}
const textarea = document.createElement('textarea');
textarea.value = text;
textarea.style.position = 'fixed';
textarea.style.left = '-9999px';
document.body.appendChild(textarea);
textarea.select();
document.execCommand('copy');
textarea.remove();
toast('디버그 로그를 복사했습니다.', 'success');
}
function buildMapDebugDump() {
const settings = (() => { try { return getSettings(); } catch { return {}; } })();
const profiles = (() => {
try {
return Array.from(window.__mmaConnectionProfileCache || []).map(profile => ({
id: profile.id || '',
name: profile.name || '',
model: profile.model || profile.modelName || profile.api || '',
}));
} catch {
return [];
}
})();
const selectedProfile = profiles.find(p => p.id === settings.connectionProfile) || null;
return JSON.stringify({
extension: '지도',
version: EXTENSION_VERSION,
time: nowStamp(),
theme: (() => { try { return getThemeKey(); } catch { return 'unknown'; } })(),
settings: {
theme: settings.theme,
outputMode: normalizeOutputMode(settings.outputMode),
fontScale: settings.fontScale,
connectionProfile: settings.connectionProfile === 'main' ? 'main' : 'selected',
selectedProfile: Boolean(selectedProfile),
cachedProfileCount: profiles.length,
},
currentMap: (() => {
try {
const memory = ensureMemory();
const map = memory.map || null;
return map ? {
mapTitle: map.mapTitle || '',
regionName: map.regionName || '',
timeHint: map.timeHint || '',
currentLocationId: map.currentLocationId || '',
locations: Array.isArray(map.locations) ? map.locations.length : 0,
footsteps: Array.isArray(map.footsteps) ? map.footsteps.length : 0,
events: Array.isArray(map.events) ? map.events.length : 0,
discoveries: Array.isArray(memory.discoveries) ? memory.discoveries.length : 0,
discoveryHistory: Array.isArray(memory.discoveryHistory) ? memory.discoveryHistory.length : 0,
managedItems: Array.isArray(memory.managedItems) ? memory.managedItems.length : 0,
recommendations: Array.isArray(memory.recommendations) ? memory.recommendations.length : 0,
trackedPeople: memory.trackedPeople ? Object.keys(memory.trackedPeople).length : 0,
} : null;
} catch {
return null;
}
})(),
searchState: (() => {
try {
const memory = ensureMemory();
return {
placeResults: Array.isArray(memory.recommendations) ? memory.recommendations.length : 0,
collectedPlaces: Array.isArray(memory.recommendations) ? memory.recommendations.filter(item => item?.collected).length : 0,
personSearchHistory: Array.isArray(memory.searchResults) ? memory.searchResults.length : 0,
trackedPeople: memory.trackedPeople ? Object.keys(memory.trackedPeople).length : 0,
activeInjectedContexts: (memory.managedItems || []).filter(item => ['injected', 'char_notice', 'user_notice'].includes(item?.status)).length,
};
} catch {
return null;
}
})(),
logs: getDebugLogs().slice(0, 40),
}, null, 2);
}
function showMapSettingsDebugDump() {
const dump = buildMapDebugDump();
const panel = document.getElementById('mma-settings-debug-panel');
const output = document.getElementById('mma-settings-debug-output');
if (panel) panel.style.display = '';
if (output) {
output.value = dump;
output.style.display = '';
}
toast('디버그 로그를 표시했습니다.', 'success');
return dump;
}
function toggleMapSettingsDebugDump() {
const panel = document.getElementById('mma-settings-debug-panel');
if (panel && panel.style.display !== 'none' && panel.offsetParent !== null) {
panel.style.display = 'none';
toast('디버그 로그를 접었습니다.', 'success');
return '';
}
return showMapSettingsDebugDump();
}
async function copyMapSettingsDebugDump() {
const dump = showMapSettingsDebugDump();
if (navigator.clipboard?.writeText) {
await navigator.clipboard.writeText(dump);
} else {
const textarea = document.createElement('textarea');
textarea.value = dump;
textarea.style.position = 'fixed';
textarea.style.left = '-9999px';
document.body.appendChild(textarea);
textarea.select();
document.execCommand('copy');
textarea.remove();
}
toast('디버그 로그를 복사했습니다.', 'success');
}
function clearMapSettingsDebugDump() {
clearDebugLogs();
const output = document.getElementById('mma-settings-debug-output');
if (output) output.value = buildMapDebugDump();
toast('디버그 로그를 비웠습니다.', 'success');
}
function setupDebugHooks() {
// Quiet runtime: do not hook global window errors/rejections or beforeunload for debug logging.
// Keep only harmless cleanup/viewport handlers needed by the map UI.
if (globalThis.__mmaDebugHooksInstalled) return;
globalThis.__mmaDebugHooksInstalled = true;
window.addEventListener('pagehide', () => {
cancelActiveMapGeneration('page hidden');
if (mapResizeState) endMapResize();
});
window.visualViewport?.addEventListener?.('resize', () => {
const canvas = document.getElementById('mma-map-canvas');
if (canvas && !mapResizeState && canvas.dataset.mmaUserResized === 'true') {
const rect = canvas.getBoundingClientRect();
const max = Math.max(240, Math.round(getViewportHeight() - rect.top - 18));
if (canvas.getBoundingClientRect().height > max) applyMapCanvasHeight(canvas, max, max);
}
});
}
function setupOverlayDebugObserver() {
// Quiet runtime: no DOM-wide debug observer. The map works without this observer.
return;
}
function stContext() {
if (!globalThis.SillyTavern?.getContext) {
throw new Error('SillyTavern.getContext()를 찾을 수 없습니다.');
}
return globalThis.SillyTavern.getContext();
}
function safeContext() {
try {
if (!globalThis.SillyTavern?.getContext) return null;
return globalThis.SillyTavern.getContext() || null;
} catch {
return null;
}
}
function isContextReady() {
const ctx = safeContext();
return Boolean(ctx && document.body);
}
function clone(value) {
if (typeof structuredClone === 'function') return structuredClone(value);
return JSON.parse(JSON.stringify(value));
}
function nowStamp() {
const d = new Date();
return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')} ${String(d.getHours()).padStart(2, '0')}:${String(d.getMinutes()).padStart(2, '0')}`;
}
function formatCompactMapTime(value) {
const text = String(value || '').trim();
const match = text.match(/^\d{4}-(\d{2})-(\d{2})\s+(\d{2}:\d{2})/);
return match ? `${match[1]}.${match[2]} ${match[3]}` : text;
}
function getSettings() {
const ctx = stContext();
if (!ctx.extensionSettings) ctx.extensionSettings = {};
if (!ctx.extensionSettings[MODULE_NAME]) ctx.extensionSettings[MODULE_NAME] = clone(SETTINGS_DEFAULTS);
const settings = ctx.extensionSettings[MODULE_NAME];
for (const [key, value] of Object.entries(SETTINGS_DEFAULTS)) {
if (!Object.hasOwn(settings, key)) settings[key] = value;
}
return settings;
}
function saveSettings() {
try {
const ctx = stContext();
if (typeof ctx?.saveSettingsDebounced === 'function') {
ctx.saveSettingsDebounced();
} else if (typeof globalThis.saveSettingsDebounced === 'function') {
globalThis.saveSettingsDebounced();
}
} catch (error) {
console.warn('[MarauderMap] 설정 저장 실패:', error);
}
}
function normalizeFontScale(value) {
const number = Number(value);
if (!Number.isFinite(number)) return 13;
// Backward compatibility: older versions stored this as a percentage
// such as 75, 100, or 115. New UI stores the visible font size in px.
const px = number > 40 ? (number / 100) * 13 : number;
return Math.min(24, Math.max(10, Math.round(px)));
}
function applyFontScale() {
let px = 13;
try {
px = normalizeFontScale(getSettings().fontScale);
} catch {
px = 13;
}
const root = document.getElementById(EXTENSION_ROOT_ID);
const windowEl = document.getElementById('mma-window');
const value = String(px / 13);
root?.style.setProperty('--mma-font-scale', value);
windowEl?.style.setProperty('--mma-font-scale', value);
}
function normalizeTheme(value) {
return Object.hasOwn(THEME_OPTIONS, value) ? value : 'marauder';
}
function getThemeKey() {
try {
const settings = getSettings();
settings.theme = normalizeTheme(settings.theme);
return settings.theme;
} catch {
return 'marauder';
}
}
function getThemeConfig() {
return THEME_OPTIONS[getThemeKey()] || THEME_OPTIONS.marauder;
}
function normalizeOutputMode(value) {
return Object.hasOwn(OUTPUT_MODE_CONFIGS, value) ? value : 'basic';
}
function getOutputModeKey() {
try {
const settings = getSettings();
settings.outputMode = normalizeOutputMode(settings.outputMode);
return settings.outputMode;
} catch {
return 'basic';
}
}
function getOutputModeConfig() {
return OUTPUT_MODE_CONFIGS[getOutputModeKey()] || OUTPUT_MODE_CONFIGS.basic;
}
function getDiscoveryUiConfig() {
return getThemeConfig().discoveryUi || THEME_OPTIONS.marauder.discoveryUi;
}
function getMapActivationCompleteText() {
const theme = getThemeConfig();
return theme.completeText || '지도가 모두 그려졌습니다.';
}
function getExtensionMenuIcon() {
return getThemeConfig().menuIcon || '📜';
}
function refreshExtensionsMenuButton() {
const button = document.getElementById('mma-extension-menu-button');
if (!button) return;
button.title = getThemeConfig().menuTitle || getThemeConfig().shortLabel;
button.innerHTML = `<span class="mma-menu-icon extensionsMenuExtensionButton">${getExtensionMenuIcon()}</span><span class="mma-menu-label">지도</span>`;
}
function applyThemeClass() {
const theme = getThemeKey();
const root = document.getElementById(EXTENSION_ROOT_ID);
const windowEl = document.getElementById('mma-window');
[root, windowEl].filter(Boolean).forEach(el => {
for (const key of Object.keys(THEME_OPTIONS)) {
el.classList.toggle(`mma-theme-${key}`, theme === key);
}
el.dataset.mmaTheme = theme;
});
}
function setTheme(value, rerender = false) {
const settings = getSettings();
settings.theme = normalizeTheme(value);
saveSettings();
applyThemeClass();
refreshExtensionsMenuButton();
if (rerender) renderSpellScreen();
}
function isModernTheme() {
return getThemeKey() === 'modern';
}
function isBonbonTheme() {
return getThemeKey() === 'bonbon';
}
function isMarauderTheme() {
return getThemeKey() === 'marauder';
}
function getCharacterKeyForRecord(character, fallback = 'default-character') {
const stableSource = character?.avatar || character?.name || fallback || 'default-character';
return safeId(String(stableSource), 'character');
}
function getCurrentCharacterKey() {
try {
const ctx = stContext();
const char = Number.isInteger(ctx.characterId) ? ctx.characters?.[ctx.characterId] : null;
return getCharacterKeyForRecord(char, ctx.name2 || ctx.characterId || 'default-character');
} catch {
return 'character-default';
}
}
function createEmptyNotebook() {
return {
managedItems: [],
footstepProfiles: {},
trackedPeople: {},
recommendations: [],
searchResults: [],
createdAt: nowStamp(),
updatedAt: nowStamp(),
};
}
function normalizeNotebookShape(notebook) {
const book = notebook && typeof notebook === 'object' && !Array.isArray(notebook) ? notebook : createEmptyNotebook();
if (!Array.isArray(book.managedItems)) book.managedItems = [];
if (!book.footstepProfiles || typeof book.footstepProfiles !== 'object' || Array.isArray(book.footstepProfiles)) book.footstepProfiles = {};
if (!book.trackedPeople || typeof book.trackedPeople !== 'object' || Array.isArray(book.trackedPeople)) book.trackedPeople = {};
if (!Array.isArray(book.recommendations)) book.recommendations = [];
if (!Array.isArray(book.searchResults)) book.searchResults = [];
book.updatedAt = book.updatedAt || nowStamp();
return book;
}
function cloneSharedNotebookData(source) {
const book = normalizeNotebookShape(clone(source && typeof source === 'object' && !Array.isArray(source)
? source
: createEmptyNotebook()));
return {
managedItems: clone(book.managedItems),
footstepProfiles: clone(book.footstepProfiles),
trackedPeople: clone(book.trackedPeople),
recommendations: clone(book.recommendations),
searchResults: clone(book.searchResults),
};
}
function assignSharedNotebookData(memory, source = null) {
if (!memory || typeof memory !== 'object') return;
const data = cloneSharedNotebookData(source);
for (const key of SHARED_NOTEBOOK_KEYS) memory[key] = data[key];
}
function clearSharedNotebookData(memory) {
assignSharedNotebookData(memory, null);
}
function sharedNotebookFingerprint(source) {
try {
const book = source && typeof source === 'object' && !Array.isArray(source) ? source : {};
return JSON.stringify({
managedItems: Array.isArray(book.managedItems) ? book.managedItems : [],
footstepProfiles: book.footstepProfiles && typeof book.footstepProfiles === 'object' && !Array.isArray(book.footstepProfiles) ? book.footstepProfiles : {},
trackedPeople: book.trackedPeople && typeof book.trackedPeople === 'object' && !Array.isArray(book.trackedPeople) ? book.trackedPeople : {},
recommendations: Array.isArray(book.recommendations) ? book.recommendations : [],
searchResults: Array.isArray(book.searchResults) ? book.searchResults : [],
});
} catch {
return '';
}
}
function isCompletelyEmptyStoredNotebook(notebook) {
if (!notebook || typeof notebook !== 'object' || Array.isArray(notebook)) return false;
const allowedKeys = new Set([
...SHARED_NOTEBOOK_KEYS,
'createdAt',
'updatedAt',
'resetToken',
]);
if (Object.keys(notebook).some(key => !allowedKeys.has(key))) return false;
const arrayKeys = ['managedItems', 'recommendations', 'searchResults'];
for (const key of arrayKeys) {
if (!Object.hasOwn(notebook, key)) continue;
if (!Array.isArray(notebook[key]) || notebook[key].length > 0) return false;
}
const objectKeys = ['footstepProfiles', 'trackedPeople'];
for (const key of objectKeys) {
if (!Object.hasOwn(notebook, key)) continue;
if (!notebook[key] || typeof notebook[key] !== 'object' || Array.isArray(notebook[key]) || Object.keys(notebook[key]).length > 0) return false;
}
return true;
}
function arrayIdentity(item, index, prefix = 'item') {
if (!item || typeof item !== 'object') return `${prefix}:${index}`;
return String(item.id || item.sourceId || item.source || item.name || item.title || item.locationName || `${prefix}:${index}`);
}
function mergeArrayByIdentity(base = [], incoming = [], limit = Infinity, prefix = 'item') {
const map = new Map();
const add = (item, index, sourcePrefix) => {
if (!item || typeof item !== 'object') return;
const key = arrayIdentity(item, index, sourcePrefix);
const previous = map.get(key) || {};
map.set(key, { ...previous, ...item });
};
(Array.isArray(base) ? base : []).forEach((item, index) => add(item, index, prefix));
(Array.isArray(incoming) ? incoming : []).forEach((item, index) => add(item, index, prefix));
const values = Array.from(map.values());
return Number.isFinite(limit) ? values.slice(0, Math.max(0, limit)) : values;
}
function mergeTrackedPeople(base = {}, incoming = {}) {
const out = { ...(base && typeof base === 'object' && !Array.isArray(base) ? base : {}) };
if (!incoming || typeof incoming !== 'object' || Array.isArray(incoming)) return out;
Object.entries(incoming).forEach(([key, value]) => {
if (!value || typeof value !== 'object') return;
const previous = out[key] || {};
const history = mergeArrayByIdentity(previous.history || [], value.history || [], Infinity, `${key}:history`);
out[key] = { ...previous, ...value, history };
});
return out;
}
function notebookHasData(source) {
if (!source || typeof source !== 'object') return false;
return Boolean(
(Array.isArray(source.managedItems) && source.managedItems.length) ||
(source.footstepProfiles && typeof source.footstepProfiles === 'object' && Object.keys(source.footstepProfiles).length) ||
(source.trackedPeople && typeof source.trackedPeople === 'object' && Object.keys(source.trackedPeople).length) ||
(Array.isArray(source.recommendations) && source.recommendations.length) ||
(Array.isArray(source.searchResults) && source.searchResults.length)
);
}
function isValidMapData(map) {
return !!map && typeof map === 'object' && Array.isArray(map.locations) && map.locations.length > 0;
}
function purgeLegacyMapBackupsFromChat(memory) {
if (!memory || typeof memory !== 'object' || Array.isArray(memory)) return false;
let changed = false;
for (const key of ['lastMaps', 'activeMapBackups']) {
if (Object.hasOwn(memory, key)) {
delete memory[key];
changed = true;
}
}
return changed;
}
function runLegacySharedNotebookCleanupOnce(settings = getSettings()) {
const completedVersion = Number(settings?.sharedNotebookMigrationVersion || 0);
if (completedVersion >= SHARED_NOTEBOOK_MIGRATION_VERSION) {
return { ran: false, cleanedBackups: 0, removedEmptyNotebooks: 0 };
}
const notebooks = settings?.characterNotebooks;
let cleanedBackups = 0;
let removedEmptyNotebooks = 0;
if (notebooks && typeof notebooks === 'object' && !Array.isArray(notebooks)) {
for (const [key, notebook] of Object.entries(notebooks)) {
if (!notebook || typeof notebook !== 'object' || Array.isArray(notebook)) continue;
let removedLegacyBackup = false;
for (const legacyKey of ['lastMaps', 'activeMapBackups']) {
if (Object.hasOwn(notebook, legacyKey)) {
delete notebook[legacyKey];
removedLegacyBackup = true;
}
}
if (removedLegacyBackup) cleanedBackups += 1;
if (isCompletelyEmptyStoredNotebook(notebook)) {
delete notebooks[key];
removedEmptyNotebooks += 1;
}
}
if (Object.keys(notebooks).length === 0) delete settings.characterNotebooks;
}
// The marker is deliberately persisted even when there was nothing to
// purge, so the all-character scan never repeats on later starts/uses.
settings.sharedNotebookMigrationVersion = SHARED_NOTEBOOK_MIGRATION_VERSION;
saveSettings();
pushDebugLog('migration.sharedNotebooks.completed', '캐릭터 공용 수첩의 1회 저장소 정리를 완료했습니다.', {
cleanedBackups,
removedEmptyNotebooks,
version: SHARED_NOTEBOOK_MIGRATION_VERSION,
});
return { ran: true, cleanedBackups, removedEmptyNotebooks };
}
const legacyChatMapCleanupQueued = new WeakSet();
function scheduleLegacyChatMapCleanupSave(memory) {
if (!memory || legacyChatMapCleanupQueued.has(memory)) return;
legacyChatMapCleanupQueued.add(memory);
Promise.resolve().then(async () => {
legacyChatMapCleanupQueued.delete(memory);
const ctx = safeContext();
if (!ctx?.chatMetadata || ctx.chatMetadata[METADATA_KEY] !== memory) return;
try {
if (typeof ctx.saveMetadata === 'function') await ctx.saveMetadata();
else if (typeof ctx.saveChatMetadata === 'function') await ctx.saveChatMetadata();
pushDebugLog('migration.chatMapBackups.purged', '현재 채팅의 예전 지도 백업을 정리했습니다.');
} catch (error) {
pushDebugLog('migration.chatMapBackups.purge.error', '현재 채팅의 예전 지도 백업 정리 저장에 실패했습니다.', serializeForDebug(error));
}
});
}
function normalizePreviousMapSnapshot(value) {
if (!value || typeof value !== 'object' || Array.isArray(value) || !isValidMapData(value.map)) return null;
return {
map: value.map,
selectedLocationId: String(value.selectedLocationId || value.map.currentLocationId || value.map.locations[0]?.id || ''),
generatedAt: value.generatedAt || null,
capturedAt: value.capturedAt || null,
reason: String(value.reason || ''),
};
}
function createPreviousMapSnapshot(memory = null, reason = 'refresh') {
const target = memory || ensureMemory();
if (!isValidMapData(target.map)) return null;
return {
map: clone(target.map),
selectedLocationId: target.selectedLocationId || target.map.currentLocationId || target.map.locations[0]?.id || '',
generatedAt: target.generatedAt || null,
capturedAt: nowStamp(),
reason: String(reason || 'refresh'),
};
}
function commitPreviousMapSnapshot(memory = null, snapshot = null) {
const target = memory || ensureMemory();
const normalized = normalizePreviousMapSnapshot(snapshot);
if (!normalized) return false;
target.previousMap = normalized;
pushDebugLog('map.rollback.capture', '현재 채팅의 직전 지도 스냅샷을 저장했습니다.', {
reason: normalized.reason,
locations: normalized.map.locations.length,
});
return true;
}
function hasPreviousMapSnapshot(memory = null) {
const target = memory || ensureMemory();
return Boolean(normalizePreviousMapSnapshot(target.previousMap));
}
async function restorePreviousMap() {
if (activeMapGeneration) {
toast(isModernTheme()
? '위치 신호망을 갱신하는 동안에는 직전 기록을 복원할 수 없습니다.'
: '지도를 생성하는 동안에는 직전 지도를 되돌릴 수 없습니다.', 'info');
return false;
}
const memory = ensureMemory();
const snapshot = normalizePreviousMapSnapshot(memory.previousMap);
if (!snapshot) {
toast(isModernTheme() ? '복원할 직전 위치 신호 기록이 없습니다.' : '되돌릴 직전 지도가 없습니다.', 'info');
return false;
}
memory.map = clone(snapshot.map);
memory.mapRevision = createMapRevisionToken();
reconcileTransientDiscoveries(memory, memory.map);
memory.selectedLocationId = snapshot.selectedLocationId || snapshot.map.currentLocationId || snapshot.map.locations[0]?.id || null;
memory.generatedAt = snapshot.generatedAt || nowStamp();
memory.lastAction = 'rollback-previous-map';
// One-step rollback only. Once restored, the same snapshot cannot be
// toggled back and forth or accidentally become a cross-chat history.
memory.previousMap = null;
await saveMemory(memory);
syncExtensionPrompt();
renderMapView();
toast(isModernTheme() ? '직전 위치 신호 기록을 복원했습니다.' : '직전 지도로 되돌렸습니다.', 'success');
pushDebugLog('map.rollback.restore', '현재 채팅의 직전 지도 스냅샷을 복구했습니다.', {
locations: memory.map.locations.length,
reason: snapshot.reason || 'refresh',
});
return true;
}
function getCharacterNotebook(settings = getSettings(), key = getCurrentCharacterKey()) {
const notebooks = settings?.characterNotebooks;
if (!notebooks || typeof notebooks !== 'object' || Array.isArray(notebooks)) {
return { key, notebook: null };
}
const notebook = notebooks[key];
if (!notebook || typeof notebook !== 'object' || Array.isArray(notebook)) {
return { key, notebook: null };
}
return { key, notebook };
}
function getSharedNotebookResetToken(settings = getSettings(), key = getCurrentCharacterKey()) {
const resets = settings?.characterNotebookResets;
if (!resets || typeof resets !== 'object' || Array.isArray(resets)) return '';
return String(resets[key] || '');
}
function createSharedNotebookResetToken() {
return `reset-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 8)}`;
}
function mergeMemoryIntoNotebook(notebook, memory) {
if (!notebook || !memory) return notebook;
notebook.managedItems = mergeArrayByIdentity(notebook.managedItems, memory.managedItems, Infinity, 'managed');
notebook.footstepProfiles = { ...(notebook.footstepProfiles || {}), ...(memory.footstepProfiles || {}) };
notebook.trackedPeople = mergeTrackedPeople(notebook.trackedPeople, memory.trackedPeople);
notebook.recommendations = mergeArrayByIdentity(notebook.recommendations, memory.recommendations, Infinity, 'recommendation');
notebook.searchResults = mergeArrayByIdentity(notebook.searchResults, memory.searchResults, Infinity, 'search');
notebook.updatedAt = nowStamp();
return normalizeNotebookShape(notebook);
}
function scheduleSharedNotebookMigrationSave(memory) {
if (!memory || sharedNotebookMigrationSaveQueued.has(memory)) return;
sharedNotebookMigrationSaveQueued.add(memory);
Promise.resolve().then(async () => {
sharedNotebookMigrationSaveQueued.delete(memory);
const ctx = safeContext();
if (!ctx?.chatMetadata || ctx.chatMetadata[METADATA_KEY] !== memory) return;
await saveMemory(memory);
});
}
function attachCharacterNotebook(memory) {
const settings = getSettings();
const key = getCurrentCharacterKey();
const resetToken = getSharedNotebookResetToken(settings, key);
if (