File size: 15,621 Bytes
2be9ba5 3a37705 2be9ba5 6c8fd46 2315c7d 6c8fd46 2be9ba5 29f5e34 2be9ba5 1dc63a4 2be9ba5 1dc63a4 3a37705 1dc63a4 3a37705 2be9ba5 aba4489 2be9ba5 169f8e1 2be9ba5 aba4489 169f8e1 2be9ba5 169f8e1 2be9ba5 3a37705 2be9ba5 3a37705 2be9ba5 3a37705 2be9ba5 6c8fd46 2be9ba5 6c8fd46 2be9ba5 6c8fd46 2315c7d 6c8fd46 2be9ba5 2315c7d | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 | import assert from 'node:assert/strict';
import test from 'node:test';
import {createReaderLifecycle} from '../../../static/reader/core/reader-lifecycle.mjs';
function fixture() {
const events = [], lifecycle = {disposed:false, stage:'prepare'};
const values = new Map();
const context = {
readerAbortController:new AbortController(), readerResources:new Set(), readerLifecycle:lifecycle,
readerRuntime:{state:{lifecycle}, setPhase:phase => { events.push(['phase',phase]); return true; },
setStage:stage => {events.push(['stage',stage]); return true;},
nextGeneration:name => {const next=(values.get(name)||0)+1;values.set(name,next);return next;},
isCurrent:(name,value)=>values.get(name)===value, dispose(){lifecycle.disposed=true;}, fail(code){events.push(['fail',code]);}},
readerContentReady:false, drainPdfTextWaiters(){events.push('drain');}
};
Object.assign(context,createReaderLifecycle(context));
return {context,events};
}
test('resource ownership, once-only release, abort and throwing cleanup behavior', () => {
const {context,events}=fixture();
const untrack=context.trackReaderResource(()=>events.push('removed'));
assert.equal(untrack(),true);assert.equal(untrack(),false);
context.trackReaderResource(()=>{events.push('broken');throw Error('cleanup');});
context.trackReaderResource(()=>events.push('remaining'));
context.stopReaderWork();
assert.equal(context.readerAbortController.signal.aborted,true);
assert.deepEqual(events,['broken','remaining']);
assert.equal(context.readerResources.size,0);
const late=context.trackReaderResource(()=>events.push('late'));
assert.equal(late(),false);assert.equal(events.at(-1),'late');
assert.throws(()=>context.trackReaderResource(()=>{throw Error('late');}),/late/);
});
test('awaitReader supports immediate values, thenables, cancellation and original errors', async () => {
const {context}=fixture();
assert.equal(await context.awaitReader(4),4);
assert.equal(await context.awaitReader({then(resolve){resolve('thenable');}}),'thenable');
const marker=new Error('original');await assert.rejects(context.awaitReader(Promise.reject(marker)),value=>value===marker);
const signal=new AbortController();
let settle;
const pending=context.awaitReader(new Promise(resolve=>{settle=resolve;}),signal.signal);
signal.abort();settle('late');
await assert.rejects(pending,{name:'AbortError',message:'Reader work cancelled'});
const cancelled=fixture().context;cancelled.readerAbortController.abort();
await assert.rejects(cancelled.awaitReader(Promise.resolve('late')),{name:'AbortError'});
});
test('generation ownership drains PDF text only for search and checks abort state', () => {
const {context,events}=fixture();
assert.equal(context.nextReaderGeneration('search'),1);assert.deepEqual(events,['drain']);
assert.equal(context.nextReaderGeneration('navigation'),1);assert.equal(context.isReaderGenerationCurrent('navigation',1),true);
assert.equal(context.isReaderGenerationCurrent('navigation',0),false);
context.readerAbortController.abort();assert.equal(context.isReaderGenerationCurrent('navigation',1),false);
});
test('error classification preserves dynamic getter access and uncoerced matching codes', () => {
const {context}=fixture();
assert.equal(context.classifyReaderError(null),'READER_PARSE');
assert.equal(context.classifyReaderError('network problem'),'READER_NETWORK');
assert.equal(context.classifyReaderError({message:'corrupt EPUB'}),'READER_CORRUPT');
assert.equal(context.classifyReaderError({code:'READER_PDF_RATE_LIMIT'}),'READER_PDF_TRANSPORT');
let calls=0;
const dynamic={get code(){calls++;return calls===1?'x':calls===2?'READER_RESTORE':42;}};
assert.equal(context.classifyReaderError(dynamic),42);assert.equal(calls,3);
const broken={get code(){throw Error('getter');}};
assert.throws(()=>context.classifyReaderError(broken),/getter/);
assert.equal(context.classifyReaderError({name:'HTTP 503',message:'corrupt'}),'READER_NETWORK');
assert.equal(context.classifyReaderError({message:'DJVU_RANGE_HTTP_404'}),'READER_NETWORK');
assert.equal(context.classifyReaderError({code:'DJVU_RANGE_TRANSIENT',message:'DJVU_RANGE_HTTP_503'}),'READER_DJVU_TRANSPORT');
assert.equal(context.classifyReaderError({code:'READER_CHAPTER_MANIFEST_TRANSIENT'}),'READER_CHAPTER_MANIFEST_TRANSIENT');
const interrupted={name:'TimeoutError',code:'READER_BODY_INTERRUPTED'};
for (const mode of ['text','markdown','html']) {
context.capability={mode};
assert.equal(context.classifyReaderError(interrupted),'READER_DOCUMENT_INTERRUPTED');
}
for (const capability of [null,{mode:'pdf'}]) {
context.capability=capability;
assert.equal(context.classifyReaderError(interrupted),'READER_NETWORK');
}
});
test('navigation warnings require a current generation and ignore aborts', () => {
const {context}=fixture();const messages=[],warn=console.warn;
console.warn=(...args)=>messages.push(args);
try {
const generation=context.nextReaderGeneration('navigation');
context.reportNavigationError({name:'AbortError'},generation);
context.reportNavigationError({name:'Other'},0);
const error={name:'Other'};context.reportNavigationError(error,generation);
assert.equal(messages.length,1);assert.deepEqual(messages[0],['Reader navigation failed',error]);
} finally {console.warn=warn;}
});
test('waitForReader rejects on cancellation and resolves on its timer', async () => {
const {context}=fixture();
await context.waitForReader(0);
const pending=context.waitForReader(5000);
context.readerAbortController.abort();
await assert.rejects(pending,{name:'AbortError'});
await assert.rejects(context.waitForReader(0),{name:'AbortError'});
// Bookmark restoration uses the frame path. A completed frame must detach
// its abort handler; aborting a pending frame must cancel exactly that ID.
const frames=new Map(), cancelled=[];
let frameId=0;
const request=globalThis.requestAnimationFrame, cancel=globalThis.cancelAnimationFrame;
globalThis.requestAnimationFrame=done=>{frames.set(++frameId,done);return frameId;};
globalThis.cancelAnimationFrame=id=>{cancelled.push(id);frames.delete(id);};
try {
const first=fixture().context, completed=first.waitForReader(0,true);
const finish=frames.get(1);
frames.delete(1);
finish();
await completed;
first.readerAbortController.abort();
assert.deepEqual(cancelled,[]);
const second=fixture().context, interrupted=second.waitForReader(0,true);
assert.deepEqual([...frames.keys()],[2]);
second.readerAbortController.abort();
await assert.rejects(interrupted,{name:'AbortError'});
assert.deepEqual(cancelled,[2]);
assert.equal(frames.size,0);
} finally {
if (request===undefined) delete globalThis.requestAnimationFrame; else globalThis.requestAnimationFrame=request;
if (cancel===undefined) delete globalThis.cancelAnimationFrame; else globalThis.cancelAnimationFrame=cancel;
}
});
test('reader readiness preserves chapter anchor only when loading node is connected', () => {
const {context,events}=fixture();
context.loadingIndicator={isConnected:true,remove(){events.push('remove');}};
context.chapterScrollAnchors={preserve(callback){events.push('preserve');return callback();}};
assert.equal(context.readerContentReady,false);
context.capability={mode:'epub-chapters'};context.markReaderContentReady();
assert.deepEqual(events,['preserve','remove']);assert.equal(context.readerContentReady,true);
events.length=0;context.capability={mode:'pdf'};context.markReaderContentReady();
assert.deepEqual(events,['remove']);
events.length=0;context.capability=null;context.markReaderContentReady();assert.deepEqual(events,['remove']);
events.length=0;context.capability={mode:'epub-chapters'};context.markReaderContentReady();
assert.deepEqual(events,['preserve','remove']);
events.length=0;context.loadingIndicator.isConnected=false;context.markReaderContentReady();
assert.deepEqual(events,['remove']);
});
test('phase and stage forward return values unchanged', () => {
const {context,events}=fixture();
assert.equal(context.setReaderPhase('ready'),true);
assert.equal(context.setReaderStage('prepare'),true);
assert.deepEqual(events,[['phase','ready'],['stage','prepare']]);
});
test('dispose is idempotent and clears all timer handles', () => {
const {context,events}=fixture();
const store=globalThis.VoiceOfMLReaderStore, oldClear=globalThis.clearTimeout, oldCancel=globalThis.cancelAnimationFrame;
globalThis.VoiceOfMLReaderStore={dispose(){events.push('store');}};
globalThis.clearTimeout=handle=>events.push(['clear',handle]);
globalThis.cancelAnimationFrame=handle=>events.push(['cancel',handle]);
context.updateDocumentState=value=>events.push(value);
const handles=['saveTimer','themeAnimationTimer','panelAnimationTimer','markerFrame'];
handles.forEach((key,index)=>context[key]=index+1);
try {
context.disposeReader();context.disposeReader();
assert.deepEqual(events,[{restorationReady:false},['clear',1],['clear',2],['clear',3],
['cancel',4],'store']);
assert.equal(context.readerLifecycle.disposed,true);
assert.deepEqual(handles.map(key=>context[key]),[0,0,0,0]);
const idle=fixture().context;
idle.updateDocumentState=context.updateDocumentState;
handles.forEach(key=>idle[key]=0);
events.length=0;
idle.disposeReader();
assert.deepEqual(events,[{restorationReady:false},['clear',0],['clear',0],['clear',0],'store']);
} finally {globalThis.VoiceOfMLReaderStore=store;globalThis.clearTimeout=oldClear;globalThis.cancelAnimationFrame=oldCancel;}
});
test('failure cleanup preserves message, lifecycle stage and retry control semantics', () => {
const {context,events}=fixture();
const oldDocument=globalThis.document,oldWindow=globalThis.window;
const errorNode={textContent:'',children:[],append(...nodes){this.children.push(...nodes);}};
const element=tag=>({tag,addEventListener(type,callback){this.event={type,callback};}});
globalThis.document={createElement:element};globalThis.window={__VOICE_PDF_PRELOAD__:{dispose(){events.push('preload');}}};
context.updateDocumentState=value=>events.push(value);
context.setReaderPanelOpen=open=>events.push(['panel',open]);
context.stopReaderWork=()=>events.push('work');
context.readerRequestManager={dispose:()=>events.push('requests')};
context.formatAdapters={dispose:()=>events.push('adapters')};
context.content={dataset:{},innerHTML:'',querySelector:()=>errorNode};
context.loadingIndicator={remove(){events.push('remove');}};
context.status={textContent:''};
try {
context.fail('test','READER_MEDIA');
assert.deepEqual(events,[{restorationReady:false},['fail','READER_MEDIA'],['panel',false],
'work','requests','adapters','preload','remove']);
assert.equal(context.readerContentReady,true);
assert.equal(context.content.dataset.errorCode,'READER_MEDIA');
assert.equal(errorNode.textContent,'test [prepare]');
assert.equal(errorNode.children.length,2);assert.equal(errorNode.children[1].event.type,'click');
assert.equal(context.status.textContent,'无法打开');
context.readerLifecycle.disposed=true;events.length=0;context.fail('ignored');assert.deepEqual(events,[]);
} finally {globalThis.document=oldDocument;globalThis.window=oldWindow;}
});
test('retry click waits for progress and reloads only while reader remains live', async () => {
const {context}=fixture();
const oldDocument=globalThis.document,oldWindow=globalThis.window,oldLocation=globalThis.location;
const errorNode={append(_br,retry){this.retry=retry;}};
globalThis.document={createElement:tag=>({tag,addEventListener(_type,callback){this.callback=callback;}})};
globalThis.window={};let reloads=0;
globalThis.location={reload(){reloads++;}};
let releaseProgress;
Object.assign(context,{updateDocumentState(){},setReaderPanelOpen(){},stopReaderWork(){},
readerRequestManager:{dispose(){}},formatAdapters:{dispose(){}},
content:{dataset:{},querySelector:()=>errorNode},status:{},loadingIndicator:{remove(){}},
progressSaveChain:new Promise(resolve=>{releaseProgress=resolve;})});
try {
context.fail('message','READER_DOCUMENT_INTERRUPTED');
assert.equal(context.content.dataset.errorCode,'READER_DOCUMENT_INTERRUPTED');
assert.equal(errorNode.textContent,'正文下载中断,原阅读进度已保留。请重试加载完整文件。 [prepare]');
const retry=errorNode.retry.callback();await new Promise(resolve=>setImmediate(resolve));assert.equal(reloads,0);
releaseProgress();await retry;assert.equal(reloads,1);
context.progressSaveChain=Promise.reject(new Error('progress save failed'));
await errorNode.retry.callback();assert.equal(reloads,2,'a rejected save must not block manual retry');
context.readerLifecycle.disposed=true;
await errorNode.retry.callback();assert.equal(reloads,2);
context.readerLifecycle.disposed=false;
context.progressSaveChain=new Promise(()=>{});
context.fail('engine','READER_ENGINE_NETWORK');
await errorNode.retry.callback();assert.equal(reloads,3,'engine retry does not wait for progress');
context.fail('manifest','READER_CHAPTER_MANIFEST_TRANSIENT');
assert.match(errorNode.textContent,/章节列表.*重试/);
await errorNode.retry.callback();assert.equal(reloads,4);
delete errorNode.retry;
context.fail('parse error');
assert.equal(errorNode.retry,undefined);
} finally {globalThis.document=oldDocument;globalThis.window=oldWindow;globalThis.location=oldLocation;}
});
test('terminal DjVu transport captures progress before invalidation and reloads the unchanged reader URL', async () => {
const {context, events}=fixture();
const oldDocument=globalThis.document,oldWindow=globalThis.window,oldLocation=globalThis.location;
const errorNode={append(_br,retry){this.retry=retry;}};
globalThis.document={createElement:tag=>({tag,addEventListener(_type,callback){this.callback=callback;}})};
globalThis.window={};
const href='https://reader.test/static/reader.html?id=book&nav=parked&return=%2Fcatalog%2F';
globalThis.location={href, reload(){events.push(['reload',this.href]);}};
const progress=Promise.withResolvers();
Object.assign(context,{updateDocumentState(){events.push('disable saving');},setReaderPanelOpen(){},stopReaderWork(){},
saveProgress(){events.push('capture progress');return progress.promise;},
readerRequestManager:{dispose(){}},formatAdapters:{dispose(){}},content:{dataset:{},querySelector:()=>errorNode},
status:{},loadingIndicator:{remove(){}},progressSaveChain:progress.promise});
try {
context.fail('range 503','READER_DJVU_TRANSPORT');
assert.deepEqual(events,['capture progress','disable saving',['fail','READER_DJVU_TRANSPORT']]);
assert.match(errorNode.textContent,/DjVu 数据.*重试加载整本/);
const reopening=errorNode.retry.callback();
await new Promise(resolve=>setImmediate(resolve));
assert.equal(events.length,3,'do not navigate before an eligible save settles');
progress.resolve(); await reopening;
assert.deepEqual(events.at(-1),['reload',href]);
context.saveProgress=()=>Promise.reject(new Error('progress store unavailable'));
context.fail('range 503','READER_DJVU_TRANSPORT');
await errorNode.retry.callback();assert.deepEqual(events.at(-1),['reload',href]);
} finally {globalThis.document=oldDocument;globalThis.window=oldWindow;globalThis.location=oldLocation;}
});
|