|
| 1 | +/** |
| 2 | + * Service Worker for External Resource Analytics |
| 3 | + * |
| 4 | + * This service worker intercepts all fetch requests and notifies the main thread |
| 5 | + * about external resource loads. The main thread logs them via Terria's analytics. |
| 6 | + * |
| 7 | + * Configuration is passed via message from the main thread after registration. |
| 8 | + */ |
| 9 | + |
| 10 | +let config = { |
| 11 | + enabled: false, |
| 12 | + // Hostnames to exclude from logging |
| 13 | + excludeHostnames: [], |
| 14 | + // Only log requests to these hostnames (empty = log all external) |
| 15 | + includeHostnames: [], |
| 16 | + // Proxy base URL to extract target hostname from proxied requests |
| 17 | + proxyBaseUrl: null |
| 18 | +}; |
| 19 | + |
| 20 | +/** |
| 21 | + * Extract the target hostname from a URL, handling proxied URLs. |
| 22 | + */ |
| 23 | +function getTargetHostname(url) { |
| 24 | + try { |
| 25 | + const parsed = new URL(url); |
| 26 | + |
| 27 | + // Check if this URL goes through a configured proxy |
| 28 | + if (config.proxyBaseUrl && url.includes(config.proxyBaseUrl)) { |
| 29 | + const proxyIndex = |
| 30 | + url.indexOf(config.proxyBaseUrl) + config.proxyBaseUrl.length; |
| 31 | + let targetUrl = url.substring(proxyIndex); |
| 32 | + |
| 33 | + // Skip optional cache flag (e.g., "_1d/", "_2d/") |
| 34 | + const cacheFlagMatch = targetUrl.match(/^_[^/]+\/(.+)$/); |
| 35 | + if (cacheFlagMatch) { |
| 36 | + targetUrl = cacheFlagMatch[1]; |
| 37 | + } |
| 38 | + |
| 39 | + // Normalize the URL (handle https:/ -> https://) |
| 40 | + const normalizedUrl = targetUrl.replace(/^(https?):\/([^/])/, "$1://$2"); |
| 41 | + return new URL(normalizedUrl).hostname; |
| 42 | + } |
| 43 | + |
| 44 | + return parsed.hostname; |
| 45 | + } catch { |
| 46 | + return "unknown"; |
| 47 | + } |
| 48 | +} |
| 49 | + |
| 50 | +/** |
| 51 | + * Check if a URL is a proxied request. |
| 52 | + */ |
| 53 | +function isProxiedRequest(url) { |
| 54 | + return config.proxyBaseUrl && url.includes(config.proxyBaseUrl); |
| 55 | +} |
| 56 | + |
| 57 | +/** |
| 58 | + * Check if a request should be logged. |
| 59 | + */ |
| 60 | +function shouldLogRequest(url) { |
| 61 | + if (!config.enabled) { |
| 62 | + return false; |
| 63 | + } |
| 64 | + |
| 65 | + try { |
| 66 | + const parsed = new URL(url); |
| 67 | + |
| 68 | + // Skip non-http(s) protocols |
| 69 | + if (!parsed.protocol.startsWith("http")) { |
| 70 | + return false; |
| 71 | + } |
| 72 | + |
| 73 | + // Skip same-origin requests UNLESS they're going through the proxy |
| 74 | + if (parsed.origin === self.location.origin && !isProxiedRequest(url)) { |
| 75 | + return false; |
| 76 | + } |
| 77 | + |
| 78 | + const hostname = getTargetHostname(url); |
| 79 | + |
| 80 | + // Skip excluded hostnames |
| 81 | + if (config.excludeHostnames.some((h) => hostname.includes(h))) { |
| 82 | + return false; |
| 83 | + } |
| 84 | + |
| 85 | + // If includeHostnames is set, only log those |
| 86 | + if (config.includeHostnames.length > 0) { |
| 87 | + return config.includeHostnames.some((h) => hostname.includes(h)); |
| 88 | + } |
| 89 | + |
| 90 | + return true; |
| 91 | + } catch { |
| 92 | + return false; |
| 93 | + } |
| 94 | +} |
| 95 | + |
| 96 | +/** |
| 97 | + * Notify the main thread about an external resource load. |
| 98 | + */ |
| 99 | +async function notifyMainThread(url, success) { |
| 100 | + const hostname = getTargetHostname(url); |
| 101 | + |
| 102 | + // Send message to all clients (main thread) |
| 103 | + const clients = await self.clients.matchAll(); |
| 104 | + clients.forEach((client) => { |
| 105 | + client.postMessage({ |
| 106 | + type: "EXTERNAL_RESOURCE", |
| 107 | + hostname: hostname, |
| 108 | + success: success |
| 109 | + }); |
| 110 | + }); |
| 111 | +} |
| 112 | + |
| 113 | +// Handle messages from the main thread (for configuration) |
| 114 | +self.addEventListener("message", (event) => { |
| 115 | + if (event.data && event.data.type === "ANALYTICS_CONFIG") { |
| 116 | + config = { ...config, ...event.data.config }; |
| 117 | + console.log( |
| 118 | + "[Analytics SW] Configuration updated:", |
| 119 | + config.enabled ? "enabled" : "disabled" |
| 120 | + ); |
| 121 | + } |
| 122 | +}); |
| 123 | + |
| 124 | +// Install event - take control immediately |
| 125 | +self.addEventListener("install", () => { |
| 126 | + self.skipWaiting(); |
| 127 | +}); |
| 128 | + |
| 129 | +// Activate event - claim all clients immediately |
| 130 | +self.addEventListener("activate", (event) => { |
| 131 | + event.waitUntil(self.clients.claim()); |
| 132 | +}); |
| 133 | + |
| 134 | +// Fetch event - intercept all requests |
| 135 | +self.addEventListener("fetch", (event) => { |
| 136 | + const url = event.request.url; |
| 137 | + |
| 138 | + if (!shouldLogRequest(url)) { |
| 139 | + return; // Let the request proceed normally without interception |
| 140 | + } |
| 141 | + |
| 142 | + // Intercept the request to track success/failure |
| 143 | + event.respondWith( |
| 144 | + fetch(event.request) |
| 145 | + .then((response) => { |
| 146 | + notifyMainThread(url, response.ok); |
| 147 | + return response; |
| 148 | + }) |
| 149 | + .catch((error) => { |
| 150 | + notifyMainThread(url, false); |
| 151 | + throw error; |
| 152 | + }) |
| 153 | + ); |
| 154 | +}); |
0 commit comments