Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,13 @@ How to write an entry (from 0.21.0 on; older sections keep their own form):
family with a fitted fallback now gets its own fitted face, deferred or not, in whichever of the build's stylesheets
it is
([fonts after the load](docs/first-paint.md#fonts-after-the-load)).
- A swap no longer fails because of another origin's module script on the next page (an analytics beacon a CDN
injects, such as Cloudflare's, blocked by an extension or offline): only the app's own modules decide the swap; the
others run after it, once per document, as on a load, with their `integrity` checked, which the swap's `import()`
skipped before ([swaps](docs/navigation.md#swaps)).
- A swap that loads its page instead (the page answered an error, a module failed to load) still morphs its
`data-sn-transition` pair: the load is handed the link that started it
([page transitions](docs/navigation.md#page-transitions)).

## 0.23.1 (2026-12-02)

Expand Down
6 changes: 5 additions & 1 deletion docs/navigation.md
Original file line number Diff line number Diff line change
Expand Up @@ -322,6 +322,9 @@ link's `#hash` is scrolled to, and the new title is announced to screen readers.
page's body (`SN540`). App modules run once per document: per-page work goes in a listener for
`sn-page`, which `document` gets after each page mounts, the first one included
(`e.detail.kind` is `load`, `push`, `replace` or `traverse`).
- Another origin's module scripts on the next page (an analytics beacon your CDN injects) run after the swap,
once per document, with their `integrity` checked, as on a load. The swap does not wait for them, and one that
does not load (blocked by an extension) does not stop it: only the app's own modules do.
- Every page runs under the first page's response headers, its Content-Security-Policy included: one
policy for the app. With a nonce policy, put each response's nonce in `<meta name="csp-nonce"
content="…">` too: the swap trusts what the server gave the next page's nonce (its styles, its module
Expand Down Expand Up @@ -401,7 +404,8 @@ element it becomes on the detail page:
list needs nothing: its rows come back as it was left ([Back and Forward](resources.md#back-and-forward)).
A link to a list (not Back) morphs into it only with `cache` on its resource, or its rows arrive too
late and it only fades.
- One morph per navigation. Navigations sinter starts itself (a redirect) do not morph.
- One morph per navigation. Navigations sinter starts itself (a redirect) do not morph, except a swap
that loads its page instead: that load still morphs from the link's row.
- **Reduced motion:** when the visitor's system asks for reduced motion (`prefers-reduced-motion: reduce`),
nothing morphs. The fade is your CSS: temper's rule turns it off then too; without temper, put your
`@view-transition` rule inside `@media (prefers-reduced-motion: no-preference) { … }`.
Expand Down
5 changes: 4 additions & 1 deletion e2e/permanent/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,10 @@ each swap; the new title announced; `<noscript>` left inert; the last of two cli
`data-sn-swap="off"`, a page with it, and a 404 are page loads; each entry's scroll position on Back and
Forward and after reloads; a link's `#hash`; a click during the transition and while the page is fetched;
a traversal that cannot swap; Back after a swapped Back; a GET form and `rel="external"`; the transition
with the stylesheet's rule and none under reduced motion.
with the stylesheet's rule and none under reduced motion; another origin's module script on the next page
(served from `localhost`, the pages from `127.0.0.1`, as a CDN injects an analytics beacon) that does not
load, whose integrity does not match, or that runs once per document, none of which stops the swap; and a
swap that loads its page instead (the page answers an error) still morphing its pair.

```sh
npm ci
Expand Down
87 changes: 83 additions & 4 deletions e2e/permanent/run.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,28 @@ const pw = createRequire(join(here, '../../package.json'))('playwright');
if (spawnSync('npx', ['vite', 'build', '--logLevel', 'warn'], { cwd: here, stdio: 'inherit' }).status) process.exit(1);

const TYPES = { '.html': 'text/html; charset=utf-8', '.js': 'text/javascript', '.css': 'text/css', '.json': 'application/json' };
let slow = false, plainA = false;
let slow = false, plainA = false, failB = false;
/**
* Another origin's module script in B's body, as a CDN injects one (Cloudflare's analytics beacon): `/control/beacon-ok`
* one that runs (it counts its runs), `-blocked` one that does not load (an extension blocks it), `-sri` one whose
* `integrity` does not match, `-none` none
*/
let beacon = 'none';
const other = createServer((req, res) => {
const path = new URL(req.url, 'http://x').pathname;
if (path !== '/beacon.js') { res.writeHead(404); return res.end(); }
res.writeHead(200, { 'Content-Type': 'text/javascript', 'Access-Control-Allow-Origin': '*', 'Cache-Control': 'no-store' });
res.end('window.__beacon = (window.__beacon ?? 0) + 1;');
});
await new Promise((r) => other.listen(0, '127.0.0.1', r));
// (`localhost`: another origin than the pages' `127.0.0.1`)
const elsewhere = `http://localhost:${other.address().port}`;
const BEACONS = {
none: '',
ok: `<script type="module" src="${elsewhere}/beacon.js" crossorigin="anonymous"></script>`,
blocked: `<script type="module" src="${elsewhere}/blocked.js" crossorigin="anonymous"></script>`,
sri: `<script type="module" src="${elsewhere}/beacon.js" integrity="sha384-${'A'.repeat(64)}" crossorigin="anonymous"></script>`,
};
/** every path the server was asked for (a page the swap cannot take would be asked for twice) */
const requested = [];
const server = createServer(async (req, res) => {
Expand All @@ -27,6 +48,10 @@ const server = createServer(async (req, res) => {
// `/control/plain-a`: the next request for `/` answers an error (it cannot swap; the load after it is answered)
if (path === '/control/plain-a') { plainA = true; res.writeHead(204); return res.end(); }
if (plainA && path === '/') { plainA = false; res.writeHead(500, { 'Content-Type': 'text/html' }); return res.end('<!doctype html><title>error</title><p>error</p>'); }
// `/control/fail-b`: the next request for `/b/` answers an error (the swap's: it loads instead, and the load is answered)
if (path === '/control/fail-b') { failB = true; res.writeHead(204); return res.end(); }
if (failB && path === '/b/') { failB = false; res.writeHead(500, { 'Content-Type': 'text/html' }); return res.end('<!doctype html><title>error</title><p>error</p>'); }
if (path.startsWith('/control/beacon-')) { beacon = path.slice('/control/beacon-'.length); res.writeHead(204); return res.end(); }
// `/control/slow`: the next page answers 600 ms late (a second click while the swap fetches)
if (path === '/control/slow') { slow = true; res.writeHead(204); return res.end(); }
if (slow && extname(path) === '' && path !== '/control/') { slow = false; await new Promise((r) => setTimeout(r, 600)); }
Expand All @@ -36,7 +61,8 @@ const server = createServer(async (req, res) => {
if (path === '/b') { res.writeHead(301, { Location: '/b/' }); return res.end(); }
const file = path === '/' ? 'index.html' : /^\/(b|plain|off|nojs)\/$/.test(path) ? `${path.slice(1)}index.html` : normalize(path).replace(/^\/+/, '');
try {
const body = await readFile(join(here, 'dist', file));
let body = await readFile(join(here, 'dist', file));
if (path === '/b/' && BEACONS[beacon]) body = body.toString().replace('</body>', `${BEACONS[beacon]}</body>`);
res.writeHead(200, { 'Content-Type': TYPES[extname(file)] ?? 'application/octet-stream', 'Cache-Control': 'no-store' });
res.end(body);
} catch {
Expand Down Expand Up @@ -94,7 +120,8 @@ for (const name of browsers) {
// WebKit does not match the build's `<link rel="preload" as="fetch">` to the page's request (it requests
// twice on a page load, swaps or not) and says so a few seconds after the load: not the swap's
// (headed browsers also ask for /favicon.ico, which this app has not)
if (/Prefetch request denied|was preloaded using link preload but not used/.test(m.text()) || ['/nope/', '/favicon.ico'].includes(new URL(m.location().url || base).pathname)) return;
// (the other origin's scripts the steps block, or whose integrity does not match: the browser reports them, as on a load)
if (/Prefetch request denied|was preloaded using link preload but not used/.test(m.text()) || m.text().includes(elsewhere) || (m.location().url ?? '').startsWith(elsewhere) || ['/nope/', '/favicon.ico'].includes(new URL(m.location().url || base).pathname)) return;
if (['error', 'warning'].includes(m.type())) errors.push(m.text());
});
const steps = [];
Expand Down Expand Up @@ -346,7 +373,8 @@ for (const name of browsers) {

// the second review's findings, each as found
const p3 = await browser.newPage();
p3.on('pageerror', (e) => errors.push(e.message));
// (WebKit reports the other origin's script whose integrity does not match as an error of the page, as on a load)
p3.on('pageerror', (e) => e.message === 'Cannot load script due to integrity mismatch' || errors.push(e.message));
const at = (path, title) => p3.waitForFunction(([p, t]) => location.pathname === p && document.title === t, [path, title], { timeout: 5000 }).catch(() => {});
const view = () => p3.evaluate(() => ({ path: location.pathname, marker: window.__marker ?? null, index: navigation.currentEntry?.index, entries: history.length, q: document.getElementById('q')?.textContent ?? null }));
try {
Expand Down Expand Up @@ -518,6 +546,56 @@ for (const name of browsers) {
const withRule = await counted(false), reduced = await counted(true);
if (readable) check('a swap transitions as the stylesheet asks, not under reduced motion', { withRule, reduced }, { withRule: 1, reduced: 0 });
else check('no page transitions in this browser: a swap starts none', { withRule, reduced }, { withRule: 0, reduced: 0 });

// another origin's module script on the next page (a CDN's analytics beacon): not the app's, so the swap does not
// wait for it or fail with it; it runs as on a load (once per document, with its integrity checked)
await p3.emulateMedia({ reducedMotion: 'no-preference' });
const beaconSwap = async (mode) => {
await p3.request.post(base + '/control/beacon-' + mode);
await p3.goto(base + '/');
await at('/', 'A: Alpha');
await p3.evaluate(() => { window.__marker = 20; });
await p3.evaluate(() => document.getElementById('to-b').click());
await at('/b/', 'B: Beta');
await p3.waitForTimeout(400);
return p3.evaluate(() => ({ marker: window.__marker ?? null, beacon: window.__beacon ?? 0, items: document.querySelectorAll('#items li').length }));
};
check('another origin\'s module script that does not load: the page still swaps', await beaconSwap('blocked'), { marker: 20, beacon: 0, items: 3 });
check('another origin\'s module script with the wrong integrity: the page swaps, the script is blocked', await beaconSwap('sri'), { marker: 20, beacon: 0, items: 3 });
const ran = await beaconSwap('ok');
// to A and back to B: the script has run in this document, it does not run again
await p3.evaluate(() => document.getElementById('to-a').click());
await at('/', 'A: Alpha');
await p3.evaluate(() => document.getElementById('to-b').click());
await at('/b/', 'B: Beta');
await p3.waitForTimeout(400);
check('another origin\'s module script: run after the swap, once per document', { ...ran, again: await p3.evaluate(() => [window.__marker, window.__beacon]) }, { marker: 20, beacon: 1, items: 3, again: [20, 1] });
await p3.request.post(base + '/control/beacon-none');

// a swap that cannot (the next page answers an error) loads instead: the load still morphs from the link's row
// (the names each page gives, as the transition captures them)
const p5 = await browser.newPage();
p5.on('pageerror', (e) => errors.push(e.message));
try {
await p5.addInitScript(() => addEventListener('pagereveal', (e) => {
const vt = e.viewTransition;
sessionStorage.setItem('reveal', vt ? 'pending' : 'none');
vt?.ready.then(() => sessionStorage.setItem('reveal', document.getElementById('heading')?.style.viewTransitionName || 'unnamed'), () => sessionStorage.setItem('reveal', 'skipped'));
}));
await p5.goto(base + '/');
await p5.waitForFunction(() => document.title === 'A: Alpha', null, { timeout: 5000 });
// (after sinter's own listener: the name it gives)
await p5.evaluate(() => addEventListener('pageswap', () => sessionStorage.setItem('swap', document.getElementById('morph').style.viewTransitionName || 'unnamed')));
await p5.request.post(base + '/control/fail-b');
await Promise.all([p5.waitForEvent('load', { timeout: 5000 }), p5.evaluate(() => document.getElementById('to-b-morph').click())]);
await p5.waitForFunction(() => document.title === 'B: Beta', null, { timeout: 5000 });
await p5.waitForTimeout(400);
const got = await p5.evaluate(() => ({ swap: sessionStorage.getItem('swap'), reveal: sessionStorage.getItem('reveal') }));
// (Firefox has no `pagereveal`: nothing recorded)
if (got.reveal == null || got.reveal === 'none') steps.push('- a swap that loads instead: no transitions between documents in this browser');
else check('a swap that loads instead still morphs from the link\'s row', { pair: /^sn-/.test(got.swap ?? '') && got.swap === got.reveal }, { pair: true });
} catch (e) { steps.push(`✗ ${e.message.split('\n')[0]}`); failed++; }
await p5.close();
} catch (e) { steps.push(`✗ ${e.message.split('\n')[0]}`); failed++; }
// headed: a load out of the app (a page that opts out), then Back: the swapped document from the
// back/forward cache, as it was, or a load of that entry; either is right, which one is reported
Expand All @@ -543,4 +621,5 @@ for (const name of browsers) {
await browser.close();
}
server.close();
other.close();
process.exit(failed ? 1 : 0);
4 changes: 2 additions & 2 deletions src/links.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,8 +41,8 @@ export const api = (): Nav | undefined => {
return g.NavigateEvent && 'sourceElement' in g.NavigateEvent.prototype ? g.navigation : undefined;
};
const none = () => {};
/** what a `navigate()` call hands its event: the element of its handler */
const INFO = Symbol('sinter.trigger');
/** what a `navigate()` call hands its event: the element of its handler (the swap's own navigations hand on the link's) */
export const INFO = Symbol('sinter.trigger');
/**
* `to`: a link to another site whose click the guards were asked about already (navigate.ts): its event asks
* none; `last`: the latest `navigate` event (the swap tells a history write from a navigation by it)
Expand Down
19 changes: 18 additions & 1 deletion src/swap-run.ts
Original file line number Diff line number Diff line change
Expand Up @@ -388,8 +388,17 @@ export async function prepare(s: SwapState, i: Intent, signal?: AbortSignal): Pr
let page: PageModule | undefined;
g[SWAPPING] = (g[SWAPPING] ?? 0) + 1;
const pre: Element[] = [];
// another origin's module scripts (analytics, a widget, what a CDN injects): not the app's, so the swap neither
// waits for them nor fails with them (blocked by an extension, offline); they run after the commit as a load runs
// them, through elements, with their `integrity` and `crossorigin` (an `import()` would ignore both)
const foreign: HTMLScriptElement[] = [];
try {
const urls = [...doc.querySelectorAll('script[type=module][src]')].filter(trusted).map((x) => new URL(x.getAttribute('src')!, final).href);
const urls: string[] = [];
for (const x of [...doc.querySelectorAll<HTMLScriptElement>('script[type=module][src]')].filter(trusted)) {
const u = new URL(x.getAttribute('src')!, final);
if (u.origin == final.origin) urls.push(u.href);
else foreign.push(x);
}
// a helper module the page shares with its early file, which a swap does not run: the page module waits for the
// module's own copy, so it loads beside it (docs/first-paint.md#own-copies); the page module reports a failure.
// Fetched, not run (a module preload): the page module runs it after its dictionary file, which a message the
Expand Down Expand Up @@ -483,6 +492,14 @@ export async function prepare(s: SwapState, i: Intent, signal?: AbortSignal): Pr
// Forward, for the resources that come back as they were left (cache.ts): the document's own navigation type is its first load's
(globalThis as any)[Symbol.for('sinter.traverse')] = i.kind == 'traverse';
booted = page!.boot?.();
// each run once per document, as the app's modules are (a URL the document already ran does not run again)
for (const x of foreign) {
const live = document.createElement('script');
for (const a of x.attributes) live.setAttribute(a.name, a.name == 'src' ? new URL(a.value, final).href : a.value);
// (the nonce is not always copied with the attribute: as for the stylesheets in `heads`)
if (x.nonce) live.nonce = x.nonce;
x.isConnected ? x.replaceWith(live) : document.head.append(live);
}
s.bare = !page!.boot;
};
type VT = { updateCallbackDone: Promise<void>; ready: Promise<void>; finished: Promise<void> };
Expand Down
14 changes: 11 additions & 3 deletions src/swap.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
// `navigate` event, and loads the rest (swap-run.ts) when a navigation needs it. Where the browser has no
// Navigation API, or one without `sourceElement` (Chromium 102 to 134, links.ts), it does nothing: every navigation
// stays a page load.
import { RANK, api, ask, asked, chain } from './links.js';
import { INFO, RANK, api, ask, asked, chain } from './links.js';
import type { App, Feature, Intent } from './runtime/app.js';
import { segments, segsMatch } from './runtime/url.js';

Expand Down Expand Up @@ -103,6 +103,14 @@ export function swap(list: SwapPage[]): Feature {
if (i.trigger?.matches('[data-sn-swap=off]') || (i.kind == 'traverse' && u.pathname == s.shown)) return;
// only to a page the build lists: any other URL is the browser's, requested once
if (!pageAt(s.list, u.pathname)) return;
// the navigation again (a load, or the swap taking on what it fetched): with the link that started it, which
// the page's `pageswap` morphs from (transition.ts); `location.assign()` would hand on none
const go = (to: string) => {
const r = (nav() as unknown as { navigate(u: string, o: object): { committed?: Promise<unknown>; finished?: Promise<unknown> } })
.navigate(to, { history: i.kind == 'replace' ? 'replace' : 'push', info: { [INFO]: i.trigger } });
r.committed?.catch(() => {});
r.finished?.catch(() => {});
};
return {
name: 'swap',
run: () => {
Expand All @@ -122,7 +130,7 @@ export function swap(list: SwapPage[]): Feature {
else {
s.held = p && { to: i.to, c, p };
ask(i.to);
(nav() as unknown as { navigate(u: string, o: object): { finished?: Promise<unknown> } }).navigate(i.to, { history: i.kind == 'replace' ? 'replace' : 'push' }).finished?.catch(() => {});
go(i.to);
}
}));
// a load instead, once: before the URL committed, of the URL; after, a reload (its guards were asked)
Expand All @@ -131,7 +139,7 @@ export function swap(list: SwapPage[]): Feature {
setTimeout(() => {
if (location.href == u.href) return location.reload();
ask(u.href);
i.kind == 'replace' ? location.replace(u) : location.assign(u);
go(u.href);
});
throw Error('sinter: loaded instead');
};
Expand Down
Loading