From b1b1363574db64a12078dd8324ef89e42a1a4cd0 Mon Sep 17 00:00:00 2001 From: flowkclav <57037551+flowkclav@users.noreply.github.com> Date: Wed, 4 Jun 2025 12:39:52 -0400 Subject: [PATCH] Fixing service worker and local storage conflicts when hosting multiple instances on same origin, different URL prefix but same space path (#1415) Co-authored-by: floakclav --- web/boot.ts | 10 ++++++++-- web/client.ts | 6 +++++- web/service_worker.ts | 3 ++- 3 files changed, 15 insertions(+), 4 deletions(-) diff --git a/web/boot.ts b/web/boot.ts index f299f928..722d20b9 100644 --- a/web/boot.ts +++ b/web/boot.ts @@ -1,7 +1,7 @@ import { safeRun } from "$lib/async.ts"; import { Client, type ClientConfig } from "./client.ts"; -const configCacheKey = "config"; +const configCacheKey = `silverbullet.${document.baseURI}.config`; safeRun(async () => { // First we attempt to fetch the config from the server @@ -50,9 +50,15 @@ safeRun(async () => { } if (navigator.serviceWorker) { // Register service worker + const workerURL = new URL("service_worker.js", document.baseURI); navigator.serviceWorker - .register(new URL("service_worker.js", document.baseURI), { + .register(workerURL, { type: "module", + //limit the scope of the service worker to any potential URL prefix + scope: workerURL.pathname.substring( + 0, + workerURL.pathname.lastIndexOf("/") + 1, + ), }) .then((registration) => { console.log("Service worker registered..."); diff --git a/web/client.ts b/web/client.ts index f5d62c54..d2f48484 100644 --- a/web/client.ts +++ b/web/client.ts @@ -145,7 +145,11 @@ export class Client { ) { // Generate a semi-unique prefix for the database so not to reuse databases for different space paths this.dbPrefix = "" + - simpleHash(clientConfig.spaceFolderPath); + simpleHash( + `${clientConfig.spaceFolderPath}:${ + document.baseURI.replace(/\/*$/, "") + }`, + ); this.onLoadRef = parseRefFromURI(); } diff --git a/web/service_worker.ts b/web/service_worker.ts index b226fe11..7272a4d8 100644 --- a/web/service_worker.ts +++ b/web/service_worker.ts @@ -217,7 +217,8 @@ self.addEventListener("message", (event: any) => { } case "config": { const spaceFolderPath = event.data.config.spaceFolderPath; - const dbPrefix = "" + simpleHash(spaceFolderPath); + const dbPrefix = "" + + simpleHash(`${spaceFolderPath}:${baseURI.replace(/\/*$/, "")}`); // Setup space const kv = new IndexedDBKvPrimitives(dbPrefix);