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.
- package/OVERVIEW.md +19 -19
- package/OVERVIEW.zh-CN.md +19 -22
- package/README.md +77 -77
- package/README.zh-CN.md +81 -81
- package/client/android-file-share.ts +25 -25
- package/client/controls.tsx +163 -163
- package/client/document-panel.tsx +166 -166
- package/client/external-file.tsx +78 -78
- package/client/file-reader.tsx +43 -43
- package/client/markdown-panel.tsx +737 -737
- package/client/markdown-scroll.ts +122 -122
- package/client/messages.ts +224 -224
- package/client/native-contacts.ts +145 -145
- package/client/page-render-queue.ts +12 -12
- package/client/page-selection.tsx +227 -227
- package/client/page-tools.tsx +72 -72
- package/client/pdf-geometry.ts +96 -96
- package/client/pdf-panel.tsx +477 -477
- package/client/reader-find.tsx +190 -190
- package/client/reader-notice.tsx +46 -46
- package/client/settings.tsx +143 -143
- package/client/syntax.tsx +55 -55
- package/client/viewport-geometry.ts +61 -61
- package/client/web.ts +462 -462
- package/client/worksheet-panel.tsx +631 -631
- package/client/zoom-controls.tsx +140 -140
- package/index.client.tsx +36 -36
- package/index.server.ts +73 -73
- package/node_modules/markdown-it/bin/markdown-it.mjs +0 -0
- package/node_modules/yaml/bin.mjs +0 -0
- package/npm-shrinkwrap.json +2 -2
- package/package.json +1 -1
- package/scripts/prepare-office.mjs +20 -20
- package/server/engine.ts +89 -89
- package/server/external-file.ts +42 -42
- package/server/generated/document-worker.ts +1 -1
- package/server/generated/rust-reader_bg.wasm +0 -0
- package/server/markdown-index.ts +305 -305
- package/server/markdown-links.ts +51 -51
- package/server/markdown-page.ts +120 -120
- package/server/office-fonts.cjs +824 -824
- package/server/office-location.ts +41 -41
- package/server/office-preview.ts +186 -186
- package/server/office-worker.cjs +49 -49
- package/server/office-xml.ts +79 -79
- package/server/pdf-engine.ts +168 -168
- package/server/pdf-text-geometry.ts +60 -60
- package/server/rust-reader.ts +40 -40
- package/server/structured-document.ts +69 -69
- package/server/text-search.ts +15 -15
- package/server/worker-entry.ts +42 -42
- package/server/worker-protocol.ts +38 -38
- package/server/worksheet.ts +67 -67
- package/server/workspace-file.ts +63 -63
- package/shared/contracts.ts +187 -187
- package/shared/file-limits.ts +5 -5
- package/shared/markdown-constants.ts +4 -4
- package/shared/markdown-math.ts +198 -198
- package/shared/markdown-references.ts +83 -83
- package/shared/markdown-source-location.ts +8 -8
- package/shared/reader-settings.ts +15 -15
- package/shared/reader-shortcuts.ts +132 -132
- package/vendor/office2pdf/office2pdf_bg.wasm +2 -2
|
@@ -1,41 +1,41 @@
|
|
|
1
|
-
import { readFile, readdir } from "node:fs/promises";
|
|
2
|
-
import { basename, dirname, join, relative } from "node:path";
|
|
3
|
-
import preparedDirectory from "./generated/office-location";
|
|
4
|
-
|
|
5
|
-
const installationSource = `export default ${JSON.stringify(preparedDirectory)};\n`;
|
|
6
|
-
|
|
7
|
-
async function matchesInstallation(directory: string) {
|
|
8
|
-
return (await readFile(join(directory, "server", "generated", "office-location.ts"), "utf8").catch(() => null))
|
|
9
|
-
=== installationSource;
|
|
10
|
-
}
|
|
11
|
-
|
|
12
|
-
let resolvedDirectory: Promise<string> | undefined;
|
|
13
|
-
|
|
14
|
-
async function findOfficeDirectory() {
|
|
15
|
-
const directory = preparedDirectory;
|
|
16
|
-
if (await matchesInstallation(directory)) return directory;
|
|
17
|
-
|
|
18
|
-
let version = directory;
|
|
19
|
-
while (dirname(version) !== version && basename(dirname(version)) !== ".staging") version = dirname(version);
|
|
20
|
-
if (basename(dirname(version)) === ".staging") {
|
|
21
|
-
const managedRoot = dirname(dirname(version));
|
|
22
|
-
const packagePath = relative(version, directory);
|
|
23
|
-
for (const plugin of await readdir(managedRoot, { withFileTypes: true })) {
|
|
24
|
-
if (!plugin.isDirectory() || plugin.name.startsWith(".")) continue;
|
|
25
|
-
const pluginRoot = join(managedRoot, plugin.name);
|
|
26
|
-
for (const revision of await readdir(pluginRoot, { withFileTypes: true }).catch(() => [])) {
|
|
27
|
-
if (!revision.isDirectory()) continue;
|
|
28
|
-
const candidate = join(pluginRoot, revision.name, packagePath);
|
|
29
|
-
if (await matchesInstallation(candidate)) return candidate;
|
|
30
|
-
}
|
|
31
|
-
}
|
|
32
|
-
}
|
|
33
|
-
throw new Error("The bundled Office renderer is missing from this installation.");
|
|
34
|
-
}
|
|
35
|
-
|
|
36
|
-
export function officeDirectory() {
|
|
37
|
-
return resolvedDirectory ??= findOfficeDirectory().catch((error) => {
|
|
38
|
-
resolvedDirectory = undefined;
|
|
39
|
-
throw error;
|
|
40
|
-
});
|
|
41
|
-
}
|
|
1
|
+
import { readFile, readdir } from "node:fs/promises";
|
|
2
|
+
import { basename, dirname, join, relative } from "node:path";
|
|
3
|
+
import preparedDirectory from "./generated/office-location";
|
|
4
|
+
|
|
5
|
+
const installationSource = `export default ${JSON.stringify(preparedDirectory)};\n`;
|
|
6
|
+
|
|
7
|
+
async function matchesInstallation(directory: string) {
|
|
8
|
+
return (await readFile(join(directory, "server", "generated", "office-location.ts"), "utf8").catch(() => null))
|
|
9
|
+
=== installationSource;
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
let resolvedDirectory: Promise<string> | undefined;
|
|
13
|
+
|
|
14
|
+
async function findOfficeDirectory() {
|
|
15
|
+
const directory = preparedDirectory;
|
|
16
|
+
if (await matchesInstallation(directory)) return directory;
|
|
17
|
+
|
|
18
|
+
let version = directory;
|
|
19
|
+
while (dirname(version) !== version && basename(dirname(version)) !== ".staging") version = dirname(version);
|
|
20
|
+
if (basename(dirname(version)) === ".staging") {
|
|
21
|
+
const managedRoot = dirname(dirname(version));
|
|
22
|
+
const packagePath = relative(version, directory);
|
|
23
|
+
for (const plugin of await readdir(managedRoot, { withFileTypes: true })) {
|
|
24
|
+
if (!plugin.isDirectory() || plugin.name.startsWith(".")) continue;
|
|
25
|
+
const pluginRoot = join(managedRoot, plugin.name);
|
|
26
|
+
for (const revision of await readdir(pluginRoot, { withFileTypes: true }).catch(() => [])) {
|
|
27
|
+
if (!revision.isDirectory()) continue;
|
|
28
|
+
const candidate = join(pluginRoot, revision.name, packagePath);
|
|
29
|
+
if (await matchesInstallation(candidate)) return candidate;
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
throw new Error("The bundled Office renderer is missing from this installation.");
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
export function officeDirectory() {
|
|
37
|
+
return resolvedDirectory ??= findOfficeDirectory().catch((error) => {
|
|
38
|
+
resolvedDirectory = undefined;
|
|
39
|
+
throw error;
|
|
40
|
+
});
|
|
41
|
+
}
|
package/server/office-preview.ts
CHANGED
|
@@ -1,186 +1,186 @@
|
|
|
1
|
-
import { execFile } from "node:child_process";
|
|
2
|
-
import { extname, join } from "node:path";
|
|
3
|
-
import { DOMParser, onErrorStopParsing } from "@xmldom/xmldom";
|
|
4
|
-
import { fromBufferPromise } from "yauzl";
|
|
5
|
-
import { pagedOfficeExtensions, type MarkdownSearchOptions } from "../shared/contracts";
|
|
6
|
-
import { pagedOfficeFileLimit } from "../shared/file-limits";
|
|
7
|
-
import type { createEngine } from "./engine";
|
|
8
|
-
import { officeDirectory } from "./office-location";
|
|
9
|
-
import { readZipText } from "./office-xml";
|
|
10
|
-
import { withWorkspaceFile } from "./workspace-file";
|
|
11
|
-
import type { EngineResults } from "./worker-protocol";
|
|
12
|
-
|
|
13
|
-
const maxPreviewBytes = 64 * 1024 * 1024;
|
|
14
|
-
const documentPart = { docx: "word/document.xml", pptx: "ppt/presentation.xml" };
|
|
15
|
-
const relationshipNamespace = "http://schemas.openxmlformats.org/package/2006/relationships";
|
|
16
|
-
const externalOrActivePart = /(?:^|\/)(?:activeX|externalLinks|oleObject[^/]*|vbaProject\.bin)(?:\/|$)/i;
|
|
17
|
-
const blockedRelationshipKinds = new Set(["oleobject", "control", "activexcontrol", "externallink", "dde", "vbaproject"]);
|
|
18
|
-
|
|
19
|
-
async function supportsFormattedPreview(content: Buffer, extension: string) {
|
|
20
|
-
if (!Object.hasOwn(documentPart, extension)) return false;
|
|
21
|
-
const archive = await fromBufferPromise(content, { lazyEntries: true, validateEntrySizes: true }).catch(() => null);
|
|
22
|
-
if (!archive) return false;
|
|
23
|
-
const parser = new DOMParser({ onError: onErrorStopParsing });
|
|
24
|
-
const entries = new Set<string>();
|
|
25
|
-
let relationshipBytes = 0;
|
|
26
|
-
let unpackedBytes = 0;
|
|
27
|
-
try {
|
|
28
|
-
if (archive.entryCount > 8_000) return false;
|
|
29
|
-
for await (const entry of archive.eachEntry()) {
|
|
30
|
-
const { fileName, uncompressedSize } = entry;
|
|
31
|
-
unpackedBytes += uncompressedSize;
|
|
32
|
-
if (unpackedBytes > 256 * 1024 * 1024) return false;
|
|
33
|
-
const normalizedName = fileName.toLowerCase();
|
|
34
|
-
if (externalOrActivePart.test(fileName) || entries.has(normalizedName)) return false;
|
|
35
|
-
entries.add(normalizedName);
|
|
36
|
-
if (!normalizedName.endsWith(".rels")) continue;
|
|
37
|
-
relationshipBytes += uncompressedSize;
|
|
38
|
-
if (relationshipBytes > 2 * 1024 * 1024) return false;
|
|
39
|
-
const source = await readZipText(archive, entry);
|
|
40
|
-
if (source.includes("\0") || /<!DOCTYPE/i.test(source)) return false;
|
|
41
|
-
const root = parser.parseFromString(source, "application/xml").documentElement;
|
|
42
|
-
if (root?.namespaceURI !== relationshipNamespace || root.localName !== "Relationships") return false;
|
|
43
|
-
for (const relation of Array.from(root.getElementsByTagNameNS(relationshipNamespace, "Relationship"))) {
|
|
44
|
-
const kind = relation.getAttribute("Type")?.split("/").pop()?.toLowerCase();
|
|
45
|
-
const external = relation.getAttribute("TargetMode")?.toLowerCase() === "external";
|
|
46
|
-
if (external && kind !== "hyperlink") return false;
|
|
47
|
-
if (kind && blockedRelationshipKinds.has(kind)) return false;
|
|
48
|
-
if (kind === "package" && !(
|
|
49
|
-
extension === "pptx" &&
|
|
50
|
-
/^ppt\/charts\/_rels\/[^/]+\.xml\.rels$/i.test(fileName) &&
|
|
51
|
-
/^(?:\.\.\/embeddings\/|\/ppt\/embeddings\/)[^/]+\.xlsx$/i.test(relation.getAttribute("Target") ?? "")
|
|
52
|
-
)) return false;
|
|
53
|
-
}
|
|
54
|
-
}
|
|
55
|
-
return entries.has(documentPart[extension as keyof typeof documentPart]);
|
|
56
|
-
} catch {
|
|
57
|
-
return false;
|
|
58
|
-
} finally {
|
|
59
|
-
archive.close();
|
|
60
|
-
}
|
|
61
|
-
}
|
|
62
|
-
|
|
63
|
-
export function createOfficePreview(engine: ReturnType<typeof createEngine>) {
|
|
64
|
-
const lifetime = new AbortController();
|
|
65
|
-
const cached = new Map<string, Uint8Array>();
|
|
66
|
-
const pending = new Map<string, Promise<Uint8Array | null>>();
|
|
67
|
-
const layouts = new Map<string, Promise<EngineResults["office-layout"] | null>>();
|
|
68
|
-
let cachedBytes = 0;
|
|
69
|
-
let queue = Promise.resolve();
|
|
70
|
-
|
|
71
|
-
async function convert(content: Buffer, extension: string) {
|
|
72
|
-
if (!await supportsFormattedPreview(content, extension)) return null;
|
|
73
|
-
const directory = await officeDirectory();
|
|
74
|
-
lifetime.signal.throwIfAborted();
|
|
75
|
-
return new Promise<Uint8Array>((resolve, reject) => {
|
|
76
|
-
const worker = execFile(process.execPath, [
|
|
77
|
-
"--max-old-space-size=192", "--wasm-num-compilation-tasks=4", "--no-wasm-tier-up",
|
|
78
|
-
join(directory, "server", "office-worker.cjs"), extension, String(content.byteLength),
|
|
79
|
-
], {
|
|
80
|
-
encoding: "buffer", maxBuffer: maxPreviewBytes, timeout: 90_000,
|
|
81
|
-
signal: lifetime.signal, killSignal: "SIGKILL", windowsHide: true,
|
|
82
|
-
}, (error, output) => {
|
|
83
|
-
if (lifetime.signal.aborted) {
|
|
84
|
-
reject(new Error("Reader stopped."));
|
|
85
|
-
return;
|
|
86
|
-
}
|
|
87
|
-
if (error?.code === "ERR_CHILD_PROCESS_STDIO_MAXBUFFER") {
|
|
88
|
-
reject(new Error("The Office preview exceeds the size limit."));
|
|
89
|
-
return;
|
|
90
|
-
}
|
|
91
|
-
if (error || !output.byteLength) {
|
|
92
|
-
reject(new Error(error?.killed ? "The Office preview took too long. Please retry."
|
|
93
|
-
: "The Office layout renderer could not render the document."));
|
|
94
|
-
return;
|
|
95
|
-
}
|
|
96
|
-
const shared = new Uint8Array(new SharedArrayBuffer(output.byteLength));
|
|
97
|
-
shared.set(output);
|
|
98
|
-
resolve(shared);
|
|
99
|
-
});
|
|
100
|
-
worker.stdin?.on("error", () => {});
|
|
101
|
-
worker.stdin?.end(content);
|
|
102
|
-
});
|
|
103
|
-
}
|
|
104
|
-
|
|
105
|
-
function load(key: string, read: () => Promise<Buffer>, extension: string) {
|
|
106
|
-
const previous = cached.get(key);
|
|
107
|
-
if (previous) {
|
|
108
|
-
cached.delete(key);
|
|
109
|
-
cached.set(key, previous);
|
|
110
|
-
return Promise.resolve(previous);
|
|
111
|
-
}
|
|
112
|
-
const current = pending.get(key);
|
|
113
|
-
if (current) return current;
|
|
114
|
-
if (pending.size >= 2) throw new Error("The Office layout renderer is busy. Please retry.");
|
|
115
|
-
const request = queue.then(async () => {
|
|
116
|
-
lifetime.signal.throwIfAborted();
|
|
117
|
-
return await convert(await read(), extension);
|
|
118
|
-
}).then((output) => {
|
|
119
|
-
if (!output || lifetime.signal.aborted) return output;
|
|
120
|
-
cached.set(key, output);
|
|
121
|
-
cachedBytes += output.byteLength;
|
|
122
|
-
while (cached.size > 4 || cachedBytes > maxPreviewBytes) {
|
|
123
|
-
const oldest = cached.entries().next().value;
|
|
124
|
-
if (!oldest) break;
|
|
125
|
-
cachedBytes -= oldest[1].byteLength;
|
|
126
|
-
cached.delete(oldest[0]);
|
|
127
|
-
}
|
|
128
|
-
return output;
|
|
129
|
-
}).finally(() => pending.delete(key));
|
|
130
|
-
queue = request.then(() => undefined, () => undefined);
|
|
131
|
-
pending.set(key, request);
|
|
132
|
-
return request;
|
|
133
|
-
}
|
|
134
|
-
|
|
135
|
-
function prepare(root: string, path: string) {
|
|
136
|
-
const extension = extname(path).slice(1).toLowerCase();
|
|
137
|
-
if (!pagedOfficeExtensions.includes(extension)) return Promise.resolve({ key: "", data: null });
|
|
138
|
-
return withWorkspaceFile(root, path, pagedOfficeExtensions, async (file, size, revision) => {
|
|
139
|
-
if (size > pagedOfficeFileLimit) throw new Error("Document exceeds the preview limit.");
|
|
140
|
-
const key = JSON.stringify([root, path, revision]);
|
|
141
|
-
return { key, data: await load(key, () => file.readFile(), extension) };
|
|
142
|
-
});
|
|
143
|
-
}
|
|
144
|
-
|
|
145
|
-
function layout(root: string, path: string) {
|
|
146
|
-
const target = JSON.stringify([root, path]);
|
|
147
|
-
const previous = layouts.get(target);
|
|
148
|
-
if (previous) return previous;
|
|
149
|
-
const request = prepare(root, path)
|
|
150
|
-
.then(({ key, data }) => data ? engine.dispatch({ kind: "office-layout", key, data }) : null)
|
|
151
|
-
.finally(() => layouts.delete(target));
|
|
152
|
-
layouts.set(target, request);
|
|
153
|
-
return request;
|
|
154
|
-
}
|
|
155
|
-
|
|
156
|
-
return {
|
|
157
|
-
async text(root: string, path: string, page: number) {
|
|
158
|
-
const { key, data } = await prepare(root, path);
|
|
159
|
-
return data ? engine.dispatch({ kind: "office-text", key, data, page }) : null;
|
|
160
|
-
},
|
|
161
|
-
async search(root: string, path: string, query: string, options: MarkdownSearchOptions) {
|
|
162
|
-
const { key, data } = await prepare(root, path);
|
|
163
|
-
return data ? engine.dispatch({ kind: "office-search", key, data, query, options }) : null;
|
|
164
|
-
},
|
|
165
|
-
async layoutStatus(root: string, path: string) {
|
|
166
|
-
let timer: ReturnType<typeof setTimeout> | undefined;
|
|
167
|
-
try {
|
|
168
|
-
return await Promise.race([
|
|
169
|
-
layout(root, path),
|
|
170
|
-
new Promise<"loading">((resolve) => { timer = setTimeout(resolve, 2_500, "loading"); }),
|
|
171
|
-
]);
|
|
172
|
-
} finally {
|
|
173
|
-
clearTimeout(timer);
|
|
174
|
-
}
|
|
175
|
-
},
|
|
176
|
-
async page(root: string, path: string, page: number, pixels: number) {
|
|
177
|
-
const { key, data } = await prepare(root, path);
|
|
178
|
-
return data ? engine.dispatch({ kind: "office", key, data, page, pixels }) : null;
|
|
179
|
-
},
|
|
180
|
-
stop() {
|
|
181
|
-
lifetime.abort(new Error("Reader stopped."));
|
|
182
|
-
cached.clear();
|
|
183
|
-
cachedBytes = 0;
|
|
184
|
-
},
|
|
185
|
-
};
|
|
186
|
-
}
|
|
1
|
+
import { execFile } from "node:child_process";
|
|
2
|
+
import { extname, join } from "node:path";
|
|
3
|
+
import { DOMParser, onErrorStopParsing } from "@xmldom/xmldom";
|
|
4
|
+
import { fromBufferPromise } from "yauzl";
|
|
5
|
+
import { pagedOfficeExtensions, type MarkdownSearchOptions } from "../shared/contracts";
|
|
6
|
+
import { pagedOfficeFileLimit } from "../shared/file-limits";
|
|
7
|
+
import type { createEngine } from "./engine";
|
|
8
|
+
import { officeDirectory } from "./office-location";
|
|
9
|
+
import { readZipText } from "./office-xml";
|
|
10
|
+
import { withWorkspaceFile } from "./workspace-file";
|
|
11
|
+
import type { EngineResults } from "./worker-protocol";
|
|
12
|
+
|
|
13
|
+
const maxPreviewBytes = 64 * 1024 * 1024;
|
|
14
|
+
const documentPart = { docx: "word/document.xml", pptx: "ppt/presentation.xml" };
|
|
15
|
+
const relationshipNamespace = "http://schemas.openxmlformats.org/package/2006/relationships";
|
|
16
|
+
const externalOrActivePart = /(?:^|\/)(?:activeX|externalLinks|oleObject[^/]*|vbaProject\.bin)(?:\/|$)/i;
|
|
17
|
+
const blockedRelationshipKinds = new Set(["oleobject", "control", "activexcontrol", "externallink", "dde", "vbaproject"]);
|
|
18
|
+
|
|
19
|
+
async function supportsFormattedPreview(content: Buffer, extension: string) {
|
|
20
|
+
if (!Object.hasOwn(documentPart, extension)) return false;
|
|
21
|
+
const archive = await fromBufferPromise(content, { lazyEntries: true, validateEntrySizes: true }).catch(() => null);
|
|
22
|
+
if (!archive) return false;
|
|
23
|
+
const parser = new DOMParser({ onError: onErrorStopParsing });
|
|
24
|
+
const entries = new Set<string>();
|
|
25
|
+
let relationshipBytes = 0;
|
|
26
|
+
let unpackedBytes = 0;
|
|
27
|
+
try {
|
|
28
|
+
if (archive.entryCount > 8_000) return false;
|
|
29
|
+
for await (const entry of archive.eachEntry()) {
|
|
30
|
+
const { fileName, uncompressedSize } = entry;
|
|
31
|
+
unpackedBytes += uncompressedSize;
|
|
32
|
+
if (unpackedBytes > 256 * 1024 * 1024) return false;
|
|
33
|
+
const normalizedName = fileName.toLowerCase();
|
|
34
|
+
if (externalOrActivePart.test(fileName) || entries.has(normalizedName)) return false;
|
|
35
|
+
entries.add(normalizedName);
|
|
36
|
+
if (!normalizedName.endsWith(".rels")) continue;
|
|
37
|
+
relationshipBytes += uncompressedSize;
|
|
38
|
+
if (relationshipBytes > 2 * 1024 * 1024) return false;
|
|
39
|
+
const source = await readZipText(archive, entry);
|
|
40
|
+
if (source.includes("\0") || /<!DOCTYPE/i.test(source)) return false;
|
|
41
|
+
const root = parser.parseFromString(source, "application/xml").documentElement;
|
|
42
|
+
if (root?.namespaceURI !== relationshipNamespace || root.localName !== "Relationships") return false;
|
|
43
|
+
for (const relation of Array.from(root.getElementsByTagNameNS(relationshipNamespace, "Relationship"))) {
|
|
44
|
+
const kind = relation.getAttribute("Type")?.split("/").pop()?.toLowerCase();
|
|
45
|
+
const external = relation.getAttribute("TargetMode")?.toLowerCase() === "external";
|
|
46
|
+
if (external && kind !== "hyperlink") return false;
|
|
47
|
+
if (kind && blockedRelationshipKinds.has(kind)) return false;
|
|
48
|
+
if (kind === "package" && !(
|
|
49
|
+
extension === "pptx" &&
|
|
50
|
+
/^ppt\/charts\/_rels\/[^/]+\.xml\.rels$/i.test(fileName) &&
|
|
51
|
+
/^(?:\.\.\/embeddings\/|\/ppt\/embeddings\/)[^/]+\.xlsx$/i.test(relation.getAttribute("Target") ?? "")
|
|
52
|
+
)) return false;
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
return entries.has(documentPart[extension as keyof typeof documentPart]);
|
|
56
|
+
} catch {
|
|
57
|
+
return false;
|
|
58
|
+
} finally {
|
|
59
|
+
archive.close();
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
export function createOfficePreview(engine: ReturnType<typeof createEngine>) {
|
|
64
|
+
const lifetime = new AbortController();
|
|
65
|
+
const cached = new Map<string, Uint8Array>();
|
|
66
|
+
const pending = new Map<string, Promise<Uint8Array | null>>();
|
|
67
|
+
const layouts = new Map<string, Promise<EngineResults["office-layout"] | null>>();
|
|
68
|
+
let cachedBytes = 0;
|
|
69
|
+
let queue = Promise.resolve();
|
|
70
|
+
|
|
71
|
+
async function convert(content: Buffer, extension: string) {
|
|
72
|
+
if (!await supportsFormattedPreview(content, extension)) return null;
|
|
73
|
+
const directory = await officeDirectory();
|
|
74
|
+
lifetime.signal.throwIfAborted();
|
|
75
|
+
return new Promise<Uint8Array>((resolve, reject) => {
|
|
76
|
+
const worker = execFile(process.execPath, [
|
|
77
|
+
"--max-old-space-size=192", "--wasm-num-compilation-tasks=4", "--no-wasm-tier-up",
|
|
78
|
+
join(directory, "server", "office-worker.cjs"), extension, String(content.byteLength),
|
|
79
|
+
], {
|
|
80
|
+
encoding: "buffer", maxBuffer: maxPreviewBytes, timeout: 90_000,
|
|
81
|
+
signal: lifetime.signal, killSignal: "SIGKILL", windowsHide: true,
|
|
82
|
+
}, (error, output) => {
|
|
83
|
+
if (lifetime.signal.aborted) {
|
|
84
|
+
reject(new Error("Reader stopped."));
|
|
85
|
+
return;
|
|
86
|
+
}
|
|
87
|
+
if (error?.code === "ERR_CHILD_PROCESS_STDIO_MAXBUFFER") {
|
|
88
|
+
reject(new Error("The Office preview exceeds the size limit."));
|
|
89
|
+
return;
|
|
90
|
+
}
|
|
91
|
+
if (error || !output.byteLength) {
|
|
92
|
+
reject(new Error(error?.killed ? "The Office preview took too long. Please retry."
|
|
93
|
+
: "The Office layout renderer could not render the document."));
|
|
94
|
+
return;
|
|
95
|
+
}
|
|
96
|
+
const shared = new Uint8Array(new SharedArrayBuffer(output.byteLength));
|
|
97
|
+
shared.set(output);
|
|
98
|
+
resolve(shared);
|
|
99
|
+
});
|
|
100
|
+
worker.stdin?.on("error", () => {});
|
|
101
|
+
worker.stdin?.end(content);
|
|
102
|
+
});
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
function load(key: string, read: () => Promise<Buffer>, extension: string) {
|
|
106
|
+
const previous = cached.get(key);
|
|
107
|
+
if (previous) {
|
|
108
|
+
cached.delete(key);
|
|
109
|
+
cached.set(key, previous);
|
|
110
|
+
return Promise.resolve(previous);
|
|
111
|
+
}
|
|
112
|
+
const current = pending.get(key);
|
|
113
|
+
if (current) return current;
|
|
114
|
+
if (pending.size >= 2) throw new Error("The Office layout renderer is busy. Please retry.");
|
|
115
|
+
const request = queue.then(async () => {
|
|
116
|
+
lifetime.signal.throwIfAborted();
|
|
117
|
+
return await convert(await read(), extension);
|
|
118
|
+
}).then((output) => {
|
|
119
|
+
if (!output || lifetime.signal.aborted) return output;
|
|
120
|
+
cached.set(key, output);
|
|
121
|
+
cachedBytes += output.byteLength;
|
|
122
|
+
while (cached.size > 4 || cachedBytes > maxPreviewBytes) {
|
|
123
|
+
const oldest = cached.entries().next().value;
|
|
124
|
+
if (!oldest) break;
|
|
125
|
+
cachedBytes -= oldest[1].byteLength;
|
|
126
|
+
cached.delete(oldest[0]);
|
|
127
|
+
}
|
|
128
|
+
return output;
|
|
129
|
+
}).finally(() => pending.delete(key));
|
|
130
|
+
queue = request.then(() => undefined, () => undefined);
|
|
131
|
+
pending.set(key, request);
|
|
132
|
+
return request;
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
function prepare(root: string, path: string) {
|
|
136
|
+
const extension = extname(path).slice(1).toLowerCase();
|
|
137
|
+
if (!pagedOfficeExtensions.includes(extension)) return Promise.resolve({ key: "", data: null });
|
|
138
|
+
return withWorkspaceFile(root, path, pagedOfficeExtensions, async (file, size, revision) => {
|
|
139
|
+
if (size > pagedOfficeFileLimit) throw new Error("Document exceeds the preview limit.");
|
|
140
|
+
const key = JSON.stringify([root, path, revision]);
|
|
141
|
+
return { key, data: await load(key, () => file.readFile(), extension) };
|
|
142
|
+
});
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
function layout(root: string, path: string) {
|
|
146
|
+
const target = JSON.stringify([root, path]);
|
|
147
|
+
const previous = layouts.get(target);
|
|
148
|
+
if (previous) return previous;
|
|
149
|
+
const request = prepare(root, path)
|
|
150
|
+
.then(({ key, data }) => data ? engine.dispatch({ kind: "office-layout", key, data }) : null)
|
|
151
|
+
.finally(() => layouts.delete(target));
|
|
152
|
+
layouts.set(target, request);
|
|
153
|
+
return request;
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
return {
|
|
157
|
+
async text(root: string, path: string, page: number) {
|
|
158
|
+
const { key, data } = await prepare(root, path);
|
|
159
|
+
return data ? engine.dispatch({ kind: "office-text", key, data, page }) : null;
|
|
160
|
+
},
|
|
161
|
+
async search(root: string, path: string, query: string, options: MarkdownSearchOptions) {
|
|
162
|
+
const { key, data } = await prepare(root, path);
|
|
163
|
+
return data ? engine.dispatch({ kind: "office-search", key, data, query, options }) : null;
|
|
164
|
+
},
|
|
165
|
+
async layoutStatus(root: string, path: string) {
|
|
166
|
+
let timer: ReturnType<typeof setTimeout> | undefined;
|
|
167
|
+
try {
|
|
168
|
+
return await Promise.race([
|
|
169
|
+
layout(root, path),
|
|
170
|
+
new Promise<"loading">((resolve) => { timer = setTimeout(resolve, 2_500, "loading"); }),
|
|
171
|
+
]);
|
|
172
|
+
} finally {
|
|
173
|
+
clearTimeout(timer);
|
|
174
|
+
}
|
|
175
|
+
},
|
|
176
|
+
async page(root: string, path: string, page: number, pixels: number) {
|
|
177
|
+
const { key, data } = await prepare(root, path);
|
|
178
|
+
return data ? engine.dispatch({ kind: "office", key, data, page, pixels }) : null;
|
|
179
|
+
},
|
|
180
|
+
stop() {
|
|
181
|
+
lifetime.abort(new Error("Reader stopped."));
|
|
182
|
+
cached.clear();
|
|
183
|
+
cachedBytes = 0;
|
|
184
|
+
},
|
|
185
|
+
};
|
|
186
|
+
}
|
package/server/office-worker.cjs
CHANGED
|
@@ -1,49 +1,49 @@
|
|
|
1
|
-
const { readFile } = require("node:fs/promises");
|
|
2
|
-
const { join } = require("node:path");
|
|
3
|
-
const { loadFontsForDocument, systemFontPaths } = require("./office-fonts.cjs");
|
|
4
|
-
|
|
5
|
-
const fontName = "NotoSansSC-Regular.otf";
|
|
6
|
-
|
|
7
|
-
async function readInput(size) {
|
|
8
|
-
if (!Number.isSafeInteger(size) || size <= 0) throw new Error("Invalid Office input size.");
|
|
9
|
-
const content = Buffer.allocUnsafe(size);
|
|
10
|
-
let offset = 0;
|
|
11
|
-
for await (const chunk of process.stdin) {
|
|
12
|
-
if (offset + chunk.byteLength > size) throw new Error("Invalid Office input size.");
|
|
13
|
-
offset += chunk.copy(content, offset);
|
|
14
|
-
}
|
|
15
|
-
if (offset !== size) throw new Error("Incomplete Office input.");
|
|
16
|
-
return content;
|
|
17
|
-
}
|
|
18
|
-
|
|
19
|
-
async function renderOffice() {
|
|
20
|
-
const [, , extension, size] = process.argv;
|
|
21
|
-
const content = await readInput(Number(size));
|
|
22
|
-
const [bundledFont, systemFonts] = await Promise.all([
|
|
23
|
-
readFile(join(__dirname, "generated", fontName)),
|
|
24
|
-
loadFontsForDocument(content, extension),
|
|
25
|
-
]);
|
|
26
|
-
const { Office2PdfConverter } = require("../vendor/office2pdf/office2pdf.cjs");
|
|
27
|
-
const converter = new Office2PdfConverter();
|
|
28
|
-
for (const font of systemFonts) {
|
|
29
|
-
try {
|
|
30
|
-
converter.registerFont(font);
|
|
31
|
-
} catch {}
|
|
32
|
-
}
|
|
33
|
-
converter.registerFont(bundledFont);
|
|
34
|
-
converter.setLastResortFontFamily("Noto Sans SC");
|
|
35
|
-
const result = converter.convertToPdf(content, extension);
|
|
36
|
-
try {
|
|
37
|
-
process.stdout.write(result.pdf);
|
|
38
|
-
} finally {
|
|
39
|
-
result.free();
|
|
40
|
-
}
|
|
41
|
-
}
|
|
42
|
-
|
|
43
|
-
if (require.main === module) {
|
|
44
|
-
renderOffice().catch(() => {
|
|
45
|
-
process.exitCode = 1;
|
|
46
|
-
});
|
|
47
|
-
}
|
|
48
|
-
|
|
49
|
-
module.exports = { systemFontPaths };
|
|
1
|
+
const { readFile } = require("node:fs/promises");
|
|
2
|
+
const { join } = require("node:path");
|
|
3
|
+
const { loadFontsForDocument, systemFontPaths } = require("./office-fonts.cjs");
|
|
4
|
+
|
|
5
|
+
const fontName = "NotoSansSC-Regular.otf";
|
|
6
|
+
|
|
7
|
+
async function readInput(size) {
|
|
8
|
+
if (!Number.isSafeInteger(size) || size <= 0) throw new Error("Invalid Office input size.");
|
|
9
|
+
const content = Buffer.allocUnsafe(size);
|
|
10
|
+
let offset = 0;
|
|
11
|
+
for await (const chunk of process.stdin) {
|
|
12
|
+
if (offset + chunk.byteLength > size) throw new Error("Invalid Office input size.");
|
|
13
|
+
offset += chunk.copy(content, offset);
|
|
14
|
+
}
|
|
15
|
+
if (offset !== size) throw new Error("Incomplete Office input.");
|
|
16
|
+
return content;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
async function renderOffice() {
|
|
20
|
+
const [, , extension, size] = process.argv;
|
|
21
|
+
const content = await readInput(Number(size));
|
|
22
|
+
const [bundledFont, systemFonts] = await Promise.all([
|
|
23
|
+
readFile(join(__dirname, "generated", fontName)),
|
|
24
|
+
loadFontsForDocument(content, extension),
|
|
25
|
+
]);
|
|
26
|
+
const { Office2PdfConverter } = require("../vendor/office2pdf/office2pdf.cjs");
|
|
27
|
+
const converter = new Office2PdfConverter();
|
|
28
|
+
for (const font of systemFonts) {
|
|
29
|
+
try {
|
|
30
|
+
converter.registerFont(font);
|
|
31
|
+
} catch {}
|
|
32
|
+
}
|
|
33
|
+
converter.registerFont(bundledFont);
|
|
34
|
+
converter.setLastResortFontFamily("Noto Sans SC");
|
|
35
|
+
const result = converter.convertToPdf(content, extension);
|
|
36
|
+
try {
|
|
37
|
+
process.stdout.write(result.pdf);
|
|
38
|
+
} finally {
|
|
39
|
+
result.free();
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
if (require.main === module) {
|
|
44
|
+
renderOffice().catch(() => {
|
|
45
|
+
process.exitCode = 1;
|
|
46
|
+
});
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
module.exports = { systemFontPaths };
|