sw.js 7.8 KB

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