Search / tests /search /reader-navigation /test_reader_navigation_baseline.mjs
vomebook
Consolidate Reader and search ownership on the live source
aeb21e9
Raw History Blame Contribute Delete
30.8 kB
// Synthetic contracts for the existing search-host navigation module. These
// cover URL/session rules and DOM ownership with a synthetic shell. Real browser
// traversal, layout, speech and native navigation remain browser-test contracts.
import assert from 'node:assert/strict';
import fs from 'node:fs';
import path from 'node:path';
import test from 'node:test';
import vm from 'node:vm';
const filename = path.join(process.cwd(), 'static/search/reader-host/application/navigation.js');
const source = fs.readFileSync(filename, 'utf8');
const contract = fs.readFileSync('static/reader/core/reader-contract.js', 'utf8');
const origin = 'https://search.example';
const readerPath = '/search/static/reader.html';
function fixture(readerDestination = readerPath, document = {readyState: 'loading', addEventListener() {}}, options) {
const data = new Map();
const calls = [], ticks = [];
let now = 1000;
const storage = {
getItem(key) { return data.has(key) ? data.get(key) : null; },
setItem(key, value) { data.set(key, String(value)); },
removeItem(key) { data.delete(key); }
};
const root = new EventTarget();
const location = new URL(origin + '/search/#/');
const crypto = {randomUUID: () => 'fixed-token'};
const history = {
state: null,
pushState(...args) { calls.push(['push', ...args]); history.state = args[0]; location.href = args[2]; },
replaceState(...args) { calls.push(['replace', ...args]); history.state = args[0]; location.href = args[2]; }
};
// Supply location and storage through the global as in browsers. Unrelated
// DOM and asynchronous Reader services remain intentionally unstubbed.
const context = vm.createContext({self: root, window: root, document, sessionStorage: storage,
localStorage: storage, location, URL, URLSearchParams,
crypto, history, console, HTMLElement: ShellElement, Event, CustomEvent,
Date: {now: () => now}, setInterval: fn => ticks.push(fn), clearInterval() {}});
vm.runInContext(contract, context, {filename: 'reader-contract.js'});
vm.runInContext(source, context, {filename});
return {nav: root.VoiceOfMLReaderNavigation.createNavigation(readerDestination, options), data, storage, crypto, calls, context, location,
tick(ms) {now += ms; ticks.at(-1)?.();}};
}
test('speech frame payload is consumed once and foreign names are left intact', () => {
const {context} = fixture();
const {speechHandoff} = context.self.VoiceOfMLReader;
const settings = {rate: 1.3, timer: 'off', deadline: 0};
for (const target of [{pending: true, settings}, {unit: 7, offset: 22, settings}]) {
const frame = {name: speechHandoff.frameName(target)};
assert.deepEqual(JSON.parse(speechHandoff.takeFramePayload(frame)), target);
assert.equal(frame.name, '');
assert.equal(speechHandoff.takeFramePayload(frame), '');
}
const foreign = {name: 'other-frame-name'};
assert.equal(speechHandoff.takeFramePayload(foreign), '');
assert.equal(foreign.name, 'other-frame-name');
});
const json = value => JSON.parse(JSON.stringify(value));
// Deliberately small DOM double: events run synchronously so dispose reentry is
// observable. It does not simulate layout, iframe loading or browser history.
class ShellElement extends EventTarget {
constructor(document, tagName) {
super();
this.document = document;
this.tagName = tagName;
this.children = [];
this.attributes = new Map();
this.styles = new Map();
this.style = {
setProperty: (key, value) => this.styles.set(key, value),
removeProperty: key => this.styles.delete(key)
};
const classes = new Set();
this.classList = {
add: value => classes.add(value), remove: value => classes.delete(value),
contains: value => classes.has(value)
};
if (tagName === 'iframe') {
this.contentWindow = new EventTarget();
this.contentWindow.postMessage = () => {};
this.contentDocument = {title: 'VoiceOfML Reader', URL: 'about:blank', querySelector: () => null};
}
}
append(...children) {
for (const child of children) { child.parent = this; this.children.push(child); }
}
replaceChildren(...children) {
for (const child of [...this.children]) child.remove();
this.append(...children);
}
remove() {
if (this.parent) this.parent.children = this.parent.children.filter(child => child !== this);
this.parent = null;
}
focus() { this.document.activeElement = this; }
setAttribute(key, value) { this.attributes.set(key, value); }
getAttribute(key) { return this.attributes.get(key) ?? null; }
hasAttribute(key) { return this.attributes.has(key); }
removeAttribute(key) { this.attributes.delete(key); }
}
function shellFixture(destination = readerPath, options) {
const document = Object.assign(new EventTarget(), {readyState: 'loading', title: 'Search'});
document.createElement = tag => new ShellElement(document, tag);
document.body = document.createElement('body');
const input = document.createElement('input');
document.body.append(input);
input.focus();
const state = fixture(destination, document, options);
return {...state, document, input,
shell: () => document.body.children.find(child => child.className === 'reader-overlay-opening'),
mini: () => document.body.children.find(child => child.className === 'reader-speech-mini')};
}
function parkSpeakingReader(nav, url) {
const frame = nav.mount(url);
frame.contentDocument.URL = frame.src;
frame.dispatchEvent(new Event('load'));
let reveals = 0;
frame.contentWindow.CCRDSpeech = {state: () => ({active: true}), reveal: () => reveals++};
nav.unmount();
assert.equal(nav.backgroundReader, frame);
return {frame, reveals: () => reveals};
}
test('parked reuse keeps the new navigation identity through replacement and recovery', () => {
const {nav, context, input, shell} = shellFixture();
const first = new URL(origin + readerPath + '?id=book&nav=old&return=%2Fold');
const parked = parkSpeakingReader(nav, first);
const resumes = [];
parked.frame.contentWindow.addEventListener('voice-reader-overlay-resume', () => {
resumes.push({url: nav.readerUrl, inert: parked.frame.hasAttribute('inert')});
});
input.focus();
const fresh = new URL(origin + readerPath + '?id=book&nav=new&return=%2Fsearch%2F%3Fq%3Dlatest');
assert.equal(nav.mount(fresh, true), parked.frame);
assert.deepEqual(resumes, [{url: fresh.href, inert: false}]);
assert.equal(nav.readerUrl, fresh.href);
assert.equal(nav.reusedMount, true);
assert.equal(nav.returnFocus, input);
assert.equal(parked.reveals(), 1);
nav.remember(fresh, {});
nav.dismiss();
nav.showCloseRecovery('/search/?q=latest');
const link = shell().children[1];
link.dispatchEvent(new Event('click'));
assert.equal(JSON.parse(context.sessionStorage.getItem('reader-navigation-restore')).readerUrl, fresh.href);
const next = nav.replace(readerPath + '?id=next', {});
const nextUrl = new URL(next.src);
assert.equal(nextUrl.searchParams.get('nav'), 'new');
assert.equal(nextUrl.searchParams.get('return'), '/search/?q=latest');
assert.equal(nav.returnFocus, input);
assert.equal(nav.reusedMount, false);
assert.equal(nav.readerUrl, next.src);
assert.equal(context.history.state.searchUrl, origin + '/search/#/');
nav.unmount(false);
});
test('ordinary frames expose a changed src and replacement rejects unowned history', () => {
const {nav, context, location} = shellFixture();
const frame = nav.mount(new URL(origin + readerPath + '?id=ordinary&nav=original'));
nav.remember(new URL(frame.src), {});
frame.src = origin + readerPath + '?id=ordinary&nav=updated&return=%2Fsearch%2F%3Fq%3Dchanged';
assert.equal(nav.reusedMount, false);
assert.equal(nav.readerUrl, frame.src);
// The visible address no longer matches the history entry: do not trust it.
location.hash = '#unrelated';
const next = nav.replace(readerPath + '?id=next', {});
assert.equal(new URL(next.src).searchParams.get('nav'), 'updated');
assert.equal(new URL(next.src).searchParams.get('return'), '/search/?q=changed');
assert.equal(context.history.state.searchUrl, null);
nav.unmount(false);
});
test('explicit fragment and bookmark opens bypass parked reuse without stopping speech', () => {
for (const target of ['#chapter%202', '&bookmark=saved&bookmark_source=https%3A%2F%2Ffiles.example%2Fbook.md']) {
const {nav, document, mini} = shellFixture();
const ordinary = nav.parse(readerPath + '?id=book&ext=md');
const url = nav.parse(ordinary.href + target);
const parked = parkSpeakingReader(nav, url);
const bar = mini();
// Even the identical opening URL is a fresh request when it comes from a link.
const next = nav.mount(url);
assert.notEqual(next, parked.frame);
assert.equal(next.src, url.href);
assert.equal(parked.reveals(), 0);
assert.equal(nav.backgroundReader, parked.frame);
assert.equal(parked.frame.parent, document.body);
assert.equal(mini(), bar);
nav.unmount(false);
assert.equal(nav.mount(ordinary), parked.frame);
assert.equal(parked.reveals(), 1);
assert.equal(nav.backgroundReader, null);
assert.equal(mini(), undefined);
nav.unmount(false);
}
});
test('mini-player resumes the live Reader even when its iframe src contains opening targets', () => {
let resumed;
const resume = raw => {
const url = nav.prepare(raw, '/search/#/?q=book');
resumed = nav.mount(url, true);
nav.remember(url, {});
};
const {nav, mini, calls} = shellFixture(readerPath, {resume});
const ordinary = nav.parse(readerPath + '?id=book&ext=md&title=Book');
const url = nav.parse(ordinary.href + '&bookmark=saved&bookmark_source=source#opening');
const parked = parkSpeakingReader(nav, url);
mini().children.find(child => child.className === 'reader-speech-mini-back').dispatchEvent(new Event('click'));
assert.equal(resumed, parked.frame);
assert.equal(parked.reveals(), 1);
assert.equal(parked.frame.src, url.href, 'resuming must not reload the live iframe');
assert.equal(calls[0][3], ordinary.href, 'mini-player history must not carry stale position requests');
assert.equal(nav.backgroundReader, null);
assert.equal(mini(), undefined);
nav.unmount(false);
});
test('pending background handoff survives opening another book and reopening the same frame', () => {
const {nav, storage, document, mini, tick} = shellFixture();
const url = nav.parse(readerPath + '?id=book');
storage.setItem('reader-speech-handoff', JSON.stringify({readerUrl:url.href,pending:true,at:1000}));
document.dispatchEvent(new Event('DOMContentLoaded'));
const pending = nav.backgroundReader;
assert.ok(pending);
assert.match(mini().children[0].textContent, /正在恢复朗读/);
const other = nav.mount(nav.parse(readerPath + '?id=other'));
assert.notEqual(other, pending);
assert.equal(nav.backgroundReader, pending);
nav.unmount(false);
assert.equal(nav.mount(url), pending);
nav.unmount();
assert.equal(nav.backgroundReader, pending);
tick(1000);
assert.equal(nav.backgroundReader, pending);
tick(300000);
assert.equal(nav.backgroundReader, null);
});
test('handoff accepts an exact cursor and can be dismissed while still starting', () => {
const {nav, storage, document, mini} = shellFixture();
const url = nav.parse(readerPath + '?id=old&nav=private&return=%2Fsearch%2F');
storage.setItem('reader-speech-handoff', JSON.stringify({readerUrl:url.href,unit:17,offset:22,at:1000}));
document.dispatchEvent(new Event('DOMContentLoaded'));
const frame = nav.backgroundReader;
assert.ok(frame);
assert.equal(new URL(frame.src).searchParams.has('nav'), false);
assert.ok(frame.name.startsWith('reader-speech-resume:'));
assert.deepEqual(JSON.parse(frame.name.slice('reader-speech-resume:'.length)), {unit:17,offset:22});
mini().children.at(-1).dispatchEvent(new Event('click'));
assert.equal(nav.backgroundReader, null);
assert.equal(frame.parent, null);
});
test('handoff ignores expired and foreign navigation targets', () => {
for (const target of [
{readerUrl:origin+readerPath,at:-300000},
{readerUrl:'https://other.example'+readerPath,at:1000},
{readerUrl:origin+readerPath,at:1000,settings:{deadline:999}},
]) {
const {nav, storage, document, mini} = shellFixture();
storage.setItem('reader-speech-handoff',JSON.stringify(target));
document.dispatchEvent(new Event('DOMContentLoaded'));
assert.equal(nav.backgroundReader,null);
assert.equal(mini(),undefined);
assert.equal(storage.getItem('reader-speech-handoff'),null);
}
});
test('a targeted Reader replacement keeps parked speech until the new Reader starts speaking', () => {
const {nav, context} = shellFixture();
const raw = readerPath + '?url=https%3A%2F%2Ffiles.example%2Fbook.md&ext=md';
const parked = parkSpeakingReader(nav, nav.parse(raw));
nav.mount(nav.parse(readerPath + '?id=other&nav=token'));
const next = nav.replace(raw + '#heading', {});
assert.notEqual(next, parked.frame);
const url = new URL(next.src);
assert.equal(url.hash, '#heading');
assert.equal(url.searchParams.get('nav'), 'token');
assert.equal(parked.reveals(), 0);
assert.equal(nav.backgroundReader, parked.frame);
const message = new Event('message');
Object.assign(message, {origin, source: next.contentWindow, data: {type: 'voice-reader-speech-start'}});
context.window.dispatchEvent(message);
assert.equal(nav.backgroundReader, null);
assert.equal(parked.frame.parent, null);
nav.unmount(false);
});
test('deferred titles survive failed history and release only for the requested URL', () => {
const {nav, document, context} = shellFixture();
const url = new URL(origin + readerPath + '?id=book&title=Filename&nav=new');
const frame = nav.mount(url, true);
assert.equal(document.title, 'Search');
assert.equal(frame.title, 'Filename');
const push = context.history.pushState;
context.history.pushState = () => { throw new Error('push failed'); };
assert.throws(() => nav.remember(url, {}), /push failed/);
frame.contentDocument = {URL: url.href, title: 'Loaded title'};
frame.dispatchEvent(new Event('load'));
assert.equal(frame.title, 'Loaded title');
assert.equal(document.title, 'Search');
const message = new Event('message');
Object.assign(message, {origin, source: frame.contentWindow, data: {type: 'voice-reader-title', title: 'Resolved title'}});
context.window.dispatchEvent(message);
assert.equal(frame.title, 'Resolved title');
assert.equal(document.title, 'Search', 'messages cannot bypass a failed history write');
context.history.pushState = push;
nav.remember(new URL(origin + readerPath + '?id=other'), {});
assert.equal(document.title, 'Search', 'an unrelated history write cannot release the pending title');
nav.remember(url, {});
assert.equal(document.title, 'Resolved title');
nav.dismiss();
document.title = 'Browser traversal title';
nav.unmount(false);
assert.equal(document.title, 'Search', 'dismiss retains the original title for post-traversal unmount');
});
test('history reentry cannot release a newer mount of the same URL', () => {
const {nav, document, context} = shellFixture();
const url = new URL(origin + readerPath + '?id=book&title=Book');
nav.mount(url, true);
const push = context.history.pushState;
context.history.pushState = (...args) => {
push(...args);
nav.mount(url, true);
};
nav.remember(url, {});
assert.equal(document.title, 'Search');
context.history.pushState = push;
nav.remember(url, {});
assert.equal(document.title, 'Book');
nav.unmount(false);
});
test('direct mount yields to disposal reentry and keeps the newer title', () => {
const {nav, document} = shellFixture();
const first = nav.mount(new URL(origin + readerPath + '?id=first&title=First'));
let newest;
first.contentWindow.addEventListener('voice-reader-dispose', () => {
newest = nav.mount(new URL(origin + readerPath + '?id=newest&title=Newest'));
});
const result = nav.mount(new URL(origin + readerPath + '?id=stale&title=Stale'), true);
assert.equal(result, newest);
assert.equal(document.title, 'Newest');
assert.equal(document.body.children.filter(child => child.tagName === 'iframe').length, 1);
nav.unmount(false);
assert.equal(document.title, 'Search');
});
test('close during disposal cancels the in-flight mount even after frame ownership is released', () => {
const {nav, document, input} = shellFixture();
const first = nav.mount(new URL(origin + readerPath + '?id=first&title=First'));
first.contentWindow.addEventListener('voice-reader-dispose', () => {
assert.equal(nav.unmount(false), null);
});
const result = nav.mount(new URL(origin + readerPath + '?id=cancelled&title=Cancelled'), true);
assert.equal(result, null);
assert.equal(document.body.children.filter(child => child.tagName === 'iframe').length, 0);
assert.equal(document.body.classList.contains('reader-overlay-open'), false);
assert.equal(input.hasAttribute('inert'), false);
assert.equal(input.hasAttribute('aria-hidden'), false);
assert.equal(document.title, 'Search');
assert.equal(nav.returnFocus, null);
assert.equal(nav.backgroundReader, null);
});
test('replacement and history restoration publish titles without a deferred push', () => {
const {nav, document} = shellFixture();
nav.mount(new URL(origin + readerPath + '?id=first&title=First'));
assert.equal(document.title, 'First');
nav.replace(readerPath + '?id=second&title=Second', {});
assert.equal(document.title, 'Second');
nav.replace(readerPath + '?id=third&title=Third', {});
assert.equal(document.title, 'Third');
nav.unmount(false);
assert.equal(document.title, 'Search');
});
test('replacement revision preserves a Reader opened synchronously during disposal', () => {
const {nav, document, input} = shellFixture();
const first = nav.mount(new URL(origin + readerPath + '?id=first&nav=token&return=%2Fsearch%2F'));
assert.equal(nav.returnFocus, input);
assert.equal(nav.backgroundReader, null);
let newest;
first.contentWindow.addEventListener('voice-reader-dispose', () => {
newest = nav.mount(new URL(origin + readerPath + '?id=newest'));
});
const result = nav.replace(readerPath + '?id=stale', {top: 50});
assert.equal(result, newest, 'outer replacement must yield to the reentrant mount');
assert.equal(first.parent, null);
assert.equal(first.src, 'about:blank');
assert.equal(document.body.children.filter(child => child.tagName === 'iframe').length, 1);
assert.equal(nav.accepts({origin, source: newest.contentWindow}), true);
assert.equal(nav.accepts({origin: 'https://other.example', source: newest.contentWindow}), false);
assert.equal(nav.accepts({origin, source: {frameElement: newest}}), true);
assert.equal(nav.accepts({origin, source: null}), false);
assert.equal(nav.accepts({origin, source: {get frameElement() { throw new Error('cross-origin'); }}}), false);
assert.equal(nav.accepts({origin, source: first.contentWindow}), false);
nav.unmount(false);
assert.equal(nav.returnFocus, null);
assert.equal(nav.unmount(), null);
});
test('ordinary replacement carries handoff and focus while releasing background ownership', () => {
const {nav, document, input, data} = shellFixture();
const hidden = document.createElement('aside');
hidden.setAttribute('inert', '');
hidden.setAttribute('aria-hidden', 'false');
document.body.append(hidden);
const first = nav.mount(new URL(origin + readerPath + '?id=first&nav=token&return=%2Fsearch%2F'));
const next = nav.replace(readerPath + '?id=next', {top: 50});
assert.notEqual(next, first);
assert.equal(new URL(next.src).searchParams.get('nav'), 'token');
assert.equal(new URL(next.src).searchParams.get('return'), '/search/');
assert.equal(JSON.parse(data.get('reader-navigation-current')).readerUrl, next.src);
assert.equal(nav.returnFocus, input);
assert.equal(nav.unmount(false), input);
assert.equal(input.hasAttribute('inert'), false);
assert.equal(input.hasAttribute('aria-hidden'), false);
assert.equal(hidden.hasAttribute('inert'), true);
assert.equal(hidden.getAttribute('aria-hidden'), 'false');
});
test('close recovery validates both search routes without changing history or private handoff', () => {
for (const destination of [readerPath, '/static/reader.html']) {
const {nav, document, input, shell, data, calls} = shellFixture(destination);
const search = destination === readerPath ? '/search/' : '/';
nav.showCloseRecovery(search);
assert.equal(shell(), undefined, 'no recovery without an active Reader');
const url = nav.prepare(destination + '?id=book&title=Book', origin + search);
nav.mount(url);
nav.remember(url, {top: 50});
const saved = data.get('reader-navigation-current');
nav.showCloseRecovery(search);
assert.equal(shell().children.some(child => child.tagName === 'a'), false, 'no recovery before close');
nav.dismiss();
assert.equal(document.title, 'Search');
const valid = destination === readerPath ? '/search/#/Repo?q=book' : '/Repo?q=book';
for (const [raw, expected] of [
[valid, valid], ['https://other.example/', search], ['javascript:alert(1)', search],
['/static/reader.html', search], ['/elsewhere/page', search], ['http://[', search],
['https://user:password@search.example' + search, search]
]) {
nav.showCloseRecovery(raw);
const link = shell().children.find(child => child.tagName === 'a');
assert.equal(link.href, origin + expected);
assert.equal(shell().parent, document.body);
assert.equal(shell().hasAttribute('inert'), false);
assert.equal(shell().styles.has('opacity'), false);
assert.equal(shell().styles.has('pointer-events'), false);
assert.equal(document.activeElement, link);
assert.equal(input.hasAttribute('inert'), true);
}
assert.equal(calls.length, 1, 'recovery must not push or replace history');
assert.equal(data.get('reader-navigation-current'), saved);
assert.equal(data.has('reader-navigation-restore'), false, 'handoff waits for explicit activation');
assert.equal(nav.returnFocus, input);
nav.unmount(false);
assert.equal(shell(), undefined);
}
});
test('recovery survives late shell load and records handoff only on native link activation', () => {
const {nav, document, shell, data, calls, storage} = shellFixture();
const target = origin + '/search/#/?q=book';
const url = nav.prepare(readerPath + '?id=book', target);
const frame = nav.mount(url);
frame.contentDocument.URL = frame.src;
frame.dispatchEvent(new Event('load'));
assert.equal(shell(), undefined);
nav.dismiss();
nav.showCloseRecovery(target);
const recovery = shell();
const link = recovery.children.find(child => child.tagName === 'a');
frame.dispatchEvent(new Event('load'));
assert.equal(shell(), recovery);
assert.equal(document.activeElement, link);
const click = new Event('click', {cancelable: true});
link.dispatchEvent(click);
assert.equal(click.defaultPrevented, false, 'native href remains the navigation action');
assert.deepEqual(JSON.parse(data.get('reader-navigation-restore')), {readerUrl: url.href, returnUrl: target});
storage.setItem = () => { throw new Error('quota'); };
assert.doesNotThrow(() => link.dispatchEvent(new Event('click')));
assert.deepEqual(calls, []);
assert.equal(nav.unmount(false).tagName, 'input');
nav.showCloseRecovery(target);
assert.equal(shell(), undefined);
});
test('parse accepts only the same-origin reader pathname', () => {
const {nav} = fixture();
assert.equal(nav.parse(readerPath + '?title=a%20b#part').href,
origin + readerPath + '?title=a%20b#part');
for (const raw of ['https://other.example' + readerPath, '/reader.html', readerPath + '/extra'])
assert.throws(() => nav.parse(raw), {message: 'Invalid reader destination'});
assert.throws(() => nav.parse('http://['), {name: 'TypeError'});
});
test('ordinary query merging replaces only selected keys and keeps repeated values', () => {
const {nav} = fixture();
const original = new URL(origin + '/search/?keep=1&q=old&q=older&ext=pdf#section');
const source = new URLSearchParams('q=first&q=second&ext=txt&unused=x');
const result = nav.mergeSearchParams(original, source, {keys: ['q', 'ext', 'missing']});
assert.equal(result.href, origin + '/search/?keep=1&q=first&q=second&ext=txt#section');
assert.equal(original.href, origin + '/search/?keep=1&q=old&q=older&ext=pdf#section');
assert.equal(source.toString(), 'q=first&q=second&ext=txt&unused=x');
});
test('hash query merging preserves route and unrelated query components', () => {
const {nav} = fixture();
const result = nav.mergeSearchParams('/search/?outer=1#/Repo?path=dir%2Fone&q=old&folder=x',
'q=hello+world&q=two&folder=', {hashRoute: true, keys: ['q', 'folder', 'absent']});
assert.equal(result.pathname, '/search/');
assert.equal(result.search, '?outer=1');
assert.equal(result.hash, '#/Repo?path=dir%2Fone&q=hello+world&q=two&folder=');
assert.equal(nav.mergeSearchParams('/search/#/Repo?q=x', '',
{hashRoute: true, keys: ['q']}).hash, '#/Repo');
});
test('merge without selected keys preserves existing query and returns a new URL', () => {
const {nav} = fixture();
const target = new URL(origin + '/search/?a=1&a=2#/Repo?b=3');
const result = nav.mergeSearchParams(target, 'a=other');
assert.notEqual(result, target);
assert.equal(result.href, target.href);
});
test('prepare records the return location and removes the previous handoff', () => {
const {nav, data} = fixture();
const old = origin + readerPath + '?nav=old-token&ext=txt';
data.set('reader-return:old-token', origin + '/old');
data.set('reader-navigation-current', JSON.stringify({readerUrl: old}));
const url = nav.prepare(readerPath + '?url=book&nav=stale', '/search/#/Repo?path=a');
assert.equal(url.searchParams.get('return'), '/search/#/Repo?path=a');
assert.equal(url.searchParams.get('nav'), 'fixed-token');
assert.equal(data.get('reader-return:fixed-token'), origin + '/search/#/Repo?path=a');
assert.equal(data.has('reader-return:old-token'), false);
assert.equal(data.has('reader-navigation-current'), false);
});
test('prepare tolerates unavailable storage or token generation without skipping destination validation', () => {
for (const broken of ['storage', 'crypto']) {
const {nav, storage, crypto} = fixture();
if (broken === 'storage') storage.setItem = () => { throw new Error('storage unavailable'); };
else crypto.randomUUID = () => { throw new Error('crypto unavailable'); };
const url = nav.prepare(readerPath + '?ext=txt', '/search/#/');
assert.equal(url.searchParams.get('return'), '/search/#/');
assert.equal(url.searchParams.has('nav'), false);
assert.throws(() => nav.prepare('https://other.example' + readerPath, '/search/'),
{message: 'Invalid reader destination'});
}
});
test('remember stores a private reader URL but exposes a sanitized history URL', () => {
const {nav, data, calls, location} = fixture();
const searchUrl = location.href;
const url = new URL(origin + readerPath + '?url=book&return=%2Fsearch%2F&nav=secret&ext=txt');
const scroll = {top: 125, key: 'entry'};
nav.remember(url, scroll);
nav.remember(url, scroll, true);
const share = origin + readerPath + '?url=book&ext=txt';
assert.deepEqual(json(nav.saved()), {shareUrl: share, readerUrl: url.href, returnScroll: scroll});
assert.equal(data.has('reader-navigation-current'), true);
assert.deepEqual(json(calls), [
['push', {voiceReaderOverlay: true, readerUrl: url.href, searchUrl}, '', share],
['replace', {voiceReaderOverlay: true, readerUrl: url.href, searchUrl}, '', share]
]);
assert.equal(url.searchParams.get('nav'), 'secret');
});
test('remember still updates history when storage fails and saved rejects malformed JSON', () => {
const {nav, data, storage, calls} = fixture();
data.set('reader-navigation-current', '{not-json');
assert.equal(nav.saved(), null);
// Valid JSON is returned verbatim; it is not guaranteed to be our record.
for (const value of [true, 17, 'text', ['item'], {readerUrl: 23}]) {
data.set('reader-navigation-current', JSON.stringify(value));
assert.deepEqual(json(nav.saved()), value);
}
storage.setItem = () => { throw new Error('quota'); };
const url = new URL(origin + readerPath + '?nav=secret');
nav.remember(url, {top: 2});
assert.equal(calls.length, 1);
assert.equal(calls[0][0], 'push');
assert.equal(calls[0][3], origin + readerPath);
});
test('clear removes only the matching session and selected return token', () => {
const {nav, data} = fixture();
const current = new URL(origin + readerPath + '?nav=current');
const other = new URL(origin + readerPath + '?nav=other');
data.set('reader-navigation-current', JSON.stringify({readerUrl: current.href}));
data.set('reader-return:current', 'current');
data.set('reader-return:other', 'other');
nav.clear(other);
assert.equal(data.has('reader-return:other'), false);
assert.equal(data.has('reader-navigation-current'), true);
nav.clear(current);
assert.equal(data.has('reader-return:current'), false);
assert.equal(data.has('reader-navigation-current'), false);
});
test('messages are rejected when no reader iframe is active', () => {
const {nav} = fixture();
assert.equal(nav.accepts({origin, source: {}}), false);
assert.equal(nav.accepts({origin: 'https://other.example', source: null}), false);
});
test('pathname and search parameter prototype overrides retain their original effects', () => {
const {nav, context} = fixture();
const path = Object.getOwnPropertyDescriptor(URL.prototype, 'pathname');
const get = URLSearchParams.prototype.get;
try {
Object.defineProperty(URL.prototype, 'pathname', {...path, get() { return undefined; }});
assert.throws(() => nav.parse(readerPath), {message: 'Invalid reader destination'});
Object.defineProperty(URL.prototype, 'pathname', path);
const result = nav.mergeSearchParams('/search/#/Repo?path=first', 'q=ok', {hashRoute:true, keys:['q']});
assert.equal(result.hash, '#/Repo?path=first&q=ok');
URLSearchParams.prototype.get = function() { return undefined; };
assert.equal(nav.prepare(readerPath, '/search/').searchParams.get('nav'), undefined);
vm.runInContext('String.prototype.split = function() { return []; }', context);
assert.match(nav.mergeSearchParams('/search/#/Repo', '', {hashRoute:true}).hash, /^#undefined/);
} finally {
Object.defineProperty(URL.prototype, 'pathname', path);
URLSearchParams.prototype.get = get;
}
});