[app] CalmRefresh: Register the worker in the app and offer the waiting version; e2e publishes a real second one
This commit is contained in:
@@ -22,6 +22,7 @@
|
|||||||
"svelte-check": "4.7.6",
|
"svelte-check": "4.7.6",
|
||||||
"typescript": "5.9.3",
|
"typescript": "5.9.3",
|
||||||
"vite": "6.4.3",
|
"vite": "6.4.3",
|
||||||
"vite-plugin-pwa": "1.3.0"
|
"vite-plugin-pwa": "1.3.0",
|
||||||
|
"workbox-window": "7.4.1"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -3,6 +3,7 @@
|
|||||||
import { createIdentity } from '@rosea/identity';
|
import { createIdentity } from '@rosea/identity';
|
||||||
import { openStorage } from '@rosea/storage';
|
import { openStorage } from '@rosea/storage';
|
||||||
import { Shell, type RoseWiring, type SunsetWiring } from '@rosea/ui';
|
import { Shell, type RoseWiring, type SunsetWiring } from '@rosea/ui';
|
||||||
|
import { registerSW } from 'virtual:pwa-register';
|
||||||
import { version } from '../package.json';
|
import { version } from '../package.json';
|
||||||
// Bundled at build time, so the letter is precached and opens offline (letter-slot.md L1).
|
// Bundled at build time, so the letter is precached and opens offline (letter-slot.md L1).
|
||||||
import letter from '../../../docs/LETTER.md?raw';
|
import letter from '../../../docs/LETTER.md?raw';
|
||||||
@@ -75,6 +76,15 @@
|
|||||||
setTimeout(() => URL.revokeObjectURL(url), 10_000);
|
setTimeout(() => URL.revokeObjectURL(url), 10_000);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// --- A new version waiting (calm-refresh.md) ----------------------------
|
||||||
|
// The worker is registered here so the page hears when a new version has installed
|
||||||
|
// and waits. It is offered, never swapped in by itself (U2).
|
||||||
|
let updateReady = $state(false);
|
||||||
|
const updateSW = registerSW({
|
||||||
|
onNeedRefresh: () => (updateReady = true),
|
||||||
|
onRegisterError: (error: unknown) => console.error('update: the service worker could not be registered', error)
|
||||||
|
});
|
||||||
|
|
||||||
const rose: RoseWiring = {
|
const rose: RoseWiring = {
|
||||||
identity: () => (identity ??= findIdentity()),
|
identity: () => (identity ??= findIdentity()),
|
||||||
loadCare: () => storage.loadCare(),
|
loadCare: () => storage.loadCare(),
|
||||||
@@ -94,4 +104,4 @@
|
|||||||
};
|
};
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
<Shell {letter} {sunset} {rose} />
|
<Shell {letter} {sunset} {rose} {updateReady} onrefresh={() => void updateSW(true)} />
|
||||||
|
|||||||
Vendored
+1
@@ -1,2 +1,3 @@
|
|||||||
/// <reference types="svelte" />
|
/// <reference types="svelte" />
|
||||||
/// <reference types="vite/client" />
|
/// <reference types="vite/client" />
|
||||||
|
/// <reference types="vite-plugin-pwa/client" />
|
||||||
|
|||||||
@@ -66,9 +66,10 @@ export default defineConfig({
|
|||||||
// Never swap a running app silently. A new worker waits until the player
|
// Never swap a running app silently. A new worker waits until the player
|
||||||
// is offered a calm refresh control (CLAUDE.md §8, GAP_ANALYSIS G0.10).
|
// is offered a calm refresh control (CLAUDE.md §8, GAP_ANALYSIS G0.10).
|
||||||
registerType: 'prompt',
|
registerType: 'prompt',
|
||||||
// An emitted registerSW.js file, not an inline snippet: the CSP has no
|
// The app registers the worker itself through virtual:pwa-register, so it hears
|
||||||
// 'unsafe-inline' for scripts.
|
// when a new version is waiting (calm-refresh.md U1). Bundled, not inline: the
|
||||||
injectRegister: 'script',
|
// CSP has no 'unsafe-inline' for scripts.
|
||||||
|
injectRegister: false,
|
||||||
manifest: {
|
manifest: {
|
||||||
// The web manifest: one of the three places the name lives, built from
|
// The web manifest: one of the three places the name lives, built from
|
||||||
// the constants in @rosea/schema so the strings exist only there.
|
// the constants in @rosea/schema so the strings exist only there.
|
||||||
|
|||||||
@@ -7,7 +7,7 @@ import { defineConfig, devices } from '@playwright/test';
|
|||||||
*/
|
*/
|
||||||
export default defineConfig({
|
export default defineConfig({
|
||||||
testDir: '.',
|
testDir: '.',
|
||||||
testMatch: /shell\.spec\.ts/,
|
testMatch: /(shell|update)\.spec\.ts/,
|
||||||
fullyParallel: false,
|
fullyParallel: false,
|
||||||
workers: 1,
|
workers: 1,
|
||||||
retries: 0,
|
retries: 0,
|
||||||
|
|||||||
+10
-4
@@ -19,7 +19,7 @@ import { fileURLToPath } from 'node:url';
|
|||||||
*/
|
*/
|
||||||
|
|
||||||
export const BASE = process.env['ROSEA_BASE'] ?? '/Rosea/';
|
export const BASE = process.env['ROSEA_BASE'] ?? '/Rosea/';
|
||||||
const DIST = fileURLToPath(new URL('../apps/rosea/dist', import.meta.url));
|
export const DIST = fileURLToPath(new URL('../apps/rosea/dist', import.meta.url));
|
||||||
|
|
||||||
const MIME: Record<string, string> = {
|
const MIME: Record<string, string> = {
|
||||||
'.html': 'text/html; charset=utf-8',
|
'.html': 'text/html; charset=utf-8',
|
||||||
@@ -36,6 +36,8 @@ export interface StaticServer {
|
|||||||
readonly url: string;
|
readonly url: string;
|
||||||
readonly origin: string;
|
readonly origin: string;
|
||||||
readonly close: () => Promise<void>;
|
readonly close: () => Promise<void>;
|
||||||
|
/** Serves another build from now on, at the same URL: a new version being published. */
|
||||||
|
readonly serveFrom: (dir: string) => void;
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function startStaticServer(): Promise<StaticServer> {
|
export async function startStaticServer(): Promise<StaticServer> {
|
||||||
@@ -45,6 +47,7 @@ export async function startStaticServer(): Promise<StaticServer> {
|
|||||||
throw new Error(`No built app at ${DIST}. Run \`pnpm build\` first. (${String(error)})`);
|
throw new Error(`No built app at ${DIST}. Run \`pnpm build\` first. (${String(error)})`);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
let root = DIST;
|
||||||
const server: Server = createServer((req, res) => {
|
const server: Server = createServer((req, res) => {
|
||||||
const path = decodeURIComponent((req.url ?? '/').split('?')[0] ?? '/');
|
const path = decodeURIComponent((req.url ?? '/').split('?')[0] ?? '/');
|
||||||
|
|
||||||
@@ -55,9 +58,9 @@ export async function startStaticServer(): Promise<StaticServer> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
const rel = normalize(path.slice(BASE.length) || 'index.html');
|
const rel = normalize(path.slice(BASE.length) || 'index.html');
|
||||||
const file = join(DIST, rel);
|
const file = join(root, rel);
|
||||||
// Confine to DIST: a test server is still a server.
|
// Confine to the served folder: a test server is still a server.
|
||||||
if (!file.startsWith(DIST + sep) && file !== DIST) {
|
if (!file.startsWith(root + sep) && file !== root) {
|
||||||
res.writeHead(403).end();
|
res.writeHead(403).end();
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
@@ -90,6 +93,9 @@ export async function startStaticServer(): Promise<StaticServer> {
|
|||||||
return {
|
return {
|
||||||
origin,
|
origin,
|
||||||
url: `${origin}${BASE}`,
|
url: `${origin}${BASE}`,
|
||||||
|
serveFrom: (dir) => {
|
||||||
|
root = dir;
|
||||||
|
},
|
||||||
close: () =>
|
close: () =>
|
||||||
new Promise<void>((resolve) => {
|
new Promise<void>((resolve) => {
|
||||||
server.closeAllConnections();
|
server.closeAllConnections();
|
||||||
|
|||||||
@@ -0,0 +1,79 @@
|
|||||||
|
import AxeBuilder from '@axe-core/playwright';
|
||||||
|
import { expect, test, type Page } from '@playwright/test';
|
||||||
|
import { PRODUCT_NAME } from '@rosea/schema';
|
||||||
|
import { en } from '@rosea/ui/copy';
|
||||||
|
import { appendFileSync, cpSync, mkdtempSync, rmSync } from 'node:fs';
|
||||||
|
import { tmpdir } from 'node:os';
|
||||||
|
import { join } from 'node:path';
|
||||||
|
import { DIST, startStaticServer } from './static-server.js';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The stale service worker (CLAUDE.md §8, calm-refresh.md). A waiting worker exists
|
||||||
|
* only between two builds, so this publishes a real second one: version A's build
|
||||||
|
* with `sw.js` changed, served at the same URL. Its extra listener answers "which
|
||||||
|
* version are you?", so the test knows for certain which worker controls the page.
|
||||||
|
*/
|
||||||
|
const VERSION_B = `
|
||||||
|
// Added by e2e/update.spec.ts: version B of the worker, and a way to ask.
|
||||||
|
self.addEventListener('message', (event) => {
|
||||||
|
if (event.data === 'rosea-which-version') event.source?.postMessage('B');
|
||||||
|
});
|
||||||
|
`;
|
||||||
|
|
||||||
|
/** "A" unless the controlling worker answers that it is B. */
|
||||||
|
async function whichVersion(page: Page): Promise<string> {
|
||||||
|
return page.evaluate(
|
||||||
|
() =>
|
||||||
|
new Promise<string>((resolve) => {
|
||||||
|
const controller = navigator.serviceWorker.controller;
|
||||||
|
if (!controller) return resolve('none');
|
||||||
|
const timer = setTimeout(() => resolve('A'), 1500);
|
||||||
|
navigator.serviceWorker.addEventListener('message', (e) => {
|
||||||
|
if (e.data === 'B') {
|
||||||
|
clearTimeout(timer);
|
||||||
|
resolve('B');
|
||||||
|
}
|
||||||
|
});
|
||||||
|
controller.postMessage('rosea-which-version');
|
||||||
|
})
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
test('a new version waits, is offered in one quiet line, and comes only when the player refreshes', async ({ browser }) => {
|
||||||
|
const server = await startStaticServer();
|
||||||
|
const context = await browser.newContext();
|
||||||
|
const versionB = mkdtempSync(join(tmpdir(), 'rosea-version-b-'));
|
||||||
|
try {
|
||||||
|
const page = await context.newPage();
|
||||||
|
await page.goto(server.url);
|
||||||
|
await expect(page.getByRole('heading', { level: 1 })).toHaveText(PRODUCT_NAME);
|
||||||
|
await page.waitForFunction(() => navigator.serviceWorker.controller !== null, null, { timeout: 20_000 });
|
||||||
|
expect(await whichVersion(page)).toBe('A');
|
||||||
|
await expect(page.getByText(en.update.ready)).toHaveCount(0);
|
||||||
|
|
||||||
|
// Publish version B at the same URL.
|
||||||
|
cpSync(DIST, versionB, { recursive: true });
|
||||||
|
appendFileSync(join(versionB, 'sw.js'), VERSION_B);
|
||||||
|
server.serveFrom(versionB);
|
||||||
|
|
||||||
|
// A navigation makes the browser check for a new worker, as it does for a player.
|
||||||
|
await page.reload();
|
||||||
|
await expect(page.getByText(en.update.ready)).toBeVisible({ timeout: 20_000 });
|
||||||
|
|
||||||
|
// Offered, not swapped: A still controls the page, and B waits.
|
||||||
|
expect(await whichVersion(page)).toBe('A');
|
||||||
|
expect(await page.evaluate(async () => (await navigator.serviceWorker.getRegistration())?.waiting !== null)).toBe(true);
|
||||||
|
expect((await new AxeBuilder({ page }).analyze()).violations.map((v) => `${v.id}: ${v.help}`)).toEqual([]);
|
||||||
|
|
||||||
|
// The player refreshes: B takes over and the page reloads under it.
|
||||||
|
await Promise.all([page.waitForEvent('load'), page.getByRole('button', { name: en.update.refresh }).click()]);
|
||||||
|
await expect(page.getByRole('heading', { level: 1 })).toHaveText(PRODUCT_NAME);
|
||||||
|
await expect.poll(() => whichVersion(page), { timeout: 10_000 }).toBe('B');
|
||||||
|
await expect(page.getByText(en.update.ready)).toHaveCount(0);
|
||||||
|
} finally {
|
||||||
|
// A test run leaves the machine as it found it (CLAUDE.md §5.7).
|
||||||
|
await context.close();
|
||||||
|
await server.close();
|
||||||
|
rmSync(versionB, { recursive: true, force: true });
|
||||||
|
}
|
||||||
|
});
|
||||||
Generated
+3
@@ -99,6 +99,9 @@ importers:
|
|||||||
vite-plugin-pwa:
|
vite-plugin-pwa:
|
||||||
specifier: 1.3.0
|
specifier: 1.3.0
|
||||||
version: 1.3.0(vite@6.4.3(@types/node@22.20.1)(terser@5.51.2)(tsx@4.23.12))(workbox-build@7.4.1)(workbox-window@7.4.1)
|
version: 1.3.0(vite@6.4.3(@types/node@22.20.1)(terser@5.51.2)(tsx@4.23.12))(workbox-build@7.4.1)(workbox-window@7.4.1)
|
||||||
|
workbox-window:
|
||||||
|
specifier: 7.4.1
|
||||||
|
version: 7.4.1
|
||||||
|
|
||||||
packages/content:
|
packages/content:
|
||||||
dependencies:
|
dependencies:
|
||||||
|
|||||||
Reference in New Issue
Block a user