'use strict'; // No page/API cache: authenticated games must always come from the server. self.addEventListener('install', event => event.waitUntil(self.skipWaiting())); self.addEventListener('activate', event => event.waitUntil(self.clients.claim())); self.addEventListener('push', event => { let data = {}; try { data = event.data?.json() || {}; } catch (_) {} const game = Number.isSafeInteger(data.game) && data.game > 0 ? data.game : null; event.waitUntil((async () => { // Skip OS notifications while the player is already looking at Microchess. const windows = await self.clients.matchAll({ type: 'window', includeUncontrolled: true }); if (windows.some(client => client.visibilityState === 'visible')) return; await self.registration.showNotification('Microchess', { body: typeof data.body === 'string' ? data.body : 'A game is waiting for you.', icon: new URL('assets/app-icon-192.png', self.registration.scope).href, tag: game ? `game-${game}` : 'microchess', data: { game } }); })()); }); self.addEventListener('notificationclick', event => { event.notification.close(); const url = new URL('./', self.registration.scope); const game = event.notification.data?.game; if (Number.isSafeInteger(game) && game > 0) url.searchParams.set('game', game); event.waitUntil((async () => { const windows = await self.clients.matchAll({ type: 'window', includeUncontrolled: true }); // Navigate the existing app window through the normal login/main-screen flow. const existing = windows.find(client => client.url.startsWith(self.registration.scope)); if (existing) { try { const navigated = await existing.navigate(url.href); if (navigated) return await navigated.focus(); } catch (_) {} } return self.clients.openWindow(url.href); })()); });