@deepseek-ai/libreoffice-kit 0.0.1 → 0.0.2-rc4

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 (90) hide show
  1. package/NOTICE +2 -0
  2. package/README.md +43 -47
  3. package/README.zh.md +35 -50
  4. package/assets/font-subset.json +70 -0
  5. package/assets/font-subset.wasm +0 -0
  6. package/lib/browser/assets.json +10 -0
  7. package/lib/browser/index.js +435 -0
  8. package/lib/browser/types/connection.d.ts +20 -0
  9. package/lib/browser/types/editor-engine.d.ts +50 -0
  10. package/lib/browser/types/editor-types.d.ts +141 -0
  11. package/lib/browser/types/editor.d.ts +9 -0
  12. package/lib/browser/types/engine-rendering.d.ts +3 -0
  13. package/lib/browser/types/engine-types.d.ts +17 -0
  14. package/lib/browser/types/font-channel.d.ts +20 -0
  15. package/lib/browser/types/index.d.ts +13 -0
  16. package/lib/browser/types/protocol.d.ts +117 -0
  17. package/lib/browser/types/rendering.d.ts +4 -0
  18. package/lib/browser/types/types.d.ts +90 -0
  19. package/lib/browser/types/worker.d.ts +2 -0
  20. package/lib/browser/worker.js +3711 -0
  21. package/lib/browser-assets.js +119 -0
  22. package/lib/cli.js +1303 -0
  23. package/lib/document.js +178 -0
  24. package/lib/engine-rendering.js +120 -0
  25. package/lib/font-config.js +46 -0
  26. package/lib/font-source.js +344 -0
  27. package/lib/font-worker.js +712 -0
  28. package/lib/index.js +319 -109
  29. package/lib/rendering.js +99 -0
  30. package/lib/sheet-geometry.js +111 -0
  31. package/lib/types/browser-assets.d.ts +15 -0
  32. package/lib/types/cli.d.ts +3 -0
  33. package/lib/types/document.d.ts +1 -1
  34. package/lib/types/engine-rendering.d.ts +15 -0
  35. package/lib/types/engine.d.ts +5 -5
  36. package/lib/types/font-config.d.ts +24 -0
  37. package/lib/types/font-full.d.ts +13 -0
  38. package/lib/types/font-loader.d.ts +1 -7
  39. package/lib/types/font-request.d.ts +12 -0
  40. package/lib/types/font-source-types.d.ts +82 -0
  41. package/lib/types/font-source.d.ts +10 -0
  42. package/lib/types/font-subsets.d.ts +35 -0
  43. package/lib/types/font-worker.d.ts +2 -0
  44. package/lib/types/fonts.d.ts +9 -29
  45. package/lib/types/harfbuzz-subset.d.ts +11 -0
  46. package/lib/types/image-operations.d.ts +58 -0
  47. package/lib/types/image-renderer.d.ts +6 -0
  48. package/lib/types/index.d.ts +25 -2
  49. package/lib/types/native.d.ts +4 -2
  50. package/lib/types/operations.d.ts +41 -0
  51. package/lib/types/png.d.ts +2 -0
  52. package/lib/types/profile.d.ts +8 -0
  53. package/lib/types/rendering.d.ts +41 -0
  54. package/lib/types/runtime.d.ts +14 -0
  55. package/lib/types/sheet-geometry.d.ts +38 -0
  56. package/lib/types/unicode-scripts.d.ts +18 -0
  57. package/lib/types/wasm.d.ts +76 -1
  58. package/lib/types/worker.d.ts +3 -0
  59. package/lib/worker.js +1012 -237
  60. package/licenses/font-subset/harfbuzz-COPYING +42 -0
  61. package/licenses/font-subset/harfbuzzjs-LICENSE +19 -0
  62. package/licenses/javascript/fflate-LICENSE +21 -0
  63. package/licenses/javascript/saxes-LICENSE +64 -0
  64. package/licenses/javascript/xmlchars-LICENSE +18 -0
  65. package/package.json +59 -12
  66. package/sources/browser/packages/browser/package.json +22 -0
  67. package/sources/browser/packages/browser/src/connection.ts +168 -0
  68. package/sources/browser/packages/browser/src/editor-engine.ts +382 -0
  69. package/sources/browser/packages/browser/src/editor-types.ts +106 -0
  70. package/sources/browser/packages/browser/src/editor.ts +55 -0
  71. package/sources/browser/packages/browser/src/engine-rendering.ts +2 -0
  72. package/sources/browser/packages/browser/src/engine-types.ts +14 -0
  73. package/sources/browser/packages/browser/src/font-channel.ts +99 -0
  74. package/sources/browser/packages/browser/src/index.ts +39 -0
  75. package/sources/browser/packages/browser/src/protocol.ts +40 -0
  76. package/sources/browser/packages/browser/src/rendering.ts +3 -0
  77. package/sources/browser/packages/browser/src/types.ts +92 -0
  78. package/sources/browser/packages/browser/src/worker.ts +171 -0
  79. package/sources/browser/packages/browser/tsconfig.json +5 -0
  80. package/sources/browser/packages/browser/tsdown.config.ts +7 -0
  81. package/sources/browser/scripts/build-browser.mjs +74 -0
  82. package/sources/font-subset/engine/font-subset/README.md +23 -0
  83. package/sources/font-subset/engine/font-subset/README.zh.md +23 -0
  84. package/sources/font-subset/engine/font-subset/source.json +16 -0
  85. package/sources/font-subset/harfbuzzjs/config-override-subset.h +7 -0
  86. package/sources/font-subset/harfbuzzjs/harfbuzz-subset.symbols +34 -0
  87. package/sources/font-subset/scripts/build-font-subset.mjs +64 -0
  88. package/sources/font-subset/scripts/pack-utils.mjs +69 -0
  89. package/sources/font-subset/scripts/platform-matrix.mjs +100 -0
  90. package/sources/font-subset/scripts/verify-artifacts.mjs +260 -0
package/lib/worker.js CHANGED
@@ -2,9 +2,10 @@ import { createRequire } from "node:module";
2
2
  import { parentPort, workerData } from "node:worker_threads";
3
3
  import { closeSync, constants, fstatSync, mkdirSync, openSync, readFileSync, readSync, readdirSync, realpathSync, statSync, writeFileSync } from "node:fs";
4
4
  import { basename, dirname, extname, join } from "node:path";
5
- import { strFromU8, unzipSync } from "fflate";
5
+ import { strFromU8, unzipSync, zlibSync } from "fflate";
6
6
  import { SaxesParser } from "saxes";
7
7
  import { create } from "fontkit";
8
+ import { createHash } from "node:crypto";
8
9
  //#region lib/types/errors.js
9
10
  /** Stable render failure categories shared across the Node worker and native helper transports. */
10
11
  const CODES = /* @__PURE__ */ new Set([
@@ -42,6 +43,198 @@ function failureCode(error) {
42
43
  return typeof code === "string" && CODES.has(code) ? code : "failed";
43
44
  }
44
45
  //#endregion
46
+ //#region lib/types/font-config.js
47
+ /** Browser-safe family ordering and Fontconfig XML shared by both WASM adapters. */
48
+ /**
49
+ * Case- and separator-insensitive family key used to compare names across sources.
50
+ * @param value - Family, style, or postscript name as recorded by a document or font.
51
+ * @returns The normalized key.
52
+ */
53
+ function normalize(value) {
54
+ return value.normalize("NFKC").toLowerCase().replaceAll(/[\s_-]/g, "");
55
+ }
56
+ /**
57
+ * Order named substitutions and their generic text family without excluding unlisted fonts.
58
+ * @param requested - Original family names, in document order.
59
+ * @param groups - Ordered family groups shared with Fontconfig aliases.
60
+ * @param pitch - VCL pitch; one requests a monospaced fallback.
61
+ * @param symbols - Whether symbol alternatives precede the generic fallback.
62
+ * @returns distinct family names, with original requests first.
63
+ */
64
+ function fontFamilyPriority(requested, groups, pitch = 0, symbols = false) {
65
+ const original = requested.map(normalize);
66
+ const matched = groups.filter((group) => group.some((family) => original.includes(normalize(family))));
67
+ const generic = original.includes("monospace") || pitch === 1 ? "monospace" : original.includes("serif") ? "serif" : matched.flat().map(normalize).find((family) => family === "serif" || family === "sansserif" || family === "monospace") ?? "sansserif";
68
+ const families = [...requested, ...matched.flat()];
69
+ for (const kind of symbols ? ["symbol", generic] : [generic]) for (const group of groups) if (group.some((family) => normalize(family) === kind)) families.push(...group);
70
+ const priority = /* @__PURE__ */ new Map();
71
+ for (const family of families) {
72
+ const name = normalize(family);
73
+ if (!priority.has(name)) priority.set(name, family);
74
+ }
75
+ return [...priority.values()];
76
+ }
77
+ /**
78
+ * Fontconfig XML restricts WASM discovery to imported originals in MEMFS.
79
+ * @param families - Ordered family groups; the first name of each group is its canonical spelling.
80
+ * @param requested - Additional family names the document declared.
81
+ * @returns the fontconfig document written into the module's memory filesystem.
82
+ */
83
+ function memoryFontConfig(families, requested = []) {
84
+ const escape = (value) => value.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;").replaceAll("\"", "&quot;").replaceAll("'", "&apos;");
85
+ return `<?xml version="1.0"?><!DOCTYPE fontconfig SYSTEM "fonts.dtd"><fontconfig><dir>/dsh-fonts</dir><cachedir>/dsh/font-cache</cachedir>${[...new Map([...families.flatMap((group) => group.slice(0, 1)), ...requested].map((name) => [normalize(name), name])).values()].map((name) => {
86
+ const alternatives = fontFamilyPriority([name], families).filter((family) => normalize(family) !== normalize(name));
87
+ return `<alias><family>${escape(name)}</family><accept>${alternatives.map((family) => `<family>${escape(family)}</family>`).join("")}</accept></alias>`;
88
+ }).join("")}</fontconfig>`;
89
+ }
90
+ //#endregion
91
+ //#region lib/types/ooxml.js
92
+ /** Bounded OOXML inspection and declared font diagnostics, using maintained ZIP/XML parsers. */
93
+ const MAIN_PARTS = {
94
+ odt: ["content.xml", "application/vnd.oasis.opendocument.text"],
95
+ ods: ["content.xml", "application/vnd.oasis.opendocument.spreadsheet"],
96
+ odp: ["content.xml", "application/vnd.oasis.opendocument.presentation"],
97
+ docx: ["word/document.xml", "application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml"],
98
+ xlsx: ["xl/workbook.xml", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml"],
99
+ pptx: ["ppt/presentation.xml", "application/vnd.openxmlformats-officedocument.presentationml.presentation.main+xml"]
100
+ };
101
+ /**
102
+ * @param character - One code point as yielded by iteration over a string.
103
+ * @returns the Unicode scalar the character encodes; iteration never yields an empty string.
104
+ */
105
+ function codePointOf(character) {
106
+ return character.codePointAt(0);
107
+ }
108
+ /**
109
+ * Validate ZIP size and membership before decoding selected document XML.
110
+ * @param bytes - Complete source document bytes.
111
+ * @param extension - Input extension, which selects the main document part.
112
+ * @param limits - Archive entry and declared uncompressed byte limits.
113
+ * @returns declared font families and the scalar values readable document XML declares.
114
+ * @throws ConversionError when the extension is unsupported or the archive violates its limits.
115
+ */
116
+ function inspectDocument$1(bytes, extension, limits) {
117
+ const main = MAIN_PARTS[extension];
118
+ if (!main) throw new ConversionError("unsupported-format", "Input extension must be docx, xlsx, or pptx.");
119
+ const odf = [
120
+ "odt",
121
+ "ods",
122
+ "odp"
123
+ ].includes(extension);
124
+ const names = /* @__PURE__ */ new Set();
125
+ let total = 0;
126
+ let files;
127
+ try {
128
+ files = unzipSync(bytes, { filter(entry) {
129
+ total += entry.originalSize;
130
+ if (names.has(entry.name) || names.size >= limits.maxArchiveEntries || !Number.isSafeInteger(total) || total > limits.maxUncompressedBytes) throw new Error("OOXML archive exceeds its limits or repeats an entry.");
131
+ names.add(entry.name);
132
+ if (odf) return [
133
+ "mimetype",
134
+ "content.xml",
135
+ "styles.xml",
136
+ "META-INF/manifest.xml"
137
+ ].includes(entry.name);
138
+ return entry.name === "[Content_Types].xml" || /^(word|xl|ppt)\/.*\.xml$/.test(entry.name) && !entry.name.endsWith("/fontTable.xml") && !entry.name.includes("/theme/");
139
+ } });
140
+ } catch (cause) {
141
+ throw new ConversionError("invalid-document", "Input is not a supported, bounded OOXML archive.", { cause });
142
+ }
143
+ const contentTypes = files["[Content_Types].xml"];
144
+ if (odf ? !names.has("content.xml") || !names.has("META-INF/manifest.xml") || strFromU8(files.mimetype ?? /* @__PURE__ */ new Uint8Array()) !== main[1] : !names.has("_rels/.rels") || !names.has(main[0]) || contentTypes === void 0 || !strFromU8(contentTypes).includes(main[1])) throw new ConversionError("invalid-document", `Input does not contain a ${extension} document.`);
145
+ const families = /* @__PURE__ */ new Map();
146
+ const codePoints = /* @__PURE__ */ new Set();
147
+ for (const [name, data] of Object.entries(files)) {
148
+ if (name === "[Content_Types].xml" || name === "mimetype" || name === "META-INF/manifest.xml") continue;
149
+ const partFamilies = [];
150
+ const partPoints = /* @__PURE__ */ new Set();
151
+ const parser = new SaxesParser({ xmlns: true });
152
+ parser.on("opentag", (tag) => {
153
+ const word = /wordprocessingml\/(?:2006\/)?main$/.test(tag.uri) && tag.local === "rFonts";
154
+ const drawing = /drawingml\/(?:2006\/)?main$/.test(tag.uri);
155
+ const sheet = /spreadsheetml\/(?:2006\/)?main$/.test(tag.uri) && tag.local === "name";
156
+ for (const attribute of Object.values(tag.attributes)) {
157
+ if (odf && attribute.local === "font-family") partFamilies.push(attribute.value.replace(/^['"]|['"]$/g, ""));
158
+ if (word && [
159
+ "ascii",
160
+ "hAnsi",
161
+ "eastAsia",
162
+ "cs"
163
+ ].includes(attribute.local) || drawing && attribute.local === "typeface" || sheet && attribute.local === "val") partFamilies.push(attribute.value);
164
+ }
165
+ });
166
+ parser.on("text", (text) => {
167
+ for (const char of text) if (!/\s/u.test(char)) partPoints.add(codePointOf(char));
168
+ });
169
+ const encoding = data[0] === 255 && data[1] === 254 ? "utf-16le" : data[0] === 254 && data[1] === 255 ? "utf-16be" : "utf-8";
170
+ try {
171
+ parser.write(new TextDecoder(encoding).decode(data)).close();
172
+ } catch {
173
+ continue;
174
+ }
175
+ for (const declared of partFamilies) for (const family of declared.split(";").map((value) => value.trim()).filter((value) => value && !/^\+(?:mj|mn)-(?:lt|ea|cs)$/.test(value))) families.set(normalize(family), family);
176
+ for (const point of partPoints) codePoints.add(point);
177
+ }
178
+ return {
179
+ families,
180
+ codePoints: [...codePoints]
181
+ };
182
+ }
183
+ //#endregion
184
+ //#region lib/types/document.js
185
+ /** Select bounded OOXML inspection or a legacy Office compound-file import. */
186
+ /** Input suffixes accepted by the public converter. */
187
+ const DOCUMENT_EXTENSIONS = [
188
+ "doc",
189
+ "docx",
190
+ "odt",
191
+ "xls",
192
+ "xlsx",
193
+ "ods",
194
+ "ppt",
195
+ "pptx",
196
+ "odp"
197
+ ];
198
+ const COMPOUND_SIGNATURE = [
199
+ 208,
200
+ 207,
201
+ 17,
202
+ 224,
203
+ 161,
204
+ 177,
205
+ 26,
206
+ 225
207
+ ];
208
+ /**
209
+ * Inspect the input container before invoking LibreOffice's document importer.
210
+ * Compound-file streams and legacy font tables are interpreted by LibreOffice;
211
+ * they do not supply the API's OOXML font diagnostics.
212
+ * @param bytes - Source bytes already bounded by maxInputBytes.
213
+ * @param extension - Lowercase source suffix.
214
+ * @param limits - Limits applied to ZIP-based document contents.
215
+ * @returns OOXML font metadata, or empty diagnostics for a binary document.
216
+ */
217
+ function inspectDocument(bytes, extension, limits) {
218
+ if (!DOCUMENT_EXTENSIONS.includes(extension)) throw new ConversionError("unsupported-format", `Input extension must be ${DOCUMENT_EXTENSIONS.join(", ")}.`);
219
+ if ([
220
+ "docx",
221
+ "xlsx",
222
+ "pptx",
223
+ "odt",
224
+ "ods",
225
+ "odp"
226
+ ].includes(extension)) return inspectDocument$1(bytes, extension, limits);
227
+ if (bytes.length < 512 || !COMPOUND_SIGNATURE.every((value, index) => bytes[index] === value)) throw new ConversionError("invalid-document", "Legacy Office input must contain an OLE compound document.");
228
+ const header = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
229
+ const version = header.getUint16(26, true);
230
+ const sectorShift = header.getUint16(30, true);
231
+ if (header.getUint16(28, true) !== 65534 || header.getUint16(32, true) !== 6 || !(version === 3 && sectorShift === 9 || version === 4 && sectorShift === 12) || bytes.length < 2 ** sectorShift * 2 || bytes.length % 2 ** sectorShift !== 0) throw new ConversionError("invalid-document", "Legacy Office input has an invalid or truncated compound-file header.");
232
+ return {
233
+ families: /* @__PURE__ */ new Map(),
234
+ codePoints: []
235
+ };
236
+ }
237
+ //#endregion
45
238
  //#region lib/types/fonts.js
46
239
  /** Host font metadata snapshots and conversion-local glyph matching over original files. */
47
240
  const FONT_EXTENSIONS = /* @__PURE__ */ new Set([
@@ -93,35 +286,6 @@ function absent(error) {
93
286
  "ENOTDIR"
94
287
  ].includes(String(error.code));
95
288
  }
96
- /**
97
- * Case- and separator-insensitive family key used to compare names across sources.
98
- * @param value - Family, style, or postscript name as recorded by a document or font.
99
- * @returns The normalized key.
100
- */
101
- function normalize(value) {
102
- return value.normalize("NFKC").toLowerCase().replaceAll(/[\s_-]/g, "");
103
- }
104
- /**
105
- * Order named substitutions and their generic text family without excluding unlisted fonts.
106
- * @param requested - Original family names, in document order.
107
- * @param groups - Ordered family groups shared with Fontconfig aliases.
108
- * @param pitch - VCL pitch; one requests a monospaced fallback.
109
- * @param symbols - Whether symbol alternatives precede the generic fallback.
110
- * @returns distinct family names, with original requests first.
111
- */
112
- function fontFamilyPriority(requested, groups, pitch = 0, symbols = false) {
113
- const original = requested.map(normalize);
114
- const matched = groups.filter((group) => group.some((family) => original.includes(normalize(family))));
115
- const generic = original.includes("monospace") || pitch === 1 ? "monospace" : original.includes("serif") ? "serif" : matched.flat().map(normalize).find((family) => family === "serif" || family === "sansserif" || family === "monospace") ?? "sansserif";
116
- const families = [...requested, ...matched.flat()];
117
- for (const kind of symbols ? ["symbol", generic] : [generic]) for (const group of groups) if (group.some((family) => normalize(family) === kind)) families.push(...group);
118
- const priority = /* @__PURE__ */ new Map();
119
- for (const family of families) {
120
- const name = normalize(family);
121
- if (!priority.has(name)) priority.set(name, family);
122
- }
123
- return [...priority.values()];
124
- }
125
289
  function fontPaths(directories, maxFiles) {
126
290
  const pending = [...directories].reverse();
127
291
  const visited = /* @__PURE__ */ new Set();
@@ -277,10 +441,30 @@ function regionalPriority(face, language) {
277
441
  /**
278
442
  * Snapshot eligible local font metadata without retaining font bytes or decoding glyph coverage.
279
443
  * @param options - Host font roots and physical file limits.
280
- * @returns metadata reused for the converter lifetime; recreate it after changing installed fonts.
444
+ * @param previous - Optional prior snapshot whose unchanged physical files can reuse parsed metadata.
445
+ * @returns current metadata; changed and newly installed files are decoded again.
281
446
  */
282
- function indexSystemFonts(options) {
283
- return fontPaths(options.directories, options.maxFiles).flatMap((path) => inspect(path, options.maxFileBytes));
447
+ function indexSystemFonts(options, previous = []) {
448
+ const reusable = /* @__PURE__ */ new Map();
449
+ for (const face of previous) {
450
+ const group = reusable.get(face.path);
451
+ if (group) group.push(face);
452
+ else reusable.set(face.path, [face]);
453
+ }
454
+ return fontPaths(options.directories, options.maxFiles).flatMap((path) => {
455
+ const prior = reusable.get(path);
456
+ if (prior !== void 0) {
457
+ let current;
458
+ try {
459
+ current = statSync(path);
460
+ } catch (error) {
461
+ if (absent(error)) return [];
462
+ throw error;
463
+ }
464
+ if (current.isFile() && current.size <= options.maxFileBytes && STAT_KEYS.every((key) => current[key] === prior[0][key])) return prior;
465
+ }
466
+ return inspect(path, options.maxFileBytes);
467
+ });
284
468
  }
285
469
  /** Conversion-local glyph coverage over the converter's first metadata snapshot. */
286
470
  var SystemFontCatalog = class {
@@ -299,7 +483,7 @@ var SystemFontCatalog = class {
299
483
  * generic families, then other glyph-covering faces.
300
484
  * @param request - VCL family/style attributes and Unicode scalars missing from its current font.
301
485
  * @param signal - cancellation checked between synchronous font reads.
302
- * @returns selected physical files, deduplicated across collection faces; absent glyphs remain unresolved.
486
+ * @returns selected files or physical faces according to deduplicateBy; absent glyphs remain unresolved.
303
487
  * @throws if an indexed font changes or cannot be read during glyph matching.
304
488
  */
305
489
  match(request, signal) {
@@ -327,9 +511,10 @@ var SystemFontCatalog = class {
327
511
  signal.throwIfAborted();
328
512
  const covered = covers(face, [...missing]);
329
513
  if (missing.size > 0 && covered.length === 0) continue;
330
- if (!files.has(face.path)) {
514
+ const identity = this.options.deduplicateBy === "face" ? `${face.path}#${face.faceIndex}` : face.path;
515
+ if (!files.has(identity)) {
331
516
  selected.push(face);
332
- files.add(face.path);
517
+ files.add(identity);
333
518
  }
334
519
  for (const point of covered) missing.delete(point);
335
520
  if (missing.size === 0) break;
@@ -365,130 +550,6 @@ function readFont(face) {
365
550
  }
366
551
  }
367
552
  //#endregion
368
- //#region lib/types/ooxml.js
369
- /** Bounded OOXML inspection and declared font diagnostics, using maintained ZIP/XML parsers. */
370
- const MAIN_PARTS = {
371
- docx: ["word/document.xml", "application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml"],
372
- xlsx: ["xl/workbook.xml", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml"],
373
- pptx: ["ppt/presentation.xml", "application/vnd.openxmlformats-officedocument.presentationml.presentation.main+xml"]
374
- };
375
- /**
376
- * @param character - One code point as yielded by iteration over a string.
377
- * @returns the Unicode scalar the character encodes; iteration never yields an empty string.
378
- */
379
- function codePointOf(character) {
380
- return character.codePointAt(0);
381
- }
382
- /**
383
- * Validate ZIP size and membership before decoding selected document XML.
384
- * @param bytes - Complete source document bytes.
385
- * @param extension - Input extension, which selects the main document part.
386
- * @param limits - Archive entry and declared uncompressed byte limits.
387
- * @returns declared font families and the scalar values readable document XML declares.
388
- * @throws ConversionError when the extension is unsupported or the archive violates its limits.
389
- */
390
- function inspectDocument$1(bytes, extension, limits) {
391
- const main = MAIN_PARTS[extension];
392
- if (!main) throw new ConversionError("unsupported-format", "Input extension must be docx, xlsx, or pptx.");
393
- const names = /* @__PURE__ */ new Set();
394
- let total = 0;
395
- let files;
396
- try {
397
- files = unzipSync(bytes, { filter(entry) {
398
- total += entry.originalSize;
399
- if (names.has(entry.name) || names.size >= limits.maxArchiveEntries || !Number.isSafeInteger(total) || total > limits.maxUncompressedBytes) throw new Error("OOXML archive exceeds its limits or repeats an entry.");
400
- names.add(entry.name);
401
- return entry.name === "[Content_Types].xml" || /^(word|xl|ppt)\/.*\.xml$/.test(entry.name) && !entry.name.endsWith("/fontTable.xml") && !entry.name.includes("/theme/");
402
- } });
403
- } catch (cause) {
404
- throw new ConversionError("invalid-document", "Input is not a supported, bounded OOXML archive.", { cause });
405
- }
406
- const contentTypes = files["[Content_Types].xml"];
407
- if (!names.has("_rels/.rels") || !names.has(main[0]) || contentTypes === void 0 || !strFromU8(contentTypes).includes(main[1])) throw new ConversionError("invalid-document", `Input does not contain a ${extension} document.`);
408
- const families = /* @__PURE__ */ new Map();
409
- const codePoints = /* @__PURE__ */ new Set();
410
- for (const [name, data] of Object.entries(files)) {
411
- if (name === "[Content_Types].xml") continue;
412
- const partFamilies = [];
413
- const partPoints = /* @__PURE__ */ new Set();
414
- const parser = new SaxesParser({ xmlns: true });
415
- parser.on("opentag", (tag) => {
416
- const word = /wordprocessingml\/(?:2006\/)?main$/.test(tag.uri) && tag.local === "rFonts";
417
- const drawing = /drawingml\/(?:2006\/)?main$/.test(tag.uri);
418
- const sheet = /spreadsheetml\/(?:2006\/)?main$/.test(tag.uri) && tag.local === "name";
419
- for (const attribute of Object.values(tag.attributes)) if (word && [
420
- "ascii",
421
- "hAnsi",
422
- "eastAsia",
423
- "cs"
424
- ].includes(attribute.local) || drawing && attribute.local === "typeface" || sheet && attribute.local === "val") partFamilies.push(attribute.value);
425
- });
426
- parser.on("text", (text) => {
427
- for (const char of text) if (!/\s/u.test(char)) partPoints.add(codePointOf(char));
428
- });
429
- const encoding = data[0] === 255 && data[1] === 254 ? "utf-16le" : data[0] === 254 && data[1] === 255 ? "utf-16be" : "utf-8";
430
- try {
431
- parser.write(new TextDecoder(encoding).decode(data)).close();
432
- } catch {
433
- continue;
434
- }
435
- for (const declared of partFamilies) for (const family of declared.split(";").map((value) => value.trim()).filter((value) => value && !/^\+(?:mj|mn)-(?:lt|ea|cs)$/.test(value))) families.set(normalize(family), family);
436
- for (const point of partPoints) codePoints.add(point);
437
- }
438
- return {
439
- families,
440
- codePoints: [...codePoints]
441
- };
442
- }
443
- //#endregion
444
- //#region lib/types/document.js
445
- /** Select bounded OOXML inspection or a legacy Office compound-file import. */
446
- /** Input suffixes accepted by the public converter. */
447
- const DOCUMENT_EXTENSIONS = [
448
- "doc",
449
- "docx",
450
- "xls",
451
- "xlsx",
452
- "ppt",
453
- "pptx"
454
- ];
455
- const COMPOUND_SIGNATURE = [
456
- 208,
457
- 207,
458
- 17,
459
- 224,
460
- 161,
461
- 177,
462
- 26,
463
- 225
464
- ];
465
- /**
466
- * Inspect the input container before invoking LibreOffice's document importer.
467
- * Compound-file streams and legacy font tables are interpreted by LibreOffice;
468
- * they do not supply the API's OOXML font diagnostics.
469
- * @param bytes - Source bytes already bounded by maxInputBytes.
470
- * @param extension - Lowercase source suffix.
471
- * @param limits - Limits applied to ZIP-based document contents.
472
- * @returns OOXML font metadata, or empty diagnostics for a binary document.
473
- */
474
- function inspectDocument(bytes, extension, limits) {
475
- if (!DOCUMENT_EXTENSIONS.includes(extension)) throw new ConversionError("unsupported-format", `Input extension must be ${DOCUMENT_EXTENSIONS.join(", ")}.`);
476
- if ([
477
- "docx",
478
- "xlsx",
479
- "pptx"
480
- ].includes(extension)) return inspectDocument$1(bytes, extension, limits);
481
- if (bytes.length < 512 || !COMPOUND_SIGNATURE.every((value, index) => bytes[index] === value)) throw new ConversionError("invalid-document", "Legacy Office input must contain an OLE compound document.");
482
- const header = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
483
- const version = header.getUint16(26, true);
484
- const sectorShift = header.getUint16(30, true);
485
- if (header.getUint16(28, true) !== 65534 || header.getUint16(32, true) !== 6 || !(version === 3 && sectorShift === 9 || version === 4 && sectorShift === 12) || bytes.length < 2 ** sectorShift * 2 || bytes.length % 2 ** sectorShift !== 0) throw new ConversionError("invalid-document", "Legacy Office input has an invalid or truncated compound-file header.");
486
- return {
487
- families: /* @__PURE__ */ new Map(),
488
- codePoints: []
489
- };
490
- }
491
- //#endregion
492
553
  //#region lib/types/font-loader.js
493
554
  /** Conversion-local font imports and exact-family diagnostics. */
494
555
  /** Build the metadata catalog inside a cancellable conversion worker. */
@@ -558,18 +619,97 @@ function preloadFonts(loader, options, document, native = false) {
558
619
  codePoints: native ? document.codePoints : []
559
620
  });
560
621
  }
622
+ //#endregion
623
+ //#region lib/types/font-full.js
624
+ /** Whole fonts for engines such as PDFium that perform their own glyph mapping. */
625
+ function fontFileFormat(bytes) {
626
+ const magic = new TextDecoder().decode(bytes.subarray(0, 4));
627
+ if (magic === "ttcf") return "ttc";
628
+ if (magic === "OTTO") return "otf";
629
+ if (magic === "true" || bytes[0] === 0 && bytes[1] === 1 && bytes[2] === 0 && bytes[3] === 0) return "ttf";
630
+ throw new Error("The full font asset is not an sfnt font or collection.");
631
+ }
632
+ /** Keep full names, encoding tables and glyphs. Apple dfont containers expose one complete sfnt resource. */
633
+ function fullFontFile(face) {
634
+ const original = readFont(face);
635
+ const sourceHash = createHash("sha256").update(original).digest("hex");
636
+ let bytes = original;
637
+ if (extname(face.path).toLowerCase() === ".dfont") bytes = indexedFace(create(original), face).stream.buffer;
638
+ return {
639
+ bytes,
640
+ sourceHash,
641
+ format: fontFileFormat(bytes)
642
+ };
643
+ }
644
+ /** Mount a fixed bounded set before PDFium performs its first installed-font enumeration. */
645
+ function preloadPdfFonts(options, faces, install) {
646
+ const catalog = new SystemFontCatalog({
647
+ faces,
648
+ fallbackFamilies: options.fontFallbacks
649
+ });
650
+ const files = /* @__PURE__ */ new Set();
651
+ const assets = /* @__PURE__ */ new Set();
652
+ let total = 0;
653
+ const families = [.../* @__PURE__ */ new Set([
654
+ ...options.initialFontFamilies,
655
+ ...options.fontFallbacks.flat(),
656
+ "sans-serif",
657
+ "serif",
658
+ "monospace"
659
+ ])];
660
+ for (const family of families) {
661
+ const result = catalog.match({
662
+ family,
663
+ style: "",
664
+ weight: 5,
665
+ italic: 0,
666
+ width: 5,
667
+ pitch: 0,
668
+ language: "",
669
+ codePoints: []
670
+ }, new AbortController().signal);
671
+ for (const face of result.fonts) {
672
+ const physical = `${face.path}#${extname(face.path).toLowerCase() === ".dfont" ? face.faceIndex : ""}`;
673
+ if (files.has(physical)) continue;
674
+ files.add(physical);
675
+ const { bytes, format } = fullFontFile(face);
676
+ const id = createHash("sha256").update(bytes).digest("hex");
677
+ if (assets.has(id)) continue;
678
+ if (total + bytes.length > options.maxLoadedFontBytes) throw new Error("PDF full-font preload exceeds maxLoadedFontBytes.");
679
+ install(`${id}.${format}`, bytes);
680
+ total += bytes.length;
681
+ assets.add(id);
682
+ }
683
+ }
684
+ }
685
+ //#endregion
686
+ //#region lib/types/profile.js
687
+ /** Private headless profile used by both native and WASM conversions. */
561
688
  /**
562
- * Fontconfig XML restricts WASM discovery to imported originals in MEMFS.
563
- * @param families - Ordered family groups; the first name of each group is its canonical spelling.
564
- * @param requested - Additional family names the document declared.
565
- * @returns the fontconfig document written into the module's memory filesystem.
689
+ * CSV selection is checked by the engine wrapper before saving; suppress the interactive warning.
690
+ * @param fontNodes - Escaped VCL font-substitution nodes, or an empty string for WASM.
691
+ * @returns The per-operation registry XML; macro execution is independently disabled at load.
566
692
  */
567
- function memoryFontConfig(families, requested = []) {
568
- const escape = (value) => value.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;").replaceAll("\"", "&quot;").replaceAll("'", "&apos;");
569
- return `<?xml version="1.0"?><!DOCTYPE fontconfig SYSTEM "fonts.dtd"><fontconfig><dir>/dsh-fonts</dir><cachedir>/dsh/font-cache</cachedir>${[...new Map([...families.flatMap((group) => group.slice(0, 1)), ...requested].map((name) => [normalize(name), name])).values()].map((name) => {
570
- const alternatives = fontFamilyPriority([name], families).filter((family) => normalize(family) !== normalize(name));
571
- return `<alias><family>${escape(name)}</family><accept>${alternatives.map((family) => `<family>${escape(family)}</family>`).join("")}</accept></alias>`;
572
- }).join("")}</fontconfig>`;
693
+ function profileXml(fontNodes = "") {
694
+ return `<?xml version="1.0" encoding="UTF-8"?><oor:items xmlns:oor="http://openoffice.org/2001/registry"><item oor:path="/org.openoffice.Office.Calc/Input"><prop oor:name="WarnActiveSheet" oor:op="fuse"><value>false</value></prop></item><item oor:path="/org.openoffice.VCL/FontSubstitutions/en">${fontNodes}</item></oor:items>\n`;
695
+ }
696
+ //#endregion
697
+ //#region lib/types/operations.js
698
+ /**
699
+ * Reject an engine output with an incorrect container signature.
700
+ * @param bytes - Complete bounded output.
701
+ * @param format - Requested output suffix.
702
+ */
703
+ function validateOutput(bytes, format) {
704
+ if (format === "pdf" && new TextDecoder().decode(bytes.subarray(0, 5)) !== "%PDF-") throw new ConversionError("invalid-output", "LibreOffice did not produce a PDF.");
705
+ if ([
706
+ "docx",
707
+ "xlsx",
708
+ "pptx",
709
+ "odt",
710
+ "ods",
711
+ "odp"
712
+ ].includes(format) && (bytes[0] !== 80 || bytes[1] !== 75 || bytes[2] !== 3 || bytes[3] !== 4)) throw new ConversionError("invalid-output", `LibreOffice did not produce a ${format} archive.`);
573
713
  }
574
714
  //#endregion
575
715
  //#region lib/types/wasm.js
@@ -593,13 +733,11 @@ function requiredFontLoader(loader) {
593
733
  if (loader === void 0) throw new Error("LibreOffice initialized without its font loader.");
594
734
  return loader;
595
735
  }
596
- /**
597
- * Convert bounded source bytes; return owned PDF bytes only after engine teardown.
598
- * @param request - Engine installation, source bytes, limits, and font metadata.
599
- * @returns the generated PDF bytes and the declared families the catalog could not provide.
600
- */
601
- async function convertWithWasm(request) {
736
+ /** A single module loader and owned session lifecycle for export and direct raster operations. */
737
+ async function withWasmSession(request, use) {
602
738
  const { engine, bytes, extension, options, document: metadata, faces } = request;
739
+ const pdf = extension === "pdf";
740
+ let idleReady = false;
603
741
  const factory = require(engine.loader);
604
742
  const raw = readFileSync(engine.data);
605
743
  const data = raw.buffer.slice(raw.byteOffset, raw.byteOffset + raw.byteLength);
@@ -611,6 +749,13 @@ async function convertWithWasm(request) {
611
749
  let failure;
612
750
  try {
613
751
  module = await factory({
752
+ dshOnCallback(type, payload) {
753
+ if (type !== 16) return;
754
+ try {
755
+ const result = JSON.parse(payload);
756
+ if (result.commandName === ".uno:ReportWhenIdle" && result.idleID === "node-raster") idleReady = true;
757
+ } catch {}
758
+ },
614
759
  noInitialRun: true,
615
760
  mainScriptUrlOrBlob: engine.loader,
616
761
  locateFile(name) {
@@ -630,10 +775,11 @@ async function convertWithWasm(request) {
630
775
  },
631
776
  preRun: [(loadedModule) => {
632
777
  for (const path of [
633
- "/dsh/profile",
778
+ "/dsh/profile/user",
634
779
  "/dsh/font-cache",
635
780
  "/dsh-fonts"
636
781
  ]) loadedModule.FS.mkdirTree(path);
782
+ loadedModule.FS.writeFile("/dsh/profile/user/registrymodifications.xcu", new TextEncoder().encode(profileXml()));
637
783
  loadedModule.FS.writeFile("/dsh/fonts.conf", new TextEncoder().encode(memoryFontConfig(options.fontFallbacks, metadata.families.values())));
638
784
  Object.assign(loadedModule.ENV, {
639
785
  HOME: "/dsh/profile",
@@ -646,7 +792,10 @@ async function convertWithWasm(request) {
646
792
  loadedModule.FS.writeFile(path, bytes);
647
793
  return path;
648
794
  }, faces);
649
- preloadFonts(fontLoader, options, metadata);
795
+ if (pdf) {
796
+ loadedModule.FS.mkdirTree("/usr/share/fonts/dsh-pdfium");
797
+ preloadPdfFonts(options, faces, (name, bytes) => loadedModule.FS.writeFile(`/usr/share/fonts/dsh-pdfium/${name}`, bytes));
798
+ } else preloadFonts(fontLoader, options, metadata);
650
799
  }],
651
800
  onAbort() {
652
801
  fatal = true;
@@ -656,52 +805,71 @@ async function convertWithWasm(request) {
656
805
  });
657
806
  const instance = module;
658
807
  const input = `/dsh/document.${extension}`;
659
- const output = "/dsh/document.pdf";
660
- instance.FS.writeFile(input, bytes);
661
- office = instance.ccall("dsh_lok_initialize", "number", ["string", "string"], [engine.programDirectory, "file:///dsh/profile"]);
662
- if (!office) throw engineError(instance, 0);
663
- document = instance.ccall("dsh_lok_document_load", "number", [
664
- "number",
665
- "string",
666
- "string"
667
- ], [
808
+ if (!pdf) instance.FS.writeFile(input, bytes);
809
+ if (pdf) {
810
+ const pointer = instance.ccall("malloc", "number", ["number"], [bytes.length]);
811
+ if (!pointer) throw engineError(instance, 0);
812
+ try {
813
+ new Uint8Array(instance.HEAPU32.buffer).set(bytes, pointer);
814
+ document = instance.ccall("dsh_pdf_open", "number", [
815
+ "number",
816
+ "number",
817
+ "string"
818
+ ], [
819
+ pointer,
820
+ bytes.length,
821
+ ""
822
+ ]);
823
+ } finally {
824
+ instance.ccall("free", null, ["number"], [pointer]);
825
+ }
826
+ if (!document) throw engineError(instance, 0);
827
+ } else {
828
+ office = instance.ccall("dsh_lok_initialize", "number", ["string", "string"], [engine.programDirectory, "file:///dsh/profile"]);
829
+ if (!office) throw engineError(instance, 0);
830
+ document = instance.ccall("dsh_lok_document_load", "number", [
831
+ "number",
832
+ "string",
833
+ "string"
834
+ ], [
835
+ office,
836
+ `file://${input}`,
837
+ "Batch=true,EnableMacrosExecution=false"
838
+ ]);
839
+ if (!document) throw engineError(instance, office);
840
+ }
841
+ return await use({
842
+ module: instance,
668
843
  office,
669
- `file://${input}`,
670
- "Batch=true,EnableMacrosExecution=false"
671
- ]);
672
- if (!document) throw engineError(instance, office);
673
- if (!instance.ccall("dsh_lok_document_save_pdf", "number", [
674
- "number",
675
- "string",
676
- "string"
677
- ], [
678
844
  document,
679
- `file://${output}`,
680
- JSON.stringify({
681
- ExportBookmarks: {
682
- type: "boolean",
683
- value: "true"
684
- },
685
- ReduceImageResolution: {
686
- type: "boolean",
687
- value: "true"
688
- },
689
- MaxImageResolution: {
690
- type: "long",
691
- value: String(options.maxImageResolution)
692
- }
693
- })
694
- ])) throw engineError(instance, office);
695
- if (!instance.FS.analyzePath(output).exists) throw new ConversionError("invalid-output", "LibreOffice did not create its PDF output.");
696
- const status = instance.FS.stat(output);
697
- if (!instance.FS.isFile(status.mode)) throw new ConversionError("invalid-output", "Generated PDF is not a regular file.");
698
- if (status.size > options.maxOutputBytes) throw new ConversionError("output-too-large", "Generated PDF exceeds its output byte limit.");
699
- const pdf = instance.FS.readFile(output);
700
- if (new TextDecoder().decode(pdf.subarray(0, 5)) !== "%PDF-") throw new ConversionError("invalid-output", "LibreOffice did not produce a PDF.");
701
- return {
702
845
  pdf,
703
- missingFonts: requiredFontLoader(fontLoader).missingFonts
704
- };
846
+ get missingFonts() {
847
+ return requiredFontLoader(fontLoader).missingFonts;
848
+ },
849
+ async idle() {
850
+ if (pdf) return;
851
+ idleReady = false;
852
+ if (!instance.ccall("dsh_lok_document_command", "number", [
853
+ "number",
854
+ "string",
855
+ "string"
856
+ ], [
857
+ document,
858
+ ".uno:ReportWhenIdle",
859
+ "{\"idleID\":{\"type\":\"string\",\"value\":\"node-raster\"}}"
860
+ ])) throw engineError(instance, office);
861
+ const deadline = performance.now() + options.timeoutMs;
862
+ while (!idleReady) {
863
+ for (let i = 0; i < 8 && !idleReady; i++) {
864
+ const pending = instance.ccall("dsh_lok_pump", "number", [], []);
865
+ if (pending < 0) throw engineError(instance, office);
866
+ if (!pending) break;
867
+ }
868
+ if (performance.now() > deadline) throw new ConversionError("timeout", "LibreOffice did not reach its raster idle barrier.");
869
+ if (!idleReady) await new Promise((resolve) => setTimeout(resolve, 0));
870
+ }
871
+ }
872
+ });
705
873
  } catch (error) {
706
874
  fatal ||= error instanceof WebAssembly.RuntimeError;
707
875
  failure = error;
@@ -710,7 +878,7 @@ async function convertWithWasm(request) {
710
878
  const errors = [];
711
879
  if (module && !fatal) {
712
880
  if (document) try {
713
- if (!module.ccall("dsh_lok_document_destroy", "number", ["number"], [document])) throw engineError(module, office);
881
+ if (!module.ccall(pdf ? "dsh_pdf_destroy" : "dsh_lok_document_destroy", "number", ["number"], [document])) throw engineError(module, office);
714
882
  } catch (error) {
715
883
  errors.push(error);
716
884
  fatal ||= error instanceof WebAssembly.RuntimeError;
@@ -729,6 +897,590 @@ async function convertWithWasm(request) {
729
897
  if (errors.length) throw new AggregateError(failure ? [failure, ...errors] : errors, "LibreOffice WASM cleanup failed.");
730
898
  }
731
899
  }
900
+ /** Convert bounded source bytes; return owned bytes only after engine teardown. */
901
+ async function convertWithWasm(request) {
902
+ return withWasmSession(request, (session) => {
903
+ const { module, office, document } = session;
904
+ const { operation, options } = request;
905
+ const output = `/dsh/output.${operation.format}`;
906
+ const filterOptions = operation.format === "pdf" ? JSON.stringify({
907
+ ExportBookmarks: {
908
+ type: "boolean",
909
+ value: "true"
910
+ },
911
+ ReduceImageResolution: {
912
+ type: "boolean",
913
+ value: "true"
914
+ },
915
+ MaxImageResolution: {
916
+ type: "long",
917
+ value: String(options.maxImageResolution)
918
+ }
919
+ }) : operation.format === "txt" ? "UTF8,LF" : "";
920
+ if (!module.ccall("dsh_lok_document_export", "number", [
921
+ "number",
922
+ "number",
923
+ "string",
924
+ "string",
925
+ "string",
926
+ "number",
927
+ "string"
928
+ ], [
929
+ office,
930
+ document,
931
+ `file://${output}`,
932
+ operation.format,
933
+ filterOptions,
934
+ Number(operation.recalculate),
935
+ operation.sheet ?? ""
936
+ ])) throw engineError(module, office);
937
+ if (!module.FS.analyzePath(output).exists) throw new ConversionError("invalid-output", "LibreOffice did not create its output.");
938
+ const status = module.FS.stat(output);
939
+ if (!module.FS.isFile(status.mode)) throw new ConversionError("invalid-output", "Generated output is not a regular file.");
940
+ if (status.size > options.maxOutputBytes) throw new ConversionError("output-too-large", "Generated output exceeds its output byte limit.");
941
+ const result = module.FS.readFile(output);
942
+ validateOutput(result, operation.format);
943
+ return {
944
+ output: result,
945
+ missingFonts: session.missingFonts
946
+ };
947
+ });
948
+ }
949
+ /** Split a region on its output-pixel grid, bounding the plan before allocating it. */
950
+ function splitRasterRectangle(rectangle, scale, limits) {
951
+ const { x, y, width, height } = rectangle;
952
+ const { maxPixels, maxDimension, maxTiles } = limits;
953
+ if (![
954
+ x,
955
+ y,
956
+ width,
957
+ height,
958
+ scale
959
+ ].every(Number.isFinite) || x < 0 || y < 0 || width <= 0 || height <= 0 || scale <= 0 || !Number.isSafeInteger(maxPixels) || maxPixels < 1 || maxPixels > 16777216 || !Number.isSafeInteger(maxDimension) || maxDimension < 1 || maxDimension > 16777216 || !Number.isSafeInteger(maxTiles) || maxTiles < 0) throw new TypeError("Invalid raster splitting limits or rectangle.");
960
+ const pixelWidth = Math.ceil(width * scale - 1e-9), pixelHeight = Math.ceil(height * scale - 1e-9);
961
+ if (![pixelWidth, pixelHeight].every((value) => Number.isSafeInteger(value) && value > 0)) throw new RangeError("Raster dimensions exceed the coordinate range.");
962
+ let tileWidth = Math.min(pixelWidth, maxDimension), tileHeight = Math.min(pixelHeight, maxDimension);
963
+ if (tileWidth * tileHeight > maxPixels) {
964
+ const side = Math.floor(Math.sqrt(maxPixels));
965
+ if (tileWidth <= side) tileHeight = Math.floor(maxPixels / tileWidth);
966
+ else if (tileHeight <= side) tileWidth = Math.floor(maxPixels / tileHeight);
967
+ else {
968
+ tileWidth = side;
969
+ tileHeight = Math.min(tileHeight, Math.floor(maxPixels / tileWidth));
970
+ }
971
+ }
972
+ const columns = Math.ceil(pixelWidth / tileWidth), rows = Math.ceil(pixelHeight / tileHeight);
973
+ if (columns * rows > maxTiles) throw new RangeError("Raster batch exceeds maxPages after worksheet splitting.");
974
+ const result = [];
975
+ for (let row = 0; row < rows; row++) for (let column = 0; column < columns; column++) {
976
+ const left = column * tileWidth / scale, top = row * tileHeight / scale;
977
+ result.push({
978
+ x: x + left,
979
+ y: y + top,
980
+ width: Math.min(tileWidth / scale, width - left),
981
+ height: Math.min(tileHeight / scale, height - top)
982
+ });
983
+ }
984
+ return result;
985
+ }
986
+ /** Writer's zero-area parity placeholders have no visible page. Offsets stay in twips. */
987
+ function writerPages(rectangles) {
988
+ const pages = rectangles.split(";").filter((value) => value.trim()).flatMap((rectangle) => {
989
+ const fields = rectangle.split(",").map((value) => Number(value.trim()));
990
+ const [x, y, width, height] = fields;
991
+ if (fields.length !== 4 || x === void 0 || y === void 0 || width === void 0 || height === void 0 || fields.some((value) => !Number.isSafeInteger(value) || value < 0 || value > 2147483647) || width === 0 !== (height === 0) || x + width > 2147483647 || y + height > 2147483647) throw new Error("LibreOffice returned invalid page rectangles.");
992
+ return width === 0 ? [] : [{
993
+ x,
994
+ y,
995
+ width: width / 15,
996
+ height: height / 15,
997
+ part: -1
998
+ }];
999
+ });
1000
+ if (pages.length === 0) throw new Error("LibreOffice returned no document pages.");
1001
+ return pages;
1002
+ }
1003
+ /** Validate coordinates before allocation or wasm32 integer conversion. */
1004
+ function tileDimensions(request, pages) {
1005
+ const page = pages[request.pageIndex];
1006
+ if (!Number.isSafeInteger(request.pageIndex) || !page || ![
1007
+ request.x,
1008
+ request.y,
1009
+ request.width,
1010
+ request.height,
1011
+ request.scale
1012
+ ].every(Number.isFinite) || request.x < 0 || request.y < 0 || request.width <= 0 || request.height <= 0 || request.scale <= 0 || request.x + request.width > page.width + .001 || request.y + request.height > page.height + .001) throw new Error("Tile rectangle lies outside its page.");
1013
+ const width = Math.ceil(request.width * request.scale - 1e-9);
1014
+ const height = Math.ceil(request.height * request.scale - 1e-9);
1015
+ if (width <= 0 || height <= 0 || !Number.isSafeInteger(width * height) || width * height > 16777216) throw new Error("Tile exceeds the 16 megapixel allocation limit.");
1016
+ const twips = [
1017
+ page.x + Math.round(request.x * 15),
1018
+ page.y + Math.round(request.y * 15),
1019
+ Math.round(request.width * 15),
1020
+ Math.round(request.height * 15)
1021
+ ];
1022
+ if (twips.some((value) => !Number.isSafeInteger(value) || value < 0 || value > 2147483647) || twips[0] + twips[2] > 2147483647 || twips[1] + twips[3] > 2147483647) throw new Error("Tile coordinates exceed the wasm32 range.");
1023
+ return {
1024
+ page,
1025
+ width,
1026
+ height
1027
+ };
1028
+ }
1029
+ /** Cairo/LO channels are premultiplied; PNG and ImageData require straight RGBA. */
1030
+ function rgbaPixels(source, tileMode) {
1031
+ if (tileMode !== 0 && tileMode !== 1 || source.length % 4 !== 0) throw new Error("LibreOffice returned an unsupported tile pixel format.");
1032
+ const result = new Uint8ClampedArray(source.length);
1033
+ for (let index = 0; index < source.length; index += 4) {
1034
+ const alpha = source[index + 3];
1035
+ const multiplier = alpha === 0 ? 0 : 255 / alpha;
1036
+ result[index] = source[index + (tileMode === 1 ? 2 : 0)] * multiplier;
1037
+ result[index + 1] = source[index + 1] * multiplier;
1038
+ result[index + 2] = source[index + (tileMode === 1 ? 0 : 2)] * multiplier;
1039
+ result[index + 3] = alpha;
1040
+ }
1041
+ return result;
1042
+ }
1043
+ //#endregion
1044
+ //#region lib/types/engine-rendering.js
1045
+ /** Shared bounded raster allocations for browser and Node engine owners. */
1046
+ function numericCall(module, name, args) {
1047
+ return module.ccall(name, "number", args.map(() => "number"), args);
1048
+ }
1049
+ /** Copy/free one engine-owned UTF-8 return value. */
1050
+ function engineString(module, name, types, args, failure) {
1051
+ const pointer = module.ccall(name, "number", types, args);
1052
+ if (!pointer) throw failure();
1053
+ try {
1054
+ return module.UTF8ToString(pointer);
1055
+ } finally {
1056
+ numericCall(module, "free", [pointer]);
1057
+ }
1058
+ }
1059
+ /** Paint into a temporary allocation; copy pixels before free or another engine call. */
1060
+ function renderRegion(module, document, request, pages, failure, pdf = false) {
1061
+ const call = (name, args) => numericCall(module, name, args);
1062
+ const { page, width, height } = tileDimensions(request, pages);
1063
+ const size = width * height * 4;
1064
+ const pointer = call("malloc", [size]);
1065
+ if (!pointer) throw failure();
1066
+ try {
1067
+ new Uint8Array(module.HEAPU32.buffer, pointer, size).fill(0);
1068
+ const position = [
1069
+ page.x + Math.round(request.x * 15),
1070
+ page.y + Math.round(request.y * 15),
1071
+ Math.max(1, Math.round(request.width * 15)),
1072
+ Math.max(1, Math.round(request.height * 15))
1073
+ ];
1074
+ if (!call(pdf ? "dsh_pdf_paint" : "dsh_lok_document_paint", [
1075
+ document,
1076
+ pointer,
1077
+ page.part,
1078
+ width,
1079
+ height,
1080
+ ...position
1081
+ ])) throw failure();
1082
+ const source = new Uint8Array(module.HEAPU32.buffer, pointer, size);
1083
+ return {
1084
+ width,
1085
+ height,
1086
+ rgba: pdf ? new Uint8ClampedArray(source) : rgbaPixels(source, call("dsh_lok_document_tile_mode", [document]))
1087
+ };
1088
+ } finally {
1089
+ call("free", [pointer]);
1090
+ }
1091
+ }
1092
+ /** PDF page dimensions use the same twips ABI, with an immutable PDF page index as part. */
1093
+ function pdfPages(module, pdf, failure) {
1094
+ const count = numericCall(module, "dsh_pdf_page_count", [pdf]);
1095
+ if (!Number.isSafeInteger(count) || count < 1 || count > 1e5) throw failure();
1096
+ const pointer = numericCall(module, "malloc", [8]);
1097
+ if (!pointer) throw failure();
1098
+ try {
1099
+ return Array.from({ length: count }, (_, part) => {
1100
+ if (!numericCall(module, "dsh_pdf_page_size", [
1101
+ pdf,
1102
+ part,
1103
+ pointer,
1104
+ pointer + 4
1105
+ ])) throw failure();
1106
+ const width = module.HEAPU32[pointer / 4];
1107
+ const height = module.HEAPU32[pointer / 4 + 1];
1108
+ if (width < 1 || height < 1 || width > 2147483647 || height > 2147483647) throw failure();
1109
+ return {
1110
+ part,
1111
+ x: 0,
1112
+ y: 0,
1113
+ width: width / 15,
1114
+ height: height / 15
1115
+ };
1116
+ });
1117
+ } finally {
1118
+ numericCall(module, "free", [pointer]);
1119
+ }
1120
+ }
1121
+ //#endregion
1122
+ //#region lib/types/sheet-geometry.js
1123
+ const MAX_COLUMN = 16383;
1124
+ const MAX_ROW = 1048575;
1125
+ function column(index) {
1126
+ let name = "";
1127
+ for (let value = index + 1; value > 0; value = Math.floor((value - 1) / 26)) name = String.fromCharCode(65 + (value - 1) % 26) + name;
1128
+ return name;
1129
+ }
1130
+ function rangeName(range) {
1131
+ return `${column(range.firstColumn)}${range.firstRow + 1}:${column(range.lastColumn)}${range.lastRow + 1}`;
1132
+ }
1133
+ function parseCellRange(value) {
1134
+ const match = /^\$?([A-Z]{1,3})\$?([1-9]\d{0,6})(?::\$?([A-Z]{1,3})\$?([1-9]\d{0,6}))?$/i.exec(value);
1135
+ if (!match) throw new TypeError("range must be an A1 cell or rectangle without a sheet prefix.");
1136
+ const col = (name) => [...name.toUpperCase()].reduce((sum, c) => sum * 26 + c.charCodeAt(0) - 64, 0) - 1;
1137
+ const firstColumn = col(match[1]);
1138
+ const firstRow = Number(match[2]) - 1;
1139
+ const lastColumn = col(match[3] ?? match[1]);
1140
+ const lastRow = Number(match[4] ?? match[2]) - 1;
1141
+ if (lastColumn < firstColumn || lastRow < firstRow || lastColumn > MAX_COLUMN || lastRow > MAX_ROW) throw new TypeError("range exceeds Calc worksheet bounds or has reversed endpoints.");
1142
+ return {
1143
+ firstColumn,
1144
+ firstRow,
1145
+ lastColumn,
1146
+ lastRow
1147
+ };
1148
+ }
1149
+ function sheetPartInfo(value) {
1150
+ const info = JSON.parse(value);
1151
+ if (!info || typeof info.name !== "string" || ![0, 1].includes(info.visible) || ![0, 1].includes(info.rtllayout) || !Number.isInteger(info.lastcolumn) || !Number.isInteger(info.lastrow) || info.lastcolumn < 0 || info.lastrow < 0 || info.lastcolumn > MAX_COLUMN || info.lastrow > MAX_ROW) throw new Error("LibreOffice returned invalid worksheet data-area metadata.");
1152
+ return info;
1153
+ }
1154
+ /** Formatting-only cells and standalone drawings do not enlarge LibreOffice's data area. */
1155
+ function dataArea(info) {
1156
+ return {
1157
+ firstColumn: 0,
1158
+ firstRow: 0,
1159
+ lastColumn: info.lastcolumn,
1160
+ lastRow: info.lastrow
1161
+ };
1162
+ }
1163
+ function spans(encoded, flags, maximum) {
1164
+ if (typeof encoded !== "string" || encoded.length > 33554432) throw new Error("Invalid worksheet geometry span encoding.");
1165
+ const tokens = encoded.trim().split(/\s+/);
1166
+ let previous = -1;
1167
+ let flag = 0;
1168
+ const result = tokens.map((token, i) => {
1169
+ const fields = token.split(":");
1170
+ let value;
1171
+ let end;
1172
+ if (flags && i > 0) {
1173
+ value = flag = 1 - flag;
1174
+ end = Number(fields[0]);
1175
+ if (fields.length !== 1) throw new Error("Invalid worksheet flag span.");
1176
+ } else {
1177
+ value = Number(fields[0]);
1178
+ end = Number(fields[1]);
1179
+ flag = value;
1180
+ if (fields.length !== 2) throw new Error("Invalid worksheet size span.");
1181
+ }
1182
+ if (!Number.isSafeInteger(value) || value < 0 || (flags ? value > 1 : value > 65535) || !Number.isSafeInteger(end) || end <= previous || end > maximum) throw new Error("Invalid worksheet geometry span.");
1183
+ previous = end;
1184
+ return {
1185
+ end,
1186
+ value
1187
+ };
1188
+ });
1189
+ if (previous !== maximum) throw new Error("Worksheet geometry does not cover the complete dimension.");
1190
+ return result;
1191
+ }
1192
+ function dimension(data, first, last, maximum, scale) {
1193
+ const sizes = spans(data?.sizes, false, maximum);
1194
+ const hidden = spans(data?.hidden, true, maximum);
1195
+ const filtered = spans(data?.filtered, true, maximum);
1196
+ let position = 0, start = 0, index = 0, si = 0, hi = 0, fi = 0;
1197
+ while (index <= last) {
1198
+ const size = sizes[si], hide = hidden[hi], filter = filtered[fi];
1199
+ const end = Math.min(size.end, hide.end, filter.end, last, index < first ? first - 1 : last);
1200
+ const pixels = hide.value || filter.value || size.value === 0 ? 0 : Math.max(1, Math.floor(size.value * scale / 15));
1201
+ if (index === first) start = position;
1202
+ position += (end - index + 1) * pixels;
1203
+ index = end + 1;
1204
+ if (index > size.end) si++;
1205
+ if (index > hide.end) hi++;
1206
+ if (index > filter.end) fi++;
1207
+ }
1208
+ return [start / scale, (position - start) / scale];
1209
+ }
1210
+ /** Logical columns advance from A; LOK itself mirrors RTL sheet painting. No manual x inversion. */
1211
+ function sheetRangeRectangle(geometry, range, scale) {
1212
+ if (!Number.isFinite(scale) || scale <= 0 || scale > 16) throw new TypeError("Invalid worksheet raster scale.");
1213
+ const [x, width] = dimension(geometry.columns, range.firstColumn, range.lastColumn, MAX_COLUMN, scale);
1214
+ const [y, height] = dimension(geometry.rows, range.firstRow, range.lastRow, MAX_ROW, scale);
1215
+ if (width <= 0 || height <= 0) throw new Error("The selected worksheet range is entirely hidden or filtered.");
1216
+ if ([
1217
+ x,
1218
+ y,
1219
+ width,
1220
+ height,
1221
+ x + width,
1222
+ y + height
1223
+ ].some((value) => !Number.isFinite(value) || value * 15 > 2147483647)) throw new Error("The selected worksheet range exceeds the supported coordinate range.");
1224
+ return {
1225
+ x,
1226
+ y,
1227
+ width,
1228
+ height
1229
+ };
1230
+ }
1231
+ //#endregion
1232
+ //#region lib/types/image-operations.js
1233
+ function selectedPages(pages, count, limit) {
1234
+ if (!Number.isSafeInteger(count) || count < 1) throw new ConversionError("invalid-document", "The document contains no renderable pages.");
1235
+ const result = pages === void 0 || pages === "all" ? Array.from({ length: Math.min(count, limit + 1) }, (_, i) => i + 1) : [...pages];
1236
+ if (result.length > limit) throw new ConversionError("output-too-large", "Selected page count exceeds maxPages; select pages or raise the limit.");
1237
+ if (result.some((page) => page > count)) throw new TypeError(`Selected page lies outside the ${count}-page document.`);
1238
+ return result;
1239
+ }
1240
+ //#endregion
1241
+ //#region lib/types/png.js
1242
+ /** Portable PNG encoding over straight RGBA; browser and Node need no native image dependency. */
1243
+ const crcTable = Uint32Array.from({ length: 256 }, (_, value) => {
1244
+ for (let bit = 0; bit < 8; bit++) value = value & 1 ? 3988292384 ^ value >>> 1 : value >>> 1;
1245
+ return value >>> 0;
1246
+ });
1247
+ function chunk(type, bytes) {
1248
+ const output = new Uint8Array(bytes.length + 12);
1249
+ const view = new DataView(output.buffer);
1250
+ view.setUint32(0, bytes.length);
1251
+ output.set(new TextEncoder().encode(type), 4);
1252
+ output.set(bytes, 8);
1253
+ let crc = 4294967295;
1254
+ for (let i = 4; i < output.length - 4; i++) crc = crcTable[(crc ^ output[i]) & 255] ^ crc >>> 8;
1255
+ view.setUint32(output.length - 4, (crc ^ 4294967295) >>> 0);
1256
+ return output;
1257
+ }
1258
+ function encodePng(width, height, rgba) {
1259
+ if (!Number.isSafeInteger(width) || !Number.isSafeInteger(height) || width < 1 || height < 1 || width * height > 16777216 || rgba.byteLength !== width * height * 4) throw new TypeError("Invalid PNG raster dimensions.");
1260
+ const header = /* @__PURE__ */ new Uint8Array(13);
1261
+ const view = new DataView(header.buffer);
1262
+ view.setUint32(0, width);
1263
+ view.setUint32(4, height);
1264
+ header[8] = 8;
1265
+ header[9] = 6;
1266
+ const scanlines = new Uint8Array(height * (width * 4 + 1));
1267
+ for (let y = 0; y < height; y++) {
1268
+ const source = y * width * 4;
1269
+ const target = y * (width * 4 + 1);
1270
+ scanlines[target] = 1;
1271
+ for (let x = 0; x < width * 4; x++) scanlines[target + 1 + x] = rgba[source + x] - (x < 4 ? 0 : rgba[source + x - 4]);
1272
+ }
1273
+ const chunks = [
1274
+ new Uint8Array([
1275
+ 137,
1276
+ 80,
1277
+ 78,
1278
+ 71,
1279
+ 13,
1280
+ 10,
1281
+ 26,
1282
+ 10
1283
+ ]),
1284
+ chunk("IHDR", header),
1285
+ chunk("IDAT", zlibSync(scanlines, { level: 6 })),
1286
+ chunk("IEND", /* @__PURE__ */ new Uint8Array())
1287
+ ];
1288
+ const result = new Uint8Array(chunks.reduce((sum, value) => sum + value.length, 0));
1289
+ let offset = 0;
1290
+ for (const value of chunks) {
1291
+ result.set(value, offset);
1292
+ offset += value.length;
1293
+ }
1294
+ return result;
1295
+ }
1296
+ //#endregion
1297
+ //#region lib/types/image-renderer.js
1298
+ /** One saved-file model and one bounded direct PNG batch; no Office-to-PDF intermediate. */
1299
+ async function regions(session, request) {
1300
+ const { module, document, office, pdf } = session;
1301
+ const call = (name, args) => numericCall(module, name, args);
1302
+ const failure = () => engineError(module, office);
1303
+ const text = (name, args) => engineString(module, name, args.map(() => "number"), args, failure);
1304
+ const values = (command) => engineString(module, "dsh_lok_document_command_values", ["number", "string"], [document, command], failure);
1305
+ const select = (pages) => ({
1306
+ count: pages.length,
1307
+ regions: selectedPages(request.pages, pages.length, request.maxPages).map((number) => {
1308
+ const page = pages[number - 1];
1309
+ return {
1310
+ page,
1311
+ number,
1312
+ rectangle: {
1313
+ x: 0,
1314
+ y: 0,
1315
+ width: page.width,
1316
+ height: page.height
1317
+ }
1318
+ };
1319
+ })
1320
+ });
1321
+ if (pdf) return select(pdfPages(module, document, failure));
1322
+ if (!call("dsh_lok_document_initialize_rendering", [document]) || !call("dsh_lok_document_listen", [document])) throw failure();
1323
+ await session.idle();
1324
+ const type = call("dsh_lok_document_type", [document]);
1325
+ if (type !== ([
1326
+ "xls",
1327
+ "xlsx",
1328
+ "ods"
1329
+ ].includes(request.extension) ? 1 : [
1330
+ "ppt",
1331
+ "pptx",
1332
+ "odp"
1333
+ ].includes(request.extension) ? 2 : 0)) throw new ConversionError("invalid-document", "LibreOffice imported the input as an unexpected document type.");
1334
+ if (type === 0) return select(writerPages(text("dsh_lok_document_page_rectangles", [document])));
1335
+ const parts = call("dsh_lok_document_parts", [document]);
1336
+ if (!Number.isSafeInteger(parts) || parts < 1 || parts > 1e5) throw new ConversionError("invalid-document", "Invalid document part count.");
1337
+ if (type === 2) {
1338
+ const sizes = JSON.parse(values(".uno:AllPageSize"));
1339
+ if (!Array.isArray(sizes.parts) || sizes.parts.length !== parts) throw new ConversionError("invalid-document", "Impress returned inconsistent slide dimensions.");
1340
+ return select(sizes.parts.map(({ width, height }, part) => {
1341
+ if (!Number.isSafeInteger(width) || !Number.isSafeInteger(height) || width < 1 || height < 1 || width > 2147483647 || height > 2147483647) throw new ConversionError("invalid-document", "Impress returned invalid slide dimensions.");
1342
+ return {
1343
+ part,
1344
+ x: 0,
1345
+ y: 0,
1346
+ width: width / 15,
1347
+ height: height / 15
1348
+ };
1349
+ }));
1350
+ }
1351
+ const sheets = Array.from({ length: parts }, (_, part) => ({
1352
+ part,
1353
+ info: sheetPartInfo(text("dsh_lok_document_part_info", [document, part]))
1354
+ }));
1355
+ const count = sheets.filter(({ info }) => info.visible).length;
1356
+ const selected = request.sheet === void 0 ? sheets.filter(({ info }) => info.visible) : sheets.filter(({ info }) => info.name === request.sheet);
1357
+ if (!selected.length) throw new ConversionError("invalid-document", "The exact worksheet name does not exist or the workbook has no visible sheets.");
1358
+ if (selected.length > request.maxPages) throw new ConversionError("output-too-large", "Selected worksheet count exceeds maxPages; select a sheet or raise the limit.");
1359
+ const result = [];
1360
+ const scale = request.dpi / 96;
1361
+ for (const { part, info } of selected) {
1362
+ if (!call("dsh_lok_document_part", [document, part])) throw failure();
1363
+ await session.idle();
1364
+ const range = request.range === void 0 ? dataArea(info) : parseCellRange(request.range);
1365
+ const rectangle = sheetRangeRectangle(JSON.parse(values(".uno:SheetGeometryData")), range, scale);
1366
+ const page = {
1367
+ x: 0,
1368
+ y: 0,
1369
+ width: rectangle.x + rectangle.width,
1370
+ height: rectangle.y + rectangle.height,
1371
+ part
1372
+ };
1373
+ result.push({
1374
+ page,
1375
+ rectangle,
1376
+ sheet: info.name,
1377
+ range: rangeName(range),
1378
+ rtl: Boolean(info.rtllayout)
1379
+ });
1380
+ }
1381
+ return {
1382
+ count,
1383
+ regions: result
1384
+ };
1385
+ }
1386
+ async function renderImagesWithWasm(request) {
1387
+ return withWasmSession(request, async (session) => {
1388
+ const { operation, options } = request;
1389
+ const { count, regions: sourceRegions } = await regions(session, operation);
1390
+ const scale = operation.dpi / 96;
1391
+ const selected = [];
1392
+ for (const region of sourceRegions) {
1393
+ if (region.sheet === void 0) {
1394
+ selected.push(region);
1395
+ continue;
1396
+ }
1397
+ let rectangles;
1398
+ try {
1399
+ rectangles = splitRasterRectangle(region.rectangle, scale, {
1400
+ maxPixels: operation.maxPixels,
1401
+ maxDimension: operation.maxDimension,
1402
+ maxTiles: operation.maxPages - selected.length
1403
+ });
1404
+ } catch (cause) {
1405
+ throw new ConversionError("output-too-large", String(cause), { cause });
1406
+ }
1407
+ selected.push(...rectangles.map((rectangle) => ({
1408
+ ...region,
1409
+ rectangle
1410
+ })));
1411
+ }
1412
+ for (const { page, rectangle } of selected) {
1413
+ const pixelWidth = Math.ceil(rectangle.width * scale - 1e-9), pixelHeight = Math.ceil(rectangle.height * scale - 1e-9);
1414
+ if (pixelWidth > operation.maxDimension || pixelHeight > operation.maxDimension || pixelWidth * pixelHeight > operation.maxPixels) throw new ConversionError("output-too-large", "Selected page exceeds maxPixels or maxDimension; reduce DPI or raise the image limits.");
1415
+ tileDimensions({
1416
+ pageIndex: 0,
1417
+ ...rectangle,
1418
+ scale
1419
+ }, [page]);
1420
+ }
1421
+ const images = [];
1422
+ let total = 0;
1423
+ for (const region of selected) {
1424
+ if (region.sheet !== void 0) {
1425
+ const call = (name, args) => numericCall(session.module, name, args);
1426
+ if (!call("dsh_lok_document_part", [session.document, region.page.part])) throw engineError(session.module, session.office);
1427
+ const { x, y, width, height } = region.rectangle;
1428
+ const command = `.uno:ViewRowColumnHeaders?x=${Math.round(x * 15)}&y=${Math.round(y * 15)}&width=${Math.round(width * 15)}&height=${Math.round(height * 15)}`;
1429
+ if (!call("dsh_lok_document_viewport", [
1430
+ session.document,
1431
+ Math.round(scale * 1440),
1432
+ 21600,
1433
+ Math.round(x * 15),
1434
+ Math.round(y * 15),
1435
+ Math.round(width * 15),
1436
+ Math.round(height * 15)
1437
+ ])) throw engineError(session.module, session.office);
1438
+ engineString(session.module, "dsh_lok_document_command_values", ["number", "string"], [session.document, command], () => engineError(session.module, session.office));
1439
+ await session.idle();
1440
+ }
1441
+ const tile = renderRegion(session.module, session.document, {
1442
+ pageIndex: 0,
1443
+ ...region.rectangle,
1444
+ scale
1445
+ }, [region.page], () => engineError(session.module, session.office), session.pdf);
1446
+ const png = encodePng(tile.width, tile.height, tile.rgba);
1447
+ total += png.length;
1448
+ if (total > options.maxOutputBytes) throw new ConversionError("output-too-large", "PNG batch exceeds maxOutputBytes.");
1449
+ const index = images.length + 1;
1450
+ const path = join(operation.outputDir, `page-${String(index).padStart(4, "0")}.png`);
1451
+ writeFileSync(path, png, {
1452
+ flag: "wx",
1453
+ mode: 384
1454
+ });
1455
+ images.push({
1456
+ index,
1457
+ ...region.number === void 0 ? {} : { page: region.number },
1458
+ ...region.sheet === void 0 ? {} : {
1459
+ sheet: region.sheet,
1460
+ range: region.range,
1461
+ rtl: region.rtl
1462
+ },
1463
+ path,
1464
+ width: tile.width,
1465
+ height: tile.height,
1466
+ rectangle: region.rectangle,
1467
+ byteLength: png.length
1468
+ });
1469
+ }
1470
+ return {
1471
+ schemaVersion: 1,
1472
+ backend: "wasm",
1473
+ rasterEngine: session.pdf ? "pdfium" : "libreoffice",
1474
+ source: "saved",
1475
+ inputPath: operation.inputPath,
1476
+ sourceSha256: createHash("sha256").update(request.bytes).digest("hex"),
1477
+ dpi: operation.dpi,
1478
+ pageCount: count,
1479
+ images,
1480
+ missingFonts: session.missingFonts
1481
+ };
1482
+ });
1483
+ }
732
1484
  //#endregion
733
1485
  //#region lib/types/worker.js
734
1486
  /** Cancellable CPU work and WASM conversion run outside the Node event loop. */
@@ -743,9 +1495,14 @@ function requireParentPort(port) {
743
1495
  }
744
1496
  const port = requireParentPort(parentPort);
745
1497
  try {
746
- const { inputPath, extension, options, engine, scratch, fontFaces } = workerData;
1498
+ const { inputPath, extension, operation, options, engine, scratch, fontFaces } = workerData;
747
1499
  const bytes = readFileSync(inputPath);
748
- const document = inspectDocument(bytes, extension, options);
1500
+ const images = "kind" in operation && operation.kind === "images";
1501
+ if (images && extension === "pdf" && new TextDecoder().decode(bytes.subarray(0, 5)) !== "%PDF-") throw new ConversionError("invalid-document", "Input does not contain a PDF header.");
1502
+ const document = images && extension === "pdf" ? {
1503
+ families: /* @__PURE__ */ new Map(),
1504
+ codePoints: []
1505
+ } : inspectDocument(bytes, extension, options);
749
1506
  const faces = fontFaces ?? indexSystemFonts({
750
1507
  directories: options.fontDirectories,
751
1508
  maxFiles: options.maxFontFiles,
@@ -755,20 +1512,38 @@ try {
755
1512
  kind: "fonts",
756
1513
  faces
757
1514
  });
1515
+ if (images && engine.backend !== "wasm") throw new ConversionError("unavailable", "Direct image rendering requires the installed WASM engine.");
758
1516
  if (engine.backend === "wasm") {
759
- if (faces.length === 0) throw new ConversionError("unavailable", "No usable fonts were found. Install fonts or configure fontDirectories before converting documents.");
760
- const result = await convertWithWasm({
761
- engine,
762
- bytes,
763
- extension,
764
- options,
765
- document,
766
- faces
767
- });
768
- port.postMessage({
769
- ok: true,
770
- ...result
771
- }, [result.pdf.buffer]);
1517
+ if (faces.length === 0 && extension !== "pdf") throw new ConversionError("unavailable", "No usable fonts were found. Install fonts or configure fontDirectories before converting documents.");
1518
+ if (images) {
1519
+ const result = await renderImagesWithWasm({
1520
+ engine,
1521
+ bytes,
1522
+ extension,
1523
+ operation,
1524
+ options,
1525
+ document,
1526
+ faces
1527
+ });
1528
+ port.postMessage({
1529
+ ok: true,
1530
+ images: result
1531
+ });
1532
+ } else {
1533
+ const result = await convertWithWasm({
1534
+ engine,
1535
+ bytes,
1536
+ extension,
1537
+ operation,
1538
+ options,
1539
+ document,
1540
+ faces
1541
+ });
1542
+ port.postMessage({
1543
+ ok: true,
1544
+ ...result
1545
+ }, [result.output.buffer]);
1546
+ }
772
1547
  } else {
773
1548
  const directory = join(scratch, "fonts");
774
1549
  mkdirSync(directory, { mode: 448 });