about summary refs log tree commit diff stats
diff options
context:
space:
mode:
authorAndrew Dolgov <fox@fakecake.org>2026-06-18 12:15:04 +0300
committerAndrew Dolgov <fox@fakecake.org>2026-06-18 12:15:04 +0300
commite8be5163b76ef7c4f735f1b9807062d94a3c9b8a (patch)
treedf7eb8175a4557848186e06063c283dc3e53051e
parentf35998422d16e06b640907f7455b11c0e48a21b6 (diff)
downloadthe-epube-e8be5163b76ef7c4f735f1b9807062d94a3c9b8a.tar.gz
the-epube-e8be5163b76ef7c4f735f1b9807062d94a3c9b8a.tar.xz
backport pseudo-atomic builds with versioned assets
-rw-r--r--build.js27
-rw-r--r--src/worker.js36
2 files changed, 47 insertions, 16 deletions
diff --git a/build.js b/build.js
index 5155dbe..3a5f6f8 100644
--- a/build.js
+++ b/build.js
@@ -1,8 +1,9 @@
 #!/usr/bin/env node
 
 import * as esbuild from 'esbuild';
-import { readFileSync } from 'fs';
+import { copyFileSync, readFileSync } from 'fs';
 import { writeFile } from 'fs/promises';
+import { globSync } from 'glob';
 import less from 'less';
 import chokidar from 'chokidar';
 import path from 'path';
@@ -95,20 +96,28 @@ async function buildApp() {
 		}
 	});
 
+	console.log('creating timestamped js files...');
+
+	// also create suffixed filenames for our worker to determine proper replica (a pseudo-atomic build)
+	const builtFiles = globSync('dist/**/*.js');
+	for (const file of builtFiles) {
+		const newFileName = `${file}_${CACHE_VERSION}`;
+		copyFileSync(file, newFileName);
+	}
+
 	console.log('building service worker...');
 
 	const workerContent = readFileSync("src/worker.js");
 
-	let MANIFEST_ASSETS = CACHE_ASSETS;
+	// Use suffixed JS filenames in manifest (stripped by worker for cache keys)
+	// worker.js itself is the service worker — not versioned, replaced atomically by deploy
+	let MANIFEST_ASSETS = CACHE_ASSETS.map(asset =>
+		asset.endsWith('.js') && asset !== 'worker.js' ? `${asset}_${CACHE_VERSION}` : asset
+	);
 
 	// Add fonts and images
-	try {
-		const { globSync } = await import('glob');
-		MANIFEST_ASSETS.push(...globSync('lib/fonts/*'));
-		MANIFEST_ASSETS.push(...globSync('img/*.png'));
-	} catch {
-		// glob not available, skip
-	}
+	MANIFEST_ASSETS.push(...globSync('lib/fonts/*'));
+	MANIFEST_ASSETS.push(...globSync('img/*.png'));
 
 	// deduplicate
 	MANIFEST_ASSETS = [...new Set(MANIFEST_ASSETS)];
diff --git a/src/worker.js b/src/worker.js
index 94da8db..6ca94b5 100644
--- a/src/worker.js
+++ b/src/worker.js
@@ -15,16 +15,35 @@ sw.addEventListener('install', (event) => {
         (async () => {
             console.log('[worker] install started', CACHE_NAME);
 
-            // await loadConfig();
-
             const cache = await caches.open(CACHE_NAME);
 
-            // 1. Map assets to Request objects that bypass old service worker caches
-            const requests = MANIFEST_ASSETS.map((url) => new Request(url, { cache: 'reload' }));
-
             try {
-                // 2. Atomic install: fills cache entirely, or fails completely if one file is missing
-                await cache.addAll(requests);
+                // 1. Fetch all assets concurrently with version parameters
+                const fetchPromises = MANIFEST_ASSETS.map(async (url) => {
+                    const cleanUrl = new URL(url, location.href);
+
+                    // normalize = strip CACHE_VERSION suffix from pathname
+                    cleanUrl.pathname = cleanUrl.pathname.replace("_" + CACHE_VERSION, "");
+
+                    // this is our original URL from manifest (with suffix if set)
+                    const networkUrl = new URL(url, location.href);
+
+                    const response = await fetch(networkUrl.toString(), { cache: 'reload' });
+
+                    // Emulate cache.addAll behavior: fail if any status is not 200-299
+                    if (!response.ok) {
+                        throw new Error(`Failed to fetch ${cleanUrl} (Status: ${response.status})`);
+                    }
+
+                    return {
+                        cleanUrlStr: cleanUrl.toString(),
+                        response: response.clone()
+                    };
+                });
+
+                const results = await Promise.all(fetchPromises);
+                await Promise.all(results.map(({ cleanUrlStr, response }) => cache.put(cleanUrlStr, response)));
+
                 console.log('[worker] all assets cached successfully');
 
                 // Only skip waiting if the entire cache was successfully built
@@ -32,6 +51,9 @@ sw.addEventListener('install', (event) => {
             } catch (err) {
                 console.error('[worker] Critical precache failed! Critical asset missing:', err);
                 // Do NOT call skipWaiting(). Let this installation fail so the old worker stays safe.
+
+                // we need to tell the browser the install failed so it throws away this worker, otherwise it gets stuck in waiting
+                throw err;
             }
         })()
     );