/** * PWA pieces for the factory app, scoped to the package app mount (never the * Kody origin root). Same lifecycle as other Kody package PWAs: versioned * cache, old-cache cleanup, SKIP_WAITING only on the user's Refresh. * The SW caches static assets and the data-free view shells only. It never * caches /api/*, /manage, or any non-GET; offline data lives in the page's * own sanitized localStorage snapshot. * * Web push: `push` shows the factory's notification (title, body, a path * inside the app); `notificationclick` focuses an open factory tab on that * path or opens one. Paths outside the app mount fall back to the app root. * `icon` is the color app icon; `badge` is the white-on-transparent status-bar * silhouette from ./badge.ts (Android draws only its alpha). */ import { CSS } from './styles.ts' import { CLIENT_JS } from './client.ts' import { THEME_BOOT_JS } from './theme.ts' import { renderShell, type View } from './ui.ts' import { BADGE_PATH, BADGE_PNG_BASE64 } from './badge.ts' /** Bump only when the SW template itself changes shape; content changes are hashed below. */ const SW_TEMPLATE_REV = 'sw5' export const SHELL_PATHS = ['/', '/work', '/projects', '/settings'] /** FNV-1a (two 32-bit lanes) over the parts; deterministic, no env needed. */ export function contentRevision(parts: string[]): string { let a = 0x811c9dc5, b = 0x01000193 ^ 0x5bd1e995 for (const part of parts) { for (let i = 0; i < part.length; i++) { const c = part.charCodeAt(i) a = Math.imul(a ^ c, 0x01000193) >>> 0 b = Math.imul(b ^ c, 0x5bd1e995) >>> 0 } a = Math.imul(a ^ 0xff, 0x01000193) >>> 0 } return a.toString(16).padStart(8, '0') + b.toString(16).padStart(8, '0') } let revision: string | null = null /** * Revision of everything the shell ships (client JS, CSS, theme boot, view * shells, SW template). Any publish that changes them changes the SW bytes, * so browsers see an update with no manual bump; an identical republish keeps * the same SW and never prompts. */ export function appRevision(): string { if (revision) return revision const views: View[] = ['overview', 'work', 'projects', 'settings'] revision = contentRevision([SW_TEMPLATE_REV, BADGE_PNG_BASE64, CLIENT_JS, CSS, THEME_BOOT_JS, ...views.map((view) => renderShell({ basePath: '', view, title: '' }))]) return revision } export function buildManifest(basePath: string) { const base = basePath.replace(/\/+$/, '') return { id: `${base}/`, name: 'Kody Factory', short_name: 'Factory', description: 'Signals, priority queue, and agent runs across your projects.', lang: 'en', start_url: `${base}/`, scope: `${base}/`, display: 'standalone', display_override: ['standalone', 'minimal-ui'], background_color: '#f7f8fc', theme_color: '#4f46e5', categories: ['productivity', 'developer'], icons: [ { src: `${base}/_assets/favicon.svg`, sizes: 'any', type: 'image/svg+xml', purpose: 'any' }, { src: `${base}/_assets/icon-192.png`, sizes: '192x192', type: 'image/png', purpose: 'any' }, { src: `${base}/_assets/icon-512.png`, sizes: '512x512', type: 'image/png', purpose: 'any' }, { src: `${base}/_assets/icon-maskable-512.png`, sizes: '512x512', type: 'image/png', purpose: 'maskable' }, ], } } export function renderServiceWorker(version = appRevision()): string { return `'use strict'; var CACHE = 'kody-factory-' + ${JSON.stringify(version)}; var BASE = self.location.pathname.replace(/\\/sw\\.js$/, ''); var SHELLS = ${JSON.stringify(SHELL_PATHS)}.map(function (p) { return BASE + (p === '/' ? '/' : p); }); var BADGE = BASE + ${JSON.stringify(BADGE_PATH)}; var STATIC = ['/_assets/favicon.svg', '/_assets/icon-192.png', '/_assets/icon-512.png', '/_assets/apple-touch-icon.png', ${JSON.stringify(BADGE_PATH)}].map(function (p) { return BASE + p; }); var NAV_TIMEOUT_MS = 3000; function rel(url) { var p = url.pathname; if (p === BASE) return '/'; return p.indexOf(BASE + '/') === 0 ? (p.slice(BASE.length).replace(/\\/+$/, '') || '/') : null; } function isShell(url) { var r = rel(url); return r !== null && ${JSON.stringify(SHELL_PATHS)}.indexOf(r) !== -1; } function isStatic(url) { return url.pathname.indexOf(BASE + '/_assets/') === 0 || url.pathname === BADGE; } function ok(res) { return res && res.ok && res.type === 'basic' && !res.redirected; } self.addEventListener('install', function (event) { event.waitUntil(caches.open(CACHE).then(function (cache) { return Promise.all(SHELLS.concat(STATIC).map(function (u) { return fetch(u, { credentials: 'same-origin', cache: 'no-store' }).then(function (res) { if (ok(res)) return cache.put(u, res); }).catch(function () {}); })); })); }); self.addEventListener('message', function (event) { var d = event.data; if (d === 'SKIP_WAITING' || (d && d.type === 'SKIP_WAITING')) self.skipWaiting(); }); self.addEventListener('activate', function (event) { event.waitUntil(caches.keys().then(function (keys) { return Promise.all(keys.filter(function (k) { return k.indexOf('kody-factory-') === 0 && k !== CACHE; }).map(function (k) { return caches.delete(k); })); }).then(function () { return self.clients.claim(); })); }); function shellKey(url) { var r = rel(url); return BASE + (r === '/' ? '/' : r); } function networkFirstShell(request) { var url = new URL(request.url); var key = shellKey(url); return new Promise(function (resolve) { var done = false; function fallback() { caches.match(key).then(function (c) { if (!done) { done = true; resolve(c || Response.error()); } }); } var timer = setTimeout(fallback, NAV_TIMEOUT_MS); fetch(request).then(function (res) { clearTimeout(timer); if (ok(res)) { var copy = res.clone(); caches.open(CACHE).then(function (c) { c.put(key, copy); }); } if (!done) { done = true; resolve(res); } }).catch(function () { clearTimeout(timer); fallback(); }); }); } self.addEventListener('push', function (event) { var d = {}; try { d = event.data ? event.data.json() : {}; } catch (e) { d = { title: 'Kody Factory', body: event.data ? event.data.text() : '' }; } var path = typeof d.path === 'string' && d.path.charAt(0) === '/' && d.path.charAt(1) !== '/' ? d.path : '/'; event.waitUntil(self.registration.showNotification(String(d.title || 'Kody Factory').slice(0, 120), { body: String(d.body || '').slice(0, 400), tag: typeof d.tag === 'string' ? d.tag : undefined, icon: BASE + '/_assets/icon-192.png', badge: BADGE, data: { url: BASE + path } })); }); self.addEventListener('notificationclick', function (event) { event.notification.close(); var target = event.notification.data && typeof event.notification.data.url === 'string' ? event.notification.data.url : BASE + '/'; var abs = new URL(target, self.location.origin); if (abs.origin !== self.location.origin || (abs.pathname !== BASE && abs.pathname.indexOf(BASE + '/') !== 0)) abs = new URL(BASE + '/', self.location.origin); event.waitUntil(self.clients.matchAll({ type: 'window', includeUncontrolled: true }).then(function (list) { for (var i = 0; i < list.length; i++) { var c = list[i]; if (new URL(c.url).pathname.indexOf(BASE) === 0 && 'focus' in c) { return c.focus().then(function (fc) { return fc && 'navigate' in fc ? fc.navigate(abs.href) : fc; }); } } return self.clients.openWindow(abs.href); })); }); self.addEventListener('fetch', function (event) { var request = event.request; if (request.method !== 'GET') return; var url = new URL(request.url); if (url.origin !== self.location.origin) return; if (request.mode === 'navigate' && isShell(url)) { event.respondWith(networkFirstShell(request)); return; } if (isStatic(url)) { event.respondWith(caches.match(request).then(function (c) { return c || fetch(request).then(function (res) { if (ok(res)) { var copy = res.clone(); caches.open(CACHE).then(function (k) { k.put(request, copy); }); } return res; }); })); } }); ` }