/// // Service worker: offline app shell + push notifications (SPEC.md §7.7, §10.1). // A push only says "group X changed"; this worker fetches the new events, // decrypts them on the device and writes the notification text itself. import { exponent, logOrder, replay, type GroupEvent } from '@oweme/core'; import { deriveKeys } from './lib/crypto.ts'; import { translate, type Lang } from './lib/i18n.ts'; import { deviceId, get, getAll, groupRange, kvGet, putEvents, updateGroup, type LocalGroup, type StoredEvent } from './lib/idb.ts'; import { decryptEvent } from './lib/events.ts'; declare const __PRECACHE__: string[]; declare const __VERSION__: string; const sw = self as unknown as ServiceWorkerGlobalScope; const CACHE = `oweme-${__VERSION__}`; sw.addEventListener('install', (e) => { e.waitUntil(caches.open(CACHE).then((c) => c.addAll(__PRECACHE__)).then(() => sw.skipWaiting())); }); sw.addEventListener('activate', (e) => { e.waitUntil( caches.keys() .then((keys) => Promise.all(keys.filter((k) => k.startsWith('oweme-') && k !== CACHE).map((k) => caches.delete(k)))) .then(() => sw.clients.claim()), ); }); sw.addEventListener('fetch', (e) => { const url = new URL(e.request.url); if (e.request.method !== 'GET' || url.origin !== location.origin || url.pathname.startsWith('/api/')) return; if (e.request.mode === 'navigate') { // Network first so deploys show up; the cached shell when offline. e.respondWith(fetch(e.request).catch(async () => (await caches.match('/index.html')) ?? Response.error())); return; } e.respondWith(caches.match(e.request).then((hit) => hit ?? fetch(e.request))); }); function fmtMoney(minor: number, currency: string, locale: string): string { const e = exponent(currency); try { return new Intl.NumberFormat(locale, { style: 'currency', currency, minimumFractionDigits: e, maximumFractionDigits: e }).format(minor / 10 ** e); } catch { return `${(minor / 10 ** e).toFixed(e)} ${currency}`; } } async function handlePush(groupId: string): Promise { const lang: Lang = (await kvGet('lang')) ?? 'en'; const locale = lang === 'cs' ? 'cs-CZ' : 'en'; const tr = (k: Parameters[1], v?: Record) => translate(lang, k, v); const group = await get('groups', groupId); const fallback = () => sw.registration.showNotification('OweMe', { body: tr('notif_new_activity', { n: 1 }), tag: groupId, icon: '/icon-192.png' }); if (!group) return fallback(); const keys = await deriveKeys(group.secret); let lastSeq = group.lastSeq; try { for (;;) { const res = await fetch(`/api/groups/${groupId}/events?after=${lastSeq}&limit=500`, { headers: { Authorization: `Bearer ${keys.authToken}` } }); if (!res.ok) break; const { events, latest } = (await res.json()) as { events: Omit[]; latest: number }; if (!events.length) break; await putEvents(events.map((e) => ({ ...e, g: groupId }))); lastSeq = events[events.length - 1].seq; if (lastSeq >= latest) break; } await updateGroup(groupId, { lastSeq }); } catch { /* offline: notify with what we have */ } const stored = await getAll('events', groupRange(groupId)); const all = (await Promise.all(stored.map((e) => decryptEvent(keys, groupId, e)))).filter((e): e is GroupEvent => !!e); const { state, activity } = replay(logOrder(all, [])); const me = await deviceId(); const fresh = activity.filter((a) => !a.ignored && (a.seq ?? 0) > group.notifiedSeq && all.find((e) => e.id === a.eventId)?.deviceId !== me); await updateGroup(groupId, { notifiedSeq: lastSeq }); // Skip if the user is looking at this group right now. const windows = await sw.clients.matchAll({ type: 'window' }); if (windows.some((w) => w.focused && w.visibilityState === 'visible' && new URL(w.url).pathname.startsWith(`/g/${groupId}`))) return; if (!fresh.length && group.notifiedSeq >= lastSeq) return fallback(); const name = (id: string | null) => state.members.find((m) => m.id === id)?.name ?? tr('someone'); const lines = fresh.slice(-4).map((a) => { const ev = all.find((e) => e.id === a.eventId)!; if ((ev.type === 'expense.created' || ev.type === 'expense.updated') && ev.data.kind === 'expense') return `${name(ev.actor)}: ${ev.data.title} · ${fmtMoney(ev.data.amount, ev.data.currency, locale)}`; if ((ev.type === 'expense.created' || ev.type === 'expense.updated') && ev.data.kind === 'transfer') return `${name(ev.data.payers[0]?.member ?? null)} → ${name(ev.data.split.entries[0]?.member ?? null)} · ${fmtMoney(ev.data.amount, ev.data.currency, locale)}`; if (ev.type === 'comment.added') return `${name(ev.actor)}: “${ev.data.text.slice(0, 80)}”`; return `${name(ev.actor)}: ${tr('notif_new_activity', { n: 1 })}`; }); const body = fresh.length > 4 ? [tr('notif_new_activity', { n: fresh.length }), ...lines].join('\n') : lines.join('\n') || tr('notif_new_activity', { n: 1 }); await sw.registration.showNotification(`${state.group?.icon ?? ''} ${state.group?.name ?? 'OweMe'}`.trim(), { body, tag: groupId, icon: '/icon-192.png', badge: '/badge-96.png', data: { url: `/g/${groupId}` }, }); } sw.addEventListener('push', (e) => { let groupId = ''; try { groupId = (e.data?.json() as { g?: string })?.g ?? ''; } catch { /* empty payload */ } e.waitUntil(handlePush(groupId).catch(() => sw.registration.showNotification('OweMe', { tag: groupId || 'oweme' }))); }); sw.addEventListener('notificationclick', (e) => { e.notification.close(); const url = (e.notification.data as { url?: string } | null)?.url ?? '/'; e.waitUntil( sw.clients.matchAll({ type: 'window', includeUncontrolled: true }).then((list) => { const existing = list.find((c) => new URL(c.url).origin === location.origin); if (existing) return existing.focus().then((c) => c.navigate(url)); return sw.clients.openWindow(url); }), ); });