import { setCacheNameDetails, cacheNames } from 'workbox-core' import * as navigationPreload from 'workbox-navigation-preload' import { registerRoute, NavigationRoute } from 'workbox-routing' import { precacheAndRoute, cleanupOutdatedCaches } from 'workbox-precaching' import { StaleWhileRevalidate, NetworkFirst, CacheFirst, CacheOnly, NetworkOnly } from 'workbox-strategies' import 'broadcastchannel-polyfill' import { notificationStore } from './indexdb' import { handlePush } from './push' import { cacheNameDetails, cachesToKeep } from './cache-names' import { SKIP_WAITING } from './update' const ENV = process.env const production = ENV['NODE-ENV'] == 'production' console.log('service-worker started in', ENV['NODE-ENV'], 'mode') const channel = new BroadcastChannel('notification') setCacheNameDetails(cacheNameDetails(ENV['APP-NAME'], ENV['APP-VERSION'])) /* for lifecycle - a new worker waits until a screen asks for it (update.ts) */ addEventListener('message', (event: any) => { if (event.data?.type === SKIP_WAITING) self.skipWaiting() }) /* for production only */ const FALLBACK_CACHE_NAME = 'index-html' const FALLBACK_HTML_URL = '/index.html' addEventListener('install', async event => { event.waitUntil(caches.open(FALLBACK_CACHE_NAME).then(cache => cache.add(FALLBACK_HTML_URL))) }) navigationPreload.enable() addEventListener('activate', event => { const cacheNamesToKeep = cachesToKeep(cacheNames, ['google-fonts', FALLBACK_CACHE_NAME]) event.waitUntil( (async function () { const userCacheNames = await caches.keys() await Promise.all( userCacheNames.map(async cacheName => { if (!cacheNamesToKeep.includes(cacheName)) { return await caches.delete(cacheName) } return await Promise.resolve() }) ) })() ) }) const networkOnly = new NetworkOnly() const navigationHandler = async params => { try { return await networkOnly.handle(params) } catch (error) { console.warn('navigationHandler', error) return caches.match(FALLBACK_HTML_URL, { cacheName: FALLBACK_CACHE_NAME }) } } registerRoute(new NavigationRoute(navigationHandler)) /* for precache */ cleanupOutdatedCaches() precacheAndRoute(self.__WB_MANIFEST || []) /* route registering */ if (production) { /* helps should be Network only for i18n sensitive */ registerRoute(/(.*)helps(.*)\.md/, new NetworkOnly()) registerRoute(/(.*)translations(.*)\.json/, new StaleWhileRevalidate()) registerRoute(({ request }) => request.destination === 'style', new CacheFirst()) registerRoute(({ request }) => request.destination === 'image', new CacheFirst()) registerRoute( ({ url }) => url.origin === 'https://fonts.googleapis.com' || url.origin === 'https://fonts.gstatic.com', new CacheFirst({ cacheName: 'google-fonts' }) ) registerRoute(({ request }) => request.destination === 'script', new CacheFirst()) } else { /* helps should be Network only for i18n sensitive */ registerRoute(/(.*)helps(.*)\.md/, new NetworkOnly()) registerRoute(/(.*)translations(.*)\.json/, new StaleWhileRevalidate()) registerRoute(({ request }) => request.destination === 'style', new NetworkFirst()) registerRoute(({ request }) => request.destination === 'image', new NetworkFirst()) registerRoute( ({ url }) => url.origin === 'https://fonts.googleapis.com' || url.origin === 'https://fonts.gstatic.com', new StaleWhileRevalidate({ cacheName: 'google-fonts' }) ) registerRoute(({ request }) => request.destination === 'script', new NetworkFirst()) } /* for push notification */ addEventListener('push', (event: any) => handlePush(event, { registration, channel, store: notificationStore, tagline: ENV['APP-TAGLINE'] }) ) addEventListener('notificationclick', async event => { const { action, notification } = event notification.close() channel.postMessage({ type: 'notificationclick', action, notification: notification.data }) const { url } = notification.data if (!url) { return } /* * PWA 알림 클릭 처리 정책: * 1) includeUncontrolled — SW 가 아직 controller 가 아닌 윈도우 (방금 설치 / 새로 열린 PWA) 도 * 매칭에 포함. 누락 시 클라가 있어도 못 찾고 fallback 으로 새 브라우저 창이 뜨는 회귀. * 2) 같은 url 이미 열려있으면 그 창 focus. * 3) 같은 origin 의 윈도우 있으면 navigate + focus — 알림 URL 로 이동 보장. 단순 focus * 만 하면 사용자가 보기엔 "아무 일도 안 일어남" + OS 가 브라우저 fallback 띄움. * 4) 매칭 없으면 openWindow — PWA 가 등록된 origin/scope 면 OS 가 자동 PWA 로 라우팅. */ event.waitUntil( (async () => { const list = await clients.matchAll({ type: 'window', includeUncontrolled: true }) for (const c of list) { if (c.url === url && 'focus' in c) { return c.focus() } } for (const c of list) { if (c.url.startsWith(self.location.origin) && 'focus' in c) { if ('navigate' in c) { try { await (c as WindowClient).navigate(url) } catch { /* cross-origin nav 거부 등 — focus 만이라도 */ } } return c.focus() } } return clients.openWindow(url) })() ) })