-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbackground.core.js
More file actions
4907 lines (4328 loc) · 169 KB
/
background.core.js
File metadata and controls
4907 lines (4328 loc) · 169 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
console.log('[ScriptVault] Service worker starting...');
// ============================================================================
// Userscript Parser
// ============================================================================
function parseUserscript(code) {
const metaBlockMatch = code.match(/\/\/\s*==UserScript==([\s\S]*?)\/\/\s*==\/UserScript==/);
if (!metaBlockMatch) {
return { error: 'No metadata block found. Scripts must include ==UserScript== header.' };
}
const meta = {
name: 'Unnamed Script',
namespace: 'scriptvault',
version: '1.0.0',
description: '',
author: '',
match: [],
include: [],
exclude: [],
excludeMatch: [],
grant: [],
require: [],
resource: {},
'run-at': 'document-idle',
noframes: false,
icon: '',
icon64: '',
homepage: '',
homepageURL: '',
website: '',
source: '',
updateURL: '',
downloadURL: '',
supportURL: '',
connect: [],
antifeature: [],
unwrap: false,
'inject-into': 'auto',
sandbox: '',
tag: [],
'run-in': '',
'top-level-await': false,
license: '',
copyright: '',
priority: 0
};
const metaBlock = metaBlockMatch[1];
const lines = metaBlock.split('\n');
for (const line of lines) {
const match = line.match(/\/\/\s*@(\S+)(?:\s+(.*))?/);
if (!match) continue;
const key = match[1].trim();
const value = (match[2] || '').trim();
switch (key) {
case 'name':
case 'namespace':
case 'version':
case 'description':
case 'author':
case 'icon':
case 'icon64':
case 'homepage':
case 'homepageURL':
case 'website':
case 'source':
case 'updateURL':
case 'downloadURL':
case 'supportURL':
case 'run-at':
case 'inject-into':
case 'sandbox':
case 'run-in':
case 'license':
case 'copyright':
meta[key] = value;
break;
case 'match':
case 'include':
case 'exclude':
case 'exclude-match':
case 'excludeMatch':
case 'grant':
case 'require':
case 'connect':
case 'antifeature':
case 'tag':
const arrayKey = key === 'exclude-match' ? 'excludeMatch' : key;
if (!meta[arrayKey]) meta[arrayKey] = [];
if (value) meta[arrayKey].push(value);
break;
case 'resource':
const resourceMatch = value.match(/^(\S+)\s+(.+)$/);
if (resourceMatch) {
meta.resource[resourceMatch[1]] = resourceMatch[2];
}
break;
case 'noframes':
meta.noframes = true;
break;
case 'unwrap':
meta.unwrap = true;
break;
case 'top-level-await':
meta['top-level-await'] = true;
break;
case 'priority':
meta.priority = parseInt(value, 10) || 0;
break;
default:
// Handle localized metadata like @name:ja
if (key.includes(':')) {
const [baseKey, locale] = key.split(':');
if (!meta.localized) meta.localized = {};
if (!meta.localized[locale]) meta.localized[locale] = {};
meta.localized[locale][baseKey] = value;
}
}
}
// Default grant if none specified
if (meta.grant.length === 0) {
meta.grant = ['none'];
}
return { meta, code, metaBlock: metaBlockMatch[0] };
}
// ============================================================================
// URL Matching
// ============================================================================
// ============================================================================
// Update System
// ============================================================================
const UpdateSystem = {
async checkForUpdates(scriptId = null) {
const scripts = scriptId
? [await ScriptStorage.get(scriptId)].filter(Boolean)
: await ScriptStorage.getAll();
const updates = [];
for (const script of scripts) {
if (!script.meta.updateURL && !script.meta.downloadURL) continue;
try {
const updateUrl = script.meta.updateURL || script.meta.downloadURL;
const headers = {};
// Conditional request using stored etag/last-modified
if (script._httpEtag) headers['If-None-Match'] = script._httpEtag;
if (script._httpLastModified) headers['If-Modified-Since'] = script._httpLastModified;
const response = await fetch(updateUrl, { headers });
// 304 Not Modified - no update needed
if (response.status === 304) continue;
if (!response.ok) continue;
// Store HTTP cache headers for next check
const etag = response.headers.get('etag');
const lastModified = response.headers.get('last-modified');
if (etag || lastModified) {
script._httpEtag = etag || '';
script._httpLastModified = lastModified || '';
await ScriptStorage.set(script.id, script);
}
const newCode = await response.text();
const parsed = parseUserscript(newCode);
if (parsed.error) continue;
if (this.compareVersions(parsed.meta.version, script.meta.version) > 0) {
updates.push({
id: script.id,
name: script.meta.name,
currentVersion: script.meta.version,
newVersion: parsed.meta.version,
code: newCode
});
}
} catch (e) {
console.error('[ScriptVault] Update check failed for:', script.meta.name, e);
}
}
return updates;
},
compareVersions(v1, v2) {
const parts1 = v1.split('.').map(Number);
const parts2 = v2.split('.').map(Number);
for (let i = 0; i < Math.max(parts1.length, parts2.length); i++) {
const p1 = parts1[i] || 0;
const p2 = parts2[i] || 0;
if (p1 > p2) return 1;
if (p1 < p2) return -1;
}
return 0;
},
async applyUpdate(scriptId, newCode) {
const script = await ScriptStorage.get(scriptId);
if (!script) return { error: 'Script not found' };
const parsed = parseUserscript(newCode);
if (parsed.error) return parsed;
// Store previous version for rollback (keep last 3)
if (!script.versionHistory) script.versionHistory = [];
script.versionHistory.push({
version: script.meta.version,
code: script.code,
updatedAt: script.updatedAt || Date.now()
});
// Trim to last 3 versions
if (script.versionHistory.length > 3) {
script.versionHistory = script.versionHistory.slice(-3);
}
script.code = newCode;
script.meta = parsed.meta;
script.updatedAt = Date.now();
await ScriptStorage.set(scriptId, script);
// Re-register so updated code takes effect immediately
try {
await unregisterScript(scriptId);
if (script.enabled !== false) {
await registerScript(script);
}
} catch (regError) {
console.error(`[ScriptVault] Failed to re-register ${script.meta.name} after update:`, regError);
}
const settings = await SettingsManager.get();
if (settings.notifyOnUpdate) {
chrome.notifications.create({
type: 'basic',
iconUrl: 'images/icon128.png',
title: 'Script Updated',
message: `${script.meta.name} updated to v${script.meta.version}`
});
}
return { success: true, script };
},
async autoUpdate() {
const settings = await SettingsManager.get();
if (!settings.autoUpdate) return;
const updates = await this.checkForUpdates();
for (const update of updates) {
await this.applyUpdate(update.id, update.code);
}
await SettingsManager.set('lastUpdateCheck', Date.now());
}
};
// ============================================================================
// Cloud Sync
// ============================================================================
const CloudSync = {
// Use providers from imported CloudSyncProviders module
get providers() {
return CloudSyncProviders;
},
async sync() {
const settings = await SettingsManager.get();
if (!settings.syncEnabled || settings.syncProvider === 'none') return;
const provider = this.providers[settings.syncProvider];
if (!provider) return;
try {
// Get local data
const scripts = await ScriptStorage.getAll();
const localData = {
version: 1,
timestamp: Date.now(),
scripts: scripts.map(s => ({
id: s.id,
code: s.code,
enabled: s.enabled,
position: s.position,
updatedAt: s.updatedAt
}))
};
// Get remote data
const remoteData = await provider.download(settings);
if (remoteData) {
// Merge: prefer newer versions
const merged = this.mergeData(localData, remoteData);
// Apply merged data locally
for (const script of merged.scripts) {
const existing = await ScriptStorage.get(script.id);
if (!existing || script.updatedAt > existing.updatedAt) {
const parsed = parseUserscript(script.code);
if (!parsed.error) {
await ScriptStorage.set(script.id, {
id: script.id,
code: script.code,
meta: parsed.meta,
enabled: script.enabled,
position: script.position,
updatedAt: script.updatedAt,
createdAt: existing?.createdAt || script.updatedAt
});
}
}
}
// Upload merged data
merged.timestamp = Date.now();
await provider.upload(merged, settings);
} else {
// First sync, just upload
await provider.upload(localData, settings);
}
await SettingsManager.set('lastSync', Date.now());
return { success: true };
} catch (e) {
console.error('[ScriptVault] Sync failed:', e);
return { error: e.message };
}
},
mergeData(local, remote) {
const scriptsMap = new Map();
// Add all local scripts
for (const script of local.scripts) {
scriptsMap.set(script.id, script);
}
// Merge remote scripts (prefer newer)
for (const script of remote.scripts) {
const existing = scriptsMap.get(script.id);
if (!existing || script.updatedAt > existing.updatedAt) {
scriptsMap.set(script.id, script);
}
}
return {
version: 1,
timestamp: Date.now(),
scripts: Array.from(scriptsMap.values())
};
}
};
// ============================================================================
// Import/Export
// ============================================================================
async function exportAllScripts() {
const scripts = await ScriptStorage.getAll();
const settings = await SettingsManager.get();
return {
version: 2,
exportedAt: new Date().toISOString(),
settings: settings,
scripts: scripts.map(s => ({
id: s.id,
code: s.code,
enabled: s.enabled,
position: s.position,
createdAt: s.createdAt,
updatedAt: s.updatedAt
}))
};
}
async function importScripts(data, options = {}) {
const { overwrite = false } = options;
const results = { imported: 0, skipped: 0, errors: [] };
if (!data.scripts || !Array.isArray(data.scripts)) {
return { error: 'Invalid import format' };
}
for (const script of data.scripts) {
try {
const parsed = parseUserscript(script.code);
if (parsed.error) {
results.errors.push({ name: script.id, error: parsed.error });
continue;
}
const existing = await ScriptStorage.get(script.id);
if (existing && !overwrite) {
results.skipped++;
continue;
}
await ScriptStorage.set(script.id, {
id: script.id,
code: script.code,
meta: parsed.meta,
enabled: script.enabled ?? true,
position: script.position ?? 0,
createdAt: script.createdAt || Date.now(),
updatedAt: script.updatedAt || Date.now()
});
results.imported++;
} catch (e) {
results.errors.push({ name: script.id, error: e.message });
}
}
// Import settings if present
if (data.settings && options.importSettings) {
await SettingsManager.set(data.settings);
}
// Re-register all scripts after import
await registerAllScripts();
return results;
}
// Export to ZIP (Tampermonkey-compatible format)
async function exportToZip() {
const scripts = await ScriptStorage.getAll();
const files = {}; // fflate uses { filename: Uint8Array } format
const usedNames = new Set();
for (const script of scripts) {
// Create safe filename, deduplicating collisions
let safeName = (script.meta.name || 'unnamed')
.replace(/[<>:"/\\|?*]/g, '_')
.replace(/\s+/g, ' ')
.trim()
.substring(0, 100);
if (usedNames.has(safeName)) {
let counter = 2;
while (usedNames.has(`${safeName}_${counter}`)) counter++;
safeName = `${safeName}_${counter}`;
}
usedNames.add(safeName);
// Add the userscript file
files[`${safeName}.user.js`] = fflate.strToU8(script.code);
// Add options.json (Tampermonkey format)
const options = {
settings: {
enabled: script.enabled,
'run-at': script.meta['run-at'] || 'document-idle',
override: {
use_includes: [],
use_matches: [],
use_excludes: [],
use_connects: [],
merge_includes: true,
merge_matches: true,
merge_excludes: true,
merge_connects: true
}
},
meta: {
name: script.meta.name,
namespace: script.meta.namespace || '',
version: script.meta.version || '1.0',
description: script.meta.description || '',
author: script.meta.author || '',
match: script.meta.match || [],
include: script.meta.include || [],
exclude: script.meta.exclude || [],
grant: script.meta.grant || [],
require: script.meta.require || [],
resource: script.meta.resource || {}
}
};
files[`${safeName}.options.json`] = fflate.strToU8(JSON.stringify(options, null, 2));
// Add storage.json if script has stored values
const values = await ScriptValues.getAll(script.id);
if (values && Object.keys(values).length > 0) {
const storage = { data: values };
files[`${safeName}.storage.json`] = fflate.strToU8(JSON.stringify(storage, null, 2));
}
}
// Generate zip as Uint8Array then convert to base64 in chunks (avoid stack overflow)
const zipData = fflate.zipSync(files, { level: 6 });
let binary = '';
const chunkSize = 8192;
for (let i = 0; i < zipData.length; i += chunkSize) {
binary += String.fromCharCode.apply(null, zipData.subarray(i, i + chunkSize));
}
const base64 = btoa(binary);
return { zipData: base64, filename: `scriptvault-backup-${new Date().toISOString().replace(/[:.]/g, '-')}.zip` };
}
// Import from ZIP (supports Tampermonkey and other formats)
async function importFromZip(zipData, options = {}) {
const results = { imported: 0, skipped: 0, errors: [] };
try {
// Convert base64 to Uint8Array if needed
let zipBytes;
if (typeof zipData === 'string') {
// Base64 string
const binaryString = atob(zipData);
zipBytes = new Uint8Array(binaryString.length);
for (let i = 0; i < binaryString.length; i++) {
zipBytes[i] = binaryString.charCodeAt(i);
}
} else if (zipData instanceof ArrayBuffer) {
zipBytes = new Uint8Array(zipData);
} else {
zipBytes = zipData;
}
// Load the zip file using fflate
const unzipped = fflate.unzipSync(zipBytes);
const fileNames = Object.keys(unzipped);
// Find all .user.js files
const userScripts = fileNames.filter(name => name.endsWith('.user.js'));
const allExistingScripts = await ScriptStorage.getAll();
for (const filename of userScripts) {
try {
const code = fflate.strFromU8(unzipped[filename]);
// Validate it's a userscript
if (!code.includes('==UserScript==')) {
results.errors.push({ name: filename, error: 'Not a valid userscript' });
continue;
}
const parsed = parseUserscript(code);
if (parsed.error) {
results.errors.push({ name: filename, error: parsed.error });
continue;
}
// Check for existing script with same name/namespace
const existing = allExistingScripts.find(s =>
s.meta.name === parsed.meta.name &&
(s.meta.namespace === parsed.meta.namespace || (!s.meta.namespace && !parsed.meta.namespace))
);
if (existing && !options.overwrite) {
results.skipped++;
continue;
}
// Look for associated options and storage files
const baseName = filename.replace('.user.js', '');
const optionsFileData = unzipped[`${baseName}.options.json`];
const storageFileData = unzipped[`${baseName}.storage.json`];
let enabled = true;
let storedValues = {};
// Parse options file if exists
if (optionsFileData) {
try {
const optionsData = JSON.parse(fflate.strFromU8(optionsFileData));
enabled = optionsData.settings?.enabled !== false;
} catch (e) {
console.warn('Failed to parse options file:', e);
}
}
// Parse storage file if exists
if (storageFileData) {
try {
const storageData = JSON.parse(fflate.strFromU8(storageFileData));
storedValues = storageData.data || storageData || {};
} catch (e) {
console.warn('Failed to parse storage file:', e);
}
}
// Create or update script
const scriptId = existing?.id || generateId();
const script = {
id: scriptId,
code: code,
meta: parsed.meta,
enabled: enabled,
position: existing?.position ?? (await ScriptStorage.getAll()).length,
createdAt: existing?.createdAt || Date.now(),
updatedAt: Date.now()
};
await ScriptStorage.set(scriptId, script);
// Import stored values
if (Object.keys(storedValues).length > 0) {
await ScriptValues.setAll(scriptId, storedValues);
}
results.imported++;
} catch (e) {
results.errors.push({ name: filename, error: e.message });
}
}
// If no .user.js files found, try importing raw JS files
if (userScripts.length === 0) {
const jsFiles = fileNames.filter(name =>
name.endsWith('.js') && !name.includes('/')
);
for (const filename of jsFiles) {
try {
const code = fflate.strFromU8(unzipped[filename]);
if (!code.includes('==UserScript==')) continue;
const parsed = parseUserscript(code);
if (parsed.error) continue;
const scriptId = generateId();
await ScriptStorage.set(scriptId, {
id: scriptId,
code: code,
meta: parsed.meta,
enabled: true,
position: (await ScriptStorage.getAll()).length,
createdAt: Date.now(),
updatedAt: Date.now()
});
results.imported++;
} catch (e) {
results.errors.push({ name: filename, error: e.message });
}
}
}
await updateBadge();
// Re-register all scripts after import
await registerAllScripts();
return results;
} catch (e) {
console.error('[ScriptVault] importFromZip error:', e);
return { ...results, error: e.message };
}
}
// ============================================================================
// Message Handlers
// ============================================================================
// Regular message listener (content scripts, popup, dashboard)
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
handleMessage(message, sender)
.then(sendResponse)
.catch(e => {
console.error('[ScriptVault] Unhandled message error:', e);
sendResponse({ error: e.message });
});
return true;
});
// USER_SCRIPT world message listener (for GM_* APIs)
// This is SEPARATE from onMessage and required for messaging: true to work
if (chrome.runtime.onUserScriptMessage) {
chrome.runtime.onUserScriptMessage.addListener((message, sender, sendResponse) => {
handleMessage(message, sender)
.then(sendResponse)
.catch(e => {
console.error('[ScriptVault] Unhandled user script message error:', e);
sendResponse({ error: e.message });
});
return true;
});
console.log('[ScriptVault] User script message listener registered');
}
async function handleMessage(message, sender) {
const { action } = message;
// Support both patterns: { action, data: { ... } } and { action, prop1, prop2, ... }
const data = message.data || message;
try {
switch (action) {
// Script Management
case 'getScripts': {
const scripts = await ScriptStorage.getAll();
// Convert meta -> metadata for dashboard compatibility
return { scripts: scripts.map(s => ({ ...s, metadata: s.meta })) };
}
case 'getScript': {
const script = await ScriptStorage.get(data.id);
if (script) {
return { ...script, metadata: script.meta };
}
return null;
}
case 'saveScript': {
const parsed = parseUserscript(data.code);
if (parsed.error) return { error: parsed.error };
const id = data.id || data.scriptId || generateId();
const existing = await ScriptStorage.get(id);
const script = {
...existing,
id,
code: data.code,
meta: parsed.meta,
enabled: data.enabled !== undefined ? data.enabled : (existing?.enabled ?? true),
settings: existing?.settings || {},
position: existing?.position ?? (await ScriptStorage.getAll()).length,
createdAt: existing?.createdAt || Date.now(),
updatedAt: Date.now()
};
await ScriptStorage.set(id, script);
await updateBadge();
await autoReloadMatchingTabs(script);
// Re-register the script with userScripts API
await unregisterScript(id);
if (script.enabled) {
await registerScript(script);
}
const settings = await SettingsManager.get();
if (!existing && settings.notifyOnInstall) {
chrome.notifications.create({
type: 'basic',
iconUrl: 'images/icon128.png',
title: 'Script Installed',
message: `${script.meta.name} v${script.meta.version}`
});
}
// Return with metadata property for dashboard compatibility
return { success: true, scriptId: id, script: { ...script, metadata: script.meta } };
}
case 'createScript': {
// Create a new script - similar to saveScript but always generates new ID
const parsed = parseUserscript(data.code);
if (parsed.error) return { error: parsed.error };
const id = generateId();
const script = {
id,
code: data.code,
meta: parsed.meta,
enabled: true,
position: (await ScriptStorage.getAll()).length,
createdAt: Date.now(),
updatedAt: Date.now()
};
await ScriptStorage.set(id, script);
await updateBadge();
// Register the new script
await registerScript(script);
const settings = await SettingsManager.get();
if (settings.notifyOnInstall) {
chrome.notifications.create({
type: 'basic',
iconUrl: 'images/icon128.png',
title: 'Script Created',
message: `${script.meta.name} v${script.meta.version}`
});
}
// Return scriptId for dashboard compatibility
return { success: true, scriptId: id, script: { ...script, metadata: script.meta } };
}
case 'deleteScript': {
const scriptId = data.id || data.scriptId;
if (!scriptId) return { error: 'No script ID provided' };
const settings = await SettingsManager.get();
const trashMode = settings.trashMode || '30';
if (trashMode !== 'disabled') {
// Move to trash instead of permanent delete
const script = await ScriptStorage.get(scriptId);
if (script) {
const trashData = await chrome.storage.local.get('trash');
const trash = trashData.trash || [];
trash.push({ ...script, trashedAt: Date.now() });
await chrome.storage.local.set({ trash });
}
}
await unregisterScript(scriptId);
await ScriptStorage.delete(scriptId);
await updateBadge();
return { success: true };
}
case 'getTrash': {
const trashData = await chrome.storage.local.get('trash');
const trash = trashData.trash || [];
// Clean expired entries
const settings = await SettingsManager.get();
const trashMode = settings.trashMode || '30';
const maxAge = trashMode === '1' ? 86400000 : trashMode === '7' ? 604800000 : trashMode === '30' ? 2592000000 : 0;
const now = Date.now();
const valid = maxAge > 0 ? trash.filter(s => now - s.trashedAt < maxAge) : trash;
if (valid.length !== trash.length) {
await chrome.storage.local.set({ trash: valid });
}
return { trash: valid };
}
case 'restoreFromTrash': {
const scriptId = data.scriptId;
const trashData = await chrome.storage.local.get('trash');
const trash = trashData.trash || [];
const idx = trash.findIndex(s => s.id === scriptId);
if (idx === -1) return { error: 'Not found in trash' };
const script = trash[idx];
delete script.trashedAt;
trash.splice(idx, 1);
await chrome.storage.local.set({ trash });
await ScriptStorage.set(script.id, script);
if (script.enabled) await registerScript(script);
await updateBadge();
return { success: true };
}
case 'emptyTrash': {
await chrome.storage.local.set({ trash: [] });
return { success: true };
}
case 'restart': {
chrome.runtime.reload();
return { success: true };
}
case 'permanentlyDelete': {
const scriptId = data.scriptId;
const trashData = await chrome.storage.local.get('trash');
const trash = trashData.trash || [];
const filtered = trash.filter(s => s.id !== scriptId);
await chrome.storage.local.set({ trash: filtered });
return { success: true };
}
case 'toggleScript': {
const scriptId = data.id || data.scriptId;
const script = await ScriptStorage.get(scriptId);
if (script) {
script.enabled = data.enabled;
script.updatedAt = Date.now();
await ScriptStorage.set(scriptId, script);
// Update userScripts registration
await unregisterScript(scriptId);
if (script.enabled) {
await registerScript(script);
}
await updateBadge();
await autoReloadMatchingTabs(script);
}
return { success: true };
}
case 'importScript': {
const parsed = parseUserscript(data.code);
if (parsed.error) return { error: parsed.error };
const id = generateId();
const script = {
id,
code: data.code,
meta: parsed.meta,
enabled: true,
position: (await ScriptStorage.getAll()).length,
createdAt: Date.now(),
updatedAt: Date.now()
};
await ScriptStorage.set(id, script);
await registerScript(script);
await updateBadge();
// Return with metadata property for dashboard compatibility
return { success: true, script: { ...script, metadata: script.meta } };
}
case 'duplicateScript': {
const newScript = await ScriptStorage.duplicate(data.id);
if (newScript) {
await registerScript(newScript);
await updateBadge();
// Return with metadata property for dashboard compatibility
return { success: true, script: { ...newScript, metadata: newScript.meta } };
}
return { error: 'Script not found' };
}
case 'searchScripts': {
const scripts = await ScriptStorage.search(data.query);
return { scripts: scripts.map(s => ({ ...s, metadata: s.meta })) };
}
case 'reorderScripts':
await ScriptStorage.reorder(data.orderedIds);
return { success: true };
// Script Values
case 'GM_getValue':
return await ScriptValues.get(data.scriptId, data.key, data.defaultValue);
case 'GM_setValue':
return await ScriptValues.set(data.scriptId, data.key, data.value);
case 'GM_deleteValue':
case 'deleteScriptValue':
await ScriptValues.delete(data.scriptId, data.key);
return { success: true };
case 'GM_listValues':
return await ScriptValues.list(data.scriptId);
case 'GM_getValues':
return await ScriptValues.getAll(data.scriptId);
case 'GM_setValues':
await ScriptValues.setAll(data.scriptId, data.values);
return { success: true };
case 'GM_deleteValues':
await ScriptValues.deleteMultiple(data.scriptId, data.keys);
return { success: true };
case 'getScriptStorage':
case 'getScriptValues': {
const values = await ScriptValues.getAll(data.scriptId);
return { values };
}
case 'setScriptStorage':
await ScriptValues.setAll(data.scriptId, data.values);
return { success: true };
case 'getStorageSize':
return await ScriptValues.getStorageSize(data.scriptId);
// Tab Storage
case 'GM_getTab':
return TabStorage.get(sender.tab?.id);
case 'GM_saveTab':
TabStorage.set(sender.tab?.id, data.data);
return { success: true };
case 'GM_getTabs':
return TabStorage.getAll();
// Settings
case 'prefetchResources': {
await ResourceCache.prefetchResources(data.resources);
return { success: true };
}
case 'getSettings': {
const settings = await SettingsManager.get();
return { settings };
}
case 'getSetting':
return await SettingsManager.get(data.key);
case 'setSettings': {
const oldSettings = await SettingsManager.get();
const result = await SettingsManager.set(data.settings);
const changed = data.settings;