vomebook commited on
Commit ·
abb4b1a
1
Parent(s): 7bd7f90
fix: restore Reader cache reuse and opening recovery
Browse filesKeep random selection responsive during asset refresh, retry owned PDF Workers, and add production opening benchmarks. Extract shared DOM search backend.
Files changed (17)
- app.py+7-3
- scripts/benchmark_reader_open.pyAdded+161
- scripts/check_reader_release.mjs+1
- scripts/reader-opening-media-samples.jsonAdded+4
- scripts/reader-opening-samples.jsonAdded+12
- static/app.js+25-2
- static/reader-dom-search.mjsAdded+414
- static/reader-resources.js+1
- static/reader.js+36-404
- static/sw.js+3-2
- tests/test_async_proxy.py+61
- tests/test_reader_architecture.js+10
- tests/test_reader_navigation_host.py+27-2
- tests/test_reader_optimizations.py+2-1
- tests/test_reader_pdf_loading.py+28-2
- tests/test_reader_refactor.py+29-7
- tests/test_static_contract.py+3-1
215 unmodified lines2162172182192202212221438 unmodified lines16611662166316641665166616671 unmodified line1669167016711672167316742 unmodified lines1677167816791680168116821683215 unmodified linesif len(chunks) > READER_ASSETS_MAX_COMPRESSED_BYTES:raise ValueError("reader assets response is too large")raw = bytes(chunks)decoded = decode_reader_assets(raw)v3_catalog = await load_reading_catalog(app.state.http_session)if v3_catalog is None and reader_assets_cache.get("v3"):raise ValueError("previously published v3 pointer disappeared")1438 unmodified linesawait ensure_reader_indexes_async()full_repo = f"VoiceOfML/{repo}" if repo else Noneoriginal = repo_reader_record_indices.get(full_repo, []) if full_repo else reader_record_indicesconverted = converted_reader_indices(await get_reader_assets(), full_repo)pool = dict.fromkeys(original)pool.update(dict.fromkeys(converted))return list(pool), converted1 unmodified line@app.get("/api/random-reader")async def api_random_reader(repo: Optional[str] = Query(default=None)):pool, converted = await get_reader_pool(repo)if not pool:return JSONResponse({"error": "无可读文档"}, status_code=404)2 unmodified linesasset = converted.get(index)if asset:rec = enrich_reader_record(rec, asset)return JSONResponse(rec)@app.get("/api/random-reader/status")async def api_random_reader_status(repo: Optional[str] = Query(default=None)):215 unmodified lines2162172182192202212221438 unmodified lines16611662166316641665166616671668166916701 unmodified line16721673167416751676167716782 unmodified lines1681168216831684168516861687215 unmodified linesif len(chunks) > READER_ASSETS_MAX_COMPRESSED_BYTES:raise ValueError("reader assets response is too large")raw = bytes(chunks)decoded = await asyncio.to_thread(decode_reader_assets, raw)v3_catalog = await load_reading_catalog(app.state.http_session)if v3_catalog is None and reader_assets_cache.get("v3"):raise ValueError("previously published v3 pointer disappeared")1438 unmodified linesawait ensure_reader_indexes_async()full_repo = f"VoiceOfML/{repo}" if repo else Noneoriginal = repo_reader_record_indices.get(full_repo, []) if full_repo else reader_record_indices# Random selection uses the complete last published snapshot while refresh# proceeds; a cold process must still await its first asset generation.assets = await get_reader_assets(wait=not bool(reader_assets_cache.get("f")))converted = converted_reader_indices(assets, full_repo)pool = dict.fromkeys(original)pool.update(dict.fromkeys(converted))return list(pool), converted1 unmodified line@app.get("/api/random-reader")async def api_random_reader(repo: Optional[str] = Query(default=None)):started = time.perf_counter()pool, converted = await get_reader_pool(repo)if not pool:return JSONResponse({"error": "无可读文档"}, status_code=404)2 unmodified linesasset = converted.get(index)if asset:rec = enrich_reader_record(rec, asset)return JSONResponse(rec, headers={"Server-Timing": f"reader_select;dur={(time.perf_counter() - started) * 1000:.2f}"})@app.get("/api/random-reader/status")async def api_random_reader_status(repo: Optional[str] = Query(default=None)):
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161"""Opt-in, read-only browser benchmark for pinned samples and random Reader opens."""import argparseimport jsonimport statisticsimport timefrom datetime import datetime, timezonefrom pathlib import Pathfrom urllib.parse import urlencode
from playwright.sync_api import sync_playwright
def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('--base-url', required=True) parser.add_argument('--path-prefix', default='') parser.add_argument('--samples', type=Path, required=True, help='JSON array of {name, params}: pinned Reader query parameters') parser.add_argument('--repeat', type=int, default=2) parser.add_argument('--random-attempts', type=int, default=0) parser.add_argument('--timeout', type=float, default=45) parser.add_argument('--browser', choices=['chromium', 'firefox'], default='chromium') parser.add_argument('--output', type=Path, required=True) parser.add_argument('--max-ready-seconds', type=float, help='Optional explicit acceptance budget; failures always exit nonzero') args = parser.parse_args() if args.repeat < 1 or args.timeout <= 0 or args.random_attempts < 0: parser.error('repeat/timeout must be positive and random-attempts nonnegative') samples = json.loads(args.samples.read_text()) if not isinstance(samples, list) or any(not isinstance(item, dict) or not isinstance(item.get('params'), dict) or not item.get('name') for item in samples): parser.error('samples must be an array of named Reader parameter objects') base = args.base_url.rstrip('/') prefix = args.path_prefix.rstrip('/') report = {'started_at': datetime.now(timezone.utc).isoformat(), 'base_url': base, 'path_prefix': prefix, 'samples': samples, 'timeout_seconds': args.timeout, 'cache_policy': 'default HTTP cache, active Service Worker, no routed requests', 'results': []} rows = report['results']
def save(): args.output.write_text(json.dumps(report, ensure_ascii=False, indent=2))
with sync_playwright() as playwright: browser = getattr(playwright, args.browser).launch(headless=True, args=['--no-sandbox'] if args.browser == 'chromium' else []) report['browser_engine'] = args.browser report['browser'] = browser.version context = browser.new_context(viewport={'width': 390, 'height': 844}) context.add_init_script('''window.__readerStages=[]; new MutationObserver(()=>{ const item={at:performance.now(),phase:document.documentElement.dataset.readerPhase, status:document.querySelector('#status')?.textContent}; const previous=__readerStages.at(-1); if(!previous||previous.phase!==item.phase||previous.status!==item.status) __readerStages.push(item); }).observe(document,{subtree:true,childList:true,attributes:true,characterData:true});''') page = context.new_page() page_errors = [] page.on('pageerror', lambda error: page_errors.append(str(error))) page.set_default_timeout(args.timeout * 1000) requests = {} cdp = context.new_cdp_session(page) if args.browser == 'chromium' else None if cdp: cdp.send('Network.enable')
def sent(event): requests[event['requestId']] = {'url': event['request']['url'], 'started': event['timestamp']}
def received(event): row = requests.get(event['requestId']) if row is not None: response = event['response'] row.update(status=response['status'], headers_ms=round((event['timestamp']-row['started'])*1000, 2), server_timing={k:v for k,v in response.get('headers', {}).items() if k.lower()=='server-timing'}, transport_timing=response.get('timing'), from_sw=response.get('fromServiceWorker', False))
def finished(event): row = requests.get(event['requestId']) if row is not None: row.update(total_ms=round((event['timestamp']-row['started'])*1000, 2), bytes=event.get('encodedDataLength'), error=event.get('errorText'))
if cdp: cdp.on('Network.requestWillBeSent', sent) cdp.on('Network.responseReceived', received) cdp.on('Network.loadingFinished', finished) cdp.on('Network.loadingFailed', finished)
def home(): page.goto(base + prefix + '/', wait_until='domcontentloaded') page.wait_for_function('()=>typeof navigateToReader==="function" && !!navigator.serviceWorker.controller') page.wait_for_timeout(2000)
try: home() selections = [('random', None, attempt) for attempt in range(args.random_attempts)] selections += [(item['name'], item['params'], attempt) for item in samples for attempt in range(args.repeat)] for name, params, attempt in selections: requests.clear() started = time.monotonic() row = {'sample': name, 'attempt': attempt} try: if params is None: page.evaluate('()=>{randomTxt();}') else: page.evaluate('url=>navigateToReader(url)', base + prefix + '/static/reader.html?' + urlencode(params)) overlay = page.locator('iframe.reader-overlay') overlay.wait_for() row['iframe_seconds'] = round(time.monotonic()-started, 3) frame = overlay.element_handle().content_frame() frame.locator('.reader-toolbar').wait_for() row['shell_seconds'] = round(time.monotonic()-started, 3) frame.wait_for_function('()=>["ready","failed"].includes(document.documentElement.dataset.readerPhase)') row['ready_seconds'] = round(time.monotonic()-started, 3) row.update(frame.evaluate(r'''()=>({phase:document.documentElement.dataset.readerPhase, error_code:document.querySelector('#content')?.dataset.errorCode, reader_mode:document.querySelector('#content')?.dataset.mode, stages:window.__readerStages, resources:performance.getEntriesByType('resource').map(e=>e.toJSON()), assets:performance.getEntriesByType('resource').filter(e=>/\.(js|mjs|css)(\?|$)/.test(e.name)).map(e=>e.name)})''')) if row['phase'] != 'ready': raise RuntimeError('Reader failed: ' + str(row.get('error_code'))) if row['reader_mode'] in ('audio', 'video'): frame.wait_for_function('()=>document.querySelector("audio,video")?.readyState>=1') row['media_metadata_seconds'] = round(time.monotonic()-started, 3) row['success'] = True frame.locator('#back').click() overlay.wait_for(state='detached') except Exception as error: row.update(success=False, error=str(error), elapsed_seconds=round(time.monotonic()-started, 3)) try: page.evaluate('()=>closeReaderOverlay()') except Exception: home() row['network'] = list(requests.values()) rows.append(row) print(json.dumps({k:v for k,v in row.items() if k not in ('network','stages','assets','resources')}, ensure_ascii=False), flush=True) save() page.wait_for_timeout(500) except Exception as error: row = {'sample': 'search-host', 'success': False, 'error': str(error), 'page_errors': page_errors, 'network': list(requests.values())} rows.append(row) print(json.dumps(row), flush=True) finally: context.close() browser.close() save() report['summary'] = {} for name in {row['sample'] for row in rows}: selected = [row for row in rows if row['sample'] == name] times = [max(row['ready_seconds'], row.get('media_metadata_seconds', 0)) for row in selected if row.get('success')] report['summary'][name] = {'runs': len(selected), 'failures': sum(not row.get('success') for row in selected), 'median_usable_seconds': statistics.median(times) if times else None, 'max_usable_seconds': max(times) if times else None} save() print(json.dumps(report['summary'], ensure_ascii=False), flush=True) return int(any(not row.get('success') or args.max_ready_seconds is not None and max(row.get('ready_seconds', float('inf')), row.get('media_metadata_seconds', 0)) > args.max_ready_seconds for row in rows))
if __name__ == '__main__': raise SystemExit(main())182 unmodified lines183184185186187188182 unmodified lines"reader-format-adapters.js","reader-security.js","reader-search-controller.mjs","pdf-worker-wrapper.mjs"];for (const file of exact) {182 unmodified lines183184185186187188189182 unmodified lines"reader-format-adapters.js","reader-security.js","reader-search-controller.mjs","reader-dom-search.mjs","pdf-worker-wrapper.mjs"];for (const file of exact) {
1234[ {"name":"audio","params":{"id":"1ec6ve775cplh","ext":"audio"}}, {"name":"video","params":{"id":"1fp4jdt5wxwvn","ext":"video"}}]123456789101112[ {"name":"txt","params":{"url":"https://voiceofml-search.hf.space/api/reader-bucket-resource?path=documents/text/txt/6a8f1ffa37c58eafd11734ae04c75ef2561439b83a8ca68245320b45bd26eb00/document.txt","ext":"txt"}}, {"name":"pdf","params":{"id":"3tp99trglsuw6","ext":"pdf"}}, {"name":"docx","params":{"url":"https://voiceofml-search.hf.space/api/reader-bucket-resource?path=documents/office/docx/6c0080103a21f936ea8e01d2bb93537c863785dd36fed04741362eb99844b497/document.docx","ext":"docx"}}, {"name":"audio","params":{"id":"1ec6ve775cplh","ext":"audio"}}, {"name":"markdown","params":{"url":"https://voiceofml-search.hf.space/api/reader-bucket-resource?path=documents/text/md/77672adf737a2f9bb3e0547f7ee3e3b3996ee18c7016585c6a79dea36accf893/document.md","ext":"md"}}, {"name":"html","params":{"url":"https://voiceofml-search.hf.space/api/reader-bucket-resource?path=documents/web/htm/31524242a3a0fa432962c4946172f4bd07988ed02d3884112a84c296a74cc8e6/document.html","ext":"html"}}, {"name":"image","params":{"url":"https://voiceofml-search.hf.space/api/reader-bucket-resource?path=pages/image/jpg/d93b5b88126534f90dfbcb8f76d352a5e39e7f0fac10a3afc1989687f9a4078f/page-manifest.json","ext":"image-pages"}}, {"name":"chm","params":{"url":"https://voiceofml-search.hf.space/api/reader-bucket-resource?path=chapters/ebook/chm/50016b251b2f92be5570573bfa56fcc933e82cffd79cf54bb3350a46086c9c00/b25a66805ef664c1/chapter-manifest.json","ext":"epub-chapters"}}, {"name":"ebook-chapters","params":{"url":"https://voiceofml-search.hf.space/api/reader-bucket-resource?path=chapters/ebook/epub/495ef4822508dd1aa36136721b5cda6fee073317f046c0798342bb0d39fccfba/c3f43269530c3fcb/chapter-manifest.json","ext":"epub-chapters"}}, {"name":"native-epub","params":{"url":"https://huggingface.co/datasets/VoiceOfML/VOMEBOOK/resolve/main/%E9%A9%AC%E5%88%97%E4%B9%8B%E5%A3%B0ebook%E5%B0%8F%E7%BB%84%E7%AC%AC%E4%B8%89%E6%89%B9%E6%88%90%E6%9E%9C%E9%9B%86%E6%88%90%E8%B5%9E%E5%8A%A9%E9%83%A8%E5%88%86/jiang2-%E8%B4%A1%E7%8C%AE/%E4%BC%8A%E6%96%AF-%E5%85%B0%E4%B8%8E%E4%B8%AD%E4%B8%9C%E9%97%AE%E9%A2%98%E7%A0%94%E7%A9%B6%E8%B5%84%E6%96%99%E9%9B%86%E6%88%90%EF%BC%88650%E4%BD%99%E7%A7%8D%EF%BC%89/%E4%BC%8A%E6%96%AF%E5%85%B0%E4%B8%8E%E4%B8%AD%E4%B8%9C%E9%97%AE%E9%A2%98%E7%A0%94%E7%A9%B6%E8%B5%84%E6%96%99%E9%9B%86%E6%88%90%EF%BC%88650%E4%BD%99%E7%A7%8D%EF%BC%89/%E4%BC%8A%E6%96%AF%E5%85%B0%E5%9B%BD%28ISIS%29%E7%A0%94%E7%A9%B6/Cockburn%2C%2BPatrick-The%2Brise%2Bof%2BIslamic%2Bstate%2B_%2BISIS%2Band%2Bthe%2Bnew%2BSunni%2Brevolution-Verso%2BBooks%2B%282015%29.epub","ext":"epub"}}]4877 unmodified lines4878487948804881488248837 unmodified lines48914892489348944895489648974898489949004901490249034877 unmodified lineslet randomReaderRequestId = 0;function openReaderRecord(rec, returnUrl = location.href) {if (!rec || location.href !== returnUrl) return false;const url = getReaderLink(rec, returnUrl);7 unmodified linestry {showToast("正在随机打开书籍...");const url = STATE.repo ? `/api/random-reader?repo=${encodeURIComponent(STATE.repo)}` : "/api/random-reader";const rec = await fetchJsonWithTimeout(url, 10000);if (!rec) throw new Error("随机阅读响应无效");if (requestId !== randomReaderRequestId || location.href !== returnUrl) return;if (!openReaderRecord(rec, returnUrl)) {showToast("暂无可读书籍");}} catch (e) {console.error(e);showToast("随机打开失败");}4877 unmodified lines48784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449057 unmodified lines491349144915491649174918491949204921492249234924492549264877 unmodified lineslet randomReaderRequestId = 0;async function fetchRandomReaderRecord(url, requestId, returnUrl) {for (let attempt = 0; attempt < 2; attempt++) {if (requestId !== randomReaderRequestId || location.href !== returnUrl) return null;const controller = new AbortController();const timer = setTimeout(() => controller.abort(), 10000);try {const response = await fetch(url, { signal: controller.signal, cache: "no-store" });if (!response.ok) {await response.body?.cancel();const error = new Error(`HTTP ${response.status}`);error.permanent = response.status < 500 && ![408, 429].includes(response.status);throw error;}return await response.json();} catch (error) {if (error.permanent || attempt || error instanceof SyntaxError || navigator.onLine === false) throw error;} finally {clearTimeout(timer);}}}function openReaderRecord(rec, returnUrl = location.href) {if (!rec || location.href !== returnUrl) return false;const url = getReaderLink(rec, returnUrl);7 unmodified linestry {showToast("正在随机打开书籍...");const url = STATE.repo ? `/api/random-reader?repo=${encodeURIComponent(STATE.repo)}` : "/api/random-reader";const rec = await fetchRandomReaderRecord(url, requestId, returnUrl);if (requestId !== randomReaderRequestId || location.href !== returnUrl) return;if (!rec) throw new Error("随机阅读响应无效");if (!openReaderRecord(rec, returnUrl)) {showToast("暂无可读书籍");}} catch (e) {if (requestId !== randomReaderRequestId || location.href !== returnUrl) return;console.error(e);showToast("随机打开失败");}
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414// DOM matching, text snapshots and marks share one Reader-owned lifecycle.export function fullSearchEscape(value) { return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");}
export function fullSearchSnippet(text, index, length) { const start = Math.max(0, index - 72), end = Math.min(text.length, index + length + 88); return { text: text.slice(start, end), matchStart: index - start, matchLength: length, prefix: start ? "…" : "", suffix: end < text.length ? "…" : "" };}
export function fullSearchPageOffset(total, requestedOffset, pageSize = 50) { return Math.max(0, Math.min( Math.floor(Math.max(0, total - 1) / pageSize), Math.floor(requestedOffset / pageSize) )) * pageSize;}
export function createReaderDomSearch({ content, runtime, isCurrent, yieldTask, getTocEntries, unwrapRoot, publishPage}) { let fullSearchActiveMarks = []; let fullSearchDomLocator = null; let fullSearchDomSnapshot = null; const DOM_SEARCH_SNAPSHOT_BYTES = 8 * 1024 * 1024; function createDomSearchSnapshot(root) { fullSearchDomSnapshot?.dispose(); let valid = true, disposed = false, value = null; const invalidate = () => { valid = false; value = null; }; const observer = new MutationObserver(invalidate); const current = () => { if (observer.takeRecords().length) invalidate(); return valid && !disposed; }; const resume = () => { if (!disposed) observer.observe(root, { subtree: true, childList: true, characterData: true, attributes: true, attributeFilter: ["class", "data-page"] }); }; const snapshot = { root, current, resume, get value() { return current() ? value : null; }, set(data) { if (!current()) return; if (data.offsets.length > 32768 || data.text.length * 2 + data.offsets.length * 64 > DOM_SEARCH_SNAPSHOT_BYTES) { snapshot.dispose(); return; } // Owned highlights replace text nodes but leave these parent boundaries intact. value = { ...data, offsets: data.offsets.map(({ parent, start, end }) => ({ parent, start, end })) }; }, pause() { current(); observer.disconnect(); }, dispose() { disposed = true; invalidate(); observer.disconnect(); } }; resume(); fullSearchDomSnapshot = snapshot; return snapshot; } const stopGeneration = runtime.events.on("generation", ({ name }) => { if (name === "search") { fullSearchDomLocator?.dispose(); fullSearchDomLocator = null; } }); function dispose() { stopGeneration(); fullSearchDomLocator?.dispose(); fullSearchDomLocator = null; fullSearchDomSnapshot?.dispose(); fullSearchDomSnapshot = null; fullSearchActiveMarks = []; } function createFullSearchDomLocator(root, generation) { fullSearchDomLocator?.dispose(); const checkpoints = []; let valid = true, disposed = false; const invalidate = () => { valid = false; checkpoints.length = 0; }; const observer = new MutationObserver(invalidate); const current = () => { if (observer.takeRecords().length) invalidate(); return valid && !disposed && isCurrent("search", generation); }; const resume = () => { if (!disposed) observer.observe(root, { subtree: true, childList: true, characterData: true, attributes: true, attributeFilter: ["class"] }); }; const locator = { current, boundaries() { return current() ? checkpoints.slice() : []; }, seed(boundaries) { if (current()) checkpoints.push(...boundaries); }, build(offsets) { if (!current()) return; const stride = Math.max(128, Math.ceil(offsets.length / 2048)); for (let index = 0; index < offsets.length && checkpoints.length < 2048;) { const { node, parent: target, start } = offsets[index]; // Element boundaries survive text splitting and normalization by our marks. if (target?.firstChild === node) { checkpoints.push({ target, start }); index += stride; } else index++; } }, checkpoint(offset) { if (!current()) return null; let low = 0, high = checkpoints.length; while (low < high) { const middle = (low + high) >> 1; if (checkpoints[middle].start <= offset) low = middle + 1; else high = middle; } const checkpoint = checkpoints[low - 1]; if (checkpoint && (!checkpoint.target.isConnected || !root.contains(checkpoint.target))) { invalidate(); return null; } return checkpoint || null; }, pause() { current(); observer.disconnect(); }, resume, dispose() { disposed = true; invalidate(); observer.disconnect(); } }; resume(); fullSearchDomLocator = locator; return locator; } function clearFullSearchMarks() { fullSearchDomLocator?.pause(); fullSearchDomSnapshot?.pause(); try { content.querySelectorAll(".reader-text-hit-box").forEach(node => node.remove()); const changedParents = new Set(); for (const mark of fullSearchActiveMarks) { if (mark.tagName === "MARK") { if (mark.parentNode) changedParents.add(mark.parentNode); mark.replaceWith(mark.textContent); } else mark.classList.remove("full-search-highlight"); } fullSearchActiveMarks = []; for (const parent of changedParents) parent.normalize(); content.querySelectorAll(".reader-chapter-search-heading").forEach(node => node.remove()); } finally { fullSearchDomLocator?.resume(); fullSearchDomSnapshot?.resume(); } } async function fullSearchTextNodes(root, generation, endOffset = Infinity, checkpoint = null, collect = null) { const nodes = [], walker = root.ownerDocument.createTreeWalker(root, NodeFilter.SHOW_TEXT); if (checkpoint) walker.currentNode = checkpoint.target; let visited = 0, length = checkpoint?.start || 0, deadline = performance.now() + 8; while (walker.nextNode()) { if (!isCurrent("search", generation)) return null; const node = walker.currentNode; if ( node.data && !node.parentElement.closest("script,style,mark.full-search-highlight,.reader-pdf-text") ) { if (collect) collect(node); else nodes.push(node); length += node.data.length; if (length >= endOffset) break; } if (++visited % 256 === 0 && performance.now() >= deadline) { await yieldTask(); deadline = performance.now() + 8; } } return nodes; } function highlightTextParts(parts) { fullSearchDomLocator?.pause(); fullSearchDomSnapshot?.pause(); const marks = []; try { for (const { node, start, end } of [...parts].reverse()) { node.splitText(end); const selected = node.splitText(start), mark = node.ownerDocument.createElement("mark"); mark.className = "full-search-highlight"; mark.textContent = selected.data; selected.replaceWith(mark); fullSearchActiveMarks.push(mark); marks.unshift(mark); } } finally { fullSearchDomLocator?.resume(); fullSearchDomSnapshot?.resume(); } return marks; }
function createFullSearchHeadingLookup(root, offsets) { const entries = getTocEntries(), boundaries = []; const headings = entries.filter(entry => entry.target); let previous = null; for (const entry of headings) { const target = entry.target; if (!target.isConnected || target.getRootNode() !== root.getRootNode() || (previous && previous !== target && !(previous.compareDocumentPosition(target) & Node.DOCUMENT_POSITION_FOLLOWING))) return null; previous = target; } const linear = headings.length * Math.ceil(Math.log2(offsets.length + 1)) > offsets.length; let cursor = 0; for (const entry of headings) { const target = entry.target; let low = 0, high = offsets.length; if (linear) { while (cursor < offsets.length && !(target.compareDocumentPosition(offsets[cursor].node) & Node.DOCUMENT_POSITION_FOLLOWING)) cursor++; low = cursor; } else { while (low < high) { const middle = (low + high) >> 1; if (target.compareDocumentPosition(offsets[middle].node) & Node.DOCUMENT_POSITION_FOLLOWING) high = middle; else low = middle + 1; } } boundaries.push({ start: offsets[low]?.start ?? Infinity, label: entry.label }); } return (offset) => { if (getTocEntries() !== entries) return null; let low = 0, high = boundaries.length; while (low < high) { const middle = (low + high) >> 1; if (boundaries[middle].start <= offset) low = middle + 1; else high = middle; } return { label: boundaries[low - 1]?.label }; }; } function fullSearchLocation(node, fallback, offset, total, headingLookup = null, parent = node.parentElement) { const page = parent && parent.closest("[data-page]"); if (page) return `第 ${page.dataset.page} 页`; const indexed = headingLookup?.(offset); if (indexed?.label !== undefined) return indexed.label; if (indexed) return `正文 ${Math.min(100, Math.floor(offset / Math.max(1, total) * 100))}%`; if (getTocEntries().length) { const heading = [...getTocEntries()].reverse().find(entry => entry.target && (entry.target === node.parentElement || !!(entry.target.compareDocumentPosition(node) & Node.DOCUMENT_POSITION_FOLLOWING))); if (heading) return heading.label; } return `正文 ${Math.min(100, Math.floor(offset / Math.max(1, total) * 100))}%`; } async function fullSearchDomMatches(root, fallback, query, generation, progressive = false, occurrence = null, navigationGeneration = runtime.currentGeneration("navigation")) { root = unwrapRoot(root); const cached = progressive && fullSearchDomSnapshot?.root === root && fullSearchDomSnapshot.value?.toc === getTocEntries() ? fullSearchDomSnapshot.value : null; const snapshot = progressive ? (cached ? fullSearchDomSnapshot : createDomSearchSnapshot(root)) : null; const locator = progressive ? createFullSearchDomLocator(root, generation) : null; const offsets = cached ? cached.offsets : [], chunks = []; let length = 0; const collect = node => { offsets.push({ node, parent: node.parentElement, start: length, end: length + node.data.length }); chunks.push(node.data); length += node.data.length; }; const nodes = cached ? [] : await fullSearchTextNodes(root, generation, Infinity, null, collect); if (!nodes || !isCurrent("search", generation)) return []; if (cached) locator?.seed(cached.checkpoints); else locator?.build(offsets); const headingLookup = cached ? cached.headingLookup : createFullSearchHeadingLookup(root, offsets); const text = cached ? cached.text : chunks.join(""), groups = [], firstHits = []; if (!cached && snapshot && (headingLookup || !getTocEntries().some(entry => entry.target))) snapshot.set({ text, offsets, headingLookup, checkpoints: locator.boundaries(), toc: getTocEntries() }); let highlightOffsets = offsets; const patternText = fullSearchEscape(query); let nextStart = 0, total = 0; const locateIndex = (index, parts = offsets) => { let low = 0, high = parts.length - 1; while (low < high) { const middle = (low + high) >> 1; if (parts[middle].end <= index) low = middle + 1; else high = middle; } return low; }; const partsFor = (start, end) => { const parts = []; for (let index = locateIndex(start, highlightOffsets); index < highlightOffsets.length && highlightOffsets[index].start < end; index++) parts.push(highlightOffsets[index]); return parts; }; const matchesIn = function* (group) { const re = new RegExp(patternText, "giu"); re.lastIndex = group.skip; for (const match of text.slice(group.start, group.end).matchAll(re)) { if (match.index >= 65536) break; yield { index: group.start + match.index, value: match[0] }; } }; const resultFor = (match) => { const part = offsets[locateIndex(match.index)]; return { location: fullSearchLocation(part.node || part.parent, fallback, match.index, text.length, headingLookup, part.parent), snippet: fullSearchSnippet(text, match.index, match.value.length), async activate(navigationGeneration = runtime.currentGeneration("navigation")) { if (!isCurrent("navigation", navigationGeneration)) return false; const searchGeneration = runtime.currentGeneration("search"); const end = match.index + match.value.length; clearFullSearchMarks(); let checkpoint = locator?.checkpoint(match.index); let currentNodes = await fullSearchTextNodes(root, searchGeneration, end, checkpoint); if (checkpoint && !locator.current()) { checkpoint = null; currentNodes = await fullSearchTextNodes(root, searchGeneration, end); } if (!currentNodes || !isCurrent("search", searchGeneration) || !isCurrent("navigation", navigationGeneration)) return false; let position = checkpoint?.start || 0, parts = []; for (const node of currentNodes) { const nodeEnd = position + node.data.length; if (nodeEnd > match.index && position < end) parts.push({ node, start: Math.max(0, match.index - position), end: Math.min(node.data.length, end - position) }); position = nodeEnd; if (position >= end) break; } if (parts.map(part => part.node.data.slice(part.start, part.end)).join("") !== match.value) return false; const [target] = highlightTextParts(parts); target?.scrollIntoView({ block: "center" }); return !!target; } }; }; const page = (requestedOffset) => { const pageSize = 50, results = []; const offset = fullSearchPageOffset(total, requestedOffset, pageSize); let passed = 0; for (const group of groups) { if (passed + group.count <= offset) { passed += group.count; continue; } for (const match of matchesIn(group)) { if (passed++ < offset) continue; results.push(resultFor(match)); if (results.length === pageSize) break; } if (results.length === pageSize) break; } return { total, offset, pageSize, results }; }; for (let start = 0; start < text.length; start += 65536) { const group = { start, end: start + 65536 + query.length - 1, skip: Math.max(0, nextStart - start), count: 0 }; for (const match of matchesIn(group)) { group.count++; nextStart = match.index + match.value.length; if (firstHits.length < 100) firstHits.push(match); } groups.push(group); total += group.count; if (progressive && (start === 0 || (group.count && total <= 50) || groups.length % 8 === 0)) { publishPage(page(0), page, true); } await yieldTask(); if (!isCurrent("search", generation)) return []; } if (progressive) { publishPage(page(0), page, false); } if (occurrence !== null) { if (!isCurrent("navigation", navigationGeneration)) return []; const matchedPage = page(occurrence); const result = matchedPage.results[occurrence - matchedPage.offset]; if (!result || !await result.activate(navigationGeneration)) return []; return [{ target: fullSearchActiveMarks[0] }]; } const fallbackResults = progressive ? null : firstHits.map(resultFor); if (cached && !snapshot.current()) return fullSearchDomMatches(root, fallback, query, generation, progressive, occurrence, navigationGeneration); if (cached && firstHits.length && navigationGeneration === runtime.currentGeneration("navigation")) { const checkpoint = locator.checkpoint(firstHits[0].index); const end = firstHits[firstHits.length - 1].index + firstHits[firstHits.length - 1].value.length; const markNodes = await fullSearchTextNodes(root, generation, end, checkpoint); if (!markNodes || !isCurrent("search", generation)) return []; if (!snapshot.current()) return fullSearchDomMatches(root, fallback, query, generation, progressive, occurrence, navigationGeneration); let position = checkpoint?.start || 0; highlightOffsets = markNodes.map(node => { const part = { node, start: position, end: position + node.data.length }; position = part.end; return part; }); } if (navigationGeneration === runtime.currentGeneration("navigation")) { for (let i = firstHits.length - 1; i >= 0; i--) { const match = firstHits[i], end = match.index + match.value.length; const parts = partsFor(match.index, end); if (!parts.length) continue; const [target] = highlightTextParts(parts.map(part => ({ node: part.node, start: Math.max(match.index, part.start) - part.start, end: Math.min(end, part.end) - part.start }))); if (fallbackResults) fallbackResults[i].target = target; } } return fallbackResults || page(0).results; } function pruneMarks() { fullSearchActiveMarks = fullSearchActiveMarks.filter(mark => mark.isConnected); } return Object.freeze({ search: fullSearchDomMatches, clearMarks: clearFullSearchMarks, highlight: highlightTextParts, pruneMarks, dispose });}100 unmodified lines101102103104105106100 unmodified lines"reader-format-adapters.js","reader-security.js","reader-search-controller.mjs","reader-pdf-text.js","reader-v3.mjs","reader-book-text.js",100 unmodified lines101102103104105106107100 unmodified lines"reader-format-adapters.js","reader-security.js","reader-search-controller.mjs","reader-dom-search.mjs","reader-pdf-text.js","reader-v3.mjs","reader-book-text.js",
123623 unmodified lines6276286296306316326335234 unmodified lines586858695870587158725873587458755876848 unmodified lines67256726672767286729673035 unmodified lines676667676768676967706771677267736774677567766777142 unmodified lines692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321import { createReaderSearchController } from "./reader-search-controller.mjs";import "/static/reader-resources.js";import "/static/reader-contract.js";623 unmodified linesconst pageState = shell.querySelector(".reader-page-state");if (pageState) setPdfPageLoadingState(pageState, shell.dataset.page);}fullSearchActiveMarks = fullSearchActiveMarks.filter(mark => mark.isConnected);}function clearPdfManifestPrefetches() {stopPdfManifestPrefetch();5234 unmodified linesreturn pdfEnginePreload;}async function preparePdfWorker(pdfjs) {assertReaderActive();if (capability.mode !== "pdf" && !pdfPrimarySource()) return pdfjs;pdfjs.GlobalWorkerOptions.workerSrc = PDFJS_WORKER_URL;const worker = new pdfjs.PDFWorker();pdfWorker = worker;let timer, destroyed = false;848 unmodified lineschapterNext.addEventListener("click", () =>activateChapter(adjacentTocIndex(1)));const fullSearchController = createReaderSearchController({document, runtime: readerRuntime, signal: readerAbortController.signal,nextGeneration: () => nextReaderGeneration("search"),35 unmodified linesstatus: fullSearchStatus} = fullSearchController.elements;// Format-specific search backends publish through the shared controller.function fullSearchPageOffset(total, requestedOffset, pageSize = 50) {return Math.max(0, Math.min(Math.floor(Math.max(0, total - 1) / pageSize),Math.floor(requestedOffset / pageSize))) * pageSize;}function chapterSearchModule() {if (!chapterSearchModulePromise)chapterSearchModulePromise = import("/static/reader-chapter-search.mjs").catch((error) => {142 unmodified linesfullSearchSession.page = { total, offset: 0, pageSize: 50, results: firstPage.slice() };return firstPage;}function fullSearchEscape(value) {return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");}let fullSearchActiveMarks = [];let fullSearchDomLocator = null;let fullSearchDomSnapshot = null;const DOM_SEARCH_SNAPSHOT_BYTES = 8 * 1024 * 1024;function createDomSearchSnapshot(root) {fullSearchDomSnapshot?.dispose();let valid = true, disposed = false, value = null;const invalidate = () => { valid = false; value = null; };const observer = new MutationObserver(invalidate);const current = () => {if (observer.takeRecords().length) invalidate();return valid && !disposed;};const resume = () => {if (!disposed) observer.observe(root, {subtree: true, childList: true, characterData: true,attributes: true, attributeFilter: ["class", "data-page"]});};const snapshot = {root, current, resume,get value() { return current() ? value : null; },set(data) {if (!current()) return;if (data.offsets.length > 32768 || data.text.length * 2 + data.offsets.length * 64 > DOM_SEARCH_SNAPSHOT_BYTES) {snapshot.dispose();return;}// Owned highlights replace text nodes but leave these parent boundaries intact.value = { ...data, offsets: data.offsets.map(({ parent, start, end }) => ({ parent, start, end })) };},pause() { current(); observer.disconnect(); },dispose() { disposed = true; invalidate(); observer.disconnect(); }};resume();fullSearchDomSnapshot = snapshot;return snapshot;}readerRuntime.events.on("generation", ({ name }) => {if (name === "search") {fullSearchDomLocator?.dispose();fullSearchDomLocator = null;}});trackReaderResource(() => {fullSearchDomLocator?.dispose();fullSearchDomLocator = null;fullSearchDomSnapshot?.dispose();fullSearchDomSnapshot = null;});function createFullSearchDomLocator(root, generation) {fullSearchDomLocator?.dispose();const checkpoints = [];let valid = true, disposed = false;const invalidate = () => { valid = false; checkpoints.length = 0; };const observer = new MutationObserver(invalidate);const current = () => {if (observer.takeRecords().length) invalidate();return valid && !disposed && isReaderGenerationCurrent("search", generation);};const resume = () => {if (!disposed) observer.observe(root, {subtree: true, childList: true, characterData: true, attributes: true, attributeFilter: ["class"]});};const locator = {current,boundaries() { return current() ? checkpoints.slice() : []; },seed(boundaries) { if (current()) checkpoints.push(...boundaries); },build(offsets) {if (!current()) return;const stride = Math.max(128, Math.ceil(offsets.length / 2048));for (let index = 0; index < offsets.length && checkpoints.length < 2048;) {const { node, parent: target, start } = offsets[index];// Element boundaries survive text splitting and normalization by our marks.if (target?.firstChild === node) {checkpoints.push({ target, start });index += stride;} else index++;}},checkpoint(offset) {if (!current()) return null;let low = 0, high = checkpoints.length;while (low < high) {const middle = (low + high) >> 1;if (checkpoints[middle].start <= offset) low = middle + 1;else high = middle;}const checkpoint = checkpoints[low - 1];if (checkpoint && (!checkpoint.target.isConnected || !root.contains(checkpoint.target))) {invalidate();return null;}return checkpoint || null;},pause() { current(); observer.disconnect(); },resume,dispose() { disposed = true; invalidate(); observer.disconnect(); }};resume();fullSearchDomLocator = locator;return locator;}function clearFullSearchMarks() {fullSearchDomLocator?.pause();fullSearchDomSnapshot?.pause();try {content.querySelectorAll(".reader-text-hit-box").forEach(node => node.remove());const changedParents = new Set();for (const mark of fullSearchActiveMarks) {if (mark.tagName === "MARK") {if (mark.parentNode) changedParents.add(mark.parentNode);mark.replaceWith(mark.textContent);}else mark.classList.remove("full-search-highlight");}fullSearchActiveMarks = [];for (const parent of changedParents) parent.normalize();content.querySelectorAll(".reader-chapter-search-heading").forEach(node => node.remove());} finally {fullSearchDomLocator?.resume();fullSearchDomSnapshot?.resume();}}async function fullSearchTextNodes(root, generation, endOffset = Infinity, checkpoint = null, collect = null) {const nodes = [],walker = root.ownerDocument.createTreeWalker(root, NodeFilter.SHOW_TEXT);if (checkpoint) walker.currentNode = checkpoint.target;let visited = 0, length = checkpoint?.start || 0, deadline = performance.now() + 8;while (walker.nextNode()) {if (!isReaderGenerationCurrent("search", generation)) return null;const node = walker.currentNode;if (node.data &&!node.parentElement.closest("script,style,mark.full-search-highlight,.reader-pdf-text")) {if (collect) collect(node);else nodes.push(node);length += node.data.length;if (length >= endOffset) break;}if (++visited % 256 === 0 && performance.now() >= deadline) {await waitForReader();deadline = performance.now() + 8;}}return nodes;}function highlightTextParts(parts) {fullSearchDomLocator?.pause();fullSearchDomSnapshot?.pause();const marks = [];try {for (const { node, start, end } of [...parts].reverse()) {node.splitText(end);const selected = node.splitText(start),mark = node.ownerDocument.createElement("mark");mark.className = "full-search-highlight";mark.textContent = selected.data;selected.replaceWith(mark);fullSearchActiveMarks.push(mark);marks.unshift(mark);}} finally {fullSearchDomLocator?.resume();fullSearchDomSnapshot?.resume();}return marks;}function fullSearchSnippet(text, index, length) {const start = Math.max(0, index - 72),end = Math.min(text.length, index + length + 88);return {text: text.slice(start, end),matchStart: index - start,matchLength: length,prefix: start ? "…" : "",suffix: end < text.length ? "…" : ""};}function createFullSearchHeadingLookup(root, offsets) {const entries = navigationState.tocEntries, boundaries = [];const headings = entries.filter(entry => entry.target);let previous = null;for (const entry of headings) {const target = entry.target;if (!target.isConnected || target.getRootNode() !== root.getRootNode() ||(previous && previous !== target &&!(previous.compareDocumentPosition(target) & Node.DOCUMENT_POSITION_FOLLOWING))) return null;previous = target;}const linear = headings.length * Math.ceil(Math.log2(offsets.length + 1)) > offsets.length;let cursor = 0;for (const entry of headings) {const target = entry.target;let low = 0, high = offsets.length;if (linear) {while (cursor < offsets.length &&!(target.compareDocumentPosition(offsets[cursor].node) & Node.DOCUMENT_POSITION_FOLLOWING)) cursor++;low = cursor;} else {while (low < high) {const middle = (low + high) >> 1;if (target.compareDocumentPosition(offsets[middle].node) & Node.DOCUMENT_POSITION_FOLLOWING) high = middle;else low = middle + 1;}}boundaries.push({ start: offsets[low]?.start ?? Infinity, label: entry.label });}return (offset) => {if (navigationState.tocEntries !== entries) return null;let low = 0, high = boundaries.length;while (low < high) {const middle = (low + high) >> 1;if (boundaries[middle].start <= offset) low = middle + 1;else high = middle;}return { label: boundaries[low - 1]?.label };};}function fullSearchLocation(node, fallback, offset, total, headingLookup = null, parent = node.parentElement) {const page = parent && parent.closest("[data-page]");if (page) return `第 ${page.dataset.page} 页`;const indexed = headingLookup?.(offset);if (indexed?.label !== undefined) return indexed.label;if (indexed) return `正文 ${Math.min(100, Math.floor(offset / Math.max(1, total) * 100))}%`;if (navigationState.tocEntries.length) {const heading = [...navigationState.tocEntries].reverse().find(entry => entry.target &&(entry.target === node.parentElement || !!(entry.target.compareDocumentPosition(node) & Node.DOCUMENT_POSITION_FOLLOWING)));if (heading) return heading.label;}return `正文 ${Math.min(100, Math.floor(offset / Math.max(1, total) * 100))}%`;}async function fullSearchDomMatches(root, fallback, query, generation, progressive = false,occurrence = null, navigationGeneration = readerRuntime.currentGeneration("navigation")) {root = foliateSectionRoot(root);const cached = progressive && fullSearchDomSnapshot?.root === root &&fullSearchDomSnapshot.value?.toc === navigationState.tocEntries ? fullSearchDomSnapshot.value : null;const snapshot = progressive ? (cached ? fullSearchDomSnapshot : createDomSearchSnapshot(root)) : null;const locator = progressive ? createFullSearchDomLocator(root, generation) : null;const offsets = cached ? cached.offsets : [],chunks = [];let length = 0;const collect = node => {offsets.push({ node, parent: node.parentElement, start: length, end: length + node.data.length });chunks.push(node.data);length += node.data.length;};const nodes = cached ? [] : await fullSearchTextNodes(root, generation, Infinity, null, collect);if (!nodes || !isReaderGenerationCurrent("search", generation)) return [];if (cached) locator?.seed(cached.checkpoints);else locator?.build(offsets);const headingLookup = cached ? cached.headingLookup : createFullSearchHeadingLookup(root, offsets);const text = cached ? cached.text : chunks.join(""), groups = [], firstHits = [];if (!cached && snapshot && (headingLookup || !navigationState.tocEntries.some(entry => entry.target)))snapshot.set({ text, offsets, headingLookup, checkpoints: locator.boundaries(), toc: navigationState.tocEntries });let highlightOffsets = offsets;const patternText = fullSearchEscape(query);let nextStart = 0, total = 0;const locateIndex = (index, parts = offsets) => {let low = 0, high = parts.length - 1;while (low < high) {const middle = (low + high) >> 1;if (parts[middle].end <= index) low = middle + 1;else high = middle;}return low;};const partsFor = (start, end) => {const parts = [];for (let index = locateIndex(start, highlightOffsets); index < highlightOffsets.length && highlightOffsets[index].start < end; index++)parts.push(highlightOffsets[index]);return parts;};const matchesIn = function* (group) {const re = new RegExp(patternText, "giu");re.lastIndex = group.skip;for (const match of text.slice(group.start, group.end).matchAll(re)) {if (match.index >= 65536) break;yield { index: group.start + match.index, value: match[0] };}};const resultFor = (match) => {const part = offsets[locateIndex(match.index)];return {location: fullSearchLocation(part.node || part.parent, fallback, match.index, text.length, headingLookup, part.parent),snippet: fullSearchSnippet(text, match.index, match.value.length),async activate(navigationGeneration = readerRuntime.currentGeneration("navigation")) {if (!isReaderGenerationCurrent("navigation", navigationGeneration)) return false;const searchGeneration = readerRuntime.currentGeneration("search");const end = match.index + match.value.length;clearFullSearchMarks();let checkpoint = locator?.checkpoint(match.index);let currentNodes = await fullSearchTextNodes(root, searchGeneration, end, checkpoint);if (checkpoint && !locator.current()) {checkpoint = null;currentNodes = await fullSearchTextNodes(root, searchGeneration, end);}if (!currentNodes || !isReaderGenerationCurrent("search", searchGeneration) ||!isReaderGenerationCurrent("navigation", navigationGeneration)) return false;let position = checkpoint?.start || 0, parts = [];for (const node of currentNodes) {const nodeEnd = position + node.data.length;if (nodeEnd > match.index && position < end)parts.push({ node, start: Math.max(0, match.index - position), end: Math.min(node.data.length, end - position) });position = nodeEnd;if (position >= end) break;}if (parts.map(part => part.node.data.slice(part.start, part.end)).join("") !== match.value) return false;const [target] = highlightTextParts(parts);target?.scrollIntoView({ block: "center" });return !!target;}};};const page = (requestedOffset) => {const pageSize = 50, results = [];const offset = fullSearchPageOffset(total, requestedOffset, pageSize);let passed = 0;for (const group of groups) {if (passed + group.count <= offset) { passed += group.count; continue; }for (const match of matchesIn(group)) {if (passed++ < offset) continue;results.push(resultFor(match));if (results.length === pageSize) break;}if (results.length === pageSize) break;}return { total, offset, pageSize, results };};for (let start = 0; start < text.length; start += 65536) {const group = { start, end: start + 65536 + query.length - 1,skip: Math.max(0, nextStart - start), count: 0 };for (const match of matchesIn(group)) {group.count++;nextStart = match.index + match.value.length;if (firstHits.length < 100) firstHits.push(match);}groups.push(group);total += group.count;if (progressive && (start === 0 || (group.count && total <= 50) || groups.length % 8 === 0)) {fullSearchSession.pageLoader = page;fullSearchSession.page = page(0);updateSearchState({ results: fullSearchSession.page.results, index: -1 });renderFullSearchResults();fullSearchStatus.textContent = `${total} 个结果(正在搜索…)`;}await waitForReader();if (!isReaderGenerationCurrent("search", generation)) return [];}if (progressive) {fullSearchSession.pageLoader = page;fullSearchSession.page = page(0);}if (occurrence !== null) {if (!isReaderGenerationCurrent("navigation", navigationGeneration)) return [];const matchedPage = page(occurrence);const result = matchedPage.results[occurrence - matchedPage.offset];if (!result || !await result.activate(navigationGeneration)) return [];return [{ target: fullSearchActiveMarks[0] }];}const fallbackResults = progressive ? null : firstHits.map(resultFor);if (cached && !snapshot.current())return fullSearchDomMatches(root, fallback, query, generation, progressive, occurrence, navigationGeneration);if (cached && firstHits.length && navigationGeneration === readerRuntime.currentGeneration("navigation")) {const checkpoint = locator.checkpoint(firstHits[0].index);const end = firstHits[firstHits.length - 1].index + firstHits[firstHits.length - 1].value.length;const markNodes = await fullSearchTextNodes(root, generation, end, checkpoint);if (!markNodes || !isReaderGenerationCurrent("search", generation)) return [];if (!snapshot.current())return fullSearchDomMatches(root, fallback, query, generation, progressive, occurrence, navigationGeneration);let position = checkpoint?.start || 0;highlightOffsets = markNodes.map(node => {const part = { node, start: position, end: position + node.data.length };position = part.end;return part;});}if (navigationGeneration === readerRuntime.currentGeneration("navigation")) {for (let i = firstHits.length - 1; i >= 0; i--) {const match = firstHits[i], end = match.index + match.value.length;const parts = partsFor(match.index, end);if (!parts.length) continue;const [target] = highlightTextParts(parts.map(part => ({ node: part.node,start: Math.max(match.index, part.start) - part.start,end: Math.min(end, part.end) - part.start })));if (fallbackResults) fallbackResults[i].target = target;}}return fallbackResults || page(0).results;}async function navigateFoliateSearchResult(result, generation) {const resolved = await epubRendition?.resolveNavigation?.(result.cfi);if (!resolved || !isReaderGenerationCurrent("navigation", generation)) return false;1234623 unmodified lines6286296306316326336345234 unmodified lines5869587058715872587358745875587658775878587958805881588258835884588558865887588858895890848 unmodified lines673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676335 unmodified lines6799680068016802680368046805142 unmodified lines694869496950695169526953import { createReaderDomSearch, fullSearchEscape, fullSearchSnippet, fullSearchPageOffset } from "./reader-dom-search.mjs";import { createReaderSearchController } from "./reader-search-controller.mjs";import "/static/reader-resources.js";import "/static/reader-contract.js";623 unmodified linesconst pageState = shell.querySelector(".reader-page-state");if (pageState) setPdfPageLoadingState(pageState, shell.dataset.page);}domSearch.pruneMarks();}function clearPdfManifestPrefetches() {stopPdfManifestPrefetch();5234 unmodified linesreturn pdfEnginePreload;}async function preparePdfWorker(pdfjs) {for (let attempt = 0; attempt < 3; attempt++) {assertReaderActive();if (attempt) await waitForReader(attempt * 500);try {return await preparePdfWorkerAttempt(pdfjs, attempt);} catch (error) {assertReaderActive();if (error?.code !== "READER_ENGINE_NETWORK" || attempt === 2) throw error;}}}async function preparePdfWorkerAttempt(pdfjs, attempt) {assertReaderActive();if (capability.mode !== "pdf" && !pdfPrimarySource()) return pdfjs;pdfjs.GlobalWorkerOptions.workerSrc = attempt? `${PDFJS_WORKER_URL}?reader-worker-retry=${attempt}` : PDFJS_WORKER_URL;const worker = new pdfjs.PDFWorker();pdfWorker = worker;let timer, destroyed = false;848 unmodified lineschapterNext.addEventListener("click", () =>activateChapter(adjacentTocIndex(1)));const domSearch = createReaderDomSearch({content, runtime: readerRuntime, isCurrent: isReaderGenerationCurrent,yieldTask: waitForReader, getTocEntries: () => navigationState.tocEntries,unwrapRoot: foliateSectionRoot,publishPage: (page, loader, partial) => {fullSearchSession.pageLoader = loader;fullSearchSession.page = page;if (partial) {updateSearchState({ results: page.results, index: -1 });renderFullSearchResults();fullSearchStatus.textContent = `${page.total} 个结果(正在搜索…)`;}}});trackReaderResource(domSearch.dispose);const {search: fullSearchDomMatches, clearMarks: clearFullSearchMarks,highlight: highlightTextParts} = domSearch;const fullSearchController = createReaderSearchController({document, runtime: readerRuntime, signal: readerAbortController.signal,nextGeneration: () => nextReaderGeneration("search"),35 unmodified linesstatus: fullSearchStatus} = fullSearchController.elements;// Format-specific search backends publish through the shared controller.function chapterSearchModule() {if (!chapterSearchModulePromise)chapterSearchModulePromise = import("/static/reader-chapter-search.mjs").catch((error) => {142 unmodified linesfullSearchSession.page = { total, offset: 0, pageSize: 50, results: firstPage.slice() };return firstPage;}async function navigateFoliateSearchResult(result, generation) {const resolved = await epubRendition?.resolveNavigation?.(result.cfi);if (!resolved || !isReaderGenerationCurrent("navigation", generation)) return false;
71 unmodified lines72737475767778798071 unmodified lines}const networkFirst = !readerShell && READER_RUNTIME_PATHS.has(url.pathname);const cacheKey = readerShell ? "/static/reader.html" : event.request;const cachePromise = caches.open(CACHE_NAME).catch(() => null);const cachedPromise = cachePromise.then(cache => cache ? cache.match(cacheKey) : undefined).catch(() => undefined);const immutable = /\.[0-9a-f]{12}\.(?:js|mjs|css)$/.test(url.pathname);let cacheWrite;const networkPromise = Promise.all([cachePromise, immutable ? cachedPromise : null]).then(([cache, cached]) => cached || fetch(event.request).then(response => {if (cache && response.ok && response.status !== 206) {71 unmodified lines7273747576777879808171 unmodified lines}const networkFirst = !readerShell && READER_RUNTIME_PATHS.has(url.pathname);const cacheKey = readerShell ? "/static/reader.html" : event.request;const immutable = /\.[0-9a-f]{12}\.(?:js|mjs|css)$/.test(url.pathname);const cachePromise = caches.open(CACHE_NAME).catch(() => null);// Pinned same-origin assets are identical across classic/module Origin headers.const cachedPromise = cachePromise.then(cache => cache ? cache.match(cacheKey, { ignoreVary: immutable }) : undefined).catch(() => undefined);let cacheWrite;const networkPromise = Promise.all([cachePromise, immutable ? cachedPromise : null]).then(([cache, cached]) => cached || fetch(event.request).then(response => {if (cache && response.ok && response.status !== 206) {
294 unmodified lines295296297298299300294 unmodified linesself.assertEqual(read.call_count, 1)self.assertEqual(second.headers["cache-control"], "public, max-age=3600")async def test_v2_chapter_manifest_and_search_index_reuse_bounded_cache(self):prefix = "chapters/ebook/epub/" + "a" * 64 + "/" + "b" * 16 + "/"for name in ("chapter-manifest.json", "epub-search-index.json.gz"):294 unmodified lines295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361294 unmodified linesself.assertEqual(read.call_count, 1)self.assertEqual(second.headers["cache-control"], "public, max-age=3600")async def test_random_reader_uses_complete_snapshot_without_waiting_for_refresh(self):snapshot = {"v": 1, "f": {"ready": {"s": 4}}}entered, release = asyncio.Event(), asyncio.Event()async def refresh():entered.set()await release.wait()return snapshotwith patch.object(app, "reader_assets_cache", snapshot), \patch.object(app, "reader_assets_cache_at", time.monotonic() - app.READER_ASSETS_CACHE_TTL_SECONDS - 1), \patch.object(app, "refresh_reader_assets", side_effect=refresh), \patch.object(app, "ensure_reader_indexes_async", AsyncMock()), \patch.object(app, "converted_reader_indices", return_value={}), \patch.object(app, "reader_record_indices", [0]), \patch.object(app, "records", [{"Repo": "VoiceOfML/Test", "File": "book", "Extension": "txt", "Folder": [], "Size": 1}]):result = await asyncio.wait_for(app.api_random_reader(None), .5)await entered.wait()self.assertFalse(release.is_set())self.assertEqual(result.status_code, 200)self.assertEqual(json.loads(result.body)["File"], "book")status = await asyncio.wait_for(app.api_random_reader_status(None), .5)self.assertEqual(json.loads(status.body), {"available": True, "count": 1})release.set()await app.app.state.reader_assets_taskasync def test_cold_random_reader_waits_for_first_complete_asset_snapshot(self):entered, release = asyncio.Event(), asyncio.Event()async def refresh():entered.set()await release.wait()return {"v": 1, "f": {}}with patch.object(app, "reader_assets_cache", {"v": 1, "f": {}}), \patch.object(app, "reader_assets_cache_at", 0), \patch.object(app, "refresh_reader_assets", side_effect=refresh), \patch.object(app, "ensure_reader_indexes_async", AsyncMock()), \patch.object(app, "converted_reader_indices", return_value={}), \patch.object(app, "reader_record_indices", []):task = asyncio.create_task(app.api_random_reader(None))await entered.wait()self.assertFalse(task.done())release.set()self.assertEqual((await task).status_code, 404)async def test_reader_asset_decode_does_not_block_ping(self):entered, release = threading.Event(), threading.Event()def decode(raw):entered.set()release.wait(3)return {"v": 1, "f": {}}app.app.state.http_session = FakeSession([FakeResponse(200, chunks=(b"sidecar",))])with patch.object(app, "reader_assets_cache_at", 0), \patch.object(app, "decode_reader_assets", side_effect=decode), \patch.object(app, "load_reading_catalog", AsyncMock(return_value=None)):task = asyncio.create_task(app.refresh_reader_assets())try:self.assertTrue(await asyncio.to_thread(entered.wait, 1))self.assertEqual((await asyncio.wait_for(app.api_ping(), .2)).status_code, 204)self.assertFalse(task.done())finally:release.set()await taskasync def test_v2_chapter_manifest_and_search_index_reuse_bounded_cache(self):prefix = "chapters/ebook/epub/" + "a" * 64 + "/" + "b" * 16 + "/"for name in ("chapter-manifest.json", "epub-search-index.json.gz"):
10 unmodified lines11121314151610 unmodified linesassertCode(reader, 'backend: { mode: () => capability.mode, search: searchReaderText')assert.doesNotMatch(reader, /dataset\.panelView\s*=\s*"full-search"/)assert.doesNotMatch(searchController, /new Worker|\bfetch\(|import\(/)const css = fs.readFileSync(path.join(root, 'static/reader.css'), 'utf8')const view = fs.readFileSync(path.join(root, 'static/foliate-reader/view.js'), 'utf8')for (const marker of ["import('./epub.js')", "import('./mobi.js')", "import('./fb2.js')", "import('./pdf.js')", "isFBZ(file)", "isFB2(file)"]) assert.ok(view.includes(marker), marker)10 unmodified lines1112131415161718192021222324252610 unmodified linesassertCode(reader, 'backend: { mode: () => capability.mode, search: searchReaderText')assert.doesNotMatch(reader, /dataset\.panelView\s*=\s*"full-search"/)assert.doesNotMatch(searchController, /new Worker|\bfetch\(|import\(/)const domSearch = fs.readFileSync(path.join(root, 'static/reader-dom-search.mjs'), 'utf8')assertCode(reader, 'import { createReaderDomSearch, fullSearchEscape, fullSearchSnippet, fullSearchPageOffset } from "./reader-dom-search.mjs"')assertCode(reader, 'trackReaderResource(domSearch.dispose)')assertCode(reader, 'getTocEntries: () => navigationState.tocEntries')assertCode(reader, 'domSearch.pruneMarks()')assert.doesNotMatch(reader, /function (?:fullSearchDomMatches|createDomSearchSnapshot|createFullSearchDomLocator|fullSearchTextNodes|highlightTextParts)\(/)assert.doesNotMatch(domSearch, /new Worker|\bfetch\(|import\(|readerRuntime|navigationState|fullSearchSession|fullSearchStatus/)assertCode(domSearch, 'const stopGeneration = runtime.events.on("generation"')assertCode(domSearch, 'function dispose() { stopGeneration()')assertCode(domSearch, 'publishPage(page(0), page, true)')const css = fs.readFileSync(path.join(root, 'static/reader.css'), 'utf8')const view = fs.readFileSync(path.join(root, 'static/foliate-reader/view.js'), 'utf8')for (const marker of ["import('./epub.js')", "import('./mobi.js')", "import('./fb2.js')", "import('./pdf.js')", "isFBZ(file)", "isFB2(file)"]) assert.ok(view.includes(marker), marker)
151 unmodified lines1521531541551561571581 unmodified line160161162163164165166151 unmodified linesconst path=new URL(document.querySelector('script[src*="reader-navigation.js"]').src).pathname.replace('reader-navigation.js','reader.html');navigateToReader(path+'?ext=txt');closeReaderOverlay();history.replaceState(null,'',previousUrl);await randomTxt();await new Promise(resolve=>originalTimer(resolve,100));const recovered=aborted&&!readerOverlay;await randomTxt();await new Promise(resolve=>originalTimer(resolve,100));return {recovered,attempts,opened:!!readerOverlay};} finally {1 unmodified lineif(localFallback)ensureLocalDataLoaded=localFallback;}}''')self.assertEqual(result, {'recovered':True,'attempts':2,'opened':True})def test_reader_folder_url_uses_current_filters(self):result = self.page.evaluate('''() => {151 unmodified lines1521531541551561571581591 unmodified line161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191151 unmodified linesconst path=new URL(document.querySelector('script[src*="reader-navigation.js"]').src).pathname.replace('reader-navigation.js','reader.html');navigateToReader(path+'?ext=txt');closeReaderOverlay();history.replaceState(null,'',previousUrl);await randomTxt();await new Promise(resolve=>originalTimer(resolve,100));const recovered=aborted&&!!readerOverlay;closeReaderOverlay();history.replaceState(null,'',previousUrl);await randomTxt();await new Promise(resolve=>originalTimer(resolve,100));return {recovered,attempts,opened:!!readerOverlay};} finally {1 unmodified lineif(localFallback)ensureLocalDataLoaded=localFallback;}}''')self.assertEqual(result, {'recovered':True,'attempts':3,'opened':True})def test_random_reader_retries_transient_http_but_not_permanent_or_stale_failure(self):result = self.page.evaluate('''async () => {const originalFetch=fetch, savedUrl=location.href;const success={Repo:'VoiceOfML/Test',File:'next',Extension:'txt',Link:'https://huggingface.co/datasets/VoiceOfML/Test/resolve/main/next.txt',Folder:[]};const rows=[];try {for(const code of [503,429,404]) {let requests=0;window.fetch=()=>Promise.resolve(++requests===1? new Response('{}',{status:code}) : new Response(JSON.stringify(success)));const id=++randomReaderRequestId;try { await fetchRandomReaderRecord('/api/random-reader',id,savedUrl); } catch (_) {}rows.push(requests);}let requests=0;window.fetch=()=>{requests++;randomReaderRequestId++;return Promise.reject(new TypeError('network'));};await fetchRandomReaderRecord('/api/random-reader',++randomReaderRequestId,savedUrl);rows.push(requests);return rows;} finally {window.fetch=originalFetch;}}''')self.assertEqual(result, [2,2,1,1])def test_reader_folder_url_uses_current_filters(self):result = self.page.evaluate('''() => {
22 unmodified lines2324252627282 unmodified lines3132333435363722 unmodified linessearch = fixtures.ReaderRefactorTest.searchdef expose(self):def instrument(route):response = route.fetch()script = response.text().replace('chapterManifestCleanup = () => {', '''2 unmodified lineschapterManifestCleanup = () => {''')route.fulfill(response=response, body=script + '''window.__chunkWindow = createPdfShellWindow;window.__snapshot = () => fullSearchDomSnapshot;window.__markerPage = () => pageAtMarker()?.dataset.page;window.__restoreText = top => restoreProgressState({scrollTop:top});window.__cancelNavigation = () => beginReaderNavigation();22 unmodified lines232425262728292 unmodified lines3233343536373822 unmodified linessearch = fixtures.ReaderRefactorTest.searchdef expose(self):fixtures.expose_dom_search_tools(self.page)def instrument(route):response = route.fetch()script = response.text().replace('chapterManifestCleanup = () => {', '''2 unmodified lineschapterManifestCleanup = () => {''')route.fulfill(response=response, body=script + '''window.__chunkWindow = createPdfShellWindow;window.__snapshot = () => window.__domSearchTools.snapshot();window.__markerPage = () => pageAtMarker()?.dataset.page;window.__restoreText = top => restoreProgressState({scrollTop:top});window.__cancelNavigation = () => beginReaderNavigation();
59 unmodified lines606162636465188 unmodified lines2542552562572582592606 unmodified lines26726826927027127227359 unmodified linesself.assertEqual(len(self.modules), 1)self.assertNotIn('reader-module-retry', self.modules[0])def test_pdf_range_policy_keeps_default_browser_cache_from_serializing_reads(self):payload = b''.join(bytes([index]) * 128 for index in range(16))metrics = {mode: {'active': 0, 'peak': 0} for mode in ('upstream', 'reader')}188 unmodified linesself.ready()self.assertEqual(lookups, [])def test_worker_timeout_terminates_once_and_exposes_retry(self):self.page.add_init_script('''const native = window.setTimeout.bind(window);window.setTimeout = (fn, ms, ...args) => native(fn, ms === 20000 ? 250 : ms, ...args);''')self.page.route(MODULE, lambda route: route.fulfill(content_type='text/javascript', body='''6 unmodified lines'''))self.open()self.page.locator('#reader-engine-retry').wait_for()self.assertEqual(self.page.evaluate('() => window.__workerDestroys'), 1)self.assertEqual(self.documents, [])self.assertEqual(self.errors, [])59 unmodified lines6061626364656667686970717273747576777879808182838485868788899091188 unmodified lines2802812822832842852866 unmodified lines29329429529629729829959 unmodified linesself.assertEqual(len(self.modules), 1)self.assertNotIn('reader-module-retry', self.modules[0])def test_transient_worker_download_failure_recovers_without_reader_reload(self):self.page.add_init_script('''const native = window.setTimeout.bind(window);window.setTimeout = (fn, ms, ...args) => native(fn, ms === 20000 ? 300 : ms, ...args);''')self.page.route(MODULE, lambda route: route.fulfill(content_type='text/javascript', body='''export const GlobalWorkerOptions = {};export class PDFWorker {constructor() {window.__workerAttempts = (window.__workerAttempts || 0) + 1;(window.__workerUrls ||= []).push(GlobalWorkerOptions.workerSrc);this.promise = window.__workerAttempts === 1 ? new Promise(() => {}) : Promise.resolve();}destroy() { window.__workerDestroys = (window.__workerDestroys || 0) + 1; }}export function getDocument() {const page = {getViewport:({scale})=>({width:600*scale,height:800*scale}),getTextContent:async()=>({items:[]}),render:()=>({promise:Promise.resolve()})};return {promise:Promise.resolve({numPages:1,getPage:async()=>page,getOutline:async()=>null}),destroy(){}};}'''))self.open()self.ready()self.assertEqual(self.page.evaluate('__workerAttempts'), 2)self.assertEqual(self.page.evaluate('__workerDestroys'), 1)self.assertIn('reader-worker-retry=1', self.page.evaluate('__workerUrls[1]'))self.assertEqual(len(self.documents), 0)def test_pdf_range_policy_keeps_default_browser_cache_from_serializing_reads(self):payload = b''.join(bytes([index]) * 128 for index in range(16))metrics = {mode: {'active': 0, 'peak': 0} for mode in ('upstream', 'reader')}188 unmodified linesself.ready()self.assertEqual(lookups, [])def test_worker_timeout_terminates_each_attempt_and_exposes_retry(self):self.page.add_init_script('''const native = window.setTimeout.bind(window);window.setTimeout = (fn, ms, ...args) => native(fn, ms === 20000 ? 250 : ms, ...args);''')self.page.route(MODULE, lambda route: route.fulfill(content_type='text/javascript', body='''6 unmodified lines'''))self.open()self.page.locator('#reader-engine-retry').wait_for()self.assertEqual(self.page.evaluate('() => window.__workerDestroys'), 3)self.assertEqual(self.documents, [])self.assertEqual(self.errors, [])
14 unmodified lines1516171819201107 unmodified lines1128112911301131113211331134113511361109 unmodified lines224622472248224922502251225253 unmodified lines23062307230823092310231123122313231423159 unmodified lines232523262327232823292330233123322333233423352336233723381 unmodified line234023412342234323442345234614 unmodified linesfrom tests import test_reader_performance as support@unittest.skipIf(support.sync_playwright is None, "Playwright is unavailable")class ReaderRefactorTest(unittest.TestCase):@classmethod1107 unmodified lineswindow.__fallbackHeld = true;await new Promise(resolve => { window.__releaseFallback = resolve; });} """ + needle)route.fulfill(response=response, body=script.replace("target = matches[0]?.target;", "target = matches[0]?.target; window.__fallbackDone = true;"))self.page.route("**/static/reader.js*", hold_fallback)self.serve(support.epub_with_many_chapters(3), "application/epub+zip")self.open(self.reader_url("epub"))self.search("正文")1109 unmodified linesroute.fulfill(response=response, body=script.replace(needle,"await new Promise(resolve => { window.__releaseActivation = resolve; }); " +needle + " window.__activationSettled = true;"))self.page.route("**/static/reader.js*", hold_activation)self.serve("oldword " * 70 + "freshword")self.open(self.reader_url())self.search("oldword")53 unmodified linesself.assertLessEqual(self.page.evaluate('window.__activationVisited'), 130)def expose_dom_search_locator(self):def instrument(route):response = route.fetch()route.fulfill(response=response, body=response.text() + '''window.__domLocator = () => fullSearchDomLocator;window.__activateDomResult = async index => {const doc = (htmlFrame?.contentDocument?.body || content).ownerDocument;const native = doc.createTreeWalker.bind(doc);9 unmodified lineswindow.__headingOracle = async entries => {const root = htmlFrame.contentDocument.body;setToc(entries.map(entry => ({label:entry.label, target:root.querySelector(entry.selector)})));const nodes = await fullSearchTextNodes(root, readerRuntime.currentGeneration('search'));let length = 0;const offsets = nodes.map(node => {const part = {node, start:length, end:length + node.data.length};length = part.end;return part;});const lookup = createFullSearchHeadingLookup(root, offsets);const compare = () => offsets.map(part => {const heading = [...navigationState.tocEntries].reverse().find(entry => entry.target &&(entry.target === part.node.parentElement ||1 unmodified lineconst page = part.node.parentElement.closest('[data-page]');const expected = page ? '第 ' + page.dataset.page + ' 页' :heading ? heading.label : '正文 ' + Math.min(100, Math.floor(part.start / Math.max(1,length) * 100)) + '%';return [fullSearchLocation(part.node, '', part.start, length, lookup), expected];});const pairs = compare();setToc([...navigationState.tocEntries].reverse());14 unmodified lines15161718192021222324252627282930313233343536371107 unmodified lines11451146114711481149115011511152115311541155115611571109 unmodified lines226722682269227022712272227353 unmodified lines232723282329233023312332233323342335233623379 unmodified lines234723482349235023512352235323542355235623572358235923601 unmodified line236223632364236523662367236814 unmodified linesfrom tests import test_reader_performance as supportdef expose_dom_search_tools(page):def instrument(route):response = route.fetch()script = response.text()marker = " function pruneMarks() {"if marker not in script:raise AssertionError("DOM search instrumentation boundary missing")route.fulfill(response=response, body=script.replace(marker, '''window.__domSearchTools = {locator: () => fullSearchDomLocator, snapshot: () => fullSearchDomSnapshot,textNodes: fullSearchTextNodes, headingLookup: createFullSearchHeadingLookup,location: fullSearchLocation};''' + marker))page.route("**/static/reader-dom-search.mjs*", instrument)@unittest.skipIf(support.sync_playwright is None, "Playwright is unavailable")class ReaderRefactorTest(unittest.TestCase):@classmethod1107 unmodified lineswindow.__fallbackHeld = true;await new Promise(resolve => { window.__releaseFallback = resolve; });} """ + needle)route.fulfill(response=response, body=script)def finish_fallback(route):response = route.fetch()route.fulfill(response=response, body=response.text().replace("target = matches[0]?.target;", "target = matches[0]?.target; window.__fallbackDone = true;"))self.page.route("**/static/reader-dom-search.mjs*", hold_fallback)self.page.route("**/static/reader.js*", finish_fallback)self.serve(support.epub_with_many_chapters(3), "application/epub+zip")self.open(self.reader_url("epub"))self.search("正文")1109 unmodified linesroute.fulfill(response=response, body=script.replace(needle,"await new Promise(resolve => { window.__releaseActivation = resolve; }); " +needle + " window.__activationSettled = true;"))self.page.route("**/static/reader-dom-search.mjs*", hold_activation)self.serve("oldword " * 70 + "freshword")self.open(self.reader_url())self.search("oldword")53 unmodified linesself.assertLessEqual(self.page.evaluate('window.__activationVisited'), 130)def expose_dom_search_locator(self):expose_dom_search_tools(self.page)def instrument(route):response = route.fetch()route.fulfill(response=response, body=response.text() + '''window.__domLocator = () => window.__domSearchTools.locator();window.__activateDomResult = async index => {const doc = (htmlFrame?.contentDocument?.body || content).ownerDocument;const native = doc.createTreeWalker.bind(doc);9 unmodified lineswindow.__headingOracle = async entries => {const root = htmlFrame.contentDocument.body;setToc(entries.map(entry => ({label:entry.label, target:root.querySelector(entry.selector)})));const nodes = await window.__domSearchTools.textNodes(root, readerRuntime.currentGeneration('search'));let length = 0;const offsets = nodes.map(node => {const part = {node, start:length, end:length + node.data.length};length = part.end;return part;});const lookup = window.__domSearchTools.headingLookup(root, offsets);const compare = () => offsets.map(part => {const heading = [...navigationState.tocEntries].reverse().find(entry => entry.target &&(entry.target === part.node.parentElement ||1 unmodified lineconst page = part.node.parentElement.closest('[data-page]');const expected = page ? '第 ' + page.dataset.page + ' 页' :heading ? heading.label : '正文 ' + Math.min(100, Math.floor(part.start / Math.max(1,length) * 100)) + '%';return [window.__domSearchTools.location(part.node, '', part.start, length, lookup), expected];});const pairs = compare();setToc([...navigationState.tocEntries].reverse());
249 unmodified lines250251252253254255256249 unmodified linesassert_source_contains(self, 'location.assign("/")', reader)self.assertIn('requestId !== randomReaderRequestId || location.href !== returnUrl', self.js)self.assertIn("rec.ReaderExtension || rec.Extension", self.js)self.assertIn("converted_reader_indices(await get_reader_assets(), full_repo)", (ROOT / "app.py").read_text(encoding="utf-8"))self.assertIn("loadReaderAssets().then(refreshResultReaderActions)", self.js)self.assertIn('id="page-number"', reader_html)assert_source_contains(self, 'document.querySelector(".page-controls").hidden = !capability.features.pagination', reader)249 unmodified lines250251252253254255256257258249 unmodified linesassert_source_contains(self, 'location.assign("/")', reader)self.assertIn('requestId !== randomReaderRequestId || location.href !== returnUrl', self.js)self.assertIn("rec.ReaderExtension || rec.Extension", self.js)backend = (ROOT / "app.py").read_text(encoding="utf-8")self.assertIn('get_reader_assets(wait=not bool(reader_assets_cache.get("f")))', backend)self.assertIn("converted_reader_indices(assets, full_repo)", backend)self.assertIn("loadReaderAssets().then(refreshResultReaderActions)", self.js)self.assertIn('id="page-number"', reader_html)assert_source_contains(self, 'document.querySelector(".page-controls").hidden = !capability.features.pagination', reader)
app.py+7-3
scripts/benchmark_reader_open.pyAdded+161
scripts/check_reader_release.mjs+1
scripts/reader-opening-media-samples.jsonAdded+4
scripts/reader-opening-samples.jsonAdded+12
static/app.js+25-2
static/reader-dom-search.mjsAdded+414
static/reader-resources.js+1
static/reader.js+36-404
static/sw.js+3-2
tests/test_async_proxy.py+61
tests/test_reader_architecture.js+10
tests/test_reader_navigation_host.py+27-2
tests/test_reader_optimizations.py+2-1
tests/test_reader_pdf_loading.py+28-2
tests/test_reader_refactor.py+29-7
tests/test_static_contract.py+3-1