-
-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathsync-core.js
More file actions
1382 lines (1220 loc) · 53.6 KB
/
Copy pathsync-core.js
File metadata and controls
1382 lines (1220 loc) · 53.6 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
/**
* Sync Core – Push, Pull, Sync with Three-Way Merge
* Core sync operations, diff computation, merge logic, and debounced auto-sync.
*/
import { commitBookmarkChanges } from './commit-bookmarks.js';
import { pushToMirrors } from './mirror-push.js';
import {
fileMapToBookmarkTree,
orderEntryKey,
} from './bookmark-serializer.js';
import { fetchRemoteFileMap, buildRemoteMaps } from './remote-fetch.js';
import { replaceLocalBookmarks } from './bookmark-replace.js';
import { decryptToken } from './crypto.js';
import { LinkwardenAPI } from './linkwarden-api.js';
import { getMessage } from './i18n.js';
import { getActiveProfileId, getProfiles, getSyncState, setSyncState } from './profile-manager.js';
import { log as debugLog } from './debug-log.js';
import { computeDiff, contentEquals } from './sync-diff.js';
export { computeDiff, contentEquals } from './sync-diff.js';
import { buildStaleBasePushChanges } from './profile-switch-logic.js';
import {
assessFileChangesDeletionGuard,
assessLocalShrink,
DEFAULT_DELETE_GUARD_MAX_FRACTION,
DEFAULT_DELETE_GUARD_MIN_FILES,
} from './deletion-guard.js';
import {
STORAGE_KEYS,
getDeviceId,
getSettings,
isConfigured,
createApi,
getLocalFileMap,
filterForDiff,
isGeneratedOrSettingsPath,
addGeneratedFiles,
hasBookmarkPayloadFiles,
countBookmarkPayloadFiles,
buildEncryptedSettings,
applyEncryptedSettings,
getRemoteEncryptedSettingsContent,
applyConnectionOverride,
getSettingsForProfile,
} from './sync-settings.js';
let isSyncing = false;
let suppressAutoSyncUntil = 0;
let debounceTimer = null;
let maxWaitTimer = null;
let syncActivityListener = null;
/**
* Register a listener notified when sync activity starts (true) or ends (false).
* The background uses this to keep the event page / service worker alive for the
* full duration of long operations (issue #143).
* @param {((active: boolean) => void) | null} listener
*/
export function setSyncActivityListener(listener) {
syncActivityListener = typeof listener === 'function' ? listener : null;
}
/**
* Single entry point for toggling the sync lock so activity transitions are
* reported exactly once (idempotent for nested push/pull-within-sync calls).
* @param {boolean} value
*/
function setSyncing(value) {
const next = Boolean(value);
if (next === isSyncing) return;
isSyncing = next;
if (syncActivityListener) {
try {
syncActivityListener(next);
} catch {
/* listener must never break the sync flow */
}
}
}
export { commitBookmarkChanges } from './commit-bookmarks.js';
async function checkStorageQuota() {
try {
if (typeof chrome !== 'undefined' && chrome.storage?.local?.getBytesInUse) {
const used = await chrome.storage.local.getBytesInUse(null);
const quota = chrome.storage.local.QUOTA_BYTES || 10485760; // 10 MB default
const pct = Math.round((used / quota) * 100);
if (pct >= 80) {
await debugLog(`[sync] Storage quota warning: ${pct}% used (${used} / ${quota} bytes)`);
}
}
} catch (e) {
// Non-fatal — quota check is best-effort
}
}
async function mirrorToLinkwarden(toPushMap) {
const globals = await chrome.storage.sync.get({
linkwardenToken: '',
linkwardenEnabled: false,
linkwardenAutoSave: false,
linkwardenUrl: '',
linkwardenDefaultCollectionId: '',
linkwardenDefaultTags: '',
});
if (!globals.linkwardenEnabled) return;
if (!globals.linkwardenAutoSave) return;
if (!globals.linkwardenUrl || !globals.linkwardenToken) return;
try {
const plainToken = await decryptToken(globals.linkwardenToken);
const api = new LinkwardenAPI(globals.linkwardenUrl, plainToken);
const defaultCollection = globals.linkwardenDefaultCollectionId;
const defaultTagsInput = globals.linkwardenDefaultTags || '';
const tags = defaultTagsInput.split(',').map(t => t.trim()).filter(t => t.length > 0).map(name => ({ name }));
for (const [path, content] of Object.entries(toPushMap)) {
if (!path.endsWith('.json') || path.endsWith('_order.json') || path.endsWith('_index.json')) continue;
if (!content) continue; // Deleted
try {
const bookmark = JSON.parse(content);
if (bookmark.url) {
await debugLog(`[Linkwarden] Auto-saving: ${bookmark.url} (${bookmark.title})`);
await api.saveLink({
url: bookmark.url,
name: bookmark.title || bookmark.url,
collectionId: defaultCollection ? parseInt(defaultCollection, 10) : undefined,
tags: tags.length > 0 ? tags : undefined
});
}
} catch (parseErr) {
// Ignored. Not a valid bookmark JSON or duplicate error from API.
}
}
} catch (err) {
await debugLog(`[Linkwarden] Failed to auto-save to Linkwarden: ${err.message}`);
}
}
/**
* Three-way merge for _order.json content.
*
* _order.json is an array of entries where each entry is either a bookmark
* filename (string) or a folder descriptor ({ dir, title }). When two devices
* concurrently add/remove different bookmarks in the same folder, both produce
* different _order.json content. Instead of treating this as a conflict, we
* merge the arrays: keep local order as the base, apply remote additions at the
* end, and honour removals from both sides.
*
* @param {string|null} baseContent - Base _order.json (null if newly created)
* @param {string} localContent - Local _order.json
* @param {string} remoteContent - Remote _order.json
* @returns {string|null} Merged JSON string, or null if merge is not possible.
*/
export function mergeOrderJson(baseContent, localContent, remoteContent) {
let base, local, remote;
try {
base = baseContent ? JSON.parse(baseContent) : [];
local = JSON.parse(localContent);
remote = JSON.parse(remoteContent);
} catch {
return null; // Malformed JSON → fall through to conflict
}
if (!Array.isArray(base) || !Array.isArray(local) || !Array.isArray(remote)) {
return null;
}
const baseKeys = new Set(base.map(orderEntryKey));
const localKeys = new Set(local.map(orderEntryKey));
const remoteKeys = new Set(remote.map(orderEntryKey));
// Determine what each side removed relative to base
const remoteRemovedKeys = new Set(
base.filter(e => !remoteKeys.has(orderEntryKey(e))).map(orderEntryKey)
);
const localRemovedKeys = new Set(
base.filter(e => !localKeys.has(orderEntryKey(e))).map(orderEntryKey)
);
// Start with local order — remove entries that remote deleted
const merged = local.filter(e => !remoteRemovedKeys.has(orderEntryKey(e)));
// Append entries that remote added (entries in remote but not in base)
// Skip any that are already present in merged (e.g. both sides added the same entry)
const mergedKeys = new Set(merged.map(orderEntryKey));
for (const entry of remote) {
const key = orderEntryKey(entry);
if (!baseKeys.has(key) && !mergedKeys.has(key) && !localRemovedKeys.has(key)) {
merged.push(entry);
mergedKeys.add(key);
}
}
// Stable dedupe: if local itself contained duplicates, collapse them now
const deduped = [];
const finalKeys = new Set();
for (const entry of merged) {
const key = orderEntryKey(entry);
if (!finalKeys.has(key)) {
deduped.push(entry);
finalKeys.add(key);
}
}
return JSON.stringify(deduped, null, 2);
}
/**
* Merge two diffs (local and remote) into a set of actions.
* Implements the three-way merge rules from the plan.
*
* For _order.json files that both sides modified, a content-level merge is
* attempted (combining additions/removals from both sides) instead of
* immediately treating the change as a conflict.
*
* @param {object} localDiff - { added, removed, modified }
* @param {object} remoteDiff - { added, removed, modified }
* @param {Object<string, string>} localFiles - Full local file map
* @param {Object<string, string>} remoteFiles - Full remote file map
* @param {Object<string, string>} [baseFiles={}] - Base file map (for _order.json merging)
* @returns {{
* toPush: Object<string, string|null>,
* toApplyLocal: Object<string, string|null>,
* conflicts: Array<{path: string, local: string|null, remote: string|null}>
* }}
*/
export function mergeDiffs(localDiff, remoteDiff, localFiles, remoteFiles, baseFiles = {}) {
const toPush = {}; // path → content (or null for delete) — changes to push to GitHub
const toApplyLocal = {}; // path → content (or null for delete) — changes to apply locally
const conflicts = [];
// All paths that were changed on either side
const allPaths = new Set([
...Object.keys(localDiff.added),
...localDiff.removed,
...Object.keys(localDiff.modified),
...Object.keys(remoteDiff.added),
...remoteDiff.removed,
...Object.keys(remoteDiff.modified),
]);
for (const path of allPaths) {
const localAdded = path in localDiff.added;
const localRemoved = localDiff.removed.includes(path);
const localModified = path in localDiff.modified;
const remoteAdded = path in remoteDiff.added;
const remoteRemoved = remoteDiff.removed.includes(path);
const remoteModified = path in remoteDiff.modified;
const localChanged = localAdded || localRemoved || localModified;
const remoteChanged = remoteAdded || remoteRemoved || remoteModified;
if (localChanged && !remoteChanged) {
// Only local change → push to remote
if (localRemoved) {
toPush[path] = null;
} else {
toPush[path] = localFiles[path];
}
} else if (!localChanged && remoteChanged) {
// Only remote change → apply locally
if (remoteRemoved) {
toApplyLocal[path] = null;
} else {
toApplyLocal[path] = remoteFiles[path];
}
} else if (localChanged && remoteChanged) {
// Both changed — check if same change
const localContent = localRemoved ? null : (localFiles[path] || null);
const remoteContent = remoteRemoved ? null : (remoteFiles[path] || null);
if (contentEquals(localContent, remoteContent)) {
// Same change on both sides (semantically) → no conflict, no action needed
continue;
}
// Attempt content-level merge for _order.json files
if (path.endsWith('/_order.json') && localContent !== null && remoteContent !== null) {
const baseContent = baseFiles[path] || null;
const merged = mergeOrderJson(baseContent, localContent, remoteContent);
if (merged !== null) {
// Successfully merged — push merged version and apply locally
toPush[path] = merged;
toApplyLocal[path] = merged;
continue;
}
// mergeOrderJson returned null → fall through to conflict
}
if (localAdded && remoteAdded) {
// Both added different files at same path → conflict
conflicts.push({ path, local: localContent, remote: remoteContent });
} else if (localRemoved && remoteRemoved) {
// Both deleted → nothing to do
continue;
} else {
// One modified/added + other modified/removed → true conflict
conflicts.push({ path, local: localContent, remote: remoteContent });
}
}
}
return { toPush, toApplyLocal, conflicts };
}
async function invokePushToMirrors(profileId, fileMap, commitSha, commitMessage) {
try {
const profiles = await getProfiles();
const profile = profiles[profileId];
const mirrors = Array.isArray(profile?.mirrors) ? profile.mirrors : [];
if (mirrors.length === 0) {
await debugLog('[mirror] skip: no mirror destinations configured');
return;
}
await pushToMirrors(profileId, fileMap, commitSha, commitMessage);
} catch (err) {
console.warn('[GitSyncMarks] Mirror push failed:', err);
await debugLog(`[mirror] push failed: ${err.message}`);
}
}
function getDeleteGuardOptions(settings) {
return {
enabled: settings?.deleteGuardEnabled !== false,
maxFraction:
typeof settings?.deleteGuardMaxFraction === 'number'
? settings.deleteGuardMaxFraction
: DEFAULT_DELETE_GUARD_MAX_FRACTION,
minFiles: DEFAULT_DELETE_GUARD_MIN_FILES,
};
}
function payloadReferenceCount(remoteFiles, baseContentMap) {
const remoteCount = countBookmarkPayloadFiles(remoteFiles);
if (remoteCount > 0) return remoteCount;
return countBookmarkPayloadFiles(baseContentMap);
}
async function returnBulkDeleteConflict(profileId, deleteCount, total) {
await setSyncState(profileId, {
hasConflict: true,
conflictReason: 'bulkDelete',
pendingDelete: { count: deleteCount, total },
lastError: null,
});
await debugLog(`sync() bulk-delete guard: blocked ${deleteCount}/${total} payload files`);
return {
success: false,
conflict: true,
message: getMessage('sync_bulkDeleteBlocked', [String(deleteCount), String(total)]),
};
}
async function blockIfBulkDeletion(
profileId,
fileChanges,
referenceCount,
settings,
backupPath
) {
const guardOpts = getDeleteGuardOptions(settings);
const assessment = assessFileChangesDeletionGuard(
fileChanges,
referenceCount,
(p) => isGeneratedOrSettingsPath(p, backupPath),
guardOpts
);
if (!assessment.blocked) return null;
return returnBulkDeleteConflict(profileId, assessment.deleteCount, assessment.referenceCount);
}
/**
* Remote bookmark paths present on the server but absent from the canonical local map.
* @param {Object<string, string>} localFiles
* @param {Object<string, string>} remoteFileMap
* @param {string} basePath
* @returns {string[]}
*/
export function listRemoteOrphanPaths(localFiles, remoteFileMap, basePath, bitwardenBackupPath) {
const base = String(basePath || 'bookmarks').replace(/\/+$/, '');
const prefix = `${base}/`;
const orphans = [];
for (const path of Object.keys(remoteFileMap || {})) {
if (
path.startsWith(prefix) &&
!(path in localFiles) &&
!isGeneratedOrSettingsPath(path, bitwardenBackupPath)
) {
orphans.push(path);
}
}
return orphans.sort();
}
/**
* @param {string[]} orphanPaths
* @param {string} basePath
* @returns {{ orphanFileCount: number, orphanFolderCount: number, sampleFolders: string[] }}
*/
export function summarizeOrphanPaths(orphanPaths, basePath) {
const base = String(basePath || 'bookmarks').replace(/\/+$/, '');
const folders = new Set();
for (const path of orphanPaths) {
const rel = path.startsWith(`${base}/`) ? path.slice(base.length + 1) : path;
const parts = rel.split('/').filter(Boolean);
if (parts.length > 1) {
folders.add(parts.slice(0, -1).join('/'));
} else if (parts.length === 1) {
folders.add(parts[0]);
}
}
return {
orphanFileCount: orphanPaths.length,
orphanFolderCount: folders.size,
sampleFolders: [...folders].sort().slice(0, 8),
};
}
/**
* Canonical bookmark file map for orphan cleanup (browser if active, else last sync cache).
* @param {string} profileId
* @param {object} settings
* @returns {Promise<Object<string, string>>}
*/
async function getCanonicalFileMapForProfile(profileId, settings) {
const basePath = settings[STORAGE_KEYS.FILE_PATH].replace(/\/+$/, '');
const activeId = await getActiveProfileId();
if (profileId === activeId) {
return getLocalFileMap(basePath, settings);
}
const state = await getSyncState(profileId);
if (!state.lastSyncFiles || Object.keys(state.lastSyncFiles).length === 0) {
throw new Error(getMessage('cleanOrphans_noLocalBaseline'));
}
const fileMap = {};
for (const [path, info] of Object.entries(state.lastSyncFiles)) {
fileMap[path] = info.content;
}
return fileMap;
}
/**
* Preview remote files/folders that would be removed by cleanRemoteOrphans().
* @param {string} [profileId] - Defaults to active profile
* @returns {Promise<object>}
*/
export async function previewRemoteOrphans(profileId) {
const id = profileId || await getActiveProfileId();
const settings = await getSettingsForProfile(id);
if (!settings || !isConfigured(settings)) {
return { success: false, message: getMessage('sync_notConfigured') };
}
const basePath = settings[STORAGE_KEYS.FILE_PATH].replace(/\/+$/, '');
let localFiles;
try {
localFiles = await getCanonicalFileMapForProfile(id, settings);
} catch (err) {
return { success: false, message: err.message };
}
const api = createApi(settings);
let remote;
try {
remote = await fetchRemoteFileMap(api, basePath, null);
} catch (err) {
return { success: false, message: getMessage('cleanOrphans_remoteFetchFailed', [err.message]) };
}
const orphanPaths = listRemoteOrphanPaths(
localFiles,
remote?.fileMap || {},
basePath,
settings.bitwardenBackupPath
);
const summary = summarizeOrphanPaths(orphanPaths, basePath);
return {
success: true,
profileId: id,
localFileCount: Object.keys(localFiles).length,
remoteFileCount: Object.keys(remote?.fileMap || {}).length,
...summary,
};
}
/**
* Delete remote bookmark files not present in the canonical local map (replace push).
* @param {string} [profileId] - Defaults to active profile
* @returns {Promise<object>}
*/
export async function cleanRemoteOrphans(profileId) {
const preview = await previewRemoteOrphans(profileId);
if (!preview.success) return preview;
if (preview.orphanFileCount === 0) {
return {
success: true,
message: getMessage('cleanOrphans_none'),
orphanFileCount: 0,
orphanFolderCount: 0,
};
}
const id = preview.profileId || profileId || await getActiveProfileId();
const settings = await getSettingsForProfile(id);
const localFiles = await getCanonicalFileMapForProfile(id, settings);
const pushResult = await pushForProfile(id, localFiles, {
replaceRemote: true,
message: getMessage('cleanOrphans_commitMessage'),
});
if (!pushResult.success) return pushResult;
return {
...pushResult,
message: getMessage('cleanOrphans_success', [
String(preview.orphanFileCount),
String(preview.orphanFolderCount),
]),
orphanFileCount: preview.orphanFileCount,
orphanFolderCount: preview.orphanFolderCount,
};
}
/**
* Push a file map to a specific profile's primary remote (for profile transfer).
* @param {string} profileId
* @param {Object<string, string>} fileMap
* @param {{ replaceRemote?: boolean, message?: string, onProgress?: CommitProgressCallback }} [options]
* @returns {Promise<{ success: boolean, message: string, commitSha?: string|null }>}
*/
export async function pushForProfile(profileId, fileMap, options = {}) {
const { replaceRemote = true, message, onProgress } = options;
if (isSyncing) {
return { success: false, message: getMessage('sync_alreadyInProgress'), alreadyInProgress: true };
}
setSyncing(true);
try {
const settings = await getSettingsForProfile(profileId);
if (!settings || !isConfigured(settings)) {
return { success: false, message: getMessage('sync_notConfigured') };
}
const api = createApi(settings);
const basePath = settings[STORAGE_KEYS.FILE_PATH].replace(/\/+$/, '');
const backupPath = settings.bitwardenBackupPath;
onProgress?.({ phase: 'fetching', current: 0, total: 0 });
let remote = null;
try {
remote = await fetchRemoteFileMap(api, basePath, null);
} catch (err) {
console.warn('[GitSyncMarks] pushForProfile: could not fetch remote:', err);
}
const fileChanges = {};
for (const [path, content] of Object.entries(fileMap)) {
if (!remote || !remote.fileMap[path] || remote.fileMap[path] !== content) {
fileChanges[path] = content;
}
}
if (replaceRemote && remote) {
for (const path of Object.keys(remote.fileMap)) {
if (
path.startsWith(`${basePath}/`) &&
!(path in fileMap) &&
!isGeneratedOrSettingsPath(path, backupPath)
) {
fileChanges[path] = null;
}
}
}
if (Object.keys(fileChanges).length === 0) {
await saveSyncStateFromMaps(profileId, fileMap, remote?.shaMap || {}, remote?.commitSha || null);
return { success: true, message: getMessage('sync_noChanges'), commitSha: remote?.commitSha || null };
}
const changeCount = Object.keys(fileChanges).length;
onProgress?.({ phase: 'pushing', current: 0, total: changeCount });
const deviceId = await getDeviceId();
const commitMsg = message || `Bookmark sync from ${deviceId.substring(0, 8)} — ${new Date().toISOString()}`;
const newCommitSha = await commitBookmarkChanges(api, commitMsg, fileChanges, onProgress);
let finalCommitSha = newCommitSha;
await saveSyncState(profileId, api, basePath, fileMap, newCommitSha);
if (replaceRemote) {
try {
const verifyRemote = await fetchRemoteFileMap(api, basePath, null);
const orphans = listRemoteOrphanPaths(
fileMap,
verifyRemote?.fileMap || {},
basePath,
backupPath
);
if (orphans.length > 0) {
const orphanChanges = Object.fromEntries(orphans.map((path) => [path, null]));
onProgress?.({ phase: 'pushing', current: 0, total: orphans.length });
const cleanupSha = await commitBookmarkChanges(
api,
`${commitMsg} — remove orphan files`,
orphanChanges,
onProgress
);
finalCommitSha = cleanupSha || newCommitSha;
await saveSyncState(profileId, api, basePath, fileMap, finalCommitSha);
}
} catch (err) {
console.warn('[GitSyncMarks] pushForProfile orphan sweep failed:', err);
}
}
await invokePushToMirrors(profileId, fileMap, finalCommitSha, commitMsg);
return { success: true, message: getMessage('sync_pushSuccess'), commitSha: finalCommitSha };
} catch (err) {
console.error('[GitSyncMarks] pushForProfile error:', err);
await setSyncState(profileId, { lastError: err.message });
return { success: false, message: getMessage('sync_pushFailed', [err.message]) };
} finally {
setSyncing(false);
}
}
/**
* Full push: upload all local bookmarks as individual files.
* Used for initial sync or force-push.
* @param {{ fromSync?: boolean }} [options] - fromSync: true when called from sync() (skip lock to avoid race)
* @returns {Promise<{success: boolean, message: string}>}
*/
export async function push(options = {}) {
if (!options.fromSync) {
if (isSyncing) return { success: false, message: getMessage('sync_alreadyInProgress'), alreadyInProgress: true };
setSyncing(true);
}
await debugLog('push() start');
try {
const baseSettings = await getSettings();
const settings = applyConnectionOverride(baseSettings, options.connectionOverride);
if (!isConfigured(settings)) return { success: false, message: getMessage('sync_notConfigured') };
const api = createApi(settings);
const basePath = settings[STORAGE_KEYS.FILE_PATH].replace(/\/+$/, '');
const backupPath = settings.bitwardenBackupPath;
const localFiles = await getLocalFileMap(basePath, settings);
const deviceId = await getDeviceId();
// Get current remote state to determine what to change
options.onProgress?.({ phase: 'fetching', current: 0, total: 0 });
let remote;
try {
remote = await fetchRemoteFileMap(api, basePath, null);
} catch (err) {
console.warn('[GitSyncMarks] Could not fetch remote state for push:', err);
remote = null;
}
// Build file changes: add/update all local files, delete remote files not in local
const fileChanges = {};
for (const [path, content] of Object.entries(localFiles)) {
if (!remote || !remote.fileMap[path] || remote.fileMap[path] !== content) {
fileChanges[path] = content;
}
}
if (remote) {
for (const path of Object.keys(remote.fileMap)) {
if (
path.startsWith(basePath + '/') &&
!(path in localFiles) &&
!isGeneratedOrSettingsPath(path, backupPath)
) {
fileChanges[path] = null; // delete
}
}
}
addGeneratedFiles(fileChanges, localFiles, basePath, settings, 'auto', remote?.fileMap || null);
const encSettings = await buildEncryptedSettings(settings);
if (encSettings) {
fileChanges[`${basePath}/${encSettings.filename}`] = encSettings.content;
}
// Linkwarden Auto-Save (Mirroring)
await mirrorToLinkwarden(fileChanges);
await debugLog(`push() fileChanges count: ${Object.keys(fileChanges).length}`);
if (Object.keys(fileChanges).length === 0) {
return { success: true, message: getMessage('sync_noChanges') };
}
const commitMsg = `Bookmark sync (push) from ${deviceId.substring(0, 8)} — ${new Date().toISOString()}`;
const t0 = performance.now();
const newCommitSha = await commitBookmarkChanges(api, commitMsg, fileChanges, options.onProgress);
const tCommit = performance.now() - t0;
await debugLog(`push() committed: newCommitSha=${newCommitSha?.substring(0, 7)} [${tCommit.toFixed(2)}ms]`);
const profileId = settings.profileId || await getActiveProfileId();
// Save sync state
await saveSyncState(profileId, api, basePath, localFiles, newCommitSha);
await invokePushToMirrors(profileId, localFiles, newCommitSha, commitMsg);
return { success: true, message: getMessage('sync_pushSuccess') };
} catch (err) {
console.error('[GitSyncMarks] Push error:', err);
const profileId = await getActiveProfileId();
await setSyncState(profileId, { lastError: err.message });
return { success: false, message: getMessage('sync_pushFailed', [err.message]) };
} finally {
if (!options.fromSync) setSyncing(false);
}
}
/**
* Generate all enabled files (mode !== 'off') and push them to the repo.
* Used for the "Generate now" button — generates files in both 'manual' and 'auto' modes.
*/
export async function generateFilesNow({ onProgress } = {}) {
const settings = await getSettings();
if (!isConfigured(settings)) {
return { success: false, message: getMessage('sync_notConfigured') };
}
const basePath = settings[STORAGE_KEYS.FILE_PATH];
const deviceId = await getDeviceId();
const api = createApi(settings);
onProgress?.({ phase: 'generating', current: 0, total: 0 });
const localFiles = await getLocalFileMap(basePath, settings);
const fileChanges = {};
addGeneratedFiles(fileChanges, localFiles, basePath, settings, 'notOff');
if (Object.keys(fileChanges).length === 0) {
return { success: true, message: getMessage('sync_noChanges') };
}
try {
const commitMsg = `Generate files from ${deviceId.substring(0, 8)} — ${new Date().toISOString()}`;
await commitBookmarkChanges(api, commitMsg, fileChanges, onProgress);
return { success: true, message: getMessage('sync_pushSuccess') };
} catch (err) {
console.error('[GitSyncMarks] Generate files error:', err);
return { success: false, message: getMessage('sync_pushFailed', [err.message]) };
}
}
/**
* Full pull: replace all local bookmarks with remote data.
* @param {{ fromSync?: boolean }} [options] - fromSync: true when called from sync() (skip lock to avoid race)
* @returns {Promise<{success: boolean, message: string}>}
*/
export async function pull(options = {}) {
if (!options.fromSync) {
if (isSyncing) return { success: false, message: getMessage('sync_alreadyInProgress'), alreadyInProgress: true };
setSyncing(true);
}
await debugLog('pull() start');
let profileId;
try {
const baseSettings = await getSettings();
const settings = applyConnectionOverride(baseSettings, options.connectionOverride);
if (!isConfigured(settings)) return { success: false, message: getMessage('sync_notConfigured') };
const api = createApi(settings);
const basePath = settings[STORAGE_KEYS.FILE_PATH].replace(/\/+$/, '');
profileId = settings.profileId || await getActiveProfileId();
options.onProgress?.({ phase: 'fetching', current: 0, total: 0 });
const tFetch = performance.now();
const remote = await fetchRemoteFileMap(api, basePath, null);
const fetchMs = performance.now() - tFetch;
const remoteCount = remote ? Object.keys(remote.fileMap).length : 0;
await debugLog(`pull() remote: fileCount=${remoteCount} commitSha=${remote?.commitSha?.substring(0, 7) ?? 'null'} [${fetchMs.toFixed(2)}ms]`);
if (!remote || Object.keys(remote.fileMap).length === 0) {
return { success: false, message: getMessage('sync_noBookmarksOnRemote') };
}
// Apply encrypted settings from remote (before bookmarks, so profile config is current)
const remoteSettingsEnc = await getRemoteEncryptedSettingsContent(remote.fileMap, basePath);
await applyEncryptedSettings(remoteSettingsEnc, settings);
// Save previous commit SHA for undo
const prevState = await getSyncState(profileId);
if (prevState.lastCommitSha) {
await setSyncState(profileId, { previousCommitSha: prevState.lastCommitSha });
}
const bookmarkCount = countBookmarkPayloadFiles(remote.fileMap);
options.onProgress?.({ phase: 'applying', current: 0, total: bookmarkCount });
// Convert remote files to bookmark tree and apply
const roleMap = fileMapToBookmarkTree(remote.fileMap, basePath);
suppressAutoSyncUntil = Date.now() + 30000;
await replaceLocalBookmarks(roleMap, {
githubReposEnabled: settings.githubReposEnabled,
githubReposParent: settings.githubReposParent,
githubReposUsername: settings.githubReposUsername,
linkwardenSyncEnabled: settings.linkwardenSyncEnabled,
linkwardenSyncParent: settings.linkwardenSyncParent,
linkwardenSyncPushToGit: settings.linkwardenSyncPushToGit,
});
options.onProgress?.({ phase: 'applying', current: bookmarkCount, total: bookmarkCount });
// Re-generate local file map (to capture exact state with any normalization)
const freshLocalFiles = await getLocalFileMap(basePath, settings);
// Save sync state with the fresh local files (content matches what browser has)
// but use remote SHAs for the stored state so remote diff is clean
await saveSyncStateFromMaps(profileId, freshLocalFiles, remote.shaMap, remote.commitSha);
return { success: true, message: getMessage('sync_loadedFromRemote') };
} catch (err) {
console.error('[GitSyncMarks] Pull error:', err);
if (profileId) await setSyncState(profileId, { lastError: err.message });
return { success: false, message: getMessage('sync_pullFailed', [err.message]) };
} finally {
if (!options.fromSync) setSyncing(false);
}
}
/**
* Bidirectional sync with three-way merge.
* @returns {Promise<{success: boolean, message: string}>}
*/
export async function sync(options = {}) {
if (isSyncing) return { success: false, message: getMessage('sync_alreadyInProgress'), alreadyInProgress: true };
setSyncing(true);
let profileId;
try {
await debugLog('sync() start');
await checkStorageQuota();
const baseSettings = await getSettings();
const settings = applyConnectionOverride(baseSettings, options.connectionOverride);
if (!isConfigured(settings)) return { success: false, message: getMessage('sync_notConfigured') };
const api = createApi(settings);
const basePath = settings[STORAGE_KEYS.FILE_PATH].replace(/\/+$/, '');
const deviceId = await getDeviceId();
profileId = settings.profileId || await getActiveProfileId();
// 1. Load base state
const stored = await getSyncState(profileId);
const baseFiles = stored.lastSyncFiles || null;
const baseCommitSha = stored.lastCommitSha || null;
if (baseFiles) {
await debugLog(`sync() loaded baseCount=${Object.keys(baseFiles).length} baseCommitSha=${baseCommitSha?.substring(0, 7) ?? 'null'}`);
}
// 2. Get local file map
const localFiles = await getLocalFileMap(basePath, settings);
// 3. Get remote file map (optimized: uses base SHAs to skip unchanged blobs)
options.onProgress?.({ phase: 'fetching', current: 0, total: 0 });
const tFetch = performance.now();
const remote = await fetchRemoteFileMap(api, basePath, baseFiles);
const fetchMs = performance.now() - tFetch;
if (remote) {
await debugLog(`sync() fetchRemote done: remoteCommitSha=${remote.commitSha?.substring(0, 7)} [${fetchMs.toFixed(2)}ms]`);
}
// 4. Handle special cases
// 4a. No base state (first sync)
if (!baseFiles) {
const hasRemote = remote ? hasBookmarkPayloadFiles(remote.fileMap) : false;
const hasLocal = hasBookmarkPayloadFiles(localFiles);
if (!hasRemote && hasLocal) {
// First sync, no remote data → push everything (hold lock to avoid concurrent sync)
console.log('[GitSyncMarks] First sync: pushing local bookmarks');
return await push({
fromSync: true,
connectionOverride: options.connectionOverride,
onProgress: options.onProgress,
});
}
if (hasRemote && !hasLocal) {
// Remote has data, local is empty → pull (hold lock to avoid concurrent sync)
console.log('[GitSyncMarks] First sync: pulling remote bookmarks');
return await pull({ fromSync: true, connectionOverride: options.connectionOverride });
}
if (hasRemote && hasLocal) {
// Both have data, no base → can't merge, user must choose
console.log('[GitSyncMarks] First sync: both sides have data, conflict');
await setSyncState(profileId, { hasConflict: true });
return { success: false, message: getMessage('sync_conflictBothModified'), conflict: true };
}
// Neither has data
return { success: true, message: getMessage('sync_allInSync') };
}
// 4b. Extract base content map (path → content) from stored state
const baseContentMap = {};
for (const [path, info] of Object.entries(baseFiles)) {
baseContentMap[path] = info.content;
}
const remoteFiles = remote ? remote.fileMap : {};
const baseCount = Object.keys(baseContentMap).length;
const localCount = Object.keys(localFiles).length;
const remoteCount = Object.keys(remoteFiles).length;
await debugLog(`sync() baseFiles: ${baseCount} localFiles: ${localCount} remoteFiles: ${remoteCount}`);
const referencePayloadCount = payloadReferenceCount(remoteFiles, baseContentMap);
const guardOpts = getDeleteGuardOptions(settings);
// 5. Compute diffs (excluding generated files like README.md)
const tDiff = performance.now();
const backupPath = settings.bitwardenBackupPath;
const localDiff = computeDiff(
filterForDiff(baseContentMap, backupPath),
filterForDiff(localFiles, backupPath)
);
const remoteDiff = computeDiff(
filterForDiff(baseContentMap, backupPath),
filterForDiff(remoteFiles, backupPath)
);
const diffMs = performance.now() - tDiff;
await debugLog(`sync() localDiff: added=${Object.keys(localDiff.added).length} removed=${localDiff.removed.length} modified=${Object.keys(localDiff.modified).length} [${diffMs.toFixed(2)}ms]`);
await debugLog(`sync() remoteDiff: added=${Object.keys(remoteDiff.added).length} removed=${remoteDiff.removed.length} modified=${Object.keys(remoteDiff.modified).length}`);
const localHasChanges = Object.keys(localDiff.added).length > 0 ||
localDiff.removed.length > 0 || Object.keys(localDiff.modified).length > 0;
const remoteHasChanges = Object.keys(remoteDiff.added).length > 0 ||
remoteDiff.removed.length > 0 || Object.keys(remoteDiff.modified).length > 0;
console.log('[GitSyncMarks] Sync analysis:', {
localChanges: {
added: Object.keys(localDiff.added).length,
removed: localDiff.removed.length,
modified: Object.keys(localDiff.modified).length,
},
remoteChanges: {
added: Object.keys(remoteDiff.added).length,
removed: remoteDiff.removed.length,
modified: Object.keys(remoteDiff.modified).length,
},
});
// 6. No changes on either side
if (!localHasChanges && !remoteHasChanges) {
// Refresh stored commit SHA when remote HEAD moved (e.g. after profile transfer push)
// but three-way base still matches local/remote content.
if (remote?.commitSha && remote.commitSha !== baseCommitSha) {
await saveSyncStateFromMaps(profileId, localFiles, remote.shaMap, remote.commitSha);
} else {
await setSyncState(profileId, { lastSyncTime: new Date().toISOString(), lastError: null });
}
return { success: true, message: getMessage('sync_allInSync') };
}
// 7. Only local changes → push
if (localHasChanges && !remoteHasChanges) {
const fileChanges = {};
for (const [p, c] of Object.entries(localDiff.added)) fileChanges[p] = c;
for (const [p, c] of Object.entries(localDiff.modified)) fileChanges[p] = c;
for (const p of localDiff.removed) fileChanges[p] = null;
addGeneratedFiles(fileChanges, localFiles, basePath, settings, 'auto', remoteFiles);
const encSettings7 = await buildEncryptedSettings(settings);
if (encSettings7) fileChanges[`${basePath}/${encSettings7.filename}`] = encSettings7.content;
const bulkBlocked7 = await blockIfBulkDeletion(
profileId,
fileChanges,
referencePayloadCount,
settings,
backupPath
);
if (bulkBlocked7) return bulkBlocked7;
const msg = `Bookmark sync from ${deviceId.substring(0, 8)} — ${new Date().toISOString()}`;
const tCommit = performance.now();
const newCommitSha = await commitBookmarkChanges(api, msg, fileChanges, options.onProgress);
const commitMs = performance.now() - tCommit;
await debugLog(`sync() path7 push: newCommitSha=${newCommitSha?.substring(0, 7)} [${commitMs.toFixed(2)}ms]`);
await saveSyncState(profileId, api, basePath, localFiles, newCommitSha);
await setSyncState(profileId, { localModifiedSinceSync: false });
await invokePushToMirrors(profileId, localFiles, newCommitSha, msg);
return { success: true, message: getMessage('sync_pushSuccess') };
}