vomebook commited on
Commit ·
68f392a
1
Parent(s): 50e6523
Tighten checked types at search and Reader boundaries
Browse files- config/types/jsconfig.reader-exact.json +1 -0
- config/types/jsconfig.strict.json +4 -0
- pyrightconfig.strict.json +2 -1
- static/app.js +1 -1
- static/reader/core/reader-document-loader.mjs +2 -2
- static/reader/core/reader-request-manager.js +2 -2
- static/reader/pdf/reader-pdf-network.mjs +102 -75
- static/reader/pdf/reader-pdf-page-window.mjs +2 -1
- static/reader/search/reader-search-controller.mjs +3 -2
- static/reader/ui/reader-progress.mjs +2 -2
- static/reader/ui/reader-speech.mjs +6 -8
- static/search/requests/infrastructure/response-cache.js +5 -4
- tests/gates/test_static_checks.py +35 -2
- tests/reader/core/test_reader_store_types.ts +1 -1
- tests/reader/pdf-network/test_reader_pdf_network_contract.mjs +29 -0
- typings/reader-globals.d.ts +4 -2
- typings/reader-pdf-engine-strict.d.ts +1 -4
- typings/search-app.d.ts +1 -1
- typings/search-bootstrap.d.ts +1 -1
- typings/search-reader-host.d.ts +1 -1
- typings/search-snapshots.d.ts +2 -2
- typings/tts-client-strict.d.ts +1 -1
config/types/jsconfig.reader-exact.json
CHANGED
|
@@ -46,6 +46,7 @@
|
|
| 46 |
"../../static/reader/pdf/reader-djvu-loader.mjs",
|
| 47 |
"../../static/reader/pdf/reader-pdf-range-cache.mjs",
|
| 48 |
"../../static/reader/pdf/reader-pdf-range-hints.mjs",
|
|
|
|
| 49 |
"../../static/reader/pdf/reader-pdf-text-store.mjs",
|
| 50 |
"../../static/reader/pdf/reader-engine-preload.js",
|
| 51 |
"../../static/reader/formats/reader-section-virtualizer.js",
|
|
|
|
| 46 |
"../../static/reader/pdf/reader-djvu-loader.mjs",
|
| 47 |
"../../static/reader/pdf/reader-pdf-range-cache.mjs",
|
| 48 |
"../../static/reader/pdf/reader-pdf-range-hints.mjs",
|
| 49 |
+
"../../static/reader/pdf/reader-pdf-network.mjs",
|
| 50 |
"../../static/reader/pdf/reader-pdf-text-store.mjs",
|
| 51 |
"../../static/reader/pdf/reader-engine-preload.js",
|
| 52 |
"../../static/reader/formats/reader-section-virtualizer.js",
|
config/types/jsconfig.strict.json
CHANGED
|
@@ -4,6 +4,10 @@
|
|
| 4 |
"checkJs": true,
|
| 5 |
"noEmit": true,
|
| 6 |
"strict": true,
|
|
|
|
|
|
|
|
|
|
|
|
|
| 7 |
"target": "esnext",
|
| 8 |
"module": "esnext",
|
| 9 |
"moduleResolution": "bundler",
|
|
|
|
| 4 |
"checkJs": true,
|
| 5 |
"noEmit": true,
|
| 6 |
"strict": true,
|
| 7 |
+
"noImplicitOverride": true,
|
| 8 |
+
"noImplicitReturns": true,
|
| 9 |
+
"noFallthroughCasesInSwitch": true,
|
| 10 |
+
"exactOptionalPropertyTypes": true,
|
| 11 |
"target": "esnext",
|
| 12 |
"module": "esnext",
|
| 13 |
"moduleResolution": "bundler",
|
pyrightconfig.strict.json
CHANGED
|
@@ -139,5 +139,6 @@
|
|
| 139 |
"backend/upstream_http.py"
|
| 140 |
],
|
| 141 |
"pythonVersion": "3.11",
|
| 142 |
-
"typeCheckingMode": "strict"
|
|
|
|
| 143 |
}
|
|
|
|
| 139 |
"backend/upstream_http.py"
|
| 140 |
],
|
| 141 |
"pythonVersion": "3.11",
|
| 142 |
+
"typeCheckingMode": "strict",
|
| 143 |
+
"reportUnnecessaryTypeIgnoreComment": "error"
|
| 144 |
}
|
static/app.js
CHANGED
|
@@ -2418,7 +2418,7 @@ function getBrowserFileReadUrl(f, currentRepo, path) {
|
|
| 2418 |
const fileLink = getBrowserFileLink(currentRepo, path, f);
|
| 2419 |
const sourceRepo = currentRepo.startsWith("VoiceOfML/") ? currentRepo : `VoiceOfML/${currentRepo}`;
|
| 2420 |
const assetPath = path ? `${path}/${displayName}` : displayName;
|
| 2421 |
-
let record = { File: f.name, Extension: f.ext, Link: fileLink, ReturnUrl: location.href };
|
| 2422 |
record = applyReaderAsset(record, sourceRepo, assetPath, fileLink);
|
| 2423 |
return isReadableRecord(record) ? VoiceOfMLReader.readerUrl(record, "/static/reader.html") : "";
|
| 2424 |
}
|
|
|
|
| 2418 |
const fileLink = getBrowserFileLink(currentRepo, path, f);
|
| 2419 |
const sourceRepo = currentRepo.startsWith("VoiceOfML/") ? currentRepo : `VoiceOfML/${currentRepo}`;
|
| 2420 |
const assetPath = path ? `${path}/${displayName}` : displayName;
|
| 2421 |
+
let record = { File: f.name, ...(f.ext === undefined ? {} : { Extension: f.ext }), Link: fileLink, ReturnUrl: location.href };
|
| 2422 |
record = applyReaderAsset(record, sourceRepo, assetPath, fileLink);
|
| 2423 |
return isReadableRecord(record) ? VoiceOfMLReader.readerUrl(record, "/static/reader.html") : "";
|
| 2424 |
}
|
static/reader/core/reader-document-loader.mjs
CHANGED
|
@@ -11,7 +11,7 @@
|
|
| 11 |
* @property {(error: unknown) => boolean} retryableReaderProxyError
|
| 12 |
* @property {(delay: number) => Promise<void>} waitForReader
|
| 13 |
* @property {(rawUrl: string) => string} readerContentUrl
|
| 14 |
-
* @property {(url: string, timeoutMs?: number, requestInit?:
|
| 15 |
* @property {<T>(open: () => Promise<T>) => Promise<T>} retryReaderProxy
|
| 16 |
* @property {(url: string, requestInit?: RequestInit) => Promise<Response>} fetchReaderUrl
|
| 17 |
* @property {() => Promise<Response>} fetchReaderResponse
|
|
@@ -60,7 +60,7 @@ export function createReaderDocumentLoader(readerContext) {
|
|
| 60 |
}));
|
| 61 |
}
|
| 62 |
|
| 63 |
-
/** @param {string} url @param {number} [timeoutMs] @param {
|
| 64 |
function fetchWithReaderTimeout(url, timeoutMs = readerContext.READER_PROXY_TIMEOUT_MS, requestInit = {}) {
|
| 65 |
return readerContext.readerRequestManager.request(url, timeoutMs, requestInit);
|
| 66 |
}
|
|
|
|
| 11 |
* @property {(error: unknown) => boolean} retryableReaderProxyError
|
| 12 |
* @property {(delay: number) => Promise<void>} waitForReader
|
| 13 |
* @property {(rawUrl: string) => string} readerContentUrl
|
| 14 |
+
* @property {(url: string, timeoutMs?: number, requestInit?: ReaderRequestInit) => Promise<Response>} fetchWithReaderTimeout
|
| 15 |
* @property {<T>(open: () => Promise<T>) => Promise<T>} retryReaderProxy
|
| 16 |
* @property {(url: string, requestInit?: RequestInit) => Promise<Response>} fetchReaderUrl
|
| 17 |
* @property {() => Promise<Response>} fetchReaderResponse
|
|
|
|
| 60 |
}));
|
| 61 |
}
|
| 62 |
|
| 63 |
+
/** @param {string} url @param {number} [timeoutMs] @param {ReaderRequestInit} [requestInit] */
|
| 64 |
function fetchWithReaderTimeout(url, timeoutMs = readerContext.READER_PROXY_TIMEOUT_MS, requestInit = {}) {
|
| 65 |
return readerContext.readerRequestManager.request(url, timeoutMs, requestInit);
|
| 66 |
}
|
static/reader/core/reader-request-manager.js
CHANGED
|
@@ -98,7 +98,7 @@
|
|
| 98 |
});
|
| 99 |
}
|
| 100 |
|
| 101 |
-
/** @param {RequestInfo | URL} url @param {number} timeoutMs @param {
|
| 102 |
* @param {number | null} [bufferLimit] @returns {Promise<Response>} */
|
| 103 |
function request(url, timeoutMs, requestInit = {}, bufferLimit = null) {
|
| 104 |
if (disposed) return Promise.reject(new DOMException("Reader disposed", "AbortError"));
|
|
@@ -246,7 +246,7 @@
|
|
| 246 |
return Object.freeze({
|
| 247 |
request,
|
| 248 |
/** @param {RequestInfo | URL} url @param {number} timeoutMs @param {number} limit
|
| 249 |
-
* @param {
|
| 250 |
requestBuffered(url, timeoutMs, limit, requestInit = {}) {
|
| 251 |
if (!Number.isSafeInteger(limit) || limit < 0) return Promise.reject(new RangeError("Invalid response limit"));
|
| 252 |
return request(url, timeoutMs, requestInit, limit);
|
|
|
|
| 98 |
});
|
| 99 |
}
|
| 100 |
|
| 101 |
+
/** @param {RequestInfo | URL} url @param {number} timeoutMs @param {ReaderRequestInit} [requestInit]
|
| 102 |
* @param {number | null} [bufferLimit] @returns {Promise<Response>} */
|
| 103 |
function request(url, timeoutMs, requestInit = {}, bufferLimit = null) {
|
| 104 |
if (disposed) return Promise.reject(new DOMException("Reader disposed", "AbortError"));
|
|
|
|
| 246 |
return Object.freeze({
|
| 247 |
request,
|
| 248 |
/** @param {RequestInfo | URL} url @param {number} timeoutMs @param {number} limit
|
| 249 |
+
* @param {ReaderRequestInit} [requestInit] @returns {Promise<Response>} */
|
| 250 |
requestBuffered(url, timeoutMs, limit, requestInit = {}) {
|
| 251 |
if (!Number.isSafeInteger(limit) || limit < 0) return Promise.reject(new RangeError("Invalid response limit"));
|
| 252 |
return request(url, timeoutMs, requestInit, limit);
|
static/reader/pdf/reader-pdf-network.mjs
CHANGED
|
@@ -31,12 +31,13 @@ function abortable(promise, signal) {
|
|
| 31 |
* @typedef {{total: number, etag: string | null}} RangeVersion
|
| 32 |
* @typedef {ReturnType<typeof createPdfRangeCache>} RangeCache
|
| 33 |
* @typedef {{signal: AbortSignal, readBytes: (response: Response, limit: number) => Promise<Uint8Array>, limit: number, rangeLimit?: number, rangeCache?: RangeCache | null, canPrefetchFirstPage?: () => boolean}} RangeHooks
|
| 34 |
-
* @typedef {({bytes: Uint8Array
|
| 35 |
* @typedef {{begin: number, end: number}} Bounds
|
| 36 |
* @typedef {{bytes: Uint8Array}} BytesResult
|
| 37 |
* @typedef {ReturnType<typeof preparePdfRangeHint>} RangeHint
|
| 38 |
* @typedef {{begin: number, end: number, hint: RangeHint | null, demanded: boolean}} AdjacentTail
|
| 39 |
-
* @typedef {{
|
|
|
|
| 40 |
* @typedef {import('../../../typings/reader-pdf-engine-strict').PdfDocument} PdfDocument
|
| 41 |
* @typedef {{promise: Promise<PdfDocument>, destroy: () => Promise<void> | void}} PdfTask
|
| 42 |
* @typedef {{abort: () => void, requestDataRange: (begin: number, end: number) => void, onDataRange: (begin: number, bytes: Uint8Array) => void}} PdfTransport
|
|
@@ -60,8 +61,10 @@ async function readPdfRange(options, begin, end, {signal, readBytes, limit, rang
|
|
| 60 |
signal.throwIfAborted();
|
| 61 |
const key = new URL(options.url, globalThis.location?.href).href;
|
| 62 |
let cached = null;
|
| 63 |
-
try {
|
| 64 |
-
|
|
|
|
|
|
|
| 65 |
if (cached && expected) return {bytes:cached, total:expected.total, etag:expected.etag};
|
| 66 |
const response = await fetch(options.url, {
|
| 67 |
headers: {Range: `bytes=${begin}-${end-1}`}, signal, credentials:"same-origin"
|
|
@@ -75,9 +78,9 @@ async function readPdfRange(options, begin, end, {signal, readBytes, limit, rang
|
|
| 75 |
return {bytes, complete:true};
|
| 76 |
}
|
| 77 |
const match = /^bytes (\d+)-(\d+)\/(\d+)$/.exec(response.headers.get("Content-Range") || "");
|
| 78 |
-
if (response.status !== 206 || !match
|
| 79 |
-
|
| 80 |
-
|
| 81 |
if (total > (total === last + 1 - start ? limit : rangeLimit))
|
| 82 |
throw Object.assign(new Error("READER_RESOURCE_LIMIT"), {code:"READER_RESOURCE_LIMIT"});
|
| 83 |
if (start !== begin || last !== Math.min(end,total)-1 || total <= start) throw invalid();
|
|
@@ -92,7 +95,7 @@ async function readPdfRange(options, begin, end, {signal, readBytes, limit, rang
|
|
| 92 |
const bytes = await readBytes(response, last-start+1);
|
| 93 |
if (bytes.byteLength !== last-start+1) throw invalid();
|
| 94 |
signal.throwIfAborted();
|
| 95 |
-
try { rangeCache?.put(key, start, bytes,
|
| 96 |
catch (_) { /* Retaining an optional copy must never fail the document. */ }
|
| 97 |
return {bytes, total, etag, complete:bytes.byteLength === total};
|
| 98 |
} catch (error) {
|
|
@@ -120,15 +123,25 @@ function preparePdfRangeHint(options, begin, end, hooks, expected) {
|
|
| 120 |
};
|
| 121 |
const flush = () => {
|
| 122 |
for (const waiter of waiters) {
|
| 123 |
-
if (
|
|
|
|
| 124 |
waiters.delete(waiter);
|
| 125 |
-
if (failed) { waiter.resolve(null); continue; }
|
| 126 |
published = true;
|
| 127 |
// Each PDF.js range reader accepts one complete, exact requested buffer.
|
| 128 |
// A proper subrange must not wait for unrelated trailing hint bytes/EOF.
|
| 129 |
-
waiter.resolve({bytes:
|
| 130 |
}
|
| 131 |
};
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 132 |
const promise = readPdfRange(options, begin, end, {
|
| 133 |
...hooks,
|
| 134 |
readBytes: async (response, length) => {
|
|
@@ -158,20 +171,13 @@ function preparePdfRangeHint(options, begin, end, hooks, expected) {
|
|
| 158 |
}
|
| 159 |
}, expected).then(result => {
|
| 160 |
// readPdfRange retains only an exact, version-checked complete response.
|
| 161 |
-
|
|
|
|
| 162 |
loaded = bytes.byteLength;
|
| 163 |
complete = true;
|
| 164 |
flush();
|
| 165 |
return result;
|
| 166 |
-
},
|
| 167 |
-
failure = error;
|
| 168 |
-
failed = true;
|
| 169 |
-
flush();
|
| 170 |
-
// If a proper subrange was already used, a malformed/truncated remainder
|
| 171 |
-
// must invalidate that document, not silently leave an accepted bad stream.
|
| 172 |
-
notifyFailure();
|
| 173 |
-
return null;
|
| 174 |
-
});
|
| 175 |
return {
|
| 176 |
begin, end, promise,
|
| 177 |
/** @param {number} from @param {number} last */
|
|
@@ -190,13 +196,17 @@ function preparePdfRangeHint(options, begin, end, hooks, expected) {
|
|
| 190 |
|
| 191 |
// The first demand overlaps engine preparation. After its complete validation,
|
| 192 |
// qualified page-one files may overlap bounded opening or tail range hints.
|
| 193 |
-
/** @param {RangeOptions} options @param {RangeHooks} hooks
|
|
|
|
|
|
|
| 194 |
export async function preparePdfInitialRange(options, hooks) {
|
| 195 |
hooks = {...hooks, rangeCache:hooks.rangeCache === undefined ? sharedPdfRangeCache() : hooks.rangeCache};
|
| 196 |
const owner = new AbortController();
|
| 197 |
const signal = AbortSignal.any([hooks.signal, owner.signal]);
|
| 198 |
-
/** @type {
|
| 199 |
-
|
|
|
|
|
|
|
| 200 |
try {
|
| 201 |
/** @param {RangeVersion} metadata */
|
| 202 |
const onHeaders = metadata => {
|
|
@@ -204,8 +214,9 @@ export async function preparePdfInitialRange(options, hooks) {
|
|
| 204 |
// Start the existing two-chunk tail on validated headers, not after the
|
| 205 |
// first body finishes. This changes scheduling, not the fetched range.
|
| 206 |
const begin = Math.floor((metadata.total - 1) / options.rangeChunkSize) * options.rangeChunkSize - options.rangeChunkSize;
|
| 207 |
-
tail = preparePdfRangeHint(options, begin, metadata.total, {...hooks, signal}, metadata);
|
| 208 |
};
|
|
|
|
| 209 |
let first = null;
|
| 210 |
// A complete retained prefix may be reused only after a fresh no-store
|
| 211 |
// one-byte 206 proves its exact strong ETag and whole-document length.
|
|
@@ -217,35 +228,38 @@ export async function preparePdfInitialRange(options, hooks) {
|
|
| 217 |
const checked = await readPdfRange(options, 0, 1, {...hooks, signal, rangeCache:null}, null, null, true);
|
| 218 |
if (checked && checked.etag === previous.etag && checked.total === previous.total) {
|
| 219 |
let bytes = null;
|
| 220 |
-
try { bytes = hooks.rangeCache?.get(key, 0, Math.min(options.rangeChunkSize,
|
| 221 |
if (bytes) {
|
| 222 |
-
first = {bytes, total:
|
| 223 |
-
if (!first.complete) onHeaders(
|
| 224 |
}
|
| 225 |
}
|
| 226 |
}
|
| 227 |
first ||= await readPdfRange(options, 0, options.rangeChunkSize, {...hooks, signal}, null, onHeaders);
|
| 228 |
-
if (!first) { owner.abort(); return
|
| 229 |
-
|
| 230 |
-
/
|
| 231 |
-
const rangeFirst = /** @type {RangeResult & RangeVersion} */ (first);
|
| 232 |
-
const currentTail = /** @type {RangeHint | null} */ (tail);
|
| 233 |
-
/** @type {ReturnType<typeof preparePdfRangeHint>[]} */
|
| 234 |
const openingRanges = [];
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 235 |
const pageOne = !first.complete && hooks.canPrefetchFirstPage?.();
|
| 236 |
const connection = /** @type {(Navigator & {connection?: {saveData?: boolean, effectiveType?: string}}) | undefined} */ (globalThis.navigator)?.connection;
|
| 237 |
-
const
|
|
|
|
| 238 |
const rangeChunkSize = first.complete ? options.rangeChunkSize :
|
| 239 |
-
choosePdfRangeChunkSize(first.bytes,
|
| 240 |
// The ordinary tail ends after startxref but some flat files store a
|
| 241 |
// large xref immediately before it. One extra chunk avoids serial tiny
|
| 242 |
// reads; it remains ETag-bound and is suppressed for data-saving modes.
|
| 243 |
-
const largeFlatTail =
|
| 244 |
-
|
| 245 |
-
|
| 246 |
-
?
|
| 247 |
-
|
| 248 |
-
if (tailStart && currentTail) extendedTail = preparePdfRangeHint(options, tailStart, currentTail.begin, {...hooks, signal}, rangeFirst);
|
| 249 |
// A wide, classic xref (or a distant xref stream) can start one chunk
|
| 250 |
// before the normal trailer hint. Read at most that adjacent chunk, and
|
| 251 |
// only after the whole trailer range has passed its byte/ETag checks.
|
|
@@ -256,16 +270,16 @@ export async function preparePdfInitialRange(options, hooks) {
|
|
| 256 |
if (xrefTail && currentTail) void currentTail.promise.then(result => {
|
| 257 |
if (!result || signal.aborted || xrefTail.demanded || !hooks.canPrefetchFirstPage?.()) return;
|
| 258 |
const begin = adjacentXrefChunkStart(result.bytes, xrefTail.end, rangeChunkSize);
|
| 259 |
-
if (begin) xrefTail.hint = preparePdfRangeHint(options, begin, xrefTail.end, {...hooks, signal},
|
| 260 |
}).catch(() => {});
|
| 261 |
const end = pageOne
|
| 262 |
-
? firstPageSectionEnd(first.bytes,
|
| 263 |
-
(extraLookahead ? firstImageSectionEnd(first.bytes,
|
| 264 |
for (let begin = options.rangeChunkSize; begin < end; begin += options.rangeChunkSize * 2) {
|
| 265 |
const last = Math.min(end, begin + options.rangeChunkSize * 2);
|
| 266 |
-
openingRanges.push(preparePdfRangeHint(options, begin, last, {...hooks, signal},
|
| 267 |
}
|
| 268 |
-
return {...first, tail, extendedTail, xrefTail, openingRanges, rangeChunkSize, cancelInitial
|
| 269 |
} catch (error) {
|
| 270 |
owner.abort(error);
|
| 271 |
throw error;
|
|
@@ -285,7 +299,10 @@ export async function openPdfRangeTask(pdfjs, options, {signal, readBytes, limit
|
|
| 285 |
let task = null;
|
| 286 |
/** @type {InitialRange | null} */
|
| 287 |
let prepared = null;
|
|
|
|
|
|
|
| 288 |
let stopped = false;
|
|
|
|
| 289 |
const failure = Promise.withResolvers();
|
| 290 |
failure.promise.catch(() => {});
|
| 291 |
/** @type {(Bounds & {resolve: () => void})[]} */
|
|
@@ -307,10 +324,11 @@ export async function openPdfRangeTask(pdfjs, options, {signal, readBytes, limit
|
|
| 307 |
const index = priority >= 0 ? priority :
|
| 308 |
(!boundedMetadata || rangeReads < PDF_METADATA_RANGE_CONCURRENCY - 1 ? 0 : -1);
|
| 309 |
if (index < 0) return;
|
| 310 |
-
rangeWaiters.splice(index,1)
|
|
|
|
| 311 |
}
|
| 312 |
};
|
| 313 |
-
/** @param {number} begin @param {number} end */
|
| 314 |
const admitMetadata = (begin,end) => {
|
| 315 |
if (!metadataAdmission) return Promise.resolve(null);
|
| 316 |
active.throwIfAborted();
|
|
@@ -358,13 +376,17 @@ export async function openPdfRangeTask(pdfjs, options, {signal, readBytes, limit
|
|
| 358 |
signal.addEventListener("abort", cancelled, {once:true});
|
| 359 |
// Optional admission for demand reads only: the bootstrap, tail and opening
|
| 360 |
// hints are already bounded. A queued read is cancelled with its document.
|
| 361 |
-
/** @param {number} begin @param {number} end
|
| 362 |
-
const read = async (begin, end
|
|
|
|
|
|
|
| 363 |
const metadataRelease = await admitMetadata(begin,end);
|
| 364 |
let release = null;
|
| 365 |
try {
|
| 366 |
release = admitRange ? await admitRange(active) : null;
|
| 367 |
-
|
|
|
|
|
|
|
| 368 |
} finally {
|
| 369 |
release?.();
|
| 370 |
metadataRelease?.();
|
|
@@ -394,14 +416,14 @@ export async function openPdfRangeTask(pdfjs, options, {signal, readBytes, limit
|
|
| 394 |
previous.rows.push(row);
|
| 395 |
} else groups.push({begin:row.begin, end:row.end, rows:[row], gapBytes:0});
|
| 396 |
}
|
| 397 |
-
for (const group of groups) read(group.begin, group.end
|
| 398 |
for (const row of group.rows)
|
| 399 |
-
row.resolve({bytes:
|
| 400 |
}, error => { for (const row of group.rows) row.reject(error); });
|
| 401 |
};
|
| 402 |
-
/** @param {number} begin @param {number} end */
|
| 403 |
const demand = (begin, end) => {
|
| 404 |
-
if (!metadataAdmission) return read(begin, end
|
| 405 |
if (active.aborted) return Promise.reject(active.reason);
|
| 406 |
return new Promise((resolve, reject) => {
|
| 407 |
demandQueue.push({begin, end, resolve, reject});
|
|
@@ -419,9 +441,8 @@ export async function openPdfRangeTask(pdfjs, options, {signal, readBytes, limit
|
|
| 419 |
});
|
| 420 |
};
|
| 421 |
try {
|
| 422 |
-
const
|
| 423 |
{signal:active, readBytes, limit, rangeLimit, rangeCache, canPrefetchFirstPage}));
|
| 424 |
-
const first = /** @type {(InitialRange & RangeVersion) | null} */ (initialResult);
|
| 425 |
active.throwIfAborted();
|
| 426 |
if (!first) {
|
| 427 |
stop();
|
|
@@ -433,21 +454,24 @@ export async function openPdfRangeTask(pdfjs, options, {signal, readBytes, limit
|
|
| 433 |
}
|
| 434 |
// The initial prefix and tail remain available at their original size;
|
| 435 |
// only PDF.js's subsequent demand chunk granularity changes.
|
| 436 |
-
const
|
|
|
|
|
|
|
|
|
|
| 437 |
if ((candidate === PDF_ADAPTIVE_CHUNK_BYTES || candidate === PDF_LARGE_FLAT_CHUNK_BYTES) &&
|
| 438 |
options.rangeChunkSize === PDF_DEFAULT_CHUNK_BYTES) chunkSize = candidate;
|
| 439 |
metadataAdmission = boundedMetadata || chunkSize < options.rangeChunkSize;
|
| 440 |
// PDF.js owns parsing and range demand; the bootstrap is the first real range.
|
| 441 |
-
const transport = new engine.PDFDataRangeTransport(
|
| 442 |
transport.abort = () => stop(new DOMException("PDF transport closed", "AbortError"));
|
| 443 |
// PDF.js parses non-linearized files from their end (trailer, then the
|
| 444 |
// cross-reference table), demanding those chunks one round trip at a
|
| 445 |
// time. Fetch the last two aligned chunks once, alongside its startup.
|
| 446 |
let tail = first.tail || null;
|
| 447 |
const extendedTail = first.extendedTail || null;
|
| 448 |
-
if (!tail &&
|
| 449 |
-
const begin = Math.floor((
|
| 450 |
-
tail = preparePdfRangeHint(options, begin,
|
| 451 |
}
|
| 452 |
// A conservative read-ahead hint, not a PDF parser: only a direct Length
|
| 453 |
// before the first stream, in the bounded opening header, can qualify.
|
|
@@ -456,24 +480,24 @@ export async function openPdfRangeTask(pdfjs, options, {signal, readBytes, limit
|
|
| 456 |
const stream = /\bstream(?:\r\n|\r|\n)/.exec(header);
|
| 457 |
const length = stream && /\/Length\s+(\d+)(?:\s+\d+\s+R)?(?=[\s/>])/.exec(header.slice(0, stream.index));
|
| 458 |
const streamEnd = length && stream.index + stream[0].length + Number(length[1]);
|
| 459 |
-
const openingStreamContinues = length && !/\sR$/.test(length[0]) && Number.isSafeInteger(streamEnd) &&
|
| 460 |
-
|
| 461 |
// One chunk only; deep restorations and non-v3/native URLs do not opt in.
|
| 462 |
const openingRanges = first.openingRanges || [];
|
| 463 |
-
const prefix = !metadataAdmission &&
|
| 464 |
!openingRanges.some(range => range.begin <= chunkSize && range.end >= chunkSize * 2)
|
| 465 |
? {begin:chunkSize, end:chunkSize * 2,
|
| 466 |
-
promise:read(chunkSize, chunkSize * 2
|
| 467 |
: null;
|
| 468 |
/** @param {number} begin @param {number} end */
|
| 469 |
const fetchOrdinaryRange = (begin, end) => prefix && begin >= prefix.begin && end <= prefix.end
|
| 470 |
? prefix.promise.then(result => result
|
| 471 |
? {bytes:result.bytes.slice(begin - prefix.begin, end - prefix.begin)}
|
| 472 |
: demand(begin, end))
|
| 473 |
-
: tail && begin >= tail.begin && end <=
|
| 474 |
? tail.read(begin, end).then(result => result || demand(begin, end))
|
| 475 |
: extendedTail && tail && begin >= extendedTail.begin && begin < extendedTail.end &&
|
| 476 |
-
end > tail.begin && end <=
|
| 477 |
? Promise.all([extendedTail.read(begin,extendedTail.end),tail.read(tail.begin,end)]).then(([a,b]) => {
|
| 478 |
if (!a || !b) return demand(begin,end);
|
| 479 |
const bytes = new Uint8Array(end-begin); bytes.set(a.bytes); bytes.set(b.bytes,a.bytes.length);
|
|
@@ -530,7 +554,7 @@ export async function openPdfRangeTask(pdfjs, options, {signal, readBytes, limit
|
|
| 530 |
for (const hint of [tail, extendedTail, ...openingRanges]) hint?.onFailure(fail);
|
| 531 |
/** @param {{begin?: number, end?: number}} [range] */
|
| 532 |
const prioritizeRange = ({begin,end} = {}) => {
|
| 533 |
-
if (typeof begin !== "number" || typeof end !== "number" || !Number.isSafeInteger(begin) || !Number.isSafeInteger(end) || begin < 0 || end <= begin || end >
|
| 534 |
ratePriority?.(begin,end);
|
| 535 |
// A requested range may already be in the short large-flat batching
|
| 536 |
// window when the page worker promotes it. Flush now, without adding
|
|
@@ -549,8 +573,10 @@ export async function openPdfRangeTask(pdfjs, options, {signal, readBytes, limit
|
|
| 549 |
};
|
| 550 |
transport.requestDataRange = (begin, end) => {
|
| 551 |
fetchRange(begin,end).then(result => {
|
| 552 |
-
for (let index=priorityRanges.length-1;index>=0;index--)
|
| 553 |
-
|
|
|
|
|
|
|
| 554 |
if (!stopped) transport.onDataRange(begin,result.bytes);
|
| 555 |
}).catch(fail);
|
| 556 |
};
|
|
@@ -610,7 +636,8 @@ export function createPdfFetchPolicy({idleMs = 15000, attemptMs = 45000,
|
|
| 610 |
const delay=Math.max(throttleUntil,nextRateStart)-now();
|
| 611 |
if (delay > 0) {rateTimer=setTimeout(drainRate,delay);return;}
|
| 612 |
const priority=rateAdmissions.findIndex(item=>ratePriority(item.start,item.end,item.url));
|
| 613 |
-
const chosen=rateAdmissions.splice(priority < 0 ? 0 : priority,1)
|
|
|
|
| 614 |
if (chosen.signal.aborted) chosen.reject(chosen.signal.reason);
|
| 615 |
else {
|
| 616 |
nextRateStart=now()+rateLimitSpacingMs;
|
|
@@ -635,7 +662,7 @@ export function createPdfFetchPolicy({idleMs = 15000, attemptMs = 45000,
|
|
| 635 |
// future ones. Never retry before the server's announced time.
|
| 636 |
for (let index=rateAdmissions.length-1;index>=0;index--) {
|
| 637 |
const item=rateAdmissions[index];
|
| 638 |
-
if (item.url!==url) continue;
|
| 639 |
rateAdmissions.splice(index,1);
|
| 640 |
item.reject(Object.assign(new Error("PDF rate limited"),{status:429,code:"READER_PDF_RATE_LIMIT",retryable:false}));
|
| 641 |
}
|
|
@@ -728,7 +755,7 @@ export function createPdfFetchPolicy({idleMs = 15000, attemptMs = 45000,
|
|
| 728 |
if (!eligible) return;
|
| 729 |
for (let index=ratePriorityRanges.length-1;index>=0;index--) {
|
| 730 |
const range=ratePriorityRanges[index];
|
| 731 |
-
if ((!range.url || range.url===url) && start <= range.begin && end+1 >= range.end)
|
| 732 |
ratePriorityRanges.splice(index,1);
|
| 733 |
}
|
| 734 |
};
|
|
|
|
| 31 |
* @typedef {{total: number, etag: string | null}} RangeVersion
|
| 32 |
* @typedef {ReturnType<typeof createPdfRangeCache>} RangeCache
|
| 33 |
* @typedef {{signal: AbortSignal, readBytes: (response: Response, limit: number) => Promise<Uint8Array>, limit: number, rangeLimit?: number, rangeCache?: RangeCache | null, canPrefetchFirstPage?: () => boolean}} RangeHooks
|
| 34 |
+
* @typedef {({bytes: Uint8Array} & ((RangeVersion & {complete?: boolean}) | {total?: never, etag?: never, complete: true}))} RangeResult
|
| 35 |
* @typedef {{begin: number, end: number}} Bounds
|
| 36 |
* @typedef {{bytes: Uint8Array}} BytesResult
|
| 37 |
* @typedef {ReturnType<typeof preparePdfRangeHint>} RangeHint
|
| 38 |
* @typedef {{begin: number, end: number, hint: RangeHint | null, demanded: boolean}} AdjacentTail
|
| 39 |
+
* @typedef {{tail?: RangeHint | null, extendedTail?: RangeHint | null, xrefTail?: AdjacentTail | null, openingRanges?: RangeHint[], rangeChunkSize?: number, cancelInitial?: (reason?: unknown) => void}} InitialHints
|
| 40 |
+
* @typedef {RangeResult & InitialHints} InitialRange
|
| 41 |
* @typedef {import('../../../typings/reader-pdf-engine-strict').PdfDocument} PdfDocument
|
| 42 |
* @typedef {{promise: Promise<PdfDocument>, destroy: () => Promise<void> | void}} PdfTask
|
| 43 |
* @typedef {{abort: () => void, requestDataRange: (begin: number, end: number) => void, onDataRange: (begin: number, bytes: Uint8Array) => void}} PdfTransport
|
|
|
|
| 61 |
signal.throwIfAborted();
|
| 62 |
const key = new URL(options.url, globalThis.location?.href).href;
|
| 63 |
let cached = null;
|
| 64 |
+
try {
|
| 65 |
+
if (expected && expected.etag !== null)
|
| 66 |
+
cached = rangeCache?.get(key, begin, Math.min(end, expected.total), {total:expected.total, etag:expected.etag});
|
| 67 |
+
} catch (_) { /* Cache allocation failure must retain normal network reading. */ }
|
| 68 |
if (cached && expected) return {bytes:cached, total:expected.total, etag:expected.etag};
|
| 69 |
const response = await fetch(options.url, {
|
| 70 |
headers: {Range: `bytes=${begin}-${end-1}`}, signal, credentials:"same-origin"
|
|
|
|
| 78 |
return {bytes, complete:true};
|
| 79 |
}
|
| 80 |
const match = /^bytes (\d+)-(\d+)\/(\d+)$/.exec(response.headers.get("Content-Range") || "");
|
| 81 |
+
if (response.status !== 206 || !match) throw invalid();
|
| 82 |
+
const start = Number(match[1]), last = Number(match[2]), total = Number(match[3]);
|
| 83 |
+
if (![start, last, total].every(Number.isSafeInteger)) throw invalid();
|
| 84 |
if (total > (total === last + 1 - start ? limit : rangeLimit))
|
| 85 |
throw Object.assign(new Error("READER_RESOURCE_LIMIT"), {code:"READER_RESOURCE_LIMIT"});
|
| 86 |
if (start !== begin || last !== Math.min(end,total)-1 || total <= start) throw invalid();
|
|
|
|
| 95 |
const bytes = await readBytes(response, last-start+1);
|
| 96 |
if (bytes.byteLength !== last-start+1) throw invalid();
|
| 97 |
signal.throwIfAborted();
|
| 98 |
+
try { if (etag !== null) rangeCache?.put(key, start, bytes, {total, etag}); }
|
| 99 |
catch (_) { /* Retaining an optional copy must never fail the document. */ }
|
| 100 |
return {bytes, total, etag, complete:bytes.byteLength === total};
|
| 101 |
} catch (error) {
|
|
|
|
| 123 |
};
|
| 124 |
const flush = () => {
|
| 125 |
for (const waiter of waiters) {
|
| 126 |
+
if (failed) { waiters.delete(waiter); waiter.resolve(null); continue; }
|
| 127 |
+
if (!bytes || loaded < waiter.end - begin || (!complete && waiter.end === end)) continue;
|
| 128 |
waiters.delete(waiter);
|
|
|
|
| 129 |
published = true;
|
| 130 |
// Each PDF.js range reader accepts one complete, exact requested buffer.
|
| 131 |
// A proper subrange must not wait for unrelated trailing hint bytes/EOF.
|
| 132 |
+
waiter.resolve({bytes:bytes.slice(waiter.begin - begin, waiter.end - begin)});
|
| 133 |
}
|
| 134 |
};
|
| 135 |
+
/** @param {unknown} error */
|
| 136 |
+
const failHint = error => {
|
| 137 |
+
failure = error;
|
| 138 |
+
failed = true;
|
| 139 |
+
flush();
|
| 140 |
+
// If a proper subrange was already used, a malformed/truncated remainder
|
| 141 |
+
// must invalidate that document, not silently leave an accepted bad stream.
|
| 142 |
+
notifyFailure();
|
| 143 |
+
return null;
|
| 144 |
+
};
|
| 145 |
const promise = readPdfRange(options, begin, end, {
|
| 146 |
...hooks,
|
| 147 |
readBytes: async (response, length) => {
|
|
|
|
| 171 |
}
|
| 172 |
}, expected).then(result => {
|
| 173 |
// readPdfRange retains only an exact, version-checked complete response.
|
| 174 |
+
if (!result) return failHint(new Error("PDF_RANGE_INVALID"));
|
| 175 |
+
bytes = result.bytes;
|
| 176 |
loaded = bytes.byteLength;
|
| 177 |
complete = true;
|
| 178 |
flush();
|
| 179 |
return result;
|
| 180 |
+
}, failHint);
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 181 |
return {
|
| 182 |
begin, end, promise,
|
| 183 |
/** @param {number} from @param {number} last */
|
|
|
|
| 196 |
|
| 197 |
// The first demand overlaps engine preparation. After its complete validation,
|
| 198 |
// qualified page-one files may overlap bounded opening or tail range hints.
|
| 199 |
+
/** @param {RangeOptions} options @param {RangeHooks} hooks
|
| 200 |
+
* @returns {Promise<(InitialRange & {rangeChunkSize: number}) | null>}
|
| 201 |
+
*/
|
| 202 |
export async function preparePdfInitialRange(options, hooks) {
|
| 203 |
hooks = {...hooks, rangeCache:hooks.rangeCache === undefined ? sharedPdfRangeCache() : hooks.rangeCache};
|
| 204 |
const owner = new AbortController();
|
| 205 |
const signal = AbortSignal.any([hooks.signal, owner.signal]);
|
| 206 |
+
/** @type {{tail: RangeHint | null}} */
|
| 207 |
+
const hints = {tail:null};
|
| 208 |
+
/** @type {RangeHint | null} */
|
| 209 |
+
let extendedTail = null;
|
| 210 |
try {
|
| 211 |
/** @param {RangeVersion} metadata */
|
| 212 |
const onHeaders = metadata => {
|
|
|
|
| 214 |
// Start the existing two-chunk tail on validated headers, not after the
|
| 215 |
// first body finishes. This changes scheduling, not the fetched range.
|
| 216 |
const begin = Math.floor((metadata.total - 1) / options.rangeChunkSize) * options.rangeChunkSize - options.rangeChunkSize;
|
| 217 |
+
hints.tail = preparePdfRangeHint(options, begin, metadata.total, {...hooks, signal}, metadata);
|
| 218 |
};
|
| 219 |
+
/** @type {RangeResult | null} */
|
| 220 |
let first = null;
|
| 221 |
// A complete retained prefix may be reused only after a fresh no-store
|
| 222 |
// one-byte 206 proves its exact strong ETag and whole-document length.
|
|
|
|
| 228 |
const checked = await readPdfRange(options, 0, 1, {...hooks, signal, rangeCache:null}, null, null, true);
|
| 229 |
if (checked && checked.etag === previous.etag && checked.total === previous.total) {
|
| 230 |
let bytes = null;
|
| 231 |
+
try { bytes = hooks.rangeCache?.get(key, 0, Math.min(options.rangeChunkSize, previous.total), previous); } catch (_) {}
|
| 232 |
if (bytes) {
|
| 233 |
+
first = {bytes, total:previous.total, etag:previous.etag, complete:bytes.byteLength === previous.total};
|
| 234 |
+
if (!first.complete) onHeaders(first);
|
| 235 |
}
|
| 236 |
}
|
| 237 |
}
|
| 238 |
first ||= await readPdfRange(options, 0, options.rangeChunkSize, {...hooks, signal}, null, onHeaders);
|
| 239 |
+
if (!first) { owner.abort(); return null; }
|
| 240 |
+
const currentTail = hints.tail;
|
| 241 |
+
/** @type {RangeHint[]} */
|
|
|
|
|
|
|
|
|
|
| 242 |
const openingRanges = [];
|
| 243 |
+
/** @param {unknown} [reason] */
|
| 244 |
+
const cancelInitial = reason => owner.abort(reason);
|
| 245 |
+
// A complete 200 has no range metadata; do not run range scheduling on it.
|
| 246 |
+
if (first.total === undefined || first.etag === undefined)
|
| 247 |
+
return {...first, tail:currentTail, extendedTail, xrefTail:null, openingRanges, rangeChunkSize:options.rangeChunkSize, cancelInitial};
|
| 248 |
+
const metadata = {total:first.total, etag:first.etag};
|
| 249 |
const pageOne = !first.complete && hooks.canPrefetchFirstPage?.();
|
| 250 |
const connection = /** @type {(Navigator & {connection?: {saveData?: boolean, effectiveType?: string}}) | undefined} */ (globalThis.navigator)?.connection;
|
| 251 |
+
const allowLookahead = !connection?.saveData && connection?.effectiveType !== "slow-2g" && connection?.effectiveType !== "2g";
|
| 252 |
+
const extraLookahead = pageOne && allowLookahead;
|
| 253 |
const rangeChunkSize = first.complete ? options.rangeChunkSize :
|
| 254 |
+
choosePdfRangeChunkSize(first.bytes, metadata.total, options.rangeChunkSize);
|
| 255 |
// The ordinary tail ends after startxref but some flat files store a
|
| 256 |
// large xref immediately before it. One extra chunk avoids serial tiny
|
| 257 |
// reads; it remains ETag-bound and is suppressed for data-saving modes.
|
| 258 |
+
const largeFlatTail = allowLookahead && metadata.total > options.rangeChunkSize * 6 && rangeChunkSize === PDF_LARGE_FLAT_CHUNK_BYTES;
|
| 259 |
+
const tailStart = largeFlatTail && currentTail
|
| 260 |
+
? Math.max(options.rangeChunkSize, currentTail.begin - options.rangeChunkSize)
|
| 261 |
+
: extraLookahead ? firstPageTailHintStart(first.bytes, metadata.total, options.rangeChunkSize) : 0;
|
| 262 |
+
if (tailStart && currentTail) extendedTail = preparePdfRangeHint(options, tailStart, currentTail.begin, {...hooks, signal}, metadata);
|
|
|
|
| 263 |
// A wide, classic xref (or a distant xref stream) can start one chunk
|
| 264 |
// before the normal trailer hint. Read at most that adjacent chunk, and
|
| 265 |
// only after the whole trailer range has passed its byte/ETag checks.
|
|
|
|
| 270 |
if (xrefTail && currentTail) void currentTail.promise.then(result => {
|
| 271 |
if (!result || signal.aborted || xrefTail.demanded || !hooks.canPrefetchFirstPage?.()) return;
|
| 272 |
const begin = adjacentXrefChunkStart(result.bytes, xrefTail.end, rangeChunkSize);
|
| 273 |
+
if (begin) xrefTail.hint = preparePdfRangeHint(options, begin, xrefTail.end, {...hooks, signal}, metadata);
|
| 274 |
}).catch(() => {});
|
| 275 |
const end = pageOne
|
| 276 |
+
? firstPageSectionEnd(first.bytes, metadata.total, options.rangeChunkSize) ||
|
| 277 |
+
(extraLookahead ? firstImageSectionEnd(first.bytes, metadata.total, options.rangeChunkSize) : 0) : 0;
|
| 278 |
for (let begin = options.rangeChunkSize; begin < end; begin += options.rangeChunkSize * 2) {
|
| 279 |
const last = Math.min(end, begin + options.rangeChunkSize * 2);
|
| 280 |
+
openingRanges.push(preparePdfRangeHint(options, begin, last, {...hooks, signal}, metadata));
|
| 281 |
}
|
| 282 |
+
return {...first, tail:currentTail, extendedTail, xrefTail, openingRanges, rangeChunkSize, cancelInitial};
|
| 283 |
} catch (error) {
|
| 284 |
owner.abort(error);
|
| 285 |
throw error;
|
|
|
|
| 299 |
let task = null;
|
| 300 |
/** @type {InitialRange | null} */
|
| 301 |
let prepared = null;
|
| 302 |
+
/** @type {RangeVersion | null} */
|
| 303 |
+
let version = null;
|
| 304 |
let stopped = false;
|
| 305 |
+
/** @type {PromiseWithResolvers<never>} */
|
| 306 |
const failure = Promise.withResolvers();
|
| 307 |
failure.promise.catch(() => {});
|
| 308 |
/** @type {(Bounds & {resolve: () => void})[]} */
|
|
|
|
| 324 |
const index = priority >= 0 ? priority :
|
| 325 |
(!boundedMetadata || rangeReads < PDF_METADATA_RANGE_CONCURRENCY - 1 ? 0 : -1);
|
| 326 |
if (index < 0) return;
|
| 327 |
+
const [waiter] = rangeWaiters.splice(index,1);
|
| 328 |
+
if (waiter) waiter.resolve();
|
| 329 |
}
|
| 330 |
};
|
| 331 |
+
/** @param {number} begin @param {number} end @returns {Promise<(() => void) | null>} */
|
| 332 |
const admitMetadata = (begin,end) => {
|
| 333 |
if (!metadataAdmission) return Promise.resolve(null);
|
| 334 |
active.throwIfAborted();
|
|
|
|
| 376 |
signal.addEventListener("abort", cancelled, {once:true});
|
| 377 |
// Optional admission for demand reads only: the bootstrap, tail and opening
|
| 378 |
// hints are already bounded. A queued read is cancelled with its document.
|
| 379 |
+
/** @param {number} begin @param {number} end */
|
| 380 |
+
const read = async (begin, end) => {
|
| 381 |
+
const expected = version;
|
| 382 |
+
if (!expected) throw new Error("PDF_RANGE_INVALID");
|
| 383 |
const metadataRelease = await admitMetadata(begin,end);
|
| 384 |
let release = null;
|
| 385 |
try {
|
| 386 |
release = admitRange ? await admitRange(active) : null;
|
| 387 |
+
const result = await readPdfRange(options, begin, end, {signal:active, readBytes, limit, rangeLimit, rangeCache}, expected);
|
| 388 |
+
if (!result) throw new Error("PDF_RANGE_INVALID");
|
| 389 |
+
return result;
|
| 390 |
} finally {
|
| 391 |
release?.();
|
| 392 |
metadataRelease?.();
|
|
|
|
| 416 |
previous.rows.push(row);
|
| 417 |
} else groups.push({begin:row.begin, end:row.end, rows:[row], gapBytes:0});
|
| 418 |
}
|
| 419 |
+
for (const group of groups) read(group.begin, group.end).then(result => {
|
| 420 |
for (const row of group.rows)
|
| 421 |
+
row.resolve({bytes:result.bytes.slice(row.begin - group.begin, row.end - group.begin)});
|
| 422 |
}, error => { for (const row of group.rows) row.reject(error); });
|
| 423 |
};
|
| 424 |
+
/** @param {number} begin @param {number} end @returns {Promise<BytesResult>} */
|
| 425 |
const demand = (begin, end) => {
|
| 426 |
+
if (!metadataAdmission) return read(begin, end);
|
| 427 |
if (active.aborted) return Promise.reject(active.reason);
|
| 428 |
return new Promise((resolve, reject) => {
|
| 429 |
demandQueue.push({begin, end, resolve, reject});
|
|
|
|
| 441 |
});
|
| 442 |
};
|
| 443 |
try {
|
| 444 |
+
const first = prepared = await (initial || preparePdfInitialRange(options,
|
| 445 |
{signal:active, readBytes, limit, rangeLimit, rangeCache, canPrefetchFirstPage}));
|
|
|
|
| 446 |
active.throwIfAborted();
|
| 447 |
if (!first) {
|
| 448 |
stop();
|
|
|
|
| 454 |
}
|
| 455 |
// The initial prefix and tail remain available at their original size;
|
| 456 |
// only PDF.js's subsequent demand chunk granularity changes.
|
| 457 |
+
const {total, etag} = first;
|
| 458 |
+
if (total === undefined || etag === undefined) throw new Error("PDF_RANGE_INVALID");
|
| 459 |
+
version = {total, etag};
|
| 460 |
+
const candidate = first.rangeChunkSize ?? choosePdfRangeChunkSize(first.bytes, total, options.rangeChunkSize);
|
| 461 |
if ((candidate === PDF_ADAPTIVE_CHUNK_BYTES || candidate === PDF_LARGE_FLAT_CHUNK_BYTES) &&
|
| 462 |
options.rangeChunkSize === PDF_DEFAULT_CHUNK_BYTES) chunkSize = candidate;
|
| 463 |
metadataAdmission = boundedMetadata || chunkSize < options.rangeChunkSize;
|
| 464 |
// PDF.js owns parsing and range demand; the bootstrap is the first real range.
|
| 465 |
+
const transport = new engine.PDFDataRangeTransport(total, first.bytes, true);
|
| 466 |
transport.abort = () => stop(new DOMException("PDF transport closed", "AbortError"));
|
| 467 |
// PDF.js parses non-linearized files from their end (trailer, then the
|
| 468 |
// cross-reference table), demanding those chunks one round trip at a
|
| 469 |
// time. Fetch the last two aligned chunks once, alongside its startup.
|
| 470 |
let tail = first.tail || null;
|
| 471 |
const extendedTail = first.extendedTail || null;
|
| 472 |
+
if (!tail && total > chunkSize * 4) {
|
| 473 |
+
const begin = Math.floor((total - 1) / chunkSize) * chunkSize - chunkSize;
|
| 474 |
+
tail = preparePdfRangeHint(options, begin, total, {signal:active, readBytes, limit, rangeLimit, rangeCache}, version);
|
| 475 |
}
|
| 476 |
// A conservative read-ahead hint, not a PDF parser: only a direct Length
|
| 477 |
// before the first stream, in the bounded opening header, can qualify.
|
|
|
|
| 480 |
const stream = /\bstream(?:\r\n|\r|\n)/.exec(header);
|
| 481 |
const length = stream && /\/Length\s+(\d+)(?:\s+\d+\s+R)?(?=[\s/>])/.exec(header.slice(0, stream.index));
|
| 482 |
const streamEnd = length && stream.index + stream[0].length + Number(length[1]);
|
| 483 |
+
const openingStreamContinues = length && !/\sR$/.test(length[0]) && streamEnd !== null && Number.isSafeInteger(streamEnd) &&
|
| 484 |
+
streamEnd > first.bytes.byteLength && streamEnd <= total;
|
| 485 |
// One chunk only; deep restorations and non-v3/native URLs do not opt in.
|
| 486 |
const openingRanges = first.openingRanges || [];
|
| 487 |
+
const prefix = !metadataAdmission && total > chunkSize * 4 && openingStreamContinues && canPrefetchOpening() &&
|
| 488 |
!openingRanges.some(range => range.begin <= chunkSize && range.end >= chunkSize * 2)
|
| 489 |
? {begin:chunkSize, end:chunkSize * 2,
|
| 490 |
+
promise:read(chunkSize, chunkSize * 2).catch(() => null)}
|
| 491 |
: null;
|
| 492 |
/** @param {number} begin @param {number} end */
|
| 493 |
const fetchOrdinaryRange = (begin, end) => prefix && begin >= prefix.begin && end <= prefix.end
|
| 494 |
? prefix.promise.then(result => result
|
| 495 |
? {bytes:result.bytes.slice(begin - prefix.begin, end - prefix.begin)}
|
| 496 |
: demand(begin, end))
|
| 497 |
+
: tail && begin >= tail.begin && end <= total
|
| 498 |
? tail.read(begin, end).then(result => result || demand(begin, end))
|
| 499 |
: extendedTail && tail && begin >= extendedTail.begin && begin < extendedTail.end &&
|
| 500 |
+
end > tail.begin && end <= total
|
| 501 |
? Promise.all([extendedTail.read(begin,extendedTail.end),tail.read(tail.begin,end)]).then(([a,b]) => {
|
| 502 |
if (!a || !b) return demand(begin,end);
|
| 503 |
const bytes = new Uint8Array(end-begin); bytes.set(a.bytes); bytes.set(b.bytes,a.bytes.length);
|
|
|
|
| 554 |
for (const hint of [tail, extendedTail, ...openingRanges]) hint?.onFailure(fail);
|
| 555 |
/** @param {{begin?: number, end?: number}} [range] */
|
| 556 |
const prioritizeRange = ({begin,end} = {}) => {
|
| 557 |
+
if (typeof begin !== "number" || typeof end !== "number" || !Number.isSafeInteger(begin) || !Number.isSafeInteger(end) || begin < 0 || end <= begin || end > total) return;
|
| 558 |
ratePriority?.(begin,end);
|
| 559 |
// A requested range may already be in the short large-flat batching
|
| 560 |
// window when the page worker promotes it. Flush now, without adding
|
|
|
|
| 573 |
};
|
| 574 |
transport.requestDataRange = (begin, end) => {
|
| 575 |
fetchRange(begin,end).then(result => {
|
| 576 |
+
for (let index=priorityRanges.length-1;index>=0;index--) {
|
| 577 |
+
const row = priorityRanges[index];
|
| 578 |
+
if (row && begin <= row.begin && end >= row.end) priorityRanges.splice(index,1);
|
| 579 |
+
}
|
| 580 |
if (!stopped) transport.onDataRange(begin,result.bytes);
|
| 581 |
}).catch(fail);
|
| 582 |
};
|
|
|
|
| 636 |
const delay=Math.max(throttleUntil,nextRateStart)-now();
|
| 637 |
if (delay > 0) {rateTimer=setTimeout(drainRate,delay);return;}
|
| 638 |
const priority=rateAdmissions.findIndex(item=>ratePriority(item.start,item.end,item.url));
|
| 639 |
+
const [chosen]=rateAdmissions.splice(priority < 0 ? 0 : priority,1);
|
| 640 |
+
if (!chosen) return;
|
| 641 |
if (chosen.signal.aborted) chosen.reject(chosen.signal.reason);
|
| 642 |
else {
|
| 643 |
nextRateStart=now()+rateLimitSpacingMs;
|
|
|
|
| 662 |
// future ones. Never retry before the server's announced time.
|
| 663 |
for (let index=rateAdmissions.length-1;index>=0;index--) {
|
| 664 |
const item=rateAdmissions[index];
|
| 665 |
+
if (!item || item.url!==url) continue;
|
| 666 |
rateAdmissions.splice(index,1);
|
| 667 |
item.reject(Object.assign(new Error("PDF rate limited"),{status:429,code:"READER_PDF_RATE_LIMIT",retryable:false}));
|
| 668 |
}
|
|
|
|
| 755 |
if (!eligible) return;
|
| 756 |
for (let index=ratePriorityRanges.length-1;index>=0;index--) {
|
| 757 |
const range=ratePriorityRanges[index];
|
| 758 |
+
if (range && (!range.url || range.url===url) && start <= range.begin && end+1 >= range.end)
|
| 759 |
ratePriorityRanges.splice(index,1);
|
| 760 |
}
|
| 761 |
};
|
static/reader/pdf/reader-pdf-page-window.mjs
CHANGED
|
@@ -46,7 +46,7 @@ export function createReaderPdfPageWindow(readerContext) {
|
|
| 46 |
|
| 47 |
/** @param {import('../../../typings/reader-page-window-strict').PdfOutlineDocument | import('../../../typings/reader-page-window-strict').DjvuOutlineDocument} pdf */
|
| 48 |
async function loadPdfOutline(pdf, isDjvu = false) {
|
| 49 |
-
if (typeof pdf?.getOutline !== "function") return;
|
| 50 |
try {
|
| 51 |
const outline = await readerContext.awaitReader(pdf.getOutline());
|
| 52 |
/** @type {import('../../../typings/reader-page-window-strict').PdfOutlineEntry[]} */
|
|
@@ -92,6 +92,7 @@ export function createReaderPdfPageWindow(readerContext) {
|
|
| 92 |
} catch (error) {
|
| 93 |
if (!readerContext.readerAbortController.signal.aborted)
|
| 94 |
console.warn("PDF outline could not be loaded", error);
|
|
|
|
| 95 |
}
|
| 96 |
}
|
| 97 |
|
|
|
|
| 46 |
|
| 47 |
/** @param {import('../../../typings/reader-page-window-strict').PdfOutlineDocument | import('../../../typings/reader-page-window-strict').DjvuOutlineDocument} pdf */
|
| 48 |
async function loadPdfOutline(pdf, isDjvu = false) {
|
| 49 |
+
if (typeof pdf?.getOutline !== "function") return undefined;
|
| 50 |
try {
|
| 51 |
const outline = await readerContext.awaitReader(pdf.getOutline());
|
| 52 |
/** @type {import('../../../typings/reader-page-window-strict').PdfOutlineEntry[]} */
|
|
|
|
| 92 |
} catch (error) {
|
| 93 |
if (!readerContext.readerAbortController.signal.aborted)
|
| 94 |
console.warn("PDF outline could not be loaded", error);
|
| 95 |
+
return undefined;
|
| 96 |
}
|
| 97 |
}
|
| 98 |
|
static/reader/search/reader-search-controller.mjs
CHANGED
|
@@ -326,6 +326,7 @@ export function createReaderSearchController({
|
|
| 326 |
return activate(next, false);
|
| 327 |
}
|
| 328 |
if (search.results.length) return activate((search.index + step + search.results.length) % search.results.length, false);
|
|
|
|
| 329 |
}
|
| 330 |
function toggle() {
|
| 331 |
if (!active()) return;
|
|
@@ -371,10 +372,10 @@ export function createReaderSearchController({
|
|
| 371 |
status.textContent = "搜索已取消";
|
| 372 |
});
|
| 373 |
listen(/** @type {Element} */ (pagination.querySelector("#full-search-page-prev")), "click", () => {
|
| 374 |
-
|
| 375 |
});
|
| 376 |
listen(/** @type {Element} */ (pagination.querySelector("#full-search-page-next")), "click", () => {
|
| 377 |
-
|
| 378 |
});
|
| 379 |
listen(/** @type {Element} */ (pagination.querySelector("#full-search-page")), "change", event => {
|
| 380 |
const target = /** @type {HTMLInputElement} */ (event.target);
|
|
|
|
| 326 |
return activate(next, false);
|
| 327 |
}
|
| 328 |
if (search.results.length) return activate((search.index + step + search.results.length) % search.results.length, false);
|
| 329 |
+
return undefined;
|
| 330 |
}
|
| 331 |
function toggle() {
|
| 332 |
if (!active()) return;
|
|
|
|
| 372 |
status.textContent = "搜索已取消";
|
| 373 |
});
|
| 374 |
listen(/** @type {Element} */ (pagination.querySelector("#full-search-page-prev")), "click", () => {
|
| 375 |
+
return state.page ? loadPage(state.page.offset - state.page.pageSize) : undefined;
|
| 376 |
});
|
| 377 |
listen(/** @type {Element} */ (pagination.querySelector("#full-search-page-next")), "click", () => {
|
| 378 |
+
return state.page ? loadPage(state.page.offset + state.page.pageSize) : undefined;
|
| 379 |
});
|
| 380 |
listen(/** @type {Element} */ (pagination.querySelector("#full-search-page")), "change", event => {
|
| 381 |
const target = /** @type {HTMLInputElement} */ (event.target);
|
static/reader/ui/reader-progress.mjs
CHANGED
|
@@ -72,8 +72,8 @@ export function createReaderProgress(readerContext) {
|
|
| 72 |
readerContext.progressSaveChain = readerContext.progressSaveChain
|
| 73 |
.catch(() => {})
|
| 74 |
.then(() => {
|
| 75 |
-
|
| 76 |
-
|
| 77 |
})
|
| 78 |
.catch((error) => {
|
| 79 |
if (readerContext.lastSavedProgress === signature) readerContext.lastSavedProgress = "";
|
|
|
|
| 72 |
readerContext.progressSaveChain = readerContext.progressSaveChain
|
| 73 |
.catch(() => {})
|
| 74 |
.then(() => {
|
| 75 |
+
return readerContext.historySuppressed ? undefined
|
| 76 |
+
: VoiceOfMLReaderStore.put({ ...progress, lastReadAt: capturedAt });
|
| 77 |
})
|
| 78 |
.catch((error) => {
|
| 79 |
if (readerContext.lastSavedProgress === signature) readerContext.lastSavedProgress = "";
|
static/reader/ui/reader-speech.mjs
CHANGED
|
@@ -282,24 +282,24 @@ export function createReaderSpeech(readerContext, loadPlayer) {
|
|
| 282 |
// of view stops following until "回到播放位置" or scrolling back to it.
|
| 283 |
follow(start) {
|
| 284 |
const part = self.partAt(start);
|
| 285 |
-
if (!part) return;
|
| 286 |
self.current = start;
|
| 287 |
// Parked in the background (Reader closed while reading): no layout to follow.
|
| 288 |
-
if (!self.following || !readerContext.viewport.getClientRects().length) return;
|
| 289 |
const range = self.range(start, start + 1);
|
| 290 |
if (!range) {
|
| 291 |
// An unrendered page/section: navigate there and wait for its text.
|
| 292 |
-
if (sourceInfo.root(part.unit) || !sourceInfo.locate) return;
|
| 293 |
self.autoUntil = performance.now() + 8000;
|
| 294 |
return Promise.resolve(sourceInfo.locate(part.unit)).then(() => until(() => sourceInfo.root(part.unit), 8000))
|
| 295 |
.finally(() => { self.autoUntil = performance.now() + 600; });
|
| 296 |
}
|
| 297 |
const position = self.visible(start, range);
|
| 298 |
-
if (position && position.inside)
|
| 299 |
-
if (position) {
|
| 300 |
self.autoUntil = performance.now() + 1200;
|
| 301 |
scrollToRange(range, "smooth");
|
| 302 |
}
|
|
|
|
| 303 |
},
|
| 304 |
following: true, current: null, autoUntil: 0,
|
| 305 |
// null when the clip has no rendered range; otherwise whether it is in view.
|
|
@@ -680,9 +680,7 @@ export function createReaderSpeech(readerContext, loadPlayer) {
|
|
| 680 |
if (speech()) return attach();
|
| 681 |
loadingPlayer = true;
|
| 682 |
// Reading is already ready; an optional player must not delay or fail it.
|
| 683 |
-
void Promise.resolve().then(() => {
|
| 684 |
-
if (!disposed) return loadPlayer();
|
| 685 |
-
}).then(() => {
|
| 686 |
if (!disposed) attach();
|
| 687 |
}).catch(() => {}).finally(() => { loadingPlayer = false; });
|
| 688 |
}
|
|
|
|
| 282 |
// of view stops following until "回到播放位置" or scrolling back to it.
|
| 283 |
follow(start) {
|
| 284 |
const part = self.partAt(start);
|
| 285 |
+
if (!part) return undefined;
|
| 286 |
self.current = start;
|
| 287 |
// Parked in the background (Reader closed while reading): no layout to follow.
|
| 288 |
+
if (!self.following || !readerContext.viewport.getClientRects().length) return undefined;
|
| 289 |
const range = self.range(start, start + 1);
|
| 290 |
if (!range) {
|
| 291 |
// An unrendered page/section: navigate there and wait for its text.
|
| 292 |
+
if (sourceInfo.root(part.unit) || !sourceInfo.locate) return undefined;
|
| 293 |
self.autoUntil = performance.now() + 8000;
|
| 294 |
return Promise.resolve(sourceInfo.locate(part.unit)).then(() => until(() => sourceInfo.root(part.unit), 8000))
|
| 295 |
.finally(() => { self.autoUntil = performance.now() + 600; });
|
| 296 |
}
|
| 297 |
const position = self.visible(start, range);
|
| 298 |
+
if (position && !position.inside) {
|
|
|
|
| 299 |
self.autoUntil = performance.now() + 1200;
|
| 300 |
scrollToRange(range, "smooth");
|
| 301 |
}
|
| 302 |
+
return undefined;
|
| 303 |
},
|
| 304 |
following: true, current: null, autoUntil: 0,
|
| 305 |
// null when the clip has no rendered range; otherwise whether it is in view.
|
|
|
|
| 680 |
if (speech()) return attach();
|
| 681 |
loadingPlayer = true;
|
| 682 |
// Reading is already ready; an optional player must not delay or fail it.
|
| 683 |
+
void Promise.resolve().then(() => disposed ? undefined : loadPlayer()).then(() => {
|
|
|
|
|
|
|
| 684 |
if (!disposed) attach();
|
| 685 |
}).catch(() => {}).finally(() => { loadingPlayer = false; });
|
| 686 |
}
|
static/search/requests/infrastructure/response-cache.js
CHANGED
|
@@ -9,14 +9,15 @@
|
|
| 9 |
this.limit = limit; this.ttl = ttl; this.budget = budget;
|
| 10 |
this.bytes = 0; this.entriesInfo = /** @type {Map<string, {bytes: number, time: number}>} */ (new Map());
|
| 11 |
}
|
| 12 |
-
/** @param {string} key */
|
| 13 |
delete(key) {
|
| 14 |
this.bytes -= this.entriesInfo.get(key)?.bytes || 0;
|
| 15 |
this.entriesInfo.delete(key);
|
| 16 |
return super.delete(key);
|
| 17 |
}
|
|
|
|
| 18 |
clear() { super.clear(); this.entriesInfo.clear(); this.bytes = 0; }
|
| 19 |
-
/** @param {string} key */
|
| 20 |
get(key) {
|
| 21 |
const info = this.entriesInfo.get(key);
|
| 22 |
if (!info) return undefined;
|
|
@@ -25,9 +26,9 @@
|
|
| 25 |
super.delete(key); super.set(key, value);
|
| 26 |
return value;
|
| 27 |
}
|
| 28 |
-
/** @param {string} key */
|
| 29 |
has(key) { return this.get(key) !== undefined; }
|
| 30 |
-
/** @param {string} key @param {T} value */
|
| 31 |
set(key, value) {
|
| 32 |
this.delete(key);
|
| 33 |
const now = Date.now();
|
|
|
|
| 9 |
this.limit = limit; this.ttl = ttl; this.budget = budget;
|
| 10 |
this.bytes = 0; this.entriesInfo = /** @type {Map<string, {bytes: number, time: number}>} */ (new Map());
|
| 11 |
}
|
| 12 |
+
/** @override @param {string} key */
|
| 13 |
delete(key) {
|
| 14 |
this.bytes -= this.entriesInfo.get(key)?.bytes || 0;
|
| 15 |
this.entriesInfo.delete(key);
|
| 16 |
return super.delete(key);
|
| 17 |
}
|
| 18 |
+
/** @override */
|
| 19 |
clear() { super.clear(); this.entriesInfo.clear(); this.bytes = 0; }
|
| 20 |
+
/** @override @param {string} key */
|
| 21 |
get(key) {
|
| 22 |
const info = this.entriesInfo.get(key);
|
| 23 |
if (!info) return undefined;
|
|
|
|
| 26 |
super.delete(key); super.set(key, value);
|
| 27 |
return value;
|
| 28 |
}
|
| 29 |
+
/** @override @param {string} key */
|
| 30 |
has(key) { return this.get(key) !== undefined; }
|
| 31 |
+
/** @override @param {string} key @param {T} value */
|
| 32 |
set(key, value) {
|
| 33 |
this.delete(key);
|
| 34 |
const now = Date.now();
|
tests/gates/test_static_checks.py
CHANGED
|
@@ -46,7 +46,7 @@ class StaticGateTests(unittest.TestCase):
|
|
| 46 |
shutil.copyfile(ROOT / "typings" / name, directory / name)
|
| 47 |
# Runtime type fixtures import Reader declarations, which in turn import
|
| 48 |
# other declarations. Preserve that dependency graph in the isolated tree.
|
| 49 |
-
for declaration in (ROOT / "typings").glob("
|
| 50 |
shutil.copyfile(declaration, self.root / "typings" / declaration.name)
|
| 51 |
for filename in ("eslint.config.mjs", "ruff.toml"):
|
| 52 |
shutil.copyfile(ROOT / filename, self.root / filename)
|
|
@@ -202,6 +202,38 @@ class StaticGateTests(unittest.TestCase):
|
|
| 202 |
source.write_text('/** @type {number} */ let value = "wrong";\nconsole.log(value);\n')
|
| 203 |
self.assert_check(self.run_check(*check), False, "TS2322")
|
| 204 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 205 |
def test_strict_javascript_gate_rejects_implicit_any(self):
|
| 206 |
config = load_type_config("jsconfig.strict.json")
|
| 207 |
self.assertTrue(config["compilerOptions"]["strict"])
|
|
@@ -3734,7 +3766,8 @@ lifecycle.trackReaderResource(() => {}); lifecycle.isReaderGenerationCurrent("se
|
|
| 3734 |
"static/reader/formats/reader-image-loader.mjs", "static/reader/formats/reader-media-format.mjs", "static/reader/formats/reader-text-format.mjs", "static/reader/search/reader-pdf-book-search.mjs", "static/reader/search/reader-pdf-book-url.mjs", "static/reader/search/reader-pdf-search-stream.mjs", "static/reader/search/reader-pdf-search-decode.mjs", "static/reader/search/reader-pdf-partition-shape.mjs", "static/reader/search/reader-pdf-partition-config.mjs", "static/reader/search/reader-pdf-partition-policy.mjs", "static/reader/search/reader-pdf-partition-page.mjs", "static/reader/search/reader-pdf-partition-requests.mjs", "static/reader/search/reader-pdf-book-compact.mjs", "static/reader/search/reader-pdf-book-validate.mjs", "static/reader/formats/reader-chapter-repository.js",
|
| 3735 |
"static/reader/ui/reader-document-styles.mjs", "static/reader/pdf/reader-engine-preload.js",
|
| 3736 |
"static/reader/pdf/pdf-first-page-worker-adapter.mjs", "static/reader/pdf/reader-djvu-worker.mjs", "static/reader/pdf/reader-djvu-scheduler.mjs", "static/reader/pdf/reader-djvu-adapter.mjs", "static/reader/pdf/reader-djvu-identity.mjs", "static/reader/pdf/reader-djvu-range.mjs", "static/reader/pdf/reader-djvu-loader.mjs", "static/reader/search/reader-chapter-search-proxy-url.mjs", "static/reader/search/reader-chapter-search-index.mjs", "static/reader/pdf/reader-pdf-range-cache.mjs",
|
| 3737 |
-
"static/reader/pdf/reader-pdf-range-hints.mjs", "static/reader/pdf/reader-pdf-
|
|
|
|
| 3738 |
"static/reader/formats/reader-section-virtualizer.js", "static/reader/ui/reader-scroll-anchor.js"}
|
| 3739 |
fixture = {"typings/reader-globals.d.ts", "tests/reader/core/test_reader_runtime_types.ts"}
|
| 3740 |
self.assertEqual(set(original["files"]), required | fixture)
|
|
|
|
| 46 |
shutil.copyfile(ROOT / "typings" / name, directory / name)
|
| 47 |
# Runtime type fixtures import Reader declarations, which in turn import
|
| 48 |
# other declarations. Preserve that dependency graph in the isolated tree.
|
| 49 |
+
for declaration in (ROOT / "typings").glob("*.d.ts"):
|
| 50 |
shutil.copyfile(declaration, self.root / "typings" / declaration.name)
|
| 51 |
for filename in ("eslint.config.mjs", "ruff.toml"):
|
| 52 |
shutil.copyfile(ROOT / filename, self.root / filename)
|
|
|
|
| 202 |
source.write_text('/** @type {number} */ let value = "wrong";\nconsole.log(value);\n')
|
| 203 |
self.assert_check(self.run_check(*check), False, "TS2322")
|
| 204 |
|
| 205 |
+
def test_strict_javascript_gate_checks_returns_overrides_switches_and_optionals(self):
|
| 206 |
+
options = load_type_config("jsconfig.strict.json")["compilerOptions"]
|
| 207 |
+
probes = (
|
| 208 |
+
("noImplicitReturns", "TS7030", """
|
| 209 |
+
/** @param {boolean} active */
|
| 210 |
+
function readCount(active) { if (active) return 1; }
|
| 211 |
+
"""),
|
| 212 |
+
("noImplicitOverride", "TS4119", """
|
| 213 |
+
class BaseProbe { clear() {} }
|
| 214 |
+
class CacheProbe extends BaseProbe { clear() {} }
|
| 215 |
+
"""),
|
| 216 |
+
("noFallthroughCasesInSwitch", "TS7029", """
|
| 217 |
+
/** @param {number} value */
|
| 218 |
+
function update(value) { switch (value) { case 0: value++; case 1: break; } }
|
| 219 |
+
"""),
|
| 220 |
+
("exactOptionalPropertyTypes", "TS2375", """
|
| 221 |
+
/** @type {{signal?: AbortSignal}} */
|
| 222 |
+
const options = {signal: undefined};
|
| 223 |
+
"""),
|
| 224 |
+
)
|
| 225 |
+
source = self.root / "static/strict-options-probe.js"
|
| 226 |
+
config = self.root / "jsconfig.json"
|
| 227 |
+
check = ["node", ROOT / "node_modules/typescript/bin/tsc", "--project", config]
|
| 228 |
+
for flag, code, program in probes:
|
| 229 |
+
with self.subTest(flag=flag):
|
| 230 |
+
self.assertIs(options.get(flag), True)
|
| 231 |
+
source.write_text(program)
|
| 232 |
+
config.write_text(json.dumps({"compilerOptions": options, "files": [str(source)]}))
|
| 233 |
+
self.assert_check(self.run_check(*check), False, code)
|
| 234 |
+
config.write_text(json.dumps({"compilerOptions": {**options, flag: False}, "files": [str(source)]}))
|
| 235 |
+
self.assert_check(self.run_check(*check), True, "")
|
| 236 |
+
|
| 237 |
def test_strict_javascript_gate_rejects_implicit_any(self):
|
| 238 |
config = load_type_config("jsconfig.strict.json")
|
| 239 |
self.assertTrue(config["compilerOptions"]["strict"])
|
|
|
|
| 3766 |
"static/reader/formats/reader-image-loader.mjs", "static/reader/formats/reader-media-format.mjs", "static/reader/formats/reader-text-format.mjs", "static/reader/search/reader-pdf-book-search.mjs", "static/reader/search/reader-pdf-book-url.mjs", "static/reader/search/reader-pdf-search-stream.mjs", "static/reader/search/reader-pdf-search-decode.mjs", "static/reader/search/reader-pdf-partition-shape.mjs", "static/reader/search/reader-pdf-partition-config.mjs", "static/reader/search/reader-pdf-partition-policy.mjs", "static/reader/search/reader-pdf-partition-page.mjs", "static/reader/search/reader-pdf-partition-requests.mjs", "static/reader/search/reader-pdf-book-compact.mjs", "static/reader/search/reader-pdf-book-validate.mjs", "static/reader/formats/reader-chapter-repository.js",
|
| 3767 |
"static/reader/ui/reader-document-styles.mjs", "static/reader/pdf/reader-engine-preload.js",
|
| 3768 |
"static/reader/pdf/pdf-first-page-worker-adapter.mjs", "static/reader/pdf/reader-djvu-worker.mjs", "static/reader/pdf/reader-djvu-scheduler.mjs", "static/reader/pdf/reader-djvu-adapter.mjs", "static/reader/pdf/reader-djvu-identity.mjs", "static/reader/pdf/reader-djvu-range.mjs", "static/reader/pdf/reader-djvu-loader.mjs", "static/reader/search/reader-chapter-search-proxy-url.mjs", "static/reader/search/reader-chapter-search-index.mjs", "static/reader/pdf/reader-pdf-range-cache.mjs",
|
| 3769 |
+
"static/reader/pdf/reader-pdf-range-hints.mjs", "static/reader/pdf/reader-pdf-network.mjs",
|
| 3770 |
+
"static/reader/pdf/reader-pdf-text-store.mjs",
|
| 3771 |
"static/reader/formats/reader-section-virtualizer.js", "static/reader/ui/reader-scroll-anchor.js"}
|
| 3772 |
fixture = {"typings/reader-globals.d.ts", "tests/reader/core/test_reader_runtime_types.ts"}
|
| 3773 |
self.assertEqual(set(original["files"]), required | fixture)
|
tests/reader/core/test_reader_store_types.ts
CHANGED
|
@@ -4,7 +4,7 @@ declare const store: ReaderStoreStrictApi;
|
|
| 4 |
store.put({ url: "book", title: 42, custom: true });
|
| 5 |
store.putBookmark({ id: "id", url: "book", createdAt: "12" });
|
| 6 |
store.list(5).then(entries => { const title: string = entries[0].title; return title; });
|
| 7 |
-
store.get("book").then(entry => {
|
| 8 |
store.listBookmarks("book").then(entries => { const label: string = entries[0].label; return label; });
|
| 9 |
store.subscribe(message => {
|
| 10 |
if (message.remote) {
|
|
|
|
| 4 |
store.put({ url: "book", title: 42, custom: true });
|
| 5 |
store.putBookmark({ id: "id", url: "book", createdAt: "12" });
|
| 6 |
store.list(5).then(entries => { const title: string = entries[0].title; return title; });
|
| 7 |
+
store.get("book").then(entry => { const time: number | undefined = entry?.lastReadAt; return time; });
|
| 8 |
store.listBookmarks("book").then(entries => { const label: string = entries[0].label; return label; });
|
| 9 |
store.subscribe(message => {
|
| 10 |
if (message.remote) {
|
tests/reader/pdf-network/test_reader_pdf_network_contract.mjs
CHANGED
|
@@ -22,6 +22,35 @@ const pdfjs = {PDFDataRangeTransport:Transport,getDocument:opts=>({
|
|
| 22 |
promise:Promise.resolve(opts),destroy:async()=>{}})};
|
| 23 |
|
| 24 |
try {
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 25 |
// A final startxref may point to the single aligned chunk before the
|
| 26 |
// standard tail. Trust the trailer only as a bounded scheduling hint.
|
| 27 |
for (const scenario of ['hint','demand-first','close','source-changed','malformed','deep','weak-net','save-data','older-offset','covered','linearized','suppressed-after-start']) {
|
|
|
|
| 22 |
promise:Promise.resolve(opts),destroy:async()=>{}})};
|
| 23 |
|
| 24 |
try {
|
| 25 |
+
// A full GET fallback has bytes but no range version. Do not manufacture
|
| 26 |
+
// undefined metadata properties or attempt any range lookahead.
|
| 27 |
+
{
|
| 28 |
+
const bytes = Uint8Array.of(1,2,3,4);
|
| 29 |
+
let requests = 0;
|
| 30 |
+
globalThis.fetch = async () => { requests++; return new Response(bytes); };
|
| 31 |
+
const hooks = {signal:new AbortController().signal,readBytes,limit:64,rangeCache:null,
|
| 32 |
+
canPrefetchFirstPage:() => assert.fail('complete bodies do not need range hints')};
|
| 33 |
+
const first = await preparePdfInitialRange(options,hooks);
|
| 34 |
+
assert.equal(first.complete,true);
|
| 35 |
+
assert.equal(Object.hasOwn(first,'total'),false);
|
| 36 |
+
assert.equal(Object.hasOwn(first,'etag'),false);
|
| 37 |
+
const task = await openPdfRangeTask(pdfjs,options,{...hooks,initial:Promise.resolve(first)});
|
| 38 |
+
const result = await task.promise;
|
| 39 |
+
assert.deepEqual(result.data,bytes);
|
| 40 |
+
assert.equal(result.range,undefined);
|
| 41 |
+
assert.equal(requests,1);
|
| 42 |
+
await task.destroy();
|
| 43 |
+
}
|
| 44 |
+
|
| 45 |
+
for (const contentRange of ['bytes 0-3/*','bytes 0-3/9007199254740992']) {
|
| 46 |
+
let cancelled = false;
|
| 47 |
+
globalThis.fetch = async () => new Response(new ReadableStream({cancel() { cancelled = true; }}),{
|
| 48 |
+
status:206,headers:{'Content-Range':contentRange,ETag:'"A"'}});
|
| 49 |
+
await assert.rejects(preparePdfInitialRange(options,{signal:new AbortController().signal,
|
| 50 |
+
limit:64,rangeCache:null,readBytes:() => assert.fail('invalid range must not read the body')}),/PDF_RANGE_INVALID/);
|
| 51 |
+
assert.equal(cancelled,true,contentRange);
|
| 52 |
+
}
|
| 53 |
+
|
| 54 |
// A final startxref may point to the single aligned chunk before the
|
| 55 |
// standard tail. Trust the trailer only as a bounded scheduling hint.
|
| 56 |
for (const scenario of ['hint','demand-first','close','source-changed','malformed','deep','weak-net','save-data','older-offset','covered','linearized','suppressed-after-start']) {
|
typings/reader-globals.d.ts
CHANGED
|
@@ -294,9 +294,11 @@ interface ReaderRequestManagerOptions {
|
|
| 294 |
clearTimer?: typeof clearTimeout;
|
| 295 |
initialIdleMs?: number;
|
| 296 |
}
|
|
|
|
|
|
|
| 297 |
interface ReaderRequestManager {
|
| 298 |
-
request(url: RequestInfo | URL, timeoutMs: number, requestInit?:
|
| 299 |
-
requestBuffered(url: RequestInfo | URL, timeoutMs: number, limit: number, requestInit?:
|
| 300 |
dispose(): void;
|
| 301 |
readonly pendingCount: number;
|
| 302 |
readonly activeCount: number;
|
|
|
|
| 294 |
clearTimer?: typeof clearTimeout;
|
| 295 |
initialIdleMs?: number;
|
| 296 |
}
|
| 297 |
+
// The manager normalizes the signal before sending a native fetch request.
|
| 298 |
+
type ReaderRequestInit = Omit<RequestInit, 'signal'> & { signal?: AbortSignal | null | undefined };
|
| 299 |
interface ReaderRequestManager {
|
| 300 |
+
request(url: RequestInfo | URL, timeoutMs: number, requestInit?: ReaderRequestInit): Promise<Response>;
|
| 301 |
+
requestBuffered(url: RequestInfo | URL, timeoutMs: number, limit: number, requestInit?: ReaderRequestInit): Promise<Response>;
|
| 302 |
dispose(): void;
|
| 303 |
readonly pendingCount: number;
|
| 304 |
readonly activeCount: number;
|
typings/reader-pdf-engine-strict.d.ts
CHANGED
|
@@ -23,10 +23,7 @@ export interface PdfOptions {
|
|
| 23 |
disableAutoFetch: boolean; disableStream: boolean; wasmUrl: string; cMapUrl: string;
|
| 24 |
cMapPacked: boolean; standardFontDataUrl: string; withCredentials: boolean;
|
| 25 |
}
|
| 26 |
-
export
|
| 27 |
-
complete?: boolean; bytes: Uint8Array; total?: number; rangeChunkSize: number;
|
| 28 |
-
etag?: string | null; cancelInitial?: (reason?: unknown) => void;
|
| 29 |
-
}
|
| 30 |
export type Initial = Promise<InitialRange | null> | null;
|
| 31 |
export interface Restoration { page?: number | string; pageOffset?: number | string; id?: string }
|
| 32 |
export interface RangeHooks {
|
|
|
|
| 23 |
disableAutoFetch: boolean; disableStream: boolean; wasmUrl: string; cMapUrl: string;
|
| 24 |
cMapPacked: boolean; standardFontDataUrl: string; withCredentials: boolean;
|
| 25 |
}
|
| 26 |
+
export type InitialRange = NonNullable<Awaited<ReturnType<typeof import('../static/reader/pdf/reader-pdf-network.mjs').preparePdfInitialRange>>>;
|
|
|
|
|
|
|
|
|
|
| 27 |
export type Initial = Promise<InitialRange | null> | null;
|
| 28 |
export interface Restoration { page?: number | string; pageOffset?: number | string; id?: string }
|
| 29 |
export interface RangeHooks {
|
typings/search-app.d.ts
CHANGED
|
@@ -23,7 +23,7 @@ interface VoiceOfMLSearchAppBodyOptions {
|
|
| 23 |
}
|
| 24 |
|
| 25 |
interface VoiceOfMLSearchAppWindow extends Omit<VoiceOfMLResultWindow, 'generation' | 'pending'> {
|
| 26 |
-
generation?: string;
|
| 27 |
pending: Map<number, VoiceOfMLWindowRequest | Promise<SearchRecentPage | null>>;
|
| 28 |
missingPages?: Set<number>;
|
| 29 |
pages: Set<number>;
|
|
|
|
| 23 |
}
|
| 24 |
|
| 25 |
interface VoiceOfMLSearchAppWindow extends Omit<VoiceOfMLResultWindow, 'generation' | 'pending'> {
|
| 26 |
+
generation?: string | undefined;
|
| 27 |
pending: Map<number, VoiceOfMLWindowRequest | Promise<SearchRecentPage | null>>;
|
| 28 |
missingPages?: Set<number>;
|
| 29 |
pages: Set<number>;
|
typings/search-bootstrap.d.ts
CHANGED
|
@@ -6,7 +6,7 @@ interface SearchBootstrapView {
|
|
| 6 |
mode: string; repo: string | null; repoFull: string | null;
|
| 7 |
}
|
| 8 |
interface SearchInitialPayload {
|
| 9 |
-
results: unknown[]; total?: number; generation?: unknown; mode?: string; repo?: string;
|
| 10 |
}
|
| 11 |
interface SearchInitialPage {
|
| 12 |
results: unknown[]; total: number; page: number; page_size: number; generation: unknown;
|
|
|
|
| 6 |
mode: string; repo: string | null; repoFull: string | null;
|
| 7 |
}
|
| 8 |
interface SearchInitialPayload {
|
| 9 |
+
results: unknown[]; total?: number | undefined; generation?: unknown; mode?: string; repo?: string;
|
| 10 |
}
|
| 11 |
interface SearchInitialPage {
|
| 12 |
results: unknown[]; total: number; page: number; page_size: number; generation: unknown;
|
typings/search-reader-host.d.ts
CHANGED
|
@@ -4,7 +4,7 @@ interface ReaderReturnPosition {
|
|
| 4 |
}
|
| 5 |
interface ReaderReturnDependencies {
|
| 6 |
readView(): { hasContainer: boolean; containerHeight: number; resultCount: number; total: number;
|
| 7 |
-
loading: boolean; loadedPage: number; positionRestore: { preview
|
| 8 |
hasResult(index: number): boolean;
|
| 9 |
getViewKey(): string; getTop(): number; setTop(top: number): void;
|
| 10 |
ensureHeights(): void; findIndex(top: number): number; getOffset(index: number): number;
|
|
|
|
| 4 |
}
|
| 5 |
interface ReaderReturnDependencies {
|
| 6 |
readView(): { hasContainer: boolean; containerHeight: number; resultCount: number; total: number;
|
| 7 |
+
loading: boolean; loadedPage: number; positionRestore: { preview: boolean | undefined; key: string } | null; routeRevision: number };
|
| 8 |
hasResult(index: number): boolean;
|
| 9 |
getViewKey(): string; getTop(): number; setTop(top: number): void;
|
| 10 |
ensureHeights(): void; findIndex(top: number): number; getOffset(index: number): number;
|
typings/search-snapshots.d.ts
CHANGED
|
@@ -3,8 +3,8 @@ type SearchSnapshotHeightEntry = readonly [string, Readonly<SearchSnapshotHeight
|
|
| 3 |
interface SearchSnapshotScroll { index: number; offset: number; viewKey?: string }
|
| 4 |
interface SearchSnapshotView {
|
| 5 |
key: string; revision: number; results: unknown[]; total: number; loadedPage: number;
|
| 6 |
-
pageCache: Record<string, unknown>; resultBackend?: string | null;
|
| 7 |
-
window?: {generation?: string | undefined; pages: Iterable<number>; count: number; invalid?: boolean} | null;
|
| 8 |
}
|
| 9 |
interface SearchResultSnapshot {
|
| 10 |
version: number; key: string; results: unknown[]; total: number; page: number; loadedPage: number;
|
|
|
|
| 3 |
interface SearchSnapshotScroll { index: number; offset: number; viewKey?: string }
|
| 4 |
interface SearchSnapshotView {
|
| 5 |
key: string; revision: number; results: unknown[]; total: number; loadedPage: number;
|
| 6 |
+
pageCache: Record<string, unknown>; resultBackend?: string | null | undefined;
|
| 7 |
+
window?: {generation?: string | undefined; pages: Iterable<number>; count: number; invalid?: boolean | undefined} | null;
|
| 8 |
}
|
| 9 |
interface SearchResultSnapshot {
|
| 10 |
version: number; key: string; results: unknown[]; total: number; page: number; loadedPage: number;
|
typings/tts-client-strict.d.ts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
| 1 |
export interface Batch { start: number; end: number; text: string; first: boolean; segment_ends: number[]; context_before: string; context_after: string }
|
| 2 |
export interface Part { index: number; start: number; end: number; audio_url: string; bytes?: unknown; pitch_semitones?: unknown; pause_kind?: unknown; pause_after_seconds?: unknown }
|
| 3 |
export interface Adapter { readonly text: string; readonly done: boolean; root?: Node | null; ensure(length: number): Promise<void>; progress?(): string; locateTop?(): Promise<number>; offsetAtTop?(): number; range?(start: number, end: number): Range | null; follow?(start: number, end: number): void | Promise<void>; reveal?(position: number): void | Promise<void>; inView?(position: number): boolean; saveView?(): { top: number; frame: number | null }; restoreView?(view: { top: number; frame: number | null }): void }
|
| 4 |
-
export interface Snapshot { id: string; title: string; text: string; adapter?: Adapter; growing?: Promise<void> | null }
|
| 5 |
export interface Preview extends Snapshot { snapshot?: Snapshot; host?: HTMLElement | null; body: HTMLElement | null }
|
| 6 |
export type PreviewInput = { id: string; title: string; host?: HTMLElement | null; body?: HTMLElement | null; tools?: Element | null; buttonClass?: string } & ({ adapter: Adapter; text?: string } | { adapter?: undefined; text: string });
|
| 7 |
export interface History extends Batch { parts: Part[] }
|
|
|
|
| 1 |
export interface Batch { start: number; end: number; text: string; first: boolean; segment_ends: number[]; context_before: string; context_after: string }
|
| 2 |
export interface Part { index: number; start: number; end: number; audio_url: string; bytes?: unknown; pitch_semitones?: unknown; pause_kind?: unknown; pause_after_seconds?: unknown }
|
| 3 |
export interface Adapter { readonly text: string; readonly done: boolean; root?: Node | null; ensure(length: number): Promise<void>; progress?(): string; locateTop?(): Promise<number>; offsetAtTop?(): number; range?(start: number, end: number): Range | null; follow?(start: number, end: number): void | Promise<void>; reveal?(position: number): void | Promise<void>; inView?(position: number): boolean; saveView?(): { top: number; frame: number | null }; restoreView?(view: { top: number; frame: number | null }): void }
|
| 4 |
+
export interface Snapshot { id: string; title: string; text: string; adapter?: Adapter | undefined; growing?: Promise<void> | null }
|
| 5 |
export interface Preview extends Snapshot { snapshot?: Snapshot; host?: HTMLElement | null; body: HTMLElement | null }
|
| 6 |
export type PreviewInput = { id: string; title: string; host?: HTMLElement | null; body?: HTMLElement | null; tools?: Element | null; buttonClass?: string } & ({ adapter: Adapter; text?: string } | { adapter?: undefined; text: string });
|
| 7 |
export interface History extends Batch { parts: Part[] }
|