-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbackground.js
More file actions
2613 lines (2244 loc) · 84.9 KB
/
Copy pathbackground.js
File metadata and controls
2613 lines (2244 loc) · 84.9 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
const extensionApi = globalThis.browser ?? chrome;
const ROOT_FOLDER_TITLE = "Browsing Library";
const BOOKMARK_METADATA_KEY = "bookmarkMetadata";
const SAVED_SESSIONS_KEY = "savedSessions";
const AI_ENRICHMENT_QUEUE_KEY = "aiEnrichmentQueue";
const AI_ENRICHMENT_CONTROL_KEY = "aiEnrichmentControl";
const SYNC_KEY_PREFIX = "sync:session:";
const SYNC_INDEX_KEY = "sync:index";
const DEVICE_ID_KEY = "deviceId";
const SETTINGS_KEY = "tabLedgerSettings";
const ARCHIVE_AI_EDITABLE_FIELDS = ["category", "tags", "description", "summary"];
const VALID_FIELD_SOURCES = new Set(["heuristic", "ai", "user"]);
const DEFAULT_SETTINGS = {
dedupeWithinSession: false,
dedupeAcrossSessions: false
};
const AI_ENRICHMENT_REQUEST_TIMEOUT_MS = 45000;
let aiEnrichmentDrainPromise = null;
let aiEnrichmentCurrentController = null;
let aiEnrichmentCurrentSessionId = null;
let aiEnrichmentInterruptReason = null;
// Resume any AI enrichment that was interrupted by browser restart
extensionApi.runtime.onStartup.addListener(() => {
drainAiEnrichmentQueue();
});
extensionApi.runtime.onInstalled.addListener(() => {
drainAiEnrichmentQueue();
});
extensionApi.runtime.onMessage.addListener((message, _sender, sendResponse) => {
if (message?.type === "open-dashboard") {
openDashboard(normalizeDashboardIntent(message.payload ?? message.scope))
.then(() => sendResponse({ ok: true }))
.catch((error) => {
console.error("Failed to open dashboard", error);
sendResponse({
ok: false,
error: error instanceof Error ? error.message : "Unknown error"
});
});
return true;
}
if (message?.type === "create-bookmark-archive") {
createBookmarkArchive(message.payload)
.then((result) => sendResponse({ ok: true, result }))
.catch((error) => {
console.error("Failed to create Browsing Library entry", error);
sendResponse({
ok: false,
error: error instanceof Error ? error.message : "Unknown error"
});
});
return true;
}
if (message?.type === "open-archive-urls") {
openArchiveUrls(message.payload)
.then((result) => sendResponse({ ok: true, result }))
.catch((error) => {
console.error("Failed to reopen Browsing Library URLs", error);
sendResponse({
ok: false,
error: error instanceof Error ? error.message : "Unknown error"
});
});
return true;
}
if (message?.type === "delete-archive-session") {
deleteArchiveSession(message.payload)
.then((result) => sendResponse({ ok: true, result }))
.catch((error) => {
console.error("Failed to delete Browsing Library session", error);
sendResponse({
ok: false,
error: error instanceof Error ? error.message : "Unknown error"
});
});
return true;
}
if (message?.type === "delete-archive-item") {
deleteArchiveItem(message.payload)
.then((result) => sendResponse({ ok: true, result }))
.catch((error) => {
console.error("Failed to delete Browsing Library item", error);
sendResponse({
ok: false,
error: error instanceof Error ? error.message : "Unknown error"
});
});
return true;
}
if (message?.type === "update-archive-item") {
updateArchiveItem(message.payload)
.then((result) => sendResponse({ ok: true, result }))
.catch((error) => {
console.error("Failed to update Browsing Library item", error);
sendResponse({
ok: false,
error: error instanceof Error ? error.message : "Unknown error"
});
});
return true;
}
if (message?.type === "update-archive-category") {
updateArchiveCategory(message.payload)
.then((result) => sendResponse({ ok: true, result }))
.catch((error) => {
console.error("Failed to update Browsing Library category", error);
sendResponse({
ok: false,
error: error instanceof Error ? error.message : "Unknown error"
});
});
return true;
}
if (message?.type === "get-bookmark-folders") {
getBookmarkFolders()
.then((folders) => sendResponse({ ok: true, folders }))
.catch((error) => {
console.error("Failed to get bookmark folders", error);
sendResponse({ ok: false, error: error.message });
});
return true;
}
if (message?.type === "import-bookmarks") {
importBookmarksAsSession(message.payload)
.then((result) => sendResponse({ ok: true, result }))
.catch((error) => {
console.error("Failed to import bookmarks", error);
sendResponse({ ok: false, error: error.message });
});
return true;
}
if (message?.type === "retry-ai-enrichment") {
retryAiEnrichment(message.payload?.sessionId)
.then((result) => sendResponse({ ok: true, result }))
.catch((error) => {
console.error("Failed to retry AI enrichment", error);
sendResponse({ ok: false, error: error.message });
});
return true;
}
if (message?.type === "resume-ai-enrichment-queue") {
resumeAiEnrichmentQueue()
.then((result) => sendResponse({ ok: true, result }))
.catch((error) => {
console.error("Failed to resume AI enrichment queue", error);
sendResponse({ ok: false, error: error.message });
});
return true;
}
if (message?.type === "pause-ai-enrichment-queue") {
pauseAiEnrichmentQueue()
.then((result) => sendResponse({ ok: true, result }))
.catch((error) => {
console.error("Failed to pause AI enrichment queue", error);
sendResponse({ ok: false, error: error.message });
});
return true;
}
if (message?.type === "stop-ai-enrichment-queue") {
stopAiEnrichmentQueue()
.then((result) => sendResponse({ ok: true, result }))
.catch((error) => {
console.error("Failed to stop AI enrichment queue", error);
sendResponse({ ok: false, error: error.message });
});
return true;
}
if (message?.type === "bulk-delete-archive-items") {
bulkDeleteArchiveItems(message.payload)
.then((result) => sendResponse({ ok: true, result }))
.catch((error) => {
console.error("Failed to bulk delete archive items", error);
sendResponse({ ok: false, error: error.message });
});
return true;
}
if (message?.type === "workspace-search-library") {
workspaceSearchLibrary(message.payload)
.then((result) => sendResponse({ ok: true, result }))
.catch((error) => {
console.error("Workspace search failed", error);
sendResponse({ ok: false, error: error.message });
});
return true;
}
if (message?.type === "workspace-generate-project") {
workspaceGenerateProject(message.payload)
.then((result) => sendResponse({ ok: true, result }))
.catch((error) => {
console.error("Workspace generate failed", error);
sendResponse({ ok: false, error: error.message });
});
return true;
}
if (message?.type === "sync-now") {
syncNow()
.then((result) => sendResponse({ ok: true, result }))
.catch((error) => {
console.error("Sync failed", error);
sendResponse({ ok: false, error: error.message });
});
return true;
}
return false;
});
function normalizeDashboardIntent(value) {
if (typeof value === "string") {
return {
capture: value
};
}
if (!value || typeof value !== "object") {
return {};
}
return {
capture: typeof value.capture === "string" ? value.capture : null,
view: typeof value.view === "string" ? value.view : null
};
}
async function openDashboard(intent = {}) {
const targetUrl = new URL(extensionApi.runtime.getURL("dashboard.html"));
if (intent.capture) {
targetUrl.searchParams.set("capture", intent.capture);
}
if (intent.view) {
targetUrl.searchParams.set("view", intent.view);
}
await extensionApi.tabs.create({ url: targetUrl.toString() });
}
async function createBookmarkArchive(payload) {
if (!extensionApi.bookmarks?.create) {
throw new Error(
"Native bookmark creation is not available in this browser. Use JSON export for now."
);
}
validatePayload(payload);
const archiveRoot = await ensureArchiveRoot();
const sessionTitle = buildSessionTitle(payload.sessionName);
const settings = await getStoredSettings();
const metadataStore = await getStoredObject(BOOKMARK_METADATA_KEY);
const savedSessions = await getStoredArray(SAVED_SESSIONS_KEY);
const dedupeResult = buildArchiveItemsForSave(payload.items, savedSessions, metadataStore, settings);
if (!dedupeResult.items.length) {
throw new Error("All tabs in this draft were skipped by your deduplication settings.");
}
const sessionFolder = await extensionApi.bookmarks.create({
parentId: archiveRoot.id,
title: sessionTitle
});
const groupedItems = groupByCategory(dedupeResult.items);
const createdBookmarkIds = [];
const archivedItems = [];
const archivedAt = new Date().toISOString();
for (const [categoryName, items] of groupedItems.entries()) {
const categoryFolder = await extensionApi.bookmarks.create({
parentId: sessionFolder.id,
title: categoryName
});
for (const item of items) {
const bookmarkNode = await extensionApi.bookmarks.create({
parentId: categoryFolder.id,
title: item.title,
url: item.url
});
metadataStore[bookmarkNode.id] = {
bookmarkId: bookmarkNode.id,
bookmarkFolderId: categoryFolder.id,
sessionFolderId: sessionFolder.id,
sessionTitle,
category: categoryName,
title: item.title,
linkUrl: item.url,
description: item.description,
summary: item.summary,
tags: item.tags,
fieldSources: normalizeArchiveFieldSources(item.fieldSources),
hostname: item.hostname,
capturedAt: item.capturedAt || new Date().toISOString(),
archivedAt
};
archivedItems.push({
bookmarkId: bookmarkNode.id,
bookmarkFolderId: categoryFolder.id,
sessionFolderId: sessionFolder.id,
title: item.title,
url: item.url,
hostname: item.hostname,
category: categoryName,
description: item.description,
summary: item.summary,
tags: item.tags,
fieldSources: normalizeArchiveFieldSources(item.fieldSources),
capturedAt: item.capturedAt || archivedAt,
archivedAt
});
createdBookmarkIds.push(bookmarkNode.id);
}
}
savedSessions.unshift({
id: sessionFolder.id,
title: sessionTitle,
createdAt: archivedAt,
tabCount: dedupeResult.items.length,
categoryCount: groupedItems.size,
bookmarkIds: createdBookmarkIds,
categories: [...groupedItems.keys()],
categoryMeta: [...groupedItems.keys()].map((name) => ({
name,
description: "",
tags: []
})),
items: archivedItems
});
await extensionApi.storage.local.set({
[BOOKMARK_METADATA_KEY]: metadataStore,
[SAVED_SESSIONS_KEY]: savedSessions
});
return {
sessionFolderId: sessionFolder.id,
sessionTitle,
tabCount: dedupeResult.items.length,
categoryCount: groupedItems.size,
duplicateCounts: dedupeResult.duplicateCounts
};
}
function validatePayload(payload) {
if (!payload || !Array.isArray(payload.items) || payload.items.length === 0) {
throw new Error("There are no tabs in the current draft to save to the Browsing Library.");
}
for (const item of payload.items) {
if (!item.title || !item.url) {
throw new Error("Every Browsing Library item needs a title and a URL.");
}
}
}
async function ensureArchiveRoot() {
const tree = await extensionApi.bookmarks.getTree();
const root = tree[0];
const destinationParent =
root.children?.find((node) => node.id === "2") ??
root.children?.find((node) => !node.url);
if (!destinationParent) {
throw new Error("Could not find a writable bookmark folder.");
}
const children = await extensionApi.bookmarks.getChildren(destinationParent.id);
const existing = children.find(
(node) => !node.url && node.title === ROOT_FOLDER_TITLE
);
if (existing) {
return existing;
}
return extensionApi.bookmarks.create({
parentId: destinationParent.id,
title: ROOT_FOLDER_TITLE
});
}
function buildSessionTitle(sessionName) {
const trimmed = String(sessionName || "").trim();
const timestamp = new Date().toLocaleString([], {
year: "numeric",
month: "short",
day: "numeric",
hour: "numeric",
minute: "2-digit"
});
return trimmed ? `${trimmed} · ${timestamp}` : `Browsing Library · ${timestamp}`;
}
function groupByCategory(items) {
const grouped = new Map();
for (const item of items) {
const categoryName = String(item.category || "Unsorted").trim() || "Unsorted";
if (!grouped.has(categoryName)) {
grouped.set(categoryName, []);
}
grouped.get(categoryName).push(item);
}
return new Map(
[...grouped.entries()].sort(([left], [right]) => left.localeCompare(right))
);
}
async function openArchiveUrls(payload) {
const urls = getUniqueUrls(payload?.urls);
if (!urls.length) {
throw new Error("There are no saved Browsing Library URLs to reopen.");
}
const [firstUrl, ...rest] = urls;
const createdWindow = await extensionApi.windows.create({ url: firstUrl });
for (const url of rest) {
await extensionApi.tabs.create({
windowId: createdWindow.id,
url
});
}
return {
openedCount: urls.length
};
}
async function deleteArchiveSession(payload) {
const sessionId = String(payload?.sessionId || "");
const sessionTitle = String(payload?.sessionTitle || "");
const savedSessions = await getStoredArray(SAVED_SESSIONS_KEY);
const metadataStore = await getStoredObject(BOOKMARK_METADATA_KEY);
const sessionIndex = savedSessions.findIndex(
(session) => String(session.id) === sessionId || session.title === sessionTitle
);
if (sessionIndex === -1) {
const removedMetadataCount = removeMetadataEntries(metadataStore, sessionId, sessionTitle);
await extensionApi.storage.local.set({
[BOOKMARK_METADATA_KEY]: metadataStore,
[SAVED_SESSIONS_KEY]: savedSessions
});
return {
removedMetadataCount
};
}
const [removedSession] = savedSessions.splice(sessionIndex, 1);
const bookmarkIds = Array.isArray(removedSession.bookmarkIds) ? removedSession.bookmarkIds : [];
removeMetadataEntriesByBookmarkIds(metadataStore, bookmarkIds);
removeMetadataEntries(metadataStore, String(removedSession.id), removedSession.title);
await removeBookmarkTree(String(removedSession.id));
await removeBookmarkNodes(bookmarkIds);
await extensionApi.storage.local.set({
[BOOKMARK_METADATA_KEY]: metadataStore,
[SAVED_SESSIONS_KEY]: savedSessions
});
return {
deletedSessionTitle: removedSession.title
};
}
async function deleteArchiveItem(payload) {
const sessionId = String(payload?.sessionId || "");
const bookmarkId = String(payload?.bookmarkId || "");
const itemTitle = String(payload?.title || "");
const itemUrl = String(payload?.url || "");
const savedSessions = await getStoredArray(SAVED_SESSIONS_KEY);
const metadataStore = await getStoredObject(BOOKMARK_METADATA_KEY);
const session = savedSessions.find((entry) => String(entry.id) === sessionId);
if (!session || !Array.isArray(session.items)) {
throw new Error("Could not find the Browsing Library session for this tab.");
}
const itemIndex = session.items.findIndex((item) =>
bookmarkId
? String(item.bookmarkId || "") === bookmarkId
: item.url === itemUrl && item.title === itemTitle
);
if (itemIndex === -1) {
throw new Error("Could not find the Browsing Library tab to delete.");
}
const [removedItem] = session.items.splice(itemIndex, 1);
if (removedItem.bookmarkId) {
delete metadataStore[removedItem.bookmarkId];
await removeBookmarkNode(String(removedItem.bookmarkId));
} else {
removeMatchingMetadataEntry(metadataStore, sessionId, itemUrl, itemTitle);
}
session.bookmarkIds = Array.isArray(session.bookmarkIds)
? session.bookmarkIds.filter((id) => String(id) !== String(removedItem.bookmarkId || ""))
: [];
session.tabCount = session.items.length;
session.categories = [...new Set(session.items.map((item) => item.category))].sort();
session.categoryCount = session.categories.length;
session.categoryMeta = ensureCategoryMeta(session).filter((entry) =>
session.categories.includes(entry.name)
);
if (removedItem.bookmarkFolderId) {
await removeBookmarkFolderIfEmpty(String(removedItem.bookmarkFolderId));
}
if (!session.items.length) {
const sessionIndex = savedSessions.findIndex((entry) => String(entry.id) === sessionId);
if (sessionIndex !== -1) {
savedSessions.splice(sessionIndex, 1);
}
await removeBookmarkTree(sessionId);
}
await extensionApi.storage.local.set({
[BOOKMARK_METADATA_KEY]: metadataStore,
[SAVED_SESSIONS_KEY]: savedSessions
});
return {
deletedTitle: removedItem.title,
remainingCount: session.items.length
};
}
async function bulkDeleteArchiveItems(payload) {
// payload.items: [{ sessionId, bookmarkId, title, url }]
const items = Array.isArray(payload?.items) ? payload.items : [];
const savedSessions = await getStoredArray(SAVED_SESSIONS_KEY);
const metadataStore = await getStoredObject(BOOKMARK_METADATA_KEY);
const bookmarkIdsToRemove = [];
const categoryFolderIds = new Set();
for (const { sessionId, bookmarkId, title, url } of items) {
const session = savedSessions.find((s) => String(s.id) === String(sessionId));
if (!session || !Array.isArray(session.items)) continue;
const itemIndex = session.items.findIndex((item) =>
bookmarkId
? String(item.bookmarkId || "") === String(bookmarkId)
: item.url === url && item.title === title
);
if (itemIndex === -1) continue;
const [removedItem] = session.items.splice(itemIndex, 1);
if (removedItem.bookmarkId) {
bookmarkIdsToRemove.push(String(removedItem.bookmarkId));
delete metadataStore[removedItem.bookmarkId];
session.bookmarkIds = (session.bookmarkIds || []).filter(
(id) => String(id) !== String(removedItem.bookmarkId)
);
if (removedItem.bookmarkFolderId) {
categoryFolderIds.add(String(removedItem.bookmarkFolderId));
}
}
session.tabCount = session.items.length;
session.categories = [...new Set(session.items.map((item) => item.category))].sort();
session.categoryCount = session.categories.length;
session.categoryMeta = ensureCategoryMeta(session).filter((entry) =>
session.categories.includes(entry.name)
);
}
// Remove individual bookmarks first
await removeBookmarkNodes(bookmarkIdsToRemove);
// Clean up category folders that became empty
for (const folderId of categoryFolderIds) {
await removeBookmarkFolderIfEmpty(folderId);
}
// Delete entire sessions that are now empty
const emptySessions = savedSessions.filter((s) => !s.items.length);
for (const emptySession of emptySessions) {
await removeBookmarkTree(String(emptySession.id));
removeMetadataEntries(metadataStore, String(emptySession.id), emptySession.title);
}
const updatedSessions = savedSessions.filter((s) => s.items.length > 0);
await extensionApi.storage.local.set({
[BOOKMARK_METADATA_KEY]: metadataStore,
[SAVED_SESSIONS_KEY]: updatedSessions
});
return { deletedTabCount: bookmarkIdsToRemove.length, deletedSessionCount: emptySessions.length };
}
async function updateArchiveItem(payload) {
const sessionId = String(payload?.sessionId || "");
const bookmarkId = String(payload?.bookmarkId || "");
const itemTitle = String(payload?.title || "");
const itemUrl = String(payload?.url || "");
const nextCategory = String(payload?.category || "").trim() || "Unsorted";
const description = String(payload?.description || "").trim();
const summary = String(payload?.summary || "").trim();
const tags = normalizeStringList(payload?.tags);
const savedSessions = await getStoredArray(SAVED_SESSIONS_KEY);
const metadataStore = await getStoredObject(BOOKMARK_METADATA_KEY);
const session = savedSessions.find((entry) => String(entry.id) === sessionId);
if (!session || !Array.isArray(session.items)) {
throw new Error("Could not find the Browsing Library session for this tab.");
}
const item = session.items.find((entry) =>
bookmarkId
? String(entry.bookmarkId || "") === bookmarkId
: entry.url === itemUrl && entry.title === itemTitle
);
if (!item) {
throw new Error("Could not find the Browsing Library tab to update.");
}
const previousFolderId = String(item.bookmarkFolderId || "");
const previousCategory = String(item.category || "");
let nextFolderId = previousFolderId || null;
const nextValues = {
category: nextCategory,
tags,
description,
summary
};
if (previousCategory !== nextCategory) {
try {
const folder = await ensureSessionCategoryFolder(sessionId, nextCategory);
nextFolderId = folder?.id || nextFolderId;
if (item.bookmarkId && nextFolderId && extensionApi.bookmarks?.move) {
await extensionApi.bookmarks.move(String(item.bookmarkId), {
parentId: String(nextFolderId)
});
}
} catch (_error) {
// Ignore bookmark tree issues and still persist archive storage changes.
}
}
const nextFieldSources = applyArchiveFieldSourceUpdates(
item.fieldSources,
item,
nextValues,
payload?.updateSource
);
item.category = nextValues.category;
item.tags = nextValues.tags;
item.description = nextValues.description;
item.summary = nextValues.summary;
item.bookmarkFolderId = nextFolderId;
item.fieldSources = nextFieldSources;
const metadataEntry = getArchiveMetadataEntry(metadataStore, sessionId, bookmarkId, itemUrl, itemTitle);
if (metadataEntry) {
metadataEntry.category = nextValues.category;
metadataEntry.tags = nextValues.tags;
metadataEntry.description = nextValues.description;
metadataEntry.summary = nextValues.summary;
metadataEntry.bookmarkFolderId = nextFolderId;
metadataEntry.fieldSources = nextFieldSources;
}
session.items = session.items
.slice()
.sort((left, right) => {
const categoryCompare = String(left.category || "").localeCompare(String(right.category || ""));
if (categoryCompare !== 0) {
return categoryCompare;
}
return String(left.title || "").localeCompare(String(right.title || ""));
});
session.tabCount = session.items.length;
session.categories = [...new Set(session.items.map((entry) => entry.category))].sort();
session.categoryCount = session.categories.length;
session.categoryMeta = ensureCategoryMeta(session).filter((entry) =>
session.categories.includes(entry.name)
);
if (previousFolderId && previousFolderId !== String(nextFolderId || "")) {
await removeBookmarkFolderIfEmpty(previousFolderId);
}
await extensionApi.storage.local.set({
[BOOKMARK_METADATA_KEY]: metadataStore,
[SAVED_SESSIONS_KEY]: savedSessions
});
return {
itemTitle: item.title,
categoryName: item.category,
fieldSources: nextFieldSources
};
}
async function updateArchiveCategory(payload) {
const sessionId = String(payload?.sessionId || "");
const previousName = String(payload?.previousName || "").trim();
const nextName = String(payload?.nextName || "").trim() || previousName;
const description = String(payload?.description || "").trim();
const tags = normalizeStringList(payload?.tags);
const savedSessions = await getStoredArray(SAVED_SESSIONS_KEY);
const metadataStore = await getStoredObject(BOOKMARK_METADATA_KEY);
const session = savedSessions.find((entry) => String(entry.id) === sessionId);
if (!session) {
throw new Error("Could not find the Browsing Library session for this category.");
}
session.categoryMeta = ensureCategoryMeta(session);
if (nextName !== previousName) {
for (const item of session.items || []) {
if (item.category === previousName) {
item.category = nextName;
}
}
for (const entry of Object.values(metadataStore)) {
if (
String(entry.sessionFolderId || "") === sessionId &&
String(entry.category || "") === previousName
) {
entry.category = nextName;
}
}
const folderIds = [...new Set(
(session.items || [])
.filter((item) => item.category === nextName)
.map((item) => item.bookmarkFolderId)
.filter(Boolean)
)];
await renameBookmarkFolders(folderIds, nextName);
}
const duplicateMeta = session.categoryMeta.find(
(entry) => entry.name === nextName && entry.name !== previousName
);
const mergedMeta = {
name: nextName,
description,
tags: duplicateMeta
? normalizeStringList([...(duplicateMeta.tags || []), ...tags])
: tags
};
session.categoryMeta = session.categoryMeta
.filter((entry) => entry.name !== previousName && entry.name !== nextName)
.concat(mergedMeta);
session.categories = [...new Set((session.items || []).map((item) => item.category))].sort();
session.categoryCount = session.categories.length;
session.categoryMeta = ensureCategoryMeta(session).filter((entry) =>
session.categories.includes(entry.name)
);
await extensionApi.storage.local.set({
[BOOKMARK_METADATA_KEY]: metadataStore,
[SAVED_SESSIONS_KEY]: savedSessions
});
return {
categoryName: nextName
};
}
const TRACKING_PARAMS = new Set([
"utm_source", "utm_medium", "utm_campaign", "utm_term", "utm_content",
"fbclid", "gclid", "_ga", "_gid",
"ref", // broad — may false-positive on GitHub branch URLs (ref=branchname)
"mc_cid", "mc_eid"
]);
function normalizeArchiveUrl(url) {
const raw = String(url || "").trim();
if (!raw) return "";
let parsed;
try {
parsed = new URL(raw);
} catch {
return raw.toLowerCase();
}
// Remove tracking query parameters
for (const key of [...parsed.searchParams.keys()]) {
if (TRACKING_PARAMS.has(key)) {
parsed.searchParams.delete(key);
}
}
// Sort remaining params so ?a=1&b=2 and ?b=2&a=1 produce the same key
parsed.searchParams.sort();
const host = parsed.hostname.toLowerCase().replace(/^www\./, "");
// Path casing is intentionally preserved — RFC 3986 treats paths as case-sensitive
// Strip trailing slash from path (root "/" becomes empty string)
const path = parsed.pathname === "/" ? "" : parsed.pathname.replace(/\/$/, "");
const query = parsed.search; // e.g. "?q=hello" or "" — fragment already absent
return `${host}${path}${query}`;
}
function getUniqueUrls(urls) {
if (!Array.isArray(urls)) {
return [];
}
const seen = new Set();
const uniqueUrls = [];
for (const url of urls) {
const raw = String(url || "").trim();
if (!raw) continue;
const key = normalizeArchiveUrl(raw);
if (seen.has(key)) continue;
seen.add(key);
uniqueUrls.push(raw); // push original, not normalized key
}
return uniqueUrls;
}
function scoreItemEnrichment(item) {
const sources = item?.fieldSources;
if (!sources || typeof sources !== "object") return 0;
let score = 0;
for (const field of ["category", "tags", "description", "summary"]) {
if (sources[field] === "user") score += 3;
else if (sources[field] === "ai") score += 2;
else if (sources[field] === "heuristic") score += 1;
}
return score;
}
function buildArchiveItemsForSave(items, savedSessions, metadataStore, settings) {
const duplicateCounts = {
withinSession: 0,
acrossSessions: 0
};
const existingLibraryUrls = settings.dedupeAcrossSessions
? buildExistingLibraryUrlSet(savedSessions, metadataStore)
: new Set();
// Step 1: Within-session dedup — group by normalized URL, keep highest-scored item.
// Output order matches first-occurrence position of each URL in the input.
let workingItems = items;
if (settings.dedupeWithinSession) {
const bestByUrl = new Map(); // normalizedUrl → best item so far
for (const item of items) {
const normalizedUrl = normalizeArchiveUrl(item.url);
if (!normalizedUrl) continue;
const current = bestByUrl.get(normalizedUrl);
if (!current || scoreItemEnrichment(item) > scoreItemEnrichment(current)) {
bestByUrl.set(normalizedUrl, item);
}
}
// Reconstruct in first-occurrence order
const seenUrls = new Set();
const deduped = [];
for (const item of items) {
const normalizedUrl = normalizeArchiveUrl(item.url);
if (!normalizedUrl) continue;
if (seenUrls.has(normalizedUrl)) continue;
seenUrls.add(normalizedUrl);
deduped.push(bestByUrl.get(normalizedUrl)); // push the best item for this URL
}
const totalWithUrls = items.filter((i) => normalizeArchiveUrl(i.url)).length;
duplicateCounts.withinSession = totalWithUrls - deduped.length;
workingItems = deduped;
}
// Step 2: Across-sessions dedup — skip URLs already saved in the library.
const filteredItems = [];
for (const item of workingItems) {
const normalizedUrl = normalizeArchiveUrl(item.url);
if (!normalizedUrl) continue;
if (settings.dedupeAcrossSessions && existingLibraryUrls.has(normalizedUrl)) {
duplicateCounts.acrossSessions += 1;
continue;
}
filteredItems.push(item);
}
return {
items: filteredItems,
duplicateCounts
};
}
// Build a map from normalized URL → prior AI/user-set metadata for that URL.
// Used to avoid re-enriching URLs that were already processed in a previous session.
function buildUrlAiEnrichmentMap(savedSessions, metadataStore) {
const map = new Map();
const considerEntry = (entry, url) => {
const normalized = normalizeArchiveUrl(url);
if (!normalized || !entry) return;
const fieldSources = entry.fieldSources || {};
// Qualifies as "already enriched" if any of the four fields was set by AI or the user
const hasEnrichment = ARCHIVE_AI_EDITABLE_FIELDS.some(
(f) => fieldSources[f] === "ai" || fieldSources[f] === "user"
);
if (!hasEnrichment) return;
const score = scoreItemEnrichment(entry);
const existing = map.get(normalized);
if (!existing || score > existing._score) {
map.set(normalized, {
category: String(entry.category || "").trim(),
tags: Array.isArray(entry.tags) ? [...entry.tags] : [],
description: String(entry.description || "").trim(),
summary: String(entry.summary || "").trim(),
fieldSources: normalizeArchiveFieldSources(fieldSources),
_score: score
});
}
};
for (const session of savedSessions || []) {
for (const item of session.items || []) {
considerEntry(item, item.url || item.linkUrl);
}
}
for (const entry of Object.values(metadataStore || {})) {
considerEntry(entry, entry.linkUrl || entry.url);
}
return map;
}
// True if an item's fieldSources indicate it's already fully processed by AI (or user-edited)
// — i.e. none of the four editable fields are still "heuristic".
function isItemAlreadyEnriched(item) {
const fs = item?.fieldSources || {};
return ARCHIVE_AI_EDITABLE_FIELDS.every(
(f) => fs[f] === "ai" || fs[f] === "user"
);
}
function buildExistingLibraryUrlSet(savedSessions, metadataStore) {
const urls = new Set();
for (const session of savedSessions || []) {
for (const item of session.items || []) {
const normalizedUrl = normalizeArchiveUrl(item?.url || item?.linkUrl);
if (normalizedUrl) {
urls.add(normalizedUrl);
}
}
}