sw.js 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250
  1. // Bambuddy Service Worker
  2. const CACHE_NAME = 'bambuddy-v31';
  3. const STATIC_CACHE = 'bambuddy-static-v29';
  4. // Static assets to cache on install
  5. const STATIC_ASSETS = [
  6. '/',
  7. '/manifest.json',
  8. '/img/favicon.png',
  9. '/img/favicon-16x16.png',
  10. '/img/favicon-32x32.png',
  11. '/img/android-chrome-192x192.png',
  12. '/img/android-chrome-512x512.png',
  13. '/img/apple-touch-icon.png',
  14. '/img/bambuddy_logo_dark.png',
  15. // Self-hosted Inter font (#1460) - cached so the UI renders offline.
  16. '/fonts/inter-latin.woff2',
  17. '/fonts/inter-latin-ext.woff2',
  18. ];
  19. // <name>-<8-char hash>.<ext> directly under /assets/, as Vite emits them.
  20. const HASHED_ASSET_RE = /^\/assets\/[^/]+-[A-Za-z0-9_-]{8}\.[A-Za-z0-9]+$/;
  21. const ENTRY_SCRIPT_RE = /\/assets\/index-[A-Za-z0-9_-]{8}\.js/;
  22. // An update ships new file names, and the old files would stay cached for
  23. // good. When a page names an entry script the cache has not seen, that is a
  24. // new build: drop the cached /assets files, and the new ones are cached as
  25. // they are used.
  26. async function dropOldBuildAssets(response) {
  27. try {
  28. const html = await response.text();
  29. const entry = html.match(ENTRY_SCRIPT_RE);
  30. if (!entry) return;
  31. const cache = await caches.open(CACHE_NAME);
  32. // Listed first, so files the new build caches meanwhile are kept.
  33. const keys = await cache.keys();
  34. if (await cache.match(entry[0])) return;
  35. await Promise.all(
  36. keys
  37. .filter((key) => new URL(key.url).pathname.startsWith('/assets/'))
  38. .map((key) => cache.delete(key)),
  39. );
  40. } catch {
  41. // Pruning is housekeeping; never let it break a page load.
  42. }
  43. }
  44. // Install event - cache static assets
  45. self.addEventListener('install', (event) => {
  46. console.log('[SW] Installing service worker...');
  47. event.waitUntil(
  48. caches.open(STATIC_CACHE).then((cache) => {
  49. console.log('[SW] Caching static assets');
  50. return cache.addAll(STATIC_ASSETS);
  51. })
  52. );
  53. // Activate immediately
  54. self.skipWaiting();
  55. });
  56. // Activate event - clean up old caches and claim existing clients.
  57. //
  58. // The forced reload that picks up a new bundle on already-open clients (the
  59. // kiosk deploy-pickup scenario) lives in sw-register.js via a
  60. // `controllerchange` listener, gated on whether the page already had a SW
  61. // controller at load time. That gate distinguishes first-install (where a
  62. // reload would race the in-flight React mount — observed on every fresh
  63. // *.demo.bambuddy.cool subdomain, and in Firefox the activate's waitUntil
  64. // hung on `client.navigate` until the document load was aborted with a
  65. // Corrupted-Content error) from upgrade-on-existing-client (where the reload
  66. // is wanted).
  67. self.addEventListener('activate', (event) => {
  68. console.log('[SW] Activating service worker...');
  69. event.waitUntil(
  70. (async () => {
  71. const cacheNames = await caches.keys();
  72. await Promise.all(
  73. cacheNames
  74. .filter((name) => name !== CACHE_NAME && name !== STATIC_CACHE)
  75. .map((name) => {
  76. console.log('[SW] Deleting old cache:', name);
  77. return caches.delete(name);
  78. }),
  79. );
  80. await self.clients.claim();
  81. })(),
  82. );
  83. });
  84. // Fetch event - network-first for API, cache-first for static
  85. self.addEventListener('fetch', (event) => {
  86. const { request } = event;
  87. const url = new URL(request.url);
  88. // Skip non-GET requests
  89. if (request.method !== 'GET') {
  90. return;
  91. }
  92. // Skip cross-origin requests - let the browser handle them directly.
  93. // Without this the catch-all HTML branch below would answer a failed
  94. // cross-origin request with our cached index.html, so e.g. a blocked
  95. // Google Fonts request came back as text/html (#1460).
  96. if (url.origin !== self.location.origin) {
  97. return;
  98. }
  99. // Skip WebSocket connections
  100. if (url.protocol === 'ws:' || url.protocol === 'wss:') {
  101. return;
  102. }
  103. // The page polls /health to learn whether the server is back (#3175); an
  104. // answer from the cache would say it is when it is not.
  105. if (url.pathname === '/health') {
  106. return;
  107. }
  108. // Skip camera stream/snapshot requests - Safari has issues with streaming through SW
  109. if (url.pathname.includes('/camera/stream') || url.pathname.includes('/camera/snapshot')) {
  110. return;
  111. }
  112. // API requests - network first, no cache (real-time data is critical)
  113. if (url.pathname.startsWith('/api/')) {
  114. event.respondWith(
  115. fetch(request).catch(() => {
  116. // Return offline response for API failures
  117. return new Response(
  118. JSON.stringify({ error: 'offline', message: 'You are currently offline' }),
  119. {
  120. status: 503,
  121. headers: { 'Content-Type': 'application/json' },
  122. }
  123. );
  124. })
  125. );
  126. return;
  127. }
  128. // Static assets - cache first, then network
  129. if (
  130. url.pathname.startsWith('/img/') ||
  131. url.pathname.startsWith('/icons/') ||
  132. url.pathname.startsWith('/fonts/') ||
  133. url.pathname.endsWith('.png') ||
  134. url.pathname.endsWith('.jpg') ||
  135. url.pathname.endsWith('.svg') ||
  136. url.pathname.endsWith('.ico') ||
  137. url.pathname.endsWith('.woff2')
  138. ) {
  139. event.respondWith(
  140. caches.match(request).then((cached) => {
  141. if (cached) {
  142. return cached;
  143. }
  144. return fetch(request).then((response) => {
  145. // Cache successful responses
  146. if (response.ok) {
  147. const clone = response.clone();
  148. caches.open(STATIC_CACHE).then((cache) => {
  149. cache.put(request, clone);
  150. });
  151. }
  152. return response;
  153. });
  154. })
  155. );
  156. return;
  157. }
  158. // Files Vite names by content hash never change (#3175): serve them from
  159. // the cache, so an installed app opens without asking the server for the
  160. // bundle. The backend marks them immutable too.
  161. if (HASHED_ASSET_RE.test(url.pathname)) {
  162. event.respondWith(
  163. caches.match(request).then((cached) => {
  164. if (cached) {
  165. return cached;
  166. }
  167. return fetch(request).then((response) => {
  168. // Kept for good, so never keep a page a proxy sent for a missing file.
  169. const isHtml = (response.headers.get('content-type') || '').includes('text/html');
  170. if (response.ok && !isHtml) {
  171. const clone = response.clone();
  172. caches.open(CACHE_NAME).then((cache) => {
  173. cache.put(request, clone);
  174. });
  175. }
  176. return response;
  177. });
  178. })
  179. );
  180. return;
  181. }
  182. // Other JS/CSS (the pdf.js runtime data under /assets/pdfjs/, ...) - network
  183. // first, the cache only when offline.
  184. if (
  185. url.pathname.startsWith('/assets/') ||
  186. url.pathname.endsWith('.js') ||
  187. url.pathname.endsWith('.css')
  188. ) {
  189. event.respondWith(
  190. fetch(request)
  191. .then((response) => {
  192. if (response.ok) {
  193. const clone = response.clone();
  194. caches.open(CACHE_NAME).then((cache) => {
  195. cache.put(request, clone);
  196. });
  197. }
  198. return response;
  199. })
  200. .catch(() => {
  201. return caches.match(request);
  202. })
  203. );
  204. return;
  205. }
  206. // HTML pages - network first, fall back to cache
  207. event.respondWith(
  208. fetch(request)
  209. .then((response) => {
  210. if (response.ok) {
  211. const clone = response.clone();
  212. caches.open(CACHE_NAME).then((cache) => {
  213. cache.put(request, clone);
  214. });
  215. const pruning = dropOldBuildAssets(response.clone());
  216. try {
  217. event.waitUntil(pruning);
  218. } catch {
  219. // Too late to extend the event in this browser; pruning still runs.
  220. }
  221. }
  222. return response;
  223. })
  224. .catch(() => {
  225. return caches.match(request).then((cached) => {
  226. if (cached) {
  227. return cached;
  228. }
  229. // Return cached index for SPA navigation
  230. return caches.match('/');
  231. });
  232. })
  233. );
  234. });