diff --git a/tests/e2e/service-worker-update.spec.ts b/tests/e2e/service-worker-update.spec.ts new file mode 100644 index 00000000..b0dab043 --- /dev/null +++ b/tests/e2e/service-worker-update.spec.ts @@ -0,0 +1,262 @@ +import { readdir, readFile } from "node:fs/promises"; +import path from "node:path"; + +import { expect, test, type Page } from "../support/browser/strict-browser-test.ts"; +import { + prepareServiceWorkerBuilds, + removeServiceWorkerBuilds, + startBuildServer, + type ServiceWorkerBuilds, +} from "./support/service-worker-builds.ts"; + +/** + * R3-6. Real-browser Service Worker checks, against real production builds. + * + * How the worker is enabled: the template's default build has + * `serviceWorker: null`, and the only supported switch is the static + * capability selection in `src/features/installed-runtime-capabilities.ts` + * (`{ mode: "ACTIVE", scriptPath: "service-worker.js", handlers: + * ["PWA_STATIC_ASSETS"] }`); `scripts/build-frontend.ts` then adds the worker + * build. `support/service-worker-builds.ts` applies that selection in a temp + * copy of the repo, builds it twice (`VITE_BUILD_ID` sw-e2e-a / sw-e2e-b), + * and serves either dist from its own port per test. The copy also records + * the worker host's `onUpdateWaiting` / `onReloadRequired` callbacks, which + * the app itself does not subscribe to yet. See that file for the build-script + * workaround (product defect found here). + * + * The preview server of this suite is not used; each test uses absolute URLs. + */ + +type Probe = typeof globalThis & { + __caServiceWorkerTest?: { + host: { requestActivation(): Promise }; + events: string[]; + }; +}; + +let builds: ServiceWorkerBuilds | undefined; + +test.beforeAll(async () => { + test.setTimeout(180_000); + builds = await prepareServiceWorkerBuilds(); +}); + +test.afterAll(async () => { + await removeServiceWorkerBuilds(builds); +}); + +function requireBuilds(): ServiceWorkerBuilds { + if (!builds) throw new Error("Service Worker builds were not prepared."); + return builds; +} + +async function waitForEvent(page: Page, prefix: string): Promise { + await page.waitForFunction( + (expected) => + (globalThis as Probe).__caServiceWorkerTest?.events.some((event) => + event.startsWith(expected), + ) === true, + prefix, + { timeout: 60_000 }, + ); + const events = await page.evaluate(() => [ + ...((globalThis as Probe).__caServiceWorkerTest?.events ?? []), + ]); + return events.find((event) => event.startsWith(prefix))!; +} + +async function startOutcome(page: Page): Promise { + return JSON.parse((await waitForEvent(page, "start:")).slice("start:".length)); +} + +async function hashedAssets(dist: string): Promise { + return (await readdir(path.join(dist, "assets"))) + .map((file) => `/assets/${file}`) + .sort(); +} + +const headerCases = [ + { + name: "Content-Type: application/javascript", + headers: { javascriptContentType: "application/javascript", gzip: false }, + }, + { + name: "Content-Encoding: gzip with the compressed Content-Length", + headers: { javascriptContentType: "text/javascript", gzip: true }, + }, +] as const; + +for (const { name, headers } of headerCases) { + test(`installs the static asset set served with ${name}`, async ({ page }) => { + const { dist } = requireBuilds(); + const server = await startBuildServer(dist, headers); + try { + await page.goto(`${server.origin}/`); + // A failed install (CONTENT_TYPE_INVALID, BYTES_MISMATCH, ...) ends as + // FAILED/INSTALL_FAILED; a first install that worked asks for a reload. + expect(await startOutcome(page)).toEqual({ kind: "RELOAD_TO_ENABLE" }); + const cached = await page.evaluate(async () => { + const names = (await caches.keys()).filter((cacheName) => + cacheName.startsWith("ca-static-v1-"), + ); + const cache = await caches.open(names[0] ?? "missing"); + const paths = (await cache.keys()) + .map((request) => new URL(request.url)) + .filter((url) => url.origin === location.origin) + .map((url) => url.pathname); + return { names, paths }; + }); + expect(cached.names).toHaveLength(1); + expect(cached.paths.sort()).toEqual(await hashedAssets(dist.a)); + + // The server really sent the headers under test. + const assets = server.served.filter((response) => + response.path.startsWith("/assets/"), + ); + expect(assets.length).toBeGreaterThan(0); + if (headers.gzip) { + expect(assets.every((response) => response.contentEncoding === "gzip")) + .toBe(true); + expect( + assets.some( + (response) => response.contentLength < response.decodedLength, + ), + ).toBe(true); + } else { + expect( + assets + .filter((response) => response.path.endsWith(".js")) + .every( + (response) => response.contentType === "application/javascript", + ), + ).toBe(true); + } + } finally { + await server.close(); + } + }); +} + +type BuildServer = Awaited>; + +// Playwright's Firefox never lets a worker control a page: even a trivial +// classic worker leaves `navigator.serviceWorker.controller` null after a new +// navigation (checked by hand with Playwright 1.62). With no controlled +// client, B skips `waiting` and activates by itself (`requestActivation()` then +// returns NO_WAITING_WORKER), and the fetch handler is never reached. The +// update tests therefore run where a page can be controlled. Not a product +// defect. +// quarantine(owner=frontend-platform, defect=playwright-firefox-no-sw-control, expires=2027-03-31) +const NO_CONTROLLED_PAGES = + "Playwright Firefox pages are never controlled by a service worker."; + +/** + * Loads build A twice (first install, then a normal navigation), switches the + * server to B, runs the update check and activates B through the app host. + * Returns whether the second load of A was controlled by the worker. + */ +async function updateFromAToB( + page: Page, + server: BuildServer, +): Promise<{ secondLoad: unknown; controlled: boolean }> { + await page.goto(`${server.origin}/`); + expect(await startOutcome(page)).toEqual({ kind: "RELOAD_TO_ENABLE" }); + await page.evaluate(async () => { + await navigator.serviceWorker.ready; + }); + // A normal navigation. (`page.reload()` would not change anything here.) + await page.goto(`${server.origin}/`); + const secondLoad = await startOutcome(page); + const controlled = await page.evaluate( + () => navigator.serviceWorker.controller !== null, + ); + + server.serve("b"); + await page.evaluate(async () => { + await (await navigator.serviceWorker.getRegistration())?.update(); + }); + await waitForEvent(page, "update-waiting"); + const activation = await page.evaluate(() => + (globalThis as Probe).__caServiceWorkerTest!.host.requestActivation(), + ); + expect(activation).toEqual({ kind: "ACTIVATED_RELOAD_REQUIRED" }); + await waitForEvent(page, "reload-required"); + return { secondLoad, controlled }; +} + +test("announces update-waiting and reload-required through the host when build B replaces A", async ({ + page, + browserName, +}) => { + test.skip(browserName === "firefox", NO_CONTROLLED_PAGES); + const server = await startBuildServer(requireBuilds().dist); + try { + await updateFromAToB(page, server); + const registration = await page.evaluate(async () => { + const current = await navigator.serviceWorker.getRegistration(); + return { + active: current?.active?.state ?? null, + waiting: current?.waiting ?? null, + }; + }); + expect(registration).toEqual({ active: "activated", waiting: null }); + } finally { + await server.close(); + } +}); + +test("serves A's removed chunk from the previous cache once B controls the page", async ({ + page, + browserName, +}) => { + test.skip(browserName === "firefox", NO_CONTROLLED_PAGES); + const { dist } = requireBuilds(); + const routeChunks = Object.values( + ( + JSON.parse( + await readFile(path.join(dist.a, "release-manifest.json"), "utf8"), + ) as { routeChunks: Record } + ).routeChunks, + ); + const inB = new Set(await hashedAssets(dist.b)); + const removedChunk = routeChunks + .map((chunk) => `/${chunk}`) + .find((chunk) => !inB.has(chunk)); + if (!removedChunk) throw new Error("Build B kept every route chunk of A."); + + const server = await startBuildServer(dist); + try { + const { secondLoad, controlled } = await updateFromAToB(page, server); + expect(secondLoad).toEqual({ kind: "ACTIVE", buildId: "sw-e2e-a" }); + expect(controlled).toBe(true); + + // B's worker now controls the page. The chunk is not in B's manifest and + // not on the server any more, so only A's retained cache can answer. + const fromWorker = await page.evaluate(async (url) => { + const response = await fetch(url); + return { status: response.status, body: await response.text() }; + }, removedChunk); + expect(fromWorker).toEqual({ + status: 200, + body: await readFile(path.join(dist.a, removedChunk), "utf8"), + }); + expect((await page.request.get(`${server.origin}${removedChunk}`)).status()) + .toBe(404); + } finally { + await server.close(); + } +}); + +// quarantine(owner=frontend-platform, defect=R3-6-service-worker-config-loader, expires=2026-12-31) +// `vite.service-worker.config.ts` loads `.generated/frontend-runtime/*.ts` +// with a runtime `import("./.generated/...")`. Vite's default `bundle` config +// loader executes the config from `node_modules/.vite-temp/`, so the path +// resolves there and the ACTIVE build stops with ERR_MODULE_NOT_FOUND at +// `npx vite build --config vite.service-worker.config.ts`. Remove the fixme +// (and the helper's `configLoaderWorkaround`) once the build script works. +test.fixme("builds the ACTIVE worker with the repo's unmodified build script", async () => { + test.setTimeout(180_000); + await removeServiceWorkerBuilds( + await prepareServiceWorkerBuilds({ configLoaderWorkaround: false }), + ); +}); diff --git a/tests/e2e/support/service-worker-builds.ts b/tests/e2e/support/service-worker-builds.ts new file mode 100644 index 00000000..be431514 --- /dev/null +++ b/tests/e2e/support/service-worker-builds.ts @@ -0,0 +1,258 @@ +import { spawnSync } from "node:child_process"; +import { + cp, + mkdtemp, + readFile, + rename, + rm, + symlink, + writeFile, +} from "node:fs/promises"; +import { createServer, type Server } from "node:http"; +import type { AddressInfo } from "node:net"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import { gzipSync } from "node:zlib"; + +/** + * R3-6 test helper: two real production builds with the Service Worker on, + * and a static server that can switch which one it serves. + * + * The template ships with `serviceWorker: null`. The supported way to turn the + * worker on is the static capability selection in + * `src/features/installed-runtime-capabilities.ts` (`mode: "ACTIVE"` with the + * `PWA_STATIC_ASSETS` handler); `scripts/build-frontend.ts` then runs the + * two-pass worker build. Runtime Config can only disable it. So the helper + * copies the repo to a temp dir, edits the selection there, and runs the + * repo's own build scripts twice with different `VITE_BUILD_ID`s. The working + * tree and its `dist` (served by the e2e preview server) are never touched. + * + * The app composes the worker host but nothing subscribes to it yet, and it is + * not reachable from outside. The copy therefore also wraps + * `createServiceWorkerRuntimeHost` so the page records the host's own + * `onUpdateWaiting` / `onReloadRequired` callbacks and `start()` outcome on + * `globalThis.__caServiceWorkerTest`. Only the temp copy is edited. + */ + +const repoRoot = path.resolve(import.meta.dirname, "../../.."); +const skipped = new Set([ + "node_modules", + ".git", + ".claude", + ".generated", + "dist", + "artifacts", + "graphify-out", +]); + +export type BuildName = "a" | "b"; +export type ServiceWorkerBuilds = Readonly<{ + root: string; + dist: Readonly>; +}>; + +const ACTIVE_SELECTION = `const SERVICE_WORKER: InstalledServiceWorkerSelection | null = { + mode: "ACTIVE", + scriptPath: "service-worker.js", + handlers: ["PWA_STATIC_ASSETS"], +};`; + +const HOST_PROBE = ` +export function createServiceWorkerRuntimeHost( + input: ServiceWorkerHostInput, +): ServiceWorkerRuntimeHost | null { + const host = createServiceWorkerRuntimeHostUnobserved(input); + if (!host) return host; + const events: string[] = []; + host.onUpdateWaiting(() => events.push("update-waiting")); + host.onReloadRequired(() => events.push("reload-required")); + const observed: ServiceWorkerRuntimeHost = Object.freeze({ + ...host, + start: async () => { + const outcome = await host.start(); + events.push("start:" + JSON.stringify(outcome)); + return outcome; + }, + }); + Object.assign(globalThis, { __caServiceWorkerTest: { host: observed, events } }); + return observed; +} +`; + +async function replaceOnce( + file: string, + search: string, + replacement: string, +): Promise { + const source = await readFile(file, "utf8"); + if (source.split(search).length !== 2) { + throw new Error(`Expected exactly one "${search}" in ${file}.`); + } + await writeFile(file, source.replace(search, replacement)); +} + +function run(cwd: string, script: string, buildId: string): void { + const result = spawnSync("node", [script], { + cwd, + encoding: "utf8", + env: { ...process.env, VITE_BUILD_ID: buildId, RELEASE_ID: buildId }, + }); + if (result.status !== 0) { + throw new Error( + `${script} failed for ${buildId}:\n${result.stdout}\n${result.stderr}`, + ); + } +} + +/** + * `configLoaderWorkaround` (default on) works around a product defect found + * by this spec: `vite.service-worker.config.ts` imports its generated inputs + * with a runtime-relative `import("./.generated/...")`, and Vite's default + * `bundle` config loader runs the config from `node_modules/.vite-temp/`, so + * the ACTIVE worker build fails with ERR_MODULE_NOT_FOUND. The copy's + * `build-frontend.ts` is given `--configLoader native` for the worker step. + */ +export async function prepareServiceWorkerBuilds( + { configLoaderWorkaround = true } = {}, +): Promise { + const root = await mkdtemp(path.join(tmpdir(), "ca-sw-builds-")); + await cp(repoRoot, root, { + recursive: true, + filter: (source) => + !skipped.has(path.relative(repoRoot, source).split(path.sep)[0]!), + }); + await symlink(path.join(repoRoot, "node_modules"), path.join(root, "node_modules")); + await replaceOnce( + path.join(root, "src/features/installed-runtime-capabilities.ts"), + "const SERVICE_WORKER: InstalledServiceWorkerSelection | null = null;", + ACTIVE_SELECTION, + ); + if (configLoaderWorkaround) { + await replaceOnce( + path.join(root, "scripts/build-frontend.ts"), + '"vite.service-worker.config.ts"]', + '"vite.service-worker.config.ts", "--configLoader", "native"]', + ); + } + const hostFile = path.join(root, "src/bootstrap/register-service-worker.ts"); + await replaceOnce( + hostFile, + "export function createServiceWorkerRuntimeHost(", + "function createServiceWorkerRuntimeHostUnobserved(", + ); + await writeFile(hostFile, (await readFile(hostFile, "utf8")) + HOST_PROBE); + + const dist = { a: path.join(root, "dist-a"), b: path.join(root, "dist-b") }; + for (const name of ["a", "b"] as const) { + run(root, "scripts/generate-product-feature-index.ts", `sw-e2e-${name}`); + run(root, "scripts/build-frontend.ts", `sw-e2e-${name}`); + await rename(path.join(root, "dist"), dist[name]); + } + return { root, dist }; +} + +export async function removeServiceWorkerBuilds( + builds: ServiceWorkerBuilds | undefined, +): Promise { + if (builds) await rm(builds.root, { recursive: true, force: true }); +} + +export type AssetHeaders = Readonly<{ + /** Sent for every `.js` file, the worker script included. */ + javascriptContentType: string; + /** gzip every `/assets/*` body; Content-Length is the compressed size. */ + gzip: boolean; +}>; + +export type ServedResponse = Readonly<{ + path: string; + contentType: string; + contentEncoding: string | null; + contentLength: number; + decodedLength: number; +}>; + +const CONTENT_TYPES: Readonly> = { + ".html": "text/html; charset=utf-8", + ".css": "text/css", + ".json": "application/json", + ".svg": "image/svg+xml", + ".png": "image/png", + ".webp": "image/webp", + ".woff2": "font/woff2", +}; + +/** + * Serves one dist directory at a time from an ephemeral 127.0.0.1 port, so + * every test gets its own origin (and its own Service Worker registration). + * Paths without an extension get `index.html`; a missing file is a plain 404, + * never the SPA fallback, so a chunk that the served build lacks really 404s. + */ +export async function startBuildServer( + dist: Readonly>, + headers: AssetHeaders = { + javascriptContentType: "text/javascript", + gzip: false, + }, +) { + let current: BuildName = "a"; + const served: ServedResponse[] = []; + const server: Server = createServer((request, response) => { + void (async () => { + const pathname = decodeURIComponent( + new URL(request.url ?? "/", "http://127.0.0.1").pathname, + ); + const root = dist[current]; + const file = path.extname(pathname) + ? path.join(root, path.normalize(pathname)) + : path.join(root, "index.html"); + let body: Buffer; + try { + if (!file.startsWith(root + path.sep)) throw new Error("outside root"); + body = await readFile(file); + } catch { + response.writeHead(404, { "cache-control": "no-store" }).end(); + return; + } + const extension = path.extname(file); + const contentType = + extension === ".js" + ? headers.javascriptContentType + : (CONTENT_TYPES[extension] ?? "application/octet-stream"); + const encoded = headers.gzip && pathname.startsWith("/assets/"); + const payload = encoded ? gzipSync(body) : body; + served.push({ + path: pathname, + contentType, + contentEncoding: encoded ? "gzip" : null, + contentLength: payload.byteLength, + decodedLength: body.byteLength, + }); + response + .writeHead(200, { + "content-type": contentType, + "content-length": String(payload.byteLength), + "cache-control": "no-cache", + ...(encoded + ? { "content-encoding": "gzip", vary: "Accept-Encoding" } + : {}), + }) + .end(request.method === "HEAD" ? undefined : payload); + })(); + }); + await new Promise((resolve) => + server.listen(0, "127.0.0.1", () => resolve()), + ); + const { port } = server.address() as AddressInfo; + return { + origin: `http://127.0.0.1:${port}`, + served, + serve(name: BuildName) { + current = name; + }, + async close() { + server.closeAllConnections(); + await new Promise((resolve) => server.close(() => resolve())); + }, + }; +}