about summary refs log tree commit diff stats
diff options
context:
space:
mode:
authorfox <fox@fakecake.org>2026-06-18 14:28:45 +0300
committerfox <fox@fakecake.org>2026-06-18 14:28:45 +0300
commit8eb610074f829cdcbbac035340318601fa41af5c (patch)
tree414e450fb2de04224554a38ab9ada6f8e11ab1ff
parent1e5204020f3099ee3c526d5c109a4c5f4b7f5078 (diff)
parentaaa40a97005a6323710ad3823532d56b668dd837 (diff)
downloadthe-epube-8eb610074f829cdcbbac035340318601fa41af5c.tar.gz
the-epube-8eb610074f829cdcbbac035340318601fa41af5c.tar.xz
Merge branch 'dev' into 'master'
ensure getActiveCacheVersion() wouldn't get stuck

See merge request git/the-epube!61
-rw-r--r--build.js8
-rw-r--r--src/app.js44
-rw-r--r--src/reader.js6
-rw-r--r--src/worker.js1
4 files changed, 41 insertions, 18 deletions
diff --git a/build.js b/build.js
index 3a5f6f8..a2eb419 100644
--- a/build.js
+++ b/build.js
@@ -1,7 +1,7 @@
 #!/usr/bin/env node
 
 import * as esbuild from 'esbuild';
-import { copyFileSync, readFileSync } from 'fs';
+import { copyFileSync, readFileSync, unlinkSync } from 'fs';
 import { writeFile } from 'fs/promises';
 import { globSync } from 'glob';
 import less from 'less';
@@ -98,6 +98,12 @@ async function buildApp() {
 
 	console.log('creating timestamped js files...');
 
+	// remove stale timestamped files from previous builds
+	const oldVersioned = globSync('dist/*_v[0-9]*');
+	for (const f of oldVersioned) {
+		try { unlinkSync(f); } catch { /* ignore */ }
+	}
+
 	// 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) {
diff --git a/src/app.js b/src/app.js
index 24f5b8d..e72da4f 100644
--- a/src/app.js
+++ b/src/app.js
@@ -60,40 +60,58 @@ class AppCommon {
             return navigator.onLine;
     }
 
-    async getActiveCacheName() {
+    async getActiveCacheName(timeoutMs = 1000) {
         const registration = await navigator.serviceWorker.ready;
         const worker = registration.active;
 
+        // Fast exit if no worker is active
         if (!worker) return null;
 
-        return new Promise((resolve) => {
+        return new Promise((resolve, reject) => {
             const channel = new MessageChannel();
+            let timeoutId = null;
 
-            // Listen for the service worker's response
             channel.port1.onmessage = (event) => {
-                resolve(event.data.cacheName);
+                clearTimeout(timeoutId); // Clean up the timeout
+                resolve(event.data?.cacheName || null);
             };
 
-            // Dispatch message to the service worker along with the response port
+            // 1. Set a timeout so it never gets stuck forever
+            timeoutId = setTimeout(() => {
+                channel.port1.onmessage = null; // Clean up listener
+                console.warn('Service worker did not respond to GET_CACHE_NAME');
+                resolve(null);
+            }, timeoutMs);
+
+            // 2. Send the message and transfer the port
             worker.postMessage({ type: 'GET_CACHE_NAME' }, [channel.port2]);
         });
     }
 
-    async getActiveCacheVersion() {
+    async getActiveCacheVersion(timeoutMs = 1000) {
         const registration = await navigator.serviceWorker.ready;
         const worker = registration.active;
 
+        // Fast exit if no worker is active
         if (!worker) return null;
 
-        return new Promise((resolve) => {
+        return new Promise((resolve, reject) => {
             const channel = new MessageChannel();
+            let timeoutId = null;
 
-            // Listen for the service worker's response
             channel.port1.onmessage = (event) => {
-                resolve(event.data.cacheName);
+                clearTimeout(timeoutId); // Clean up the timeout
+                resolve(event.data?.cacheName || null);
             };
 
-            // Dispatch message to the service worker along with the response port
+            // 1. Set a timeout so it never gets stuck forever
+            timeoutId = setTimeout(() => {
+                channel.port1.onmessage = null; // Clean up listener
+                console.warn('Service worker did not respond to GET_CACHE_VERSION');
+                resolve(null);
+            }, timeoutMs);
+
+            // 2. Send the message and transfer the port
             worker.postMessage({ type: 'GET_CACHE_VERSION' }, [channel.port2]);
         });
     }
@@ -140,7 +158,7 @@ class AppClass extends AppCommon {
     cached_urls = [];
 
     /** @type{string} */
-    version = BUILD_CACHE_VERSION;
+    cacheVersion = BUILD_CACHE_VERSION;
 
     /** @type{string} */
     cosmeticVersion = BUILD_VERSION;
@@ -149,7 +167,7 @@ class AppClass extends AppCommon {
     csrf_token = "";
 
     async init() {
-        console.log('version', this.version, 'current, worker', await this.getActiveCacheVersion());
+        console.log('cache version, current:', this.cacheVersion, 'worker:', await this.getActiveCacheVersion());
 
         // Read URL params for mode/query/offset
         this.index_mode = this.urlParam("mode") || "";
@@ -389,7 +407,7 @@ class AppClass extends AppCommon {
     }
 
     async offlineInit() {
-        console.log('version', this.version, 'current, worker', await this.getActiveCacheVersion());
+        console.log('cache version, current:', this.cacheVersion, 'worker:', await this.getActiveCacheVersion());
 
         if (typeof EpubeApp != "undefined") {
             $(".navbar").hide();
diff --git a/src/reader.js b/src/reader.js
index f436810..8f8e784 100644
--- a/src/reader.js
+++ b/src/reader.js
@@ -26,7 +26,7 @@ class ReaderClass extends AppCommon {
 
     _prevent_lastread;
 
-    version = BUILD_CACHE_VERSION;
+    cacheVersion = BUILD_CACHE_VERSION;
 
     cosmeticVersion = BUILD_VERSION;
 
@@ -110,7 +110,7 @@ class ReaderClass extends AppCommon {
     }
 
     async init() {
-        console.log('version', this.version, 'current, worker', await this.getActiveCacheVersion());
+        console.log('cache version, current:', this.cacheVersion, 'worker:', await this.getActiveCacheVersion());
 
         this.csrf_token = Cookie.get('epube_csrf_token');
 
@@ -706,7 +706,7 @@ class ReaderClass extends AppCommon {
                 });
             }
 
-            $(".last-mod-timestamp").html(`${this.cosmeticVersion} &mdash; ${this.version}
+            $(".last-mod-timestamp").html(`${this.cosmeticVersion} &mdash; ${this.cacheVersion}
                 (${this.isOnline() ? `<span class='text-success'>Online</span>` : `<span class='text-danger'>Offline</span>`})
                 `);
 
diff --git a/src/worker.js b/src/worker.js
index 6ca94b5..44ea5b1 100644
--- a/src/worker.js
+++ b/src/worker.js
@@ -67,7 +67,6 @@ sw.addEventListener('message', (event) => {
         // Respond directly to the specific frontend window/tab that asked
         event.ports[0].postMessage({ cacheName: CACHE_VERSION });
     }
-
 });
 
 // Activate: clean up old caches and take control of all pages