aboutsummaryrefslogtreecommitdiffstats
path: root/sw.js
blob: b226d35f1027ffe7f918ce77fc995493a768a65f (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
/* Baby Tracker — shell-only service worker
   Precaches static UI assets. Never caches API / Supabase / config. */
const CACHE = 'baby-shell-v1';
const PRECACHE = [
  './',
  './index.html',
  './manifest.webmanifest',
  './src/styles/main.css',
  './src/js/config.js',
  './src/js/utils.js',
  './src/js/db.js',
  './src/js/charts.js',
  './src/js/toast.js',
  './src/js/app.js',
  './icons/icon.svg',
  './icons/apple-touch-icon.svg'
];
 
self.addEventListener('install', (event) => {
  event.waitUntil(
    caches.open(CACHE)
      .then((cache) => cache.addAll(PRECACHE))
      .then(() => self.skipWaiting())
      .catch(() => self.skipWaiting())
  );
});
 
self.addEventListener('activate', (event) => {
  event.waitUntil(
    caches.keys().then((keys) =>
      Promise.all(keys.filter((k) => k !== CACHE).map((k) => caches.delete(k)))
    ).then(() => self.clients.claim())
  );
});
 
function isShellRequest(url) {
  // Only same-origin static assets
  if (url.origin !== self.location.origin) return false;
  const path = url.pathname;
  if (path.endsWith('.html') || path.endsWith('/') || path.endsWith('.css') ||
      path.endsWith('.js') || path.endsWith('.svg') || path.endsWith('.webmanifest') ||
      path.endsWith('.ico') || path.endsWith('.png')) {
    // Never cache remote config path if hosted same-origin under /api
    if (path.includes('/api/')) return false;
    return true;
  }
  return false;
}
 
self.addEventListener('fetch', (event) => {
  const req = event.request;
  if (req.method !== 'GET') return;
 
  let url;
  try { url = new URL(req.url); } catch { return; }
 
  // Pass through cross-origin (CDN, Supabase, APIs)
  if (url.origin !== self.location.origin) return;
  if (!isShellRequest(url)) return;
 
  // Network-first for HTML so deploys show up; cache-first for static assets
  const isHTML = url.pathname.endsWith('.html') || url.pathname.endsWith('/');
 
  if (isHTML) {
    event.respondWith(
      fetch(req).then((res) => {
        const copy = res.clone();
        caches.open(CACHE).then((c) => c.put(req, copy)).catch(() => {});
        return res;
      }).catch(() => caches.match(req).then((r) => r || caches.match('./index.html')))
    );
    return;
  }
 
  event.respondWith(
    caches.match(req).then((cached) => {
      const network = fetch(req).then((res) => {
        if (res && res.ok) {
          const copy = res.clone();
          caches.open(CACHE).then((c) => c.put(req, copy)).catch(() => {});
        }
        return res;
      }).catch(() => cached);
      return cached || network;
    })
  );
});