File size: 15,533 Bytes
fb915bd
ae48295
9eda756
6a3faf6
fb915bd
5ea8fc3
 
 
 
 
 
 
 
 
2315c7d
5ea8fc3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
02a27d4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5ea8fc3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fb915bd
 
76d6c6d
2315c7d
76d6c6d
 
ee872c7
 
ae48295
 
 
 
7816974
 
 
ee872c7
7816974
 
 
 
 
 
 
 
 
 
 
 
2315c7d
7816974
 
 
 
 
 
 
 
 
 
 
2315c7d
7816974
f1e391e
 
7816974
 
 
 
2315c7d
 
 
 
 
 
7816974
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2315c7d
7816974
 
 
 
 
 
 
 
 
 
76d6c6d
 
 
5ea8fc3
fb915bd
 
 
ee872c7
 
fb915bd
ee872c7
 
 
 
 
 
 
fb915bd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ee872c7
 
 
 
 
 
 
 
fb915bd
ee872c7
 
 
 
 
 
 
 
 
 
fb915bd
 
ee872c7
fb915bd
 
 
 
 
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
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
import { openDjvuDocument } from "./reader-djvu-adapter.mjs";
import { openDjvuRange } from "./reader-djvu-range.mjs";
import { createDjvuWorkerAdapter } from "./reader-djvu-worker.mjs";
import { resolveDjvuSource } from "./reader-djvu-identity.mjs";

/** @typedef {{bytes: number, sha256: string}} DjvuPrimaryRef */
/** @typedef {{primary: {resource: DjvuPrimaryRef}}} DjvuManifest */
/** @typedef {{readerAbortController: AbortController, sourceUrl: string, ocrManifestUrl: string,
 * READER_PROXY_TIMEOUT_MS: number, pdfOcrManifest: unknown,
 * readerDownloadApiUrl(path: string): string, readerContentUrl(url: string): string,
 * fetchWithReaderTimeout(url: string, timeout: number, options?: RequestInit): Promise<Response>,
 * fetchReaderUrl(url: string, options: RequestInit): Promise<Response>,
 * readPdfOcrJson(url: string, limit: number, sha: string, retry: number, priority: string): Promise<unknown>,
 * trackReaderResource(cleanup: () => void): () => void, assertReaderActive(): void, v3ResourceUrl(ref: DjvuPrimaryRef): string}} DjvuContext */
/** @typedef {DjvuContext & {fail(message: string, code: string): void}} NativeDjvuContext */
/** @typedef {Awaited<ReturnType<typeof openDjvuRange>>} DjvuRange */
/** @param {unknown} error @returns {error is Record<string, unknown>} */
function isErrorDetail(error) { return error !== null && (typeof error === 'object' || typeof error === 'function'); }
/** @param {DjvuRange | undefined} range @returns {DjvuRange} */
function requireRange(range) { if (!range) throw new Error('DJVU_RANGE_INVALID'); return range; }
/** @param {Response} response @param {DjvuRange} range */
function sameOutlineSource(response,range) {
  const encoding=response.headers.get('Content-Encoding'),size=response.headers.get('Content-Length');
  if (response.status!==200 || response.headers.get('ETag')!==range.etag || (encoding && encoding!=='identity')) return false;
  return size===null || (/^\d+$/.test(size) && Number(size)===range.total);
}
/** @param {AbortSignal} signal */
function checkOutlineAbort(signal) {
  if (signal.aborted) throw signal.reason || new DOMException('DjVu outline cancelled','AbortError');
}
/** @param {DjvuContext} context @param {URL} resolved @param {DjvuRange} range @param {AbortSignal} signal @param {number} cacheBytes */
async function openFullOutline(context,resolved,range,signal,cacheBytes) {
  const response=await context.fetchReaderUrl(resolved.href,{signal});
  if (!sameOutlineSource(response,range)) {
    await response.body?.cancel().catch(()=>{});
    throw new Error('DJVU_SOURCE_CHANGED');
  }
  const packed=await VoiceOfMLReaderSecurity.readBytes(response,range.total);
  checkOutlineAbort(signal);
  if (packed.byteLength!==range.total) throw new Error('DJVU_SOURCE_CHANGED');
  const bytes=packed.byteOffset===0 && packed.byteLength===packed.buffer.byteLength ? packed.buffer :
    packed.buffer.slice(packed.byteOffset,packed.byteOffset+packed.byteLength);
  const full=await openDjvuDocument({workerUrl,bytes,signal,cacheBytes,cachePages:1});
  const destroy=()=>{signal.removeEventListener('abort',destroy);full.destroy();};
  signal.addEventListener('abort',destroy,{once:true});
  if(signal.aborted){destroy();checkOutlineAbort(signal);}
  return {...full,destroy};
}
/** @param {unknown} failure */
function transportAllowsFallback(failure) {
  const detail=isErrorDetail(failure) ? failure : null;
  return !failure || ['AbortError','TimeoutError'].some(value=>value===detail?.name) || detail?.code === 'DJVU_RANGE_UNSUPPORTED';
}
/** @param {unknown} error */
function supportsFallback(error) {
  const detail=isErrorDetail(error) ? error : null;
  const code=detail?.code || detail?.message;
  return ['DJVU_RANGE_UNSUPPORTED','DJVU_LAZY_UNSUPPORTED','DJVU_LAZY_METADATA_UNSUPPORTED'].some(value=>value===code);
}
/** @param {unknown} transportFailure @param {unknown} error */
function requireSupportedFallback(transportFailure,error) {
  if (!transportAllowsFallback(transportFailure)) throw transportFailure;
  if (!supportsFallback(error)) throw error;
}
/** @param {DjvuContext} context @param {URL} resolved @param {AbortSignal} signal @param {number} cacheBytes */
async function openFullNative(context,resolved,signal,cacheBytes) {
  signal.throwIfAborted();
  /** @type {ReturnType<typeof createDjvuWorkerAdapter> | undefined} */
  let worker;
  const abort = () => worker?.close(signal.reason);
  signal.addEventListener('abort',abort,{once:true});
  // The URL is already pinned and this path has authorized a full read.
  // Initialize only the decoder while downloading and authenticating the
  // original; neither source bytes nor OCR reach it before validation.
  const preparing = (async () => {
    worker = createDjvuWorkerAdapter(workerUrl,{cacheBytes});
    await worker.prepare(signal);
    return worker;
  })();
  // Keep the source verdict authoritative even if engine preparation fails first.
  preparing.catch(()=>{});
  try {
    const response = await context.fetchReaderUrl(resolved.href, {signal});
    if (!response.ok) throw new Error(`DJVU_SOURCE_HTTP_${response.status}`);
    /** @type {Uint8Array<ArrayBuffer>} */
    const packed = await VoiceOfMLReaderSecurity.readBytes(response, VoiceOfMLReaderSecurity.LIMITS.documentBytes);
    signal.throwIfAborted();
    const hash = [...new Uint8Array(await crypto.subtle.digest('SHA-256',packed))]
      .map(value=>value.toString(16).padStart(2,'0')).join('');
    signal.throwIfAborted();
    if (context.ocrManifestUrl) await attachHistoricalOcr(context,hash,signal);
    signal.throwIfAborted();
    const preparedWorker = await preparing;
    const bytes = packed.byteOffset === 0 && packed.byteLength === packed.buffer.byteLength
      ? packed.buffer : packed.buffer.slice(packed.byteOffset,packed.byteOffset+packed.byteLength);
    const opened = await openDjvuDocument({workerUrl,bytes,signal,cacheBytes,cachePages:2,preparedWorker});
    const document = Object.assign(opened,{sourceSha256:hash});
    context.trackReaderResource(()=>document.destroy());
    context.assertReaderActive();
    return document;
  } catch (error) {
    worker?.close(error);
    throw error;
  } finally {
    signal.removeEventListener('abort',abort);
  }
}
/** @param {DjvuContext} context @param {string} hash @param {AbortSignal} signal */
async function attachHistoricalOcr(context,hash,signal) {
  try {
    const raw = await context.readPdfOcrJson(context.ocrManifestUrl, VoiceOfMLReaderSecurity.LIMITS.manifestBytes, '', 0, 'high');
    VoiceOfMLReaderSecurity.validatePdfOcrManifest(raw);
    if (!isErrorDetail(raw) || raw.source_sha256 !== hash) throw new Error('DJVU_OCR_SOURCE_MISMATCH');
    context.pdfOcrManifest = raw;
  } catch (error) {
    if (signal.aborted) throw error;
    console.warn('DjVu OCR text does not match this source; using embedded text', error);
    context.ocrManifestUrl = '';
    context.pdfOcrManifest = null;
  }
}
const workerUrl = new URL("./reader-djvu-engine-worker.mjs", import.meta.url);

// Native URLs can be read directly without creating or fetching a page map.
/** @param {NativeDjvuContext} context */
export async function openNativeDjvu(context) {
  const signal = context.readerAbortController.signal;
  signal.throwIfAborted();
  const resolving = resolveDjvuSource(context,context.sourceUrl,signal);
  const cacheBytes=matchMedia('(max-width: 700px)').matches ? 32*1024*1024 : 64*1024*1024;
  // Historical OCR is retained only under the already-established full-source
  // SHA-256 check below. Until the bytes can be independently authenticated,
  // never substitute OCR from an unverified metadata claim.
  if (!context.ocrManifestUrl) return openRangedNative(context,resolving,signal,cacheBytes);
  return openFullNative(context,await resolving,signal,cacheBytes);
}

/** @param {unknown} error @param {unknown} prepareFailure @param {boolean} rangeAuthorized
 * @param {AbortSignal} signal @param {unknown} transportFailure */
function checkNativeFallback(error, prepareFailure, rangeAuthorized, signal, transportFailure) {
  if (error === prepareFailure) {
    const failure = /** @type {{error: unknown}} */ (prepareFailure);
    throw failure.error;
  }
  if (signal.aborted) throw error;
  if (!rangeAuthorized && (!isErrorDetail(error) || error.code !== 'DJVU_RANGE_UNSUPPORTED')) throw error;
  requireSupportedFallback(transportFailure,error);
}

/** @param {NativeDjvuContext} context @param {Promise<URL>} resolving @param {AbortSignal} signal @param {number} cacheBytes */
async function openRangedNative(context,resolving,signal,cacheBytes) {
  /** @type {DjvuRange | undefined} */
  let range;
  /** @type {ReturnType<typeof createDjvuWorkerAdapter> | undefined} */
  let documentWorker;
  const stopBootstrap=new AbortController();
  const abortBootstrap=()=>{stopBootstrap.abort(signal.reason);documentWorker?.close(signal.reason);};
  signal.addEventListener('abort',abortBootstrap,{once:true});
  if (signal.aborted) abortBootstrap();
  // Preparing the decoder needs no source bytes. Only begin Range I/O once
  // revision resolution succeeds, even if decoder preparation fails first.
  let rangeAuthorized = false, documentOpened = false;
  /** @type {import('./reader-djvu-worker.mjs').DjvuRangeReader} */
  const deferredRange = {get ownedReads(){return range?.ownedReads === true;},
    get total(){return rangeAuthorized ? (range?.total ?? 0) : 0}, get failure(){return range?.failure},
    read:(offset,length)=>requireRange(rangeAuthorized ? range : undefined).read(offset,length), close:()=>range?.close()};
  const prepareFailure = {error: /** @type {unknown} */ (null)};
  const preparing=Promise.resolve().then(()=>{
    stopBootstrap.signal.throwIfAborted();
    documentWorker=createDjvuWorkerAdapter(workerUrl,{cacheBytes,rangeReader:deferredRange,onRangeFailure(error){
      // Text, outline and speculative reads share this worker. Their caller
      // can disappear even though the terminal failure affects the whole book.
      if (documentOpened && !signal.aborted && isErrorDetail(error) && error.code === 'DJVU_RANGE_TRANSIENT')
        context.fail('DjVu 数据读取失败。','READER_DJVU_TRANSPORT');
    }});
    return documentWorker.prepare(stopBootstrap.signal);
  }).catch(error=>{
    prepareFailure.error = error;
    throw prepareFailure;
  });
  preparing.catch(()=>{});
  let resolved;
  try {
    resolved = await resolving;
    signal.throwIfAborted();
  } catch (error) {
    stopBootstrap.abort(error);
    signal.removeEventListener('abort',abortBootstrap);
    documentWorker?.close(error);
    throw error;
  }
  const stopOutline=new AbortController();
  const abortOutline=()=>stopOutline.abort(signal.reason);
  signal.addEventListener('abort',abortOutline,{once:true});
  if(signal.aborted)abortOutline();
  const outlineFallback=()=>openFullOutline(context,resolved,requireRange(range),stopOutline.signal,cacheBytes);
  /** @type {typeof fetch} */
  const fetchResponse=(url,options)=>context.fetchWithReaderTimeout(
    typeof url === 'string' ? url : url instanceof URL ? url.href : url.url,context.READER_PROXY_TIMEOUT_MS,options);
  try {
    const rangeUrl=context.readerContentUrl(resolved.href);
    const opening=openDjvuRange({signal:stopBootstrap.signal,fetchResponse,url:rangeUrl,
      readBytes:(response,limit)=>VoiceOfMLReaderSecurity.readBytes(response,limit),
      timeoutMs:context.READER_PROXY_TIMEOUT_MS}).then(value=>{range=value;return value;});

    await Promise.all([opening,preparing]);
    rangeAuthorized = true;
    const document=await openDjvuDocument({workerUrl,rangeReader:range,preparedWorker:documentWorker,
      signal,outlineFallback,cacheBytes,cachePages:2});
    // Until the transport has authenticated all slices as one immutable
    // object, do not claim to have locally computed a whole-file digest.
    context.trackReaderResource(()=>{stopOutline.abort();stopBootstrap.abort();
      signal.removeEventListener('abort',abortOutline);signal.removeEventListener('abort',abortBootstrap);document.destroy();});
    context.assertReaderActive();
    documentOpened = true;
    return document;
  } catch (error) {
    stopOutline.abort();stopBootstrap.abort();signal.removeEventListener('abort',abortOutline);
    signal.removeEventListener('abort',abortBootstrap);documentWorker?.close();
    const transportFailure=range?.failure;
    range?.close();
    // Engine setup cannot authorize a full-source fallback. Only a Range
    // capability failure or an unsupported lazy open may do so.
    checkNativeFallback(error,prepareFailure,rangeAuthorized,signal,transportFailure);
    return openFullNative(context,resolved,signal,cacheBytes);
  }
}

/** @param {DjvuContext} context @param {DjvuManifest} manifest @param {Promise<unknown>} pageMapPromise */
export async function openDirectDjvu(context, manifest, pageMapPromise) {
  const ref = manifest.primary.resource;
  const signal = context.readerAbortController.signal;
  // Prepare only the decoder while loading the checked source and page map.
  // The Worker must not receive any document bytes until both are verified.
  const download = new AbortController();
  const cacheBytes = matchMedia("(max-width: 700px)").matches ? 32 * 1024 * 1024 : 64 * 1024 * 1024;
  /** @type {ReturnType<typeof createDjvuWorkerAdapter> | undefined} */
  let worker;
  const stopDownload = () => {
    download.abort(signal.reason);
    worker?.close(signal.reason);
  };
  signal.addEventListener("abort", stopDownload, { once: true });
  if (signal.aborted) stopDownload();
  const source = (async () => {
    const response = await context.fetchReaderUrl(context.v3ResourceUrl(ref), { signal: download.signal });
    if (!response.ok) throw new Error(`DJVU_SOURCE_HTTP_${response.status}`);
    // A checksummed immutable primary has an exact expected length. Reject a
    // larger body immediately rather than buffering up to the generic ceiling.
    const bytes = await VoiceOfMLReaderSecurity.readBytes(response, Math.min(ref.bytes, VoiceOfMLReaderSecurity.LIMITS.documentBytes));
    signal.throwIfAborted?.();
    if (bytes.byteLength !== ref.bytes) throw new Error("DJVU_PRIMARY_SIZE_MISMATCH");
    const hash = [...new Uint8Array(await crypto.subtle.digest("SHA-256", bytes))]
      .map(value => value.toString(16).padStart(2, "0")).join("");
    if (hash !== ref.sha256) throw new Error("DJVU_PRIMARY_HASH_MISMATCH");
    return bytes;
  })();
  const preparing = Promise.resolve().then(async () => {
    signal.throwIfAborted();
    worker = createDjvuWorkerAdapter(workerUrl, {cacheBytes});
    await worker.prepare(signal);
    return worker;
  });
  // Keep integrity failures authoritative even if the engine fails first.
  preparing.catch(() => {});
  try {
    const [packed, pageMap] = await Promise.all([source, pageMapPromise]);
    context.assertReaderActive();
    const preparedWorker = await preparing;
    const bytes = packed.byteOffset === 0 && packed.byteLength === packed.buffer.byteLength
      ? packed.buffer : packed.buffer.slice(packed.byteOffset, packed.byteOffset + packed.byteLength);
    const document = await openDjvuDocument({workerUrl, bytes, pageMap, signal, cacheBytes,
      cachePages: 2, preparedWorker});
    context.trackReaderResource(() => document.destroy());
    context.assertReaderActive();
    return document;
  } catch (error) {
    download.abort();
    worker?.close(error);
    throw error;
  } finally {
    signal.removeEventListener("abort", stopDownload);
  }
}