From 05f14979b2ada26232184f429d3d7ac1fea3b1e6 Mon Sep 17 00:00:00 2001 From: Karim Masmoudi <125830216+Kernel-Hunter@users.noreply.github.com> Date: Fri, 30 Oct 2026 22:28:23 +0100 Subject: [PATCH] Tell open pages and the extension when a new version is out The web app writes its build id into index.html and version.json. The page compares the two when it is shown again and every 30 minutes, and shows a notice with a Reload button. It never reloads by itself: Reload pauses playback and saves the reading position first, and waits while a voice is downloading. The service worker never caches version.json, and the voices stay in the Origin Private File System, which updates do not touch. The extension popup asks GitHub for the latest release at most once a day and, when it is newer, says how to update the unpacked folder. A release workflow attaches narrata-extension-.zip to v* tags. --- .github/workflows/pages.yml | 2 + .github/workflows/release.yml | 47 +++++++++ .gitignore | 1 + README.md | 29 ++++-- extension/manifest.json | 2 +- extension/popup.html | 7 +- extension/src/popup.ts | 25 ++++- extension/src/update.ts | 77 +++++++++++++++ src/main.ts | 15 ++- src/pwa/sw.js | 3 + src/pwa/update.ts | 101 +++++++++++++++++++ src/styles/app.css | 4 + src/ui/app.ts | 19 ++++ src/ui/overlay.ts | 24 ++++- tests/e2e/verify-ext-update.mjs | 69 +++++++++++++ tests/e2e/verify-update.mjs | 165 ++++++++++++++++++++++++++++++++ tests/ext-update.test.ts | 69 +++++++++++++ tests/update.test.ts | 43 +++++++++ vite.config.ts | 23 +++-- 19 files changed, 701 insertions(+), 24 deletions(-) create mode 100644 .github/workflows/release.yml create mode 100644 extension/src/update.ts create mode 100644 src/pwa/update.ts create mode 100644 tests/e2e/verify-ext-update.mjs create mode 100644 tests/e2e/verify-update.mjs create mode 100644 tests/ext-update.test.ts create mode 100644 tests/update.test.ts diff --git a/.github/workflows/pages.yml b/.github/workflows/pages.yml index 939be7a..ca6d531 100644 --- a/.github/workflows/pages.yml +++ b/.github/workflows/pages.yml @@ -36,6 +36,8 @@ jobs: - run: pnpm build - name: Check the service worker is in the build run: test -f dist/sw.js && grep -q "Cross-Origin-Embedder-Policy" dist/sw.js + - name: Check the build id is in index.html and version.json + run: grep -q "\"build\":\"$(grep -o 'narrata-build" content="[0-9a-f]*' dist/index.html | cut -d'"' -f3)\"" dist/version.json - uses: actions/configure-pages@v5 - uses: actions/upload-pages-artifact@v4 with: diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml new file mode 100644 index 0000000..1028a20 --- /dev/null +++ b/.github/workflows/release.yml @@ -0,0 +1,47 @@ +# On a version tag (v0.2.0), builds the extension and attaches it to the GitHub release as +# narrata-extension-.zip, so people can install or update it without building it. +# The version lives in package.json; the build copies it into the manifest, and the tag must match. +name: Release + +on: + push: + tags: ['v*'] + +permissions: + contents: write + +jobs: + extension: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v5 + - uses: pnpm/action-setup@v4 + - uses: actions/setup-node@v5 + with: + node-version: 24 + cache: pnpm + - run: pnpm install --frozen-lockfile + - name: Check the tag matches package.json + run: | + version=$(node -p "require('./package.json').version") + if [ "v$version" != "$GITHUB_REF_NAME" ]; then + echo "Tag $GITHUB_REF_NAME does not match package.json version $version" + exit 1 + fi + echo "VERSION=$version" >> "$GITHUB_ENV" + - run: pnpm test + - run: pnpm build:ext + - run: pnpm audit:licenses + - name: Zip the extension + run: | + test "$(node -p "require('./dist-ext/manifest.json').version")" = "$VERSION" + (cd dist-ext && zip -qr "../narrata-extension-$VERSION.zip" .) + - name: Attach it to the release + env: + GH_TOKEN: ${{ github.token }} + run: | + if gh release view "$GITHUB_REF_NAME" > /dev/null 2>&1; then + gh release upload "$GITHUB_REF_NAME" "narrata-extension-$VERSION.zip" --clobber + else + gh release create "$GITHUB_REF_NAME" "narrata-extension-$VERSION.zip" --title "$GITHUB_REF_NAME" --generate-notes + fi diff --git a/.gitignore b/.gitignore index 806a406..2560569 100644 --- a/.gitignore +++ b/.gitignore @@ -8,6 +8,7 @@ public/pdfjs dist-ext dist-ext-test .e2e-profile* +.e2e-update-site narrata-e2e-*.json __pycache__ .bench-profile diff --git a/README.md b/README.md index 682a0cc..0263597 100644 --- a/README.md +++ b/README.md @@ -28,7 +28,7 @@ **Web app:** open [kernel-hunter.github.io/narrata](https://kernel-hunter.github.io/narrata/). Pick a voice, then try the sample, open a file or paste text. Nothing to install, though the browser can install it as an app. -**Chrome extension:** not in the Chrome Web Store yet. [Load it from the source](#chrome-extension) in a few steps. +**Chrome extension:** not in the Chrome Web Store yet. [Download it from the releases and load it](#chrome-extension) in a few steps.
Run it from the source @@ -97,7 +97,7 @@ Most other Piper voices are fine-tuned from the "lessac" voice, whose recordings ## Privacy -Everything runs in your browser. The app downloads the voice you choose from Hugging Face the first time (and the other voice only if you pick it later). Apart from that it makes no network requests of its own: no analytics, no server, no account. Your documents, reading positions and settings stay in the browser's storage (IndexedDB, local storage and the Origin Private File System) and are never uploaded. Clearing the site data in your browser, or **Remove voice data** under More, About and storage, deletes them. +Everything runs in your browser. The app downloads the voice you choose from Hugging Face the first time (and the other voice only if you pick it later). While it is open, it also checks the site it was loaded from for a newer version (a small `version.json` file), and offers to reload when there is one. Apart from that it makes no network requests of its own: no analytics, no server, no account. Your documents, reading positions and settings stay in the browser's storage (IndexedDB, local storage and the Origin Private File System) and are never uploaded. Clearing the site data in your browser, or **Remove voice data** under More, About and storage, deletes them. ## Chrome extension @@ -105,12 +105,21 @@ The extension reads web pages where they are, highlights the word being spoken o ![Reading an article with the extension: the current word and sentence are highlighted on the page, with the floating player in the corner](docs/screenshots/ext-reading.png) -It is not in the Chrome Web Store yet. To install it from the source: +It is not in the Chrome Web Store yet. To install it: -1. Install [Node.js](https://nodejs.org/) 22 or newer and [pnpm](https://pnpm.io/installation). -2. Run `pnpm install` and then `pnpm build:ext` in this folder. -3. Open `chrome://extensions`, turn on **Developer mode**, click **Load unpacked** and pick the `dist-ext` folder. -4. On an article, click the Narrata button and choose **Read this page**, or press Alt+Shift+R. The first time, the player asks which voice to download. +1. Download `narrata-extension-.zip` from the [latest release](https://github.com/Kernel-Hunter/narrata/releases/latest) and unzip it into a folder you will keep. +2. Open `chrome://extensions`, turn on **Developer mode**, click **Load unpacked** and pick that folder. +3. On an article, click the Narrata button and choose **Read this page**, or press Alt+Shift+R. The first time, the player asks which voice to download. + +To build it yourself instead, install [Node.js](https://nodejs.org/) 22 or newer and [pnpm](https://pnpm.io/installation), run `pnpm install` and then `pnpm build:ext` in this folder, and load the `dist-ext` folder. + +**Updating.** Chrome does not update extensions loaded this way. When a new version is out, the Narrata popup says so. To update: + +1. Download the new zip from the release page. +2. Unzip it and copy its files over your Narrata folder. +3. In `chrome://extensions`, click the reload button on Narrata. + +Keep the same folder. Chrome ties an unpacked extension to its folder, so loading a different one, or removing the extension, starts over without your settings and the downloaded voice. What it does: @@ -128,7 +137,7 @@ What it does: | `storage` | Remember your speed, voice and model choice. | | `contextMenus` | The right-click entries. | -There are no host permissions. The extension's content security policy allows network connections only to Hugging Face, for the voice download. +There are no host permissions. The extension's content security policy allows network connections only to Hugging Face, for the voice download, and to `api.github.com`, where the popup checks for a newer release at most once a day. The request sends nothing about what you read. ## Browser support @@ -205,10 +214,12 @@ pnpm build:ext:test # extension with test hooks pnpm audit:licenses # fails on GPL, LGPL or AGPL ``` -`pnpm build:ext:test` builds the extension with hooks for automated checks, in `dist-ext-test/`. `pnpm audit:licenses` checks the licences of everything the builds contain. +`pnpm build:ext:test` builds the extension with hooks for automated checks, in `dist-ext-test/`. `node tests/e2e/verify-update.mjs` checks the web app's update notice against a local copy served the way GitHub Pages serves it, and `node tests/e2e/verify-ext-update.mjs` checks the one in the extension popup. `pnpm audit:licenses` checks the licences of everything the builds contain. The production build uses relative paths, so `dist/` can be served from any path, such as `https://.github.io/narrata/`. `.github/workflows/pages.yml` builds it and deploys it to GitHub Pages; `.github/workflows/ci.yml` runs the tests, type check, both builds and the licence audit on every push and pull request. +The version lives in `package.json`; `pnpm build:ext` copies it into the extension manifest. To publish the extension, bump it, then push a matching tag (`v0.2.0`): `.github/workflows/release.yml` builds the extension and attaches `narrata-extension-.zip` to the GitHub release. + The G2P data in `src/engine/g2p/data/` is generated by the scripts in `scripts/g2p/`; each one explains its inputs at the top. `pnpm dev` and `pnpm build` copy the ONNX Runtime and pdf.js runtime files into `public/`, so the app never loads code from a CDN.
diff --git a/extension/manifest.json b/extension/manifest.json index bc60b06..56c8f5f 100644 --- a/extension/manifest.json +++ b/extension/manifest.json @@ -21,6 +21,6 @@ "cross_origin_embedder_policy": { "value": "require-corp" }, "cross_origin_opener_policy": { "value": "same-origin" }, "content_security_policy": { - "extension_pages": "script-src 'self' 'wasm-unsafe-eval'; object-src 'self'; connect-src 'self' https://huggingface.co https://*.huggingface.co https://*.hf.co; default-src 'self'; img-src 'self' data:; style-src 'self' 'unsafe-inline'; media-src 'self' blob:; worker-src 'self'" + "extension_pages": "script-src 'self' 'wasm-unsafe-eval'; object-src 'self'; connect-src 'self' https://huggingface.co https://*.huggingface.co https://*.hf.co https://api.github.com; default-src 'self'; img-src 'self' data:; style-src 'self' 'unsafe-inline'; media-src 'self' blob:; worker-src 'self'" } } diff --git a/extension/popup.html b/extension/popup.html index 0be9702..56936ab 100644 --- a/extension/popup.html +++ b/extension/popup.html @@ -50,10 +50,15 @@ a { color: inherit; } .links { display: grid; gap: 6px; } footer { padding: 12px 16px 14px; color: var(--muted); font-size: 12px; } + #update { background: var(--surface); } + #update h2 { color: var(--ink); font-size: 13px; text-transform: none; letter-spacing: 0; } + #update ol { margin: 0 0 12px; padding-left: 18px; } + #update li { margin: 2px 0; }

Narrata

+

This page

Checking…

@@ -70,7 +75,7 @@

Shortcuts

-
Private: the voice runs on this computer. The only network request Narrata makes is the one-time voice download from Hugging Face. Nothing you read leaves your browser.
+
Private: the voice runs on this computer. Narrata connects to Hugging Face to download the voice, once, and to GitHub once a day to check for a new version. Nothing you read leaves your browser.
diff --git a/extension/src/popup.ts b/extension/src/popup.ts index 8a89307..35f4eac 100644 --- a/extension/src/popup.ts +++ b/extension/src/popup.ts @@ -1,4 +1,5 @@ -// Toolbar popup: what is happening on this page, the voice download, shortcuts and privacy. +// Toolbar popup: a new version if there is one, what is happening on this page, the voice +// download, shortcuts and privacy. import type { EngineInfo } from '../../src/engine/client'; import { downloadSize } from '../../src/engine/model-store'; @@ -6,6 +7,7 @@ import { icons, logo } from '../../src/ui/icons'; import { choiceHtml, isFirstRun } from './choice'; import { WEB_APP_URL } from './config'; import { type PopupEvent, type PopupRequest, type PopupStatus, envelope, isEnvelope } from './protocol'; +import { type Release, availableUpdate } from './update'; const $ = (sel: string) => document.querySelector(sel) as T; const mb = (n: number) => `${Math.round(n / 1e6)} MB`; @@ -106,6 +108,26 @@ async function refresh() { void renderEngine(s.engine); } +/** The extension cannot update itself when loaded unpacked, so say how. */ +function renderUpdate(release: Release) { + const box = $('#update'); + const zip = `narrata-extension-${release.version}.zip`; + box.innerHTML = `

Update available: v${release.version}

+
  1. Download ${zip} from the release page.
  2. Unzip it and copy the files over your Narrata folder. Keep the same folder, so the voice stays downloaded.
  3. In chrome://extensions, click the reload button on Narrata.
+${icons.download}Open the release page`; + $('#release-link').setAttribute('href', release.url); + $('#extensions-link').onclick = (e) => { + e.preventDefault(); + void chrome.tabs.create({ url: 'chrome://extensions' }); + }; + box.hidden = false; +} + +async function checkForUpdate() { + const release = await availableUpdate(chrome.runtime.getManifest().version, chrome.storage.local).catch(() => null); + if (release) renderUpdate(release); +} + async function shortcuts() { const list = await chrome.commands.getAll(); const names: Record = { 'read-page': 'Read this page', 'read-selection': 'Read selection', 'toggle-reading': 'Play or pause' }; @@ -136,6 +158,7 @@ async function init() { const forced = Number(new URLSearchParams(location.search).get('tab')); const [tab] = forced ? [] : await chrome.tabs.query({ active: true, currentWindow: true }); tabId = forced || (tab?.id ?? -1); + void checkForUpdate(); await Promise.all([refresh(), shortcuts()]); setInterval(refresh, 1500); } diff --git a/extension/src/update.ts b/extension/src/update.ts new file mode 100644 index 0000000..bfade0a --- /dev/null +++ b/extension/src/update.ts @@ -0,0 +1,77 @@ +// Unpacked extensions cannot update themselves. The popup asks GitHub for the latest release, at +// most once a day (the answer is kept in chrome.storage), and offers it when it is newer than the +// version that is running. The request sends nothing about what they read. + +export const RELEASES_API = 'https://api.github.com/repos/Kernel-Hunter/narrata/releases/latest'; +const RELEASES_PAGE = 'https://github.com/Kernel-Hunter/narrata/releases/'; +const KEY = 'update'; +const DAY_MS = 24 * 60 * 60 * 1000; + +export interface Release { + /** Without the leading v, as in the manifest. */ + version: string; + /** The release page on GitHub. */ + url: string; +} + +interface Cached { + checkedAt: number; + latest: Release | null; +} + +/** The part of chrome.storage.local this needs, so tests can pass a stand-in. */ +export interface UpdateStorage { + get(key: string): Promise>; + set(items: Record): Promise; +} + +const parts = (v: string) => v.replace(/^v/i, '').split('.').map((n) => Number.parseInt(n, 10) || 0); + +/** True when `candidate` is a later version than `current` ("0.10.0" is later than "0.9.2"). */ +export function isNewer(candidate: string, current: string): boolean { + const a = parts(candidate); + const b = parts(current); + for (let i = 0; i < Math.max(a.length, b.length); i++) { + const d = (a[i] ?? 0) - (b[i] ?? 0); + if (d !== 0) return d > 0; + } + return false; +} + +/** The release in a GitHub API answer, or null if it is not a usable published release. */ +export function parseRelease(data: unknown): Release | null { + if (!data || typeof data !== 'object') return null; + const r = data as { tag_name?: unknown; html_url?: unknown; draft?: unknown; prerelease?: unknown }; + if (r.draft || r.prerelease || typeof r.tag_name !== 'string' || typeof r.html_url !== 'string') return null; + const version = r.tag_name.replace(/^v/i, ''); + if (!/^\d+(\.\d+){0,3}$/.test(version)) return null; + // Only ever link to this repository's releases. + if (!r.html_url.startsWith(RELEASES_PAGE)) return null; + return { version, url: r.html_url }; +} + +/** + * The latest release, from storage if GitHub was asked less than a day ago. A failed request + * counts as a check too, so an unreachable GitHub is not asked on every popup. + */ +export async function latestRelease(storage: UpdateStorage, now = Date.now(), fetcher: typeof fetch = fetch): Promise { + const stored: Record = await storage.get(KEY).catch(() => ({})); + const cached = stored[KEY] as Cached | undefined; + if (cached && typeof cached.checkedAt === 'number' && now - cached.checkedAt < DAY_MS && now >= cached.checkedAt) return cached.latest; + let latest: Release | null = cached?.latest ?? null; + try { + const res = await fetcher(RELEASES_API, { headers: { Accept: 'application/vnd.github+json' }, credentials: 'omit', cache: 'no-store' }); + if (res.ok) latest = parseRelease(await res.json()); + else if (res.status === 404) latest = null; // no release published yet + } catch { + // Offline: keep what was known. + } + await storage.set({ [KEY]: { checkedAt: now, latest } satisfies Cached }).catch(() => {}); + return latest; +} + +/** The release to offer, or null when the running version is the latest. */ +export async function availableUpdate(current: string, storage: UpdateStorage, now = Date.now(), fetcher: typeof fetch = fetch): Promise { + const latest = await latestRelease(storage, now, fetcher); + return latest && isNewer(latest.version, current) ? latest : null; +} diff --git a/src/main.ts b/src/main.ts index adeed57..2335a6a 100644 --- a/src/main.ts +++ b/src/main.ts @@ -1,7 +1,8 @@ import './styles/app.css'; import { onIsolationReady, registerServiceWorker, reloadForIsolation } from './pwa/register'; +import { reloadForUpdate, watchForUpdates } from './pwa/update'; import { App } from './ui/app'; -import { toast } from './ui/overlay'; +import { notice, toast } from './ui/overlay'; const root = document.getElementById('app')!; @@ -12,6 +13,18 @@ async function boot() { const app = new App(root); // The first install took very long and the app started single-threaded: offer the reload. onIsolationReady(() => toast('Narrata is ready to use all processor cores.', { action: 'Reload', onAction: reloadForIsolation, ms: 60_000 })); + // A newer version was deployed while this page was open. Reload only when asked, so playback + // is never cut off; the document and the reading position are saved first. + watchForUpdates(() => + notice('Narrata was updated. Reload to get the new version.', { + action: 'Reload', + className: 'update-notice', + onAction: async () => { + if (!(await app.prepareReload())) return false; + await reloadForUpdate(); + }, + }), + ); // Files opened with the installed app ("Open with Narrata"). const lq = (window as unknown as { launchQueue?: { setConsumer(cb: (p: { files: FileSystemFileHandle[] }) => void): void } }).launchQueue; lq?.setConsumer(async (params) => { diff --git a/src/pwa/sw.js b/src/pwa/sw.js index 58d8434..7f201a8 100644 --- a/src/pwa/sw.js +++ b/src/pwa/sw.js @@ -20,6 +20,7 @@ const abs = (p) => new URL(p, self.registration.scope).href; const revByUrl = new Map(Object.entries(REVS).map(([p, r]) => [abs(p), r])); const assetsPrefix = abs('./assets/'); const appUrls = new Set([abs('./'), abs('./index.html')]); +const versionUrl = abs('./version.json'); /** URL without query or fragment, the key files are cached under. */ const keyOf = (url) => { const u = new URL(url); @@ -211,5 +212,7 @@ self.addEventListener('fetch', (event) => { const url = new URL(req.url); if (url.origin !== self.location.origin) return; if (req.cache === 'only-if-cached' && req.mode !== 'same-origin') return; + // The page checks this file for a newer deploy, so it always comes from the network. + if (keyOf(req.url) === versionUrl) return; event.respondWith(req.mode === 'navigate' ? navigate(req) : asset(req, event)); }); diff --git a/src/pwa/update.ts b/src/pwa/update.ts new file mode 100644 index 0000000..3678217 --- /dev/null +++ b/src/pwa/update.ts @@ -0,0 +1,101 @@ +// Tells a page that stays open when a newer version of Narrata has been deployed. The build +// writes its id into index.html () and into version.json next to it +// (see vite.config.ts). The service worker never caches version.json, so when the two differ, +// this page is out of date. +// +// The page checks when it becomes visible again (at most once a minute), every 30 minutes, when +// the connection comes back, and when the browser finds a new service worker by itself. It never +// reloads on its own: the app shows a notice and reloads when the user asks (see main.ts). + +const CHECK_EVERY_MS = 30 * 60_000; +/** Switching tabs back and forth checks at most this often. */ +const MIN_GAP_MS = 60_000; +/** Longest wait for the new service worker before reloading anyway. */ +const WORKER_WAIT_MS = 10_000; + +/** The build id of the running page, or null in development. */ +export function currentBuild(doc: Document = document): string | null { + return doc.querySelector('meta[name="narrata-build"]')?.content || null; +} + +/** The build id of the latest deploy, or null when it cannot be read (offline, for example). */ +export async function latestBuild(base: string = document.baseURI, fetcher: typeof fetch = fetch): Promise { + try { + // The query and no-store skip every cache on the way (GitHub Pages sends max-age=600). + const url = new URL('./version.json', base); + url.searchParams.set('t', String(Date.now())); + const res = await fetcher(url, { cache: 'no-store' }); + if (!res.ok) return null; + const data = (await res.json()) as { build?: unknown }; + return typeof data.build === 'string' && data.build ? data.build : null; + } catch { + return null; + } +} + +/** Calls `onUpdate` once, when a deploy newer than this page is found. */ +export function watchForUpdates(onUpdate: () => void): void { + const mine = currentBuild(); + if (!mine) return; + let found = false; + let running = false; + let last = 0; + const check = async (force = false) => { + if (found || running || !navigator.onLine) return; + if (!force && Date.now() - last < MIN_GAP_MS) return; + running = true; + last = Date.now(); + const latest = await latestBuild(); + running = false; + if (found || !latest || latest === mine) return; + found = true; + clearInterval(timer); + // Let the service worker cache the new version now, so the reload is quick and works offline. + void navigator.serviceWorker?.getRegistration().then((reg) => reg?.update()).catch(() => {}); + onUpdate(); + }; + const timer = setInterval(() => void check(true), CHECK_EVERY_MS); + document.addEventListener('visibilitychange', () => { + if (!document.hidden) void check(); + }); + addEventListener('online', () => void check()); + // The browser checks for a new service worker on its own too (on navigations, for example). + void navigator.serviceWorker + ?.getRegistration() + .then((reg) => + reg?.addEventListener('updatefound', () => { + const worker = reg.installing; + worker?.addEventListener('statechange', () => { + if (worker.state === 'activated') void check(true); + }); + }), + ) + .catch(() => {}); +} + +/** Resolves when the registration has no worker installing, or after `ms`. */ +async function workerSettled(reg: ServiceWorkerRegistration, ms: number): Promise { + await Promise.race([ + (async () => { + await reg.update().catch(() => {}); + const worker = reg.installing ?? reg.waiting; + if (!worker) return; + await new Promise((resolve) => { + const done = () => worker.state === 'activated' || worker.state === 'redundant'; + if (done()) return resolve(); + worker.addEventListener('statechange', () => done() && resolve()); + }); + })(), + new Promise((resolve) => setTimeout(resolve, ms)), + ]); +} + +/** + * Reloads into the new version. Waits briefly for the new service worker, which caches the new + * app shell as it installs, so the reload does not fall back to the previous version's copy. + */ +export async function reloadForUpdate(): Promise { + const reg = await navigator.serviceWorker?.getRegistration().catch(() => undefined); + if (reg) await workerSettled(reg, WORKER_WAIT_MS); + location.reload(); +} diff --git a/src/styles/app.css b/src/styles/app.css index 118c148..0093916 100644 --- a/src/styles/app.css +++ b/src/styles/app.css @@ -832,6 +832,10 @@ kbd { .toast button { border: 0; background: none; color: var(--logo-accent); font-weight: 650; padding: 4px 6px; border-radius: 8px; } .toast.error { background: var(--danger); color: #fff; } .toast.error button { color: #fff; } +.toast button:disabled { opacity: 0.6; } +.toast .notice-close { display: grid; place-items: center; width: 28px; height: 28px; margin-left: -6px; padding: 0; color: inherit; opacity: 0.7; } +.toast .notice-close:hover { opacity: 1; } +.toast .notice-close svg { width: 16px; height: 16px; } .drop-overlay { position: fixed; diff --git a/src/ui/app.ts b/src/ui/app.ts index cd4aaeb..ff6aaa9 100644 --- a/src/ui/app.ts +++ b/src/ui/app.ts @@ -856,6 +856,25 @@ export class App { this.schedulePositionSave(word.start); } + /** + * Before a reload into a new version: pauses and saves the reading position now (it is + * otherwise saved a moment after each word). Returns false while a voice is downloading, so + * the download is not cut off. + */ + async prepareReload(): Promise { + const info = this.tts.info; + if (info.state === 'downloading' || info.voiceDownload) { + toast('Reload when the voice download has finished.'); + return false; + } + this.player.pause(); + clearTimeout(this.saveTimer); + this.saveTimer = 0; + const meta = this.doc?.meta; + if (meta && this.player.state !== 'ended') await this.library.savePosition(meta.id, this.player.currentOffset()).catch(() => null); + return true; + } + private schedulePositionSave(offset: number) { const meta = this.doc?.meta; if (!meta || this.saveTimer) return; diff --git a/src/ui/overlay.ts b/src/ui/overlay.ts index 9a0799b..fb25fca 100644 --- a/src/ui/overlay.ts +++ b/src/ui/overlay.ts @@ -91,8 +91,9 @@ export function sheet(title: string, body: Node[], opts: { onClose?: () => void; let region: HTMLElement | null = null; +const toastRegion = () => (region ??= document.body.appendChild(h('div', { class: 'toast-region', role: 'status', 'aria-live': 'polite' }))); + export function toast(message: string, opts: { action?: string; onAction?: () => void; error?: boolean; ms?: number } = {}): void { - region ??= document.body.appendChild(h('div', { class: 'toast-region', role: 'status', 'aria-live': 'polite' })); const el = h('div', { class: `toast${opts.error ? ' error' : ''}` }, h('span', { class: 'grow' }, message)); const remove = () => el.remove(); if (opts.action) { @@ -105,6 +106,25 @@ export function toast(message: string, opts: { action?: string; onAction?: () => }, opts.action), ); } - region.append(el); + toastRegion().append(el); setTimeout(remove, opts.ms ?? (opts.action ? 6000 : 3500)); } + +/** + * A toast that stays until it is closed, with one action. The action may return false to keep + * the notice open (it is disabled while the action runs). + */ +export function notice(message: string, opts: { action: string; onAction: () => Promise | boolean | void; className?: string }): () => void { + const el = h('div', { class: `toast notice${opts.className ? ` ${opts.className}` : ''}` }, h('span', { class: 'grow' }, message)); + const remove = () => el.remove(); + const action = h('button', {}, opts.action) as HTMLButtonElement; + action.addEventListener('click', async () => { + action.disabled = true; + const keep = (await opts.onAction()) === false; + action.disabled = false; + if (!keep) remove(); + }); + el.append(action, h('button', { class: 'notice-close', 'aria-label': 'Close', title: 'Close', html: icons.close, onclick: remove })); + toastRegion().append(el); + return remove; +} diff --git a/tests/e2e/verify-ext-update.mjs b/tests/e2e/verify-ext-update.mjs new file mode 100644 index 0000000..213c8a0 --- /dev/null +++ b/tests/e2e/verify-ext-update.mjs @@ -0,0 +1,69 @@ +// Checks the update notice in the extension popup, with GitHub's answer stubbed. +// +// pnpm build:ext:test && node tests/e2e/verify-ext-update.mjs [--headed] [--shots DIR] +// +// Loads dist-ext-test/ unpacked in a fresh profile and opens the popup as a page: once with a +// release newer than the manifest version (the notice shows, and a second popup within the day +// does not ask GitHub again), once with the same version (no notice). +import { mkdtempSync, mkdirSync, readFileSync, rmSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { extPath, launch, root, sleep } from './harness.mjs'; + +const args = process.argv.slice(2); +const headless = !args.includes('--headed'); +const i = args.indexOf('--shots'); +const shots = i >= 0 ? args[i + 1] : join(root, 'docs', 'screenshots'); +mkdirSync(shots, { recursive: true }); +const current = JSON.parse(readFileSync(join(extPath, 'manifest.json'), 'utf8')).version; +const bump = (v) => v.split('.').map((n, k) => (k === 1 ? Number(n) + 1 : k === 2 ? 0 : n)).join('.'); + +let failed = 0; +function check(name, ok, detail) { + if (!ok) failed++; + console.log(`${ok ? 'PASS' : 'FAIL'} ${name}${detail === undefined ? '' : ' ' + JSON.stringify(detail)}`); +} + +/** A fresh profile whose popup sees `tag` as GitHub's latest release. */ +async function run(tag, shot) { + const profile = mkdtempSync(join(tmpdir(), 'narrata-ext-update-')); + const ctx = await launch({ userDataDir: profile, headless }); + let calls = 0; + await ctx.context.route('https://api.github.com/**', (route) => { + calls++; + route.fulfill({ + status: 200, + contentType: 'application/json', + headers: { 'access-control-allow-origin': '*' }, + body: JSON.stringify({ tag_name: tag, html_url: `https://github.com/Kernel-Hunter/narrata/releases/tag/${tag}`, draft: false, prerelease: false }), + }); + }); + const open = async () => { + const popup = await ctx.context.newPage(); + await popup.setViewportSize({ width: 340, height: 600 }); + await popup.goto(`chrome-extension://${ctx.extId}/popup.html`); + await sleep(1500); + return popup; + }; + const popup = await open(); + const box = popup.locator('#update'); + const result = { visible: await box.isVisible(), text: (await box.textContent()) ?? '', href: await popup.locator('#release-link').getAttribute('href').catch(() => null), calls }; + if (shot) await popup.screenshot({ path: join(shots, shot) }); + await popup.close(); + const again = await open(); + result.visibleAgain = await again.locator('#update').isVisible(); + result.callsAfterSecond = calls; + await ctx.context.close(); + rmSync(profile, { recursive: true, force: true }); + return result; +} + +const newer = bump(current); +const a = await run(`v${newer}`, 'ext-update-notice.png'); +check(`a newer release (v${newer}, running v${current}) shows the notice`, a.visible && a.text.includes(`Update available: v${newer}`) && a.text.includes(`narrata-extension-${newer}.zip`), a); +check('the button opens the release page', a.href === `https://github.com/Kernel-Hunter/narrata/releases/tag/v${newer}`, a.href); +check('GitHub is asked once, the second popup uses the stored answer', a.calls === 1 && a.callsAfterSecond === 1 && a.visibleAgain, { calls: a.callsAfterSecond }); +const b = await run(`v${current}`, 'ext-update-none.png'); +check('no notice when up to date', !b.visible && b.calls === 1, b); +console.log(failed ? `${failed} check(s) failed` : 'All checks passed'); +process.exit(failed ? 1 : 0); diff --git a/tests/e2e/verify-update.mjs b/tests/e2e/verify-update.mjs new file mode 100644 index 0000000..5fa103c --- /dev/null +++ b/tests/e2e/verify-update.mjs @@ -0,0 +1,165 @@ +// End-to-end check of the update notice in the web app, the way GitHub Pages serves it. +// +// node tests/e2e/verify-update.mjs [--headed] [--profile DIR] [--port 5350] [--shots DIR] +// +// Builds version A into a folder served under /narrata/ without isolation headers (like Pages, +// with its max-age=600), opens it and waits for the service worker to isolate the page. Opens the +// sample, starts reading, then builds version B into the same folder while it plays. Checks that +// the notice appears, that nothing reloads while audio plays, and that Reload brings version B, +// still isolated, on the same document and position, with the stored voice untouched. +// +// The voice is downloaded into the profile the first time (about 180 MB); later runs reuse it. +// Writes update-notice.png and update-notice-close.png to docs/screenshots/ (or --shots). +import { createHash } from 'node:crypto'; +import { createServer } from 'node:http'; +import { existsSync, mkdirSync, readFileSync, rmSync, statSync } from 'node:fs'; +import { extname, join, normalize } from 'node:path'; +import { chromium } from '@playwright/test'; +import { build } from 'vite'; +import { root, sleep, waitFor } from './harness.mjs'; + +const args = process.argv.slice(2); +const arg = (name, def) => { + const i = args.indexOf(name); + return i >= 0 ? args[i + 1] : def; +}; +const headless = !args.includes('--headed'); +const profile = arg('--profile', join(root, '.e2e-profile-update')); +const port = Number(arg('--port', '5350')); +const served = join(root, '.e2e-update-site'); +const shots = arg('--shots', join(root, 'docs', 'screenshots')); +mkdirSync(shots, { recursive: true }); + +let failed = 0; +function check(name, ok, detail) { + if (!ok) failed++; + console.log(`${ok ? 'PASS' : 'FAIL'} ${name}${detail === undefined ? '' : ' ' + JSON.stringify(detail)}`); +} + +/** Builds the app into the served folder. Version B also marks itself so the test can tell. */ +async function buildVersion(label) { + const plugins = + label === 'B' + ? [{ name: 'mark-b', transform: (code, id) => (id.endsWith('/src/main.ts') ? `${code}\n;window.narrataTestBuild = 'B';\n` : null) }] + : []; + await build({ root, configFile: join(root, 'vite.config.ts'), logLevel: 'warn', plugins, build: { outDir: served, emptyOutDir: true } }); + return JSON.parse(readFileSync(join(served, 'version.json'), 'utf8')).build; +} + +const types = { '.html': 'text/html; charset=utf-8', '.js': 'text/javascript', '.mjs': 'text/javascript', '.css': 'text/css', '.json': 'application/json', '.wasm': 'application/wasm', '.svg': 'image/svg+xml', '.png': 'image/png', '.webmanifest': 'application/manifest+json' }; + +/** Static files under /narrata/ with GitHub Pages' caching and no COOP/COEP headers. */ +function serve() { + const server = createServer((req, res) => { + const url = new URL(req.url, 'http://x'); + if (!url.pathname.startsWith('/narrata/')) return res.writeHead(404).end(); + let rel = decodeURIComponent(url.pathname.slice('/narrata/'.length)) || 'index.html'; + if (rel.endsWith('/')) rel += 'index.html'; + const file = normalize(join(served, rel)); + if (!file.startsWith(served) || !existsSync(file) || statSync(file).isDirectory()) return res.writeHead(404).end('not found'); + const data = readFileSync(file); + const etag = `"${createHash('sha1').update(data).digest('hex').slice(0, 16)}"`; + const headers = { 'content-type': types[extname(file)] ?? 'application/octet-stream', 'cache-control': 'max-age=600', etag }; + if (req.headers['if-none-match'] === etag) return res.writeHead(304, headers).end(); + res.writeHead(200, headers).end(data); + }); + server.listen(port, 'localhost'); + return server; +} + +const buildA = await buildVersion('A'); +const server = serve(); +const base = `http://localhost:${port}/narrata/`; + +// A worker kept from an earlier run would serve its own cached build. +rmSync(join(profile, 'Default', 'Service Worker'), { recursive: true, force: true }); +const context = await chromium.launchPersistentContext(profile, { + channel: 'chromium', + headless, + viewport: { width: 1100, height: 760 }, + deviceScaleFactor: 2, + args: ['--autoplay-policy=no-user-gesture-required'], +}); +const page = context.pages()[0] ?? (await context.newPage()); +page.on('pageerror', (e) => console.log('page error:', e.message)); +let navigations = 0; +page.on('framenavigated', (f) => f === page.mainFrame() && navigations++); + +const ready = () => page.waitForFunction(() => self.crossOriginIsolated && window.narrata?.app, null, { timeout: 90_000 }); +const pageBuild = () => page.evaluate(() => document.querySelector('meta[name="narrata-build"]')?.content ?? null); +const notice = page.locator('.update-notice'); +/** Model files in the Origin Private File System, with their sizes. */ +const storedModels = () => + page.evaluate(async () => { + const out = {}; + try { + const models = await (await navigator.storage.getDirectory()).getDirectoryHandle('models'); + for await (const [name, dir] of models.entries()) { + if (dir.kind !== 'directory') continue; + for await (const [file, h] of dir.entries()) if (h.kind === 'file') out[`${name}/${file}`] = (await h.getFile()).size; + } + } catch {} + return out; + }); + +// 1. Version A, first visit: the worker installs, the page reloads once and is isolated. +await page.goto(base); +await ready(); +check('version A loads and is cross-origin isolated after the first visit', (await pageBuild()) === buildA, { build: buildA, navigations }); +check('no update notice on the current version', (await notice.count()) === 0); + +// 2. Open the sample (no #sample in the address, so a reload must reopen it from the library). +await page.evaluate(async () => { + localStorage.setItem('narrata.settings', JSON.stringify({ ...JSON.parse(localStorage.getItem('narrata.settings') || '{}'), model: 'compact' })); +}); +await page.evaluate(() => window.narrata.app.openSample()); +await page.waitForFunction(() => document.title.startsWith('The Lighthouse Keeper')); +console.log('preparing the voice (downloads it the first time)…'); +await page.evaluate(() => window.narrata.tts.prepare('compact', window.narrata.app.settings.voice)); +await waitFor(() => page.evaluate(() => window.narrata.tts.info.state === 'ready'), { timeout: 600_000, label: 'voice ready' }); +const modelsBefore = await storedModels(); +check('the voice is stored in the Origin Private File System', Object.keys(modelsBefore).some((f) => f.endsWith('.onnx')), modelsBefore); + +await page.locator('.play-btn').click(); +await waitFor(() => page.evaluate(() => window.narrata.player.state === 'playing'), { timeout: 120_000, label: 'playback' }); +await sleep(1500); +const wordBefore = await page.evaluate(() => window.narrata.player.currentWord()); +await page.evaluate(() => (window.notReloaded = true)); +const navBefore = navigations; + +// 3. Deploy version B while it reads, and let the page check (as when the tab is shown again). +const buildB = await buildVersion('B'); +check('version B has another build id', buildB !== buildA, { buildA, buildB }); +await page.evaluate(() => document.dispatchEvent(new Event('visibilitychange'))); +await notice.waitFor({ timeout: 30_000 }); +check('the notice appears', (await notice.textContent()).includes('Narrata was updated. Reload to get the new version.')); +await sleep(6000); +const during = await page.evaluate(() => ({ state: window.narrata.player.state, word: window.narrata.player.currentWord(), marker: window.notReloaded === true })); +check('no reload while audio plays', during.marker && navigations === navBefore && during.state === 'playing' && during.word > wordBefore, { ...during, wordBefore, navigations: navigations - navBefore }); +await page.screenshot({ path: join(shots, 'update-notice.png') }); +await notice.screenshot({ path: join(shots, 'update-notice-close.png') }); + +// 4. Reload: playback pauses, the position is saved, and version B opens. +await notice.getByRole('button', { name: 'Reload' }).click(); +await page.waitForFunction(() => !window.notReloaded, null, { timeout: 30_000 }).catch(() => {}); +await ready(); +await page.waitForFunction(() => document.title.startsWith('The Lighthouse Keeper'), null, { timeout: 30_000 }); +const after = await page.evaluate(async () => { + const meta = (await window.narrata.library.list())[0]; + return { testBuild: window.narrataTestBuild ?? null, isolated: self.crossOriginIsolated, saved: meta?.position ?? null, at: window.narrata.player.currentOffset(), title: document.title }; +}); +const wordAt = await page.evaluate(() => window.narrata.player.currentWord()); +check('Reload gives version B', (await pageBuild()) === buildB && after.testBuild === 'B', { build: await pageBuild(), testBuild: after.testBuild }); +check('still cross-origin isolated', after.isolated === true); +check('the same document is open', after.title.startsWith('The Lighthouse Keeper'), after.title); +check('the reading position is kept', after.saved > 0 && after.at === after.saved && wordAt >= during.word, { saved: after.saved, at: after.at, wordAt, wordAtNotice: during.word }); +check('no notice after updating', (await notice.count()) === 0); +const modelsAfter = await storedModels(); +check('the stored voice is untouched', JSON.stringify(modelsAfter) === JSON.stringify(modelsBefore), { files: Object.keys(modelsAfter).length }); +const caches = await page.evaluate(() => caches.keys()); +check('the app cache moved to version B', caches.includes(`narrata-${buildB}`), caches); + +await context.close(); +server.close(); +console.log(failed ? `${failed} check(s) failed` : 'All checks passed'); +process.exit(failed ? 1 : 0); diff --git a/tests/ext-update.test.ts b/tests/ext-update.test.ts new file mode 100644 index 0000000..a9a9e98 --- /dev/null +++ b/tests/ext-update.test.ts @@ -0,0 +1,69 @@ +import { describe, expect, it } from 'vitest'; +import { RELEASES_API, type UpdateStorage, availableUpdate, isNewer, parseRelease } from '../extension/src/update'; + +const DAY = 24 * 60 * 60 * 1000; + +function memoryStorage(): UpdateStorage & { data: Record } { + const data: Record = {}; + return { + data, + get: async (key) => (key in data ? { [key]: data[key] } : {}), + set: async (items) => void Object.assign(data, items), + }; +} + +function github(body: unknown, status = 200) { + const calls: string[] = []; + const fetcher = (async (url: URL | RequestInfo) => { + calls.push(String(url)); + return new Response(JSON.stringify(body), { status }); + }) as typeof fetch; + return { fetcher, calls }; +} + +const release = (tag: string) => ({ tag_name: tag, html_url: `https://github.com/Kernel-Hunter/narrata/releases/tag/${tag}`, draft: false, prerelease: false }); + +describe('extension update check', () => { + it('compares versions number by number', () => { + expect(isNewer('0.2.0', '0.1.0')).toBe(true); + expect(isNewer('v0.10.0', '0.9.2')).toBe(true); + expect(isNewer('1.0', '0.99.99')).toBe(true); + expect(isNewer('0.1.0', '0.1.0')).toBe(false); + expect(isNewer('0.1', '0.1.0')).toBe(false); + expect(isNewer('0.1.0', '0.2.0')).toBe(false); + }); + + it('reads only published releases of this repository', () => { + expect(parseRelease(release('v0.2.0'))).toEqual({ version: '0.2.0', url: 'https://github.com/Kernel-Hunter/narrata/releases/tag/v0.2.0' }); + expect(parseRelease({ ...release('v0.2.0'), prerelease: true })).toBeNull(); + expect(parseRelease({ ...release('v0.2.0'), draft: true })).toBeNull(); + expect(parseRelease({ ...release('v0.2.0'), html_url: 'https://evil.example/narrata' })).toBeNull(); + expect(parseRelease(release('nightly'))).toBeNull(); + expect(parseRelease(null)).toBeNull(); + }); + + it('offers a newer release and asks GitHub at most once a day', async () => { + const storage = memoryStorage(); + const gh = github(release('v0.2.0')); + const now = 1_000_000_000_000; + expect(await availableUpdate('0.1.0', storage, now, gh.fetcher)).toEqual({ version: '0.2.0', url: release('v0.2.0').html_url }); + expect(gh.calls).toEqual([RELEASES_API]); + expect(await availableUpdate('0.1.0', storage, now + DAY - 1, gh.fetcher)).not.toBeNull(); + expect(gh.calls).toHaveLength(1); + // Updated in the meantime: the cached answer is not newer any more. + expect(await availableUpdate('0.2.0', storage, now + 1000, gh.fetcher)).toBeNull(); + await availableUpdate('0.1.0', storage, now + DAY, gh.fetcher); + expect(gh.calls).toHaveLength(2); + }); + + it('offers nothing when up to date, without a release, or offline', async () => { + expect(await availableUpdate('0.2.0', memoryStorage(), Date.now(), github(release('v0.2.0')).fetcher)).toBeNull(); + expect(await availableUpdate('0.1.0', memoryStorage(), Date.now(), github({ message: 'Not Found' }, 404).fetcher)).toBeNull(); + const storage = memoryStorage(); + const offline = (async () => { + throw new TypeError('Failed to fetch'); + }) as typeof fetch; + expect(await availableUpdate('0.1.0', storage, Date.now(), offline)).toBeNull(); + expect(storage.data.update).toMatchObject({ latest: null }); + }); +}); diff --git a/tests/update.test.ts b/tests/update.test.ts new file mode 100644 index 0000000..7f8cdb1 --- /dev/null +++ b/tests/update.test.ts @@ -0,0 +1,43 @@ +// @vitest-environment jsdom +import { describe, expect, it } from 'vitest'; +import { currentBuild, latestBuild } from '../src/pwa/update'; + +const base = 'https://example.org/narrata/'; + +function fakeFetch(body: unknown, init: { status?: number; fail?: boolean } = {}) { + const calls: { url: string; init?: RequestInit }[] = []; + const fetcher = (async (url: URL | RequestInfo, opts?: RequestInit) => { + calls.push({ url: String(url), init: opts }); + if (init.fail) throw new TypeError('offline'); + return new Response(typeof body === 'string' ? body : JSON.stringify(body), { status: init.status ?? 200 }); + }) as typeof fetch; + return { fetcher, calls }; +} + +describe('update check', () => { + it('reads the build id of the page from index.html', () => { + expect(currentBuild()).toBeNull(); + const meta = document.createElement('meta'); + meta.name = 'narrata-build'; + meta.content = 'abc123def456'; + document.head.append(meta); + expect(currentBuild()).toBe('abc123def456'); + }); + + it('fetches version.json next to the page, past every cache', async () => { + const { fetcher, calls } = fakeFetch({ version: '0.1.0', build: 'b2' }); + expect(await latestBuild(base, fetcher)).toBe('b2'); + const url = new URL(calls[0].url); + expect(url.origin + url.pathname).toBe('https://example.org/narrata/version.json'); + expect(url.searchParams.get('t')).toMatch(/^\d+$/); + expect(calls[0].init?.cache).toBe('no-store'); + }); + + it('gives null when the file cannot be read', async () => { + expect(await latestBuild(base, fakeFetch({}, { fail: true }).fetcher)).toBeNull(); + expect(await latestBuild(base, fakeFetch('not found', { status: 404 }).fetcher)).toBeNull(); + expect(await latestBuild(base, fakeFetch('').fetcher)).toBeNull(); + expect(await latestBuild(base, fakeFetch({ build: 42 }).fetcher)).toBeNull(); + expect(await latestBuild(base, fakeFetch({ build: '' }).fetcher)).toBeNull(); + }); +}); diff --git a/vite.config.ts b/vite.config.ts index 59bd201..bda7d16 100644 --- a/vite.config.ts +++ b/vite.config.ts @@ -36,7 +36,7 @@ function shellFiles(outDir: string, all: Set): string[] { * Writes dist/sw.js with two lists: SHELL, cached while the worker installs (small, so the page * becomes cross-origin isolated within seconds even on a slow link), and PRECACHE, every other * built file with a short content hash, cached in the background once the worker runs so the - * app works offline after the first visit. + * app works offline after the first visit. Also writes dist/version.json with the build id. */ function serviceWorker(): Plugin { let outDir = 'dist'; @@ -60,20 +60,25 @@ function serviceWorker(): Plugin { } }; walk(outDir); - const list = files.filter((f) => f !== 'sw.js' && !f.endsWith('.map')).sort(); + const list = files.filter((f) => f !== 'sw.js' && f !== 'version.json' && !f.endsWith('.map')).sort(); const template = readFileSync('src/pwa/sw.js', 'utf8'); - const version = createHash('sha256').update(template); + const hash = createHash('sha256').update(template); + for (const f of list) hash.update(f).update(readFileSync(join(outDir, f))); + const version = hash.digest('hex').slice(0, 12); + // The page reads its own build id from index.html and compares it with version.json, which + // the service worker never caches, to tell when a newer deploy is out (src/pwa/update.ts). + const indexPath = join(outDir, 'index.html'); + const html = readFileSync(indexPath, 'utf8'); + writeFileSync(indexPath, html.replace('', ` \n `)); + const pkg = JSON.parse(readFileSync('package.json', 'utf8')) as { version: string }; + writeFileSync(join(outDir, 'version.json'), JSON.stringify({ version: pkg.version, build: version }) + '\n'); const revs: Record = {}; - for (const f of list) { - const data = readFileSync(join(outDir, f)); - version.update(f).update(data); - revs[`./${f}`] = createHash('sha256').update(data).digest('hex').slice(0, 10); - } + for (const f of list) revs[`./${f}`] = createHash('sha256').update(readFileSync(join(outDir, f))).digest('hex').slice(0, 10); revs['./'] = revs['./index.html']; const shell = ['./', ...shellFiles(outDir, new Set(list)).map((f) => `./${f}`)]; const rest = Object.keys(revs).filter((f) => !shell.includes(f)); const src = template - .replaceAll('__VERSION__', version.digest('hex').slice(0, 12)) + .replaceAll('__VERSION__', version) .replaceAll('__SHELL__', JSON.stringify(shell)) .replaceAll('__PRECACHE__', JSON.stringify(rest)) .replaceAll('__REVS__', JSON.stringify(revs));