From da66a6f301ef1998ae429ccbfad1c85bfbe45c21 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 14 Nov 2026 00:51:22 +0000 Subject: [PATCH] Pin the frame to UOR-Foundation/template@d65a5ff prism-devrel#6 edited bootstrap/page.mjs and site/page.template.html by hand for the Prism id change, so frame-sync --check refuses main. Take the frame from the template instead, at the commit that carries that change (template#73) and its re-lock (template#75). This also moves the frame from template@f54d6b7 to the template's current frame files. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013Asa3NdLCxdzL1iQw9rg5T --- bootstrap/frame-sync.mjs | 2 + bootstrap/page.mjs | 60 +++------- bootstrap/screens.mjs | 61 +---------- bootstrap/weight.mjs | 150 +++++++++++++++++++++++++ bootstrap/worker-runtime.mjs | 46 ++++++++ frame.lock | 30 +++-- lighthouserc.json | 2 - site/app.mjs | 205 +++++++++++++---------------------- site/guest-worker.mjs | 44 +++++--- site/page.template.html | 5 +- site/prism-page.css | 83 ++++---------- site/sw.js | 58 ++++++++-- 12 files changed, 407 insertions(+), 339 deletions(-) create mode 100644 bootstrap/weight.mjs create mode 100644 bootstrap/worker-runtime.mjs diff --git a/bootstrap/frame-sync.mjs b/bootstrap/frame-sync.mjs index fcd2c7a..bb3f442 100644 --- a/bootstrap/frame-sync.mjs +++ b/bootstrap/frame-sync.mjs @@ -42,6 +42,8 @@ const FRAME = [ "bootstrap/precache.mjs", "bootstrap/register.mjs", "bootstrap/screens.mjs", + "bootstrap/weight.mjs", + "bootstrap/worker-runtime.mjs", "lighthouserc.json", "site/app.mjs", "site/guest-worker.mjs", diff --git a/bootstrap/page.mjs b/bootstrap/page.mjs index d4fb7a0..e8811d1 100644 --- a/bootstrap/page.mjs +++ b/bootstrap/page.mjs @@ -11,8 +11,10 @@ import { access, readdir, readFile, writeFile } from "node:fs/promises"; import { join } from "node:path"; import { fileURLToPath } from "node:url"; import { DEFAULT_REGISTRY } from "./register.mjs"; +import { prepareWorkerRuntime } from "./worker-runtime.mjs"; const site = process.argv[2] ?? "site"; +await prepareWorkerRuntime(site, fileURLToPath(new URL("../try/vendor", import.meta.url))); const read = (path) => readFile(join(site, path), "utf8"); const escape = (text) => @@ -36,7 +38,10 @@ const cardModule = await access(join(site, "card.mjs")).then(() => true, () => f // brand/hologram-warm.css and brand/fonts.css, both pinned by brand.lock. // Comments and indentation out: the stylesheet travels inside every page. const minify = (text) => text.replace(/\/\*[\s\S]*?\*\//g, "").replace(/^[ \t]+/gm, "").replace(/\n{2,}/g, "\n").trim(); -const css = minify([await read("brand/hologram-warm.css"), await read("brand/fonts.css"), await read("prism-page.css"), card.css] +// The display sizes its type to what it holds; its first size is set here, +// from the placeholder, so the type does not shrink when the script arrives. +const startChars = `#input{--chars:${Math.max(String(meta.placeholder ?? "").length, 4)}}`; +const css = minify([await read("brand/hologram-warm.css"), await read("brand/fonts.css"), await read("prism-page.css"), card.html ? "" : startChars, card.css] .join("\n") .replace(/url\("\.\.\/fonts\//g, 'url("./fonts/')); const theme = (await read("theme.js")).trim(); @@ -312,57 +317,18 @@ const promise = (() => { })(); // The surface: an app with its own (card.html) fills it from the slot script; -// any other gets a form a visitor can read at a glance: what to type, a button -// that runs it (Enter does too), examples that run on a tap, and the answer -// under them, with a state for every moment (nothing yet, verifying, an answer, -// a refusal, an error). The words come from app.json: inputLabel, submitLabel, -// outputLabel, placeholder, hint. -const submitLabel = meta.submitLabel ?? "Run"; -const outputLabel = meta.outputLabel ?? "Answer"; -const inputLabel = meta.inputLabel ?? "Request"; -const lower = (s) => s.charAt(0).toLowerCase() + s.slice(1); -const idleText = `Type a ${lower(inputLabel)} and press ${submitLabel}, or pick an example.`; -const hint = meta.hint ?? `Press Enter or ${submitLabel}. It runs in your browser, on the app this page verifies.`; -// Try: a few of the holo's own short examples, at most two per answer, in -// words a visitor could type in one line (raw hex requests and requests with -// line breaks stay in the spec). +// any other gets the display, its input as the largest thing on screen. +const surface = card.html ? "" : ` `; +// Try: a few of the holo's own short examples, at most two per answer. const tries = card.html ? "" : (() => { const seen = new Map(); - const asked = new Set(); return vectors.filter((v) => { const k = kind(v.res); - if (k === "refuse" || v.req === "" || v.req.length > 24 || v.req.startsWith("hex:") || /[\u0000-\u001f]/.test(v.req) || asked.has(v.req) || (seen.get(k) ?? 0) >= 2) return false; + if (k === "refuse" || v.req === "" || v.req.length > 24 || (seen.get(k) ?? 0) >= 2) return false; seen.set(k, (seen.get(k) ?? 0) + 1); - asked.add(v.req); return true; }).map((v) => ``).join(""); })(); -const surface = card.html ? "" : `
-
- -
-

${escape(hint)}

-
-

Examples

${tries}
-
-

${escape(outputLabel)}

- ${escape(idleText)} -
-
`; -// Where to go next: app.json "links", [{ label, href }], a row under the -// description, the first one the main way on. A link is to this site (a -// relative path) or to https. -const nav = (meta.links ?? []).map((l) => { - if (!l?.label || !/^(https:\/\/|\.?\/?[\w-])/.test(String(l.href ?? ""))) throw new Error(`app.json links: ${JSON.stringify(l)} needs a label and a relative or https href`); - return `${escape(l.label)}`; -}).join(""); -// The rail: for an app with its own surface, its result and controls; for any -// other, what the app does in full, beside the form. -const about = sentences(meta.purpose).filter((x) => x !== tagline).join(" "); -const rail = card.html - ? `
—
-

Controls

` - : about ? `

What it does

${escape(about)}

` : ""; // The slot script: before first paint, it moves the parts of the app's own // surface into the workspace (data-slot names the place; the ids are the // first card's, read when an app has not marked its parts yet), so nothing @@ -474,13 +440,13 @@ const fill = { HOLO_NAME: escape(meta.name.toLowerCase().normalize("NFKD").replace(/\p{M}/gu, "").replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "") || "app"), PURPOSE: escape(meta.purpose), TAGLINE: escape(tagline), - NAV: nav ? `` : "", PROMISE_HEADLINE: escape(promise.headline), ATT_PROOF_URL: escape(meta.attestations?.proof?.url ?? ""), ICON_DOC: ICON.doc, ICON_X: ICON.x, SURFACE: surface, - RAIL: rail, + ACTIONS_LABEL: card.html ? "Controls" : "Try", + TRIES: tries, CARD: cardBlock, VERSION: escape(model.cargo_version ? `v${model.cargo_version}` : ""), REPO: escape(meta.repository), @@ -489,7 +455,7 @@ const fill = { IMPORTMAP: importmap, SPECULATION_RULES: speculationRules, FRAME_CONNECT: frameConnect, - APP_DATA: JSON.stringify({ answers: meta.answers, frame: frameHost.href, card: cardModule, inputLabel, idle: idleText, answerLinks: meta.answerLinks ?? {} }).replace(/ /^(\d+)\/\1$/.test(document.getElementById("frame")?.getAttribute("examples") ?? ""), null, { timeout: 20000 }); @@ -103,7 +98,7 @@ for (const c of classes) { const small = []; // The frame draws in its own shadow root; its controls count too. const roots = [document, ...[...document.querySelectorAll("*")].map((el) => el.shadowRoot).filter(Boolean)]; - for (const el of roots.flatMap((root) => [...root.querySelectorAll("button, input, a.ghost, a.spec-link, .head-nav a, summary")])) { + for (const el of roots.flatMap((root) => [...root.querySelectorAll("button, input, a.ghost, a.spec-link, summary")])) { if (el.hidden || el.closest("[hidden]") || el.classList.contains("use") || el.classList.contains("bare")) continue; // The spec, closed, is off screen; it is checked open, below. if (getComputedStyle(el).visibility === "hidden") continue; @@ -112,9 +107,7 @@ for (const c of classes) { if (coarse && (r.height < 48 || (el.tagName === "BUTTON" && r.width < 48))) small.push(`${el.tagName.toLowerCase()}#${el.id || el.className} ${Math.round(r.width)}x${Math.round(r.height)}`); } return { - // Main clips too, so content wider than it is hidden, not scrolled: - // that counts as overflow. - overflow: doc.scrollWidth > doc.clientWidth || document.querySelector("main").scrollWidth > document.querySelector("main").clientWidth + 1, + overflow: doc.scrollWidth > doc.clientWidth, // The page clips rather than scrolls (html and body hide overflow), so // the check is that the workspace ends inside the screen and holds // everything it has: a planted 4 rem passed a scroll check alone. @@ -139,54 +132,6 @@ for (const c of classes) { if (c.touch && !facts.coarse) fail(where, "the emulated device is not a coarse pointer"); for (const s of facts.small) fail(where, `touch target under 48 px: ${s}`); if (facts.verified !== "verified") fail(where, `status is "${facts.verified}"`); - // Every way on from the header lands on a page. - if (theme === "dark") { - for (const href of await page.locator(".head-nav a").evaluateAll((links) => links.map((a) => a.href))) { - if (!href.startsWith(origin)) continue; - const status = (await page.request.get(href)).status(); - if (status !== 200) fail(where, `the header link ${href.slice(origin.length - 1)} lands nowhere (${status})`); - } - } - // The journey, as a visitor takes it: each example, then a request typed - // and sent with Enter, then with the button, then the button with - // nothing typed. Each must show an answer, in words, on screen. - if (theme === "dark" && await page.locator("#ask").count()) { - // An answer counts once the page has shown a new one (app.mjs counts them). - let seen = 0; - const answered = async (what, states) => { - await page.waitForFunction((n) => Number(document.getElementById("out").dataset.answers ?? 0) > n, seen, { timeout: 10000 }).catch(() => {}); - seen = Number(await page.locator("#out").getAttribute("data-answers") ?? 0); - const r = await page.evaluate(() => { - const o = document.getElementById("out"); - const box = o.getBoundingClientRect(); - return { state: o.className, text: o.textContent.trim(), tag: document.getElementById("state").textContent.trim(), onScreen: box.height > 0 && box.top >= 0 && box.top < innerHeight - 16 }; - }); - if (!states.includes(r.state) || !r.text || !r.tag) fail(where, `${what} showed no answer (state "${r.state}", "${r.text.slice(0, 60)}")`); - else if (!r.onScreen) fail(where, `${what} answered off screen`); - return r; - }; - const examples = await page.locator("#tries button[data-request]").all(); - if (!examples.length) fail(where, "the page offers no examples to try"); - for (const button of examples) { - const request = await button.getAttribute("data-request"); - await button.click(); - await answered(`the example "${request}"`, ["good", "bad"]); - if (await page.inputValue("#input") !== request) fail(where, `the example "${request}" did not fill the field`); - } - const first = examples.length ? await examples[0].getAttribute("data-request") : "0"; - await page.fill("#input", first); - const left = await page.locator("#out").getAttribute("class"); - if (left !== "idle") fail(where, `typing a new request left the old answer up (${left})`); - await page.press("#input", "Enter"); - await answered("Enter", ["good", "bad"]); - await page.fill("#input", first); - await page.click("#go"); - await answered("the submit button", ["good", "bad"]); - await page.fill("#input", ""); - await page.click("#go"); - await answered("the submit button with nothing typed", ["refuse"]); - await page.fill("#input", ""); - } await page.screenshot({ path: join(out, `${c.name}-${theme}.png`), fullPage: true }); // The spec opens beside the window from 840 px (the window narrows by // the spec's width) and over it below; either way it is on screen, diff --git a/bootstrap/weight.mjs b/bootstrap/weight.mjs new file mode 100644 index 0000000..836037f --- /dev/null +++ b/bootstrap/weight.mjs @@ -0,0 +1,150 @@ +#!/usr/bin/env node +// The weight gate (FR-03). Opens the assembled site as a first visitor on a +// phone, with no service worker, waits until the page has started (the +// canonical frame is running and the shield has replayed every example), +// then until the network is quiet, and counts every byte that came over the +// wire, the page's workers included. Measured at that state, the count is the +// same on every run: Lighthouse's resource summary was not, because the +// frame, the worker runtime and the holo wait for first paint and land in its +// trace only some of the time (72 KB one run, 152 KB the next, same build). +// +// The bytes are split two ways, each with its own budget: +// frame: what every Prism app carries and only the template changes (the +// canonical frame from its host, the fonts, the worker runtime and +// the frame-locked page modules); +// app: everything else, from the page itself to the holo and the app's +// own modules. +// A template change that grows the frame fails the template; an app that +// grows fails the app; neither can push the other over. +// node bootstrap/weight.mjs site +// Needs playwright with Chromium: npm install -g playwright && playwright install chromium +import { createServer } from "node:http"; +import { readFile, stat } from "node:fs/promises"; +import { extname, join, normalize } from "node:path"; +import { execSync } from "node:child_process"; +import { gzipSync } from "node:zlib"; +import { pathToFileURL } from "node:url"; + +export const BUDGET = { + frame: 100 * 1024, + app: 120 * 1024, + requests: 28, +}; + +// Site paths the template owns: what frame.lock pins under site/, the fonts, +// and the worker runtime bootstrap/worker-runtime.mjs writes. +export function frameOwned(lock) { + const files = new Set(lock.files.map((f) => f.path).filter((p) => p.startsWith("site/")).map((p) => p.slice("site/".length))); + return (path) => files.has(path) || path.startsWith("fonts/") || path.startsWith("worker-runtime/"); +} + +// requests: [{ url, bytes }] for one visit; site: the page's URL; owned: from +// frameOwned; frameHost: the frame's URL from app.json. +export function weigh(requests, { site, owned, frameHost }) { + const sum = { frame: 0, app: 0, requests: 0, lines: [] }; + const base = new URL(site); + const host = new URL(frameHost); + for (const { url, bytes } of requests) { + const u = new URL(url); + if (u.protocol === "blob:" || u.protocol === "data:") continue; + let part = "app"; + if (u.origin === host.origin && u.pathname.startsWith(host.pathname)) part = "frame"; + else if (u.origin === base.origin && u.pathname.startsWith(base.pathname) && owned(u.pathname.slice(base.pathname.length))) part = "frame"; + sum[part] += bytes; + sum.requests += 1; + sum.lines.push({ part, bytes, url }); + } + return sum; +} + +export function judge(sum, budget = BUDGET) { + const failures = []; + if (sum.frame > budget.frame) failures.push(`the frame's bytes are ${sum.frame}, over its budget of ${budget.frame}`); + if (sum.app > budget.app) failures.push(`the app's bytes are ${sum.app}, over its budget of ${budget.app}`); + if (sum.requests > budget.requests) failures.push(`${sum.requests} requests, over the budget of ${budget.requests}`); + return failures; +} + +// The page has started: the canonical frame is running and the shield has +// replayed every example (or named why it could not). +export function started() { + const frame = document.getElementById("frame"); + return Boolean(customElements.get("prism-frame")) + && /^(\d+\/\d+|error)$/.test(frame?.getAttribute("examples") ?? ""); +} + +// GitHub Pages compresses text and leaves woff2, png and the like as they are. +const types = { ".html": "text/html", ".css": "text/css", ".mjs": "text/javascript", ".js": "text/javascript", ".json": "application/json", ".webmanifest": "application/manifest+json", ".svg": "image/svg+xml", ".woff2": "font/woff2", ".png": "image/png", ".holo": "application/octet-stream", ".wasm": "application/wasm" }; +const compressed = new Set([".html", ".css", ".mjs", ".js", ".json", ".webmanifest", ".svg", ".holo", ".wasm"]); + +async function main() { + const site = process.argv[2] ?? "site"; + const playwright = await import("playwright").catch(() => + import(pathToFileURL(join(execSync("npm root -g").toString().trim(), "playwright", "index.mjs")).href)); + const { chromium } = playwright; + const owned = frameOwned(JSON.parse(await readFile("frame.lock", "utf8"))); + const app = JSON.parse(await readFile(join(site, "app.json"), "utf8")); + const frameHost = app.frame ?? "https://uor-foundation.github.io/template/frame/"; + + const server = createServer(async (request, response) => { + let path = decodeURIComponent(new URL(request.url, "http://x").pathname); + if (path.endsWith("/")) path += "index.html"; + const file = normalize(join(site, path)); + try { + await stat(file); + let body = await readFile(file); + const headers = { "content-type": types[extname(file)] ?? "application/octet-stream" }; + if (compressed.has(extname(file)) && /\bgzip\b/.test(request.headers["accept-encoding"] ?? "")) { + body = gzipSync(body, { level: 9 }); + headers["content-encoding"] = "gzip"; + } + response.writeHead(200, headers); + response.end(body); + } catch { + response.writeHead(404); + response.end(); + } + }); + await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve)); + const origin = `http://127.0.0.1:${server.address().port}/`; + + const browser = await chromium.launch(); + const runs = []; + try { + for (let run = 0; run < 2; run++) { + const context = await browser.newContext({ viewport: { width: 412, height: 823 }, isMobile: true, hasTouch: true, serviceWorkers: "block" }); + const page = await context.newPage(); + const requests = []; + const pending = []; + page.on("requestfinished", (request) => pending.push(request.sizes().then((s) => { + requests.push({ url: request.url(), bytes: s.responseBodySize + s.responseHeadersSize }); + }, () => {}))); + await page.goto(origin, { waitUntil: "load" }); + try { + await page.waitForFunction(started, null, { timeout: 30000 }); + } catch { + throw new Error(`the page never started: frame ${await page.evaluate(() => Boolean(customElements.get("prism-frame")))}, examples "${await page.locator("#frame").getAttribute("examples")}"`); + } + await page.waitForLoadState("networkidle"); + await Promise.all(pending); + runs.push(weigh(requests, { site: origin, owned, frameHost })); + await context.close(); + } + } finally { + await browser.close(); + server.close(); + } + + const [sum] = runs; + for (const line of sum.lines.sort((a, b) => b.bytes - a.bytes)) console.log(`${line.part.padEnd(5)} ${String(line.bytes).padStart(7)} ${line.url.replace(origin, "./")}`); + for (const r of runs) console.log(`weight: frame ${r.frame} of ${BUDGET.frame}, app ${r.app} of ${BUDGET.app}, ${r.requests} of ${BUDGET.requests} requests`); + const failures = runs.flatMap((r) => judge(r)); + // Both runs see the same requests, or the measure is not the page's. + if (runs[0].requests !== runs[1].requests) failures.push(`the runs saw ${runs[0].requests} and ${runs[1].requests} requests: the page had not settled`); + if (failures.length) { + for (const f of new Set(failures)) console.error(`FR-03: ${f}`); + process.exit(1); + } +} + +if (import.meta.url === pathToFileURL(process.argv[1] ?? "").href) await main(); diff --git a/bootstrap/worker-runtime.mjs b/bootstrap/worker-runtime.mjs new file mode 100644 index 0000000..b439029 --- /dev/null +++ b/bootstrap/worker-runtime.mjs @@ -0,0 +1,46 @@ +// Module workers have no document import map. Package the locked runtime with +// the same explicit crypto adapter the page already selects. These are module +// address changes only: no archive parser, verifier or guest loop is replaced. +import { createHash } from "node:crypto"; +import { mkdir, readFile, writeFile } from "node:fs/promises"; +import { dirname, join, posix } from "node:path"; + +const MODULES = ["browser.mjs", "index.mjs", "archive.mjs", "view.mjs", "core.mjs", "closure.mjs", "errors.mjs", "canonical/index.js", "blake3.mjs", "sha256.mjs"]; +const digest = (bytes) => createHash("sha256").update(bytes).digest("hex"); +const refusal = (message) => Object.assign(new Error(`frame.worker.bundle: ${message}`), { code: "frame.worker.bundle" }); + +export async function prepareWorkerRuntime(site, vendor) { + const output = join(site, "worker-runtime"); + const files = []; + // Validate the whole graph before writing anything. Unknown imports are a + // dependency change to review, never permission to fall back to the UI thread. + for (const path of MODULES) { + const source = `prism-code/src/${path}`; + const before = await readFile(join(vendor, source), "utf8"); + let after = before; + if (path === "canonical/index.js") { + const alias = "from 'node:crypto'"; + if (before.split(alias).length !== 2) throw refusal("the canonical crypto import changed"); + after = before.replace(alias, "from '../node-crypto-shim.mjs'"); + } + // The locked package uses one-line static imports. Validate those edges; + // lazy Node/closure loaders retain their original code and are not linked + // by browser.loadArchive. The real module-link test checks this inventory. + const imports = [...after.matchAll(/^\s*(?:import\s+(?:[^;\n]*?\s+from\s+)?|export\s+[^;\n]*?\s+from\s+)(["'])([^"']+)\1/gm)]; + for (const [, , specifier] of imports) { + if (!specifier.startsWith(".")) throw refusal(`unregistered import ${specifier} in ${path}`); + const target = posix.normalize(posix.join(posix.dirname(path), specifier)); + if (!MODULES.includes(target) && target !== "node-crypto-shim.mjs") throw refusal(`import ${specifier} in ${path} is outside the locked runtime`); + } + files.push({ path, source, before, after }); + } + const shim = await readFile(join(vendor, "node-crypto-shim.mjs"), "utf8"); + files.push({ path: "node-crypto-shim.mjs", source: "node-crypto-shim.mjs", before: shim, after: shim }); + for (const file of files) { + await mkdir(dirname(join(output, file.path)), { recursive: true }); + await writeFile(join(output, file.path), file.after); + } + const receipt = { schema: "prism/worker-runtime-packaging/1", files: files.map(({ path, source, before, after }) => ({ path, source, source_sha256: digest(before), output_sha256: digest(after) })) }; + await writeFile(join(output, "packaging.json"), JSON.stringify(receipt, null, 2) + "\n"); + return output; +} diff --git a/frame.lock b/frame.lock index 3f4cb3a..3295c3d 100644 --- a/frame.lock +++ b/frame.lock @@ -2,13 +2,13 @@ "spec": "prism/frame-lock/1", "source": { "repository": "UOR-Foundation/template", - "commit": "f54d6b7b0011df178859b2ee5ec647b9cf7679b0", - "raw": "https://raw.githubusercontent.com/UOR-Foundation/template/f54d6b7b0011df178859b2ee5ec647b9cf7679b0/" + "commit": "d65a5ff543bf98fc4bbfb4a4e81789767529ab1d", + "raw": "https://raw.githubusercontent.com/UOR-Foundation/template/d65a5ff543bf98fc4bbfb4a4e81789767529ab1d/" }, "files": [ { "path": "bootstrap/frame-sync.mjs", - "sha256": "c7df2d026b14ec0783a068a3fcb87a1eaabf2ea7f55ac6b61cb96b96e21e7957" + "sha256": "5d874908a8f5813b6f7c1004ec0e73ec03584139bf7ac8ffabb2ad5c0eeee7af" }, { "path": "bootstrap/icons.py", @@ -20,7 +20,7 @@ }, { "path": "bootstrap/page.mjs", - "sha256": "8d828ffa556efde2d80d45af2c5ddecb8e83a069195c1c728f0389f6a1bcc01b" + "sha256": "8eee238bce9206ca58fc9be5471c28c0bdab82e2350ed78f1972da2a1da6581f" }, { "path": "bootstrap/precache.mjs", @@ -32,27 +32,35 @@ }, { "path": "bootstrap/screens.mjs", - "sha256": "8981c65440813841bb0cc3d105d5782d378cb926a4a106198db3ca5cd21ef3dc" + "sha256": "c9787ebf5ad8e8b649034ec3e43f8812ba51777ba59eb11f1f51ca084a395b67" + }, + { + "path": "bootstrap/weight.mjs", + "sha256": "de432422e9931b4adf0f422a2030d7b38097a60a4d8fc9ed62fd20fe0c468373" + }, + { + "path": "bootstrap/worker-runtime.mjs", + "sha256": "0f9fbb6ec4db48fb7f7c4b779a0494e95d5411e868b36e1e163e5173fcc34557" }, { "path": "lighthouserc.json", - "sha256": "0145d04da93193801b0d8736ceba7e0df94b9b15f183b07a16e6feda16d72082" + "sha256": "85aa0f6219cb8396b34f5b461c1d4d7b149e4cc1674cbd2f0100c5b5e16636d9" }, { "path": "site/app.mjs", - "sha256": "8ec5c53c8cde662a05592b1c9c2a36621fbff816c95849526b7fff88ba95e2b8" + "sha256": "b5b30e78ab9b693fd6d29b89b9d2b74542340542864e99e4533a9ced2d987ee0" }, { "path": "site/guest-worker.mjs", - "sha256": "0aae31bd459646dfa3a9b8f5f1e9139a34f2fc86154342c14ad5601ec9876d7e" + "sha256": "fb7c63cca4f503ca6a3e11e4393a989f94a3c993e0e1dbde2e13f458690b1821" }, { "path": "site/page.template.html", - "sha256": "472de84e731ba74c5fecf50da42fbe0f57811e9507438185dd10d0e45c72faac" + "sha256": "b48b9d18e23e959c9e96b4bec58e2e7d80b7b977e981d8a7b0fd369293819b08" }, { "path": "site/prism-page.css", - "sha256": "6a673e2a30208acd03b541c79ac36ffac8eb37af1d71f8a85366d85cd155932f" + "sha256": "e74dc6dbe7f1394fdf1f7c663578ea4fbb4836f301b87f82d57a7c5dc6066e1c" }, { "path": "site/spec.css", @@ -64,7 +72,7 @@ }, { "path": "site/sw.js", - "sha256": "b4d4eb5c8314f5abed013ea9d172e7352dbdfa5aa2b503901df364ebcfbf11f7" + "sha256": "baf0fbd7da2fa0b33124951bbd1218aa6658c342340fb24415c636f220c9ea74" }, { "path": "site/theme.js", diff --git a/lighthouserc.json b/lighthouserc.json index 9d99a49..6ccede7 100644 --- a/lighthouserc.json +++ b/lighthouserc.json @@ -23,8 +23,6 @@ "total-blocking-time": ["error", { "maxNumericValue": 100 }], "cumulative-layout-shift": ["error", { "maxNumericValue": 0 }], "first-contentful-paint": ["error", { "maxNumericValue": 1200 }], - "resource-summary:total:size": ["error", { "maxNumericValue": 122880 }], - "resource-summary:total:count": ["error", { "maxNumericValue": 28 }], "resource-summary:third-party:count": ["error", { "maxNumericValue": 2 }], "uses-long-cache-ttl": "off", "network-dependency-tree-insight": "off", diff --git a/site/app.mjs b/site/app.mjs index 0e626fa..c343802 100644 --- a/site/app.mjs +++ b/site/app.mjs @@ -33,7 +33,9 @@ function chip(element, text, state) { element.className = `chip chip-${state}`; } -// The canonical , run only if it matches the pointer's SHA-256. +// The canonical , run only if its bytes match the pointer's +// SHA-256, so a template change reaches every app and nothing stands in for +// it. ?frame= pins one; offline, the service worker serves the last. async function frame() { if (customElements.get("prism-frame")) return; const host = new URL(data.frame); @@ -119,7 +121,10 @@ function answerState(text) { return ""; } -// Heavy work waits for first contentful paint (or a timer), to keep LCP low. +// The frame, runtime and holo wait for the first contentful paint (the fonts +// are optional, so the first frame may have no text): fetched earlier, they +// pushed every app's LCP past 1.5 s on a simulated phone. A background tab +// never paints, so a timer stands in. const afterFirstFrame = () => new Promise((resolve) => { const after = () => requestAnimationFrame(() => setTimeout(resolve, 0)); setTimeout(resolve, 1000); @@ -136,55 +141,58 @@ const afterFirstFrame = () => new Promise((resolve) => { } }); -// The holo loads and verifies on the first touch, key, scroll or focus, not -// on load, to keep the page within its size and blocking-time budget. -const firstIntent = () => new Promise((resolve) => { - const events = ["pointerdown", "keydown", "touchstart", "wheel", "focusin"]; - const start = () => { - for (const name of events) removeEventListener(name, start, true); - removeEventListener("hashchange", start); - resolve(); +// Verification belongs to the worker too: loading a large model can block +// the UI before the guest ever runs. Only unavailable/broken worker transport +// falls back to the same fully verified runtime on the page. A runtime refusal +// is final, not evidence that workers are unavailable. +async function offThread(source) { + const onPage = async () => { + const { load } = await import("./vendor/prism-code/src/browser.mjs"); + return load(source); }; - if (location.hash || $("input")?.value) return start(); - for (const name of events) addEventListener(name, start, { capture: true, passive: true }); - addEventListener("hashchange", start); -}); - -// The verified guest runs in a worker, so nothing blocks the page; without -// workers it runs here. -async function offThread(app) { - if (typeof Worker !== "function") return app; - const { resolveArchive } = await import("./vendor/prism-code/src/index.mjs"); - const wasm = resolveArchive(app.archive).guest.content; - const worker = new Worker("./guest-worker.mjs", { type: "module" }); + if (typeof Worker !== "function") return onPage(); + let worker; + try { + worker = new Worker("./guest-worker.mjs", { type: "module" }); + } catch { + return onPage(); + } const waiting = new Map(); let next = 0; + let failure = null; + const stop = () => { + failure ??= Object.assign(new Error("the guest worker failed"), { code: "frame.worker" }); + worker.terminate(); + for (const settle of waiting.values()) settle.reject(failure); + waiting.clear(); + }; worker.onmessage = ({ data: reply }) => { - const settle = waiting.get(reply.id); + const settle = waiting.get(reply?.id); + if (!settle || typeof reply.ok !== "boolean") { stop(); return; } waiting.delete(reply.id); if (reply.ok) settle.resolve(reply.value); - else settle.reject(new Error(reply.error)); - }; - // A crashed worker fails every call; the page falls back to the instance. - worker.onerror = (event) => { - event.preventDefault?.(); - for (const settle of waiting.values()) settle.reject(new Error("the guest worker failed")); - waiting.clear(); + else settle.reject(Object.assign(new Error(reply.error), { code: reply.code, runtimeRefusal: true })); }; - const call = (kind, payload) => new Promise((resolve, reject) => { + worker.onerror = (event) => { event.preventDefault?.(); stop(); }; + worker.onmessageerror = stop; + const call = (kind, payload = {}) => new Promise((resolve, reject) => { + if (failure) { reject(failure); return; } const id = next++; waiting.set(id, { resolve, reject }); - worker.postMessage({ id, kind, ...payload }); + try { worker.postMessage({ id, kind, ...payload }); } catch { stop(); } }); + let identities; try { - await call("init", { wasm, limits: app.limits ?? {} }); - } catch { + identities = await call("init", { source }); + } catch (error) { worker.terminate(); - return app; + if (error.runtimeRefusal) throw error; + return onPage(); } return { + identities, dispatch: (request) => call("dispatch", { request }), - acceptance: () => call("acceptance", { vectors: app.vectors }), + acceptance: () => call("acceptance"), }; } @@ -238,60 +246,16 @@ const report = (result) => { specModule?.apply(checked); }; -// The form, live from first paint; the answer shows under it with its state. -const STATES = { good: "Answer", bad: "Refused", refuse: "Not understood", wait: "Verifying", error: "Error" }; -function workspace(ready) { +// Answer as the visitor types; keep a request once they pause, press Enter or pick one. +function workspace(runner) { const input = $("input"); - const form = $("ask"); - if (!input || !form) return; + if (!input) return; const out = $("out"); - const tag = $("state"); const hist = $("hist"); + const size = () => input.style.setProperty("--chars", String(Math.max((input.value || input.placeholder).length, 4))); let seq = 0; - let shown = 0; + let settle = 0; let last = ""; - let settled; - ready.then((runner) => { settled = runner; }, () => { settled = null; }); - const links = data.answerLinks ?? {}; - // "key value" lines; answerLinks link a value. - const line = (text) => { - const row = document.createElement("li"); - const at = text.indexOf(" "); - if (at <= 0) { row.textContent = text; return row; } - const key = text.slice(0, at); - const value = text.slice(at + 1); - const k = document.createElement("span"); - k.className = "key"; - k.textContent = key.charAt(0).toUpperCase() + key.slice(1); - let v; - if (links[key] && /^[\w.:-]+$/.test(value)) { - v = document.createElement("a"); - v.href = links[key].split("{}").join(encodeURIComponent(value)); - } else { - v = document.createElement("span"); - } - v.className = "val"; - v.textContent = value; - row.append(k, v); - return row; - }; - const say = (state, text, lines) => { - out.className = state; - if (lines) { - const list = document.createElement("ul"); - list.className = "lines"; - list.append(...lines.map(line)); - out.replaceChildren(list); - } else { - out.textContent = text; - } - // Counted, so a test can tell a new answer. - if (state !== "idle" && state !== "wait") out.dataset.answers = String(++shown); - tag.hidden = state === "idle"; - tag.className = `tag ${state}`; - tag.textContent = STATES[state] ?? ""; - form.setAttribute("aria-busy", String(state === "wait")); - }; const remember = (text, response) => { if (!text || text === last) return; last = text; @@ -301,58 +265,46 @@ function workspace(ready) { again.className = "again"; const req = document.createElement("span"); req.textContent = text.length > 22 ? `${text.slice(0, 20)}…` : text; - const t = document.createElement("span"); - t.className = `tag ${answerState(response)}`; - t.textContent = STATES[answerState(response)] ?? "Answer"; - again.append(req, t); - again.addEventListener("click", () => { input.value = text; answer(); }); + const tag = document.createElement("span"); + tag.className = `tag ${answerState(response)}`; + tag.textContent = response.length > 18 ? `${response.length} bytes` : response; + again.append(req, tag); + again.addEventListener("click", () => { input.value = text; answer(true); input.focus(); }); row.append(again); hist.prepend(row); while (hist.children.length > 30) hist.lastChild.remove(); }; - async function answer() { + async function answer(commit = false) { const text = input.value; const n = ++seq; - if (text.trim() === "") { - say("refuse", `Type a ${(data.inputLabel || "request").toLowerCase()} first, or pick an example.`); - input.focus({ preventScroll: true }); - return; - } - let runner = settled; - if (runner === undefined) { - say("wait", "Checking this app in your browser before it answers. This takes a moment, once."); - runner = await ready; - if (n !== seq) return; - } - if (!runner) { - say("error", "This app could not be verified in your browser, so it will not answer. Reload the page to try again."); + size(); + clearTimeout(settle); + if (text === "") { + out.textContent = "—"; + out.className = "idle"; return; } + if (!runner) return; let response; try { response = show(await runner.dispatch(parse(text))); } catch (error) { - if (n !== seq) return; - if (error?.message === "malformed hex") response = data.answers?.refusal ?? "invalid request"; - else { - say("error", `The app could not run this request: ${describe(error)}`); - return; - } + response = error?.message === "malformed hex" ? data.answers?.refusal ?? "invalid request" : `dispatch failed: ${describe(error)}`; } if (n !== seq) return; const state = answerState(response); - if (state === "refuse") say("refuse", `That is not a valid ${(data.inputLabel || "request").toLowerCase()}. Try one of the examples.`); - else { - const lines = response.split("\n").map((x) => x.trim()).filter(Boolean); - say(state, response, lines.length ? lines : [response]); - } - remember(text, response); + out.textContent = state === "refuse" ? `Not a valid ${(data.inputLabel || "request").toLowerCase()}` : response.charAt(0).toUpperCase() + response.slice(1); + out.className = state; + if (commit) remember(text, response); + else settle = setTimeout(() => remember(text, response), 900); } - form.addEventListener("submit", (event) => { event.preventDefault(); answer(); }); - input.addEventListener("input", () => { seq++; if (out.className !== "idle") say("idle", data.idle ?? ""); }); + input.addEventListener("input", () => answer()); + input.addEventListener("keydown", (event) => { if (event.key === "Enter") answer(true); }); for (const button of $("tries").querySelectorAll("button[data-request]")) { - button.addEventListener("click", () => { input.value = button.dataset.request; answer(); }); + button.addEventListener("click", () => { input.value = button.dataset.request; answer(true); input.focus({ preventScroll: true }); }); } + size(); + if (input.value) answer(); } async function main() { @@ -361,33 +313,24 @@ async function main() { offline(); spec(); - let ready; - const verified = new Promise((resolve) => { ready = resolve; }); - workspace(verified); - let app; try { await afterFirstFrame(); - verdict("wait", "Verifies when you start"); - await firstIntent(); - verdict("wait", "Verifying in this browser"); - const { load } = await import("./vendor/prism-code/src/browser.mjs"); - app = await load("./app.holo"); + app = await offThread(new URL("./app.holo", document.baseURI).href); } catch (error) { verdict("bad", "The app failed to load"); replayed("error"); report({ error: `the app failed to load: ${describe(error)}` }); - ready(null); await card(null, "no app"); return; } const { identities } = app; - const runner = await offThread(app); + const runner = app; const ok = identities.verified; verdict(ok ? "good" : "bad", ok ? "Verified in this browser" : "NOT verified", identities.archiveFingerprint); checked.fingerprint = identities.archiveFingerprint; - ready(ok ? runner : null); + workspace(ok ? runner : null); card(ok ? runner : null, ok ? "" : "not verified"); if (!ok) { replayed("error"); diff --git a/site/guest-worker.mjs b/site/guest-worker.mjs index 5b47c70..430d6cb 100644 --- a/site/guest-worker.mjs +++ b/site/guest-worker.mjs @@ -1,29 +1,37 @@ -// Runs the holo's guest off the page's main thread. A request that takes a -// second on a slow phone (a chess reply, a long search) never blocks a tap or -// a paint. The page loads and verifies the holo itself and sends this worker -// the guest bytes of that same verified archive; the worker only compiles and -// runs them with the runtime's own guest loop, one fresh instance per request. -import { compileGuest, runGuest, runAcceptance } from "./vendor/prism-code/src/core.mjs"; - -let guest = null; -let limits = {}; +// The locked runtime owns archive verification, compilation and execution. +// Keep the verified application here; only identities and request results +// cross the boundary. No parsed archive or guest bytes are trusted from the UI. +import { load } from "./worker-runtime/browser.mjs"; +let app = null; +let started = false; +const refuse = (code) => { throw Object.assign(new Error(code), { code }); }; const describe = (error) => error?.code ?? error?.message ?? String(error); self.onmessage = async ({ data }) => { const { id, kind } = data; try { if (kind === "init") { - guest = await compileGuest(data.wasm); - limits = data.limits; - self.postMessage({ id, ok: true }); - } else if (kind === "dispatch") { - self.postMessage({ id, ok: true, value: runGuest(guest, data.request, limits) }); - } else if (kind === "acceptance") { - const result = await runAcceptance(data.vectors, async (request) => runGuest(guest, request, limits)); - self.postMessage({ id, ok: true, value: { total: result.total, passed: result.passed } }); + if (started) refuse("frame.worker.initialized"); + started = true; + app = await load(data.source); + self.postMessage({ id, ok: true, value: app.identities }); + } else { + if (!app) refuse("frame.worker.not-ready"); + if (!app.identities.verified) refuse("frame.worker.not-verified"); + if (kind === "dispatch") { + self.postMessage({ id, ok: true, value: await app.dispatch(data.request) }); + } else if (kind === "acceptance") { + const result = await app.acceptance(); + self.postMessage({ id, ok: true, value: { + total: result.total, passed: result.passed, + failed: (result.failed ?? []).map(({ index }) => ({ index })), + } }); + } else { + refuse("frame.worker.request"); + } } } catch (error) { - self.postMessage({ id, ok: false, error: describe(error) }); + self.postMessage({ id, ok: false, error: describe(error), code: error?.code }); } }; diff --git a/site/page.template.html b/site/page.template.html index bd75ff5..dd11d40 100644 --- a/site/page.template.html +++ b/site/page.template.html @@ -47,7 +47,7 @@

{{NAME}}

-

{{TAGLINE}}

{{NAV}} +

{{TAGLINE}}

@@ -56,7 +56,8 @@

{{NAME}}

{{SURFACE}}
-{{RAIL}} +
—
+

{{ACTIONS_LABEL}}

{{TRIES}}

Recent

    diff --git a/site/prism-page.css b/site/prism-page.css index 0a545a4..1d645d4 100644 --- a/site/prism-page.css +++ b/site/prism-page.css @@ -335,55 +335,28 @@ h1 { } .k { margin: 0 0 var(--space-2); font-size: var(--text-14); color: var(--muted-foreground); } -/* Where to go next, under the description: the first link is the main way on. */ -.head-nav { display: flex; flex-wrap: wrap; gap: var(--space-2); margin-top: var(--space-3); } -.head-nav a { display: inline-flex; align-items: center; min-height: var(--control); padding: 0 var(--space-4); border: var(--border-width) solid var(--border); border-radius: var(--radius-control); color: var(--foreground); font-size: var(--text-14); font-weight: 500; text-decoration: none; transition: background var(--duration) var(--ease); } -.head-nav a:hover { background: var(--accent); } -.head-nav a:first-child { background: var(--primary); border-color: var(--primary); color: var(--primary-foreground); } -.head-nav a:first-child:hover { background: var(--primary-hover); border-color: var(--primary-hover); } - -/* The form: a label, a field and the button that runs it, a line on how, - * the examples, then the answer, which takes the rest of the stage and - * scrolls inside itself, so the page never moves when an answer arrives. */ -.stage:has(.ask) { grid-template-columns: minmax(0, 1fr); place-items: stretch center; } -.ask { width: min(100%, 44rem); min-height: 0; display: flex; flex-direction: column; gap: var(--space-6); } -.ask-form { display: flex; flex-direction: column; gap: var(--space-2); } -.ask-form .k { margin: 0; font-size: var(--text-16); font-weight: 500; color: var(--foreground); } -.ask-row { display: flex; gap: var(--space-2); } -.ask-row input { - flex: 1; - width: 0; - min-width: 0; - min-height: var(--touch); - padding: 0 var(--space-4); - border: var(--border-width) solid var(--border); - border-radius: var(--radius-control); - background: var(--card); +/* The input as a display: what you type is the largest thing on screen, and + * it shrinks to fit however long it gets (app.mjs counts the characters). */ +.display { display: block; width: min(100%, 40rem); container-type: inline-size; cursor: text; } +.display .k { margin-bottom: var(--space-1); } +.display input { + display: block; + width: 100%; + padding: 0; + border: 0; + outline: 0; + background: none; color: var(--foreground); + caret-color: var(--foreground); font-family: var(--font-mono); - font-size: var(--text-18); -} -.ask-row input:focus-visible { border-color: var(--ring); } -.ask-row input::placeholder { color: var(--muted-foreground); } -.ask-row button { flex: none; min-height: var(--touch); padding: 0 var(--space-6); font-size: var(--text-16); } -.hint { margin: 0; font-size: var(--text-14); color: var(--muted-foreground); } -.ask .actions .k { margin-bottom: var(--space-2); } -.answer { flex: 1; min-height: 6rem; display: flex; flex-direction: column; padding: var(--space-4); border: var(--border-width) solid var(--border); border-radius: var(--radius); background: var(--card); } -.answer-head { flex: none; display: flex; align-items: center; justify-content: space-between; gap: var(--space-3); margin-bottom: var(--space-3); } -.answer-head .k { margin: 0; font-family: var(--font-sans); font-weight: 500; } -.answer output { flex: 1; min-height: 0; display: block; overflow-y: auto; scrollbar-width: thin; font-size: var(--text-18); line-height: 1.5; overflow-wrap: anywhere; } -.answer output.idle, .answer output.wait { color: var(--muted-foreground); font-size: var(--text-16); } -.answer output.refuse, .answer output.error { font-size: var(--text-16); } -.answer .lines { margin: 0; padding: 0; list-style: none; display: grid; gap: var(--space-2); } -.answer .lines li { display: flex; flex-wrap: wrap; align-items: baseline; gap: 0 var(--space-3); } -.answer .key { min-width: 5rem; font-size: var(--text-14); color: var(--muted-foreground); } -.answer .val { font-family: var(--font-mono); color: var(--foreground); } -.answer a.val { color: var(--foreground); text-decoration: underline; text-underline-offset: 0.2em; } -.answer output.good .lines li:first-child .val { color: var(--success); } -.tag.wait { background: var(--muted); color: var(--muted-foreground); } -.tag.bad, .tag.refuse { background: var(--muted); color: var(--foreground); } -.tag.error { background: var(--muted); color: var(--destructive); } -.about-text { margin: 0; font-size: var(--text-14); line-height: 1.6; color: var(--muted-foreground); } + font-weight: 400; + font-size: min(7rem, 16vh, 100cqw * 1.5 / var(--chars, 4)); + line-height: 1.15; + letter-spacing: -0.05em; +} +.display input::placeholder { color: color-mix(in oklab, var(--muted-foreground) 45%, transparent); } +.display .rule { display: block; height: 2px; margin-top: var(--space-2); border-radius: 2px; background: linear-gradient(90deg, var(--foreground), transparent); opacity: 0.2; transition: opacity var(--duration) var(--ease); } +.display:focus-within .rule { opacity: 0.5; } /* Rail: the result, the actions, the history. */ .result { flex: none; min-height: 4.25rem; display: flex; align-items: flex-start; } @@ -408,7 +381,7 @@ h1 { padding: 0 var(--space-3); border-radius: 999px; background: transparent; - color: var(--foreground); + color: var(--muted-foreground); font-family: var(--font-mono); font-weight: 400; } @@ -510,12 +483,7 @@ button.spec-x:hover { background: var(--accent); color: var(--foreground); } border-top: var(--border-width) solid var(--border); background: color-mix(in oklab, var(--background), var(--foreground) 2%); } - .rail .k, .history, .about { display: none; } - .ws:has(.ask) { grid-template-rows: minmax(0, 1fr); } - .ws:has(.ask) .rail { display: none; } - .ask { gap: var(--space-4); } - .head-nav a { padding: 0 var(--space-3); } - .ask-row button { padding: 0 var(--space-4); } + .rail .k, .history { display: none; } .result, .has-card .result { min-height: 2.5rem; align-items: center; } .result output { font-size: 2.25rem; } .result output.refuse { font-size: var(--text-16); } @@ -529,11 +497,6 @@ button.spec-x:hover { background: var(--accent); color: var(--foreground); } .lede { display: none; } .head { padding-top: var(--space-2); } .stage { padding-block: var(--space-2); } - .ask { gap: var(--space-2); } - .hint, .ask-form .k, .ask .actions .k { display: none; } - .head-nav { margin-top: var(--space-2); } - .answer { min-height: 4.5rem; padding: var(--space-2) var(--space-3); } - .answer-head { margin-bottom: var(--space-1); } } /* Immersive: the rail and the spec are frosted glass over the photo. */ @@ -553,7 +516,7 @@ html.immersive .rail { background: color-mix(in oklab, var(--card) 60%, transpar /* Touch: every control is 48 px, Material's minimum, whatever rule sized it * above. Last, so nothing overrides it. */ @media (pointer: coarse) { - button, input, .ghost, a.ghost, .spec-link, .spec summary, .links a, .head-nav a, + button, input, .ghost, a.ghost, .spec-link, .spec summary, .links a, .tries button, button.again, button.term, button.more, button.copy, button.check, button.spec-x, .rail .controls button, .rail .controls select { min-height: var(--touch); } button, .tries button, button.term, button.more, button.copy, button.spec-x, .rail .controls button, .spec-link { min-width: var(--touch); } diff --git a/site/sw.js b/site/sw.js index 064324f..1f4574d 100644 --- a/site/sw.js +++ b/site/sw.js @@ -10,7 +10,15 @@ // an unchanged deploy is not. Every file but index.html is immutable per // deploy (the holo is content-addressed), so the cache is the source and the // network the fallback; index.html goes to the network first, so a new deploy -// is seen on the next visit, and the new worker then tells the page once. +// is seen on the next visit. +// +// This file's bytes are the same in every deploy, so the browser never installs +// a new worker for one: the worker that kept the first visit's files would serve +// them forever, under every later index.html. So each navigation that reaches +// the network also asks precache.json for the deploy's version, and a version +// this worker does not keep becomes its cache before the page is answered: the +// page's own files then come from the network into the new cache, and the +// earlier deploy's cache is dropped. const MANIFEST = "./precache.json"; let cacheName = null; @@ -27,17 +35,40 @@ async function currentCacheName() { return cacheName; } +// Opens the cache for this deploy's manifest and keeps its eager files there. +async function keep(list) { + const cache = await caches.open(`prism-${list.version}`); + await cache.put(MANIFEST, new Response(JSON.stringify(list), { headers: { "content-type": "application/json" } })); + const eager = list.files.filter((file) => file.eager).map((file) => new Request(file.path, { cache: "reload" })); + await cache.addAll(eager); +} + self.addEventListener("install", (event) => { event.waitUntil((async () => { const list = await manifest(); + await keep(list); cacheName = `prism-${list.version}`; - const cache = await caches.open(cacheName); - await cache.put(MANIFEST, new Response(JSON.stringify(list), { headers: { "content-type": "application/json" } })); - const eager = list.files.filter((file) => file.eager).map((file) => new Request(file.path, { cache: "reload" })); - await cache.addAll(eager); })()); }); +// A deploy this worker does not keep becomes its cache, once, however many +// navigations ask at the same time. Offline, or with no manifest, the kept +// deploy stays. +let moving = null; +function follow() { + moving ??= (async () => { + const list = await manifest(); + const name = `prism-${list.version}`; + if (name === (await currentCacheName())) return; + await keep(list); + cacheName = name; + for (const old of await caches.keys()) { + if (old.startsWith("prism-") && old !== name) await caches.delete(old); + } + })().catch(() => {}).finally(() => { moving = null; }); + return moving; +} + self.addEventListener("activate", (event) => { event.waitUntil((async () => { const keep = await currentCacheName(); @@ -85,17 +116,24 @@ self.addEventListener("fetch", (event) => { if (url.pathname.endsWith("/precache.json")) return; const isPage = event.request.mode === "navigate" || url.pathname.endsWith("/") || url.pathname.endsWith("/index.html"); event.respondWith((async () => { - const name = await currentCacheName(); - const cache = name ? await caches.open(name) : null; if (isPage) { + let fresh = null; try { - const fresh = await fetch(event.request); - if (fresh.ok && cache) await cache.put("./", fresh.clone()); - return fresh; + fresh = await fetch(event.request); } catch { + const name = await currentCacheName(); + const cache = name ? await caches.open(name) : null; return (cache && ((await cache.match("./")) ?? (await cache.match(event.request)))) ?? Response.error(); } + if (fresh.ok) { + await follow(); + const name = await currentCacheName(); + if (name) await (await caches.open(name)).put("./", fresh.clone()); + } + return fresh; } + const name = await currentCacheName(); + const cache = name ? await caches.open(name) : null; const hit = cache && (await cache.match(event.request, { ignoreSearch: true })); if (hit) return hit; const fresh = await fetch(event.request);