File size: 10,513 Bytes
2c1d035 1743620 2c1d035 b3b9424 45407fd 2c1d035 45407fd 2c1d035 45407fd 2c1d035 45407fd 1743620 b3b9424 f6b4ee0 e5ab2df b3b9424 45407fd 2c1d035 b3b9424 2c1d035 1743620 2c1d035 1743620 e5ab2df 1743620 e5ab2df 1743620 e5ab2df 1743620 e5ab2df 1743620 2c1d035 e5ab2df 2c1d035 1743620 e5ab2df 2c1d035 | 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 | export function createReaderPdfEngine(readerContext) {
function loadPdfTaskWithTimeout(pdfjs, options, url, initial = null) {
readerContext.assertReaderActive();
let task = null, documentReady = false;
const owner = new AbortController();
return new Promise((resolve, reject) => {
let timeout = 0,
destroyed = false;
const destroy = () => {
if (destroyed) return;
destroyed = true;
owner.abort(readerContext.readerAbortError());
clearTimeout(timeout);
try {
task?.destroy()?.catch?.(() => {});
} catch (_) {}
reject(readerContext.readerAbortError());
};
const untrack = readerContext.trackReaderResource(destroy);
timeout = setTimeout(() => {
reject(new Error("reader PDF timeout"));
untrack();
destroy();
}, readerContext.READER_PROXY_TIMEOUT_MS);
readerContext.openPdfRangeTask(pdfjs, options(url), {
signal:owner.signal, readBytes:VoiceOfMLReaderSecurity.readBytes, initial,
limit:VoiceOfMLReaderSecurity.LIMITS.documentBytes,
canPrefetchOpening: () => !!readerContext.pdfV3Manifest && readerContext.readerRestorationLoaded &&
(!readerContext.readerRestorationEntry || Number(readerContext.readerRestorationEntry.page) <= 1),
canPrefetchFirstPage: () => readerContext.capability?.mode === "pdf" &&
readerContext.readerRestorationLoaded && !readerContext.restorationFailed &&
(!readerContext.readerRestorationEntry || Number(readerContext.readerRestorationEntry.page) === 1),
onError() {
if (!documentReady || readerContext.readerAbortController.signal.aborted || readerContext.capability.mode !== "pdf") return;
// Page retries cannot revive a destroyed PDF.js document. Capture an
// eligible position before failure stops work; reload owns recovery.
readerContext.saveProgress();
readerContext.fail("PDF 数据读取失败,请重试加载。", "READER_PDF_TRANSPORT");
}
}).then(opened => {
task = opened;
if (destroyed) {task.destroy()?.catch?.(() => {});throw readerContext.readerAbortError();}
return task.promise;
}).then(
(document) => {
clearTimeout(timeout);
documentReady = true;
if (readerContext.readerAbortController.signal.aborted) {
destroy();
return;
}
resolve(document);
},
(error) => {
clearTimeout(timeout);
reject(error);
untrack();
destroy();
}
);
});
}
function loadPdfWithTimeout(pdfjs, options, originalUrl = readerContext.sourceUrl, proxyUrl = readerContext.contentUrl, takeInitial = () => null) {
return readerContext.retryReaderProxy(() => readerContext.loadPdfTaskWithTimeout(pdfjs, options, proxyUrl, takeInitial(proxyUrl))).catch((error) => {
readerContext.assertReaderActive();
if (error && error.name === "AbortError") throw error;
if (readerContext.retryableReaderProxyError(error)) throw error;
return readerContext.loadPdfTaskWithTimeout(pdfjs, options, originalUrl);
});
}
function preloadPdfEngine() {
if (!readerContext.pdfEnginePreload) readerContext.pdfEnginePreload = readerContext.loadPdfEngine().then(readerContext.preparePdfWorker);
return readerContext.pdfEnginePreload;
}
async function preparePdfWorker(pdfjs) {
for (let attempt = 0; attempt < 3; attempt++) {
readerContext.assertReaderActive();
if (attempt) await readerContext.waitForReader(attempt * 500);
try {
return await readerContext.preparePdfWorkerAttempt(pdfjs, attempt);
} catch (error) {
readerContext.assertReaderActive();
if (error?.code !== "READER_ENGINE_NETWORK" || attempt === 2) throw error;
}
}
}
async function preparePdfWorkerAttempt(pdfjs, attempt) {
readerContext.assertReaderActive();
if (readerContext.capability.mode !== "pdf" && !readerContext.pdfPrimarySource()) return pdfjs;
pdfjs.GlobalWorkerOptions.workerSrc = attempt
? `${readerContext.PDFJS_WORKER_URL}?reader-worker-retry=${attempt}` : readerContext.PDFJS_WORKER_URL;
const worker = new pdfjs.PDFWorker();
readerContext.pdfWorker = worker;
let timer, destroyed = false;
const destroy = () => {
if (destroyed) return;
destroyed = true;
clearTimeout(timer);
worker.destroy();
if (readerContext.pdfWorker === worker) {
readerContext.pdfWorker = null;
readerContext.releasePdfWorker = null;
}
};
readerContext.releasePdfWorker = destroy;
const untrack = readerContext.trackReaderResource(destroy);
try {
await readerContext.awaitReader(Promise.race([
worker.promise,
new Promise((_, reject) => {
timer = setTimeout(() => reject(new Error("PDF worker timeout")), 20000);
})
]));
readerContext.assertReaderActive();
return pdfjs;
} catch (error) {
untrack();
destroy();
readerContext.assertReaderActive();
throw Object.assign(new Error("PDF 阅读组件下载失败,请检查网络后重试加载,或下载原文件。"),
{ code: "READER_ENGINE_NETWORK", cause: error });
} finally {
clearTimeout(timer);
}
}
async function loadPdfEngine() {
for (let attempt = 0; attempt < 3; attempt++) {
readerContext.assertReaderActive();
if (attempt) await readerContext.waitForReader(attempt * 500);
readerContext.assertReaderActive();
// Browsers can retain a rejected import for the life of this document.
// Use two bounded retry URLs for the same pinned bytes, never a random URL.
const url = attempt ? `${readerContext.PDFJS_URL}?reader-module-retry=${attempt}` : readerContext.PDFJS_URL;
let timer;
try {
const pdfjs = await readerContext.awaitReader(
Promise.race([
import(url),
new Promise((_, reject) => {
timer = setTimeout(
() => reject(new DOMException("PDF engine timeout", "TimeoutError")),
20000
);
})
])
);
readerContext.assertReaderActive();
return pdfjs;
} catch (error) {
readerContext.assertReaderActive();
const networkFailure =
error?.name === "TimeoutError" ||
/failed to fetch dynamically imported module|error loading dynamically imported module|importing a module script failed/i.test(
error?.message || ""
);
if (!networkFailure) throw error;
if (attempt === 2)
throw Object.assign(
new Error("PDF 阅读组件下载失败,请检查网络后重试加载,或下载原文件。"),
{ code: "READER_ENGINE_NETWORK", cause: error }
);
} finally {
clearTimeout(timer);
}
}
}
function loadPdfDocument(target = readerContext.sourceUrl) {
readerContext.assertReaderActive();
const proxyUrl = readerContext.readerContentUrl(target);
if (!readerContext.pdfFetchPolicy) {
readerContext.pdfFetchPolicy = readerContext.createPdfFetchPolicy();
readerContext.trackReaderResource(() => { readerContext.pdfFetchPolicy?.dispose(); readerContext.pdfFetchPolicy = null; });
}
readerContext.pdfFetchPolicy.add([target, proxyUrl]);
const owner = new AbortController();
const untrack = readerContext.trackReaderResource(() => owner.abort(readerContext.readerAbortError()));
let pageOneKnown = false;
const navigation = readerContext.readerRuntime?.currentGeneration("navigation");
readerContext.readerRestorationPromise?.then(entry => {
pageOneKnown = readerContext.capability?.mode === "pdf" && !readerContext.restorationFailed &&
(!entry || Number(entry.page) === 1);
}).catch(() => {});
// This is the first demand, not extra speculation or a larger/full download.
// Keep it owned while engine preparation is pending and consume it only once.
let initial = readerContext.preparePdfInitialRange({url:proxyUrl, rangeChunkSize:262144}, {
signal:AbortSignal.any([owner.signal, readerContext.readerAbortController.signal]),
readBytes:VoiceOfMLReaderSecurity.readBytes, limit:VoiceOfMLReaderSecurity.LIMITS.documentBytes,
canPrefetchFirstPage: () => pageOneKnown && !owner.signal.aborted &&
navigation === readerContext.readerRuntime?.currentGeneration("navigation")
});
initial.catch(() => {});
let initialHandedOff = false, rangeTransportAvailable = false;
const takeInitial = url => {
if (url !== proxyUrl) return null;
const pending = initial;
initial = null;
if (pending && rangeTransportAvailable) initialHandedOff = true;
return pending;
};
return readerContext.measurePdf(readerContext.preloadPdfEngine(), "engine").then((pdfjs) => {
readerContext.assertReaderActive();
rangeTransportAvailable = typeof pdfjs.PDFDataRangeTransport === "function";
pdfjs.GlobalWorkerOptions.workerSrc = readerContext.PDFJS_WORKER_URL;
const options = (url) => ({
url,
worker: readerContext.pdfWorker,
// Bound demand reads for original and converted PDFs alike. Streaming
// otherwise keeps the full download running alongside these ranges.
rangeChunkSize: 262144,
disableAutoFetch: true,
disableStream: true,
wasmUrl: readerContext.PDFJS_WASM_URL,
cMapUrl: readerContext.PDFJS_CMAP_URL,
cMapPacked: true,
standardFontDataUrl: readerContext.PDFJS_STANDARD_FONT_URL,
withCredentials: false
});
return readerContext.measurePdf(readerContext.loadPdfWithTimeout(pdfjs, options, target, proxyUrl, takeInitial), "document");
}).finally(() => {
initial = null;
untrack();
// A validated first-page section can still be serving getPage/render
// after the document promise resolves. The transport now owns those
// reads through cancelInitial; only an unhanded bootstrap ends here.
if (!initialHandedOff) owner.abort(readerContext.readerAbortError());
});
}
return {
loadPdfTaskWithTimeout,
loadPdfWithTimeout,
preloadPdfEngine,
preparePdfWorker,
preparePdfWorkerAttempt,
loadPdfEngine,
loadPdfDocument
};
}
|