sw.ts 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161
  1. /// <reference lib="webworker" />
  2. /**
  3. * NetPulse — Service Worker propio (vite-plugin-pwa `injectManifest`).
  4. *
  5. * ¿Por qué injectManifest y no generateSW + importScripts?
  6. * generateSW no admite handlers custom (Web Push exige `push` y
  7. * `notificationclick`). La alternativa "mínima" (importScripts de un
  8. * push-sw.js estático en public/) dejaba la lógica push fuera del build TS
  9. * (sin type-check, sin minificar, archivo separado que versionar a mano) y
  10. * además ese archivo caía dentro del propio glob de precache. Con
  11. * injectManifest el SW es un único bundle TS versionado y el precache
  12. * app-shell se inyecta en self.__WB_MANIFEST con los mismos globPatterns
  13. * de siempre (16 entradas).
  14. */
  15. import { clientsClaim } from 'workbox-core'
  16. import { cleanupOutdatedCaches, precacheAndRoute } from 'workbox-precaching'
  17. import { NavigationRoute, registerRoute } from 'workbox-routing'
  18. import { NetworkFirst } from 'workbox-strategies'
  19. import { localizePush, pushLang, type PushCatalog } from '@/lib/push-i18n'
  20. declare let self: ServiceWorkerGlobalScope
  21. // registerType: 'autoUpdate' — el SW nuevo toma el control sin esperar al
  22. // cierre de pestañas (equivale al comportamiento anterior con generateSW).
  23. self.skipWaiting()
  24. clientsClaim()
  25. // Punto de inyección de workbox-build: el literal `self.__WB_MANIFEST` se
  26. // sustituye por el manifiesto de precache en el build (no refactorizar).
  27. precacheAndRoute(self.__WB_MANIFEST)
  28. cleanupOutdatedCaches()
  29. // App-shell offline para navegaciones (equivale a `navigateFallback:
  30. // 'index.html'` de generateSW). En dev NO se registra: el SW de desarrollo
  31. // no precachea index.html y esta ruta serviría un HTML congelado.
  32. // FORK: except where a navigation is meant to reach the server itself - the
  33. // root certificate, the fingerprint, and API downloads (CSV exports, the
  34. // backup). Served from here they turned into the app's "page not found".
  35. if (!import.meta.env.DEV) {
  36. // #1214: las navegaciones van NETWORK-FIRST (con fallback corto de 3s) en
  37. // vez del precache cache-first. Con createHandlerBoundToURL('/index.html')
  38. // el SW servía el index.html PRECACHEADO aunque el servidor ya publicara
  39. // uno nuevo: el navegador del usuario se quedaba con la UI vieja
  40. // indefinidamente (los hashes viejos desaparecían del servidor y la app
  41. // "no se actualizaba" hasta que el SW se reinstalaba a su ritmo). Ahora un
  42. // reload normal ya trae la UI nueva; si no hay red, cae al index.html del
  43. // precache y la app sigue abriendo offline.
  44. const nav = new NetworkFirst({ cacheName: 'np-nav-v1', networkTimeoutSeconds: 3 })
  45. registerRoute(
  46. new NavigationRoute(
  47. async (params) => {
  48. try {
  49. return await nav.handle(params)
  50. } catch {
  51. const cached = await caches.match('/index.html')
  52. return cached ?? Response.error()
  53. }
  54. },
  55. { denylist: [/^\/api\//, /^\/netpulse-ca\./, /^\/fingerprint$/, /^\/health$/] },
  56. ),
  57. )
  58. }
  59. // ---------------------------------------------------------------------------
  60. // Web Push (SPEC-PUSH §2)
  61. // Payload: {title, body, type, vars, category, severity, url:"/alerts", tag}
  62. // ---------------------------------------------------------------------------
  63. interface PushPayload {
  64. title?: string
  65. body?: string
  66. /** slug estable del tipo de alerta (#689); permite traducir en el SW */
  67. type?: string
  68. /** variables de interpolación del tipo (#689) */
  69. vars?: Record<string, string>
  70. category?: string
  71. severity?: string
  72. url?: string
  73. tag?: string
  74. hint?: string
  75. }
  76. const I18N_CACHE = 'netpulse-i18n-v1'
  77. /**
  78. * Catálogo de traducciones del idioma dado, cache-first (#689). Los locales
  79. * viven en public/ y se sirven como estáticos; el SW los cachea la primera vez
  80. * para no depender de la red en cada push.
  81. */
  82. async function pushCatalog(lang: 'es' | 'en' | 'zh' | 'ru'): Promise<PushCatalog | null> {
  83. const url = `/locales/${lang}/translation.json`
  84. try {
  85. const cache = await caches.open(I18N_CACHE)
  86. let res = await cache.match(url)
  87. if (!res) {
  88. res = await fetch(url)
  89. if (res.ok) await cache.put(url, res.clone())
  90. }
  91. if (!res || !res.ok) return null
  92. return (await res.json()) as PushCatalog
  93. } catch {
  94. return null
  95. }
  96. }
  97. self.addEventListener('push', (event: PushEvent) => {
  98. event.waitUntil(onPush(event))
  99. })
  100. async function onPush(event: PushEvent): Promise<void> {
  101. let payload: PushPayload = {}
  102. try {
  103. if (event.data) payload = event.data.json() as PushPayload
  104. } catch {
  105. // Payload no-JSON: notificación genérica (nunca romper el handler)
  106. payload = {}
  107. }
  108. let title = payload.title || 'NetPulse'
  109. let body = [payload.body, payload.hint].filter(Boolean).join('\n')
  110. // #689: si el evento trae el slug del tipo, traduce al idioma del dispositivo
  111. // (catálogo de la app); si falla, se conservan los literales del server.
  112. if (payload.type) {
  113. const catalog = await pushCatalog(pushLang(navigator.language))
  114. const loc = localizePush(catalog, payload.type, payload.vars, {
  115. title: payload.title,
  116. body: payload.body,
  117. hint: payload.hint,
  118. })
  119. title = loc.title
  120. body = [loc.body, loc.hint].filter(Boolean).join('\n')
  121. }
  122. await self.registration.showNotification(title, {
  123. body,
  124. icon: '/icon-192.png',
  125. badge: '/icon-192.png',
  126. // tag = dedup nativo del navegador (SPEC: tag = id del evento)
  127. tag: payload.tag ?? 'netpulse-alert',
  128. data: { url: payload.url ?? '/alerts' },
  129. })
  130. }
  131. self.addEventListener('notificationclick', (event: NotificationEvent) => {
  132. event.notification.close()
  133. const url = (event.notification.data as { url?: string } | undefined)?.url ?? '/alerts'
  134. event.waitUntil(focusOrOpen(url))
  135. })
  136. /** Foco a una ventana ya abierta de la app (navegándola a `url`) o abre una nueva. */
  137. async function focusOrOpen(url: string): Promise<void> {
  138. const target = new URL(url, self.location.origin).pathname
  139. const windows = await self.clients.matchAll({ type: 'window', includeUncontrolled: true })
  140. for (const client of windows) {
  141. if (new URL(client.url).origin !== self.location.origin) continue
  142. await client.focus()
  143. if (new URL(client.url).pathname !== target) {
  144. await client.navigate(target)
  145. }
  146. return
  147. }
  148. await self.clients.openWindow(target)
  149. }