|
| 1 | +/* eslint-env worker */ |
| 2 | + |
| 3 | +let connections = {}; |
| 4 | +let messageQueue = []; |
| 5 | +let isProcessingQueue = false; |
| 6 | +let messageCounter = 0; |
| 7 | +const MAX_QUEUE_SIZE = 1000; |
| 8 | +const RATE_LIMIT_INTERVAL = 1000; // 1 second |
| 9 | +const MAX_MESSAGES_PER_INTERVAL = 100; |
| 10 | + |
| 11 | +let heartbeatIntervals = {}; |
| 12 | + |
| 13 | +function logWithTimestamp(message, data) { |
| 14 | + console.log(`[${new Date().toISOString()}] ${message}`, data); |
| 15 | +} |
| 16 | + |
| 17 | +function processMessageQueue() { |
| 18 | + if (isProcessingQueue || messageQueue.length === 0) return; |
| 19 | + |
| 20 | + isProcessingQueue = true; |
| 21 | + const startTime = Date.now(); |
| 22 | + let processedCount = 0; |
| 23 | + |
| 24 | + while (messageQueue.length > 0 && processedCount < MAX_MESSAGES_PER_INTERVAL) { |
| 25 | + const { message, sender, sendResponse } = messageQueue.shift(); |
| 26 | + try { |
| 27 | + handleMessage(message, sender, sendResponse); |
| 28 | + messageCounter++; |
| 29 | + } catch (error) { |
| 30 | + console.error('Error processing message:', error); |
| 31 | + reportError(error); |
| 32 | + } |
| 33 | + processedCount++; |
| 34 | + |
| 35 | + if (Date.now() - startTime >= RATE_LIMIT_INTERVAL) { |
| 36 | + break; |
| 37 | + } |
| 38 | + } |
| 39 | + |
| 40 | + isProcessingQueue = false; |
| 41 | + |
| 42 | + if (messageQueue.length > 0) { |
| 43 | + setTimeout(processMessageQueue, RATE_LIMIT_INTERVAL); |
| 44 | + } |
| 45 | + |
| 46 | + logWithTimestamp(`Processed ${processedCount} messages. Total messages: ${messageCounter}`); |
| 47 | +} |
| 48 | + |
| 49 | +function queueMessage(message, sender, sendResponse) { |
| 50 | + if (messageQueue.length >= MAX_QUEUE_SIZE) { |
| 51 | + logWithTimestamp('Message queue full. Dropping oldest message.'); |
| 52 | + messageQueue.shift(); |
| 53 | + } |
| 54 | + messageQueue.push({ message, sender, sendResponse }); |
| 55 | + processMessageQueue(); |
| 56 | +} |
| 57 | + |
| 58 | +function handleMessage(request, sender, sendResponse) { |
| 59 | + logWithTimestamp('Processing message:', request); |
| 60 | + |
| 61 | + if (sender.tab) { |
| 62 | + const tabId = sender.tab.id; |
| 63 | + if (tabId in connections) { |
| 64 | + if (request.type === 'HTMX_EVENT' || request.type.startsWith('htmx:')) { |
| 65 | + logWithTimestamp(`Forwarding htmx event to panel for tab ${tabId}:`, request); |
| 66 | + connections[tabId].postMessage({ |
| 67 | + type: 'HTMX_EVENT_FOR_PANEL', |
| 68 | + data: request.data, // Ensure we're sending the full data |
| 69 | + }); |
| 70 | + logWithTimestamp(`htmx event sent to panel for tab ${tabId}`); |
| 71 | + } else { |
| 72 | + // Only forward non-CONNECTION_TEST messages to the panel |
| 73 | + if (request.type !== 'CONNECTION_TEST') { |
| 74 | + logWithTimestamp(`Forwarding message to panel for tab ${tabId}:`, request); |
| 75 | + connections[tabId].postMessage(request); |
| 76 | + logWithTimestamp(`Message sent to panel for tab ${tabId}`); |
| 77 | + } else { |
| 78 | + logWithTimestamp(`Received CONNECTION_TEST from tab ${tabId}`); |
| 79 | + } |
| 80 | + } |
| 81 | + } else { |
| 82 | + logWithTimestamp('Tab not found in connection list:', tabId); |
| 83 | + } |
| 84 | + } else if (request.type === 'TEST') { |
| 85 | + logWithTimestamp('Received test message:', request); |
| 86 | + Object.values(connections).forEach((port) => { |
| 87 | + port.postMessage(request); |
| 88 | + logWithTimestamp('Test message sent to panel'); |
| 89 | + }); |
| 90 | + } else { |
| 91 | + logWithTimestamp('sender.tab not defined and not a test message.'); |
| 92 | + } |
| 93 | + |
| 94 | + // Always send a response to avoid timeouts |
| 95 | + if (sendResponse) { |
| 96 | + sendResponse({ status: 'Message processed' }); |
| 97 | + } |
| 98 | +} |
| 99 | + |
| 100 | +function startHeartbeat(tabId) { |
| 101 | + if (heartbeatIntervals[tabId]) { |
| 102 | + clearInterval(heartbeatIntervals[tabId]); |
| 103 | + } |
| 104 | + heartbeatIntervals[tabId] = setInterval(() => { |
| 105 | + // Changed to setInterval (self is already recognized) |
| 106 | + if (connections[tabId]) { |
| 107 | + connections[tabId].postMessage({ type: 'HEARTBEAT' }); |
| 108 | + } else { |
| 109 | + clearInterval(heartbeatIntervals[tabId]); |
| 110 | + delete heartbeatIntervals[tabId]; |
| 111 | + } |
| 112 | + }, 5000); // Send heartbeat every 5 seconds |
| 113 | +} |
| 114 | + |
| 115 | +// Listen for connections from the devtools panel |
| 116 | +chrome.runtime.onConnect.addListener(function (port) { |
| 117 | + if (port.name !== 'panel') return; |
| 118 | + |
| 119 | + const extensionListener = function (message) { |
| 120 | + if (message.name === 'init') { |
| 121 | + connections[message.tabId] = port; |
| 122 | + logWithTimestamp(`Panel connected for tab ${message.tabId}`); |
| 123 | + startHeartbeat(message.tabId); |
| 124 | + } |
| 125 | + }; |
| 126 | + |
| 127 | + port.onMessage.addListener(extensionListener); |
| 128 | + |
| 129 | + port.onDisconnect.addListener(function (disconnectedPort) { |
| 130 | + port.onMessage.removeListener(extensionListener); |
| 131 | + const tabs = Object.keys(connections); |
| 132 | + for (let i = 0, len = tabs.length; i < len; i++) { |
| 133 | + if (connections[tabs[i]] === disconnectedPort) { |
| 134 | + logWithTimestamp(`Panel disconnected for tab ${tabs[i]}`); |
| 135 | + delete connections[tabs[i]]; |
| 136 | + clearInterval(heartbeatIntervals[tabs[i]]); |
| 137 | + delete heartbeatIntervals[tabs[i]]; |
| 138 | + break; |
| 139 | + } |
| 140 | + } |
| 141 | + }); |
| 142 | +}); |
| 143 | + |
| 144 | +// Listen for messages from content scripts |
| 145 | +chrome.runtime.onMessage.addListener(function (request, sender, sendResponse) { |
| 146 | + // Use queueMessage instead of directly calling handleMessage |
| 147 | + queueMessage(request, sender, sendResponse); |
| 148 | + return true; // Indicate that the response is sent asynchronously |
| 149 | +}); |
| 150 | + |
| 151 | +logWithTimestamp('Background service worker loaded'); |
| 152 | + |
| 153 | +// Keep the service worker alive and manage periodic tasks |
| 154 | +chrome.runtime.onInstalled.addListener(() => { |
| 155 | + console.log('Extension installed or updated'); |
| 156 | + chrome.alarms.create('keep-alive', { periodInMinutes: 1 }); |
| 157 | + chrome.alarms.create('reset-counter', { periodInMinutes: 60 }); // Reset counter every hour |
| 158 | + chrome.alarms.create('log-stats', { periodInMinutes: 5 }); // Log stats every 5 minutes |
| 159 | +}); |
| 160 | + |
| 161 | +chrome.runtime.onUpdateAvailable.addListener(() => { |
| 162 | + console.log('Extension update available. Reloading...'); |
| 163 | + chrome.runtime.reload(); |
| 164 | +}); |
| 165 | + |
| 166 | +chrome.alarms.onAlarm.addListener((alarm) => { |
| 167 | + switch (alarm.name) { |
| 168 | + case 'keep-alive': |
| 169 | + logWithTimestamp('Keep-alive ping'); |
| 170 | + break; |
| 171 | + case 'reset-counter': |
| 172 | + logWithTimestamp(`Resetting message counter. Previous count: ${messageCounter}`); |
| 173 | + messageCounter = 0; |
| 174 | + break; |
| 175 | + case 'log-stats': |
| 176 | + logWithTimestamp(`Current message count: ${messageCounter}`); |
| 177 | + logWithTimestamp(`Current queue size: ${messageQueue.length}`); |
| 178 | + break; |
| 179 | + } |
| 180 | +}); |
| 181 | + |
| 182 | +function reportError(error) { |
| 183 | + console.error('Error in background script:', error); |
| 184 | + Object.values(connections).forEach((port) => { |
| 185 | + port.postMessage({ type: 'ERROR', error: error.message, stack: error.stack }); |
| 186 | + }); |
| 187 | +} |
| 188 | + |
| 189 | +// Global error handling |
| 190 | +globalThis.addEventListener('error', (event) => { |
| 191 | + // Changed from self to globalThis |
| 192 | + reportError(event.error); |
| 193 | +}); |
| 194 | + |
| 195 | +globalThis.addEventListener('unhandledrejection', (event) => { |
| 196 | + // Changed from self to globalThis |
| 197 | + reportError(event.reason); |
| 198 | +}); |
| 199 | + |
| 200 | +// Example of avoiding window usage in background script |
| 201 | +chrome.runtime.onInstalled.addListener(() => { |
| 202 | + console.log('Extension installed'); |
| 203 | +}); |
| 204 | + |
| 205 | +// If you need to communicate with content scripts or popup |
| 206 | +chrome.runtime.onMessage.addListener((message, sender, sendResponse) => { |
| 207 | + if (message.type === 'heartbeat') { |
| 208 | + // Handle heartbeat message |
| 209 | + sendResponse({ status: 'alive' }); |
| 210 | + } |
| 211 | + |
| 212 | + if (message.type === 'HTMX_EVENT') { |
| 213 | + chrome.runtime.sendMessage({ |
| 214 | + type: 'HTMX_EVENT_FOR_PANEL', |
| 215 | + data: message.data, |
| 216 | + }); |
| 217 | + } |
| 218 | +}); |
0 commit comments