-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathstorage.js
More file actions
1340 lines (1171 loc) · 46.8 KB
/
Copy pathstorage.js
File metadata and controls
1340 lines (1171 loc) · 46.8 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 Manager for Local iTab Extension
* Handles all chrome.storage.local operations with error handling and validation
*/
class StorageManager {
constructor() {
this.syncMetaKey = '__localItabSyncMeta';
this.syncChunkPrefix = '__localItabSyncData_';
this.syncMaxChunks = 20;
this.syncTotalBudget = 98000;
this._textEncoder = null;
this._syncInitialized = false;
this._syncInitPromise = null;
this._isApplyingSync = false;
this._ignoreRemoteSyncUntil = 0;
this._syncPushTimer = null;
// Default configuration schema
this.defaultConfig = {
clock: {
hour12: false,
showSeconds: true
},
search: {
engine: 'google',
custom: ''
},
bg: {
type: 'gradient',
value: ''
},
themePreset: 'aurora-glass',
show: {
clock: true,
search: true,
shortcuts: true,
weather: false,
hot: false,
movie: false
},
privacy: {
onlineFavicons: false
},
categories: [
{ id: 'work', name: '\u5de5\u4f5c', icon: '\ud83d\udcbc' },
{ id: 'social', name: '\u793e\u4ea4', icon: '\ud83d\udc65' },
{ id: 'entertainment', name: '\u5a31\u4e50', icon: '\ud83c\udfae' },
{ id: 'tools', name: '\u5de5\u5177', icon: '\ud83d\udd27' },
{ id: 'learning', name: '\u5b66\u4e60', icon: '\ud83d\udcda' }
],
links: [],
weather: {
city: 'Local',
temp: 22,
cond: 'Sunny',
aqiLabel: 'Good',
aqi: 50,
low: 18,
high: 26
},
hot: {
tab: 'baidu',
baidu: [],
weibo: [],
zhihu: []
},
movie: {
title: 'Sample Movie',
note: 'A great movie to watch',
poster: ''
},
quote: 'Welcome to your personalized new tab page!',
layout: {
autoArrange: true,
alignToGrid: true,
gridSize: 96,
columns: 6,
positions: {}
},
ui: {
dashboardHidden: false,
dashboardPadding: null,
showShortcutTitles: true,
shortcutsStyle: {
gapX: null,
gapY: null,
iconSize: null,
titleSize: null,
titleColor: ''
}
},
sync: {
enabled: false,
lastSync: '',
lastError: '',
includeLargeAssets: false
}
};
}
/**
* Get a value from storage with default fallback
* @param {string} key - Storage key
* @param {*} defaultValue - Default value if key doesn't exist
* @returns {Promise<*>} - Retrieved value or default
*/
async get(key, defaultValue = null) {
try {
await this.ensureSyncInitialized();
const result = await chrome.storage.local.get([key]);
if (result[key] !== undefined) {
// Validate retrieved data
try {
const validatedValue = this.validateData(key, result[key]);
return validatedValue;
} catch (validationError) {
console.warn(`Data validation failed for key "${key}", using default:`, validationError);
// Notify about data corruption recovery
if (typeof errorHandler !== 'undefined') {
errorHandler.showDataRecovery([key]);
}
const defaultVal = defaultValue !== null ? defaultValue : this.getDefaultValue(key);
// Try to save the corrected default value
try {
await this.set(key, defaultVal);
} catch (saveError) {
console.error(`Failed to save corrected value for key "${key}":`, saveError);
}
return defaultVal;
}
}
// Return provided default or schema default
if (defaultValue !== null) {
return defaultValue;
}
return this.getDefaultValue(key);
} catch (error) {
console.error(`Storage get error for key "${key}":`, error);
// Handle specific storage errors
if (typeof errorHandler !== 'undefined') {
errorHandler.handleStorageError(error, `retrieve ${key}`);
}
return defaultValue !== null ? defaultValue : this.getDefaultValue(key);
}
}
/**
* Set a value in storage with validation
* @param {string} key - Storage key
* @param {*} value - Value to store
* @returns {Promise<boolean>} - Success status
*/
async set(key, value) {
try {
await this.ensureSyncInitialized();
// Validate the data before storing
const validatedValue = this.validateData(key, value);
await chrome.storage.local.set({ [key]: validatedValue });
if (!this._isApplyingSync) {
if (key === 'sync') {
if (validatedValue.enabled) {
this.scheduleSyncPush();
} else {
await this.disableRemoteSync();
}
} else if (await this.isSyncEnabledLocally()) {
this.scheduleSyncPush();
}
}
return true;
} catch (error) {
console.error(`Storage set error for key "${key}":`, error);
// Handle quota exceeded error
if (error.message && error.message.includes('QUOTA_EXCEEDED')) {
throw new Error('Storage quota exceeded. Please remove some data or export your settings.');
}
return false;
}
}
/**
* Get all stored data
* @returns {Promise<Object>} - All stored data with defaults for missing keys
*/
async getAll() {
try {
await this.ensureSyncInitialized();
const result = await chrome.storage.local.get(null);
// Merge with defaults for any missing keys
const completeConfig = this.cloneDefaultConfig();
for (const [key, value] of Object.entries(result)) {
if (this.defaultConfig.hasOwnProperty(key)) {
completeConfig[key] = this.validateData(key, value);
}
}
return completeConfig;
} catch (error) {
console.error('Storage getAll error:', error);
return { ...this.defaultConfig };
}
}
/**
* Set multiple values at once
* @param {Object} data - Key-value pairs to store
* @returns {Promise<boolean>} - Success status
*/
async setAll(data, options = {}) {
try {
if (!options.skipSyncInitialization) {
await this.ensureSyncInitialized();
}
const wasSyncEnabled = await this.isSyncEnabledLocally();
const validatedData = {};
// Validate each key-value pair
for (const [key, value] of Object.entries(data)) {
validatedData[key] = this.validateData(key, value);
}
await chrome.storage.local.set(validatedData);
if (!this._isApplyingSync && !options.skipSyncSideEffects) {
const syncEnabled = validatedData.sync?.enabled || await this.isSyncEnabledLocally();
if (syncEnabled) {
this.scheduleSyncPush();
} else if (validatedData.sync && validatedData.sync.enabled === false && wasSyncEnabled) {
await this.disableRemoteSync();
}
}
return true;
} catch (error) {
console.error('Storage setAll error:', error);
if (error.message && error.message.includes('QUOTA_EXCEEDED')) {
throw new Error('Storage quota exceeded. Please reduce the amount of data being stored.');
}
return false;
}
}
/**
* Clear all stored data
* @returns {Promise<boolean>} - Success status
*/
async clear() {
try {
const current = await chrome.storage.local.get(['sync']);
const wasSyncing = current.sync?.enabled === true;
await chrome.storage.local.clear();
if (wasSyncing) {
await this.disableRemoteSync();
}
return true;
} catch (error) {
console.error('Storage clear error:', error);
return false;
}
}
/**
* Get storage usage information
* @returns {Promise<Object>} - Storage usage stats
*/
async getStorageInfo() {
try {
const bytesInUse = await chrome.storage.local.getBytesInUse();
const quota = chrome.storage.local.QUOTA_BYTES || 5242880; // 5MB default
const syncAvailable = this.isSyncAvailable();
const syncBytesInUse = syncAvailable ? await chrome.storage.sync.getBytesInUse(null) : 0;
const syncQuota = syncAvailable ? (chrome.storage.sync.QUOTA_BYTES || 102400) : 0;
return {
bytesInUse,
quota,
percentUsed: Math.round((bytesInUse / quota) * 100),
available: quota - bytesInUse,
local: {
bytesInUse,
quota,
percentUsed: Math.round((bytesInUse / quota) * 100),
available: quota - bytesInUse
},
sync: {
available: syncAvailable,
bytesInUse: syncBytesInUse,
quota: syncQuota,
percentUsed: syncQuota ? Math.round((syncBytesInUse / syncQuota) * 100) : 0,
availableBytes: syncQuota ? Math.max(0, syncQuota - syncBytesInUse) : 0
}
};
} catch (error) {
console.error('Storage info error:', error);
return {
bytesInUse: 0,
quota: 5242880,
percentUsed: 0,
available: 5242880,
local: {
bytesInUse: 0,
quota: 5242880,
percentUsed: 0,
available: 5242880
},
sync: {
available: false,
bytesInUse: 0,
quota: 0,
percentUsed: 0,
availableBytes: 0
}
};
}
}
/**
* Get default value for a key from schema
* @param {string} key - Storage key
* @returns {*} - Default value
*/
getDefaultValue(key) {
return this.defaultConfig.hasOwnProperty(key)
? JSON.parse(JSON.stringify(this.defaultConfig[key]))
: null;
}
cloneDefaultConfig() {
return JSON.parse(JSON.stringify(this.defaultConfig));
}
getDisabledSyncConfig() {
return this.validateSyncConfig({
enabled: false,
lastSync: '',
lastError: '',
includeLargeAssets: false
});
}
sanitizeConfigForBackup(config) {
const sanitized = this.validateConfigObject(config);
sanitized.sync = this.getDisabledSyncConfig();
return sanitized;
}
getExtensionVersion() {
try {
if (typeof chrome !== 'undefined' && chrome.runtime?.getManifest) {
return chrome.runtime.getManifest().version || '';
}
} catch (_) {}
return '';
}
countBackupItems(config) {
const source = this.validateConfigObject(config);
const links = Array.isArray(source.links) ? source.links : [];
const hot = source.hot || {};
const dataUrlIcons = links.filter(link => typeof link.icon === 'string' && link.icon.startsWith('data:')).length;
const hasBackgroundImage = source.bg?.type === 'image' && !!source.bg.value;
const hasMoviePoster = !!source.movie?.poster;
return {
shortcuts: links.length,
categories: Array.isArray(source.categories) ? source.categories.length : 0,
hotTopics: (hot.baidu?.length || 0) + (hot.weibo?.length || 0) + (hot.zhihu?.length || 0),
dataUrlIcons,
hasBackgroundImage,
hasMoviePoster,
localImagesIncluded: !!(hasBackgroundImage || hasMoviePoster || dataUrlIcons > 0)
};
}
buildManualExportPayload(config, metadata = {}) {
const sanitized = this.sanitizeConfigForBackup(config);
const exportDate = metadata.exportDate || new Date().toISOString();
return {
version: '1.0',
schemaVersion: 1,
exportDate,
createdAt: exportDate,
exportedBy: 'Local iTab Extension',
extensionVersion: metadata.extensionVersion || this.getExtensionVersion(),
itemCounts: this.countBackupItems(sanitized),
data: sanitized
};
}
buildDriveBackupPayload(config, metadata = {}) {
const sanitized = this.sanitizeConfigForBackup(config);
const createdAt = metadata.createdAt || new Date().toISOString();
const snapshotId = metadata.snapshotId || `snapshot_${Date.now()}`;
const deviceId = typeof metadata.deviceId === 'string' ? metadata.deviceId : '';
const deviceName = typeof metadata.deviceName === 'string' ? metadata.deviceName : '';
return {
version: '1.0',
schemaVersion: 1,
type: 'backupSnapshot',
app: 'local-itab',
createdAt,
exportDate: createdAt,
exportedBy: 'Local iTab Extension',
extensionVersion: metadata.extensionVersion || this.getExtensionVersion(),
snapshotId,
device: {
id: deviceId,
name: deviceName
},
metadata: {
app: 'local-itab',
type: 'backupSnapshot',
schemaVersion: 1,
deviceId,
snapshotId,
reason: typeof metadata.reason === 'string' ? metadata.reason : 'manual'
},
itemCounts: this.countBackupItems(sanitized),
data: sanitized
};
}
validateImportPayload(importData) {
let settings;
if (importData && typeof importData === 'object' && importData.data && (importData.version || importData.schemaVersion || importData.type)) {
settings = importData.data;
} else if (importData && typeof importData === 'object' && importData.settings) {
settings = importData.settings;
} else {
settings = importData;
}
if (!settings || typeof settings !== 'object' || Array.isArray(settings)) {
throw new Error('Settings data must be an object');
}
const validated = this.validateConfigObject(settings);
validated.sync = this.getDisabledSyncConfig();
if (!Array.isArray(validated.links)) {
validated.links = [];
}
if (typeof validated.quote !== 'string') {
validated.quote = this.defaultConfig.quote;
}
return validated;
}
prepareRestoredConfig(importData, currentConfig = null) {
const restored = this.validateImportPayload(importData);
if (currentConfig && typeof currentConfig === 'object') {
restored.sync = this.validateSyncConfig(currentConfig.sync || this.defaultConfig.sync);
}
return restored;
}
validateConfigObject(data) {
const validated = this.cloneDefaultConfig();
if (!data || typeof data !== 'object') {
return validated;
}
for (const key of Object.keys(this.defaultConfig)) {
if (Object.prototype.hasOwnProperty.call(data, key)) {
validated[key] = this.validateData(key, data[key]);
}
}
return validated;
}
isSyncAvailable() {
return !!(typeof chrome !== 'undefined' && chrome.storage && chrome.storage.sync);
}
async isSyncEnabledLocally() {
try {
const result = await chrome.storage.local.get(['sync']);
return result.sync?.enabled === true;
} catch (_) {
return false;
}
}
async getLocalProviderState() {
const result = await chrome.storage.local.get(['sync']);
return {
sync: this.validateSyncConfig(result.sync || this.defaultConfig.sync)
};
}
async ensureSyncInitialized() {
if (this._syncInitialized) return;
if (this._syncInitPromise) return this._syncInitPromise;
this._syncInitPromise = (async () => {
if (!this.isSyncAvailable()) {
this._syncInitialized = true;
return;
}
try {
const remoteMeta = await this.getRemoteMeta();
if (!remoteMeta?.enabled) {
this._syncInitialized = true;
return;
}
const localResult = await chrome.storage.local.get(['sync']);
const localSync = this.validateSyncConfig(localResult.sync || this.defaultConfig.sync);
if (localSync.lastSync === remoteMeta.updatedAt) {
this._syncInitialized = true;
return;
}
const remoteData = await this.readRemoteSyncData(remoteMeta);
if (!remoteData) {
this._syncInitialized = true;
return;
}
const validated = this.validateConfigObject(remoteData);
validated.sync = this.validateSyncConfig({
enabled: true,
lastSync: remoteMeta.updatedAt || '',
lastError: '',
includeLargeAssets: false
});
this._isApplyingSync = true;
try {
await chrome.storage.local.set(validated);
} finally {
this._isApplyingSync = false;
}
} catch (error) {
console.warn('Cloud sync initialization failed:', error);
await this.updateLocalSyncState({
enabled: false,
lastError: error.message || String(error)
});
} finally {
this._syncInitialized = true;
}
})();
return this._syncInitPromise;
}
async getSyncStatus() {
await this.ensureSyncInitialized();
const localResult = await chrome.storage.local.get(['sync']);
const localSync = this.validateSyncConfig(localResult.sync || this.defaultConfig.sync);
const remoteMeta = this.isSyncAvailable() ? await this.getRemoteMeta() : null;
const storageInfo = await this.getStorageInfo();
return {
available: this.isSyncAvailable(),
enabled: localSync.enabled,
local: localSync,
remote: remoteMeta,
storage: storageInfo.sync
};
}
async setSyncEnabled(enabled) {
await this.ensureSyncInitialized();
const config = await this.getAll();
config.sync = this.validateSyncConfig({
...config.sync,
enabled,
lastError: ''
});
await chrome.storage.local.set({ sync: config.sync });
if (enabled) {
try {
return await this.pushToSync();
} catch (error) {
await this.updateLocalSyncState({
enabled: false,
lastError: error.message || String(error)
});
throw error;
}
}
await this.disableRemoteSync();
return this.getSyncStatus();
}
async pushToSync() {
if (this._syncPushTimer) {
clearTimeout(this._syncPushTimer);
this._syncPushTimer = null;
}
if (this._isApplyingSync) return this.getSyncStatus();
if (!this.isSyncAvailable()) {
throw new Error('Chrome Sync storage is not available in this browser.');
}
try {
const config = await this.getAll();
const { payload, omittedAssets } = this.prepareSyncPayload(config);
const payloadJson = JSON.stringify(payload);
const payloadBytes = this.getUtf8ByteLength(payloadJson);
const oldMeta = await this.getRemoteMeta();
const chunks = this.createSyncChunks(payloadJson);
const updatedAt = new Date().toISOString();
const items = {
[this.syncMetaKey]: {
enabled: true,
version: 2,
updatedAt,
chunkCount: chunks.length,
payloadBytes,
omittedAssets
}
};
chunks.forEach((chunk, index) => {
items[`${this.syncChunkPrefix}${index}`] = chunk;
});
const syncBytes = this.getSyncItemsBytes(items);
if (syncBytes > this.syncTotalBudget) {
throw new Error(`Cloud sync payload is too large (${Math.round(syncBytes / 1024)} KB after Chrome Sync encoding). Remove some shortcuts or use manual export for large data.`);
}
this._ignoreRemoteSyncUntil = Date.now() + 2000;
await chrome.storage.sync.set(items);
const oldCount = Number.isFinite(oldMeta?.chunkCount) ? oldMeta.chunkCount : 0;
if (oldCount > chunks.length) {
const staleKeys = [];
for (let i = chunks.length; i < oldCount; i += 1) {
staleKeys.push(`${this.syncChunkPrefix}${i}`);
}
if (staleKeys.length) await chrome.storage.sync.remove(staleKeys);
}
await this.updateLocalSyncState({
enabled: true,
lastSync: updatedAt,
lastError: ''
});
return this.getSyncStatus();
} catch (error) {
await this.updateLocalSyncState({
enabled: true,
lastError: error.message || String(error)
});
throw error;
}
}
async pullFromSync() {
if (!this.isSyncAvailable()) {
throw new Error('Chrome Sync storage is not available in this browser.');
}
const remoteMeta = await this.getRemoteMeta();
if (!remoteMeta?.enabled) {
await this.updateLocalSyncState({ enabled: false });
return { applied: false, status: await this.getSyncStatus() };
}
const localResult = await chrome.storage.local.get(['sync']);
const localSync = this.validateSyncConfig(localResult.sync || this.defaultConfig.sync);
if (localSync.lastSync === remoteMeta.updatedAt) {
return { applied: false, status: await this.getSyncStatus() };
}
const remoteData = await this.readRemoteSyncData(remoteMeta);
if (!remoteData) {
throw new Error('Cloud sync data is empty or corrupted.');
}
const validated = this.validateConfigObject(remoteData);
validated.sync = this.validateSyncConfig({
enabled: true,
lastSync: remoteMeta.updatedAt || '',
lastError: '',
includeLargeAssets: false
});
this._isApplyingSync = true;
try {
await chrome.storage.local.set(validated);
} finally {
this._isApplyingSync = false;
}
return { applied: true, status: await this.getSyncStatus() };
}
async clearSync() {
if (!this.isSyncAvailable()) {
throw new Error('Chrome Sync storage is not available in this browser.');
}
await this.disableRemoteSync(true);
return this.getSyncStatus();
}
async getRemoteMeta() {
if (!this.isSyncAvailable()) return null;
const result = await chrome.storage.sync.get([this.syncMetaKey]);
const meta = result[this.syncMetaKey];
return meta && typeof meta === 'object' ? meta : null;
}
async readRemoteSyncData(meta) {
const chunkCount = Number.isFinite(meta?.chunkCount) ? meta.chunkCount : 0;
if (chunkCount <= 0 || chunkCount > this.syncMaxChunks) return null;
const keys = Array.from({ length: chunkCount }, (_, index) => `${this.syncChunkPrefix}${index}`);
const result = await chrome.storage.sync.get(keys);
const json = keys.map(key => result[key] || '').join('');
if (!json) return null;
return JSON.parse(json);
}
async disableRemoteSync(clearChunks = false) {
if (!this.isSyncAvailable()) return;
const oldMeta = await this.getRemoteMeta();
const oldCount = Number.isFinite(oldMeta?.chunkCount) ? oldMeta.chunkCount : 0;
const keysToRemove = [];
if (clearChunks || oldCount) {
for (let i = 0; i < oldCount; i += 1) {
keysToRemove.push(`${this.syncChunkPrefix}${i}`);
}
}
if (keysToRemove.length) {
await chrome.storage.sync.remove(keysToRemove);
}
this._ignoreRemoteSyncUntil = Date.now() + 2000;
await chrome.storage.sync.set({
[this.syncMetaKey]: {
enabled: false,
version: 2,
updatedAt: new Date().toISOString(),
chunkCount: 0,
payloadBytes: 0,
omittedAssets: []
}
});
await this.updateLocalSyncState({
enabled: false,
lastError: ''
});
}
getUtf8ByteLength(value) {
const text = String(value);
if (typeof TextEncoder !== 'undefined') {
if (!this._textEncoder) {
this._textEncoder = new TextEncoder();
}
return this._textEncoder.encode(text).length;
}
if (typeof Blob !== 'undefined') {
return new Blob([text]).size;
}
return text.length;
}
getSyncItemQuotaBytes() {
const quota = this.isSyncAvailable()
? chrome.storage.sync.QUOTA_BYTES_PER_ITEM
: null;
return Number.isFinite(quota) ? quota : 8192;
}
getSyncItemBudgetBytes() {
return Math.max(0, this.getSyncItemQuotaBytes() - 64);
}
getSyncItemBytes(key, value) {
return this.getUtf8ByteLength(key) + this.getUtf8ByteLength(JSON.stringify(value));
}
getSyncItemsBytes(items) {
return Object.entries(items).reduce((total, [key, value]) => {
return total + this.getSyncItemBytes(key, value);
}, 0);
}
createSyncChunks(payloadJson) {
const chunks = [];
let chunk = '';
for (const char of payloadJson) {
const key = `${this.syncChunkPrefix}${chunks.length}`;
const candidate = chunk + char;
if (this.getSyncItemBytes(key, candidate) <= this.getSyncItemBudgetBytes()) {
chunk = candidate;
continue;
}
if (!chunk) {
throw new Error('Cloud sync payload contains an item that is too large for Chrome Sync.');
}
chunks.push(chunk);
if (chunks.length >= this.syncMaxChunks) {
throw new Error('Cloud sync payload needs too many chunks. Remove some shortcuts or use manual export for large data.');
}
chunk = char;
const nextKey = `${this.syncChunkPrefix}${chunks.length}`;
if (this.getSyncItemBytes(nextKey, chunk) > this.getSyncItemBudgetBytes()) {
throw new Error('Cloud sync payload contains an item that is too large for Chrome Sync.');
}
}
chunks.push(chunk);
return chunks;
}
async updateLocalSyncState(partial) {
try {
const current = await chrome.storage.local.get(['sync']);
const next = this.validateSyncConfig({
...(current.sync || this.defaultConfig.sync),
...partial
});
await chrome.storage.local.set({ sync: next });
} catch (error) {
console.warn('Failed to update local sync state:', error);
}
}
prepareSyncPayload(config) {
const source = this.validateConfigObject(config);
const payload = {};
const omittedAssets = [];
for (const key of Object.keys(this.defaultConfig)) {
if (key !== 'sync') {
payload[key] = JSON.parse(JSON.stringify(source[key]));
}
}
if (payload.bg?.type === 'image' && this.isLargeEmbeddedAsset(payload.bg.value)) {
payload.bg = { type: 'gradient', value: '' };
omittedAssets.push('backgroundImage');
}
if (payload.movie?.poster && this.isLargeEmbeddedAsset(payload.movie.poster)) {
payload.movie.poster = '';
omittedAssets.push('moviePoster');
}
if (Array.isArray(payload.links)) {
payload.links = payload.links.map(link => {
if (this.isLargeEmbeddedAsset(link.icon)) {
return { ...link, icon: '🌐' };
}
return link;
});
}
return { payload, omittedAssets };
}
isLargeEmbeddedAsset(value) {
return typeof value === 'string' && (value.startsWith('data:') || value.length > 4000);
}
shouldIgnoreRemoteSyncChange() {
return Date.now() < this._ignoreRemoteSyncUntil;
}
scheduleSyncPush(delayMs = 900) {
if (!this.isSyncAvailable() || this._isApplyingSync) return;
if (this._syncPushTimer) {
clearTimeout(this._syncPushTimer);
}
this._syncPushTimer = setTimeout(async () => {
this._syncPushTimer = null;
try {
if (await this.isSyncEnabledLocally()) {
await this.pushToSync();
}
} catch (error) {
console.warn('Background cloud sync failed:', error);
await this.updateLocalSyncState({
enabled: true,
lastError: error.message || String(error)
});
}
}, delayMs);
}
/**
* Validate data according to schema
* @param {string} key - Storage key
* @param {*} value - Value to validate
* @returns {*} - Validated value
*/
validateData(key, value) {
if (!this.defaultConfig.hasOwnProperty(key)) {
throw new Error(`Invalid storage key: ${key}`);
}
try {
switch (key) {
case 'clock':
return this.validateClockConfig(value);
case 'search':
return this.validateSearchConfig(value);
case 'bg':
return this.validateBackgroundConfig(value);
case 'show':
return this.validateShowConfig(value);
case 'privacy':
return this.validatePrivacyConfig(value);
case 'themePreset':
return this.validateThemePreset(value);
case 'categories':
return this.validateCategoriesConfig(value);
case 'links':
return this.validateLinksConfig(value);
case 'weather':
return this.validateWeatherConfig(value);
case 'hot':
return this.validateHotConfig(value);
case 'movie':
return this.validateMovieConfig(value);
case 'quote':
return this.validateQuoteConfig(value);
case 'layout':
return this.validateLayoutConfig(value);
case 'ui':
return this.validateUiConfig(value);
case 'sync':
return this.validateSyncConfig(value);
default:
return value;
}
} catch (error) {
console.warn(`Validation failed for ${key}, using default:`, error);
return this.getDefaultValue(key);
}
}
/**
* Validate clock configuration
*/
validateClockConfig(value) {
if (typeof value !== 'object' || value === null) {
throw new Error('Clock config must be an object');
}
return {
hour12: typeof value.hour12 === 'boolean' ? value.hour12 : this.defaultConfig.clock.hour12,
showSeconds: typeof value.showSeconds === 'boolean' ? value.showSeconds : this.defaultConfig.clock.showSeconds
};
}
/**
* Validate search configuration
*/
validateSearchConfig(value) {