import type { APIResponse, Frame, Page, Route } from "@playwright/test"; /** * 1103/11-09. Which link-preloaded scripts a page actually ran. * * WebKit warns about a preload no request has used three seconds after the * load event, once. That is a timing guess: a route entered just before the * check preloads chunks the page runs a moment later, and a preload the page * never runs goes unreported when the test ends first. This check does not * depend on when it runs, and it is the same in every engine: * * - Every `` and `` a document gets * is recorded (a MutationObserver from before the document's first byte, * plus the links still in the document at the end). * - Every build script the page receives (`/assets/*.js`) starts with one * statement that records its own URL when it is evaluated. A preload only * fetches (WebKit, Firefox) or fetches and parses (Chromium); none of them * evaluates, so a preloaded chunk counts as used only once the module graph * ran it. * - At the end, a preloaded script that was not run is `preloadunused:`. The * check waits for a dynamic import still in flight (up to `timeoutMs`). * * What it cannot see fails closed, under its own name: * - `preloadunverifiable::` a preload of anything but a script. * - `preloadunverifiable:service-worker:` a script preloaded while a Service * Worker controlled the document. The worker answers the page's requests, * so this route never sees them; marking what the worker fetches would * change bytes it checks against the release manifest. * - `preloadunverifiable:unmarked:` a script this route could not fetch to * mark (the browser got it unmarked). * A script outside `/assets/`, or one a test's own handler fulfilled without * `fulfillBuildScript`, never records itself and is `preloadunused:`. * * Only the documents open at the end are checked: a document the test * navigated away from takes its records with it. */ const BUILD_SCRIPT = /\/assets\/[^/?#]+\.js$/u; const STATE = "__e2ePreloadUse"; const FETCH_ATTEMPTS = 3; type Preload = Readonly<{ href: string; kind: string }>; type FrameRecord = Readonly<{ preloaded: readonly Preload[]; evaluated: readonly string[]; }>; export type PreloadUseCheck = Readonly<{ /** Every preloaded URL path the open documents recorded. */ preloaded: readonly string[]; /** `preloadunused:` and `preloadunverifiable::` lines. */ failures: readonly string[]; }>; export type PreloadUseTracker = Readonly<{ check(options?: Readonly<{ timeoutMs?: number }>): Promise; }>; /** Runs in every document before its first byte. */ function recordPreloads(state: string): void { const record = { preloaded: new Map(), evaluated: new Set(), }; Object.defineProperty(globalThis, state, { value: record }); const remember = (node: Node) => { if (!(node instanceof HTMLLinkElement) || node.href === "") return; const script = node.relList.contains("modulepreload") || (node.relList.contains("preload") && node.as === "script"); if (script) { const controlled = navigator.serviceWorker?.controller != null; record.preloaded.set(node.href, controlled ? "service-worker" : "script"); } else if (node.relList.contains("preload")) { record.preloaded.set(node.href, node.as || "unknown"); } }; new MutationObserver((mutations) => { for (const mutation of mutations) { for (const node of mutation.addedNodes) { remember(node); if (node instanceof Element) node.querySelectorAll("link").forEach(remember); } } }).observe(document, { childList: true, subtree: true }); } function readRecord(state: string): FrameRecord { const record = (globalThis as Record)[state] as | { preloaded: Map; evaluated: Set } | undefined; const preloaded = new Map(record?.preloaded); const controlled = navigator.serviceWorker?.controller != null; for (const link of document.querySelectorAll("link")) { if (link.href === "" || preloaded.has(link.href)) continue; if ( link.relList.contains("modulepreload") || (link.relList.contains("preload") && link.as === "script") ) { preloaded.set(link.href, controlled ? "service-worker" : "script"); } else if (link.relList.contains("preload")) { preloaded.set(link.href, link.as || "unknown"); } } return { preloaded: [...preloaded].map(([href, kind]) => ({ href, kind })), evaluated: [...(record?.evaluated ?? [])], }; } /** * Fulfills a request with `response`, the evaluation mark added when it is a * build script. A test that fulfills build scripts itself (for example to add * headers) uses this, or every preload of those scripts reads as unused. */ export async function fulfillBuildScript( route: Route, response: APIResponse, headers: Readonly> = response.headers(), ): Promise { const url = route.request().url(); const type = response.headers()["content-type"] ?? ""; if ( !BUILD_SCRIPT.test(new URL(url).pathname) || response.status() !== 200 || !/javascript/u.test(type) ) { return route.fulfill({ response, headers: { ...headers } }); } const marked = { ...headers }; delete marked["content-length"]; delete marked["content-encoding"]; await route.fulfill({ status: response.status(), headers: marked, // Valid in a module and in a classic script; a no-op where the page's // record does not exist (a worker). body: `globalThis.${STATE}?.evaluated.add(${JSON.stringify(url)});\n${await response.text()}`, }); } function pathOf(href: string, origin: string): string { const url = new URL(href); return url.origin === origin ? `${url.pathname}${url.search}` : href; } export async function trackPreloadUse(page: Page): Promise { /** URL → why it reached the browser without the mark. */ const unmarked = new Map(); async function markEvaluation(route: Route): Promise { if (route.request().method() !== "GET") return route.fallback(); let lastError: unknown; for (let attempt = 0; attempt < FETCH_ATTEMPTS; attempt += 1) { let response: APIResponse; try { response = await route.fetch(); } catch (error) { lastError = error; continue; } return fulfillBuildScript(route, response); } // The browser gets the request as the server answers it, unmarked. unmarked.set( route.request().url(), String(lastError).split("\n")[0] ?? "fetch failed", ); return route.continue(); } async function frameResult(frame: Frame): Promise< Readonly<{ preloaded: string[]; failures: string[] }> | undefined > { if (frame.isDetached()) return { preloaded: [], failures: [] }; let record: FrameRecord; let origin: string; try { [record, origin] = await Promise.all([ frame.evaluate(readRecord, STATE), frame.evaluate(() => location.origin), ]); } catch { // The document is being replaced; read the next one. return undefined; } const evaluated = new Set(record.evaluated); const failures: string[] = []; for (const { href, kind } of record.preloaded) { const where = pathOf(href, origin); if (kind !== "script" && kind !== "service-worker") { failures.push(`preloadunverifiable:${kind}:${where}`); } else if (evaluated.has(href)) { continue; } else if (unmarked.has(href)) { failures.push(`preloadunverifiable:unmarked:${where}: ${unmarked.get(href)}`); } else if (kind === "service-worker") { failures.push(`preloadunverifiable:service-worker:${where}`); } else { failures.push(`preloadunused:${where}`); } } return { preloaded: record.preloaded.map(({ href }) => pathOf(href, origin)), failures, }; } await page.addInitScript(recordPreloads, STATE); await page.route((url) => BUILD_SCRIPT.test(url.pathname), markEvaluation); return Object.freeze({ async check({ timeoutMs = 5_000 } = {}) { const deadline = Date.now() + timeoutMs; for (;;) { if (page.isClosed()) return { preloaded: [], failures: [] }; const frames = await Promise.all(page.frames().map(frameResult)); const settled = frames.every((frame) => frame !== undefined); const preloaded = frames.flatMap((frame) => frame?.preloaded ?? []).sort(); const failures = frames.flatMap((frame) => frame?.failures ?? []).sort(); if ((settled && failures.length === 0) || Date.now() >= deadline) { return { preloaded, failures: settled ? failures : [...failures, "preloadcheck:unreadable-document"], }; } await new Promise((resolve) => setTimeout(resolve, 100)); } }, }); }