experiments in a post-browser web
1/**
2 * Sync Extension Background Script
3 *
4 * Provides sync commands and functionality
5 *
6 * Runs in isolated extension process (peek://ext/sync/background.html)
7 */
8
9const api = window.app;
10
11const id = 'sync';
12const labels = {
13 name: 'Sync',
14 description: 'Sync commands and functionality'
15};
16
17console.log('[ext:sync] background', labels.name);
18
19// ===== Command definitions =====
20
21const commandDefinitions = [
22 {
23 name: 'Sync now',
24 description: 'Trigger manual sync with server',
25 execute: async () => {
26 console.log('[sync] Triggering manual sync...');
27
28 // Check if sync API is available
29 if (!api?.sync?.syncAll) {
30 console.error('[sync] Sync API not available');
31 return {
32 success: false,
33 error: 'Sync API not available'
34 };
35 }
36
37 try {
38 const result = await api.sync.syncAll();
39
40 if (result.success) {
41 const { pulled, pushed, conflicts } = result.data || {};
42 console.log('[sync] Sync completed:', result.data);
43
44 let message = 'Sync completed';
45 const details = [];
46 if (pulled) details.push(`${pulled} pulled`);
47 if (pushed) details.push(`${pushed} pushed`);
48 if (conflicts) details.push(`${conflicts} conflicts`);
49 if (details.length) message += `: ${details.join(', ')}`;
50
51 return {
52 success: true,
53 command: 'sync',
54 message,
55 data: result.data
56 };
57 } else {
58 console.error('[sync] Sync failed:', result.error);
59 return {
60 success: false,
61 command: 'sync',
62 error: result.error || 'Sync failed'
63 };
64 }
65 } catch (err) {
66 console.error('[sync] Error during sync:', err);
67 return {
68 success: false,
69 command: 'sync',
70 error: err.message
71 };
72 }
73 }
74 }
75];
76
77// ===== Registration =====
78
79let registeredCommands = [];
80
81const initCommands = () => {
82 commandDefinitions.forEach(cmd => {
83 api.commands.register(cmd);
84 registeredCommands.push(cmd.name);
85 });
86 console.log('[ext:sync] Registered commands:', registeredCommands);
87};
88
89const uninitCommands = () => {
90 registeredCommands.forEach(name => {
91 api.commands.unregister(name);
92 });
93 registeredCommands = [];
94 console.log('[ext:sync] Unregistered commands');
95};
96
97const init = () => {
98 console.log('[ext:sync] init');
99
100 // Wait for cmd:ready before registering commands
101 api.subscribe('cmd:ready', () => {
102 initCommands();
103 }, api.scopes.GLOBAL);
104
105 // Query in case cmd is already ready (it usually is since cmd loads first)
106 api.publish('cmd:query', {}, api.scopes.GLOBAL);
107};
108
109const uninit = () => {
110 console.log('[ext:sync] uninit');
111 uninitCommands();
112};
113
114export default {
115 id,
116 init,
117 uninit,
118 labels
119};