Search / tests /reader /core /test_reader_regression.js
vomebook
Integrate AVIF dual reads with current Space release gates
e6e90f2
Raw History Blame Contribute Delete
37.7 kB
const fs = require('fs')
const path = require('path')
const assert = require('assert')
const vm = require('vm')
const { TextEncoder } = require('util')
const { assertCode, readReaderSource } = require('../../support/reader_source_contract')
const root = path.resolve(__dirname, '../../..')
const reader = readReaderSource(root)
const contract = fs.readFileSync(path.join(root, 'static/reader/core/reader-contract.js'), 'utf8')
const sandbox = { self: {}, TextEncoder, URLSearchParams, URL }
vm.runInNewContext(contract, sandbox)
const pdfText = {}
vm.runInNewContext(fs.readFileSync(path.join(root, 'static/reader/pdf/reader-pdf-text.js'), 'utf8').replace(/^export /gm, ''), pdfText)
for (const [raw, expected] of [
['', ''], ['hello world', 'hello world'], ['a\n b', 'a\n b'],
['\u624b \u673a', '\u624b\u673a'], ['\u624b\u3002\u673a', '\u624b\u3002\u673a'],
['\u6bdb \u6cfd\n\u4e1c hello world', '\u6bdb\u6cfd\u4e1c hello world'],
['\ud840\udc00 \ud840\udc01', '\ud840\udc00\ud840\udc01'],
['\u624b\t\n \u673a a b \u624b \u673a', '\u624b\u673a a b \u624b\u673a'],
]) {
for (let repeat = 0; repeat < 3; repeat++) {
assert.strictEqual(pdfText.normalizePdfSearchText(raw), expected)
const mapped = pdfText.pdfSearchText(raw)
assert.strictEqual(mapped.text, expected)
assert.strictEqual(Array.from({length: mapped.text.length}, (_, index) => raw[pdfText.pdfSourceOffset(mapped, index)]).join(''), expected)
}
}
const unchanged = pdfText.pdfSearchText('unchanged text '.repeat(10000))
assert.strictEqual(unchanged.offsets, null)
const sparse = pdfText.pdfSearchText('prefix '.repeat(10000) + '\u624b \u673a' + ' suffix'.repeat(10000))
assert.strictEqual(sparse.offsets.byteLength, 8)
for (const raw of ['\u624b \u673a \u624b\n\u673a', '\ud840\udc00 \ud840\udc01\r\n\u624b \u673a']) {
const deleted = new Set()
for (const match of raw.matchAll(/(?<=\p{Script=Han})\s+(?=\p{Script=Han})/gu))
for (let i=match.index;i<match.index+match[0].length;i++) deleted.add(i)
const oracle = Array.from({length:raw.length}, (_,i)=>i).filter(i=>!deleted.has(i))
const mapped = pdfText.pdfSearchText(raw)
assert.deepStrictEqual(Array.from({length:mapped.text.length}, (_,i)=>pdfText.pdfSourceOffset(mapped,i)), oracle)
}
// Dense vertical pages must measure every attached run before writing any
// final scale. A fake DOM makes forced-layout ordering deterministic.
class TextElement {
constructor(tag, owner) {
this.tagName = tag; this.ownerDocument = owner; this.children = [];
this.dataset = {}; this.className = ''; this.textContent = '';
this.style = { setProperty(key,value) { this[key] = value; } };
}
appendChild(node) { this.children.push(node); return node; }
replaceChildren(fragment) { this.children = fragment.children; }
querySelector(selector) { return selector === '.reader-pdf-text-run'
? this.children.find(child => child.className === 'reader-pdf-text-run') : null; }
querySelectorAll(selector) {
const found = [];
const walk = node => {
if (node.className === selector.slice(1)) found.push(node);
for (const child of node.children || []) walk(child);
};
for (const child of this.children) walk(child);
return found;
}
get offsetHeight() { this.ownerDocument.events.push('read'); return this.measuredHeight ?? 24; }
}
const fakeDoc = {
events: [],
createElement(tag) {
if (tag === 'canvas') return {getContext:()=>({measureText:()=>({width:200})})};
return new TextElement(tag,this);
},
createDocumentFragment() { return new TextElement('fragment',this); },
createTextNode(text) { return {textContent:text}; },
defaultView: {getComputedStyle(run) { return {fontSize: run.measuredHeight === 0 ? '0px' : '12px'}; }}
};
function textLayer() {
const layer = new TextElement('div',fakeDoc);
layer.parentElement = {getBoundingClientRect:()=>({width:600,height:800})};
return layer;
}
function traceVerticalWrites(layer) {
for (const run of layer.querySelectorAll('.reader-pdf-text-run')) {
let transform = run.style.transform;
Object.defineProperty(run.style,'transform',{get:()=>transform,set(value) {
fakeDoc.events.push('write'); transform=value;
}});
}
}
function runTextLayerContract(independent) {
const layer = textLayer(), nativeReplace = layer.replaceChildren;
layer.replaceChildren = function(fragment) {
nativeReplace.call(this,fragment);
const runs = this.querySelectorAll('.reader-pdf-text-run');
runs[1].measuredHeight = 0; // Hidden/zero-height text retains its estimate.
traceVerticalWrites(this);
};
fakeDoc.events.length = 0;
if (independent) {
const text = '甲乙丙', quad = [[0,0],[.1,0],[.1,.3],[0,.3]];
pdfText.populateIndependentTextLayer(layer,{text,generation:'g',regions:Array.from(text,(value,i)=>({
start:i,end:i+1,text:value,quad,writing_mode:i===2?'horizontal-tb':'vertical-rl',direction:'ltr',id:String(i)
}))});
assert.strictEqual(layer.dataset.textGeneration,'g');
assert.strictEqual(layer.style.userSelect,'text');
} else {
pdfText.populatePdfTextLayer(layer,Array.from({length:3},(_,i)=>({str:String(i),fontName:'f',
transform:[12,0,0,12,20,40],height:40,width:40,dir:i===2?'ltr':'ttb'})),
{width:600,height:800,scale:1,transform:[1,0,0,1,0,0],convertToViewportPoint:(x,y)=>[x,y]});
}
const runs = layer.querySelectorAll('.reader-pdf-text-run');
assert.deepStrictEqual(fakeDoc.events,['read','read','write']);
assert.notStrictEqual(runs[0].style.transform,'scaleY(0)');
assert.match(runs[1].style.transform,/^scaleY\(/);
assert.match(runs[2].style.transform,/^scaleX\(/);
}
runTextLayerContract(false);
runTextLayerContract(true);
// A source oracle for text-node gaps is the former Array.from/slice path.
// Include sparse and irregular native zones, paired/unpaired surrogates,
// adjacent regions and ranges extending beyond the end of the text.
{
const quad = [[0,0],[.1,0],[.1,.2],[0,.2]], alphabet = ['甲','B','😀','\ud800','\udc00','\n'];
let seed = 0x8123abcd;
const random = n => { seed = (Math.imul(seed,1664525)+1013904223)>>>0;return seed % n; };
for (let trial=0;trial<300;trial++) {
let text = '';
for (let i=0,n=random(24);i<n;i++) text+=alphabet[random(alphabet.length)];
const chars = Array.from(text), regions=[];
let cursor=0;
for (let i=0,n=random(7);i<n;i++) {
let start=cursor+random(3), end=start+1+random(4);
if (trial % 7 === 0 && i === 1) start=Math.max(0,cursor-1);
if (trial % 11 === 0 && i === 2) {start=1;end=1;}
regions.push({start,end,text:chars.slice(start,end).join(''),quad,writing_mode:'horizontal-tb',direction:'ltr',id:String(i)});
cursor=end;
}
const layer = textLayer();
pdfText.populateIndependentTextLayer(layer,{text,regions,generation:'fixture'});
const expected=[];let end=0;
for (const region of regions) {expected.push(chars.slice(end,region.start).join(''));end=region.end;}
expected.push(chars.slice(end).join(''));
const gaps=layer.children.filter((_,i)=>i%2===0).map(node=>node.textContent);
assert.deepStrictEqual(gaps,expected,JSON.stringify({trial,text,regions}));
assert.deepStrictEqual(layer.querySelectorAll('.reader-pdf-text-run').map(node=>node.textContent),regions.map(r=>r.text));
}
const text='😀中'.repeat(150000), layer=textLayer();
const nativeFrom=Array.from;
try {
Array.from=function(value,...args){if(value===text) throw new Error('full text array');return nativeFrom(value,...args);};
pdfText.populateIndependentTextLayer(layer,{text,generation:'large',regions:[{id:'last',start:299998,end:300000,
text:'😀中',quad,writing_mode:'horizontal-tb',direction:'ltr'}]});
assert.strictEqual(layer.children[0].textContent.length,text.length-3);
assert.strictEqual(layer.children[1].children[0].textContent,'😀中');
assert.strictEqual(layer.children[2].textContent,'');
} finally {Array.from=nativeFrom;}
}
const assets = sandbox.self.VoiceOfMLReader
const retiredLink = new URL(assets.readerUrl({ Link: 'https://example.test/book.pdf', Extension: 'pdf',
OcrUrl: '/txt/book.txt', ReaderOcrManifest: 'https://voiceofml-search.hf.space/api/reader-bucket-resource?path=objects%2Ftext' }), 'https://site.test')
assert.strictEqual(retiredLink.searchParams.has('ocr'), false)
assert.strictEqual(retiredLink.searchParams.get('ocr_manifest'), 'https://voiceofml-search.hf.space/api/reader-bucket-resource?path=objects%2Ftext')
const vectors = require('../../support/reader-contract-vectors.json')
for (const [value, expected] of vectors.ids) assert.strictEqual(assets.shortSourceId(value), expected)
const idPrefix = 'https://huggingface.co/datasets/VoiceOfML/VOMEBOOK/resolve/main/'
for (const [value, expected] of vectors.canonicalPaths) {
assert.strictEqual(assets.canonicalSourceUrl(idPrefix + value), idPrefix + expected)
assert.strictEqual(assets.canonicalSourceUrl(idPrefix + expected), idPrefix + expected)
assert.strictEqual(assets.shortSourceId(idPrefix + value), assets.shortSourceId(idPrefix + expected))
}
for (const bookPath of [vectors.reportedBook.path, vectors.reportedBook.path.split('/').map(encodeURIComponent).join('/')]) {
const link = idPrefix + bookPath
assert.strictEqual(assets.shortSourceId(link), vectors.reportedBook.id)
assert.strictEqual(new URL(assets.readerUrl({ Link: link, Extension: 'pdf' }), 'https://site.test').searchParams.get('id'), vectors.reportedBook.id)
}
assert.notStrictEqual(assets.shortSourceId(idPrefix + 'a%2Fb.pdf'), assets.shortSourceId(idPrefix + 'a/b.pdf'))
assert.notStrictEqual(assets.shortSourceId(idPrefix + 'a%2528.pdf'), assets.shortSourceId(idPrefix + 'a%28.pdf'))
// Preserve the previous canonicalization exactly, including malformed UTF-16
// errors and query/fragment boundaries: the result is a persistent ID key.
function legacyCanonical(value) {
return value.replace(/^(https:\/\/huggingface\.co\/datasets\/VoiceOfML\/)([^?#]*)/, (_, prefix, path) =>
prefix + path.replace(/%[0-9a-fA-F]{2}|[^A-Za-z0-9._~/-]/gu, token => {
if (/^%[0-9a-f]{2}$/i.test(token)) {
const char = String.fromCharCode(parseInt(token.slice(1), 16))
return /^[A-Za-z0-9._~-]$/.test(char) ? char : token.toUpperCase()
}
return encodeURIComponent(token).replace(/[!'()*]/g, char =>
'%' + char.charCodeAt(0).toString(16).toUpperCase())
}))
}
function compareCanonical(input) {
let expected
try { expected = legacyCanonical(input) } catch (error) {
assert.throws(() => assets.canonicalSourceUrl(input), {name: error.name})
return
}
assert.strictEqual(assets.canonicalSourceUrl(input), expected)
assert.strictEqual(assets.shortSourceId(input), legacyId(expected))
}
for (let n = 0; n < 256; n++) {
const hex = n.toString(16).padStart(2, '0')
for (const token of [hex, hex.toUpperCase()]) {
compareCanonical(idPrefix + 'folder/a%' + token + 'b.pdf?query=%' + token + '#page=2')
compareCanonical(idPrefix + 'folder/%' + token + '%' + token + '/file')
}
}
// Compare the 32-bit-limb implementation to the original BigInt operation.
// IDs are persistent reader/history/OCR keys and must be byte-for-byte stable.
function legacyId(value) {
let hash = 1469598103934665603n
for (const byte of new TextEncoder().encode(assets.canonicalSourceUrl(value))) {
hash ^= BigInt(byte)
hash = BigInt.asUintN(64, hash * 1099511628211n)
}
return hash.toString(36).padStart(13, '0')
}
let seed = 0x01234567
const alphabet = [...'abcXYZ0123/%?&# +\\.()!-_~', '文', '😀', '𠀀', '\u0000', '\ud800', '\udc00']
for (let n = 0; n < 6000; n++) {
seed = (Math.imul(seed, 1664525) + 1013904223) >>> 0
const length = seed % 120
let suffix = ''
for (let i = 0; i < length; i++) {
seed = (Math.imul(seed, 1664525) + 1013904223) >>> 0
suffix += alphabet[seed % alphabet.length]
}
const input = n % 2 ? idPrefix + suffix : suffix
compareCanonical(input)
let expected
try { expected = legacyId(input) } catch (error) {
assert.throws(() => assets.shortSourceId(input), {name: error.name}, `source error mismatch at ${n}`)
continue
}
assert.strictEqual(assets.shortSourceId(input), expected, `source ID mismatch at ${n}`)
}
const assetRoot = 'objects/aa/' + 'a'.repeat(64) + '/'
const legacyPrefix = '/datasets/vomebook/Reader-Assets/resolve/main/' // deleted dataset, kept only as a negative fixture
// Dataset-era object paths without a bucket are no longer readable.
for (const directory of ['', 'converter-v1/', 'b'.repeat(16) + '/', 'b'.repeat(16) + '/converter-v1/']) {
const path = assetRoot + directory + 'linearized.pdf'
assert.strictEqual(assets.assetFields({s: 2, m: 'p', p: path}, '/api/reader-bucket-resource'), null)
}
for (const extension of ['epub', 'mobi', 'azw3', 'fb2', 'chm']) {
const path = 'chapters/ebook/' + extension + '/' + 'c'.repeat(64) + '/' + 'b'.repeat(16) + '/chapter-manifest.json'
const book = {s: 2, m: 'e', p: path, b: 'vomebook/reader-assets-v2'}
assert.strictEqual(assets.assetFields(book, '/api/reader-bucket-resource'), null)
assert.strictEqual(assets.assetFields({...book, c: path}, '/api/reader-bucket-resource'), null)
const fields = assets.assetFields({...book, c: path, cb: 'vomebook/reader-assets-v2'}, '/api/reader-bucket-resource')
assert.strictEqual(fields.ReaderExtension, 'epub-chapters')
assert.strictEqual(fields.ReaderLink, '/api/reader-bucket-resource?path=' + encodeURIComponent(path))
}
const bucket = assetRoot + 'b'.repeat(16) + '/page-manifest.json'
for (const suffix of ['b'.repeat(16) + '/']) {
const url = 'https://huggingface.co/buckets/vomebook/pdf-pages-v2/resolve/' + assetRoot + suffix + 'page-manifest.json'
const parsed = assets.pdfPageSource(url, 'https://site.test', 'https://api.test')
assert.strictEqual(parsed.root, (assetRoot + suffix).slice(0, -1))
assert.strictEqual(parsed.pageUrl, undefined, 'PDF page manifests cannot construct retired image URLs')
}
const imageBucket = 'pages/image/tiff/' + 'c'.repeat(64) + '/page-manifest.json'
const imageUrl = 'https://huggingface.co/buckets/vomebook/reader-assets-v2/resolve/' + imageBucket
const imageSource = assets.imagePageSource(imageUrl, 'https://site.test', 'https://api.test')
const pageProxy = new URL(imageSource.pageUrl(2))
assert.strictEqual(pageProxy.origin + pageProxy.pathname, 'https://api.test/api/reader-bucket-resource')
assert.strictEqual(pageProxy.searchParams.get('path'), imageBucket.replace('page-manifest.json', 'pages/page-000002.webp'))
assert.strictEqual(assets.imagePageSource('https://voiceofml-search.hf.space/api/reader-bucket-resource?path=' +
encodeURIComponent(imageBucket), 'https://site.test', 'https://site.test').pageUrl(2),
pageProxy.href.replace('https://api.test', 'https://voiceofml-search.hf.space'))
assert.throws(() => imageSource.pageUrl(0), /PDF_PAGE_INVALID/)
const imageBucketName = 'vomebook/reader-assets-v2'
const avifDocument = imageBucket.replace('page-manifest.json', 'document.avif')
const avifPage = imageBucket.replace('page-manifest.json', 'pages/page-000002.avif')
const avifPageProxy = new URL(imageSource.assetUrl(avifPage))
assert.strictEqual(avifPageProxy.origin + avifPageProxy.pathname, 'https://api.test/api/reader-bucket-resource')
assert.strictEqual(avifPageProxy.searchParams.get('path'), avifPage)
assert.throws(() => imageSource.assetUrl(avifPage.replace('c'.repeat(64), 'd'.repeat(64))), /PDF_ASSET_INVALID/)
for (const path of [avifDocument, avifPage]) {
assert.strictEqual(assets.isBucketPath(path, true, imageBucketName), true)
assert.strictEqual(assets.isBucketPath(path, true, 'vomebook/pdf-pages-v2'), false)
}
for (const path of [avifDocument, `pages/image/gif/${'c'.repeat(64)}/document.webp`]) {
const fields = assets.assetFields({s: 2, m: 'i', p: path, b: imageBucketName}, '/api/reader-bucket-resource')
assert.strictEqual(fields.ReaderExtension, 'image')
assert.strictEqual(fields.ReaderLink, '/api/reader-bucket-resource?path=' + encodeURIComponent(path))
}
for (const path of [avifPage, avifDocument + '.exe', `pages/image/png/${'c'.repeat(64)}/document.png`,
`pages/image/gif/${'c'.repeat(64)}/document.gif`, assetRoot + 'document.avif']) {
assert.strictEqual(assets.assetFields({s: 2, m: 'i', p: path, b: imageBucketName}, '/api/reader-bucket-resource'), null)
}
assert.strictEqual(assets.assetFields({s: 2, m: 'p', p: avifDocument, b: imageBucketName}, '/api/reader-bucket-resource'), null)
assert.ok(assets.pdfPageSource('https://api.test/api/reader-bucket-resource?path=' + encodeURIComponent(bucket), 'https://site.test', 'https://api.test'))
for (const url of [
'https://evil.test/buckets/vomebook/pdf-pages-v2/resolve/' + bucket,
'https://api.test/api/reader-bucket-resource?path=' + encodeURIComponent(assetRoot + 'page-manifest.json'),
])
assert.strictEqual(assets.pdfPageSource(url, 'https://site.test', 'https://api.test'), null)
// The deleted dataset form is no longer a source for any Reader surface.
for (const url of [
'https://huggingface.co/datasets/vomebook/Reader-Assets/resolve/main/' + bucket,
'https://hf-mirror.com/datasets/vomebook/Reader-Assets/revision/main/' + bucket,
])
assert.strictEqual(assets.pdfPageSource(url, 'https://site.test', 'https://api.test'), null)
assert.strictEqual(assets.assetFields({s: 2, m: 'p', p: bucket}, '/api/reader-bucket-resource').ReaderLink,
'/api/reader-bucket-resource?path=' + encodeURIComponent(bucket))
assert.strictEqual(assets.assetFields({s: 2, m: 'p', p: bucket, b: 'vomebook/pdf-pages-v2'}, '/api/reader-bucket-resource').ReaderLink,
'/api/reader-bucket-resource?path=' + encodeURIComponent(bucket))
const nativeMediaPath = 'media/audio/native/' + 'a'.repeat(64) + '/audio.flac'
const nativeMedia = assets.assetFields({s: 2, m: 'a', p: nativeMediaPath, b: 'vomebook/reader-assets-v2'}, '/api/reader-bucket-resource')
assert.strictEqual(nativeMedia.ReaderExtension, 'audio')
assert.strictEqual(nativeMedia.ReaderLink,
'/api/reader-bucket-resource?path=' + encodeURIComponent(nativeMediaPath))
assert.strictEqual(assets.isBucketPath(nativeMediaPath, true, 'vomebook/reader-assets-v2'), true)
const swfPath = 'media/swf/native/' + 'a'.repeat(64) + '/document.swf'
const swf = assets.assetFields({s: 2, m: 'f', p: swfPath, b: 'vomebook/reader-assets-v2'}, '/api/reader-bucket-resource')
assert.strictEqual(swf.ReaderExtension, 'swf')
assert.strictEqual(assets.capability('swf').mode, 'swf')
assert.strictEqual(swf.ReaderLink,
'/api/reader-bucket-resource?path=' + encodeURIComponent(swfPath))
for (const path of ['derived/migration/' + 'a'.repeat(32) + '/document.pdf', 'documents/pdf/ppt/' + 'a'.repeat(64) + '/document.pdf']) {
const fields = assets.assetFields({s: 2, m: 'p', p: path, b: path.startsWith('derived/') ? 'vomebook/pdf-pages-v2' : 'vomebook/reader-assets-v2'}, '/api/reader-bucket-resource')
assert.strictEqual(fields.ReaderLink, '/api/reader-bucket-resource?path=' + encodeURIComponent(path))
assert.strictEqual(fields.ReaderExtension, 'pdf')
}
assert.strictEqual(assets.assetFields({s: 2, m: 'p', p: bucket, b: 'vomebook/pdf-pages'}), null)
const optimized = assetRoot + 'pdf-range-v1-document/document.pdf'
assert.strictEqual(assets.assetFields({s: 2, m: 'p', p: optimized, b: 'vomebook/pdf-optimized'}), null)
assert.strictEqual(assets.assetFields({s: 2, m: 'p', p: legacyPrefix + 'pdf_manifest.json'}), null)
assert.strictEqual(assets.assetFields({s: 2, m: 'p', p: legacyPrefix + assetRoot + 'epub-chapters/chapters/chapter-0012.xhtml'}), null)
for (const path of [assetRoot + '../linearized.pdf', assetRoot + 'private.json', 'objects/invalid/document.pdf']) {
assert.strictEqual(assets.assetFields({s: 2, m: 'p', p: path}), null)
}
for (const extension of ['pdf', 'pdf-pages', 'txt', 'md', 'markdown', 'html', 'htm', 'epub-chapters', 'jpg', 'png', 'mp3', 'm4a', 'flac', 'mpga', 'audio', 'mp4', 'mov', 'video']) {
assert.ok(sandbox.self.VoiceOfMLReader.capability(extension).mode, extension)
}
for (const extension of ['epub', 'mobi', 'azw', 'azw3', 'fb2', 'fbz']) assert.strictEqual(sandbox.self.VoiceOfMLReader.capability(extension).mode, null)
for (const extension of sandbox.self.VoiceOfMLReader.articleExtensions) assert.deepStrictEqual(Object.keys(sandbox.self.VoiceOfMLReader.capability(extension).features).sort(), ['bookmarks', 'media', 'pagination', 'search', 'toc', 'zoom'])
assert.strictEqual(sandbox.self.VoiceOfMLReader.capability('pdf-pages').mode, 'pdf-pages')
assert.strictEqual(sandbox.self.VoiceOfMLReader.capability('pdf-pages').features.toc, true)
assert.strictEqual(sandbox.self.VoiceOfMLReader.capability('epub-chapters').features.search, true)
for (const extension of ['mp3', 'm4a', 'flac', 'mpga', 'audio']) assert.strictEqual(sandbox.self.VoiceOfMLReader.capability(extension).mode, 'audio')
for (const extension of ['mp4', 'mov', 'video']) assert.strictEqual(sandbox.self.VoiceOfMLReader.capability(extension).mode, 'video')
assert.strictEqual(sandbox.self.VoiceOfMLReader.capability('zip').mode, null)
assert.strictEqual(sandbox.self.VoiceOfMLReader.capability('docx').mode, null)
assert.strictEqual(sandbox.self.VoiceOfMLReader.capability('epub-chapters').mode, 'epub-chapters')
const convertedUrl = sandbox.self.VoiceOfMLReader.readerUrl({
Link: 'https://download.example.test/books/book.mobi',
File: '原始书名', Extension: 'mobi', ReaderExtension: 'epub-chapters',
DownloadLink: 'https://download.example.test/books/book.mobi',
ReaderChapterManifest: 'https://voiceofml-search.hf.space/api/reader-bucket-resource?path=' + encodeURIComponent('chapters/ebook/mobi/' + 'c'.repeat(64) + '/' + 'b'.repeat(16) + '/chapter-manifest.json'),
}, '/reader.html')
const convertedParams = new URL(`https://example.test${convertedUrl}`).searchParams
assert.strictEqual(convertedParams.get('ext'), 'epub-chapters')
assert.strictEqual(convertedParams.get('title'), '原始书名.mobi')
assert.strictEqual(convertedParams.get('download'), 'https://download.example.test/books/book.mobi')
assert.strictEqual(convertedParams.get('fallback'), null)
assert.strictEqual(convertedParams.get('chapter_manifest'), 'https://voiceofml-search.hf.space/api/reader-bucket-resource?path=' + encodeURIComponent('chapters/ebook/mobi/' + 'c'.repeat(64) + '/' + 'b'.repeat(16) + '/chapter-manifest.json'))
const pageAssetUrl = sandbox.self.VoiceOfMLReader.readerUrl({
ReaderLink: 'https://voiceofml-search.hf.space/api/reader-bucket-resource?path=' + encodeURIComponent('objects/aa/' + 'a'.repeat(64) + '/1234567890abcdef/page-manifest.json'),
ReaderExtension: 'pdf-pages', Extension: 'mobi', File: '原始书名',
})
const pageAssetParams = new URL(`https://example.test${pageAssetUrl}`).searchParams
assert.strictEqual(pageAssetParams.get('url'), 'https://voiceofml-search.hf.space/api/reader-bucket-resource?path=' + encodeURIComponent('objects/aa/' + 'a'.repeat(64) + '/1234567890abcdef/page-manifest.json'))
assert.strictEqual(pageAssetParams.get('ext'), 'pdf-pages')
const sharedAsset = 'https://voiceofml-search.hf.space/api/reader-bucket-resource?path=' + encodeURIComponent('chapters/ebook/chm/' + 'a'.repeat(64) + '/' + 'b'.repeat(16) + '/chapter-manifest.json')
const sourceIds = ['Teachers', 'MLMRL-Hub'].map(repo => {
const record = { Link: `https://huggingface.co/datasets/VoiceOfML/${repo}/resolve/main/book.mobi`, File: 'book', Extension: 'mobi' }
const params = value => new URL(`https://example.test${sandbox.self.VoiceOfMLReader.readerUrl(value)}`).searchParams
const original = sandbox.self.VoiceOfMLReader.shortSourceId(record.Link)
const converted = params({ ...record, ReaderLink: sharedAsset, ReaderExtension: 'epub-chapters' })
assert.strictEqual(converted.get('id'), original)
assert.match(original, /^[a-z0-9]{13}$/)
assert.strictEqual(converted.get('ext'), 'epub-chapters')
return original
})
assert.notStrictEqual(sourceIds[0], sourceIds[1])
const normalizedUrl = sandbox.self.VoiceOfMLReader.readerUrl({ Link: 'https://download.example.test/book.TXT', File: '书名', Extension: 'TXT', ReaderExtension: 'TXT' }, '/reader.html')
const normalizedParams = new URL(`https://example.test${normalizedUrl}`).searchParams
assert.strictEqual(normalizedParams.get('ext'), 'TXT')
assert.strictEqual(normalizedParams.get('title'), '书名.TXT')
assert.strictEqual(sandbox.self.VoiceOfMLReader.readerUrl(null, '/reader.html'), '')
assert.strictEqual(sandbox.self.VoiceOfMLReader.readerUrl({ Link: 'https://download.example.test/archive.zip', Extension: 'zip' }, '/reader.html'), '')
assert.strictEqual(sandbox.self.VoiceOfMLReader.readerUrl({ Link: 'https://download.example.test/book.txt', Extension: '.txt' }, '/reader.html'), '')
assert.strictEqual(sandbox.self.VoiceOfMLReader.capability('PDF').readerMode, sandbox.self.VoiceOfMLReader.ReaderMode.ORIGINAL)
assert.strictEqual(sandbox.self.VoiceOfMLReader.capability('PDF').article, true)
assert.strictEqual(sandbox.self.VoiceOfMLReader.capability('zip').readerMode, sandbox.self.VoiceOfMLReader.ReaderMode.UNSUPPORTED)
assert.strictEqual(sandbox.self.VoiceOfMLReader.capability('zip').article, false)
for (const extension of ['pdf', 'pdf-pages', 'epub-chapters', 'txt', 'md', 'html', 'jpg', 'png', 'webp', 'mp3', 'm4a', 'flac', 'mp4', 'mov']) assert.ok(sandbox.self.VoiceOfMLReader.articleExtensions.includes(extension), extension)
assert.ok(!sandbox.self.VoiceOfMLReader.articleExtensions.includes('docx'))
assert.strictEqual(Object.isFrozen(sandbox.self.VoiceOfMLReader.articleExtensions), true)
assert.strictEqual(Object.isFrozen(sandbox.self.VoiceOfMLReader.capability('pdf')), true)
const immutableRecord = { Link: 'https://download.example.test/book.txt', File: 'book', Extension: 'txt' }
const immutableBefore = JSON.stringify(immutableRecord)
const defaultReaderUrl = sandbox.self.VoiceOfMLReader.readerUrl(immutableRecord)
assert.ok(defaultReaderUrl.startsWith('/static/reader.html?'))
assert.strictEqual(JSON.stringify(immutableRecord), immutableBefore)
assert.strictEqual((reader.match(/function setToc\(/g) || []).length, 1)
assertCode(reader, 'const previousList = /** @type {HTMLElement} */ (document.querySelector("#toc-list"))')
assertCode(reader, 'previousList.cloneNode(false)')
assertCode(reader, 'previousList.replaceWith(list)')
assert.match(reader, /reader-source:/)
assert.match(reader, /reader-zoom/)
assert.match(reader, /readerRuntime\.track\(readerRequestManager\)/)
assert.match(reader, /readerPath[\s\S]*voice-reader-navigate/)
assert.match(reader, /title: historyTitle|title,\s*extension/)
console.log('reader regression contracts passed')
require('node:test')('Markdown restores saved positions without overriding explicit links', async (t) => {
const { createReaderFormatController } = await import('../../../static/reader/formats/reader-format-controller.mjs')
const { createReaderBookmarks } = await import('../../../static/reader/ui/reader-bookmarks.mjs')
const { createReaderNavigation } = await import('../../../static/reader/ui/reader-navigation.mjs')
const { createReaderProgress } = await import('../../../static/reader/ui/reader-progress.mjs')
const { createReaderUi } = await import('../../../static/reader/ui/reader-ui.mjs')
const previous = Object.fromEntries(['location', 'window', 'document', 'VoiceOfMLReader', 'VoiceOfMLReaderStore'].map(key => [key, globalThis[key]]))
t.after(() => Object.assign(globalThis, previous))
const sourceUrl = 'https://huggingface.co/datasets/VoiceOfML/Books/resolve/main/book.md'
const link = new URL('https://reader.example.test/static/reader.html#section%202')
link.searchParams.set('url', sourceUrl)
link.searchParams.set('ext', 'md')
const historyEntry = { url: sourceUrl, scrollTop: 980, readerUrl: link.href }
const bookmark = { ...historyEntry, id: 'saved', scrollTop: 420 }
globalThis.VoiceOfMLReader = { ReaderMode: { UNSUPPORTED: 'unsupported' } }
globalThis.VoiceOfMLReaderStore = { get: async () => historyEntry, listBookmarks: async () => [bookmark], list: async () => [historyEntry] }
let assigned
const openUrl = (href) => {
globalThis.location = Object.assign(new URL(href), { assign: target => { assigned = new URL(target) } })
}
globalThis.window = { get location() { return globalThis.location }, history: { replaceState(_state, _title, href) { openUrl(href) } } }
function fixture(url) {
openUrl(url)
const viewport = { scrollTop: 0 }
const context = {
viewport, sourceUrl, params: new URLSearchParams(globalThis.location.search), capability: { mode: 'markdown' },
documentState: { title: 'Book' }, content: { querySelector: () => ({
querySelectorAll: () => [{ id: 'section 2', scrollIntoView() { viewport.scrollTop = 120 } }]
}) },
readerRuntime: { currentGeneration: () => 1 }, isReaderGenerationCurrent: () => true, beginReaderNavigation: () => 1,
resolveReaderSource: async () => {}, measurePdf: promise => promise, awaitReader: promise => promise, assertReaderActive() {},
waitForReader: ms => { assert.strictEqual(ms, 150); return new Promise(() => {}) },
syncCapabilityControls() {}, setReaderStage() {}, validSource: url => url === sourceUrl,
downloadButton: {}, readerDownloadUrl: () => sourceUrl, applyReaderMetadata() {},
formatAdapters: { activate() {}, active: { open() {}, render() {}, restore: (entry, generation) => context.restoreFormat('markdown', entry, generation) } },
readerResources: new Set(), markReaderContentReady() {}, updateDocumentState() {},
setReaderPhase: () => false, isReaderOverlayFrame: () => false, reportNavigationError: error => { throw error },
nextReaderGeneration: () => 1, readerAbortController: new AbortController(), classifyReaderError: error => { throw error }
}
return Object.assign(context, createReaderBookmarks(context), createReaderProgress(context), {
updateProgressTools() {}, scheduleSave() {}, saveProgress: async () => {}
})
}
const opening = new URL(link)
opening.searchParams.set('return', 'back')
const context = fixture(opening)
assert.strictEqual(context.currentReaderUrl().hash, '')
assert.deepStrictEqual([...context.currentReaderUrl().searchParams], [...link.searchParams])
assert.strictEqual(globalThis.location.href, opening.href)
// Exercise the history button, not just the URL serializer; old records still have a fragment.
const { navigateReader } = createReaderNavigation(context)
const node = () => ({ children: [], setAttribute() {}, addEventListener(type, fn) { this[type] = fn }, append(...items) { this.children.push(...items) } })
const list = node()
list.appendChild = item => list.append(item)
Object.defineProperty(list, 'childElementCount', { get: () => list.children.length })
globalThis.document = { querySelector: () => list, createElement: node }
await createReaderUi({ ...context, navigateReader, filterPanel() {}, emptyPanel(_list, message) { assert.fail(message) } }).renderHistory()
await list.children[0].children[0].click()
const historyUrl = assigned
assert.strictEqual(historyUrl.hash, '')
await navigateReader(link.href, bookmark)
const bookmarkUrl = assigned
assert.strictEqual(bookmarkUrl.hash, '')
assert.strictEqual(bookmarkUrl.searchParams.get('bookmark'), bookmark.id)
await navigateReader(link.href)
assert.strictEqual(assigned.hash, link.hash)
const anchoredBookmark = new URL(bookmarkUrl)
anchoredBookmark.hash = link.hash
const missingBookmark = new URL(anchoredBookmark)
missingBookmark.searchParams.set('bookmark', 'missing')
for (const [url, expected, hash] of [
[historyUrl, 980, ''], [link, 120, link.hash], [missingBookmark, 120, link.hash],
[bookmarkUrl, 420, ''], [anchoredBookmark, 420, '']
]) {
const openingContext = fixture(url)
await createReaderFormatController(openingContext).start()
assert.strictEqual(openingContext.viewport.scrollTop, expected, url.href)
assert.strictEqual(globalThis.location.hash, hash)
if (expected === bookmark.scrollTop) assert.strictEqual(globalThis.location.searchParams.has('bookmark'), false)
}
})
require('node:test')('optional Reader player skips non-text, handles failure and ignores completion after disposal', async (t) => {
const { createReaderSpeech } = await import('../../../static/reader/ui/reader-speech.mjs')
const keys = ['window', 'document', 'CCRDSpeech']
const previous = keys.map(key => [key, Object.getOwnPropertyDescriptor(globalThis, key)])
t.after(() => {
for (const [key, descriptor] of previous) {
if (descriptor) Object.defineProperty(globalThis, key, descriptor)
else delete globalThis[key]
}
})
let probed = 0
globalThis.window = new EventTarget()
globalThis.document = Object.assign(new EventTarget(), { querySelector: () => { probed++; return null } })
delete globalThis.CCRDSpeech
let phase, succeed, attempts = 0
const context = {
capability: { mode: 'image' }, isReaderOverlayFrame: () => true,
readerRuntime: { events: { on: (_, callback) => { phase = callback } } }
}
const reader = createReaderSpeech(context, () => {
if (++attempts === 1) throw Error('player unavailable')
return new Promise(resolve => { succeed = resolve })
})
const flush = () => new Promise(setImmediate)
reader.installReaderSpeech()
phase({ phase: 'ready' })
await flush()
assert.strictEqual(attempts, 0)
context.capability.mode = 'text'
phase({ phase: 'ready' })
await flush()
assert.strictEqual(attempts, 1)
assert.strictEqual(reader.readerSpeechAdapter(), null)
phase({ phase: 'ready' })
phase({ phase: 'ready' })
await flush()
assert.strictEqual(attempts, 2)
phase({ phase: 'disposed' })
const before = probed
globalThis.CCRDSpeech = { previewClosed() {}, previewLoaded: () => assert.fail('disposed Reader attached speech') }
succeed()
await flush()
assert.strictEqual(probed, before, 'no attachment or DOM access after disposal')
assert.strictEqual(reader.readerSpeechAdapter(), null)
})
require('node:test')('Reader speech uses the visible PDF page and does not require a chapter search index', async (t) => {
const { createReaderSpeech } = await import('../../../static/reader/ui/reader-speech.mjs')
const keys = ['window', 'document', 'NodeFilter', 'CCRDSpeech', 'sessionStorage', 'localStorage']
const previous = keys.map(key => [key, Object.getOwnPropertyDescriptor(globalThis, key)])
t.after(() => {
for (const [key, descriptor] of previous) {
if (descriptor) Object.defineProperty(globalThis, key, descriptor)
else delete globalThis[key]
}
})
const published = []
Object.assign(globalThis, {
window: Object.assign(new EventTarget(), { name: '' }),
document: Object.assign(new EventTarget(), { querySelector: () => null }),
NodeFilter: { SHOW_TEXT: 4 },
CCRDSpeech: { previewClosed() {}, previewLoaded: value => published.push(value.adapter) }
})
for (const key of ['sessionStorage', 'localStorage'])
Object.defineProperty(globalThis, key, { configurable: true, value: { removeItem() {} } })
const rect = { top: 0, bottom: 20, height: 20 }
const textElement = (data, dataset = {}, onWalk = () => {}) => ({ dataset, getBoundingClientRect: () => rect, ownerDocument: {
createTreeWalker() {
onWalk()
let read = false
return { nextNode() { if (read) return null; read = true; return { data, length: data.length } } }
},
createRange: () => ({ setStart() {}, setEnd() {}, getClientRects: () => [rect], getBoundingClientRect: () => rect })
} })
let pdfWalks = 0
const pdfText = textElement('Visible PDF text.', {}, () => { pdfWalks++ })
const pdfPage = { dataset: { page: '8', textReady: '1' }, querySelector: () => pdfText }
const chapter = textElement('Second chapter text.', { chapter: '2' })
const viewport = Object.assign(new EventTarget(), { getBoundingClientRect: () => ({ top: 0, bottom: 800 }) })
let phase
const context = {
capability: { mode: 'pdf' }, sourceUrl: 'fixture', viewport,
content: { querySelector: selector => selector.includes('data-page="8"') ? pdfPage : null },
documentState: { page: 26, pageCount: 40 }, pageAtMarker: () => pdfPage,
readerRuntime: { events: { on: (_, callback) => { phase = callback } } }
}
createReaderSpeech(context, async () => assert.fail('existing player must be reused')).installReaderSpeech()
phase({ phase: 'ready' })
await new Promise(setImmediate)
assert.strictEqual(published.length, 1, 'a stale saved page must not hide speech on the visible page')
const pdf = published[0]
assert.strictEqual(pdf.base, 7)
const walksAfterProbe = pdfWalks
assert.strictEqual(pdf.partAt(await pdf.locateTop()).unit, 8)
assert.strictEqual(pdfWalks - walksAfterProbe, 1, 'locateTop walks the DOM for position, then reuses the probe text')
const loads = []
Object.assign(context, { capability: { mode: 'epub-chapters' }, chapterSearchConfiguration: null,
chapterManifestLoader: Object.assign(async index => { loads.push(index); return textElement('First chapter text.') }, { count: 2 }),
content: { querySelector: selector => selector.includes('data-chapter="2"') ? chapter : null,
querySelectorAll: () => [chapter] } })
phase({ phase: 'ready' })
assert.strictEqual(published.length, 2, 'a chapter manifest alone is sufficient for speech')
const epub = published[1]
const part = epub.partAt(await epub.locateTop())
assert.strictEqual(part.unit, 1)
assert.strictEqual(part.raw, 'Second chapter text.')
assert.deepStrictEqual(loads, [1], 'translate player units to one-based Reader chapter indices')
phase({ phase: 'disposed' })
})