-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathstorage.js
More file actions
2521 lines (2230 loc) · 131 KB
/
Copy pathstorage.js
File metadata and controls
2521 lines (2230 loc) · 131 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
// storage.js
// [설계 전제 / 수정 금지선]
// 이 앱은 여러 탭에서 동일한 문서를 동시에 편집하는 것 자체를 지원하지 않고, 가정하지도 않습니다.
// storage.js의 저장/로드/복구 경계는 단일 활성 문서의 데이터 무결성을 위한 것이며,
// cross-tab 동기화, 문서 컨텍스트 간 병합, localStorage lease lock, storage event 기반 조정으로 확장하지 않습니다.
// [보안 수정] 프로토타입 오염(Prototype Pollution)을 방지하기 위한 재귀적 객체 정제 함수입니다.
// 외부 JSON 데이터를 파싱한 직후 이 함수를 호출하여 '__proto__', 'constructor', 'prototype' 같은
// 위험한 키가 전역 Object 프로토타입을 오염시키는 것을 원천적으로 차단합니다.
const sanitizeObjectForPrototypePollution = (obj) => {
if (obj === null || typeof obj !== 'object') {
return false; // 객체가 아니면 재귀를 중단합니다.
}
let removedUnsafeKey = false;
const dangerousKeys = ['__proto__', 'constructor', 'prototype'];
for (const key of dangerousKeys) {
if (Object.prototype.hasOwnProperty.call(obj, key)) {
delete obj[key];
removedUnsafeKey = true;
}
}
// 객체의 모든 속성에 대해 재귀적으로 정제 함수를 호출합니다.
for (const key in obj) {
if (Object.prototype.hasOwnProperty.call(obj, key)) {
removedUnsafeKey = sanitizeObjectForPrototypePollution(obj[key]) || removedUnsafeKey;
}
}
return removedUnsafeKey;
};
// [버그 수정] Chrome Storage API를 Promise 기반으로 사용하기 위한 래퍼 함수
// 브라우저/환경 간 호환성을 보장하고, chrome.runtime.lastError를 확인하여 모든 실패 사례를 처리합니다.
export const storageGet = (keys) =>
new Promise((resolve, reject) => {
chrome.storage.local.get(keys, (result) => {
if (chrome.runtime.lastError) {
return reject(chrome.runtime.lastError);
}
resolve(result);
});
});
export const storageSet = (obj) =>
new Promise((resolve, reject) => {
chrome.storage.local.set(obj, () => {
if (chrome.runtime.lastError) {
return reject(chrome.runtime.lastError);
}
resolve();
});
});
export const storageRemove = (keys) =>
new Promise((resolve, reject) => {
chrome.storage.local.remove(keys, () => {
if (chrome.runtime.lastError) {
return reject(chrome.runtime.lastError);
}
resolve();
});
});
// [버그 수정] 순환 참조 해결을 위해 generateUniqueId를 state.js에서 가져오도록 수정합니다.
import { state, setState, buildNoteMap, CONSTANTS, generateUniqueId } from './state.js';
import { showToast, showConfirm, importFileInput, sortNotes, showAlert, showPrompt } from './components.js';
import { updateNoteCreationDates } from './itemActions.js';
// [수정] welcomeNote.js에서 환영 메시지 내용을 가져옵니다.
import { welcomeNoteContent } from './welcomeNote.js';
import { escapeHtml } from './sanitizer.js';
// [기능 추가] LunaFlowACT.js에서 노트 내용을 가져옵니다.
import { lunaFlowACTContent } from './LunaFlowACT.js';
import { withAppStateWriteLock } from './storageLock.js';
import {
parseEmergencyBackupChanges,
shouldDiscardEmergencyNoteUpdate,
shouldDiscardEmergencyItemRename,
shouldDiscardEmergencyBackupAfterTransaction
} from './emergencyRecoveryUtils.js';
// [기능 추가] 습관 트래커 데이터 키 상수
const HABIT_TRACKER_DATA_KEY = 'habitTrackerDataV2_integrated';
// [기능 추가] 다이어트 챌린지 데이터 키 상수
const DIET_CHALLENGE_DATA_KEY = 'diet_pro_records'; // dietChallenge.js의 STORAGE_KEY와 일치해야 함
const DIET_CHALLENGE_SETTINGS_KEY = 'diet_pro_settings'; // dietChallenge.js의 SETTINGS_KEY와 일치해야 함
// [CRITICAL FIX] 실제 데이터 ID가 가상 폴더 ID와 충돌하면 해당 항목을 선택/삭제/복원할 수 없게 됩니다.
// 로드/가져오기 시 폴더·노트 ID 형식과 예약 ID를 엄격히 검증해 앱 내부 참조 무결성을 보장합니다.
const RESERVED_ITEM_IDS = new Set(Object.values(CONSTANTS.VIRTUAL_FOLDERS).map(folder => folder.id));
const MAX_ITEM_ID_LENGTH = 160;
// 휴지통 항목은 구버전 백업에서 type이 없을 수 있고, 손상된 데이터에서는 type만
// 반대로 기록될 수 있습니다. type을 무조건 신뢰하면 본문이 있는 노트를 빈 폴더로
// 정규화할 수 있으므로, 실제 데이터 필드의 형태를 우선해 판별합니다.
const hasOwnDataField = (item, key) => Object.prototype.hasOwnProperty.call(item, key);
const hasFolderDataShape = item => hasOwnDataField(item, 'name') || hasOwnDataField(item, 'notes');
const hasNoteDataShape = item => hasOwnDataField(item, 'title') || hasOwnDataField(item, 'content');
const getTrashItemKind = item => {
if (!item || typeof item !== 'object' || Array.isArray(item)) return null;
const hasFolderShape = hasFolderDataShape(item);
const hasNoteShape = hasNoteDataShape(item);
// 폴더·노트 필드가 동시에 있으면 어느 쪽이 원본인지 무손실로 판단할 수 없습니다.
if (hasFolderShape && hasNoteShape) return 'ambiguous';
if (hasFolderShape) return CONSTANTS.ITEM_TYPE.FOLDER;
if (hasNoteShape) return CONSTANTS.ITEM_TYPE.NOTE;
if (item.type === CONSTANTS.ITEM_TYPE.FOLDER) return CONSTANTS.ITEM_TYPE.FOLDER;
if (item.type === CONSTANTS.ITEM_TYPE.NOTE) return CONSTANTS.ITEM_TYPE.NOTE;
// [CRITICAL BUG FIX] 유형과 데이터 형태를 모두 알 수 없는 레코드를 노트로
// 간주하면 빈 노트로 저장되면서 원래의 알 수 없는 필드가 영구 소실됩니다.
return null;
};
// Number.isFinite만으로는 Date가 표현할 수 없는 1e300 같은 값도 통과합니다.
// 날짜 표시·정렬·달력 필터가 Invalid Date/NaN으로 오염되지 않도록 실제 Date 범위까지 확인합니다.
const toValidTimestamp = value => {
const timestamp = Number(value);
if (!Number.isFinite(timestamp) || timestamp <= 0) return null;
return Number.isNaN(new Date(timestamp).getTime()) ? null : timestamp;
};
const isReservedItemId = id => RESERVED_ITEM_IDS.has(String(id));
const normalizeFolderName = (value, fallback = '새 폴더') => {
// 폴더 이름 입력은 길이를 제한하지 않으므로, 로드/가져오기에서도
// 임의로 자르지 않습니다. 일치하지 않는 제한은 정상 저장된 이름을
// 재시작·가져오기·롤백 시 조용히 손실시킬 수 있습니다.
const normalized = String(value ?? fallback).trim();
return normalized || fallback;
};
const getUniqueFolderName = (name, usedNameKeys) => {
const baseName = normalizeFolderName(name);
const baseKey = baseName.toLowerCase();
if (!usedNameKeys.has(baseKey)) {
usedNameKeys.add(baseKey);
return baseName;
}
let counter = 2;
while (counter < 10000) {
const suffix = ` (${counter})`;
const candidate = `${baseName}${suffix}`;
const candidateKey = candidate.toLowerCase();
if (!usedNameKeys.has(candidateKey)) {
usedNameKeys.add(candidateKey);
return candidate;
}
counter += 1;
}
const fallbackSuffix = ` (${Date.now()})`;
const fallbackName = `${baseName}${fallbackSuffix}`;
usedNameKeys.add(fallbackName.toLowerCase());
return fallbackName;
};
const isValidItemIdForType = (id, prefix) => (
typeof id === 'string'
&& id.length > 0
&& id.length <= MAX_ITEM_ID_LENGTH
&& id.startsWith(prefix)
&& !isReservedItemId(id)
);
const getFolderIdAfterSanitization = (folderId, folderIdUpdateMap = new Map()) => {
if (folderId === undefined || folderId === null) return null;
const normalizedId = String(folderId);
// 가상 폴더 세션은 실제 폴더의 손상 ID 복구 맵과 충돌하지 않도록 그대로 유지합니다.
return isReservedItemId(normalizedId)
? normalizedId
: (folderIdUpdateMap.get(normalizedId) || normalizedId);
};
// [순환 참조 해결] generateUniqueId 함수를 state.js 파일로 이동시켰습니다.
// 이 파일에 있던 함수 정의를 완전히 삭제합니다.
// appState의 read-modify-write는 storageLock.js를 통해 현재 문서 컨텍스트 안의 비동기 작업 순서를 명확히 합니다.
// 세션 상태(활성 폴더/노트 등) 저장
// 초기화 중 임의의 중간 상태는 저장하지 않되, loadData()가 검증을 끝낸 최종 상태만 명시적으로 저장할 수 있습니다.
export const saveSession = ({ allowDuringInitialization = false } = {}) => {
if (window.isInitializing && !allowDuringInitialization) return;
try {
localStorage.setItem(CONSTANTS.LS_KEY, JSON.stringify({
f: state.activeFolderId,
n: state.activeNoteId,
s: state.noteSortOrder,
l: state.lastActiveNotePerFolder
}));
} catch (e) {
console.error("세션 저장 실패:", e);
}
};
const buildDataReferenceContext = (data) => {
const folders = Array.isArray(data?.folders) ? data.folders : [];
const trash = Array.isArray(data?.trash) ? data.trash : [];
const rawFavorites = data?.favorites instanceof Set
? Array.from(data.favorites)
: (Array.isArray(data?.favorites) ? data.favorites : []);
const favorites = new Set(rawFavorites.map(String));
const noteIdsByFolder = new Map();
const activeNoteIds = new Set();
const trashItemIds = new Set();
folders.forEach(folder => {
if (!folder?.id) return;
const folderId = String(folder.id);
const noteIds = new Set();
(Array.isArray(folder.notes) ? folder.notes : []).forEach(note => {
if (!note?.id) return;
const noteId = String(note.id);
noteIds.add(noteId);
activeNoteIds.add(noteId);
});
noteIdsByFolder.set(folderId, noteIds);
});
trash.forEach(item => {
if (item?.id) trashItemIds.add(String(item.id));
});
return { noteIdsByFolder, activeNoteIds, trashItemIds, favorites };
};
const isValidLastActiveReference = (folderId, noteId, context) => {
if (!folderId || !noteId) return false;
const normalizedFolderId = String(folderId);
const normalizedNoteId = String(noteId);
if (context.noteIdsByFolder.has(normalizedFolderId)) {
return context.noteIdsByFolder.get(normalizedFolderId).has(normalizedNoteId);
}
const { ALL, RECENT, FAVORITES, TRASH } = CONSTANTS.VIRTUAL_FOLDERS;
if (normalizedFolderId === ALL.id || normalizedFolderId === RECENT.id) {
return context.activeNoteIds.has(normalizedNoteId);
}
if (normalizedFolderId === FAVORITES.id) {
return context.activeNoteIds.has(normalizedNoteId) && context.favorites.has(normalizedNoteId);
}
if (normalizedFolderId === TRASH.id) {
return context.trashItemIds.has(normalizedNoteId);
}
return false;
};
const sanitizeLastActiveNoteMap = (rawMap, data, idUpdateMaps = {}, markChanged = null) => {
const sourceMap = rawMap && typeof rawMap === 'object' && !Array.isArray(rawMap) ? rawMap : {};
if (sourceMap !== rawMap && typeof markChanged === 'function') markChanged();
// 과거 호출부의 단일 Map도 허용하되, 새 경로에서는 폴더/노트 ID 맵을 분리해
// 서로 다른 유형이 같은 손상 ID를 가진 경우에도 참조를 정확히 복구합니다.
const legacyMap = idUpdateMaps instanceof Map ? idUpdateMaps : null;
const folderIdUpdateMap = legacyMap || idUpdateMaps.folderIdUpdateMap || new Map();
const noteIdUpdateMap = legacyMap || idUpdateMaps.noteIdUpdateMap || new Map();
const context = buildDataReferenceContext(data);
const cleaned = Object.create(null);
for (const [folderId, noteId] of Object.entries(sourceMap)) {
const normalizedFolderId = String(folderId);
const normalizedNoteId = String(noteId);
const newFolderId = getFolderIdAfterSanitization(normalizedFolderId, folderIdUpdateMap);
const newNoteId = noteIdUpdateMap.get(normalizedNoteId) || normalizedNoteId;
if (isValidLastActiveReference(newFolderId, newNoteId, context)) {
cleaned[newFolderId] = newNoteId;
} else if (typeof markChanged === 'function') {
markChanged();
}
}
return cleaned;
};
const parseSimplenoteTimestamp = (value, fallback) => {
// 숫자형 Unix 타임스탬프는 Date 문자열 파싱보다 먼저 판별해야 합니다.
// 그렇지 않으면 초 단위 값이 밀리초로 해석되어 1970년 날짜가 됩니다.
const numeric = Number(value);
if (Number.isFinite(numeric) && numeric > 0) {
return toValidTimestamp(numeric < 100000000000 ? numeric * 1000 : numeric) ?? fallback;
}
const parsed = new Date(value).getTime();
return toValidTimestamp(parsed) ?? fallback;
};
const createUnrecoverableAppStateError = message => {
const error = new Error(message);
error.name = 'UnrecoverableAppStateError';
return error;
};
/**
* [CRITICAL FIX] 로드된 데이터의 무결성을 검증하고, 손상된 배열/객체/ID 참조를 자동 복구합니다.
* 일반 폴더는 type 필드가 없으므로 notes 배열을 기준으로도 폴더를 판별합니다.
* @param {object} data - chrome.storage.local에서 로드한 appState 객체
* @returns {{sanitizedData: object, wasSanitized: boolean, shouldNotify: boolean, isTopLevelInvalid: boolean, idUpdateMap: Map<string, string>, folderIdUpdateMap: Map<string, string>, noteIdUpdateMap: Map<string, string>}}
*/
export const verifyAndSanitizeLoadedData = (data) => {
const emptyMaps = {
idUpdateMap: new Map(),
folderIdUpdateMap: new Map(),
noteIdUpdateMap: new Map()
};
const now = Date.now();
const createEmptySanitizedAppState = () => ({
folders: [],
trash: [],
favorites: [],
lastActiveNotePerFolder: {},
activeFolderId: CONSTANTS.VIRTUAL_FOLDERS.ALL.id,
activeNoteId: null,
lastSavedTimestamp: now
});
const createInvalidStructureResult = () => ({
sanitizedData: createEmptySanitizedAppState(),
wasSanitized: true,
shouldNotify: true,
isTopLevelInvalid: true,
...emptyMaps
});
if (!data || typeof data !== 'object' || Array.isArray(data)) {
console.warn('[Data Sanitization] Invalid top-level appState was detected. A non-persistable safe placeholder was created for validation only.');
return createInvalidStructureResult();
}
// [CRITICAL FIX] 사용자 데이터를 담는 배열 자체나 그 안의 레코드가 손상된 경우,
// 빈 배열로 정규화한 뒤 원본에 덮어쓰면 노트·휴지통 데이터가 영구 소실됩니다.
// 손실 없이 복구할 수 없는 구조는 저장 가능한 정제본으로 취급하지 않고 원본을 보존합니다.
const hasOwn = (target, key) => Object.prototype.hasOwnProperty.call(target, key);
const isRecord = value => Boolean(value) && typeof value === 'object' && !Array.isArray(value);
const hasLossyTextField = (record, key) => (
hasOwn(record, key)
&& record[key] !== null
&& typeof record[key] === 'object'
);
const hasInvalidNoteRecord = note => (
!isRecord(note)
|| hasFolderDataShape(note)
|| hasLossyTextField(note, 'title')
|| hasLossyTextField(note, 'content')
);
const hasInvalidOptionalArray = key => hasOwn(data, key) && !Array.isArray(data[key]);
const hasInvalidNoteCollection = folder => (
hasOwn(folder, 'notes')
&& (!Array.isArray(folder.notes) || folder.notes.some(hasInvalidNoteRecord))
);
const hasInvalidFolderRecords = Array.isArray(data.folders) && data.folders.some(folder => (
!isRecord(folder)
|| hasNoteDataShape(folder)
|| hasLossyTextField(folder, 'name')
|| hasInvalidNoteCollection(folder)
));
const hasInvalidTrashRecords = Array.isArray(data.trash) && data.trash.some(item => {
if (!isRecord(item)) return true;
const itemKind = getTrashItemKind(item);
if (!itemKind || itemKind === 'ambiguous') return true;
return itemKind === CONSTANTS.ITEM_TYPE.FOLDER
? hasLossyTextField(item, 'name') || hasInvalidNoteCollection(item)
: hasInvalidNoteRecord(item);
});
const hasUnrecoverableDataStructure = (
!Array.isArray(data.folders)
|| hasInvalidOptionalArray('trash')
|| hasInvalidOptionalArray('favorites')
|| hasInvalidFolderRecords
|| hasInvalidTrashRecords
);
if (hasUnrecoverableDataStructure) {
console.warn('[Data Sanitization] A malformed data container or record was detected. Automatic persistence was blocked to preserve the original appState.');
return createInvalidStructureResult();
}
const unsafePrototypeKeysRemoved = sanitizeObjectForPrototypePollution(data);
if (unsafePrototypeKeysRemoved) {
console.warn('[Data Sanitization] Unsafe prototype-pollution keys were removed from appState.');
}
const folderIdUpdateMap = new Map();
const noteIdUpdateMap = new Map();
const seenOriginalFolderIds = new Set();
const seenOriginalNoteIds = new Set();
const usedIds = new Set(RESERVED_ITEM_IDS);
let changesMade = false;
let notifyChangesMade = false;
const markChanged = (shouldNotify = true) => {
changesMade = true;
if (shouldNotify) notifyChangesMade = true;
};
const markMinorChanged = () => markChanged(false);
const assignNormalizedValue = (target, key, value) => {
if (!Object.is(target[key], value)) markMinorChanged();
target[key] = value;
return value;
};
if (unsafePrototypeKeysRemoved) markChanged();
const ensureArray = (value) => {
if (Array.isArray(value)) return value;
// 누락된 필드도 메모리에만 기본값을 만들고 끝내면 다음 트랜잭션이 원본 손상 값을
// 다시 읽습니다. 알림은 생략하되 정제본은 반드시 저장 대상으로 표시합니다.
markChanged(value !== undefined);
return [];
};
const ensureObject = (value) => {
if (value && typeof value === 'object' && !Array.isArray(value)) return value;
markMinorChanged();
return {};
};
const normalizeText = (value, fallback) => {
const text = String(value ?? fallback ?? '').trim();
return text;
};
const normalizeTimestamp = (value, fallback = now, shouldNotify = true) => {
const timestamp = toValidTimestamp(value);
if (timestamp !== null) return timestamp;
markChanged(shouldNotify);
return fallback;
};
const normalizeId = (item, prefix, itemType) => {
const oldId = item.id === undefined || item.id === null ? '' : String(item.id);
const isFolder = itemType === CONSTANTS.ITEM_TYPE.FOLDER;
const seenIds = isFolder ? seenOriginalFolderIds : seenOriginalNoteIds;
const updateMap = isFolder ? folderIdUpdateMap : noteIdUpdateMap;
const wasSeenInSameType = Boolean(oldId && seenIds.has(oldId));
const hasUnsafeFormat = !isValidItemIdForType(oldId, prefix);
const collidesGlobally = Boolean(oldId && usedIds.has(oldId));
let finalId = oldId;
if (hasUnsafeFormat || collidesGlobally) {
finalId = generateUniqueId(prefix, usedIds);
item.id = finalId;
// 다른 유형과 충돌한 첫 항목은 유형별 참조 맵으로 정확히 추적합니다.
// 같은 유형 안의 중복은 어느 항목을 뜻하는지 모호하므로 첫 항목을 기준으로 유지합니다.
if (oldId && !wasSeenInSameType && !updateMap.has(oldId)) {
updateMap.set(oldId, finalId);
}
markChanged();
console.warn(`[Data Sanitization] Unsafe, reserved, or duplicate ID fixed on load: ${oldId || '(empty)'} -> ${finalId}`);
} else if (item.id !== finalId) {
// 숫자형 등 문자열이 아닌 ID는 실제 데이터에도 문자열로 기록해 strict 비교 실패를 막습니다.
item.id = finalId;
markMinorChanged();
}
if (oldId) seenIds.add(oldId);
usedIds.add(finalId);
return finalId;
};
data.folders = ensureArray(data.folders);
data.trash = ensureArray(data.trash);
data.favorites = ensureArray(data.favorites);
data.lastActiveNotePerFolder = ensureObject(data.lastActiveNotePerFolder);
const normalizeNote = (rawNote, isTrash = false) => {
if (!rawNote || typeof rawNote !== 'object' || Array.isArray(rawNote)) {
markChanged();
return null;
}
const note = rawNote;
normalizeId(note, CONSTANTS.ID_PREFIX.NOTE, CONSTANTS.ITEM_TYPE.NOTE);
assignNormalizedValue(note, 'title', normalizeText(note.title, '제목 없음') || '제목 없음');
assignNormalizedValue(note, 'content', String(note.content ?? ''));
assignNormalizedValue(note, 'createdAt', normalizeTimestamp(note.createdAt));
assignNormalizedValue(note, 'updatedAt', normalizeTimestamp(note.updatedAt, note.createdAt));
assignNormalizedValue(note, 'isPinned', Boolean(note.isPinned));
if (isTrash) {
assignNormalizedValue(note, 'type', CONSTANTS.ITEM_TYPE.NOTE);
assignNormalizedValue(note, 'deletedAt', normalizeTimestamp(note.deletedAt, now, false));
if (note.originalFolderId !== undefined && note.originalFolderId !== null) {
assignNormalizedValue(note, 'originalFolderId', String(note.originalFolderId));
}
if ('wasFavorite' in note) assignNormalizedValue(note, 'wasFavorite', Boolean(note.wasFavorite));
} else if (note.type !== undefined) {
delete note.type;
markChanged(false);
}
return note;
};
const normalizeFolder = (rawFolder, isTrash = false) => {
if (!rawFolder || typeof rawFolder !== 'object' || Array.isArray(rawFolder)) {
markChanged();
return null;
}
const folder = rawFolder;
normalizeId(folder, CONSTANTS.ID_PREFIX.FOLDER, CONSTANTS.ITEM_TYPE.FOLDER);
assignNormalizedValue(folder, 'name', normalizeFolderName(folder.name));
assignNormalizedValue(folder, 'createdAt', normalizeTimestamp(folder.createdAt));
assignNormalizedValue(folder, 'updatedAt', normalizeTimestamp(folder.updatedAt, folder.createdAt));
const rawNotes = ensureArray(folder.notes);
folder.notes = rawNotes
.map(note => normalizeNote(note, isTrash))
.filter(Boolean);
if (isTrash) {
assignNormalizedValue(folder, 'type', CONSTANTS.ITEM_TYPE.FOLDER);
assignNormalizedValue(folder, 'deletedAt', normalizeTimestamp(folder.deletedAt, now, false));
} else if (folder.type !== undefined) {
delete folder.type;
markChanged(false);
}
return folder;
};
data.folders = data.folders
.map(folder => normalizeFolder(folder, false))
.filter(Boolean);
const usedActiveFolderNameKeys = new Set();
data.folders.forEach(folder => {
const uniqueName = getUniqueFolderName(folder.name, usedActiveFolderNameKeys);
if (folder.name !== uniqueName) {
console.warn(`[Data Sanitization] Duplicate folder name fixed on load: ${folder.name} -> ${uniqueName}`);
folder.name = uniqueName;
folder.updatedAt = Math.max(Number(folder.updatedAt) || now, now);
markChanged();
}
});
data.trash = data.trash
.map(item => {
if (!item || typeof item !== 'object' || Array.isArray(item)) {
markChanged();
return null;
}
const itemKind = getTrashItemKind(item);
return itemKind === CONSTANTS.ITEM_TYPE.FOLDER
? normalizeFolder(item, true)
: normalizeNote(item, true);
})
.filter(Boolean);
const activeNoteIds = new Set();
data.folders.forEach(folder => folder.notes.forEach(note => activeNoteIds.add(String(note.id))));
// 즐겨찾기는 노트 ID 맵만 적용해야 폴더/노트 간 손상 ID 충돌에서도 잘못된 유형으로 이동하지 않습니다.
const originalFavorites = data.favorites;
const normalizedFavorites = Array.from(new Set(originalFavorites
.map(id => {
const normalizedId = String(id);
return noteIdUpdateMap.get(normalizedId) || normalizedId;
})
.filter(id => activeNoteIds.has(id))));
if (normalizedFavorites.length !== originalFavorites.length
|| normalizedFavorites.some((id, index) => !Object.is(id, originalFavorites[index]))) {
markMinorChanged();
}
data.favorites = normalizedFavorites;
data.trash.forEach(item => {
const applyOriginalFolderFix = (note) => {
if (note?.originalFolderId !== undefined && note.originalFolderId !== null) {
const normalizedId = String(note.originalFolderId);
assignNormalizedValue(note, 'originalFolderId', folderIdUpdateMap.get(normalizedId) || normalizedId);
}
};
if (item?.type === CONSTANTS.ITEM_TYPE.FOLDER) item.notes.forEach(applyOriginalFolderFix);
else applyOriginalFolderFix(item);
});
const typedIdMaps = { folderIdUpdateMap, noteIdUpdateMap };
// 실제 폴더뿐 아니라 가상 폴더 세션도 정상 참조로 인정합니다.
data.lastActiveNotePerFolder = sanitizeLastActiveNoteMap(
data.lastActiveNotePerFolder,
data,
typedIdMaps,
markMinorChanged
);
if (data.activeFolderId !== undefined && data.activeFolderId !== null) {
assignNormalizedValue(data, 'activeFolderId', getFolderIdAfterSanitization(data.activeFolderId, folderIdUpdateMap));
}
if (data.activeNoteId !== undefined && data.activeNoteId !== null) {
const normalizedId = String(data.activeNoteId);
assignNormalizedValue(data, 'activeNoteId', noteIdUpdateMap.get(normalizedId) || normalizedId);
}
assignNormalizedValue(data, 'lastSavedTimestamp', normalizeTimestamp(data.lastSavedTimestamp, now, false));
// 기존 단일 맵 소비자를 위한 호환 맵입니다. 두 유형에서 동시에 쓰인 원본 ID는 모호하므로 제외합니다.
const idUpdateMap = new Map();
folderIdUpdateMap.forEach((newId, oldId) => {
if (!seenOriginalNoteIds.has(oldId)) idUpdateMap.set(oldId, newId);
});
noteIdUpdateMap.forEach((newId, oldId) => {
if (!seenOriginalFolderIds.has(oldId)) idUpdateMap.set(oldId, newId);
});
return {
sanitizedData: data,
wasSanitized: changesMade,
shouldNotify: notifyChangesMade,
isTopLevelInvalid: false,
idUpdateMap,
folderIdUpdateMap,
noteIdUpdateMap
};
};
// [아키텍처 리팩토링] loadData에서 localStorage 기반 비상 백업 복구 로직을 완전히 제거하고,
// chrome.storage.local을 유일한 데이터 소스로 사용하도록 단순화합니다.
export const loadData = async () => {
let recoveryMessage = null;
let authoritativeData = null; // [버그 수정] 데이터 로딩 순서 제어를 위해 변수 위치 변경
// 손상 ID 복구 시 폴더와 노트 참조를 서로 다른 맵으로 추적합니다.
let folderIdUpdateMap = new Map();
let noteIdUpdateMap = new Map();
try {
// 미완료 가져오기 복구는 같은 appState 저장 경계 안에서 판정·복원·정리합니다.
// 목적은 초기화/복구 경로의 데이터 무결성을 지키는 것입니다.
const importRecoveryMessage = await withAppStateWriteLock(async () => {
const importStatus = localStorage.getItem(CONSTANTS.LS_KEY_IMPORT_IN_PROGRESS);
const backupResult = await storageGet('appState_backup');
const backupPayload = backupResult.appState_backup;
if (importStatus === 'done') {
if (backupPayload) {
// [CRITICAL BUG FIX] 완료 플래그는 저장 순서만 나타낼 뿐, 실제 appState의
// 무결성을 보장하지 않습니다. 가져온 데이터를 검증하기 전에 롤백 백업을
// 삭제하면 누락·손상된 결과만 남아 이전 노트를 복구할 수 없습니다.
const importedResult = await storageGet('appState');
const hasImportedAppState = Object.prototype.hasOwnProperty.call(importedResult, 'appState')
&& importedResult.appState !== null
&& importedResult.appState !== undefined;
const verification = hasImportedAppState
? verifyAndSanitizeLoadedData(JSON.parse(JSON.stringify(importedResult.appState)))
: null;
if (!verification || verification.isTopLevelInvalid) {
console.warn('Completed import data failed integrity validation. Rolling back to the previous data.');
await restoreImportBackupPayload(backupPayload);
await storageRemove('appState_backup');
localStorage.removeItem(CONSTANTS.LS_KEY_IMPORT_IN_PROGRESS);
return '가져온 데이터의 무결성 검사에 실패하여, 가져오기 이전 데이터로 안전하게 복구했습니다.';
}
// 복구 가능한 ID·메타데이터 문제는 백업을 버리기 전에 영구 저장합니다.
// 이 저장이 실패하면 예외가 전파되어 백업과 완료 플래그가 다음 재시도용으로 남습니다.
if (verification.wasSanitized) {
await storageSet({ appState: verification.sanitizedData });
}
await storageRemove('appState_backup');
}
// 성공 후 백업만 먼저 지워진 경우에도 완료 플래그가 영구히 남지 않게 정리합니다.
localStorage.removeItem(CONSTANTS.LS_KEY_IMPORT_IN_PROGRESS);
return backupPayload ? CONSTANTS.MESSAGES.SUCCESS.IMPORT_SUCCESS : null;
}
if (importStatus === 'true' && backupPayload) {
console.warn('Incomplete import detected. Rolling back to previous data.');
// 롤백은 가져오기 직전 스냅샷을 그대로 복원해야 합니다. 복원 과정에서
// 정제된 빈 상태로 바꾸면 손상 원본을 유일한 복구 사본까지 잃을 수 있습니다.
await restoreImportBackupPayload(backupPayload);
await storageRemove('appState_backup');
localStorage.removeItem(CONSTANTS.LS_KEY_IMPORT_IN_PROGRESS);
return '데이터 가져오기 작업이 비정상적으로 종료되어, 이전 데이터로 안전하게 복구했습니다.';
}
if (importStatus === 'true' && !backupPayload) {
console.warn("Inconsistent import state detected: flag is 'true' but no backup exists.");
localStorage.removeItem(CONSTANTS.LS_KEY_IMPORT_IN_PROGRESS);
return '이전 데이터 가져오기 작업이 비정상적으로 중단되었습니다. 작업을 다시 시도해주세요.';
}
return null;
});
if (importRecoveryMessage) recoveryMessage = importRecoveryMessage;
// 2. 주 저장소를 단일 활성 문서의 저장 경계 안에서 읽고, 무결성 보정이 필요하면 같은 경계 안에서 저장합니다.
// 현재 문서 컨텍스트 안의 연속 작업 간 read-modify-write 안정성을 위한 처리입니다.
const loadedResult = await withAppStateWriteLock(async () => {
const mainStorageResult = await storageGet('appState');
const hasStoredAppState = Object.prototype.hasOwnProperty.call(mainStorageResult, 'appState')
&& mainStorageResult.appState !== null
&& mainStorageResult.appState !== undefined;
let loadedData = hasStoredAppState ? mainStorageResult.appState : null;
let loadedFolderIdUpdateMap = new Map();
let loadedNoteIdUpdateMap = new Map();
let shouldShowRecoveryNotice = false;
if (hasStoredAppState) {
const verification = verifyAndSanitizeLoadedData(JSON.parse(JSON.stringify(loadedData)));
if (verification.isTopLevelInvalid) {
throw createUnrecoverableAppStateError('저장된 노트 데이터의 최상위 구조가 손상되었습니다. 원본을 보존하기 위해 자동 초기화를 중단했습니다.');
}
loadedData = verification.sanitizedData;
loadedFolderIdUpdateMap = verification.folderIdUpdateMap;
loadedNoteIdUpdateMap = verification.noteIdUpdateMap;
shouldShowRecoveryNotice = verification.shouldNotify;
if (verification.wasSanitized) {
await storageSet({ appState: loadedData });
console.log('Sanitized data has been saved back to storage.');
}
}
return {
loadedData,
loadedFolderIdUpdateMap,
loadedNoteIdUpdateMap,
shouldShowRecoveryNotice
};
});
authoritativeData = loadedResult.loadedData;
folderIdUpdateMap = loadedResult.loadedFolderIdUpdateMap;
noteIdUpdateMap = loadedResult.loadedNoteIdUpdateMap;
if (loadedResult.shouldShowRecoveryNotice) {
const sanitizationMessage = '데이터 무결성 검사 중 문제를 발견하여 자동 복구했습니다. 앱이 정상적으로 동작합니다.';
recoveryMessage = recoveryMessage ? `${recoveryMessage}\n${sanitizationMessage}` : sanitizationMessage;
}
// --- BUG-C-02 FIX START ---
// 비정상 종료 데이터 복구 로직 (안전한 '변경사항' 기반 복구)
const emergencyBackupJSON = localStorage.getItem(CONSTANTS.LS_KEY_EMERGENCY_CHANGES_BACKUP);
if (emergencyBackupJSON) {
let emergencyBackupValidated = false;
let emergencyBackupRemoved = false;
const removeEmergencyBackup = () => {
localStorage.removeItem(CONSTANTS.LS_KEY_EMERGENCY_CHANGES_BACKUP);
emergencyBackupRemoved = true;
};
try {
const backupChanges = parseEmergencyBackupChanges(emergencyBackupJSON);
emergencyBackupValidated = true;
// --- [버그 수정 시작] ---
// 비상 복구를 실행하기 전에, 데이터 정제 과정에서 변경된 ID가 있다면 비상 백업 데이터의 ID를 먼저 업데이트합니다.
// 이렇게 하지 않으면, ID가 변경된 노트를 찾지 못해 복구가 실패할 수 있습니다.
if (folderIdUpdateMap.size > 0 || noteIdUpdateMap.size > 0) {
console.log("Applying typed ID updates from sanitization to emergency backup data before restoration.");
if (backupChanges.noteUpdate?.noteId) {
const oldNoteId = String(backupChanges.noteUpdate.noteId);
backupChanges.noteUpdate.noteId = noteIdUpdateMap.get(oldNoteId) || oldNoteId;
if (oldNoteId !== backupChanges.noteUpdate.noteId) {
console.warn(`Emergency backup noteId was updated due to sanitization: ${oldNoteId} -> ${backupChanges.noteUpdate.noteId}`);
}
}
if (backupChanges.itemRename?.id) {
const oldItemId = String(backupChanges.itemRename.id);
const renameMap = backupChanges.itemRename.type === CONSTANTS.ITEM_TYPE.FOLDER
? folderIdUpdateMap
: noteIdUpdateMap;
backupChanges.itemRename.id = renameMap.get(oldItemId) || oldItemId;
if (oldItemId !== backupChanges.itemRename.id) {
console.warn(`Emergency backup rename itemId was updated due to sanitization: ${oldItemId} -> ${backupChanges.itemRename.id}`);
}
}
}
// --- [버그 수정 끝] ---
const findNoteForEmergencyRecovery = (noteId, data) => {
const normalizedNoteId = String(noteId ?? '');
if (!normalizedNoteId || !data) return null;
const activeFolders = Array.isArray(data.folders) ? data.folders : [];
for (const folder of activeFolders) {
const note = (Array.isArray(folder.notes) ? folder.notes : [])
.find(item => String(item?.id ?? '') === normalizedNoteId);
if (note) return note;
}
const trashItems = Array.isArray(data.trash) ? data.trash : [];
for (const item of trashItems) {
if (String(item?.id ?? '') === normalizedNoteId && (!Array.isArray(item?.notes) || item.type === CONSTANTS.ITEM_TYPE.NOTE)) {
return item;
}
const nestedNote = Array.isArray(item?.notes)
? item.notes.find(note => String(note?.id ?? '') === normalizedNoteId)
: null;
if (nestedNote) return nestedNote;
}
return null;
};
const findItemForEmergencyRecovery = (id, type, data) => {
const normalizedId = String(id ?? '');
if (!normalizedId || !data) return null;
if (type === CONSTANTS.ITEM_TYPE.FOLDER) {
const activeFolders = Array.isArray(data.folders) ? data.folders : [];
const trashItems = Array.isArray(data.trash) ? data.trash : [];
return activeFolders.find(folder => String(folder?.id ?? '') === normalizedId)
|| trashItems.find(item =>
String(item?.id ?? '') === normalizedId
&& (item.type === CONSTANTS.ITEM_TYPE.FOLDER || Array.isArray(item?.notes))
)
|| null;
}
return findNoteForEmergencyRecovery(normalizedId, data);
};
if (backupChanges.noteUpdate) {
const recoveryTarget = findNoteForEmergencyRecovery(backupChanges.noteUpdate.noteId, authoritativeData);
if (!recoveryTarget) {
console.warn('Emergency backup note target no longer exists. Dropping stale note recovery entry.');
delete backupChanges.noteUpdate;
} else if (shouldDiscardEmergencyNoteUpdate(backupChanges.noteUpdate, recoveryTarget)) {
console.warn('Emergency backup note entry is already saved or older than the committed note. Dropping stale recovery entry.');
delete backupChanges.noteUpdate;
}
}
if (backupChanges.itemRename) {
const recoveryTarget = findItemForEmergencyRecovery(
backupChanges.itemRename.id,
backupChanges.itemRename.type,
authoritativeData
);
if (!recoveryTarget) {
console.warn('Emergency backup rename target no longer exists. Dropping stale rename recovery entry.');
delete backupChanges.itemRename;
} else if (shouldDiscardEmergencyItemRename(backupChanges.itemRename, recoveryTarget)) {
console.warn('Emergency backup rename entry is already saved or older than the committed item. Dropping stale recovery entry.');
delete backupChanges.itemRename;
}
}
if (!backupChanges.noteUpdate && !backupChanges.itemRename) {
removeEmergencyBackup();
console.warn('Emergency backup had no applicable changes and was removed to prevent repeated recovery prompts.');
} else {
let confirmMessage = "탭이 비정상적으로 종료되기 전, 저장되지 않은 변경사항이 발견되었습니다.<br><br>";
if(backupChanges.noteUpdate) {
const safeTitle = escapeHtml(String(backupChanges.noteUpdate.title ?? '').slice(0, 20));
confirmMessage += `<strong>📝 노트 수정:</strong> '${safeTitle}...'<br>`;
}
if(backupChanges.itemRename) {
const itemTypeStr = backupChanges.itemRename.type === 'folder' ? '📁 폴더' : '📝 노트';
const safeNewName = escapeHtml(String(backupChanges.itemRename.newName ?? '').slice(0, 20));
confirmMessage += `<strong>✏️ 이름 변경:</strong> ${itemTypeStr} → '${safeNewName}...'<br>`;
}
confirmMessage += "<br>이 변경사항을 복원하시겠습니까?";
const userConfirmed = await showConfirm({
title: '📝 저장되지 않은 변경사항 복원',
message: confirmMessage,
isHtml: true,
confirmText: '✅ 예, 복원합니다',
cancelText: '❌ 아니요, 버립니다'
});
if (userConfirmed) {
// --- [CRITICAL BUG FIX] START ---
// 트랜잭션 실행 전, 이름 변경 충돌을 미리 확인하고 사용자에게 해결을 요청합니다.
if (backupChanges.itemRename) {
const { id, type, newName } = backupChanges.itemRename;
const foldersToCheck = authoritativeData?.folders || [];
const isConflict = foldersToCheck.some(f =>
(type === 'folder' && f.id !== id && f.name.toLowerCase() === newName.toLowerCase())
);
if (isConflict) {
const resolvedName = await showPrompt({
title: '✏️ 이름 충돌 해결',
message: CONSTANTS.MESSAGES.ERROR.RENAME_CONFLICT_ON_RECOVERY(newName),
initialValue: `${newName} (복사본)`,
validationFn: (value) => {
const trimmedValue = value.trim();
if (!trimmedValue) return { isValid: false, message: CONSTANTS.MESSAGES.ERROR.EMPTY_NAME_ERROR };
if (foldersToCheck.some(f => f.name.toLowerCase() === trimmedValue.toLowerCase())) {
return { isValid: false, message: CONSTANTS.MESSAGES.ERROR.FOLDER_EXISTS(trimmedValue) };
}
return { isValid: true };
}
});
if (resolvedName) {
// 사용자가 새 이름을 입력하면 백업 객체를 수정하여 복원을 계속합니다.
backupChanges.itemRename.newName = resolvedName.trim();
} else {
// 사용자가 취소하면 이름 변경 복원만 제외하고 나머지는 계속 진행합니다.
showToast(CONSTANTS.MESSAGES.ERROR.RENAME_RECOVERY_CANCELED, CONSTANTS.TOAST_TYPE.ERROR);
delete backupChanges.itemRename;
}
}
}
// --- [CRITICAL BUG FIX] END ---
if (!backupChanges.noteUpdate && !backupChanges.itemRename) {
removeEmergencyBackup();
showToast('복원할 수 있는 변경사항이 없어 비상 백업을 정리했습니다.', CONSTANTS.TOAST_TYPE.SUCCESS);
} else {
const { performTransactionalUpdate } = await import('./itemActions.js');
const transactionResult = await performTransactionalUpdate(latestData => {
const now = Date.now();
let changesApplied = false;
// 1. 노트 내용 업데이트 복원
// [CRITICAL BUG FIX] 비상 복구 대상 검증은 활성 폴더와 휴지통을 모두 인정하지만,
// 실제 적용은 활성 폴더만 검색하고 있어 휴지통으로 이동된 노트의 미저장 내용이 사라질 수 있었습니다.
// 활성 폴더, 휴지통 최상위 노트, 휴지통 폴더 내부 노트까지 동일하게 복구합니다.
if (backupChanges.noteUpdate) {
const { noteId, title, content } = backupChanges.noteUpdate;
const normalizedNoteId = String(noteId ?? '');
const applyRecoveredNoteUpdate = (note, parentFolder = null) => {
if (!note || String(note.id ?? '') !== normalizedNoteId) return false;
note.title = String(title ?? '');
note.content = String(content ?? '');
note.updatedAt = now;
if (parentFolder) parentFolder.updatedAt = now;
return true;
};
for (const folder of latestData.folders) {
const noteToUpdate = (Array.isArray(folder.notes) ? folder.notes : []).find(n => String(n?.id ?? '') === normalizedNoteId);
if (applyRecoveredNoteUpdate(noteToUpdate, folder)) {
changesApplied = true;
break;
}
}
if (!changesApplied) {
for (const trashItem of latestData.trash) {
const isTopLevelTrashNote = String(trashItem?.id ?? '') === normalizedNoteId
&& (!Array.isArray(trashItem?.notes) || trashItem.type === CONSTANTS.ITEM_TYPE.NOTE);
if (isTopLevelTrashNote && applyRecoveredNoteUpdate(trashItem)) {
changesApplied = true;
break;
}
if (Array.isArray(trashItem?.notes)) {
const noteInTrashFolder = trashItem.notes.find(n => String(n?.id ?? '') === normalizedNoteId);
if (applyRecoveredNoteUpdate(noteInTrashFolder, trashItem)) {
changesApplied = true;
break;
}
}
}
}
}
// [CRITICAL BUG FIX & COMMENT FIX] 2. 이름 변경 복원 (활성 폴더 및 휴지통 모두 검색)
if (backupChanges.itemRename) {
const { id, type, newName } = backupChanges.itemRename;
let itemToRename = null;
let parentFolder = null;
if (type === CONSTANTS.ITEM_TYPE.FOLDER) {
// 활성 폴더 또는 휴지통에서 폴더 찾기
itemToRename = latestData.folders.find(f => f.id === id) || latestData.trash.find(item => item.id === id && item.type === 'folder');
if (itemToRename) {
itemToRename.name = newName;
itemToRename.updatedAt = now;
changesApplied = true;
}
} else if (type === CONSTANTS.ITEM_TYPE.NOTE) {
// 활성 폴더들의 노트에서 먼저 검색
for (const folder of latestData.folders) {
const note = folder.notes.find(n => n.id === id);
if (note) { itemToRename = note; parentFolder = folder; break; }
}
// 활성 폴더에 없으면 휴지통에서 검색 (휴지통의 최상위 또는 폴더 내부 노트)
if (!itemToRename) {
for (const trashItem of latestData.trash) {
if (trashItem.id === id && (trashItem.type === 'note' || !trashItem.type)) {
itemToRename = trashItem;
break;
}
if (trashItem.type === 'folder' && Array.isArray(trashItem.notes)) {
const noteInTrashFolder = trashItem.notes.find(n => n.id === id);
if (noteInTrashFolder) {
itemToRename = noteInTrashFolder;
break;
}
}
}
}
if (itemToRename) {
itemToRename.title = newName;