vomebook commited on
Commit ·
58d59b4
1
Parent(s): a055f49
Fix reviewed search and Reader regressions
Browse filesFiles changed (17)
- backend/reader/document/http/transport.py+3-1
- quality/reviewed-audit-source-transition.json+12-2
- scripts/backend_paths.py+1-1
- static/app.js+7-2
- static/reader/core/reader-bindings.mjs+6-2
- static/reader/formats/reader-chapter-format.mjs+9-11
- static/reader/formats/reader-html-format.mjs+28-2
- static/reader/pdf/reader-pdf-network.mjs+18-5
- static/reader/ui/reader-bookmarks.mjs+10-1
- static/reader/ui/reader-progress.mjs+27-3
- tests/gates/test_static_contract.py+4-2
- tests/proxy/test_async_proxy.py+50-3
- tests/reader/browser/test_reader_accessibility_browser.py+65
- tests/reader/browser/test_reader_ebook_flow.py+69
- tests/reader/browser/test_reader_refactor.py+27
- tests/reader/pdf-network/test_reader_pdf_backpressure.mjs+53-1
- tests/search/browser/test_search_session_browser.py+82-1
26 unmodified lines27282930313233172 unmodified lines20620720820921021126 unmodified linesclass OpenResponse(Protocol):def __call__(self, session: object, url: str, timeout: aiohttp.ClientTimeout, *,method: str, request_headers: dict[str, str], url_validator: Callable[[str], str],auto_decompress: bool) -> Awaitable[aiohttp.ClientResponse]: ...class ProxyTiming(Protocol):172 unmodified linesrequest_headers=forwarded_headers,url_validator=url_validator,auto_decompress=False,)headers_at = deps.clock()if upstream.status == 429:26 unmodified lines27282930313233172 unmodified lines20620720820921021121221326 unmodified linesclass OpenResponse(Protocol):def __call__(self, session: object, url: str, timeout: aiohttp.ClientTimeout, *,method: str, request_headers: dict[str, str], url_validator: Callable[[str], str],auto_decompress: bool, cache_redirects: bool = True) -> Awaitable[aiohttp.ClientResponse]: ...class ProxyTiming(Protocol):172 unmodified linesrequest_headers=forwarded_headers,url_validator=url_validator,auto_decompress=False,# Validate freshness against the source, not an older signed target.cache_redirects=not (fresh_range or has_conditionals),)headers_at = deps.clock()if upstream.status == 429:
127 unmodified lines1281291301311321331341 unmodified line136137138139140141142143144145146147148127 unmodified lines]},"backend/reader/document/http/transport.py": {"current_sha256": "641f1f6282542946dd5d0ab9ac7a85d7b506a109e104063839b07ffc5b299faa","parent_sha256": "4c75cd63a93bcdf1d7b03949d6478cb8d35f74b5fc869e2895b3a6f54b96cb92","hunks": [[1 unmodified line"from backend.reader.document.domain.range_cache import (RangeCacheState, range_cache_seconds,\n requires_fresh_range, resident_age_headers)\n","from backend.reader.document.domain.range_cache import RangeCacheState, range_cache_seconds, requires_fresh_range\n"],[170," current_time = deps.clock()\n if current_time - cached_at < range_cache_seconds(cached_headers, deps.cache_ttl()):\n cached_headers = resident_age_headers(cached_headers, cached_at, current_time)\n"," if deps.clock() - cached_at < range_cache_seconds(cached_headers, deps.cache_ttl()):\n"],[210," if upstream.status == 429:\n # We generate our own error body, so do not copy its upstream\n # representation headers. Keep the origin's retry deadline even\n # when its (unused) error body is compressed or too large.\n retry_headers = {\"Cache-Control\": \"no-store\"}\n retry_after = upstream.headers.get(\"Retry-After\", \"\").strip()\n if re.fullmatch(r\"[ -~]{1,128}\", retry_after):\n retry_headers[\"Retry-After\"] = retry_after\n if request.method == \"HEAD\":\n return Response(status_code=429, headers=retry_headers)\n return JSONResponse({\"error\": \"上游阅读文件加载失败: HTTP 429\"},\n status_code=429, headers=retry_headers)\n",""]127 unmodified lines1281291301311321331341 unmodified line136137138139140141142143144145146147148149150151152153154155156157158127 unmodified lines]},"backend/reader/document/http/transport.py": {"current_sha256": "6a39be6b5adb79031dbedf75bcae5c93a83fd8fb1d3f89db5f1c2c6bd430110d","parent_sha256": "4c75cd63a93bcdf1d7b03949d6478cb8d35f74b5fc869e2895b3a6f54b96cb92","hunks": [[1 unmodified line"from backend.reader.document.domain.range_cache import (RangeCacheState, range_cache_seconds,\n requires_fresh_range, resident_age_headers)\n","from backend.reader.document.domain.range_cache import RangeCacheState, range_cache_seconds, requires_fresh_range\n"],[29," auto_decompress: bool, cache_redirects: bool = True) -> Awaitable[aiohttp.ClientResponse]: ...\n"," auto_decompress: bool) -> Awaitable[aiohttp.ClientResponse]: ...\n"],[170," current_time = deps.clock()\n if current_time - cached_at < range_cache_seconds(cached_headers, deps.cache_ttl()):\n cached_headers = resident_age_headers(cached_headers, cached_at, current_time)\n"," if deps.clock() - cached_at < range_cache_seconds(cached_headers, deps.cache_ttl()):\n"],[208," # Validate freshness against the source, not an older signed target.\n cache_redirects=not (fresh_range or has_conditionals),\n",""],[212," if upstream.status == 429:\n # We generate our own error body, so do not copy its upstream\n # representation headers. Keep the origin's retry deadline even\n # when its (unused) error body is compressed or too large.\n retry_headers = {\"Cache-Control\": \"no-store\"}\n retry_after = upstream.headers.get(\"Retry-After\", \"\").strip()\n if re.fullmatch(r\"[ -~]{1,128}\", retry_after):\n retry_headers[\"Retry-After\"] = retry_after\n if request.method == \"HEAD\":\n return Response(status_code=429, headers=retry_headers)\n return JSONResponse({\"error\": \"上游阅读文件加载失败: HTTP 429\"},\n status_code=429, headers=retry_headers)\n",""]
13 unmodified lines1415161718192013 unmodified linesTRANSITION_FILE = 'quality/reviewed-functional-source-transition.json'TRANSITION_SHA = '3b284323fdf226820b69b074473f7933f563bf41f3d011bdbb9273be0efeb97b'AUDIT_TRANSITION_FILE = 'quality/reviewed-audit-source-transition.json'AUDIT_TRANSITION_SHA = '275e5d37fb79e1d80e2f3e22e9c25d67d620549d376003d66128a94edb4b9570'SEARCH_PERF_TRANSITION_FILE = 'quality/reviewed-wildcard-scope-transition.json'SEARCH_PERF_TRANSITION_SHA = 'b60180abab5ccc8a0af958e60f4cabe46e2fab6c439c1d3150762324dcd6a48a'# These files have exact Refactor23 hashes but no import-relocation entries.13 unmodified lines1415161718192013 unmodified linesTRANSITION_FILE = 'quality/reviewed-functional-source-transition.json'TRANSITION_SHA = '3b284323fdf226820b69b074473f7933f563bf41f3d011bdbb9273be0efeb97b'AUDIT_TRANSITION_FILE = 'quality/reviewed-audit-source-transition.json'AUDIT_TRANSITION_SHA = 'd07320b74be14a5e3f4f1dcf4c766deee50441306bf470be8504f488111cd6d4'SEARCH_PERF_TRANSITION_FILE = 'quality/reviewed-wildcard-scope-transition.json'SEARCH_PERF_TRANSITION_SHA = 'b60180abab5ccc8a0af958e60f4cabe46e2fab6c439c1d3150762324dcd6a48a'# These files have exact Refactor23 hashes but no import-relocation entries.
2481 unmodified lines2482248324842485248624872488248924901205 unmodified lines36963697369836993700370137022481 unmodified lines}function renderResults(animate = false) {pendingResultEntrance = false;if (!positionRestore && STATE._loadedPage >= 1) rememberDisplayedSearchView();activateSearchView();clearResultsSkeleton();if (STATE.results.length === 0) {DOM.resultsList.innerHTML = "";1205 unmodified linesif (DOM.mirrorLinksToggle) DOM.mirrorLinksToggle.addEventListener("change", () => {STATE.useMirrorLinks = DOM.mirrorLinksToggle.checked;syncStateToURL(true);if (STATE.results.length > 0) renderResults();});getResultInteractions().installSelection();DOM.hamburgerBtn.addEventListener("click", toggleLeftSidebar);2481 unmodified lines248224832484248524862487248824892490249124922493249424951205 unmodified lines37013702370337043705370637072481 unmodified lines}function renderResults(animate = false) {if (!positionRestore && STATE._loadedPage >= 1) rememberDisplayedSearchView();activateSearchView();redrawResults(animate);}// Presentation changes must not assign the pending search key to existing rows.function redrawResults(animate = false) {pendingResultEntrance = false;clearResultsSkeleton();if (STATE.results.length === 0) {DOM.resultsList.innerHTML = "";1205 unmodified linesif (DOM.mirrorLinksToggle) DOM.mirrorLinksToggle.addEventListener("change", () => {STATE.useMirrorLinks = DOM.mirrorLinksToggle.checked;syncStateToURL(true);if (STATE.results.length > 0) redrawResults();});getResultInteractions().installSelection();DOM.hamburgerBtn.addEventListener("click", toggleLeftSidebar);
540 unmodified lines54154254354454554614 unmodified lines5615625635645655666 unmodified lines573574575576577578579580581540 unmodified lines/** @type {Element} */ (document.querySelector("#bookmark-add")).addEventListener("click", async (event) => {const button = /** @type {HTMLButtonElement} */ (event.currentTarget),editing = readerContext.panelState.editingBookmark;const snapshot = readerContext.pendingBookmarkSnapshot || editing || readerContext.captureBookmarkSnapshot();const label = readerContext.bookmarkLabelInput.value.trim() || snapshot.label,excerpt = readerContext.bookmarkExcerptInput.value.trim();14 unmodified linescreatedAt: Date.now()});const invoker = readerContext.bookmarkInvoker;readerContext.closeBookmarkPopover();if (!/** @type {HTMLElement} */ (document.querySelector("#bookmarks-panel")).hidden) {6 unmodified lines).focus();}} catch (_) {/** @type {Element} */ (document.querySelector("#bookmark-prompt")).textContent = "书签保存失败,请重试。";} finally {button.disabled = false;}});readerContext.bookmarkPopover.addEventListener("keydown", (event) => {540 unmodified lines54154254354454554654754814 unmodified lines5635645655665675685696 unmodified lines576577578579580581582583584585540 unmodified lines/** @type {Element} */ (document.querySelector("#bookmark-add")).addEventListener("click", async (event) => {const button = /** @type {HTMLButtonElement} */ (event.currentTarget),editing = readerContext.panelState.editingBookmark;const saveGeneration = readerContext.nextReaderGeneration("bookmark-dialog");const ownsDialog = () => readerContext.isReaderGenerationCurrent("bookmark-dialog", saveGeneration);const snapshot = readerContext.pendingBookmarkSnapshot || editing || readerContext.captureBookmarkSnapshot();const label = readerContext.bookmarkLabelInput.value.trim() || snapshot.label,excerpt = readerContext.bookmarkExcerptInput.value.trim();14 unmodified linescreatedAt: Date.now()});if (!ownsDialog()) return;const invoker = readerContext.bookmarkInvoker;readerContext.closeBookmarkPopover();if (!/** @type {HTMLElement} */ (document.querySelector("#bookmarks-panel")).hidden) {6 unmodified lines).focus();}} catch (_) {if (ownsDialog())/** @type {Element} */ (document.querySelector("#bookmark-prompt")).textContent = "书签保存失败,请重试。";} finally {if (ownsDialog()) button.disabled = false;}});readerContext.bookmarkPopover.addEventListener("keydown", (event) => {
1234742 unmodified lines7477487497507517527537547557567 unmodified lines76476576676776876977035 unmodified lines806807808809810811812813814815816817818import { EBOOK_LAYOUT_STYLE, wrapEbookTables } from "../ui/reader-document-styles.mjs";// The current MOBI chapter manifest for this five-volume edition contains// cross-volume sidebar targets that point back into volume 1. Its own verified742 unmodified linesreaderContext.chapterManifestLoader = chapterManifestLoader;setChapterToc();await readerContext.getInitialReaderRestoration();const savedChapter = Number(readerContext.readerRestorationEntry?.chapterIndex) - 1;const initialChapter = Number.isInteger(savedChapter)? Math.max(0, Math.min(manifest.chapters.length - 1, savedChapter)): 0;const initial = /** @type {import("../../../typings/reader-chapter-format-strict").Chapter} */ (manifest.chapters[initialChapter]);chapterFocusIndex = initial.index;if (initialChapter > 0) ensureSentinel(/** @type {import("../../../typings/reader-chapter-format-strict").Chapter} */ (manifest.chapters[initialChapter - 1]), true);7 unmodified lineschapterScheduler.prefetch(chapterPrefetchIndices());await readerContext.awaitReader(Promise.race([firstChapter, openingLanding.promise]));} catch (error) {if (readerContext.readerRestorationEntry?.chapterIndex == null) throw error;throw Object.assign(new Error("阅读位置恢复失败,原进度已保留,请重试加载。", { cause: error }), {code: "READER_RESTORE"});35 unmodified lines/** @param {import("../../../typings/reader-progress-strict").ProgressState} entry @param {number} generation* @param {number} [progressFraction] A transient slider target, never stored in a bookmark or history entry. */async function restoreChapterPosition(entry, generation, progressFraction) {if (/-epub-chapters-v5\//.test(readerContext.chapterManifestUrl || readerContext.sourceUrl) &&entry.chapterManifest !== (readerContext.chapterManifestUrl || readerContext.sourceUrl)) return false;const loader = readerContext.chapterManifestLoader;if (!loader || entry.chapterIndex === undefined || !Number.isInteger(entry.chapterIndex) ||!readerContext.isReaderGenerationCurrent("navigation", generation)) return false;const chapter = await loader(entry.chapterIndex);if (!chapter?.isConnected || !readerContext.isReaderGenerationCurrent("navigation", generation)) return false;const viewport = readerContext.viewport, last = entry.chapterIndex === loader.count;12345742 unmodified lines7487497507517527537547557567 unmodified lines76476576676776876977035 unmodified lines806807808809810811812813814815816import { EBOOK_LAYOUT_STYLE, wrapEbookTables } from "../ui/reader-document-styles.mjs";import { chapterIndexInRange, matchesChapterManifest } from "../ui/reader-progress.mjs";// The current MOBI chapter manifest for this five-volume edition contains// cross-volume sidebar targets that point back into volume 1. Its own verified742 unmodified linesreaderContext.chapterManifestLoader = chapterManifestLoader;setChapterToc();await readerContext.getInitialReaderRestoration();const savedChapter = readerContext.readerRestorationEntry?.chapterIndex;const hasSavedChapter = chapterIndexInRange(savedChapter, manifest.chapters.length);const initialChapter = hasSavedChapter ? savedChapter - 1 : 0;const initial = /** @type {import("../../../typings/reader-chapter-format-strict").Chapter} */ (manifest.chapters[initialChapter]);chapterFocusIndex = initial.index;if (initialChapter > 0) ensureSentinel(/** @type {import("../../../typings/reader-chapter-format-strict").Chapter} */ (manifest.chapters[initialChapter - 1]), true);7 unmodified lineschapterScheduler.prefetch(chapterPrefetchIndices());await readerContext.awaitReader(Promise.race([firstChapter, openingLanding.promise]));} catch (error) {if (!hasSavedChapter) throw error;throw Object.assign(new Error("阅读位置恢复失败,原进度已保留,请重试加载。", { cause: error }), {code: "READER_RESTORE"});35 unmodified lines/** @param {import("../../../typings/reader-progress-strict").ProgressState} entry @param {number} generation* @param {number} [progressFraction] A transient slider target, never stored in a bookmark or history entry. */async function restoreChapterPosition(entry, generation, progressFraction) {const loader = readerContext.chapterManifestLoader;if (!loader || !chapterIndexInRange(entry.chapterIndex, loader.count) ||!readerContext.isReaderGenerationCurrent("navigation", generation) ||!matchesChapterManifest(entry.chapterManifest, readerContext.chapterManifestUrl || readerContext.sourceUrl,readerContext.trustedReaderAssetManifestUrl)) return false;const chapter = await loader(entry.chapterIndex);if (!chapter?.isConnected || !readerContext.isReaderGenerationCurrent("navigation", generation)) return false;const viewport = readerContext.viewport, last = entry.chapterIndex === loader.count;
517 unmodified lines5185195205215225235244 unmodified lines529530531532533534535517 unmodified linesfunction sanitizeOfflineHtml(text) {// A global ALLOWED_URI_REGEXP would also strip every non-allow-listed plain// attribute (colspan/rowspan/width), so scope the inline-image rule to URLs.DOMPurify.addHook("uponSanitizeAttribute", restrictOfflineUrlAttribute);let clean;try {clean = DOMPurify.sanitize(text, {4 unmodified linesFORBID_ATTR: ["action", "formaction", "srcdoc"]});} finally {DOMPurify.removeHook("uponSanitizeAttribute", restrictOfflineUrlAttribute);}const template = document.createElement("template");template.content.appendChild(clean);517 unmodified lines5185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495504 unmodified lines555556557558559560561517 unmodified linesfunction sanitizeOfflineHtml(text) {// A global ALLOWED_URI_REGEXP would also strip every non-allow-listed plain// attribute (colspan/rowspan/width), so scope the inline-image rule to URLs.// Use the original document URL, not the proxy, srcdoc, or a supplied <base>./** @type {URL | null} */let base = null;try {const original = new URL(readerContext.downloadUrl || readerContext.sourceUrl);if (/^https?:$/.test(original.protocol) && !original.username && !original.password) {original.hash = "";base = original;}} catch (_) {}/** @param {Element} node @param {{attrName: string, attrValue: string, keepAttr: boolean}} data */const restrict = (node, data) => {if (base && data.attrName === "href" && node.localName === "a") {const value = data.attrValue, hashIndex = value.indexOf("#");if (hashIndex > 0 && !/^(?:[a-z][a-z0-9+.-]*:|\/\/)/i.test(value) &&!/[\u0000-\u001f\u007f-\u009f\\]/.test(value)) {try {const target = new URL(value, base);target.hash = "";// Compare the full URL, including the query, before keeping only the fragment.if (target.href === base.href) data.attrValue = value.slice(hashIndex);} catch (_) {}}}restrictOfflineUrlAttribute(node, data);};DOMPurify.addHook("uponSanitizeAttribute", restrict);let clean;try {clean = DOMPurify.sanitize(text, {4 unmodified linesFORBID_ATTR: ["action", "formaction", "srcdoc"]});} finally {DOMPurify.removeHook("uponSanitizeAttribute", restrict);}const template = document.createElement("template");template.content.appendChild(clean);
3 unmodified lines45678952 unmodified lines6263646566676869707172737475767717 unmodified lines95969798991001013 unmodified linesfrom "./reader-pdf-range-hints.mjs";export const PDF_METADATA_RANGE_CONCURRENCY = 24;const PDF_LARGE_FLAT_BATCH_DELAY_MS = 12;const PDF_LARGE_FLAT_GAP_BUDGET = PDF_LARGE_FLAT_CHUNK_BYTES * 3;52 unmodified linescached = rangeCache?.get(key, begin, Math.min(end, expected.total), {total:expected.total, etag:expected.etag});} catch (_) { /* Cache allocation failure must retain normal network reading. */ }if (cached && expected) return {bytes:cached, total:expected.total, etag:expected.etag};const response = await fetch(options.url, {headers: {Range: `bytes=${begin}-${end-1}`}, signal, credentials:"same-origin"});const invalid = () => new Error("PDF_RANGE_INVALID");try {if (!response.ok) throw Object.assign(new Error(`server response (${response.status})`), {status:response.status});if (!expected && response.status === 200) {if (partialOnly) { await response.body?.cancel(); return null; }const bytes = await readBytes(response, limit);return {bytes, complete:true};}const match = /^bytes (\d+)-(\d+)\/(\d+)$/.exec(response.headers.get("Content-Range") || "");if (response.status !== 206 || !match) throw invalid();17 unmodified linescatch (_) { /* Retaining an optional copy must never fail the document. */ }return {bytes, total, etag, complete:bytes.byteLength === total};} catch (error) {await response.body?.cancel().catch(() => {});throw error;}}3 unmodified lines4567891052 unmodified lines636465666768697071727374757677787980818283848586878817 unmodified lines1061071081091101111121131143 unmodified linesfrom "./reader-pdf-range-hints.mjs";export const PDF_METADATA_RANGE_CONCURRENCY = 24;const PDF_WHOLE_BODY_TIMEOUT_MS = 120000;const PDF_LARGE_FLAT_BATCH_DELAY_MS = 12;const PDF_LARGE_FLAT_GAP_BUDGET = PDF_LARGE_FLAT_CHUNK_BYTES * 3;52 unmodified linescached = rangeCache?.get(key, begin, Math.min(end, expected.total), {total:expected.total, etag:expected.etag});} catch (_) { /* Cache allocation failure must retain normal network reading. */ }if (cached && expected) return {bytes:cached, total:expected.total, etag:expected.etag};const wholeOwner = !expected && !partialOnly ? new AbortController() : null;const active = wholeOwner ? AbortSignal.any([signal, wholeOwner.signal]) : signal;const response = await fetch(options.url, {headers: {Range: `bytes=${begin}-${end-1}`}, signal:active, credentials:"same-origin"});const invalid = () => new Error("PDF_RANGE_INVALID");try {if (!response.ok) throw Object.assign(new Error(`server response (${response.status})`), {status:response.status});if (!expected && response.status === 200) {if (!wholeOwner) { await response.body?.cancel(); return null; }// The fetch policy hands off a 200 at headers. Native PDF staging can// await this body before the Reader's document timer has even started.const timer = setTimeout(() => wholeOwner.abort(new DOMException("PDF whole body timed out", "TimeoutError")),PDF_WHOLE_BODY_TIMEOUT_MS);try {active.throwIfAborted();const bytes = await abortable(readBytes(response, limit), active);active.throwIfAborted();return {bytes, complete:true};} finally { clearTimeout(timer); }}const match = /^bytes (\d+)-(\d+)\/(\d+)$/.exec(response.headers.get("Content-Range") || "");if (response.status !== 206 || !match) throw invalid();17 unmodified linescatch (_) { /* Retaining an optional copy must never fail the document. */ }return {bytes, total, etag, complete:bytes.byteLength === total};} catch (error) {const cancelled = response.body?.cancel().catch(() => {});// A failed whole-body read must settle without waiting for stream cleanup.if (!wholeOwner || response.status !== 200) await cancelled;throw error;}}
189 unmodified lines19019119219319419586 unmodified lines2822832842852862873 unmodified lines2912922932942952962972 unmodified lines300301302303304305189 unmodified linesremove.setAttribute("aria-label", `删除书签:${open.textContent}`);remove.addEventListener("click", async () => {await VoiceOfMLReaderStore.removeBookmark(entry.id);const restoreFocus = row.contains(document.activeElement);const next = row.nextElementSibling?.querySelector("button") || row.previousElementSibling?.querySelector("button") ||readerContext.bookmarksAllButton;86 unmodified linesfunction openBookmarkPopover(invoker = readerContext.bookmarkRibbon, entry = null) {if (!entry && readerContext.pdfDocument?._pdfInfo?.readerPageCountPending) return;if (!readerContext.bookmarkPopover.hidden) return;readerContext.bookmarkInvoker = invoker;readerContext.pendingBookmarkSnapshot = entry ? null : readerContext.captureBookmarkSnapshot();readerContext.updatePanelState({ editingBookmark: entry ? { ...entry } : null });3 unmodified lines: `在${snapshot.label}添加书签?`;readerContext.bookmarkLabelInput.value = snapshot.label || "";readerContext.bookmarkExcerptInput.value = typeof snapshot.excerpt === "string" ? snapshot.excerpt : "";/** @type {HTMLElement} */ (document.querySelector("#bookmark-add")).textContent = entry ? "保存书签" : "添加书签";readerContext.bookmarkPopover.hidden = false;invoker.setAttribute("aria-expanded", "true");invoker.setAttribute("aria-controls", readerContext.bookmarkPopover.id);2 unmodified lines}function closeBookmarkPopover() {readerContext.pendingBookmarkSnapshot = null;readerContext.updatePanelState({ editingBookmark: null });readerContext.bookmarkPopover.hidden = true;189 unmodified lines19019119219319419519619719819920086 unmodified lines2872882892902912922933 unmodified lines2972982993003013023033043052 unmodified lines308309310311312313314189 unmodified linesremove.setAttribute("aria-label", `删除书签:${open.textContent}`);remove.addEventListener("click", async () => {await VoiceOfMLReaderStore.removeBookmark(entry.id);if (!readerContext.isReaderGenerationCurrent("bookmarks", generation)) {// A scope switch or remote refresh can replace this row with a stale copy.await renderBookmarks();return;}const restoreFocus = row.contains(document.activeElement);const next = row.nextElementSibling?.querySelector("button") || row.previousElementSibling?.querySelector("button") ||readerContext.bookmarksAllButton;86 unmodified linesfunction openBookmarkPopover(invoker = readerContext.bookmarkRibbon, entry = null) {if (!entry && readerContext.pdfDocument?._pdfInfo?.readerPageCountPending) return;if (!readerContext.bookmarkPopover.hidden) return;readerContext.nextReaderGeneration("bookmark-dialog");readerContext.bookmarkInvoker = invoker;readerContext.pendingBookmarkSnapshot = entry ? null : readerContext.captureBookmarkSnapshot();readerContext.updatePanelState({ editingBookmark: entry ? { ...entry } : null });3 unmodified lines: `在${snapshot.label}添加书签?`;readerContext.bookmarkLabelInput.value = snapshot.label || "";readerContext.bookmarkExcerptInput.value = typeof snapshot.excerpt === "string" ? snapshot.excerpt : "";const save = /** @type {HTMLButtonElement} */ (document.querySelector("#bookmark-add"));save.textContent = entry ? "保存书签" : "添加书签";save.disabled = false;readerContext.bookmarkPopover.hidden = false;invoker.setAttribute("aria-expanded", "true");invoker.setAttribute("aria-controls", readerContext.bookmarkPopover.id);2 unmodified lines}function closeBookmarkPopover() {readerContext.nextReaderGeneration("bookmark-dialog");readerContext.pendingBookmarkSnapshot = null;readerContext.updatePanelState({ editingBookmark: null });readerContext.bookmarkPopover.hidden = true;
1234123 unmodified lines128129130131132133134135176 unmodified lines312313314315316317/** @param {import('../../../typings/reader-progress-strict').ProgressContext} readerContext */export function createReaderProgress(readerContext) {function scheduleSave() {if (readerContext.readerLifecycle.disposed || readerContext.readerAbortController.signal.aborted) return;123 unmodified linesconst currentEntry = (entry) => {if (readerContext.capability.mode === "epub-chapters" &&/-epub-chapters-v5\//.test(readerContext.chapterManifestUrl || readerContext.sourceUrl) &&entry?.chapterManifest !== (readerContext.chapterManifestUrl || readerContext.sourceUrl)) return null;return entry;};176 unmodified lines/** @param {import('../../../typings/reader-progress-strict').ProgressState | null} entry* @param {number} generation */async function applyInitialRestoration(entry, generation) {readerContext.updateDocumentState({ restoredEntry: entry });// Startup already applied the current zoom. Reapplying an identical saved// value needlessly invalidates PDF canvases and lays out every format again.123456789101112131415161718192021222324123 unmodified lines148149150151152153154155176 unmodified lines332333334335336337338339340341/** @param {number | undefined} index @param {number} count @returns {index is number} */export function chapterIndexInRange(index, count) {return index !== undefined && Number.isInteger(index) && index >= 1 && index <= count;}/** @param {string | undefined} saved @param {string} current* @param {(url: string) => string | null} trustedManifestUrl */export function matchesChapterManifest(saved, current, trustedManifestUrl) {if (saved === current) return true;// Legacy v5 required an exact identity, including for direct bookmark restores.if (/-epub-chapters-v5\//.test(current)) return false;// Otherwise older positions can still restore if their chapter is in range.if (typeof saved !== "string" || !saved) return true;const previous = trustedManifestUrl(saved), active = trustedManifestUrl(current);// The trusted resolver fixes the bucket and endpoint. Compare non-empty object// paths, including the version, without mistaking URL spelling for a revision.const savedPath = previous && new URL(previous).searchParams.get("path");return !!savedPath && !!active && savedPath === new URL(active).searchParams.get("path");}/** @param {import('../../../typings/reader-progress-strict').ProgressContext & Pick<import('../../../typings/reader-chapter-format-strict').ChapterFormatContext, 'trustedReaderAssetManifestUrl'>} readerContext */export function createReaderProgress(readerContext) {function scheduleSave() {if (readerContext.readerLifecycle.disposed || readerContext.readerAbortController.signal.aborted) return;123 unmodified linesconst currentEntry = (entry) => {if (readerContext.capability.mode === "epub-chapters" &&entry && !matchesChapterManifest(entry.chapterManifest, readerContext.chapterManifestUrl || readerContext.sourceUrl,readerContext.trustedReaderAssetManifestUrl)) return null;return entry;};176 unmodified lines/** @param {import('../../../typings/reader-progress-strict').ProgressState | null} entry* @param {number} generation */async function applyInitialRestoration(entry, generation) {// Ignore stale indices, not failures to load a chapter that still exists.const loader = readerContext.chapterManifestLoader, index = entry?.chapterIndex;if (readerContext.capability.mode === "epub-chapters" && loader && Number.isInteger(index) &&!chapterIndexInRange(index, loader.count)) entry = null;readerContext.updateDocumentState({ restoredEntry: entry });// Startup already applied the current zoom. Reapplying an identical saved// value needlessly invalidates PDF canvases and lays out every format again.
480 unmodified lines481482483484485486487488480 unmodified linesassert_source_contains(self, 'frame.setAttribute("sandbox", "allow-same-origin")', reader)self.assertIn('"script"', reader)assert_source_contains(self, 'const OFFLINE_INLINE_IMAGE = /^data:image', reader)assert_source_contains(self, 'DOMPurify.addHook("uponSanitizeAttribute", restrictOfflineUrlAttribute)', reader)assert_source_contains(self, 'DOMPurify.removeHook("uponSanitizeAttribute", restrictOfflineUrlAttribute)', reader)assert_source_contains(self, 'template.content.querySelectorAll("style")', reader)assert_source_contains(self, 'template.content.querySelectorAll("[style]")', reader)self.assertIn('/^\\/datasets\\/VoiceOfML\\/[^/]+\\/(resolve|raw)\\//.test(url.pathname)', reader)480 unmodified lines481482483484485486487488489490480 unmodified linesassert_source_contains(self, 'frame.setAttribute("sandbox", "allow-same-origin")', reader)self.assertIn('"script"', reader)assert_source_contains(self, 'const OFFLINE_INLINE_IMAGE = /^data:image', reader)assert_source_contains(self, 'if (target.href === base.href) data.attrValue = value.slice(hashIndex)', reader)assert_source_contains(self, 'restrictOfflineUrlAttribute(node, data);', reader)assert_source_contains(self, 'DOMPurify.addHook("uponSanitizeAttribute", restrict)', reader)assert_source_contains(self, 'DOMPurify.removeHook("uponSanitizeAttribute", restrict)', reader)assert_source_contains(self, 'template.content.querySelectorAll("style")', reader)assert_source_contains(self, 'template.content.querySelectorAll("[style]")', reader)self.assertIn('/^\\/datasets\\/VoiceOfML\\/[^/]+\\/(resolve|raw)\\//.test(url.pathname)', reader)
10 unmodified lines111213141516172169 unmodified lines218721882189219021912192152 unmodified lines234523462347234823492350235123522353235410 unmodified linesfrom collections import OrderedDictfrom types import SimpleNamespacefrom unittest.mock import AsyncMock, Mock, patchfrom urllib.parse import unquote, urlencodeIMPORT_ERROR = Nonetry:2169 unmodified linesself.assertEqual(len(session.urls), 3)self.assertEqual(state.upstream_semaphore._value, 1)async def test_reader_range_age_limits_exact_and_containing_hits(self):url = "https://huggingface.co/datasets/VoiceOfML/Test/resolve/main/document.pdf"state = app.app.state152 unmodified linesreturn candidate# A fresh attempt fails under the restrictive redirect policy; an exact# or contained cached response must never use the looser policy.for requested in ("bytes=0-3", "bytes=1-2"):session.responses = [FakeResponse(302, {"Location":storage})]response = await app._stream_reader_document(SimpleNamespace(method="GET",headers={"Range":requested}),url,url_validator=source_only)self.assertEqual(response.status_code,502)self.assertIn(b"storage redirect not authorized",response.body)self.assertEqual(state.upstream_semaphore._value,1)10 unmodified lines111213141516172169 unmodified lines2187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238152 unmodified lines2391239223932394239523962397239823992400240110 unmodified linesfrom collections import OrderedDictfrom types import SimpleNamespacefrom unittest.mock import AsyncMock, Mock, patchfrom urllib.parse import quote, unquote, urlencodeIMPORT_ERROR = Nonetry:2169 unmodified linesself.assertEqual(len(session.urls), 3)self.assertEqual(state.upstream_semaphore._value, 1)async def test_reader_reload_and_conditions_resolve_moved_hf_source(self):source = "https://huggingface.co/datasets/VoiceOfML/MLMRL-Hub/resolve/main/" + quote("001643/学点逻辑.pdf")old = "https://us.aws.cdn.hf.co/old-object?Expires=2100000000"new = "https://us.aws.cdn.hf.co/new-object?Expires=2100000000"state = app.app.stateasync def get(url, **options):headers = options["headers"]if url == source:return FakeResponse(302, {"Location": target})if url == old:if any(name in headers for name in ("If-None-Match", "If-Modified-Since")):return FakeResponse(304, {"ETag": '"old"'}, chunks=())if headers.get("If-Range") == '"old"':return FakeResponse(206, {"ETag": '"old"', "Content-Range": "bytes 0-1/3"}, chunks=(b"ol",))return FakeResponse(200, {"ETag": '"old"'}, chunks=(b"old",))self.assertEqual(url, new)return FakeResponse(200, {"ETag": '"new"'}, chunks=(b"new",))for headers in ({"Cache-Control": "no-cache"}, {"Cache-Control": "no-store"},{"Cache-Control": "max-age=0"}, {"Pragma": "no-cache"},{"If-None-Match": '"old"'}, {"If-Modified-Since": "Tue, 25 Aug 2026 00:00:00 GMT"},{"Range": "bytes=0-1", "If-Range": '"old"'},):with self.subTest(headers=headers):upstream_http.upstream_redirect_cache.clear()opener = AsyncMock(side_effect=get)state.http_session = SimpleNamespace(get=opener)target = oldfor _ in range(2):ordinary = await app.api_reader_content(SimpleNamespace(method="GET", headers={}), source)self.assertEqual([chunk async for chunk in ordinary.body_iterator], [b"old"])cached = upstream_http.upstream_redirect_cache[("GET", source)]target = newresponse = await app.api_reader_content(SimpleNamespace(method="GET", headers=headers), source)body = [chunk async for chunk in response.body_iterator] if hasattr(response, "body_iterator") else []self.assertEqual(response.status_code, 200)self.assertEqual(body, [b"new"])self.assertEqual([call.args[0] for call in opener.await_args_list], [source, old, old, source, new])for call in opener.await_args_list[-2:]:self.assertEqual(call.kwargs["headers"], {"Accept-Encoding": "identity", **headers})self.assertEqual(upstream_http.upstream_redirect_cache[("GET", source)], cached)self.assertEqual(state.upstream_semaphore._value, 1)async def test_reader_range_age_limits_exact_and_containing_hits(self):url = "https://huggingface.co/datasets/VoiceOfML/Test/resolve/main/document.pdf"state = app.app.state152 unmodified linesreturn candidate# A fresh attempt fails under the restrictive redirect policy; an exact# or contained cached response must never use the looser policy.for headers in ({"Range": "bytes=0-3"}, {"Range": "bytes=1-2"},{"Range": "bytes=0-3", "Cache-Control": "no-cache"}):session.responses = [FakeResponse(302, {"Location":storage})]response = await app._stream_reader_document(SimpleNamespace(method="GET", headers=headers), url, url_validator=source_only)self.assertEqual(response.status_code,502)self.assertIn(b"storage redirect not authorized",response.body)self.assertEqual(state.upstream_semaphore._value,1)
238 unmodified lines239240241242243244238 unmodified linesself.page.wait_for_function("()=>!document.querySelector('#bookmarks-list .panel-item')")self.assertEqual(self.page.evaluate('document.activeElement.id'), 'bookmarks-all')def test_failure_is_announced_without_stealing_keyboard_focus(self):self.open_book('unsupported', 'not supported')self.assertEqual(self.page.get_by_role('alert').count(), 1)238 unmodified lines239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309238 unmodified linesself.page.wait_for_function("()=>!document.querySelector('#bookmarks-list .panel-item')")self.assertEqual(self.page.evaluate('document.activeElement.id'), 'bookmarks-all')def test_pending_bookmark_delete_survives_switch_to_all_bookmarks(self):self.open_book('txt', 'A document\n' * 200)self.page.evaluate('''async () => {const url = new URL(location.href).searchParams.get('url');await VoiceOfMLReaderStore.putBookmark({id:'one', url, label:'Remove me', title:'This book'});await VoiceOfMLReaderStore.putBookmark({id:'two', url:url+'/other', label:'Keep me', title:'Other book'});const store = VoiceOfMLReaderStore;window.VoiceOfMLReaderStore = {...store, async removeBookmark(id) {await new Promise(resolve => { window.releaseBookmarkDelete = resolve; });await store.removeBookmark(id);window.bookmarkDeleteCompleted = true;}};}''')self.page.locator('#history').press('Enter')self.page.locator('#bookmarks-tab').press('Enter')self.page.get_by_role('button', name='删除书签:Remove me', exact=True).click()self.page.wait_for_function('() => typeof window.releaseBookmarkDelete === "function"')toggle = self.page.locator('#bookmarks-all')toggle.click()self.page.get_by_role('button', name='Other book · Keep me', exact=True).wait_for()self.page.evaluate('window.releaseBookmarkDelete()')self.page.wait_for_function('() => window.bookmarkDeleteCompleted === true')self.page.locator('#bookmarks-list [data-bookmark-id="one"]').wait_for(state='detached', timeout=2500)self.assertTrue(self.page.get_by_role('button', name='Other book · Keep me', exact=True).is_visible())self.assertTrue(toggle.evaluate('node => node === document.activeElement'))def check_stale_bookmark_save(self, reject):self.open_book('txt', 'A document\n' * 200)self.page.evaluate('''reject => {const store = VoiceOfMLReaderStore;window.VoiceOfMLReaderStore = {...store, async putBookmark(entry) {await new Promise(resolve => { window.releaseBookmarkSave = resolve; });if (reject) throw new Error('Delayed save failure');await store.putBookmark(entry);}};}''', reject)ribbon = self.page.locator('#bookmark-ribbon')label = self.page.locator('#bookmark-label')ribbon.click()label.fill('First bookmark')self.page.locator('#bookmark-add').click()self.page.wait_for_function('() => typeof window.releaseBookmarkSave === "function"')self.page.locator('#bookmark-cancel').click()ribbon.click()label.fill('Second draft')prompt = self.page.locator('#bookmark-prompt').text_content()self.page.evaluate('window.releaseBookmarkSave()')# Wait for a real write on success. On rejection, let the rejected# promise and the original save handler drain before inspecting UI.if not reject:self.page.wait_for_function('''async () => (await VoiceOfMLReaderStore.listAllBookmarks()).some(entry => entry.label === 'First bookmark')''')self.page.evaluate('() => new Promise(resolve => requestAnimationFrame(() => requestAnimationFrame(resolve)))')self.assertTrue(self.page.get_by_role('dialog').is_visible())self.assertEqual(self.page.locator('#bookmark-prompt').text_content(), prompt)self.assertEqual(label.input_value(), 'Second draft')self.assertTrue(label.evaluate('node => node === document.activeElement'))self.assertTrue(self.page.locator('#bookmark-add').is_enabled())def test_stale_bookmark_save_does_not_close_new_editor(self):self.check_stale_bookmark_save(reject=False)def test_stale_bookmark_save_error_does_not_change_new_editor(self):self.check_stale_bookmark_save(reject=True)def test_failure_is_announced_without_stealing_keyboard_focus(self):self.open_book('unsupported', 'not supported')self.assertEqual(self.page.get_by_role('alert').count(), 1)
7 unmodified lines89101112137 unmodified linessetUpClass = classmethod(support.PdfFollowupTests.setUpClass.__func__)setUp = support.PdfFollowupTests.setUpdef test_successful_toc_jump_owns_open_before_old_chapter_fails(self):source = ('https://voiceofml-search.hf.space/api/reader-bucket-resource?path=chapters/ebook/epub/'+ 'a' * 64 + '/1234567890abcdef/chapter-manifest.json')7 unmodified lines89101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081827 unmodified linessetUpClass = classmethod(support.PdfFollowupTests.setUpClass.__func__)setUp = support.PdfFollowupTests.setUpdef open_with_saved_chapter(self, index, manifest_revision, bookmark=False):source = 'https://huggingface.co/datasets/VoiceOfML/Test/resolve/main/restore.epub'endpoint = 'https://voiceofml-search.hf.space/api/reader-bucket-resource?'path = 'chapters/ebook/epub/' + 'a' * 64 + '/1234567890abcdef/chapter-manifest.json'manifest_url = endpoint + 'path=' + pathmanifest = {'version': 1, 'kind': 'epub-chapters', 'chapters': [{'index': i, 'path': f'chapters/chapter-{i:04d}.xhtml'} for i in (1, 2)]}self.page.route('**/api/reader-bucket-resource**', lambda route: route.fulfill(json=manifest)if 'chapter-manifest.json' in route.request.url else route.fulfill(content_type='text/html', body='<h1>Chapter</h1><p style="height:1600px">Text</p>'))reader_url = self.origin + support.PREFIX + '/static/reader.html'self.page.goto(reader_url)entry = {'url': source, 'chapterIndex': index, 'chapterOffset': 180}if manifest_revision == 'old':entry['chapterManifest'] = endpoint + urlencode({'path': path.replace('1234567890abcdef', '0123456789abcdef')})elif manifest_revision == 'current':# Same object as the current URL, but with an encoded path query value.entry['chapterManifest'] = endpoint + urlencode({'path': path})params = dict(url=source, ext='epub-chapters', chapter_manifest=manifest_url)if bookmark:entry['id'] = 'chapter-regression'params.update(bookmark=entry['id'], bookmark_source=source)self.page.evaluate('entry => entry.id ? VoiceOfMLReaderStore.putBookmark(entry) : VoiceOfMLReaderStore.put(entry)', entry)self.page.goto(reader_url + '?' + urlencode(params))self.page.wait_for_function("()=>document.documentElement.dataset.readerPhase==='ready' || ""document.querySelector('.reader-error')")self.assertEqual(self.page.locator('html').get_attribute('data-reader-phase'), 'ready',self.page.locator('.reader-error').all_text_contents())self.page.unroute('**/api/reader-bucket-resource**')return self.page.evaluate('__ebook.captureChapter()')def test_obsolete_chapter_progress_does_not_block_opening(self):self.expose()for index, revision in [(9, 'old'), (9, 'current'), (9, None), (2, 'old')]:with self.subTest(index=index, revision=revision):self.assertEqual(self.open_with_saved_chapter(index, revision)['chapterIndex'], 1)def test_matching_chapter_positions_keep_their_offset(self):self.expose()for revision, bookmark in [(None, False), ('current', True)]:with self.subTest(revision=revision, bookmark=bookmark):position = self.open_with_saved_chapter(2, revision, bookmark)self.assertEqual(position['chapterIndex'], 2)self.assertAlmostEqual(position['chapterOffset'], 180, delta=2)def test_legacy_v5_bookmark_requires_exact_manifest(self):self.page.goto(self.origin + support.PREFIX + '/static/reader.html')self.assertEqual(self.page.evaluate('''async () => {const {createReaderChapterFormat} = await import('./reader/formats/reader-chapter-format.mjs');const {createReaderProgress, matchesChapterManifest} = await import('./reader/ui/reader-progress.mjs');const manifest = 'https://example.test/book-epub-chapters-v5/chapter-manifest.json';const url = 'https://example.test/book.epub', params = new URLSearchParams({bookmark:'v5', bookmark_source:url});let loads = 0;const context = {sourceUrl:url, chapterManifestUrl:manifest, capability:{mode:'epub-chapters'}, params,chapterManifestLoader:Object.assign(async () => { loads++; return null; }, {count:2}),isReaderGenerationCurrent:() => true, trustedReaderAssetManifestUrl:() => null};const {restoreChapterPosition} = createReaderChapterFormat(context);const {loadReaderRestoration} = createReaderProgress(context);const rows = [];for (const saved of [undefined, '', manifest + '?ignored=1', manifest]) {const bookmark = {id:'v5', url, chapterIndex:2, chapterManifest:saved};await VoiceOfMLReaderStore.putBookmark(bookmark);rows.push([!!(await loadReaderRestoration()), await restoreChapterPosition(bookmark, 0), loads]);}// Not an admitted shape today; an absent object path is never an identity match.return [rows, matchesChapterManifest('old', 'new', url => 'https://example.test/' + url)];}'''), [[[False, False, 0], [False, False, 0], [False, False, 0], [True, False, 1]], False])def test_successful_toc_jump_owns_open_before_old_chapter_fails(self):source = ('https://voiceofml-search.hf.space/api/reader-bucket-resource?path=chapters/ebook/epub/'+ 'a' * 64 + '/1234567890abcdef/chapter-manifest.json')
2923 unmodified lines2924292529262927292829292923 unmodified linesself.assertEqual(result, {"policy": True, "violations": ["img-src"]})self.assertNotIn("https://img.remote.test/a.png", remote)def frame_host_reader(self, overlay=False, cross_origin=False):# The Reader must decide by its real host whether parent messages are handled.reader = self.reader_url(name="framed", path="Test/docs")2923 unmodified lines2924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562923 unmodified linesself.assertEqual(result, {"policy": True, "violations": ["img-src"]})self.assertNotIn("https://img.remote.test/a.png", remote)def test_offline_html_relative_same_document_links_jump_without_navigation(self):self.serve('''<!doctype html><body><a id="relative" href="./report.html#methods">Methods (relative)</a><a id="fragment" href="#methods">Methods</a><a id="other-file" href="./appendix.html#methods">Appendix</a><a id="same-name" href="../report.html#methods">Other report</a><a id="other-query" href="./report.html?edition=2#methods">Other edition</a><p style="height: 1800px">Introduction</p><h2 id="methods">Methods</h2><p style="height: 1200px">Details</p></body>''', "text/html")self.open(self.reader_url("html", "books/report"))frame = self.page.locator("iframe.html-frame").element_handle().content_frame()history_length = self.page.evaluate("history.length")reader_url = self.page.urlfor link_id in ("other-file", "same-name", "other-query"):self.assertIsNone(frame.locator(f"#{link_id}").get_attribute("href"), link_id)for link_id in ("relative", "fragment"):with self.subTest(link=link_id):frame.evaluate("scrollTo(0, 0)")link = frame.locator(f"#{link_id}")self.assertEqual(link.get_attribute("href"), "#methods")link.click()frame.wait_for_function("Math.abs(document.querySelector('#methods').getBoundingClientRect().top) < 2")self.assertEqual(frame.url, "about:srcdoc")self.assertEqual(self.page.url, reader_url)self.assertEqual(self.page.evaluate("history.length"), history_length)def frame_host_reader(self, overlay=False, cross_origin=False):# The Reader must decide by its real host whether parent messages are handled.reader = self.reader_url(name="framed", path="Test/docs")
12345650 unmodified lines575859606162import assert from 'node:assert/strict';import {mock} from 'node:test';import {createPdfFetchPolicy} from '../../../static/reader/pdf/reader-pdf-network.mjs';// Local transport fixture only: no upstream connection is made.globalThis.location = {href:'https://reader.test/'};50 unmodified lines}try {// A genuine 429 triggers one bounded retry after the shared pause, then a// correctly versioned body is delivered without reopening the document.{12345650 unmodified lines57585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114import assert from 'node:assert/strict';import {mock} from 'node:test';import {createPdfFetchPolicy, preparePdfInitialRange} from '../../../static/reader/pdf/reader-pdf-network.mjs';// Local transport fixture only: no upstream connection is made.globalThis.location = {href:'https://reader.test/'};50 unmodified lines}try {// Native PDF staging awaits the bootstrap before the outer Reader timer// exists. When the first Range gets a 200, the policy hands off the body.for (const scenario of ['stall','close','complete']) await withClock(async advance=>{const owner=new AbortController(), requests=[];const closeReason=new DOMException('caller closed','AbortError'), bodyDeadline=120000;let body, upstream, waitingForMore=false, outcome;globalThis.fetch=async (_input,init)=>{requests.push(new Headers(init.headers).get('Range'));upstream=init.signal;return new Response(new ReadableStream({start(controller){body=controller;controller.enqueue(bytes.slice(0,2));upstream.addEventListener('abort',()=>controller.error(upstream.reason),{once:true});},pull(){waitingForMore=true;}},{highWaterMark:0}),{status:200});};const policy=createPdfFetchPolicy(opts);policy.add(['/a.pdf']);try {const url=new URL('/a.pdf',globalThis.location.href).href;void preparePdfInitialRange({url,rangeChunkSize:2},{signal:owner.signal,limit:64,rangeCache:null,readBytes:async response=>new Uint8Array(await response.arrayBuffer())}).then(first=>{outcome={first};},error=>{outcome={error};});await advance(0);assert.deepEqual(requests,['bytes=0-1']);assert.equal(waitingForMore,true,'the body has already delivered bytes and is waiting for more');await advance(scenario==='close' ? 1 : bodyDeadline-1);assert.equal(outcome,undefined,'the bootstrap must not settle early or publish a prefix');assert.equal(upstream.aborted,false);if (scenario==='stall') {await advance(1);assert.equal(outcome?.error?.name,'TimeoutError','the 200 body must time out before the outer Reader timer starts');assert.equal(upstream.aborted,true);assert.equal(upstream.reason,outcome.error);assert.equal(owner.signal.aborted,false);} else if (scenario==='close') {owner.abort(closeReason);await advance(0);assert.equal(outcome?.error,closeReason);assert.equal(upstream.reason,closeReason);} else {body.enqueue(bytes.slice(2));body.close();await advance(0);assert.equal(outcome?.first?.complete,true);assert.deepEqual(outcome.first.bytes,bytes);await advance(1);assert.equal(upstream.aborted,false,'completion clears the body deadline');}assert.deepEqual(requests,['bytes=0-1'],'the bootstrap needs no second request');} finally {owner.abort(closeReason);policy.dispose();}});// A genuine 429 triggers one bounded retry after the shared pause, then a// correctly versioned body is delivered without reopening the document.{
12345213 unmodified lines219220221222223"""Exercise the actual IndexedDB session adapter in Chromium."""import unittestfrom tests.reader.browser import test_reader_pdf_followup as support213 unmodified linesself.assertNotIn("voiceofml-search-state", result["databases"])if __name__ == "__main__":unittest.main()1234567891011213 unmodified lines225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304"""Exercise IndexedDB sessions and filter result snapshots in Chromium."""import mimetypesimport osfrom pathlib import Pathimport unittestfrom urllib.parse import urlsplitfrom playwright.sync_api import sync_playwrightfrom tests.reader.browser import test_reader_pdf_followup as support213 unmodified linesself.assertNotIn("voiceofml-search-state", result["databases"])class FilterSnapshotBrowserTests(unittest.TestCase):def test_mirror_toggle_does_not_restore_pdf_for_txt_filter(self):root = Path(__file__).resolve().parents[3]origin = 'https://search-fixture.test'prefix = ''entry = '/?q=ownership'requests = []inventory = [{'name': ext, 'count': 1} for ext in ('pdf', 'txt')]rows = [dict(Repo='VoiceOfML/Test', File='ownership', Extension=ext, Folder=[], Size=1)for ext in ('pdf', 'txt')]def fulfill(route):url = urlsplit(route.request.url)path = url.pathif path == '/api/search' and route.request.method == 'POST':body = route.request.post_data_jsonextensions = body.get('extensions', [])requests.append(extensions)results = [row for row in rows if not extensions or row['Extension'] in extensions]route.fulfill(json=dict(results=results, total=len(results), page=1, page_size=body['page_size']),headers={'Access-Control-Allow-Origin': '*'})elif path == '/api/search' and route.request.method == 'OPTIONS':route.fulfill(status=204, headers={'Access-Control-Allow-Origin': '*','Access-Control-Allow-Headers': 'content-type'})elif path.startswith('/api/'):data = {'/api/extensions': inventory, '/api/repos': [],'/api/bootstrap': {'repos': [], 'extensions': inventory}}route.fulfill(json=data.get(path, {}), headers={'Access-Control-Allow-Origin': '*'})elif url.hostname == 'search-fixture.test' and path == prefix + '/':route.fulfill(path=root / 'static/index.html', content_type='text/html')elif url.hostname == 'search-fixture.test' and path.startswith(prefix + '/static/'):asset = root / path.removeprefix(prefix).lstrip('/')if asset.is_file():route.fulfill(path=asset, content_type=mimetypes.guess_type(asset)[0])else:route.fulfill(status=404)else:route.abort()with sync_playwright() as playwright:browser = playwright.chromium.launch(executable_path=os.getenv('CHROMIUM_PATH'),args=['--disable-background-networking', '--host-resolver-rules=MAP * ~NOTFOUND'])context = browser.new_context(service_workers='block', viewport={'width': 1280, 'height': 800})context.route('**/*', fulfill)page = context.new_page()errors = []page.on('pageerror', lambda error: errors.append(str(error)))page.add_init_script("Object.defineProperty(navigator, 'onLine', {get: () => true});")page.goto(origin + entry, wait_until='domcontentloaded')txt = page.locator('#filter-ext-list input[value="txt"]')txt.wait_for(state='attached', timeout=5000)pdf_row = page.locator('.result-item[aria-label="ownership.pdf"]')pdf_copy = pdf_row.locator('[data-action="copy"]')self.assertIn('hf-mirror.com', pdf_copy.get_attribute('data-link', timeout=5000))page.clock.install()page.clock.pause_at(page.evaluate('Date.now() + 100'))txt.evaluate('input => input.click()')self.assertTrue(page.evaluate('filterSearchTimer !== null'))page.locator('#mirror-links-toggle').evaluate('input => input.click()')self.assertEqual(urlsplit(pdf_copy.get_attribute('data-link')).hostname, 'huggingface.co')self.assertEqual(requests, [[]])page.clock.run_for(200)page.clock.resume()page.wait_for_function('filterSearchTimer === null && !STATE.isLoading', timeout=5000)self.assertEqual((page.locator('.result-item').evaluate_all('rows => rows.map(row => row.ariaLabel)'), requests),(['ownership.txt'], [[], ['txt']]),)self.assertEqual(errors, [])context.close()browser.close()if __name__ == "__main__":unittest.main()
backend/reader/document/http/transport.py+3-1
quality/reviewed-audit-source-transition.json+12-2
scripts/backend_paths.py+1-1
static/app.js+7-2
static/reader/core/reader-bindings.mjs+6-2
static/reader/formats/reader-chapter-format.mjs+9-11
static/reader/formats/reader-html-format.mjs+28-2
static/reader/pdf/reader-pdf-network.mjs+18-5
static/reader/ui/reader-bookmarks.mjs+10-1
static/reader/ui/reader-progress.mjs+27-3
tests/gates/test_static_contract.py+4-2
tests/proxy/test_async_proxy.py+50-3
tests/reader/browser/test_reader_accessibility_browser.py+65
tests/reader/browser/test_reader_ebook_flow.py+69
tests/reader/browser/test_reader_refactor.py+27
tests/reader/pdf-network/test_reader_pdf_backpressure.mjs+53-1
tests/search/browser/test_search_session_browser.py+82-1