merong-docs 0.1.11 → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (63) hide show
  1. package/OVERVIEW.md +19 -19
  2. package/OVERVIEW.zh-CN.md +19 -22
  3. package/README.md +77 -77
  4. package/README.zh-CN.md +81 -81
  5. package/client/android-file-share.ts +25 -25
  6. package/client/controls.tsx +163 -163
  7. package/client/document-panel.tsx +166 -166
  8. package/client/external-file.tsx +78 -78
  9. package/client/file-reader.tsx +43 -43
  10. package/client/markdown-panel.tsx +737 -737
  11. package/client/markdown-scroll.ts +122 -122
  12. package/client/messages.ts +224 -224
  13. package/client/native-contacts.ts +145 -145
  14. package/client/page-render-queue.ts +12 -12
  15. package/client/page-selection.tsx +227 -227
  16. package/client/page-tools.tsx +72 -72
  17. package/client/pdf-geometry.ts +96 -96
  18. package/client/pdf-panel.tsx +477 -477
  19. package/client/reader-find.tsx +190 -190
  20. package/client/reader-notice.tsx +46 -46
  21. package/client/settings.tsx +143 -143
  22. package/client/syntax.tsx +55 -55
  23. package/client/viewport-geometry.ts +61 -61
  24. package/client/web.ts +462 -462
  25. package/client/worksheet-panel.tsx +631 -631
  26. package/client/zoom-controls.tsx +140 -140
  27. package/index.client.tsx +36 -36
  28. package/index.server.ts +73 -73
  29. package/node_modules/markdown-it/bin/markdown-it.mjs +0 -0
  30. package/node_modules/yaml/bin.mjs +0 -0
  31. package/npm-shrinkwrap.json +2 -2
  32. package/package.json +1 -1
  33. package/scripts/prepare-office.mjs +20 -20
  34. package/server/engine.ts +89 -89
  35. package/server/external-file.ts +42 -42
  36. package/server/generated/document-worker.ts +1 -1
  37. package/server/generated/rust-reader_bg.wasm +0 -0
  38. package/server/markdown-index.ts +305 -305
  39. package/server/markdown-links.ts +51 -51
  40. package/server/markdown-page.ts +120 -120
  41. package/server/office-fonts.cjs +824 -824
  42. package/server/office-location.ts +41 -41
  43. package/server/office-preview.ts +186 -186
  44. package/server/office-worker.cjs +49 -49
  45. package/server/office-xml.ts +79 -79
  46. package/server/pdf-engine.ts +168 -168
  47. package/server/pdf-text-geometry.ts +60 -60
  48. package/server/rust-reader.ts +40 -40
  49. package/server/structured-document.ts +69 -69
  50. package/server/text-search.ts +15 -15
  51. package/server/worker-entry.ts +42 -42
  52. package/server/worker-protocol.ts +38 -38
  53. package/server/worksheet.ts +67 -67
  54. package/server/workspace-file.ts +63 -63
  55. package/shared/contracts.ts +187 -187
  56. package/shared/file-limits.ts +5 -5
  57. package/shared/markdown-constants.ts +4 -4
  58. package/shared/markdown-math.ts +198 -198
  59. package/shared/markdown-references.ts +83 -83
  60. package/shared/markdown-source-location.ts +8 -8
  61. package/shared/reader-settings.ts +15 -15
  62. package/shared/reader-shortcuts.ts +132 -132
  63. package/vendor/office2pdf/office2pdf_bg.wasm +2 -2
@@ -1,79 +1,79 @@
1
- import { posix } from "node:path";
2
- import { DOMParser, onErrorStopParsing, type Document, type Element } from "@xmldom/xmldom";
3
- import { fromBufferPromise, type Entry, type ZipFile } from "yauzl";
4
-
5
- const xmlLimit = 4 * 1024 * 1024;
6
- const totalXmlLimit = 12 * 1024 * 1024;
7
- const parser = new DOMParser({ onError: onErrorStopParsing });
8
- type XmlParts = Map<string, Document>;
9
-
10
- export async function readZipText(archive: ZipFile, entry: Entry): Promise<string> {
11
- const stream = await archive.openReadStreamPromise(entry);
12
- const chunks: Buffer[] = [];
13
- for await (const chunk of stream) chunks.push(chunk);
14
- return Buffer.concat(chunks).toString("utf8").replace(/^\uFEFF/, "");
15
- }
16
-
17
- export function descendants(node: Document | Element, name: string): Element[] {
18
- return Array.from(node.getElementsByTagNameNS("*", name));
19
- }
20
-
21
- export function children(node: Element, names: string[]): Element[] {
22
- return Array.from(node.childNodes).filter((child): child is Element =>
23
- child.nodeType === 1 && names.includes((child as Element).localName ?? ""),
24
- );
25
- }
26
-
27
- export function plainText(node: Element): string {
28
- return descendants(node, "t").map(({ textContent }) => textContent ?? "").join("");
29
- }
30
-
31
- export async function loadOfficeSources(bytes: Buffer, select: (path: string) => boolean) {
32
- const archive = await fromBufferPromise(bytes, { lazyEntries: true, validateEntrySizes: true });
33
- const documents = new Map<string, string>();
34
- let total = 0;
35
- try {
36
- if (archive.entryCount > 8_000) throw new Error("Document exceeds the preview limit.");
37
- for await (const entry of archive.eachEntry()) {
38
- if (!select(entry.fileName)) continue;
39
- total += entry.uncompressedSize;
40
- if (entry.uncompressedSize > xmlLimit || total > totalXmlLimit) throw new Error("Document exceeds the preview limit.");
41
- const source = await readZipText(archive, entry);
42
- if (/<!DOCTYPE/i.test(source)) throw new Error("Unsupported document XML.");
43
- documents.set(entry.fileName, source);
44
- }
45
- return documents;
46
- } finally {
47
- archive.close();
48
- }
49
- }
50
-
51
- export async function loadOffice(bytes: Buffer, select: (path: string) => boolean): Promise<XmlParts> {
52
- const documents = await loadOfficeSources(bytes, select);
53
- return new Map(Array.from(documents, ([name, source]) => [name, parser.parseFromString(source, "application/xml")]));
54
- }
55
-
56
- export function relatedParts(documents: XmlParts, main: string, tag: string) {
57
- const part = documents.get(main);
58
- const directory = posix.dirname(main);
59
- const relationships = documents.get(`${directory}/_rels/${posix.basename(main)}.rels`);
60
- if (!part || !relationships) throw new Error("Missing document parts.");
61
- const targets = new Map(descendants(relationships, "Relationship").flatMap((relation) => {
62
- const target = relation.getAttribute("Target");
63
- const id = relation.getAttribute("Id");
64
- if (!id || !target || relation.getAttribute("TargetMode") === "External") return [];
65
- const path = target.startsWith("/") ? target.slice(1) : posix.normalize(`${directory}/${target}`);
66
- return [[id, path] as const];
67
- }));
68
- return descendants(part, tag).map((entry) => {
69
- const relationship = entry.getAttributeNS("http://schemas.openxmlformats.org/officeDocument/2006/relationships", "id")
70
- ?? entry.getAttributeNS("http://purl.oclc.org/ooxml/officeDocument/relationships", "id");
71
- const path = targets.get(relationship ?? "");
72
- return {
73
- name: entry.getAttribute("name") ?? undefined,
74
- hidden: ["hidden", "veryHidden"].includes(entry.getAttribute("state") ?? ""),
75
- path,
76
- content: path ? documents.get(path) : undefined,
77
- };
78
- });
79
- }
1
+ import { posix } from "node:path";
2
+ import { DOMParser, onErrorStopParsing, type Document, type Element } from "@xmldom/xmldom";
3
+ import { fromBufferPromise, type Entry, type ZipFile } from "yauzl";
4
+
5
+ const xmlLimit = 4 * 1024 * 1024;
6
+ const totalXmlLimit = 12 * 1024 * 1024;
7
+ const parser = new DOMParser({ onError: onErrorStopParsing });
8
+ type XmlParts = Map<string, Document>;
9
+
10
+ export async function readZipText(archive: ZipFile, entry: Entry): Promise<string> {
11
+ const stream = await archive.openReadStreamPromise(entry);
12
+ const chunks: Buffer[] = [];
13
+ for await (const chunk of stream) chunks.push(chunk);
14
+ return Buffer.concat(chunks).toString("utf8").replace(/^\uFEFF/, "");
15
+ }
16
+
17
+ export function descendants(node: Document | Element, name: string): Element[] {
18
+ return Array.from(node.getElementsByTagNameNS("*", name));
19
+ }
20
+
21
+ export function children(node: Element, names: string[]): Element[] {
22
+ return Array.from(node.childNodes).filter((child): child is Element =>
23
+ child.nodeType === 1 && names.includes((child as Element).localName ?? ""),
24
+ );
25
+ }
26
+
27
+ export function plainText(node: Element): string {
28
+ return descendants(node, "t").map(({ textContent }) => textContent ?? "").join("");
29
+ }
30
+
31
+ export async function loadOfficeSources(bytes: Buffer, select: (path: string) => boolean) {
32
+ const archive = await fromBufferPromise(bytes, { lazyEntries: true, validateEntrySizes: true });
33
+ const documents = new Map<string, string>();
34
+ let total = 0;
35
+ try {
36
+ if (archive.entryCount > 8_000) throw new Error("Document exceeds the preview limit.");
37
+ for await (const entry of archive.eachEntry()) {
38
+ if (!select(entry.fileName)) continue;
39
+ total += entry.uncompressedSize;
40
+ if (entry.uncompressedSize > xmlLimit || total > totalXmlLimit) throw new Error("Document exceeds the preview limit.");
41
+ const source = await readZipText(archive, entry);
42
+ if (/<!DOCTYPE/i.test(source)) throw new Error("Unsupported document XML.");
43
+ documents.set(entry.fileName, source);
44
+ }
45
+ return documents;
46
+ } finally {
47
+ archive.close();
48
+ }
49
+ }
50
+
51
+ export async function loadOffice(bytes: Buffer, select: (path: string) => boolean): Promise<XmlParts> {
52
+ const documents = await loadOfficeSources(bytes, select);
53
+ return new Map(Array.from(documents, ([name, source]) => [name, parser.parseFromString(source, "application/xml")]));
54
+ }
55
+
56
+ export function relatedParts(documents: XmlParts, main: string, tag: string) {
57
+ const part = documents.get(main);
58
+ const directory = posix.dirname(main);
59
+ const relationships = documents.get(`${directory}/_rels/${posix.basename(main)}.rels`);
60
+ if (!part || !relationships) throw new Error("Missing document parts.");
61
+ const targets = new Map(descendants(relationships, "Relationship").flatMap((relation) => {
62
+ const target = relation.getAttribute("Target");
63
+ const id = relation.getAttribute("Id");
64
+ if (!id || !target || relation.getAttribute("TargetMode") === "External") return [];
65
+ const path = target.startsWith("/") ? target.slice(1) : posix.normalize(`${directory}/${target}`);
66
+ return [[id, path] as const];
67
+ }));
68
+ return descendants(part, tag).map((entry) => {
69
+ const relationship = entry.getAttributeNS("http://schemas.openxmlformats.org/officeDocument/2006/relationships", "id")
70
+ ?? entry.getAttributeNS("http://purl.oclc.org/ooxml/officeDocument/relationships", "id");
71
+ const path = targets.get(relationship ?? "");
72
+ return {
73
+ name: entry.getAttribute("name") ?? undefined,
74
+ hidden: ["hidden", "veryHidden"].includes(entry.getAttribute("state") ?? ""),
75
+ path,
76
+ content: path ? documents.get(path) : undefined,
77
+ };
78
+ });
79
+ }
@@ -1,168 +1,168 @@
1
- import { PDFiumLibrary, type PDFiumDocument } from "@hyzyla/pdfium/inline";
2
- import type { MarkdownSearchOptions, PageRun, PageTextMatch } from "../shared/contracts";
3
- import { pdfFileLimit } from "../shared/file-limits";
4
- import { readPageText } from "./pdf-text-geometry";
5
- import { rustReader } from "./rust-reader";
6
- import { searchExpression } from "./text-search";
7
- import { withWorkspaceFile } from "./workspace-file";
8
-
9
- const maxJpegBytes = 750 * 1024;
10
- const maxCachedLayouts = 8;
11
- const maxCachedLayoutRuns = 4096;
12
- const maxCachedPages = 16;
13
- const maxCachedCharacters = 8 * 1024 * 1024;
14
- let library: Promise<PDFiumLibrary> | undefined;
15
- let opened: { key: string; document: PDFiumDocument; runs?: PageRun[] } | undefined;
16
- const cachedLayouts = new Map<string, PageRun[]>();
17
- const renderedPages = new Map<string, Awaited<ReturnType<typeof renderPage>>>();
18
- let cachedCharacters = 0;
19
-
20
- function usePdfFile<Result>(root: string, path: string, consume: (key: string, bytes: () => Promise<Buffer>) => Promise<Result>) {
21
- return withWorkspaceFile(root, path, ["pdf"], async (file, size, revision) => {
22
- if (size > pdfFileLimit) throw new Error("PDF exceeds the preview limit.");
23
- return consume(JSON.stringify([root, path, revision]), () => file.readFile());
24
- });
25
- }
26
-
27
- export function rasterizePdf(root: string, path: string, pageNumber: number, pixels: number) {
28
- return usePdfFile(root, path, (key, bytes) => rasterizePdfPage(key, bytes, pageNumber, pixels));
29
- }
30
-
31
- export function inspectPdf(root: string, path: string) {
32
- return usePdfFile(root, path, inspectPdfPages);
33
- }
34
-
35
- export function pdfText(root: string, path: string, page: number) {
36
- return usePdfFile(root, path, (key, bytes) => readPdfText(key, bytes, page));
37
- }
38
-
39
- export function searchPdf(root: string, path: string, query: string, options: MarkdownSearchOptions) {
40
- return usePdfFile(root, path, (key, bytes) => findPageTextMatches(key, bytes, query, options));
41
- }
42
-
43
- async function openDocument(key: string, bytes: () => Promise<Uint8Array>) {
44
- if (opened?.key !== key) {
45
- opened?.document.destroy();
46
- opened = undefined;
47
- const engine = await (library ??= PDFiumLibrary.init({ disableBase64Warning: true }));
48
- const document = await engine.loadDocument(await bytes());
49
- opened = { key, document };
50
- }
51
- return opened;
52
- }
53
-
54
- export async function readPdfText(key: string, bytes: () => Promise<Uint8Array>, number: number) {
55
- const { document } = await openDocument(key, bytes);
56
- if (number > document.getPageCount()) return { text: "", truncated: false, glyphs: [] };
57
- const page = document.getPage(number - 1);
58
- try {
59
- return readPageText(page, true);
60
- } finally {
61
- page.close();
62
- }
63
- }
64
-
65
- export async function findPageTextMatches(key: string, bytes: () => Promise<Uint8Array>, query: string, options: MarkdownSearchOptions) {
66
- const expression = searchExpression(query, options, true);
67
- const matches: PageTextMatch[] = [];
68
- if (!expression) return { matches, limited: false, invalidPattern: true };
69
- const { document } = await openDocument(key, bytes);
70
- const count = document.getPageCount();
71
- const limit = 10_000;
72
- let limited = false;
73
- for (let number = 1; number <= count; number++) {
74
- const page = document.getPage(number - 1);
75
- try {
76
- const { text, truncated } = readPageText(page, false);
77
- limited ||= truncated;
78
- for (const match of text.matchAll(expression)) {
79
- if (!match[0].length) continue;
80
- if (matches.length >= limit) return { matches, limited: true, invalidPattern: false };
81
- matches.push([number, match.index, match.index + match[0].length]);
82
- }
83
- } finally {
84
- page.close();
85
- }
86
- }
87
- return { matches, limited, invalidPattern: false };
88
- }
89
-
90
- function readSize(page: ReturnType<PDFiumDocument["getPage"]>) {
91
- const { originalWidth: width, originalHeight: height } = page.getOriginalSize();
92
- if (!Number.isFinite(width + height) || width <= 0 || height <= 0) {
93
- throw new Error("PDF page has invalid dimensions.");
94
- }
95
- return { width, height };
96
- }
97
-
98
- export async function inspectPdfPages(key: string, bytes: () => Promise<Uint8Array>) {
99
- const cached = cachedLayouts.get(key);
100
- if (cached) {
101
- cachedLayouts.delete(key);
102
- cachedLayouts.set(key, cached);
103
- return cached;
104
- }
105
- const opened = await openDocument(key, bytes);
106
- if (opened.runs) return opened.runs;
107
- const { document } = opened;
108
- const pages = document.getPageCount();
109
- if (pages < 1) throw new Error("PDF has no pages.");
110
- const runs: PageRun[] = [];
111
- for (let index = 0; index < pages; index++) {
112
- const page = document.getPage(index);
113
- try {
114
- const { width, height } = readSize(page);
115
- const previous = runs.at(-1);
116
- if (previous?.width === width && previous.height === height) previous.count++;
117
- else runs.push({ count: 1, width, height });
118
- } finally {
119
- page.close();
120
- }
121
- }
122
- opened.runs = runs;
123
- if (runs.length <= maxCachedLayoutRuns) {
124
- cachedLayouts.set(key, runs);
125
- if (cachedLayouts.size > maxCachedLayouts) {
126
- const oldest = cachedLayouts.keys().next().value;
127
- if (oldest !== undefined) cachedLayouts.delete(oldest);
128
- }
129
- }
130
- return runs;
131
- }
132
-
133
- export async function rasterizePdfPage(key: string, bytes: () => Promise<Uint8Array>, pageNumber: number, pixels: number) {
134
- const cacheKey = JSON.stringify([key, pageNumber, pixels]);
135
- const cached = renderedPages.get(cacheKey);
136
- if (cached) {
137
- renderedPages.delete(cacheKey);
138
- renderedPages.set(cacheKey, cached);
139
- return cached;
140
- }
141
- const image = await renderPage(key, bytes, pageNumber, pixels);
142
- renderedPages.set(cacheKey, image);
143
- cachedCharacters += image.uri.length;
144
- for (const [oldestKey, oldest] of renderedPages) {
145
- if (renderedPages.size <= maxCachedPages && cachedCharacters <= maxCachedCharacters) break;
146
- renderedPages.delete(oldestKey);
147
- cachedCharacters -= oldest.uri.length;
148
- }
149
- return image;
150
- }
151
-
152
- async function renderPage(key: string, bytes: () => Promise<Uint8Array>, pageNumber: number, pixels: number) {
153
- const { document } = await openDocument(key, bytes);
154
- const pages = document.getPageCount();
155
- if (pages < 1) throw new Error("PDF has no pages.");
156
- const pageIndex = Math.min(pageNumber, pages);
157
- const page = document.getPage(pageIndex - 1);
158
- try {
159
- const { width, height } = readSize(page);
160
- const scale = Math.min(pixels / width, 3072 / height, Math.sqrt(5_000_000 / (width * height)));
161
- const raster = await page.render({ width: Math.max(1, Math.floor(width * scale)), height: Math.max(1, Math.floor(height * scale)) });
162
- const { encodePageJpeg } = await rustReader();
163
- const jpeg = encodePageJpeg(raster.data, raster.width, raster.height, maxJpegBytes);
164
- return { page: pageIndex, pages, width, height, uri: `data:image/jpeg;base64,${Buffer.from(jpeg).toString("base64")}` };
165
- } finally {
166
- page.close();
167
- }
168
- }
1
+ import { PDFiumLibrary, type PDFiumDocument } from "@hyzyla/pdfium/inline";
2
+ import type { MarkdownSearchOptions, PageRun, PageTextMatch } from "../shared/contracts";
3
+ import { pdfFileLimit } from "../shared/file-limits";
4
+ import { readPageText } from "./pdf-text-geometry";
5
+ import { rustReader } from "./rust-reader";
6
+ import { searchExpression } from "./text-search";
7
+ import { withWorkspaceFile } from "./workspace-file";
8
+
9
+ const maxJpegBytes = 750 * 1024;
10
+ const maxCachedLayouts = 8;
11
+ const maxCachedLayoutRuns = 4096;
12
+ const maxCachedPages = 16;
13
+ const maxCachedCharacters = 8 * 1024 * 1024;
14
+ let library: Promise<PDFiumLibrary> | undefined;
15
+ let opened: { key: string; document: PDFiumDocument; runs?: PageRun[] } | undefined;
16
+ const cachedLayouts = new Map<string, PageRun[]>();
17
+ const renderedPages = new Map<string, Awaited<ReturnType<typeof renderPage>>>();
18
+ let cachedCharacters = 0;
19
+
20
+ function usePdfFile<Result>(root: string, path: string, consume: (key: string, bytes: () => Promise<Buffer>) => Promise<Result>) {
21
+ return withWorkspaceFile(root, path, ["pdf"], async (file, size, revision) => {
22
+ if (size > pdfFileLimit) throw new Error("PDF exceeds the preview limit.");
23
+ return consume(JSON.stringify([root, path, revision]), () => file.readFile());
24
+ });
25
+ }
26
+
27
+ export function rasterizePdf(root: string, path: string, pageNumber: number, pixels: number) {
28
+ return usePdfFile(root, path, (key, bytes) => rasterizePdfPage(key, bytes, pageNumber, pixels));
29
+ }
30
+
31
+ export function inspectPdf(root: string, path: string) {
32
+ return usePdfFile(root, path, inspectPdfPages);
33
+ }
34
+
35
+ export function pdfText(root: string, path: string, page: number) {
36
+ return usePdfFile(root, path, (key, bytes) => readPdfText(key, bytes, page));
37
+ }
38
+
39
+ export function searchPdf(root: string, path: string, query: string, options: MarkdownSearchOptions) {
40
+ return usePdfFile(root, path, (key, bytes) => findPageTextMatches(key, bytes, query, options));
41
+ }
42
+
43
+ async function openDocument(key: string, bytes: () => Promise<Uint8Array>) {
44
+ if (opened?.key !== key) {
45
+ opened?.document.destroy();
46
+ opened = undefined;
47
+ const engine = await (library ??= PDFiumLibrary.init({ disableBase64Warning: true }));
48
+ const document = await engine.loadDocument(await bytes());
49
+ opened = { key, document };
50
+ }
51
+ return opened;
52
+ }
53
+
54
+ export async function readPdfText(key: string, bytes: () => Promise<Uint8Array>, number: number) {
55
+ const { document } = await openDocument(key, bytes);
56
+ if (number > document.getPageCount()) return { text: "", truncated: false, glyphs: [] };
57
+ const page = document.getPage(number - 1);
58
+ try {
59
+ return readPageText(page, true);
60
+ } finally {
61
+ page.close();
62
+ }
63
+ }
64
+
65
+ export async function findPageTextMatches(key: string, bytes: () => Promise<Uint8Array>, query: string, options: MarkdownSearchOptions) {
66
+ const expression = searchExpression(query, options, true);
67
+ const matches: PageTextMatch[] = [];
68
+ if (!expression) return { matches, limited: false, invalidPattern: true };
69
+ const { document } = await openDocument(key, bytes);
70
+ const count = document.getPageCount();
71
+ const limit = 10_000;
72
+ let limited = false;
73
+ for (let number = 1; number <= count; number++) {
74
+ const page = document.getPage(number - 1);
75
+ try {
76
+ const { text, truncated } = readPageText(page, false);
77
+ limited ||= truncated;
78
+ for (const match of text.matchAll(expression)) {
79
+ if (!match[0].length) continue;
80
+ if (matches.length >= limit) return { matches, limited: true, invalidPattern: false };
81
+ matches.push([number, match.index, match.index + match[0].length]);
82
+ }
83
+ } finally {
84
+ page.close();
85
+ }
86
+ }
87
+ return { matches, limited, invalidPattern: false };
88
+ }
89
+
90
+ function readSize(page: ReturnType<PDFiumDocument["getPage"]>) {
91
+ const { originalWidth: width, originalHeight: height } = page.getOriginalSize();
92
+ if (!Number.isFinite(width + height) || width <= 0 || height <= 0) {
93
+ throw new Error("PDF page has invalid dimensions.");
94
+ }
95
+ return { width, height };
96
+ }
97
+
98
+ export async function inspectPdfPages(key: string, bytes: () => Promise<Uint8Array>) {
99
+ const cached = cachedLayouts.get(key);
100
+ if (cached) {
101
+ cachedLayouts.delete(key);
102
+ cachedLayouts.set(key, cached);
103
+ return cached;
104
+ }
105
+ const opened = await openDocument(key, bytes);
106
+ if (opened.runs) return opened.runs;
107
+ const { document } = opened;
108
+ const pages = document.getPageCount();
109
+ if (pages < 1) throw new Error("PDF has no pages.");
110
+ const runs: PageRun[] = [];
111
+ for (let index = 0; index < pages; index++) {
112
+ const page = document.getPage(index);
113
+ try {
114
+ const { width, height } = readSize(page);
115
+ const previous = runs.at(-1);
116
+ if (previous?.width === width && previous.height === height) previous.count++;
117
+ else runs.push({ count: 1, width, height });
118
+ } finally {
119
+ page.close();
120
+ }
121
+ }
122
+ opened.runs = runs;
123
+ if (runs.length <= maxCachedLayoutRuns) {
124
+ cachedLayouts.set(key, runs);
125
+ if (cachedLayouts.size > maxCachedLayouts) {
126
+ const oldest = cachedLayouts.keys().next().value;
127
+ if (oldest !== undefined) cachedLayouts.delete(oldest);
128
+ }
129
+ }
130
+ return runs;
131
+ }
132
+
133
+ export async function rasterizePdfPage(key: string, bytes: () => Promise<Uint8Array>, pageNumber: number, pixels: number) {
134
+ const cacheKey = JSON.stringify([key, pageNumber, pixels]);
135
+ const cached = renderedPages.get(cacheKey);
136
+ if (cached) {
137
+ renderedPages.delete(cacheKey);
138
+ renderedPages.set(cacheKey, cached);
139
+ return cached;
140
+ }
141
+ const image = await renderPage(key, bytes, pageNumber, pixels);
142
+ renderedPages.set(cacheKey, image);
143
+ cachedCharacters += image.uri.length;
144
+ for (const [oldestKey, oldest] of renderedPages) {
145
+ if (renderedPages.size <= maxCachedPages && cachedCharacters <= maxCachedCharacters) break;
146
+ renderedPages.delete(oldestKey);
147
+ cachedCharacters -= oldest.uri.length;
148
+ }
149
+ return image;
150
+ }
151
+
152
+ async function renderPage(key: string, bytes: () => Promise<Uint8Array>, pageNumber: number, pixels: number) {
153
+ const { document } = await openDocument(key, bytes);
154
+ const pages = document.getPageCount();
155
+ if (pages < 1) throw new Error("PDF has no pages.");
156
+ const pageIndex = Math.min(pageNumber, pages);
157
+ const page = document.getPage(pageIndex - 1);
158
+ try {
159
+ const { width, height } = readSize(page);
160
+ const scale = Math.min(pixels / width, 3072 / height, Math.sqrt(5_000_000 / (width * height)));
161
+ const raster = await page.render({ width: Math.max(1, Math.floor(width * scale)), height: Math.max(1, Math.floor(height * scale)) });
162
+ const { encodePageJpeg } = await rustReader();
163
+ const jpeg = encodePageJpeg(raster.data, raster.width, raster.height, maxJpegBytes);
164
+ return { page: pageIndex, pages, width, height, uri: `data:image/jpeg;base64,${Buffer.from(jpeg).toString("base64")}` };
165
+ } finally {
166
+ page.close();
167
+ }
168
+ }
@@ -1,60 +1,60 @@
1
- import type { PDFiumDocument } from "@hyzyla/pdfium/inline";
2
- import type { PageGlyph } from "../shared/contracts";
3
-
4
- type Page = ReturnType<PDFiumDocument["getPage"]>;
5
- type TextGeometryPage = {
6
- pageIdx: number;
7
- loadTextPage(): number;
8
- module: {
9
- _FPDFText_CountChars(text: number): number;
10
- _FPDFText_GetUnicode(text: number, index: number): number;
11
- _FPDFText_GetLooseCharBox(text: number, index: number, rect: number): number;
12
- _FPDF_PageToDevice(page: number, x: number, y: number, width: number, height: number, rotation: number,
13
- pdfX: number, pdfY: number, deviceX: number, deviceY: number): number;
14
- HEAPF32: Float32Array;
15
- HEAP32: Int32Array;
16
- wasmExports: { malloc(size: number): number; free(address: number): void };
17
- };
18
- };
19
-
20
- const resolution = 10_000;
21
- const maxGlyphs = 16_384;
22
-
23
- export function readPageText(page: Page, positioned: boolean) {
24
- const { module, pageIdx, loadTextPage } = page as unknown as TextGeometryPage;
25
- const textPage = loadTextPage.call(page);
26
- const count = module._FPDFText_CountChars(textPage);
27
- const buffer = positioned ? module.wasmExports.malloc(16) : 0;
28
- if (positioned && !buffer) throw new Error("Could not allocate the page text buffer.");
29
- const slot = buffer >>> 2;
30
- let text = "";
31
- const glyphs: PageGlyph[] = [];
32
- try {
33
- for (let index = 0; index < Math.min(count, maxGlyphs); index++) {
34
- const code = module._FPDFText_GetUnicode(textPage, index);
35
- if (code <= 0 || code > 0x10ffff || code === 13) continue;
36
- const start = text.length;
37
- text += String.fromCodePoint(code);
38
- if (!positioned || code === 10 || !module._FPDFText_GetLooseCharBox(textPage, index, buffer)) continue;
39
- const f32 = module.HEAPF32;
40
- const left = f32[slot];
41
- const top = f32[slot + 1];
42
- const right = f32[slot + 2];
43
- const bottom = f32[slot + 3];
44
- if (!(right > left && top > bottom)) continue;
45
- const i32 = module.HEAP32;
46
- module._FPDF_PageToDevice(pageIdx, 0, 0, resolution, resolution, 0, left, top, buffer, buffer + 4);
47
- const firstX = i32[slot];
48
- const firstY = i32[slot + 1];
49
- module._FPDF_PageToDevice(pageIdx, 0, 0, resolution, resolution, 0, right, bottom, buffer, buffer + 4);
50
- const lastX = i32[slot];
51
- const lastY = i32[slot + 1];
52
- if (firstX === lastX || firstY === lastY) continue;
53
- glyphs.push([start, text.length, Math.min(firstX, lastX) / resolution, Math.min(firstY, lastY) / resolution,
54
- Math.max(firstX, lastX) / resolution, Math.max(firstY, lastY) / resolution]);
55
- }
56
- return { text, glyphs, truncated: count > maxGlyphs };
57
- } finally {
58
- if (buffer) module.wasmExports.free(buffer);
59
- }
60
- }
1
+ import type { PDFiumDocument } from "@hyzyla/pdfium/inline";
2
+ import type { PageGlyph } from "../shared/contracts";
3
+
4
+ type Page = ReturnType<PDFiumDocument["getPage"]>;
5
+ type TextGeometryPage = {
6
+ pageIdx: number;
7
+ loadTextPage(): number;
8
+ module: {
9
+ _FPDFText_CountChars(text: number): number;
10
+ _FPDFText_GetUnicode(text: number, index: number): number;
11
+ _FPDFText_GetLooseCharBox(text: number, index: number, rect: number): number;
12
+ _FPDF_PageToDevice(page: number, x: number, y: number, width: number, height: number, rotation: number,
13
+ pdfX: number, pdfY: number, deviceX: number, deviceY: number): number;
14
+ HEAPF32: Float32Array;
15
+ HEAP32: Int32Array;
16
+ wasmExports: { malloc(size: number): number; free(address: number): void };
17
+ };
18
+ };
19
+
20
+ const resolution = 10_000;
21
+ const maxGlyphs = 16_384;
22
+
23
+ export function readPageText(page: Page, positioned: boolean) {
24
+ const { module, pageIdx, loadTextPage } = page as unknown as TextGeometryPage;
25
+ const textPage = loadTextPage.call(page);
26
+ const count = module._FPDFText_CountChars(textPage);
27
+ const buffer = positioned ? module.wasmExports.malloc(16) : 0;
28
+ if (positioned && !buffer) throw new Error("Could not allocate the page text buffer.");
29
+ const slot = buffer >>> 2;
30
+ let text = "";
31
+ const glyphs: PageGlyph[] = [];
32
+ try {
33
+ for (let index = 0; index < Math.min(count, maxGlyphs); index++) {
34
+ const code = module._FPDFText_GetUnicode(textPage, index);
35
+ if (code <= 0 || code > 0x10ffff || code === 13) continue;
36
+ const start = text.length;
37
+ text += String.fromCodePoint(code);
38
+ if (!positioned || code === 10 || !module._FPDFText_GetLooseCharBox(textPage, index, buffer)) continue;
39
+ const f32 = module.HEAPF32;
40
+ const left = f32[slot];
41
+ const top = f32[slot + 1];
42
+ const right = f32[slot + 2];
43
+ const bottom = f32[slot + 3];
44
+ if (!(right > left && top > bottom)) continue;
45
+ const i32 = module.HEAP32;
46
+ module._FPDF_PageToDevice(pageIdx, 0, 0, resolution, resolution, 0, left, top, buffer, buffer + 4);
47
+ const firstX = i32[slot];
48
+ const firstY = i32[slot + 1];
49
+ module._FPDF_PageToDevice(pageIdx, 0, 0, resolution, resolution, 0, right, bottom, buffer, buffer + 4);
50
+ const lastX = i32[slot];
51
+ const lastY = i32[slot + 1];
52
+ if (firstX === lastX || firstY === lastY) continue;
53
+ glyphs.push([start, text.length, Math.min(firstX, lastX) / resolution, Math.min(firstY, lastY) / resolution,
54
+ Math.max(firstX, lastX) / resolution, Math.max(firstY, lastY) / resolution]);
55
+ }
56
+ return { text, glyphs, truncated: count > maxGlyphs };
57
+ } finally {
58
+ if (buffer) module.wasmExports.free(buffer);
59
+ }
60
+ }