// Transport is supplied by the Reader's cancellation/deadline-owned request manager. /** @typedef {import('../../../typings/reader-v3-strict').Resource} Resource */ /** @typedef {import('../../../typings/reader-v3-strict').DatasetPrimary} DatasetPrimary */ /** @typedef {import('../../../typings/reader-v3-strict').Partition} Partition */ /** @typedef {import('../../../typings/reader-v3-strict').TextEntry} TextEntry */ /** @typedef {import('../../../typings/reader-v3-strict').TextLayer} TextLayer */ /** @typedef {import('../../../typings/reader-v3-strict').TextIndex} TextIndex */ /** @typedef {import('../../../typings/reader-v3-strict').TextPartition} TextPartition */ /** @typedef {import('../../../typings/reader-v3-strict').ReadingManifest} ReadingManifest */ /** @typedef {import('../../../typings/reader-v3-strict').PageMap} PageMap */ /** @param {unknown} value */ const sha = value => typeof value === "string" && /^[0-9a-f]{64}$/.test(value); /** @param {number} value */ const positive = value => Number.isFinite(value) && value > 0; /** @param {number} value */ const integer = value => Number.isSafeInteger(value) && value > 0; /** @returns {never} */ function invalid() { throw new Error("PDF_V3_INVALID"); } const modes = new Set(["auto", "horizontal-ltr", "horizontal-rtl", "vertical-rl", "vertical-lr"]); const pathPattern = /^objects\/[0-9a-f]{2}\/[0-9a-f]{64}\/[0-9a-f]{16}\/(?:reading-manifest\.json|page-map\.json\.gz|text-layer-manifest\.json|text-review-manifest\.json|text\/(?:page-[0-9]{6}\.json\.gz|book-text\.json\.gz|search-[0-9]{6}-[0-9]{6}\.json\.gz|partition-[0-9]{6}-[0-9]{6}-manifest\.json)|preview\/(?:page-[0-9]{6}\.(?:png|webp|jpeg|svg|jxl)|partition-[0-9]{6}-[0-9]{6}-manifest\.json))$/; const sharedPagePattern = /^objects\/[0-9a-f]{2}\/[0-9a-f]{64}\/[0-9a-f]{16}\/pages\/page-[0-9]{6}\.(?:jxl|png)$/; /** @param {unknown} path */ export const isV3Path = path => typeof path === "string" && (pathPattern.test(path) || sharedPagePattern.test(path)); /** @param {Resource} ref @param {string} [source] */ export function validateResource(ref, source = "") { if (!ref || typeof ref.path !== "string" || !["vomebook/pdf-pages-v2", "vomebook/reader-assets-v2"].includes(ref.bucket) || ref.role !== "runtime" || !sha(ref.sha256) || !integer(ref.bytes) || !(/** @type {typeof globalThis & {VoiceOfMLReader: {isBucketPath(path: string, runtime: boolean, bucket: string): boolean}}} */ (globalThis)).VoiceOfMLReader.isBucketPath(ref.path, true, ref.bucket)) invalid(); if (isV3Path(ref.path) && (ref.bucket !== "vomebook/pdf-pages-v2" || (source && !ref.path.startsWith(`objects/${source.slice(0, 2)}/${source}/`)))) invalid(); return ref; } /** @param {DatasetPrimary} ref @param {string} [sourceKey] @param {string} [sourceSha] @param {string} [expectedKind] */ function validateDatasetPrimary(ref, sourceKey, sourceSha, expectedKind) { const keys = ["kind", "repo", "path", "revision", "sha256", "bytes", "role"]; if (!ref || typeof ref !== "object" || Array.isArray(ref) || Object.keys(ref).length !== keys.length || keys.some(key => !Object.hasOwn(ref, key)) || ref.kind !== "dataset-source" || ref.role !== "runtime" || typeof ref.repo !== "string" || !/^VoiceOfML\/[A-Za-z0-9._-]+$/.test(ref.repo) || [".", ".."].includes(ref.repo.slice("VoiceOfML/".length)) || typeof ref.path !== "string" || !ref.path || ref.path.startsWith("/") || ref.path.split("/").some(part => !part || part === "." || part === "..") || /[\\%?#\x00-\x1f\x7f\p{Cs}]/u.test(ref.path) || !/\.(?:pdf|djvu)$/i.test(ref.path) || typeof ref.revision !== "string" || !/^[0-9a-f]{40}$/.test(ref.revision) || !sha(ref.sha256) || !integer(ref.bytes) || ref.bytes > (/\.pdf$/i.test(ref.path) ? 2 * 1024 * 1024 * 1024 : 512 * 1024 * 1024) || (sourceKey !== undefined && sourceKey !== ref.repo + "\0" + ref.path) || (sourceSha !== undefined && sourceSha !== ref.sha256) || (expectedKind !== undefined && !ref.path.toLowerCase().endsWith("." + expectedKind))) invalid(); } /** @param {DatasetPrimary} ref */ export function datasetPrimaryUrl(ref) { validateDatasetPrimary(ref); return `https://huggingface.co/datasets/${ref.repo}/resolve/${ref.revision}/` + ref.path.split("/").map(encodeURIComponent).join("/"); } /** @param {unknown} b */ function validBox(b) { return Array.isArray(b) && b.length === 4 && b.every(v => Number.isFinite(v) && v >= 0 && v <= 1) && b[0] < b[2] && b[1] < b[3]; } /** @param {unknown} quad */ function validQuad(quad) { if (!Array.isArray(quad) || quad.length !== 4 || quad.some(point => !Array.isArray(point) || point.length !== 2 || point.some(v => !Number.isFinite(v) || v < 0 || v > 1))) return false; let area = 0; for (let i = 0; i < 4; i++) area += quad[i][0] * quad[(i + 1) % 4][1] - quad[(i + 1) % 4][0] * quad[i][1]; return Math.abs(area) > 2e-9; } /** @param {TextLayer} layer @param {TextEntry} entry @param {string} source */ export function validateTextLayer(layer, entry, source) { if (!entry || !layer || layer.version !== 1 || layer.kind !== "pdf-text-layer" || layer.source_sha256 !== source || layer.page !== entry.page || !sha(layer.generation) || layer.generation !== entry.generation || !sha(layer.raw_sha256) || !sha(layer.page_identity) || layer.page_identity !== entry.page_identity || layer.offset_unit !== "unicode-codepoint" || typeof layer.text !== "string" || !["raw", "accepted"].includes(layer.revision) || !["unreviewed", "partially-reviewed"].includes(layer.quality) || !["processed", "processed-empty"].includes(layer.processing) || layer.quality !== entry.quality || layer.processing !== entry.processing || !positive(layer.geometry?.width) || !positive(layer.geometry?.height) || layer.geometry.coordinate_space !== "normalized-page" || !Array.isArray(layer.regions) || layer.regions.length > 10000) invalid(); if ((layer.revision === "raw" && layer.quality !== "unreviewed") || (layer.revision === "accepted" && (layer.quality !== "partially-reviewed" || !sha(layer.parent_generation) || !Array.isArray(layer.acceptances) || !layer.acceptances.length))) invalid(); const ids = new Set(), text = layer.text; // Regions are ordered and non-overlapping in code points. Keep one forward // UTF-16 cursor instead of allocating an array for every point on the page. let end = 0, unit = 0; /** @param {number} target */ const advance = target => { while (end < target && unit < text.length) { const high = text.charCodeAt(unit++); if (high >= 0xd800 && high <= 0xdbff && unit < text.length) { const low = text.charCodeAt(unit); if (low >= 0xdc00 && low <= 0xdfff) unit++; } end++; } return end === target; }; for (const [order, region] of layer.regions.entries()) { if (!region || typeof region.id !== "string" || ids.has(region.id) || region.order !== order || !Number.isSafeInteger(region.start) || !Number.isSafeInteger(region.end) || region.start < end || region.end <= region.start || typeof region.text !== "string" || !validBox(region.box) || !validQuad(region.quad) || !modes.has(region.writing_mode) || !["ltr", "rtl", "mixed", "neutral"].includes(region.direction)) invalid(); if (!advance(region.start)) invalid(); const begin = unit; if (!advance(region.end) || text.slice(begin, unit) !== region.text) invalid(); ids.add(region.id); } return layer; } /** @param {Partition[]} partitions @param {number} page */ export function partitionFor(partitions, page) { let low = 0, high = partitions.length; while (low < high) { const mid = (low + high) >> 1; const part = partitions[mid]; if (part && part.start <= page) low = mid + 1; else high = mid; } const part = partitions[low - 1]; return part && page <= part.end ? part : null; } /** @param {Partition[]} values @param {number} count @param {boolean} complete @param {string} source */ function partitions(values, count, complete, source) { if (!Array.isArray(values)) invalid(); let end = 0; for (const part of values) { if (!part || !integer(part.start) || !integer(part.end) || part.start <= end || part.end < part.start || part.end > count || (complete && part.start !== end + 1)) invalid(); validateResource(part.resource, source); end = part.end; } if (complete && end !== count) invalid(); } /** @param {import('../../../typings/reader-v3-strict').RepositoryOptions} options */ export function createV3Repository({ readJson, resourceUrl, signal, pageCount, sourceSha }) { /** @type {Map} */ const cache = new Map(); /** @type {Map>} */ const pending = new Map(); /** @type {TextIndex | null} */ let index = null; /** @type {Promise | null} */ let textPending = null; let bytes = 0, disposed = false, indexKey = ""; const active = () => { if (disposed || signal?.aborted) throw new DOMException("Reader closed", "AbortError"); }; /** @param {Resource} ref @param {string} [source] */ async function read(ref, source = sourceSha) { active(); validateResource(ref, source); const key = ref.bucket + ":" + ref.path + ":" + ref.sha256; const cached = cache.get(key); if (cached) { cache.delete(key); cache.set(key, cached); return cached.value; } const existing = pending.get(key); if (existing) return existing; if (pending.size >= 8) throw new Error("PDF_V3_BUSY"); const task = Promise.resolve().then(() => readJson(resourceUrl(ref), ref)).then(value => { active(); const size = JSON.stringify(value).length * 2; if (size <= 2 * 1024 * 1024) { cache.set(key, { value, size }); bytes += size; while (cache.size > 4 || bytes > 2 * 1024 * 1024) { const oldest = cache.keys().next().value; if (oldest === undefined) break; const evicted = cache.get(oldest); if (evicted) bytes -= evicted.size; cache.delete(oldest); } } return value; }).finally(() => pending.delete(key)); pending.set(key, task); return task; } /** @param {Resource} ref */ async function textIndex(ref) { active(); validateResource(ref, sourceSha); const key = ref.bucket + ":" + ref.path + ":" + ref.sha256; if (indexKey && indexKey !== key) throw new Error("PDF_V3_GENERATION_CHANGED"); indexKey = key; if (index) return index; if (!textPending) textPending = read(ref).then(payload => { const value = /** @type {TextIndex} */ (payload); if (!value || value.version !== 1 || value.kind !== "pdf-text-layer-index" || value.complete !== true || value.source_sha256 !== sourceSha || value.page_count !== pageCount || !sha(value.generation) || !["raw", "effective"].includes(value.revision) || value.offset_unit !== "unicode-codepoint") invalid(); partitions(value.partitions, pageCount, true, sourceSha); validateResource(value.book_text, sourceSha); if (!value.book_text.path.endsWith("/text/book-text.json.gz")) invalid(); if (value.search_partitions !== undefined) { partitions(value.search_partitions, pageCount, true, sourceSha); for (const part of value.search_partitions) { if (part.end - part.start >= 32 || !part.resource.path.endsWith( `/text/search-${String(part.start).padStart(6, "0")}-${String(part.end).padStart(6, "0")}.json.gz`)) invalid(); } } active(); index = value; return value; }).catch(error => { textPending = null; throw error; }); return textPending; } return { read, textIndex, /** @param {Resource} ref @param {number} page */ async textPage(ref, page) { if (!integer(page) || page > pageCount) invalid(); const root = await textIndex(ref), part = partitionFor(root.partitions, page); if (!part) invalid(); const value = /** @type {TextPartition} */ (await read(part.resource)); if (!value || value.version !== 1 || value.kind !== "pdf-text-partition" || value.source_sha256 !== sourceSha || value.generation !== root.generation || value.start !== part.start || value.end !== part.end || !Array.isArray(value.pages) || value.pages.length !== part.end - part.start + 1 || value.pages.some((p, i) => !p || p.page !== part.start + i)) invalid(); const entry = value.pages[page - part.start]; if (!entry) invalid(); validateResource(entry.resource, sourceSha); if (!entry.resource.path.endsWith(`/text/page-${String(page).padStart(6, "0")}.json.gz`)) invalid(); return validateTextLayer(/** @type {TextLayer} */ (await read(entry.resource)), entry, sourceSha); }, dispose() { disposed = true; cache.clear(); bytes = 0; index = null; } }; } /** @param {ReadingManifest} manifest @param {number} maxPages */ export function validateReadingManifest(manifest, maxPages) { if (!manifest || manifest.version !== 3 || manifest.kind !== "pdf-reading" || !sha(manifest.source_sha256) || !sha(manifest.generation) || !integer(manifest.page_count) || manifest.page_count > maxPages || typeof manifest.source_key !== "string" || !["pdf", "djvu"].includes(manifest.primary?.kind) || manifest.primary.status !== "ready" || typeof manifest.preview?.complete !== "boolean" || manifest.preview.page_count !== manifest.page_count) invalid(); const primary = manifest.primary.resource; const dataset = primary?.kind === "dataset-source"; if (dataset) validateDatasetPrimary(/** @type {DatasetPrimary} */ (primary), manifest.source_key, manifest.source_sha256, manifest.primary.kind); else validateResource(/** @type {Resource} */ (primary)); if (manifest.primary.kind === "djvu" && (manifest.page_count > 10000 || (!dataset && ((/** @type {Resource} */ (primary)).bucket !== "vomebook/pdf-pages-v2" || primary.sha256 !== manifest.source_sha256 || primary.bytes > 512 * 1024 * 1024 || !primary.path.startsWith(`objects/${manifest.source_sha256.slice(0, 2)}/${manifest.source_sha256}/`) || !primary.path.endsWith("/document.djvu"))))) invalid(); if (manifest.primary.kind === "pdf" && !dataset && !primary.path.endsWith(".pdf")) invalid(); validateResource(manifest.page_map, manifest.source_sha256); if (!manifest.page_map.path.endsWith("/page-map.json.gz")) invalid(); partitions(manifest.preview.partitions, manifest.page_count, manifest.preview.complete, manifest.source_sha256); if (!Number.isSafeInteger(manifest.preview.ready_pages) || manifest.preview.ready_pages < 0 || manifest.preview.ready_pages > manifest.page_count || (manifest.preview.complete && manifest.preview.ready_pages !== manifest.page_count)) invalid(); if (manifest.preview.complete && manifest.preview.partitions.some(p => p.complete !== true)) invalid(); if (manifest.text_layer) validateResource(manifest.text_layer, manifest.source_sha256); if (manifest.text_layer && !manifest.text_layer.path.endsWith("/text-layer-manifest.json")) invalid(); const skipped = manifest.preview.status === "skipped"; if (manifest.preview.status !== undefined && !skipped) invalid(); if (skipped && (manifest.preview.complete || manifest.preview.ready_pages !== 0 || manifest.preview.partitions.length !== 0)) invalid(); if (manifest.primary.kind === "djvu" && !skipped) throw new Error("DJVU_LEGACY_READING_UNSUPPORTED"); if (manifest.components?.document !== "ready" || manifest.components.preview !== (skipped ? "skipped" : manifest.preview.complete ? "ready" : "pending") || manifest.components.text !== (manifest.text_layer ? "ready" : "pending")) invalid(); return manifest; } /** @param {PageMap} map @param {ReadingManifest} manifest */ export function validatePageMap(map, manifest) { if (!map || map.version !== 1 || map.kind !== "pdf-page-map" || map.source_sha256 !== manifest.source_sha256 || !Array.isArray(map.pages) || map.pages.length !== manifest.page_count || map.pages.some((p, i) => !p || p.page !== i + 1 || !sha(p.identity) || !positive(p.width) || !positive(p.height) || ![0, 90, 180, 270].includes(p.rotation) || !Array.isArray(p.crop_box) || p.crop_box.length !== 4 || !Array.isArray(p.media_box) || p.media_box.length !== 4 || [...p.crop_box, ...p.media_box].some(v => !Number.isFinite(v)))) invalid(); return map; }