|
| 1 | +import React, { useEffect } from 'react'; |
| 2 | + |
| 3 | +type RootProps = { |
| 4 | + readonly children: React.ReactNode; |
| 5 | +}; |
| 6 | + |
| 7 | +const CLEANUP_STORAGE_KEY = 'esphome-devices-sw-cleanup'; |
| 8 | +const LEGACY_CACHE_PATTERNS = [/gatsby/i, /workbox/i, /precache/i, /app-shell/i, /offline/i]; |
| 9 | + |
| 10 | +function markCleanupAttempted(): void { |
| 11 | + if (typeof window === 'undefined') { |
| 12 | + return; |
| 13 | + } |
| 14 | + |
| 15 | + try { |
| 16 | + window.localStorage.setItem(CLEANUP_STORAGE_KEY, new Date().toISOString()); |
| 17 | + } catch (error) { |
| 18 | + console.warn('Unable to persist service worker cleanup marker', error); |
| 19 | + } |
| 20 | +} |
| 21 | + |
| 22 | +async function unregisterLegacyServiceWorkers(): Promise<void> { |
| 23 | + if (typeof window === 'undefined') { |
| 24 | + return; |
| 25 | + } |
| 26 | + |
| 27 | + try { |
| 28 | + if ('serviceWorker' in navigator) { |
| 29 | + const registrations = await navigator.serviceWorker.getRegistrations(); |
| 30 | + await Promise.all( |
| 31 | + registrations.map(async (registration) => { |
| 32 | + try { |
| 33 | + await registration.unregister(); |
| 34 | + } catch (error) { |
| 35 | + console.error('Failed to unregister service worker', error); |
| 36 | + } |
| 37 | + }), |
| 38 | + ); |
| 39 | + } |
| 40 | + |
| 41 | + if ('caches' in window) { |
| 42 | + const cacheNames = await caches.keys(); |
| 43 | + const legacyCaches = cacheNames.filter((cacheName) => |
| 44 | + LEGACY_CACHE_PATTERNS.some((pattern) => pattern.test(cacheName)), |
| 45 | + ); |
| 46 | + |
| 47 | + await Promise.all( |
| 48 | + legacyCaches.map(async (cacheName) => { |
| 49 | + try { |
| 50 | + await caches.delete(cacheName); |
| 51 | + } catch (error) { |
| 52 | + console.error(`Failed to delete cache ${cacheName}`, error); |
| 53 | + } |
| 54 | + }), |
| 55 | + ); |
| 56 | + } |
| 57 | + |
| 58 | + markCleanupAttempted(); |
| 59 | + } catch (error) { |
| 60 | + console.error('Legacy service worker cleanup failed', error); |
| 61 | + } |
| 62 | +} |
| 63 | + |
| 64 | +export default function Root({ children }: RootProps): JSX.Element { |
| 65 | + useEffect(() => { |
| 66 | + if (typeof window === 'undefined') { |
| 67 | + return; |
| 68 | + } |
| 69 | + void unregisterLegacyServiceWorkers(); |
| 70 | + }, []); |
| 71 | + |
| 72 | + return <>{children}</>; |
| 73 | +} |
| 74 | + |
0 commit comments