feat: add service worker precaching with app shell and runtime cache strategies

This commit is contained in:
Chris Scott committed 2026-06-17 16:41:32 -04:00
1 parent da28f58706
commit 78d2fe20ef
8 files changed
+277 -17

No files matched your search

+1
View File
@@ -3,6 +3,7 @@
<head>
<meta charset="UTF-8" />
<link rel="icon" type="image/svg+xml" href="/favicon.svg" />
<link rel="preload" as="image" href="/icons/icon-192x192.png" />
<link rel="manifest" href="/manifest.json" />
<link rel="apple-touch-icon" href="/icons/apple-touch-icon.png" />
<link rel="apple-touch-startup-image" href="/splash/splash-750x1334.png" media="(device-width: 375px) and (device-height: 667px) and (-webkit-device-pixel-ratio: 2) and (orientation: portrait)" />
+75
View File
@@ -0,0 +1,75 @@
import { createHash } from "node:crypto";
import { readdir, readFile, writeFile } from "node:fs/promises";
import path from "node:path";
import type { Plugin } from "vite";
const SW_FILENAME = "sw.js";
const PRECACHE_DIR_PREFIXES = ["assets/"];
const PRECACHE_ROOT_FILES = ["index.html", "manifest.json", "favicon.svg"];
async function collectFiles(dir: string, base = dir): Promise<string[]> {
const entries = await readdir(dir, { withFileTypes: true });
const files = await Promise.all(
entries.map(async (entry) => {
const absolute = path.join(dir, entry.name);
if (entry.isDirectory()) return collectFiles(absolute, base);
return [path.relative(base, absolute)];
})
);
return files.flat();
}
function toUrl(relativePath: string): string {
return "/" + relativePath.split(path.sep).join("/");
}
function isPrecacheTarget(relativePath: string): boolean {
const url = toUrl(relativePath);
if (url === `/${SW_FILENAME}` || url.endsWith(".map")) return false;
if (PRECACHE_ROOT_FILES.includes(relativePath)) return true;
return PRECACHE_DIR_PREFIXES.some((prefix) => url.startsWith(`/${prefix}`));
}
export function swPrecacheManifest(): Plugin {
let outDir = "";
return {
name: "sw-precache-manifest",
apply: "build",
configResolved(config) {
outDir = path.resolve(config.root, config.build.outDir);
},
async closeBundle() {
const swPath = path.join(outDir, SW_FILENAME);
let swSource: string;
try {
swSource = await readFile(swPath, "utf-8");
} catch {
throw new Error(`[sw-precache-manifest] ${SW_FILENAME} not found in ${outDir}`);
}
const relativePaths = (await collectFiles(outDir)).filter(isPrecacheTarget).sort();
const hash = createHash("sha256");
const urls: string[] = [];
for (const relativePath of relativePaths) {
const content = await readFile(path.join(outDir, relativePath));
const url = toUrl(relativePath);
urls.push(url);
hash.update(url);
hash.update(content);
}
if (!urls.includes("/index.html")) {
throw new Error("[sw-precache-manifest] index.html missing from build output");
}
const buildHash = hash.digest("hex").slice(0, 16);
const header =
`self.__SW_BUILD_HASH__=${JSON.stringify(buildHash)};` +
`self.__SW_PRECACHE__=${JSON.stringify(urls)};\n`;
await writeFile(swPath, header + swSource);
},
};
}
+2
View File
@@ -17,6 +17,7 @@ import { VersionNotifier } from './components/VersionNotifier'
import { PwaUpdatePrompt } from '@/components/PwaUpdatePrompt'
import { MobileTabBar } from '@/components/navigation/MobileTabBar'
import { MobileSheetHost } from '@/components/navigation/MobileSheetHost'
import { RouteErrorBoundary } from '@/components/ui/route-error-boundary'
import { DesktopSidebar } from '@/components/navigation/DesktopSidebar'
import { useTheme } from './hooks/useTheme'
import { useRightEdgeSwipe, useSwipeBack } from './hooks/useMobile'
@@ -185,6 +186,7 @@ function AppShell() {
const router = createBrowserRouter([
{
element: <AppShell />,
errorElement: <RouteErrorBoundary />,
children: [
{
path: '/login',
@@ -0,0 +1,109 @@
import { useRouteError, isRouteErrorResponse } from 'react-router-dom'
import { AlertTriangle, RefreshCw, LogIn, WifiOff } from 'lucide-react'
import { Button } from '@/components/ui/button'
import { parseNetworkError, parseOpenCodeError } from '@/lib/opencode-errors'
import type { OpenCodeError } from '@/lib/opencode-errors'
function isOpenCodeError(error: unknown): error is OpenCodeError {
return typeof error === 'object' && error !== null && 'name' in error && 'data' in error
}
function getErrorDetails(error: unknown) {
if (isRouteErrorResponse(error)) {
if (error.status === 401 || error.status === 403) {
return {
title: 'Authentication Required',
message: 'Please log in to access this page.',
isRetryable: false,
statusCode: error.status,
}
}
if (error.status === 404) {
return {
title: 'Page Not Found',
message: 'The page you are looking for does not exist.',
isRetryable: false,
statusCode: error.status,
}
}
return {
title: error.statusText || 'Error',
message: error.data?.message || error.status.toString(),
isRetryable: true,
statusCode: error.status,
}
}
if (isOpenCodeError(error)) {
const parsed = parseOpenCodeError(error)
if (parsed) return parsed
}
if (error instanceof Error) {
const networkParsed = parseNetworkError(error)
if (networkParsed.title === 'Connection Failed') {
return {
...networkParsed,
title: "You're offline",
message: '',
isRetryable: false,
variant: 'offline' as const,
}
}
return networkParsed
}
return {
title: 'Unexpected Error',
message: 'An unexpected error occurred. Please try refreshing the page.',
isRetryable: true,
}
}
export function RouteErrorBoundary() {
const error = useRouteError()
const details = getErrorDetails(error)
const { title, message, isRetryable, statusCode } = details
const isAuthError = statusCode === 401 || statusCode === 403
if ('variant' in details && details.variant === 'offline') {
return (
<div className="flex min-h-screen flex-col items-center justify-center gap-6 bg-background text-foreground">
<img src="/icons/icon-192x192.png" alt="" className="h-36 w-36" />
<div className="flex items-center gap-3 text-2xl font-semibold text-foreground">
<WifiOff className="h-6 w-6" />
<span>{title}</span>
</div>
<Button variant="outline" onClick={() => window.location.reload()} className="gap-2">
<RefreshCw className="h-4 w-4" />
Reload
</Button>
</div>
)
}
return (
<div className="flex flex-col items-center justify-center min-h-screen gap-6 p-6 text-center bg-background">
<AlertTriangle className="w-12 h-12 text-destructive" />
<div className="space-y-2">
<h1 className="text-xl font-semibold text-foreground">{title}</h1>
<p className="text-sm text-muted-foreground max-w-sm">{message}</p>
</div>
<div className="flex gap-3">
{isAuthError && (
<Button variant="default" onClick={() => (window.location.href = '/login')}>
<LogIn className="w-4 h-4 mr-2" />
Log in
</Button>
)}
{isRetryable && (
<Button variant="outline" onClick={() => window.location.reload()} className="gap-2">
<RefreshCw className="w-4 h-4" />
Try again
</Button>
)}
</div>
</div>
)
}
+5 -1
View File
@@ -4,19 +4,23 @@ type UpdateCallback = () => void;
let updateCallback: UpdateCallback | null = null;
let updatePending = false;
let updateNotified = false;
function notifyUpdate() {
if (updateNotified) return;
if (!updateCallback) {
updatePending = true;
return;
}
updateNotified = true;
updatePending = false;
updateCallback();
}
export function onServiceWorkerUpdate(callback: UpdateCallback): void {
updateCallback = callback;
if (updatePending) {
if (updatePending && !updateNotified) {
updateNotified = true;
updatePending = false;
callback();
}
+82 -15
View File
@@ -1,18 +1,44 @@
/// <reference lib="webworker" />
declare const self: ServiceWorkerGlobalScope & typeof globalThis;
const worker = self as unknown as ServiceWorkerGlobalScope & typeof globalThis;
self.addEventListener("install", () => {
self.skipWaiting();
interface SwBuildGlobals {
__SW_BUILD_HASH__?: string;
__SW_PRECACHE__?: string[];
}
const buildGlobals = worker as unknown as SwBuildGlobals;
const BUILD_HASH = buildGlobals.__SW_BUILD_HASH__ ?? "dev";
const PRECACHE_URLS = buildGlobals.__SW_PRECACHE__ ?? [];
const APP_SHELL_CACHE = `app-shell-${BUILD_HASH}`;
const RUNTIME_CACHE = `runtime-${BUILD_HASH}`;
const APP_SHELL_URL = "/index.html";
const MANAGED_CACHE_PREFIXES = ["app-shell-", "runtime-", "offline-assets-"];
worker.addEventListener("install", (event) => {
event.waitUntil(caches.open(APP_SHELL_CACHE).then((cache) => cache.addAll(PRECACHE_URLS)));
worker.skipWaiting();
});
self.addEventListener("activate", (event) => {
worker.addEventListener("activate", (event) => {
event.waitUntil(
caches.keys().then((names) =>
Promise.all(names.map((name) => caches.delete(name)))
).then(() => self.clients.claim())
.then(() => self.clients.matchAll({ type: "window" }))
.then((clients) => {
caches.keys().then(async (names) => {
const stale = names.filter(
(name) =>
MANAGED_CACHE_PREFIXES.some((prefix) => name.startsWith(prefix)) &&
name !== APP_SHELL_CACHE &&
name !== RUNTIME_CACHE
);
const isUpdate = stale.length > 0;
await Promise.all(stale.map((name) => caches.delete(name)));
await worker.clients.claim();
if (!isUpdate) return;
const clients = await worker.clients.matchAll({ type: "window" });
for (const client of clients) {
client.postMessage({ type: "SW_UPDATED" });
}
@@ -20,6 +46,47 @@ self.addEventListener("activate", (event) => {
);
});
async function networkFirstShell(request: Request): Promise<Response> {
const cache = await caches.open(APP_SHELL_CACHE);
try {
const response = await fetch(request);
if (response.ok) cache.put(APP_SHELL_URL, response.clone());
return response;
} catch (error) {
const cached = await cache.match(APP_SHELL_URL);
if (cached) return cached;
throw error;
}
}
async function cacheFirstAsset(request: Request): Promise<Response> {
const cached = await caches.match(request);
if (cached) return cached;
const response = await fetch(request);
if (response.ok && response.status === 200) {
const cache = await caches.open(RUNTIME_CACHE);
cache.put(request, response.clone());
}
return response;
}
worker.addEventListener("fetch", (event) => {
const { request } = event;
if (request.method !== "GET") return;
const url = new URL(request.url);
if (url.origin !== worker.location.origin) return;
if (url.pathname.startsWith("/api/") || url.pathname === "/sw.js") return;
if (request.mode === "navigate") {
event.respondWith(networkFirstShell(request));
return;
}
event.respondWith(cacheFirstAsset(request));
});
interface PushNotificationData {
title: string;
body: string;
@@ -37,7 +104,7 @@ interface PushNotificationData {
};
}
self.addEventListener("push", (event) => {
worker.addEventListener("push", (event) => {
if (!event.data) return;
let payload: PushNotificationData;
@@ -60,27 +127,27 @@ self.addEventListener("push", (event) => {
requireInteraction: isHighPriority(payload.data?.eventType, payload.data?.priority),
};
event.waitUntil(self.registration.showNotification(payload.title, options));
event.waitUntil(worker.registration.showNotification(payload.title, options));
});
self.addEventListener("notificationclick", (event) => {
worker.addEventListener("notificationclick", (event) => {
event.notification.close();
const url = (event.notification.data?.url as string) ?? "/";
event.waitUntil(
self.clients
worker.clients
.matchAll({ type: "window", includeUncontrolled: true })
.then((clientList) => {
for (const client of clientList) {
if (new URL(client.url).origin === self.location.origin) {
if (new URL(client.url).origin === worker.location.origin) {
const channel = new BroadcastChannel("notification-click");
channel.postMessage({ url });
channel.close();
return (client as WindowClient).focus();
}
}
return self.clients.openWindow(url);
return worker.clients.openWindow(url);
})
);
});
+1 -1
View File
@@ -22,5 +22,5 @@
"noFallthroughCasesInSwitch": true,
"noUncheckedSideEffectImports": true
},
"include": ["vite.config.ts"]
"include": ["vite.config.ts", "plugins/**/*.ts"]
}
+2
View File
@@ -2,6 +2,7 @@ import path from "path";
import { defineConfig, loadEnv } from "vite";
import react from "@vitejs/plugin-react";
import tailwindcss from "@tailwindcss/vite";
import { swPrecacheManifest } from "./plugins/sw-precache-manifest";
export default defineConfig(({ mode }) => {
const env = loadEnv(mode, path.resolve(__dirname, ".."), "");
@@ -12,6 +13,7 @@ export default defineConfig(({ mode }) => {
plugins: [
react(),
tailwindcss(),
swPrecacheManifest(),
],
resolve: {
alias: {