sw.js 5.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199
  1. // Bambuddy Service Worker
  2. const CACHE_NAME = 'bambuddy-v21';
  3. const STATIC_CACHE = 'bambuddy-static-v21';
  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. ];
  16. // Install event - cache static assets
  17. self.addEventListener('install', (event) => {
  18. console.log('[SW] Installing service worker...');
  19. event.waitUntil(
  20. caches.open(STATIC_CACHE).then((cache) => {
  21. console.log('[SW] Caching static assets');
  22. return cache.addAll(STATIC_ASSETS);
  23. })
  24. );
  25. // Activate immediately
  26. self.skipWaiting();
  27. });
  28. // Activate event - clean up old caches
  29. self.addEventListener('activate', (event) => {
  30. console.log('[SW] Activating service worker...');
  31. event.waitUntil(
  32. caches.keys().then((cacheNames) => {
  33. return Promise.all(
  34. cacheNames
  35. .filter((name) => name !== CACHE_NAME && name !== STATIC_CACHE)
  36. .map((name) => {
  37. console.log('[SW] Deleting old cache:', name);
  38. return caches.delete(name);
  39. })
  40. );
  41. })
  42. );
  43. // Take control immediately
  44. self.clients.claim();
  45. });
  46. // Fetch event - network-first for API, cache-first for static
  47. self.addEventListener('fetch', (event) => {
  48. const { request } = event;
  49. const url = new URL(request.url);
  50. // Skip non-GET requests
  51. if (request.method !== 'GET') {
  52. return;
  53. }
  54. // Skip WebSocket connections
  55. if (url.protocol === 'ws:' || url.protocol === 'wss:') {
  56. return;
  57. }
  58. // API requests - network first, no cache (real-time data is critical)
  59. if (url.pathname.startsWith('/api/')) {
  60. event.respondWith(
  61. fetch(request).catch(() => {
  62. // Return offline response for API failures
  63. return new Response(
  64. JSON.stringify({ error: 'offline', message: 'You are currently offline' }),
  65. {
  66. status: 503,
  67. headers: { 'Content-Type': 'application/json' },
  68. }
  69. );
  70. })
  71. );
  72. return;
  73. }
  74. // Static assets - cache first, then network
  75. if (
  76. url.pathname.startsWith('/img/') ||
  77. url.pathname.startsWith('/icons/') ||
  78. url.pathname.endsWith('.png') ||
  79. url.pathname.endsWith('.jpg') ||
  80. url.pathname.endsWith('.svg') ||
  81. url.pathname.endsWith('.ico')
  82. ) {
  83. event.respondWith(
  84. caches.match(request).then((cached) => {
  85. if (cached) {
  86. return cached;
  87. }
  88. return fetch(request).then((response) => {
  89. // Cache successful responses
  90. if (response.ok) {
  91. const clone = response.clone();
  92. caches.open(STATIC_CACHE).then((cache) => {
  93. cache.put(request, clone);
  94. });
  95. }
  96. return response;
  97. });
  98. })
  99. );
  100. return;
  101. }
  102. // JS/CSS assets - stale-while-revalidate
  103. if (
  104. url.pathname.startsWith('/assets/') ||
  105. url.pathname.endsWith('.js') ||
  106. url.pathname.endsWith('.css')
  107. ) {
  108. event.respondWith(
  109. caches.match(request).then((cached) => {
  110. const fetchPromise = fetch(request).then((response) => {
  111. if (response.ok) {
  112. const clone = response.clone();
  113. caches.open(CACHE_NAME).then((cache) => {
  114. cache.put(request, clone);
  115. });
  116. }
  117. return response;
  118. });
  119. return cached || fetchPromise;
  120. })
  121. );
  122. return;
  123. }
  124. // HTML pages - network first, fall back to cache
  125. event.respondWith(
  126. fetch(request)
  127. .then((response) => {
  128. if (response.ok) {
  129. const clone = response.clone();
  130. caches.open(CACHE_NAME).then((cache) => {
  131. cache.put(request, clone);
  132. });
  133. }
  134. return response;
  135. })
  136. .catch(() => {
  137. return caches.match(request).then((cached) => {
  138. if (cached) {
  139. return cached;
  140. }
  141. // Return cached index for SPA navigation
  142. return caches.match('/');
  143. });
  144. })
  145. );
  146. });
  147. // Handle push notifications (for future use)
  148. self.addEventListener('push', (event) => {
  149. if (!event.data) return;
  150. const data = event.data.json();
  151. const options = {
  152. body: data.body || 'New notification from Bambuddy',
  153. icon: '/img/android-chrome-192x192.png',
  154. badge: '/img/favicon-32x32.png',
  155. vibrate: [100, 50, 100],
  156. data: {
  157. url: data.url || '/',
  158. },
  159. };
  160. event.waitUntil(
  161. self.registration.showNotification(data.title || 'Bambuddy', options)
  162. );
  163. });
  164. // Handle notification clicks
  165. self.addEventListener('notificationclick', (event) => {
  166. event.notification.close();
  167. const url = event.notification.data?.url || '/';
  168. event.waitUntil(
  169. clients.matchAll({ type: 'window', includeUncontrolled: true }).then((windowClients) => {
  170. // Check if there's already a window open
  171. for (const client of windowClients) {
  172. if (client.url.includes(self.location.origin) && 'focus' in client) {
  173. client.navigate(url);
  174. return client.focus();
  175. }
  176. }
  177. // Open a new window if none exists
  178. if (clients.openWindow) {
  179. return clients.openWindow(url);
  180. }
  181. })
  182. );
  183. });