@deepseek-ai/libreoffice-kit 0.1.5 → 0.2.0-alpha6

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 (77) hide show
  1. package/NOTICE +4 -0
  2. package/README.md +44 -8
  3. package/README.zh.md +45 -9
  4. package/frame-forwarding/CMakeLists.txt +40 -0
  5. package/frame-forwarding/LICENSE +21 -0
  6. package/frame-forwarding/README.md +83 -0
  7. package/frame-forwarding/README.zh.md +83 -0
  8. package/frame-forwarding/include/dsh_frame_forwarding.h +101 -0
  9. package/frame-forwarding/include/dsh_frame_forwarding_engine.h +66 -0
  10. package/frame-forwarding/include/dsh_frame_forwarding_node.h +27 -0
  11. package/frame-forwarding/include/dsh_webgpu.h +52 -0
  12. package/frame-forwarding/index.d.ts +145 -0
  13. package/frame-forwarding/index.mjs +71 -0
  14. package/frame-forwarding/lib/browser/display.d.ts +46 -0
  15. package/frame-forwarding/lib/browser/display.js +128 -0
  16. package/frame-forwarding/lib/browser/index.d.ts +4 -0
  17. package/frame-forwarding/lib/browser/index.js +3 -0
  18. package/frame-forwarding/lib/browser/painters.d.ts +9 -0
  19. package/frame-forwarding/lib/browser/painters.js +180 -0
  20. package/frame-forwarding/lib/browser/types.d.ts +51 -0
  21. package/frame-forwarding/lib/browser/types.js +1 -0
  22. package/frame-forwarding/lib/electron/adapter.d.ts +9 -0
  23. package/frame-forwarding/lib/electron/adapter.js +118 -0
  24. package/frame-forwarding/lib/electron/index.d.ts +3 -0
  25. package/frame-forwarding/lib/electron/index.js +3 -0
  26. package/frame-forwarding/lib/electron/preload.d.ts +13 -0
  27. package/frame-forwarding/lib/electron/preload.js +47 -0
  28. package/frame-forwarding/lib/electron/transfer.d.ts +15 -0
  29. package/frame-forwarding/lib/electron/transfer.js +36 -0
  30. package/frame-forwarding/prebuilds/darwin-arm64/frame-forwarding.node +0 -0
  31. package/frame-forwarding/prebuilds/darwin-arm64/libdsh_frame_forwarding_sdk.a +0 -0
  32. package/frame-forwarding/prebuilds/darwin-arm64/manifest.json +34 -0
  33. package/frame-forwarding/prebuilds/darwin-x64/frame-forwarding.node +0 -0
  34. package/frame-forwarding/prebuilds/darwin-x64/libdsh_frame_forwarding_sdk.a +0 -0
  35. package/frame-forwarding/prebuilds/darwin-x64/manifest.json +34 -0
  36. package/frame-forwarding/prebuilds/win32-arm64/dsh_frame_forwarding_sdk.lib +0 -0
  37. package/frame-forwarding/prebuilds/win32-arm64/frame-forwarding.node +0 -0
  38. package/frame-forwarding/prebuilds/win32-arm64/manifest.json +34 -0
  39. package/frame-forwarding/prebuilds/win32-x64/dsh_frame_forwarding_sdk.lib +0 -0
  40. package/frame-forwarding/prebuilds/win32-x64/frame-forwarding.node +0 -0
  41. package/frame-forwarding/prebuilds/win32-x64/manifest.json +34 -0
  42. package/frame-forwarding/receipt.json +23 -0
  43. package/frame-forwarding/scripts/build-webgpu.mjs +197 -0
  44. package/frame-forwarding/scripts/build.mjs +43 -0
  45. package/frame-forwarding/scripts/metadata.mjs +47 -0
  46. package/frame-forwarding/scripts/source-identity.mjs +15 -0
  47. package/frame-forwarding/scripts/verify-prebuilds.mjs +14 -0
  48. package/frame-forwarding/sdk.json +45 -0
  49. package/frame-forwarding/src/node-producer.cc +595 -0
  50. package/frame-forwarding/src/producer-internal.h +8 -0
  51. package/frame-forwarding/src/producer.cc +306 -0
  52. package/frame-forwarding/src/receiver.cc +1050 -0
  53. package/frame-forwarding/src/relay-transport.inc +293 -0
  54. package/frame-forwarding/src/transport.cc +405 -0
  55. package/frame-forwarding/src/transport.h +80 -0
  56. package/frame-forwarding/src/webgpu.cc +214 -0
  57. package/frame-forwarding/src/win-delay-load.LICENSE +24 -0
  58. package/frame-forwarding/src/win-delay-load.cc +43 -0
  59. package/frame-forwarding/verify.d.mts +4 -0
  60. package/frame-forwarding/verify.mjs +101 -0
  61. package/frame-forwarding/webgpu-dependencies.json +51 -0
  62. package/lib/cli.js +109 -46
  63. package/lib/editor.js +2061 -0
  64. package/lib/index.js +109 -46
  65. package/lib/types/editor-protocol.d.ts +29 -0
  66. package/lib/types/editor-transport.d.ts +36 -0
  67. package/lib/types/editor-types.d.ts +119 -0
  68. package/lib/types/editor.d.ts +105 -0
  69. package/lib/types/engine.d.ts +4 -2
  70. package/lib/types/fonts.d.ts +4 -8
  71. package/lib/types/native-image-renderer.d.ts +0 -1
  72. package/lib/types/native-process.d.ts +1 -0
  73. package/lib/types/native.d.ts +30 -2
  74. package/lib/types/runtime.d.ts +2 -0
  75. package/lib/types/worker.d.ts +2 -2
  76. package/lib/worker.js +38 -31
  77. package/package.json +94 -9
package/lib/editor.js ADDED
@@ -0,0 +1,2061 @@
1
+ import { createRequire } from "node:module";
2
+ import { copyFile, mkdir, mkdtemp, readFile, rm, stat, symlink, unlink, writeFile } from "node:fs/promises";
3
+ import { closeSync, constants, createWriteStream, fstatSync, lstatSync, openSync, readSync, readdirSync, writeFileSync } from "node:fs";
4
+ import { homedir, tmpdir } from "node:os";
5
+ import { basename, dirname, extname, isAbsolute, join, posix, relative, resolve, sep, win32 } from "node:path";
6
+ import { pathToFileURL } from "node:url";
7
+ import { randomUUID } from "node:crypto";
8
+ import { create } from "fontkit";
9
+ import { Worker } from "node:worker_threads";
10
+ import { strFromU8, unzipSync } from "fflate";
11
+ import { SaxesParser } from "saxes";
12
+ import { spawn } from "node:child_process";
13
+ import { EventEmitter } from "node:events";
14
+ import { Readable } from "node:stream";
15
+ import { finished } from "node:stream/promises";
16
+ //#region lib/types/font-file-identity.js
17
+ /** Preserve 64-bit device and inode values without JavaScript integer rounding. */
18
+ function fontFileIdentity(status) {
19
+ return {
20
+ dev: status.dev.toString(),
21
+ ino: status.ino.toString(),
22
+ size: Number(status.size),
23
+ mtimeMs: Number(status.mtimeNs) / 1e6,
24
+ ctimeMs: Number(status.ctimeNs) / 1e6
25
+ };
26
+ }
27
+ /** Compare a source descriptor's exact identity with its indexed font metadata. */
28
+ function matchesFontFile(status, expected) {
29
+ const current = fontFileIdentity(status);
30
+ return [
31
+ "dev",
32
+ "ino",
33
+ "size",
34
+ "mtimeMs",
35
+ "ctimeMs"
36
+ ].every((key) => current[key] === expected[key]);
37
+ }
38
+ //#endregion
39
+ //#region lib/types/fonts.js
40
+ /** Host font metadata snapshots and conversion-local glyph matching over original files. */
41
+ const VCL_WEIGHTS = [
42
+ 400,
43
+ 100,
44
+ 200,
45
+ 300,
46
+ 350,
47
+ 400,
48
+ 500,
49
+ 600,
50
+ 700,
51
+ 800,
52
+ 900
53
+ ];
54
+ const GENERIC_FAMILIES = /* @__PURE__ */ new Set([
55
+ "serif",
56
+ "sansserif",
57
+ "monospace",
58
+ "cursive",
59
+ "fantasy",
60
+ "systemui",
61
+ "symbol"
62
+ ]);
63
+ /**
64
+ * @param error - Thrown filesystem value.
65
+ * @returns whether it means the path is not a usable font source.
66
+ */
67
+ function absent(error) {
68
+ return error instanceof Error && "code" in error && [
69
+ "ENOENT",
70
+ "EACCES",
71
+ "EPERM",
72
+ "ENOTDIR"
73
+ ].includes(String(error.code));
74
+ }
75
+ /**
76
+ * Case- and separator-insensitive family key used to compare names across sources.
77
+ * @param value - Family, style, or postscript name as recorded by a document or font.
78
+ * @returns The normalized key.
79
+ */
80
+ function normalize(value) {
81
+ return value.normalize("NFKC").toLowerCase().replaceAll(/[\s_-]/g, "");
82
+ }
83
+ /**
84
+ * Order named substitutions and their generic text family without excluding unlisted fonts.
85
+ * @param requested - Original family names, in document order.
86
+ * @param groups - Ordered family groups shared with Fontconfig aliases.
87
+ * @param pitch - VCL pitch; one requests a monospaced fallback.
88
+ * @param symbols - Whether symbol alternatives precede the generic fallback.
89
+ * @returns distinct family names, with original requests first.
90
+ */
91
+ function fontFamilyPriority(requested, groups, pitch = 0, symbols = false) {
92
+ const original = requested.map(normalize);
93
+ const matched = groups.filter((group) => group.some((family) => original.includes(normalize(family))));
94
+ 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";
95
+ const families = [...requested, ...matched.flat()];
96
+ for (const kind of symbols ? ["symbol", generic] : [generic]) for (const group of groups) if (group.some((family) => normalize(family) === kind)) families.push(...group);
97
+ const priority = /* @__PURE__ */ new Map();
98
+ for (const family of families) {
99
+ const name = normalize(family);
100
+ if (!priority.has(name)) priority.set(name, family);
101
+ }
102
+ return [...priority.values()];
103
+ }
104
+ /**
105
+ * Discover system and per-user font roots using the selected platform's path separators.
106
+ * @param platform - Host operating system.
107
+ * @param home - Host user home used to locate per-user font directories.
108
+ * @param env - Host environment containing Windows and XDG directory overrides.
109
+ * @returns candidate directories; missing platform directories are ignored during indexing.
110
+ */
111
+ function systemFontDirectories(platform = process.platform, home = homedir(), env = process.env) {
112
+ if (platform === "win32") return [win32.join(env.SystemRoot ?? "C:\\Windows", "Fonts"), win32.join(env.LOCALAPPDATA ?? win32.join(home, "AppData", "Local"), "Microsoft", "Windows", "Fonts")];
113
+ if (platform === "darwin") return [
114
+ "/System/Library/Fonts",
115
+ "/Library/Fonts",
116
+ posix.join(home, "Library/Fonts"),
117
+ ...mobileAssetFontDirectories("/System/Library/AssetsV2")
118
+ ];
119
+ const shared = (env.XDG_DATA_DIRS ?? "/usr/local/share:/usr/share").split(":").filter(Boolean);
120
+ return [.../* @__PURE__ */ new Set([
121
+ ...shared.map((path) => posix.join(path, "fonts")),
122
+ posix.join(home, ".fonts"),
123
+ posix.join(env.XDG_DATA_HOME ?? posix.join(home, ".local/share"), "fonts")
124
+ ])];
125
+ }
126
+ /**
127
+ * Font asset directories macOS publishes under its MobileAsset root.
128
+ * @param assets - Absolute MobileAsset font directory root.
129
+ * @returns matching asset directories, sorted by name.
130
+ * @throws when the root exists but cannot be read for a reason other than its absence or protection.
131
+ */
132
+ function mobileAssetFontDirectories(assets) {
133
+ let entries = [];
134
+ try {
135
+ entries = readdirSync(assets);
136
+ } catch (error) {
137
+ if (!absent(error)) throw error;
138
+ }
139
+ return entries.filter((name) => /^com_apple_MobileAsset_Font\d*$/.test(name)).sort().map((name) => join(assets, name));
140
+ }
141
+ /**
142
+ * @param parsed - Parsed font file: one face, or a collection of faces.
143
+ * @param face - Indexed metadata naming the face inside that file.
144
+ * @returns the physical face the index names.
145
+ * @throws when the file no longer provides the indexed face.
146
+ */
147
+ function indexedFace(parsed, face) {
148
+ const font = "fonts" in parsed ? parsed.fonts[face.faceIndex] : parsed;
149
+ if (font === void 0 || font.postscriptName !== face.postscriptName) throw new Error("The indexed font face is no longer available; recreate the converter.");
150
+ return font;
151
+ }
152
+ function regionalPriority(face, language) {
153
+ const locale = language.toLowerCase();
154
+ const preferred = locale.startsWith("ja") ? ["jp"] : locale.startsWith("ko") ? ["kr"] : locale.startsWith("zh") ? /hant|tw|hk|mo/.test(locale) ? ["tc", "hk"] : ["sc"] : [];
155
+ if (preferred.length === 0) return 0;
156
+ const region = `${face.family} ${face.postscriptName} ${basename(face.path)}`.toLowerCase().match(/(?:cjk|[\s_-])(sc|tc|jp|kr|hk)(?=[\s_.-]|$)/)?.[1];
157
+ return region === void 0 ? 1 : preferred.includes(region) ? 0 : 2;
158
+ }
159
+ /** Conversion-local glyph coverage over one operation's metadata snapshot. */
160
+ var SystemFontCatalog = class {
161
+ options;
162
+ faces;
163
+ queried = /* @__PURE__ */ new Map();
164
+ byFile = /* @__PURE__ */ new Map();
165
+ /**
166
+ * @param options - Host metadata snapshot and fallback families.
167
+ */
168
+ constructor(options) {
169
+ this.options = options;
170
+ this.faces = options.faces.map((face) => ({ ...face }));
171
+ for (const face of this.faces) {
172
+ const members = this.byFile.get(face.path) ?? [];
173
+ members.push(face);
174
+ this.byFile.set(face.path, members);
175
+ }
176
+ }
177
+ /**
178
+ * Find installed faces covering the requested family or missing characters.
179
+ * Exact families precede configured alternatives, symbol families for missing symbols,
180
+ * generic families, then other glyph-covering faces.
181
+ * @param request - VCL family/style attributes and Unicode scalars missing from its current font.
182
+ * @param signal - cancellation checked between synchronous font reads.
183
+ * @returns selected physical files, deduplicated across collection faces; absent glyphs remain unresolved.
184
+ * @throws if an indexed font changes or cannot be read during glyph matching.
185
+ */
186
+ match(request, signal) {
187
+ signal.throwIfAborted();
188
+ const requested = request.family.split(";").map((family) => family.trim()).filter(Boolean);
189
+ const primary = requested[0];
190
+ let missingFamily;
191
+ if (primary !== void 0 && !GENERIC_FAMILIES.has(normalize(primary)) && !this.faces.some((face) => face.aliases.includes(normalize(primary)))) missingFamily = primary;
192
+ const priority = fontFamilyPriority(requested, this.options.fallbackFamilies, request.pitch, request.codePoints.some((point) => /\p{Symbol}/u.test(String.fromCodePoint(point)))).map(normalize);
193
+ const missing = new Set(request.codePoints);
194
+ const ranked = this.faces.map((face) => {
195
+ const rank = priority.findIndex((family) => face.aliases.includes(family));
196
+ const region = regionalPriority(face, request.language);
197
+ const style = (request.style && normalize(request.style) === normalize(face.style) ? -1 : 0) + (request.italic === 3 || request.italic !== 0 === face.italic ? 0 : 100) + (request.pitch === 0 || request.pitch === 1 === face.fixed ? 0 : 50) + Math.abs((VCL_WEIGHTS[request.weight] ?? 400) - face.weight) / 100 + (request.width === 0 ? 0 : Math.abs(request.width - face.width));
198
+ return {
199
+ face,
200
+ rank: rank < 0 ? priority.length : rank,
201
+ region,
202
+ style
203
+ };
204
+ }).sort((left, right) => left.rank - right.rank || left.region - right.region || left.style - right.style || left.face.path.localeCompare(right.face.path, "en") || left.face.faceIndex - right.face.faceIndex);
205
+ const selected = [];
206
+ const files = /* @__PURE__ */ new Set();
207
+ for (const { face } of ranked) {
208
+ signal.throwIfAborted();
209
+ let covered;
210
+ if (face.coverage !== void 0) {
211
+ const coverage = face.coverage;
212
+ covered = [...missing].filter((point) => coverage.some(([first, last]) => point >= first && point <= last));
213
+ } else {
214
+ let known = this.queried.get(face);
215
+ if (known === void 0) {
216
+ known = /* @__PURE__ */ new Map();
217
+ this.queried.set(face, known);
218
+ }
219
+ const unknown = [...missing].filter((point) => !known.has(point));
220
+ if (unknown.length > 0) {
221
+ const parsed = create(readFont(face));
222
+ const collection = "fonts" in parsed ? { fonts: parsed.fonts } : parsed;
223
+ for (const member of this.byFile.get(face.path)) {
224
+ let answers = this.queried.get(member);
225
+ if (answers === void 0) {
226
+ answers = /* @__PURE__ */ new Map();
227
+ this.queried.set(member, answers);
228
+ }
229
+ const font = indexedFace(collection, member);
230
+ try {
231
+ for (const point of unknown) answers.set(point, font.hasGlyphForCodePoint(point));
232
+ } catch {
233
+ for (const point of unknown) answers.set(point, false);
234
+ }
235
+ }
236
+ }
237
+ covered = [...missing].filter((point) => known.get(point));
238
+ }
239
+ if (missing.size > 0 && covered.length === 0) continue;
240
+ if (!files.has(face.path)) {
241
+ selected.push(face);
242
+ files.add(face.path);
243
+ }
244
+ for (const point of covered) missing.delete(point);
245
+ if (missing.size === 0) break;
246
+ }
247
+ return {
248
+ fonts: selected,
249
+ ...missingFamily === void 0 ? {} : { missingFamily },
250
+ ...missing.size === 0 ? {} : { unresolvedCodePoints: [...missing] }
251
+ };
252
+ }
253
+ };
254
+ /**
255
+ * Read the unchanged indexed regular file; reject concurrent replacement or truncation.
256
+ * @param face - Indexed face metadata whose identity and timestamps must still match the file.
257
+ * @returns the complete original font bytes.
258
+ * @throws when the file changed, was replaced, or was truncated since indexing.
259
+ */
260
+ function readFont(face) {
261
+ const fd = openSync(face.path, constants.O_RDONLY | constants.O_NONBLOCK | constants.O_NOFOLLOW);
262
+ try {
263
+ const before = fstatSync(fd, { bigint: true });
264
+ if (!before.isFile() || !matchesFontFile(before, face)) throw new Error("An indexed font changed; recreate the converter.");
265
+ const bytes = Buffer.alloc(face.size);
266
+ for (let offset = 0; offset < bytes.length;) {
267
+ const count = readSync(fd, bytes, offset, bytes.length - offset, offset);
268
+ if (!count) throw new Error("An indexed font was truncated.");
269
+ offset += count;
270
+ }
271
+ if (!matchesFontFile(fstatSync(fd, { bigint: true }), face)) throw new Error("An indexed font changed while reading.");
272
+ return bytes;
273
+ } finally {
274
+ closeSync(fd);
275
+ }
276
+ }
277
+ //#endregion
278
+ //#region lib/types/font-metadata-cache.js
279
+ /** Resolve the platform's user-local cache, independently of font discovery. */
280
+ function defaultFontMetadataCacheDirectory(platform = process.platform, home = homedir(), env = process.env) {
281
+ if (platform === "darwin") return posix.join(home, "Library/Caches/libreoffice-kit");
282
+ if (platform === "win32") return win32.join(env.LOCALAPPDATA ?? win32.join(home, "AppData/Local"), "libreoffice-kit/Cache");
283
+ return posix.join(env.XDG_CACHE_HOME && posix.isAbsolute(env.XDG_CACHE_HOME) ? env.XDG_CACHE_HOME : posix.join(home, ".cache"), "libreoffice-kit");
284
+ }
285
+ //#endregion
286
+ //#region lib/types/options.js
287
+ const SANS_CJK_FAMILIES = [
288
+ "Microsoft YaHei",
289
+ "Microsoft YaHei UI",
290
+ "微软雅黑",
291
+ "PingFang SC",
292
+ "Noto Sans CJK SC",
293
+ "Noto Sans SC",
294
+ "Source Han Sans SC",
295
+ "SimHei",
296
+ "黑体",
297
+ "Heiti SC",
298
+ "STHeiti"
299
+ ];
300
+ /** Ordered family groups used when the caller supplies none. */
301
+ const FONT_FALLBACKS = [
302
+ ["Calibri", "Carlito"],
303
+ [
304
+ "Calibri Light",
305
+ "Carlito",
306
+ "Calibri"
307
+ ],
308
+ ["Cambria", "Caladea"],
309
+ [
310
+ "宋体",
311
+ "SimSun",
312
+ "NSimSun",
313
+ "Songti SC",
314
+ "STSong",
315
+ "Noto Serif CJK SC",
316
+ "Noto Serif SC",
317
+ "Source Han Serif SC"
318
+ ],
319
+ [
320
+ "黑体",
321
+ "SimHei",
322
+ "Heiti SC",
323
+ "STHeiti",
324
+ "Noto Sans CJK SC",
325
+ "Noto Sans SC",
326
+ "Source Han Sans SC"
327
+ ],
328
+ [
329
+ "微软雅黑",
330
+ "Microsoft YaHei",
331
+ "Microsoft YaHei UI",
332
+ "PingFang SC",
333
+ "Noto Sans CJK SC",
334
+ "Noto Sans SC"
335
+ ],
336
+ [
337
+ "楷体",
338
+ "KaiTi",
339
+ "Kaiti SC",
340
+ "STKaiti",
341
+ "LXGW WenKai"
342
+ ],
343
+ [
344
+ "仿宋",
345
+ "FangSong",
346
+ "STFangsong",
347
+ "Songti SC",
348
+ "Noto Serif CJK SC"
349
+ ],
350
+ [
351
+ "sans-serif",
352
+ "Arial",
353
+ "Liberation Sans",
354
+ "Helvetica",
355
+ "DejaVu Sans",
356
+ "Calibri",
357
+ "Calibri Light",
358
+ "Carlito",
359
+ ...SANS_CJK_FAMILIES
360
+ ],
361
+ [
362
+ "serif",
363
+ "Times New Roman",
364
+ "Liberation Serif",
365
+ "Times",
366
+ "DejaVu Serif",
367
+ "Cambria",
368
+ "Caladea",
369
+ "SimSun",
370
+ "NSimSun",
371
+ "宋体",
372
+ "Songti SC",
373
+ "STSong",
374
+ "Noto Serif CJK SC",
375
+ "Noto Serif SC",
376
+ "Source Han Serif SC"
377
+ ],
378
+ [
379
+ "monospace",
380
+ "Courier New",
381
+ "Liberation Mono",
382
+ "DejaVu Sans Mono",
383
+ "Menlo",
384
+ "Monaco",
385
+ "Courier",
386
+ "NSimSun",
387
+ "Noto Sans Mono CJK SC",
388
+ ...SANS_CJK_FAMILIES
389
+ ],
390
+ [
391
+ "Symbol",
392
+ "Standard Symbols PS",
393
+ "Symbola",
394
+ "Segoe UI Symbol",
395
+ "Apple Symbols",
396
+ "FreeSerif",
397
+ "DejaVu Sans"
398
+ ]
399
+ ];
400
+ const DEFAULT_LIMITS = {
401
+ timeoutMs: 12e4,
402
+ maxInputBytes: 67108864,
403
+ maxOutputBytes: 134217728,
404
+ maxImageResolution: 144,
405
+ maxArchiveEntries: 2e4,
406
+ maxUncompressedBytes: 536870912,
407
+ maxFontFiles: 2e4,
408
+ maxFontFileBytes: 268435456,
409
+ maxLoadedFontBytes: 536870912,
410
+ maxFontResolutionEntries: 4096,
411
+ maxFontMetadataCacheBytes: 33554432
412
+ };
413
+ const FONT_COLLECTION_NAMES = ["fontDirectories", "initialFontFamilies"];
414
+ function positiveSafeInteger(value, name) {
415
+ if (typeof value !== "number" || !Number.isSafeInteger(value) || value < 1) throw new RangeError(`${name} must be a positive safe integer.`);
416
+ if (name.endsWith("Ms") && value > 2147483647) throw new RangeError(`${name} exceeds the Node timer range.`);
417
+ return value;
418
+ }
419
+ function fontNames(value, name) {
420
+ if (!Array.isArray(value)) throw new TypeError(`${name} must contain nonempty strings.`);
421
+ const names = [];
422
+ for (const entry of value) {
423
+ if (typeof entry !== "string" || entry.length === 0 || entry.includes("\0")) throw new TypeError(`${name} must contain nonempty strings.`);
424
+ names.push(entry);
425
+ }
426
+ return names;
427
+ }
428
+ function fontGroups(value) {
429
+ if (!Array.isArray(value) || value.some((group) => !Array.isArray(group) || group.length < 2 || group.some((entry) => typeof entry !== "string" || !entry.trim()))) throw new TypeError("fontFallbacks must contain groups of at least two nonblank font names.");
430
+ return value.map((group) => [...group]);
431
+ }
432
+ /**
433
+ * Resolve defaults once; reject misspelled options and malformed font settings.
434
+ * @param input - Caller options; absent fields keep their documented default.
435
+ * @returns The validated limits and font settings, with caller arrays copied.
436
+ * @throws TypeError for a non-object argument or an unknown option name.
437
+ * @throws RangeError for a limit outside the positive safe-integer timer range.
438
+ */
439
+ function resolveOptions(input = {}) {
440
+ const callerOptions = input;
441
+ if (callerOptions === null || typeof callerOptions !== "object" || Array.isArray(callerOptions)) throw new TypeError("Converter options must be an object.");
442
+ const merged = {
443
+ ...DEFAULT_LIMITS,
444
+ fontDirectories: systemFontDirectories(),
445
+ fontFallbacks: FONT_FALLBACKS,
446
+ initialFontFamilies: [],
447
+ ...input
448
+ };
449
+ for (const key of Object.keys(input)) if (!(key in DEFAULT_LIMITS) && !FONT_COLLECTION_NAMES.includes(key) && key !== "fontFallbacks" && key !== "fontMetadataCacheDirectory") throw new TypeError(`Unknown converter option: ${key}`);
450
+ const cacheDirectory = input.fontMetadataCacheDirectory === void 0 ? defaultFontMetadataCacheDirectory() : input.fontMetadataCacheDirectory;
451
+ if (cacheDirectory !== false && (typeof cacheDirectory !== "string" || !isAbsolute(cacheDirectory) || cacheDirectory.includes("\0"))) throw new TypeError("fontMetadataCacheDirectory must be an absolute path or false.");
452
+ return {
453
+ fontMetadataCacheDirectory: cacheDirectory,
454
+ maxFontMetadataCacheBytes: positiveSafeInteger(merged.maxFontMetadataCacheBytes, "maxFontMetadataCacheBytes"),
455
+ timeoutMs: positiveSafeInteger(merged.timeoutMs, "timeoutMs"),
456
+ maxInputBytes: positiveSafeInteger(merged.maxInputBytes, "maxInputBytes"),
457
+ maxOutputBytes: positiveSafeInteger(merged.maxOutputBytes, "maxOutputBytes"),
458
+ maxImageResolution: positiveSafeInteger(merged.maxImageResolution, "maxImageResolution"),
459
+ maxArchiveEntries: positiveSafeInteger(merged.maxArchiveEntries, "maxArchiveEntries"),
460
+ maxUncompressedBytes: positiveSafeInteger(merged.maxUncompressedBytes, "maxUncompressedBytes"),
461
+ maxFontFiles: positiveSafeInteger(merged.maxFontFiles, "maxFontFiles"),
462
+ maxFontFileBytes: positiveSafeInteger(merged.maxFontFileBytes, "maxFontFileBytes"),
463
+ maxLoadedFontBytes: positiveSafeInteger(merged.maxLoadedFontBytes, "maxLoadedFontBytes"),
464
+ maxFontResolutionEntries: positiveSafeInteger(merged.maxFontResolutionEntries, "maxFontResolutionEntries"),
465
+ fontDirectories: fontNames(merged.fontDirectories, "fontDirectories"),
466
+ includeOfficeFonts: input.fontDirectories === void 0,
467
+ initialFontFamilies: fontNames(merged.initialFontFamilies, "initialFontFamilies"),
468
+ fontFallbacks: fontGroups(merged.fontFallbacks)
469
+ };
470
+ }
471
+ //#endregion
472
+ //#region lib/types/engine.js
473
+ /** Resolve installed, version-matched engine packages without downloads or compilation. */
474
+ const require = createRequire(import.meta.url);
475
+ /** Exact compatible engine versions; unchanged platforms retain their published packages. */
476
+ const ENGINE_VERSIONS = Object.freeze({
477
+ "darwin-arm64": "0.2.0-alpha6",
478
+ "darwin-x64": "0.2.0-alpha6",
479
+ "linux-arm64-glibc": "0.1.1",
480
+ "linux-x64-glibc": "0.1.1",
481
+ "win32-arm64": "0.1.5",
482
+ "win32-x64": "0.2.0-alpha6",
483
+ wasm: "0.2.0-alpha5"
484
+ });
485
+ /** npm scope and name prefix shared by the engine packages this adapter installs. */
486
+ const ENGINE_PREFIX = "@deepseek-ai/libreoffice-kit";
487
+ /**
488
+ * Whether an installed engine package directory is present on the resolution path.
489
+ * @param name - Engine package name.
490
+ * @returns true when at least one resolution directory holds the package.
491
+ */
492
+ function installedPackageExists(name) {
493
+ return (require.resolve.paths(name) ?? []).some((directory) => lstatSync(join(directory, name), { throwIfNoEntry: false }) !== void 0);
494
+ }
495
+ /**
496
+ * Return the optional package target for the current process ABI.
497
+ * @param platform - Host operating system.
498
+ * @param arch - Host CPU architecture.
499
+ * @param report - Host diagnostic report used to identify glibc.
500
+ * @returns the declared platform target, or undefined for an unsupported host.
501
+ */
502
+ function platformTarget(platform = process.platform, arch = process.arch, report = hostReport) {
503
+ if (!["arm64", "x64"].includes(arch)) return void 0;
504
+ if (platform === "darwin" || platform === "win32") return `${platform}-${arch}`;
505
+ if (platform !== "linux") return void 0;
506
+ return report().header?.glibcVersionRuntime ? `linux-${arch}-glibc` : void 0;
507
+ }
508
+ /** @returns the host diagnostic report as the engine resolver reads it. */
509
+ function hostReport() {
510
+ return process.report.getReport();
511
+ }
512
+ function asset(root, value) {
513
+ if (typeof value !== "string" || !value || isAbsolute(value)) throw new Error("Engine manifest contains an invalid asset path.");
514
+ const path = resolve(root, value);
515
+ if (relative(root, path).startsWith(`..${sep}`) || relative(root, path) === "..") throw new Error("Engine asset escapes its installed package.");
516
+ return path;
517
+ }
518
+ function glibcVersion(value) {
519
+ return typeof value === "string" && /^(0|[1-9]\d*)\.(0|[1-9]\d*)(?:\.(0|[1-9]\d*))?$/.test(value) && value.split(".").every((part) => Number.isSafeInteger(Number(part))) ? value.split(".").map(Number) : void 0;
520
+ }
521
+ /**
522
+ * Prefer the installed compatible native engine; hosts without one use the shared WASM package.
523
+ * @param resolvePackage - Package manifest resolver; injectable for selection tests.
524
+ * @param packageExists - Installed-package probe; injectable for selection tests.
525
+ * @param host - Process identification and diagnostic report.
526
+ * @returns the installed native engine, or the installed WASM engine.
527
+ */
528
+ async function resolveEngine(resolvePackage = (name) => require.resolve(`${name}/package.json`), packageExists = installedPackageExists, { platform = process.platform, arch = process.arch, report = hostReport } = {}) {
529
+ const details = platform === "linux" ? report() : {};
530
+ const target = platformTarget(platform, arch, () => details);
531
+ if (target !== void 0) {
532
+ const name = `${ENGINE_PREFIX}-${target}`;
533
+ let packageFile;
534
+ try {
535
+ packageFile = resolvePackage(name);
536
+ } catch (error) {
537
+ const failure = error;
538
+ if (!(failure?.code === "MODULE_NOT_FOUND" && typeof failure.message === "string" && failure.message.includes(`${name}/package.json`))) throw error;
539
+ if (packageExists(name)) throw new Error(`Installed LibreOfficeKit package is incomplete: ${name}`, { cause: error });
540
+ }
541
+ if (packageFile !== void 0) {
542
+ const engine = await readEngine(packageFile, "native", target);
543
+ const minimum = glibcVersion(engine.glibcMinimum);
544
+ const host = glibcVersion(details.header?.glibcVersionRuntime);
545
+ if (!(minimum && host && minimum.some((part, index) => part > (host[index] ?? 0) && minimum.slice(0, index).every((prior, priorIndex) => prior === host[priorIndex])))) return engine;
546
+ }
547
+ }
548
+ return readEngine(resolvePackage(`${ENGINE_PREFIX}-wasm`), "wasm", "wasm");
549
+ }
550
+ async function engineAsset(root, value, name, kind) {
551
+ const path = asset(root, value);
552
+ const status = await stat(path);
553
+ if (kind === "directory" ? !status.isDirectory() : !status.isFile()) throw new Error(`Installed LibreOfficeKit ${name} is not a ${kind}.`);
554
+ if (name === "executable" && process.platform !== "win32" && !(status.mode & 73)) throw new Error("Installed LibreOfficeKit executable is not executable.");
555
+ return path;
556
+ }
557
+ async function readEngine(packageFile, backend, target) {
558
+ const root = dirname(packageFile);
559
+ const [pkg, manifest] = await Promise.all([readFile(packageFile, "utf8").then((text) => JSON.parse(text)), readFile(resolve(root, "prebuilds.json"), "utf8").then((text) => JSON.parse(text))]);
560
+ const engine = manifest.engine;
561
+ if (pkg.name !== `${ENGINE_PREFIX}-${target}` || pkg.version !== ENGINE_VERSIONS[target] || manifest.version !== pkg.version || manifest.schemaVersion !== 1 || manifest.status !== "built" || engine === void 0 || engine.kind !== backend || manifest.platform !== target) throw new Error(`Installed LibreOfficeKit ${backend} package has an incompatible or incomplete manifest.`);
562
+ const minimum = engine.glibcMinimum;
563
+ if (minimum !== void 0 && (!target.endsWith("-glibc") || !glibcVersion(minimum))) throw new Error("Installed LibreOfficeKit engine has an invalid glibcMinimum.");
564
+ const glibcFloor = minimum === void 0 ? {} : { glibcMinimum: minimum };
565
+ if (backend === "native") {
566
+ const executable = await engineAsset(root, engine.executable, "executable", "file");
567
+ return {
568
+ backend,
569
+ root,
570
+ programDirectory: await engineAsset(root, engine.programDirectory, "programDirectory", "directory"),
571
+ executable,
572
+ ...["0.1.1", "0.1.5"].includes(String(pkg.version)) ? { legacyInputPath: true } : {},
573
+ ...glibcFloor
574
+ };
575
+ }
576
+ return {
577
+ backend,
578
+ root,
579
+ programDirectory: String(engine.programDirectory),
580
+ loader: await engineAsset(root, engine.loader, "loader", "file"),
581
+ wasm: await engineAsset(root, engine.wasm, "wasm", "file"),
582
+ data: await engineAsset(root, engine.data, "data", "file"),
583
+ metadata: await engineAsset(root, engine.metadata, "metadata", "file"),
584
+ ...glibcFloor
585
+ };
586
+ }
587
+ //#endregion
588
+ //#region lib/types/errors.js
589
+ /** Stable render failure categories shared across the Node worker and native helper transports. */
590
+ const CODES = /* @__PURE__ */ new Set([
591
+ "input-too-large",
592
+ "output-too-large",
593
+ "invalid-document",
594
+ "unsupported-format",
595
+ "invalid-output",
596
+ "timeout",
597
+ "unavailable",
598
+ "failed"
599
+ ]);
600
+ /** An actionable converter failure; operating-system errors and caller abort reasons remain unchanged. */
601
+ var ConversionError = class extends Error {
602
+ /** Published failure category carried across worker and helper transports. */
603
+ code;
604
+ /**
605
+ * @param code - Published failure category.
606
+ * @param message - Consumer-facing failure description.
607
+ * @param options - Standard error options; a cause is preserved for diagnostics.
608
+ */
609
+ constructor(code, message, options) {
610
+ super(message, options);
611
+ this.name = "ConversionError";
612
+ this.code = code;
613
+ }
614
+ };
615
+ /**
616
+ * Only published categories cross worker/helper messages; unknown errors use the generic failure category.
617
+ * @param error - The thrown value, which may be any type and may carry an unpublished `code`.
618
+ * @returns The published category, or `failed` when no published category is present.
619
+ */
620
+ function failureCode(error) {
621
+ const code = error?.code;
622
+ return typeof code === "string" && CODES.has(code) ? code : "failed";
623
+ }
624
+ //#endregion
625
+ //#region lib/types/font-snapshot-state.js
626
+ /** Shared in-flight metadata work with independent cancellation and joined Worker cleanup. */
627
+ /** Run one scan outside the event loop and join it before returning or cleaning its temporary file. */
628
+ async function runFontSnapshot(options, previous, signal) {
629
+ signal.throwIfAborted();
630
+ const temporaryPath = options.fontMetadataCacheDirectory === false ? void 0 : join(options.fontMetadataCacheDirectory, `.font-metadata-${randomUUID()}.tmp`);
631
+ const data = {
632
+ options,
633
+ previous,
634
+ ...temporaryPath === void 0 ? {} : { temporaryPath }
635
+ };
636
+ const worker = new Worker(new URL("./font-snapshot-worker.js", import.meta.url), {
637
+ workerData: data,
638
+ execArgv: [],
639
+ name: "libreoffice-font-metadata",
640
+ stdout: true,
641
+ stderr: true
642
+ });
643
+ worker.stdout.resume();
644
+ worker.stderr.resume();
645
+ const result = Promise.withResolvers();
646
+ const abort = () => result.reject(signal.reason);
647
+ signal.addEventListener("abort", abort, { once: true });
648
+ worker.once("error", result.reject);
649
+ worker.once("exit", (code) => result.reject(new ConversionError("failed", `Font metadata worker exited before returning a snapshot (${code}).`)));
650
+ worker.once("message", (message) => {
651
+ if (message.ok) result.resolve(message.snapshot);
652
+ else result.reject(new ConversionError(failureCode(message), message.error));
653
+ });
654
+ try {
655
+ return await result.promise;
656
+ } finally {
657
+ signal.removeEventListener("abort", abort);
658
+ await worker.terminate();
659
+ if (temporaryPath !== void 0) try {
660
+ await rm(temporaryPath, { force: true });
661
+ } catch {}
662
+ }
663
+ }
664
+ /** Each acquisition refreshes inventory; overlapping acquisitions share only the active scan. */
665
+ var FontSnapshotState = class {
666
+ previous = [];
667
+ scan;
668
+ /** Revalidate files for an operation without coupling its cancellation to other waiters. */
669
+ async acquire(options, signal) {
670
+ signal.throwIfAborted();
671
+ while (this.scan?.controller.signal.aborted) {
672
+ await this.scan.promise.catch(() => {});
673
+ signal.throwIfAborted();
674
+ }
675
+ if (this.scan === void 0) {
676
+ const controller = new AbortController();
677
+ const promise = runFontSnapshot(options, this.previous, controller.signal).then((snapshot) => {
678
+ this.previous = Buffer.byteLength(JSON.stringify(snapshot.records)) <= options.maxFontMetadataCacheBytes ? snapshot.records : [];
679
+ return snapshot;
680
+ }).finally(() => {
681
+ this.scan = void 0;
682
+ });
683
+ this.scan = {
684
+ controller,
685
+ promise,
686
+ waiters: 0
687
+ };
688
+ }
689
+ const scan = this.scan;
690
+ scan.waiters++;
691
+ const cancelled = Promise.withResolvers();
692
+ const abort = () => cancelled.reject(signal.reason);
693
+ signal.addEventListener("abort", abort, { once: true });
694
+ try {
695
+ return await Promise.race([scan.promise, cancelled.promise]);
696
+ } finally {
697
+ signal.removeEventListener("abort", abort);
698
+ scan.waiters--;
699
+ if (scan.waiters === 0 && this.scan === scan) {
700
+ scan.controller.abort(/* @__PURE__ */ new Error("All font scan waiters stopped."));
701
+ await scan.promise.catch(() => {});
702
+ }
703
+ }
704
+ }
705
+ /** Release completed metadata after the owning factory has joined its operations. */
706
+ clear() {
707
+ this.previous = [];
708
+ }
709
+ };
710
+ //#endregion
711
+ //#region lib/types/ooxml.js
712
+ /** Bounded OOXML inspection and declared font diagnostics, using maintained ZIP/XML parsers. */
713
+ const MAIN_PARTS = {
714
+ odt: ["content.xml", "application/vnd.oasis.opendocument.text"],
715
+ ods: ["content.xml", "application/vnd.oasis.opendocument.spreadsheet"],
716
+ odp: ["content.xml", "application/vnd.oasis.opendocument.presentation"],
717
+ docx: ["word/document.xml", "application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml"],
718
+ xlsx: ["xl/workbook.xml", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml"],
719
+ pptx: ["ppt/presentation.xml", "application/vnd.openxmlformats-officedocument.presentationml.presentation.main+xml"]
720
+ };
721
+ /**
722
+ * @param character - One code point as yielded by iteration over a string.
723
+ * @returns the Unicode scalar the character encodes; iteration never yields an empty string.
724
+ */
725
+ function codePointOf(character) {
726
+ return character.codePointAt(0);
727
+ }
728
+ /**
729
+ * Validate ZIP size and membership before decoding selected document XML.
730
+ * @param bytes - Complete source document bytes.
731
+ * @param extension - Input extension, which selects the main document part.
732
+ * @param limits - Archive entry and declared uncompressed byte limits.
733
+ * @returns declared font families and the scalar values readable document XML declares.
734
+ * @throws ConversionError when the extension is unsupported or the archive violates its limits.
735
+ */
736
+ function inspectDocument$1(bytes, extension, limits) {
737
+ const main = MAIN_PARTS[extension];
738
+ if (!main) throw new ConversionError("unsupported-format", "Input extension must be docx, xlsx, or pptx.");
739
+ const odf = [
740
+ "odt",
741
+ "ods",
742
+ "odp"
743
+ ].includes(extension);
744
+ const names = /* @__PURE__ */ new Set();
745
+ let total = 0;
746
+ let files;
747
+ try {
748
+ files = unzipSync(bytes, { filter(entry) {
749
+ total += entry.originalSize;
750
+ 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.");
751
+ names.add(entry.name);
752
+ if (odf) return [
753
+ "mimetype",
754
+ "content.xml",
755
+ "styles.xml",
756
+ "META-INF/manifest.xml"
757
+ ].includes(entry.name);
758
+ return entry.name === "[Content_Types].xml" || /^(word|xl|ppt)\/.*\.xml$/.test(entry.name) && !entry.name.endsWith("/fontTable.xml") && !entry.name.includes("/theme/");
759
+ } });
760
+ } catch (cause) {
761
+ throw new ConversionError("invalid-document", "Input is not a supported, bounded OOXML archive.", { cause });
762
+ }
763
+ const contentTypes = files["[Content_Types].xml"];
764
+ 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.`);
765
+ const families = /* @__PURE__ */ new Map();
766
+ const codePoints = /* @__PURE__ */ new Set();
767
+ for (const [name, data] of Object.entries(files)) {
768
+ if (name === "[Content_Types].xml" || name === "mimetype" || name === "META-INF/manifest.xml") continue;
769
+ const partFamilies = [];
770
+ const partPoints = /* @__PURE__ */ new Set();
771
+ const parser = new SaxesParser({ xmlns: true });
772
+ parser.on("opentag", (tag) => {
773
+ const word = /wordprocessingml\/(?:2006\/)?main$/.test(tag.uri) && tag.local === "rFonts";
774
+ const drawing = /drawingml\/(?:2006\/)?main$/.test(tag.uri);
775
+ const sheet = /spreadsheetml\/(?:2006\/)?main$/.test(tag.uri) && tag.local === "name";
776
+ for (const attribute of Object.values(tag.attributes)) {
777
+ if (odf && attribute.local === "font-family") partFamilies.push(attribute.value.replace(/^['"]|['"]$/g, ""));
778
+ if (word && [
779
+ "ascii",
780
+ "hAnsi",
781
+ "eastAsia",
782
+ "cs"
783
+ ].includes(attribute.local) || drawing && attribute.local === "typeface" || sheet && attribute.local === "val") partFamilies.push(attribute.value);
784
+ }
785
+ });
786
+ parser.on("text", (text) => {
787
+ for (const char of text) if (!/\s/u.test(char)) partPoints.add(codePointOf(char));
788
+ });
789
+ const encoding = data[0] === 255 && data[1] === 254 ? "utf-16le" : data[0] === 254 && data[1] === 255 ? "utf-16be" : "utf-8";
790
+ try {
791
+ parser.write(new TextDecoder(encoding).decode(data)).close();
792
+ } catch {
793
+ continue;
794
+ }
795
+ 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);
796
+ for (const point of partPoints) codePoints.add(point);
797
+ }
798
+ return {
799
+ families,
800
+ codePoints: [...codePoints]
801
+ };
802
+ }
803
+ //#endregion
804
+ //#region lib/types/document.js
805
+ /** Select bounded OOXML inspection or a legacy Office compound-file import. */
806
+ /** Input suffixes accepted by the public converter. */
807
+ const DOCUMENT_EXTENSIONS = [
808
+ "doc",
809
+ "docx",
810
+ "odt",
811
+ "xls",
812
+ "xlsx",
813
+ "ods",
814
+ "ppt",
815
+ "pptx",
816
+ "odp"
817
+ ];
818
+ const COMPOUND_SIGNATURE = [
819
+ 208,
820
+ 207,
821
+ 17,
822
+ 224,
823
+ 161,
824
+ 177,
825
+ 26,
826
+ 225
827
+ ];
828
+ /**
829
+ * Inspect the input container before invoking LibreOffice's document importer.
830
+ * Compound-file streams and legacy font tables are interpreted by LibreOffice;
831
+ * they do not supply the API's OOXML font diagnostics.
832
+ * @param bytes - Source bytes already bounded by maxInputBytes.
833
+ * @param extension - Lowercase source suffix.
834
+ * @param limits - Limits applied to ZIP-based document contents.
835
+ * @returns OOXML font metadata, or empty diagnostics for a binary document.
836
+ */
837
+ function inspectDocument(bytes, extension, limits) {
838
+ if (!DOCUMENT_EXTENSIONS.includes(extension)) throw new ConversionError("unsupported-format", `Input extension must be ${DOCUMENT_EXTENSIONS.join(", ")}.`);
839
+ if ([
840
+ "docx",
841
+ "xlsx",
842
+ "pptx",
843
+ "odt",
844
+ "ods",
845
+ "odp"
846
+ ].includes(extension)) return inspectDocument$1(bytes, extension, limits);
847
+ 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.");
848
+ const header = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
849
+ const version = header.getUint16(26, true);
850
+ const sectorShift = header.getUint16(30, true);
851
+ 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.");
852
+ return {
853
+ families: /* @__PURE__ */ new Map(),
854
+ codePoints: []
855
+ };
856
+ }
857
+ //#endregion
858
+ //#region lib/types/font-loader.js
859
+ /** Conversion-local font imports backed by a factory-lifetime match cache. */
860
+ const faceKey = (face) => `${face.path}\0${face.faceIndex}`;
861
+ const requestKey = ({ codePoints: _codePoints, ...request }) => JSON.stringify(request);
862
+ /** Build one operation's loader over a factory-owned immutable font snapshot. */
863
+ function createFontLoader(options, document, install, faces, cache = []) {
864
+ const catalog = new SystemFontCatalog({
865
+ faces,
866
+ fallbackFamilies: options.fontFallbacks
867
+ });
868
+ const byFace = new Map(faces.map((face) => [faceKey(face), face]));
869
+ const matches = /* @__PURE__ */ new Map();
870
+ for (const entry of cache.slice(-options.maxFontResolutionEntries)) matches.set(entry.key, {
871
+ ...entry,
872
+ codePoints: [...entry.codePoints],
873
+ faces: entry.faces.map((face) => ({ ...face }))
874
+ });
875
+ const loaded = /* @__PURE__ */ new Map();
876
+ const resolved = /* @__PURE__ */ new Map();
877
+ const missing = /* @__PURE__ */ new Map();
878
+ const substitutions = /* @__PURE__ */ new Map();
879
+ const signal = new AbortController().signal;
880
+ let bytes = 0;
881
+ function retain(entry) {
882
+ matches.delete(entry.key);
883
+ matches.set(entry.key, entry);
884
+ while (matches.size > options.maxFontResolutionEntries) matches.delete(matches.keys().next().value);
885
+ }
886
+ function cachedMatch(request) {
887
+ const key = requestKey(request);
888
+ const points = [...new Set(request.codePoints)].sort((left, right) => left - right);
889
+ const prior = matches.get(key);
890
+ if (prior && (points.length === 0 && prior.emptyRequest || points.every((point) => prior.codePoints.includes(point)))) {
891
+ retain(prior);
892
+ return {
893
+ fonts: prior.faces.map((reference) => byFace.get(faceKey(reference))).filter((face) => face !== void 0),
894
+ ...prior.missingFamily === void 0 ? {} : { missingFamily: prior.missingFamily }
895
+ };
896
+ }
897
+ const unknown = prior === void 0 ? points : points.filter((point) => !prior.codePoints.includes(point));
898
+ const current = catalog.match({
899
+ ...request,
900
+ codePoints: points.length === 0 ? [] : unknown
901
+ }, signal);
902
+ const references = new Map((prior?.faces ?? []).map((face) => [faceKey(face), face]));
903
+ for (const face of current.fonts) references.set(faceKey(face), {
904
+ path: face.path,
905
+ faceIndex: face.faceIndex
906
+ });
907
+ const missingFamily = prior?.missingFamily ?? current.missingFamily;
908
+ const entry = {
909
+ key,
910
+ codePoints: [.../* @__PURE__ */ new Set([...prior?.codePoints ?? [], ...points])].sort((left, right) => left - right),
911
+ emptyRequest: prior?.emptyRequest === true || points.length === 0,
912
+ faces: [...references.values()],
913
+ ...missingFamily === void 0 ? {} : { missingFamily }
914
+ };
915
+ retain(entry);
916
+ return {
917
+ fonts: entry.faces.map((reference) => byFace.get(faceKey(reference))).filter((face) => face !== void 0),
918
+ ...entry.missingFamily === void 0 ? {} : { missingFamily: entry.missingFamily }
919
+ };
920
+ }
921
+ return {
922
+ get missingFonts() {
923
+ return [...missing.values()];
924
+ },
925
+ get substitutions() {
926
+ return [...substitutions.values()];
927
+ },
928
+ get files() {
929
+ return [...loaded.values()];
930
+ },
931
+ get cacheEntries() {
932
+ return [...matches.values()];
933
+ },
934
+ resolve(request) {
935
+ const key = JSON.stringify(request);
936
+ const cached = resolved.get(key);
937
+ if (cached) return cached;
938
+ const match = cachedMatch(request);
939
+ if (match.missingFamily && document.families.has(normalize(match.missingFamily))) {
940
+ const family = normalize(match.missingFamily);
941
+ missing.set(family, match.missingFamily);
942
+ if (match.fonts[0]) substitutions.set(family, {
943
+ family: match.missingFamily,
944
+ substitute: match.fonts[0].family
945
+ });
946
+ }
947
+ const paths = match.fonts.map((face) => {
948
+ const installed = loaded.get(face.path);
949
+ if (installed !== void 0) return installed;
950
+ if (bytes + face.size > options.maxLoadedFontBytes) throw new Error("Imported fonts exceed maxLoadedFontBytes.");
951
+ const path = install(`${loaded.size}${extname(face.path)}`, readFont(face));
952
+ bytes += face.size;
953
+ loaded.set(face.path, path);
954
+ return path;
955
+ });
956
+ resolved.set(key, paths);
957
+ return paths;
958
+ }
959
+ };
960
+ }
961
+ /** Supply native imports and seed WASM's first usable default font. */
962
+ function preloadFonts(loader, options, document, native = false) {
963
+ const families = [
964
+ ...options.initialFontFamilies,
965
+ ...native ? [...document.families.values()] : [],
966
+ "sans-serif"
967
+ ];
968
+ for (const family of families) loader.resolve({
969
+ family,
970
+ style: "",
971
+ weight: 5,
972
+ italic: 0,
973
+ width: 5,
974
+ pitch: 0,
975
+ language: "",
976
+ codePoints: native ? document.codePoints : []
977
+ });
978
+ }
979
+ //#endregion
980
+ //#region lib/types/native-process.js
981
+ /** Native helper stdio; Windows pipe handles permit read/write access under restricted tokens. */
982
+ let pipeAttributes;
983
+ function windowsPipes() {
984
+ const koffi = createRequire(import.meta.url)("koffi");
985
+ const kernel = koffi.load("kernel32.dll"), advapi = koffi.load("advapi32.dll"), node = koffi.load(null);
986
+ const attributes = pipeAttributes ??= koffi.struct({
987
+ nLength: "uint32",
988
+ lpSecurityDescriptor: "void *",
989
+ bInheritHandle: "int"
990
+ });
991
+ const createPipe = kernel.func("__stdcall", "CreatePipe", "int", [
992
+ koffi.out(koffi.pointer("void *")),
993
+ koffi.out(koffi.pointer("void *")),
994
+ koffi.pointer(attributes),
995
+ "uint32"
996
+ ]);
997
+ const closeHandle = kernel.func("int __stdcall CloseHandle(void *handle)");
998
+ const localFree = kernel.func("void * __stdcall LocalFree(void *memory)");
999
+ const peek = kernel.func("int __stdcall PeekNamedPipe(void *pipe, void *buffer, uint32 size, void *read, _Out_ uint32 *available, void *remaining)");
1000
+ const lastError = kernel.func("uint32 __stdcall GetLastError()");
1001
+ const convertSecurityDescriptor = advapi.func("int __stdcall ConvertStringSecurityDescriptorToSecurityDescriptorW(void *sddl, uint32 revision, _Out_ void **descriptor, void *size)");
1002
+ const openFd = node.func("int uv_open_osfhandle(void *handle)");
1003
+ function pipe() {
1004
+ const reads = [null], writes = [null];
1005
+ const descriptor = [null];
1006
+ if (!convertSecurityDescriptor(Buffer.from("D:(A;;GRGW;;;WD)\0", "utf16le"), 1, descriptor, null)) throw new Error(`Pipe security descriptor failed: ${lastError()}`);
1007
+ try {
1008
+ if (!createPipe(reads, writes, {
1009
+ nLength: attributes.size,
1010
+ lpSecurityDescriptor: descriptor[0],
1011
+ bInheritHandle: 0
1012
+ }, 0)) throw new Error(`CreatePipe failed: ${lastError()}`);
1013
+ } finally {
1014
+ localFree(descriptor[0]);
1015
+ }
1016
+ const read = openFd(reads[0]);
1017
+ if (read < 0) {
1018
+ closeHandle(reads[0]);
1019
+ closeHandle(writes[0]);
1020
+ throw new Error("Cannot open anonymous input descriptor");
1021
+ }
1022
+ const write = openFd(writes[0]);
1023
+ if (write < 0) {
1024
+ closeSync(read);
1025
+ closeHandle(writes[0]);
1026
+ throw new Error("Cannot open anonymous output descriptor");
1027
+ }
1028
+ let timer;
1029
+ let ended = false;
1030
+ const readable = new Readable({
1031
+ read() {
1032
+ if (timer === void 0 && !ended) poll();
1033
+ },
1034
+ destroy(error, callback) {
1035
+ ended = true;
1036
+ clearTimeout(timer);
1037
+ try {
1038
+ closeSync(read);
1039
+ callback(error);
1040
+ } catch (cause) {
1041
+ callback(error ?? cause);
1042
+ }
1043
+ }
1044
+ });
1045
+ function poll() {
1046
+ timer = void 0;
1047
+ try {
1048
+ const available = [0];
1049
+ if (!peek(reads[0], null, 0, null, available, null)) {
1050
+ const code = lastError();
1051
+ if (code !== 109) throw new Error(`PeekNamedPipe failed: ${code}`);
1052
+ ended = true;
1053
+ readable.push(null);
1054
+ return;
1055
+ }
1056
+ if (available[0] > 0) {
1057
+ const buffer = Buffer.allocUnsafe(Math.min(available[0], 65536));
1058
+ const count = readSync(read, buffer, 0, buffer.length, null);
1059
+ if (!readable.push(buffer.subarray(0, count))) return;
1060
+ }
1061
+ timer = setTimeout(poll, 5);
1062
+ } catch (error) {
1063
+ readable.destroy(error);
1064
+ }
1065
+ }
1066
+ return {
1067
+ read,
1068
+ write,
1069
+ readable
1070
+ };
1071
+ }
1072
+ return { pipe };
1073
+ }
1074
+ /**
1075
+ * Spawn with inherited token and Job restrictions; pipe creation never requests a new sandbox policy.
1076
+ * @param executable - Verified native helper executable.
1077
+ * @param args - Helper protocol arguments.
1078
+ * @param env - Filtered operation environment.
1079
+ * @returns Helper streams and process lifetime, with output drained before close.
1080
+ */
1081
+ function spawnNative(executable, args, env) {
1082
+ if (process.platform !== "win32") return spawn(executable, args, {
1083
+ stdio: "pipe",
1084
+ windowsHide: true,
1085
+ env
1086
+ });
1087
+ const { pipe } = windowsPipes();
1088
+ const owned = [];
1089
+ let child;
1090
+ try {
1091
+ const input = pipe();
1092
+ owned.push(input);
1093
+ const output = pipe();
1094
+ owned.push(output);
1095
+ const error = pipe();
1096
+ owned.push(error);
1097
+ child = spawn(executable, args, {
1098
+ stdio: [
1099
+ input.read,
1100
+ output.write,
1101
+ error.write
1102
+ ],
1103
+ windowsHide: true,
1104
+ env
1105
+ });
1106
+ } catch (error) {
1107
+ for (const entry of owned) {
1108
+ entry.readable.destroy();
1109
+ closeSync(entry.write);
1110
+ }
1111
+ throw error;
1112
+ }
1113
+ const [input, output, error] = owned;
1114
+ input.readable.destroy();
1115
+ closeSync(output.write);
1116
+ closeSync(error.write);
1117
+ const stdin = createWriteStream("", {
1118
+ fd: input.write,
1119
+ autoClose: true
1120
+ });
1121
+ const helper = new class extends EventEmitter {
1122
+ stdin = stdin;
1123
+ stdout = output.readable;
1124
+ stderr = error.readable;
1125
+ get pid() {
1126
+ return child.pid;
1127
+ }
1128
+ get exitCode() {
1129
+ return child.exitCode;
1130
+ }
1131
+ get signalCode() {
1132
+ return child.signalCode;
1133
+ }
1134
+ kill(signal) {
1135
+ return child.kill(signal);
1136
+ }
1137
+ }();
1138
+ let failure;
1139
+ const fail = (cause) => {
1140
+ failure ??= cause;
1141
+ child.kill("SIGKILL");
1142
+ };
1143
+ stdin.on("error", fail);
1144
+ output.readable.on("error", fail);
1145
+ error.readable.on("error", fail);
1146
+ const drained = Promise.allSettled([
1147
+ finished(stdin),
1148
+ finished(output.readable),
1149
+ finished(error.readable)
1150
+ ]);
1151
+ child.once("error", (cause) => {
1152
+ failure ??= cause;
1153
+ });
1154
+ child.once("close", (code, signal) => {
1155
+ stdin.destroy();
1156
+ output.readable.resume();
1157
+ error.readable.resume();
1158
+ drained.then(() => {
1159
+ if (failure !== void 0) helper.emit("error", failure);
1160
+ helper.emit("close", code, signal);
1161
+ });
1162
+ });
1163
+ return helper;
1164
+ }
1165
+ //#endregion
1166
+ //#region lib/types/profile.js
1167
+ /** Private headless profile used by both native and WASM conversions. */
1168
+ /**
1169
+ * CSV selection is checked by the engine wrapper before saving; suppress the interactive warning.
1170
+ * @param fontNodes - Escaped VCL font-substitution nodes, or an empty string for WASM.
1171
+ * @returns The per-operation registry XML; macro execution is independently disabled at load.
1172
+ */
1173
+ function profileXml(fontNodes = "") {
1174
+ 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`;
1175
+ }
1176
+ //#endregion
1177
+ //#region lib/types/native-font-names.js
1178
+ /** Localized search names from LibreOffice Core's fixed font-name dictionary. */
1179
+ const LOCALIZED_FONT_SEARCH_NAMES = /* @__PURE__ */ new Map([
1180
+ ["바탕", "batang"],
1181
+ ["바탕체", "batangche"],
1182
+ ["궁서", "gungshu"],
1183
+ ["궁서체", "gungshuche"],
1184
+ ["굴림", "gulim"],
1185
+ ["굴림체", "gulimche"],
1186
+ ["돋움", "dotum"],
1187
+ ["돋움체", "dotumche"],
1188
+ ["宋体", "simsun"],
1189
+ ["新宋体", "nsimsun"],
1190
+ ["黑体", "simhei"],
1191
+ ["楷体", "simkai"],
1192
+ ["中易宋体", "zycjksun"],
1193
+ ["中易黑体", "zycjkhei"],
1194
+ ["中易楷体", "zycjkkai"],
1195
+ ["方正黑体", "fzhei"],
1196
+ ["方正楷体", "fzkai"],
1197
+ ["方正宋一", "fzsong"],
1198
+ ["方正书宋", "fzshusong"],
1199
+ ["方正仿宋", "fzfangsong"],
1200
+ ["m简黑", "mhei"],
1201
+ ["m潠窪", "mhei"],
1202
+ ["m简楷噬", "mkai"],
1203
+ ["m潠翱抎", "mkai"],
1204
+ ["m简宋", "msong"],
1205
+ ["m潠冼", "msong"],
1206
+ ["m简夫宋", "cfangsong"],
1207
+ ["m潠溘冼", "cfangsong"],
1208
+ ["細明體", "mingliu"],
1209
+ ["新細明體", "pmingliu"],
1210
+ ["桥", "hei"],
1211
+ ["歡", "kai"],
1212
+ ["浩湧", "ming"],
1213
+ ["msゴシック", "msgothic"],
1214
+ ["mspゴシック", "mspgothic"],
1215
+ ["ms明朝", "msmincho"],
1216
+ ["msp明朝", "mspmincho"],
1217
+ ["微軟正黑體", "microsoftjhenghei"],
1218
+ ["微软雅黑", "microsoftyahei"],
1219
+ ["メイリオ", "meiryo"],
1220
+ ["hg明朝l", "hgminchol"],
1221
+ ["hgゴシックb", "hggothicb"],
1222
+ ["hgp明朝l", "hgpminchol"],
1223
+ ["hgpゴシックb", "hgpgothicb"],
1224
+ ["hg明朝lsun", "hgmincholsun"],
1225
+ ["hgゴシックbsun", "hggothicbsun"],
1226
+ ["hgp明朝lsun", "hgpmincholsun"],
1227
+ ["hgpゴシックbsun", "hgpgothicbsun"],
1228
+ ["hg平成明朝体", "hgheiseimin"],
1229
+ ["hg平成明朝体w3x12", "hgheiseimin"],
1230
+ ["ipa明朝", "ipamincho"],
1231
+ ["ipap明朝", "ipapmincho"],
1232
+ ["ipaゴシック", "ipagothic"],
1233
+ ["ipapゴシック", "ipapgothic"],
1234
+ ["ipauiゴシック", "ipauigothic"],
1235
+ ["takao明朝", "takaomincho"],
1236
+ ["takaop明朝", "takaopmincho"],
1237
+ ["takaoゴシック", "takaogothic"],
1238
+ ["takaopゴシック", "takaopgothic"],
1239
+ ["さざなみ明朝", "sazanamimincho"],
1240
+ ["さざなみゴシック", "sazanamigothic"],
1241
+ ["東風明朝", "kochimincho"],
1242
+ ["東風ゴシック", "kochigothic"],
1243
+ ["썬돋움", "sundotum"],
1244
+ ["썬굴림", "sungulim"],
1245
+ ["썬바탕", "sunbatang"],
1246
+ ["백묵돋움", "baekmukdotum"],
1247
+ ["백묵굴림", "baekmukgulim"],
1248
+ ["백묵바탕", "baekmukbatang"],
1249
+ ["方正黑體", "fzheiti"],
1250
+ ["方正楷體", "fzkaitib"],
1251
+ ["方正明體", "fzmingtib"],
1252
+ ["方正宋体", "fzsongti"],
1253
+ ["hy견명조", "hymyeongjoextra"],
1254
+ ["hy신명조", "hysinmyeongjomedium"],
1255
+ ["hy중고딕", "hygothicmedium"],
1256
+ ["hy그래픽m", "hygraphicmedium"],
1257
+ ["hy그래픽", "hygraphic"],
1258
+ ["새굴림", "newgulim"],
1259
+ ["썬궁서", "sungungseo"],
1260
+ ["hy궁서b", "hygungsobold"],
1261
+ ["hy궁서", "hygungso"],
1262
+ ["썬헤드라인", "sunheadline"],
1263
+ ["hy헤드라인m", "hyheadlinemedium"],
1264
+ ["hy헤드라인", "hyheadline"],
1265
+ ["휴먼옛체", "yetr"],
1266
+ ["hy견고딕", "hygothicextra"],
1267
+ ["썬목판", "sunmokpan"],
1268
+ ["썬엽서", "sunyeopseo"],
1269
+ ["썬백송", "sunbaeksong"],
1270
+ ["hy엽서l", "hypostlight"],
1271
+ ["hy엽서", "hypost"],
1272
+ ["휴먼매직체", "magicr"],
1273
+ ["썬크리스탈", "suncrystal"],
1274
+ ["썬샘물", "sunsaemmul"],
1275
+ ["hy얕은샘물m", "hyshortsamulmedium"],
1276
+ ["hy얕은샘물", "hyshortsamul"],
1277
+ ["한컴바탕", "haansoftbatang"],
1278
+ ["한컴돋움", "haansoftdotum"],
1279
+ ["한양해서", "hyhaeseo"],
1280
+ ["md솔체", "mdsol"],
1281
+ ["md개성체", "mdgaesung"],
1282
+ ["md아트체", "mdart"],
1283
+ ["md아롱체", "mdalong"],
1284
+ ["md이솝체", "mdeasop"],
1285
+ ["hgゴシックe", "hggothice"],
1286
+ ["hgpゴシックe", "hgpgothice"],
1287
+ ["hgsゴシックe", "hgsgothice"],
1288
+ ["hgゴシックm", "hggothicm"],
1289
+ ["hgpゴシックm", "hgpgothicm"],
1290
+ ["hgsゴシックm", "hgsgothicm"],
1291
+ ["hg行書体", "hggyoshotai"],
1292
+ ["hgp行書体", "hgpgyoshotai"],
1293
+ ["hgs行書体", "hgsgyoshotai"],
1294
+ ["hg教科書体", "hgkyokashotai"],
1295
+ ["hgp教科書体", "hgpkyokashotai"],
1296
+ ["hgs教科書体", "hgskyokashotai"],
1297
+ ["hg明朝b", "hgminchob"],
1298
+ ["hgp明朝b", "hgpminchob"],
1299
+ ["hgs明朝b", "hgsminchob"],
1300
+ ["hg明朝e", "hgminchoe"],
1301
+ ["hgp明朝e", "hgpminchoe"],
1302
+ ["hgs明朝e", "hgsminchoe"],
1303
+ ["hg創英角ポップ体", "hgsoeikakupoptai"],
1304
+ ["hgp創英角ポップ体", "hgpsoeikakupopta"],
1305
+ ["hgs創英角ポップ体", "hgssoeikakupopta"],
1306
+ ["hg創英プレゼンスeb", "hgsoeipresenceeb"],
1307
+ ["hgp創英プレゼンスeb", "hgpsoeipresenceeb"],
1308
+ ["hgs創英プレゼンスeb", "hgssoeipresenceeb"],
1309
+ ["hg創英角ゴシックub", "hgsoeikakugothicub"],
1310
+ ["hgp創英角ゴシックub", "hgpsoeikakugothicub"],
1311
+ ["hgs創英角ゴシックub", "hgssoeikakugothicub"],
1312
+ ["hg正楷書体-pro", "hgseikaishotaipro"],
1313
+ ["hg丸ゴシック-pro", "hgmarugothicmpro"],
1314
+ ["ヒラギノ明朝pro", "hiraginominchopro"],
1315
+ ["ヒラギノ明朝pron", "hiraginominchopron"],
1316
+ ["ヒラギノ角ゴシック", "hiraginosans"],
1317
+ ["ヒラギノ角ゴpro", "hiraginokakugothicpro"],
1318
+ ["ヒラギノ角ゴpron", "hiraginokakugothicpron"],
1319
+ ["ヒラギノ丸ゴpro", "hiraginomarugothicpro"],
1320
+ ["ヒラギノ丸ゴpron", "hiraginomarugothicpron"],
1321
+ ["游ゴシック", "yugothic"],
1322
+ ["游ゴシック体", "yugothictai"],
1323
+ ["游明朝", "yumincho"],
1324
+ ["游明朝体", "yuminchotai"],
1325
+ ["源ノ角ゴシック", "sourcehansans"],
1326
+ ["源ノ角ゴシックjp", "sourcehansansjp"],
1327
+ ["源ノ角ゴシックhw", "sourcehansanshw"],
1328
+ ["源ノ明朝", "sourcehanserif"],
1329
+ ["源ノ明朝jp", "sourcehanserifjp"],
1330
+ ["ipamj明朝", "ipamjmincho"],
1331
+ ["ipaexゴシック", "ipaexgothic"],
1332
+ ["ipaex明朝", "ipaexmimcho"]
1333
+ ]);
1334
+ //#endregion
1335
+ //#region lib/types/native.js
1336
+ const METRIC_SEARCH_NAMES = /* @__PURE__ */ new Map([
1337
+ ["timesnewroman", "liberationserif"],
1338
+ ["arial", "liberationsans"],
1339
+ ["arialnarrow", "liberationsansnarrow"],
1340
+ ["couriernew", "liberationmono"],
1341
+ ["cambria", "caladea"],
1342
+ ["calibri", "carlito"],
1343
+ ["bundessans", "calibri"],
1344
+ ["bundessansoffice", "calibri"],
1345
+ ["bundessansregular", "calibri"],
1346
+ ["bundesserif", "cambria"],
1347
+ ["bundesserifoffice", "cambria"],
1348
+ ["bundesserifregular", "cambria"]
1349
+ ]);
1350
+ /** Environment variables the helper inherits from the embedding process. */
1351
+ const NATIVE_ENVIRONMENT_KEYS = [
1352
+ "PATH",
1353
+ "SystemRoot",
1354
+ "SYSTEMROOT",
1355
+ "WINDIR",
1356
+ "COMSPEC",
1357
+ "PATHEXT",
1358
+ "LANG",
1359
+ "LC_ALL",
1360
+ "TZ",
1361
+ "OFFICE_GRAPHITE_DIAGNOSTICS",
1362
+ "OFFICE_LOAD_DIAGNOSTICS"
1363
+ ];
1364
+ function fontSearchName(value) {
1365
+ const name = value.replaceAll(/[\uff00-\uff5e]/g, (character) => String.fromCharCode(character.charCodeAt(0) - 65248)).replaceAll(/[A-Z]/g, (character) => character.toLowerCase()).replaceAll(/[^a-z0-9;()\u0080-\uffff]/g, "");
1366
+ return LOCALIZED_FONT_SEARCH_NAMES.get(name) ?? name;
1367
+ }
1368
+ /**
1369
+ * Write missing-family choices into the private profile's VCL substitution table.
1370
+ * Installed originals and metric-compatible fonts are resolved before this table by LibreOffice.
1371
+ * @param profile - Existing, conversion-owned profile directory.
1372
+ * @param substitutions - Missing document families and the selected installed family.
1373
+ * @returns Resolves after the exclusive profile file is written; empty choices still disable the interactive CSV warning.
1374
+ */
1375
+ async function prepareNativeFontProfile(profile, substitutions) {
1376
+ const families = new Map(substitutions.map(({ family, substitute }) => [fontSearchName(family), substitute]));
1377
+ for (const [family, substitute] of [...families]) for (let alias = METRIC_SEARCH_NAMES.get(family); alias; alias = METRIC_SEARCH_NAMES.get(alias)) if (!families.has(alias)) families.set(alias, substitute);
1378
+ const escape = (value) => value.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;").replaceAll("\"", "&quot;").replaceAll("'", "&apos;");
1379
+ const xml = profileXml([...families].map(([family, substitute]) => `<node oor:name="${escape(family)}" oor:op="replace"><prop oor:name="SubstFonts" oor:op="fuse"><value>${escape(substitute)}</value></prop></node>`).join(""));
1380
+ const user = join(profile, "user");
1381
+ await mkdir(user, { mode: 448 });
1382
+ await writeFile(join(user, "registrymodifications.xcu"), xml, {
1383
+ flag: "wx",
1384
+ mode: 384
1385
+ });
1386
+ }
1387
+ /**
1388
+ * Native conversion and rendering disable printer discovery to avoid driver UI and network waits.
1389
+ * Linux searches the verified program directory; ambient loader overrides and credentials are excluded.
1390
+ * @param profile - Conversion-owned profile directory the helper treats as home.
1391
+ * @param programDirectory - Verified engine program directory.
1392
+ * @param source - Embedding process environment.
1393
+ * @param platform - Host operating system.
1394
+ * @returns the environment the helper starts with.
1395
+ */
1396
+ function nativeEnvironment(profile, programDirectory, source = process.env, platform = process.platform) {
1397
+ const env = {};
1398
+ for (const key of NATIVE_ENVIRONMENT_KEYS) {
1399
+ const value = source[key];
1400
+ if (value !== void 0) env[key] = value;
1401
+ }
1402
+ if (platform === "linux") env.LD_LIBRARY_PATH = programDirectory;
1403
+ return Object.assign(env, {
1404
+ HOME: profile,
1405
+ USERPROFILE: profile,
1406
+ TMPDIR: profile,
1407
+ TMP: profile,
1408
+ TEMP: profile,
1409
+ SAL_DISABLE_PRINTERLIST: "1",
1410
+ SAL_DISABLE_DEFAULTPRINTER: "1"
1411
+ });
1412
+ }
1413
+ /**
1414
+ * Prepare short Windows engine paths owned by the caller's private profile.
1415
+ * @param engine - Verified engine installation; its resources remain in place.
1416
+ * @param profile - Private operation directory that owns the temporary executable and junction.
1417
+ * @returns Engine paths and a release function to call once, after the helper closes and before removing the profile.
1418
+ */
1419
+ async function prepareNativeEngine(engine, profile) {
1420
+ if (process.platform !== "win32" || engine.executable.length < 260 && engine.programDirectory.length < 260) return {
1421
+ engine,
1422
+ release: async () => {}
1423
+ };
1424
+ const root = join(profile, "engine");
1425
+ await symlink(engine.root, root, "junction");
1426
+ try {
1427
+ const executable = join(profile, "libreoffice-kit.exe");
1428
+ await copyFile(engine.executable, executable, constants.COPYFILE_EXCL);
1429
+ return {
1430
+ engine: {
1431
+ ...engine,
1432
+ root,
1433
+ executable,
1434
+ programDirectory: join(root, relative(engine.root, engine.programDirectory))
1435
+ },
1436
+ release: () => unlink(root)
1437
+ };
1438
+ } catch (error) {
1439
+ await unlink(root);
1440
+ throw error;
1441
+ }
1442
+ }
1443
+ //#endregion
1444
+ //#region lib/types/editor-protocol.js
1445
+ /** Encode a control record; the native editor accepts no binary input. */
1446
+ function encodeEditorRequest(control) {
1447
+ const json = Buffer.from(JSON.stringify(control));
1448
+ if (json.length > 1048576) throw new RangeError("Editor request exceeds 1 MiB.");
1449
+ const header = Buffer.alloc(8);
1450
+ header.writeUInt32BE(json.length);
1451
+ return Buffer.concat([header, json]);
1452
+ }
1453
+ /** Parses fragmented records without repeatedly copying a partial pixel frame. */
1454
+ var EditorFrameReader = class {
1455
+ maxPixelBytes;
1456
+ receive;
1457
+ maxControlBytes;
1458
+ header = Buffer.alloc(8);
1459
+ headerBytes = 0;
1460
+ body;
1461
+ bodyBytes = 0;
1462
+ jsonBytes = 0;
1463
+ constructor(maxPixelBytes, receive, maxControlBytes = 1048576) {
1464
+ this.maxPixelBytes = maxPixelBytes;
1465
+ this.receive = receive;
1466
+ this.maxControlBytes = maxControlBytes;
1467
+ }
1468
+ /** Consume arbitrary process chunks; invalid sizes or JSON are fatal to the session. */
1469
+ push(chunk) {
1470
+ let offset = 0;
1471
+ while (offset < chunk.length) {
1472
+ if (this.body === void 0) {
1473
+ const count = Math.min(8 - this.headerBytes, chunk.length - offset);
1474
+ chunk.copy(this.header, this.headerBytes, offset, offset + count);
1475
+ offset += count;
1476
+ this.headerBytes += count;
1477
+ if (this.headerBytes !== 8) continue;
1478
+ this.jsonBytes = this.header.readUInt32BE(0);
1479
+ const pixels = this.header.readUInt32BE(4);
1480
+ if (this.jsonBytes < 1 || this.jsonBytes > this.maxControlBytes || pixels > this.maxPixelBytes) throw new RangeError("Native editor returned an invalid frame length.");
1481
+ this.body = Buffer.allocUnsafe(this.jsonBytes + pixels);
1482
+ this.bodyBytes = 0;
1483
+ }
1484
+ const count = Math.min(this.body.length - this.bodyBytes, chunk.length - offset);
1485
+ chunk.copy(this.body, this.bodyBytes, offset, offset + count);
1486
+ offset += count;
1487
+ this.bodyBytes += count;
1488
+ if (this.bodyBytes !== this.body.length) continue;
1489
+ const value = JSON.parse(this.body.toString("utf8", 0, this.jsonBytes));
1490
+ if (typeof value !== "object" || value === null || Array.isArray(value)) throw new Error("Invalid editor control record.");
1491
+ const frame = {
1492
+ control: value,
1493
+ pixels: this.body.subarray(this.jsonBytes)
1494
+ };
1495
+ this.headerBytes = 0;
1496
+ this.body = void 0;
1497
+ this.receive(frame);
1498
+ }
1499
+ }
1500
+ /** Reject truncated records when stdout closes. */
1501
+ finish() {
1502
+ if (this.headerBytes !== 0 || this.body !== void 0) throw new Error("Native editor closed during a frame.");
1503
+ }
1504
+ };
1505
+ /** Read an integer from the native process, rejecting invalid counters and dimensions. */
1506
+ function editorInteger(control, key, minimum = 0) {
1507
+ const value = control[key];
1508
+ if (typeof value !== "number" || !Number.isSafeInteger(value) || value < minimum) throw new Error(`Invalid editor response field: ${key}.`);
1509
+ return value;
1510
+ }
1511
+ /** Validate straight RGBA and retain the reader-owned buffer without copying its pixels. */
1512
+ function decodeEditorPixels({ control: c, pixels }) {
1513
+ const width = editorInteger(c, "pixelWidth", 1), height = editorInteger(c, "pixelHeight", 1);
1514
+ if (width > 4096 || height > 4096 || pixels.length !== width * height * 4 || c.pixelFormat !== "rgba-straight") throw new Error("Invalid native editor pixel result.");
1515
+ return {
1516
+ width,
1517
+ height,
1518
+ pixels: new Uint8Array(pixels.buffer, pixels.byteOffset, pixels.byteLength),
1519
+ revision: editorInteger(c, "revision"),
1520
+ ...c.part === void 0 ? {} : { part: editorInteger(c, "part") },
1521
+ ...c.ended === void 0 ? {} : { ended: c.ended === true }
1522
+ };
1523
+ }
1524
+ //#endregion
1525
+ //#region lib/types/editor-transport.js
1526
+ /** Owns one isolated native process and settles every request on cancellation, timeout, or exit. */
1527
+ /** Process-private request multiplexer; the public editor serializes operations before submitting. */
1528
+ var EditorTransport = class {
1529
+ timeoutMs;
1530
+ signal;
1531
+ onProgress;
1532
+ child;
1533
+ pending = /* @__PURE__ */ new Map();
1534
+ ready = Promise.withResolvers();
1535
+ exited = Promise.withResolvers();
1536
+ listeners = /* @__PURE__ */ new Set();
1537
+ failure;
1538
+ sequence = 0;
1539
+ stderr = "";
1540
+ closing = false;
1541
+ initialized = false;
1542
+ abort;
1543
+ startupTimer;
1544
+ constructor(executable, args, env, timeoutMs, maxPixelBytes, signal, maxControlBytes = 1048576, source, onProgress) {
1545
+ this.timeoutMs = timeoutMs;
1546
+ this.signal = signal;
1547
+ this.onProgress = onProgress;
1548
+ signal.throwIfAborted();
1549
+ this.child = spawnNative(executable, args, env);
1550
+ const reader = new EditorFrameReader(maxPixelBytes, (frame) => this.receive(frame), maxControlBytes);
1551
+ this.child.stdout.on("data", (chunk) => {
1552
+ try {
1553
+ reader.push(chunk);
1554
+ } catch (error) {
1555
+ this.fail(error instanceof Error ? error : new Error(String(error)));
1556
+ }
1557
+ });
1558
+ this.child.stderr.setEncoding("utf8");
1559
+ let diagnosticPending = "";
1560
+ this.child.stderr.on("data", (chunk) => {
1561
+ this.stderr = (this.stderr + chunk).slice(-65536);
1562
+ if (env.OFFICE_GRAPHITE_DIAGNOSTICS !== "1" && env.OFFICE_LOAD_DIAGNOSTICS !== "1") return;
1563
+ const lines = (diagnosticPending + chunk).split("\n");
1564
+ diagnosticPending = lines.pop().slice(-65536);
1565
+ for (const raw of lines) {
1566
+ const line = raw.replace(/\r$/, "");
1567
+ const graphite = env.OFFICE_GRAPHITE_DIAGNOSTICS === "1" && (line.startsWith("officeGraphiteFrame {") || /^office(?:Graphite|Ganesh) (?:[A-Za-z]+=\d+ ?)+$/.test(line));
1568
+ const loading = env.OFFICE_LOAD_DIAGNOSTICS === "1" && line.startsWith("officeLoad ");
1569
+ if (line.length <= 65536 && (graphite || loading)) process.stderr.write(`${line}\n`);
1570
+ }
1571
+ });
1572
+ this.child.stdin.on("error", (error) => this.fail(error));
1573
+ this.child.on("error", (error) => this.fail(error));
1574
+ this.child.once("close", (code) => {
1575
+ try {
1576
+ reader.finish();
1577
+ } catch (error) {
1578
+ this.fail(error instanceof Error ? error : new Error(String(error)));
1579
+ }
1580
+ if (!this.closing || this.pending.size > 0 || code !== 0) this.fail(/* @__PURE__ */ new Error(`Native editor exited (${code}). ${this.stderr}`));
1581
+ clearTimeout(this.startupTimer);
1582
+ this.signal.removeEventListener("abort", this.abort);
1583
+ this.exited.resolve();
1584
+ });
1585
+ this.abort = () => this.fail(signal.reason instanceof Error ? signal.reason : /* @__PURE__ */ new Error("Editor cancelled."));
1586
+ signal.addEventListener("abort", this.abort, { once: true });
1587
+ this.startupTimer = setTimeout(() => this.fail(/* @__PURE__ */ new Error("Native editor initialization timed out.")), timeoutMs);
1588
+ if (source) this.child.stdin.write(source, (error) => {
1589
+ if (error) this.fail(error);
1590
+ });
1591
+ }
1592
+ fail(error) {
1593
+ if (this.failure) return;
1594
+ this.failure = error;
1595
+ clearTimeout(this.startupTimer);
1596
+ this.ready.reject(error);
1597
+ for (const pending of this.pending.values()) {
1598
+ clearTimeout(pending.timer);
1599
+ pending.reject(error);
1600
+ }
1601
+ this.pending.clear();
1602
+ this.child.kill("SIGKILL");
1603
+ this.emit({
1604
+ kind: "failure",
1605
+ error
1606
+ });
1607
+ }
1608
+ emit(event) {
1609
+ for (const listener of this.listeners) try {
1610
+ listener(event);
1611
+ } catch (error) {
1612
+ process.emitWarning(error instanceof Error ? error : String(error));
1613
+ }
1614
+ }
1615
+ receive(frame) {
1616
+ const c = frame.control;
1617
+ if (c.kind === "loading") {
1618
+ if (c.stage !== "document" || frame.pixels.length !== 0 || this.initialized) throw new Error("Invalid native loading stage.");
1619
+ try {
1620
+ this.onProgress?.(c.stage);
1621
+ } catch (error) {
1622
+ process.emitWarning(error instanceof Error ? error : String(error));
1623
+ }
1624
+ return;
1625
+ }
1626
+ if (c.kind === "event" && Number.isSafeInteger(c.type) && typeof c.payload === "string" && frame.pixels.length === 0) {
1627
+ this.emit({
1628
+ kind: "callback",
1629
+ type: c.type,
1630
+ payload: c.payload
1631
+ });
1632
+ return;
1633
+ }
1634
+ if (c.kind === "revision" && Number.isSafeInteger(c.revision) && c.revision >= 0 && frame.pixels.length === 0) {
1635
+ this.emit({
1636
+ kind: "revision",
1637
+ revision: c.revision
1638
+ });
1639
+ return;
1640
+ }
1641
+ if (c.kind === "presentation" && Number.isSafeInteger(c.part) && c.part >= 0 && typeof c.ended === "boolean" && frame.pixels.length === 0) {
1642
+ this.emit({
1643
+ kind: "presentation",
1644
+ part: c.part,
1645
+ ended: c.ended
1646
+ });
1647
+ return;
1648
+ }
1649
+ if (c.kind === "ready") {
1650
+ if (c.protocol !== 4 || c.nativeRenderProtocol !== 1 || frame.pixels.length !== 0) throw new Error("Native editor requires editor protocol 4 and native render protocol 1.");
1651
+ this.initialized = true;
1652
+ clearTimeout(this.startupTimer);
1653
+ this.ready.resolve(frame);
1654
+ return;
1655
+ }
1656
+ if (c.kind !== "reply" || typeof c.id !== "number" || typeof c.ok !== "boolean") throw new Error("Invalid native editor reply.");
1657
+ const pending = this.pending.get(c.id);
1658
+ if (!pending) throw new Error("Native editor replied to an unknown request.");
1659
+ this.pending.delete(c.id);
1660
+ clearTimeout(pending.timer);
1661
+ if (c.ok) pending.resolve(frame);
1662
+ else pending.reject(new Error(typeof c.error === "string" ? c.error : "Native editor operation failed."));
1663
+ }
1664
+ /** Actual owned native process; never supplied by a renderer. */
1665
+ get processId() {
1666
+ if (this.child.pid === void 0) throw new Error("Native editor process has not started.");
1667
+ return this.child.pid;
1668
+ }
1669
+ /** Wait for document initialization; failure still requires close() to join cleanup. */
1670
+ opened() {
1671
+ return this.ready.promise;
1672
+ }
1673
+ /** Subscribe until disposed; observers must not throw. */
1674
+ onEvent(listener) {
1675
+ this.listeners.add(listener);
1676
+ return () => this.listeners.delete(listener);
1677
+ }
1678
+ /** Submit a bounded operation; a timeout terminates the session because edit completion is then uncertain. */
1679
+ request(control) {
1680
+ if (this.failure) return Promise.reject(this.failure);
1681
+ if (this.closing) return Promise.reject(/* @__PURE__ */ new Error("Editor is closing."));
1682
+ const id = ++this.sequence;
1683
+ const bytes = encodeEditorRequest({
1684
+ ...control,
1685
+ id
1686
+ });
1687
+ return new Promise((resolve, reject) => {
1688
+ const timer = setTimeout(() => this.fail(/* @__PURE__ */ new Error("Native editor operation timed out.")), this.timeoutMs);
1689
+ this.pending.set(id, {
1690
+ resolve,
1691
+ reject,
1692
+ timer
1693
+ });
1694
+ this.child.stdin.write(bytes, (error) => {
1695
+ if (error) this.fail(error);
1696
+ });
1697
+ });
1698
+ }
1699
+ /** Graceful EOF or forced termination; resolves only after the OS closes the process streams. */
1700
+ async close() {
1701
+ this.closing = true;
1702
+ this.child.stdin.end();
1703
+ const timer = setTimeout(() => this.child.kill("SIGKILL"), this.timeoutMs);
1704
+ try {
1705
+ await this.exited.promise;
1706
+ } finally {
1707
+ clearTimeout(timer);
1708
+ this.listeners.clear();
1709
+ }
1710
+ }
1711
+ };
1712
+ //#endregion
1713
+ //#region lib/types/editor.js
1714
+ /** Native, one-process-per-document editing. Batch conversion and Web WASM APIs are independent. */
1715
+ function info({ control: c }) {
1716
+ const type = c.documentType;
1717
+ if (type !== 0 && type !== 1 && type !== 2) throw new Error("Unsupported native editor document type.");
1718
+ if (c.renderBackend !== "ganesh" && c.renderBackend !== "graphite" && c.renderBackend !== "raster") throw new Error("Invalid native editor rendering backend.");
1719
+ if (typeof c.rectangles !== "string" || !Array.isArray(c.parts) || c.parts.length < 1 || c.parts.length > 1e4) throw new Error("Invalid native editor document geometry.");
1720
+ const parts = c.parts.map((part) => {
1721
+ if (typeof part !== "object" || part === null || !("index" in part) || !("name" in part) || typeof part.index !== "number" || !Number.isSafeInteger(part.index) || part.index < 0 || typeof part.name !== "string") throw new Error("Invalid native editor part.");
1722
+ return {
1723
+ index: part.index,
1724
+ name: part.name
1725
+ };
1726
+ });
1727
+ return {
1728
+ documentType: type === 0 ? "text" : type === 1 ? "spreadsheet" : "presentation",
1729
+ width: editorInteger(c, "width", 1),
1730
+ height: editorInteger(c, "height", 1),
1731
+ part: editorInteger(c, "part"),
1732
+ rectangles: c.rectangles,
1733
+ parts,
1734
+ renderBackend: c.renderBackend
1735
+ };
1736
+ }
1737
+ function surfaceResult(frame) {
1738
+ const c = frame.control;
1739
+ if (frame.pixels.byteLength !== 0 || c.shared !== true || typeof c.requestId !== "string") throw new Error("Invalid native shared surface reply.");
1740
+ return {
1741
+ shared: true,
1742
+ requestId: c.requestId,
1743
+ width: editorInteger(c, "width", 1),
1744
+ height: editorInteger(c, "height", 1),
1745
+ revision: editorInteger(c, "revision"),
1746
+ ...c.part === void 0 ? {} : { part: editorInteger(c, "part") },
1747
+ ...c.ended === void 0 ? {} : { ended: c.ended === true }
1748
+ };
1749
+ }
1750
+ const snapshots = new FontSnapshotState();
1751
+ const readCommands = /* @__PURE__ */ new Set([
1752
+ "SelectAll",
1753
+ "GoToStartOfDoc",
1754
+ "GoToEndOfDoc",
1755
+ "GoToCell",
1756
+ "Copy"
1757
+ ]);
1758
+ /**
1759
+ * Open an isolated native document from an owned, seekable memory stream, preparing its fonts.
1760
+ * @param request - Validated-format bytes and explicit editing permission.
1761
+ * @returns A live document; the caller must close it even after process failure.
1762
+ * @throws If the matching native engine is missing, the input is invalid, or opening times out.
1763
+ */
1764
+ async function openDocument(request) {
1765
+ if (![
1766
+ "docx",
1767
+ "xlsx",
1768
+ "pptx"
1769
+ ].includes(request.format)) throw new TypeError("Native editing requires DOCX, XLSX, or PPTX.");
1770
+ const progress = (stage) => {
1771
+ try {
1772
+ request.onProgress?.(stage);
1773
+ } catch (error) {
1774
+ process.emitWarning(error instanceof Error ? error : String(error));
1775
+ }
1776
+ };
1777
+ const options = resolveOptions(request.options);
1778
+ if (!(request.bytes instanceof Uint8Array) || request.bytes.byteLength < 1 || request.bytes.byteLength > options.maxInputBytes) throw new RangeError("Editor input exceeds maxInputBytes or is empty.");
1779
+ const renderBackend = request.renderBackend ?? "auto";
1780
+ const graphiteCacheBytes = request.graphiteCacheBytes ?? 134217728;
1781
+ if (!Number.isSafeInteger(graphiteCacheBytes) || graphiteCacheBytes < 2) throw new RangeError("Graphite cache budget must be an integer of at least two bytes.");
1782
+ if (renderBackend !== "auto" && renderBackend !== "ganesh" && renderBackend !== "graphite" && renderBackend !== "raster") throw new TypeError("Unsupported native render backend.");
1783
+ const source = Buffer.from(request.bytes);
1784
+ const writable = request.writable === true;
1785
+ const lifetime = new AbortController();
1786
+ const signal = request.signal ? AbortSignal.any([request.signal, lifetime.signal]) : lifetime.signal;
1787
+ signal.throwIfAborted();
1788
+ const engine = await resolveEngine();
1789
+ if (engine.backend !== "native" || engine.legacyInputPath) throw new Error("Native editing requires a preview-capable native engine package.");
1790
+ const scratch = await mkdtemp(join(tmpdir(), "libreoffice-editor-"));
1791
+ let transport;
1792
+ let prepared;
1793
+ try {
1794
+ progress("fonts");
1795
+ const metadata = inspectDocument(source, request.format, options);
1796
+ const profile = join(scratch, "profile"), fontsDirectory = join(scratch, "fonts");
1797
+ await Promise.all([mkdir(profile, { mode: 448 }), mkdir(fontsDirectory, { mode: 448 })]);
1798
+ const fonts = createFontLoader(options, metadata, (name, bytes) => {
1799
+ const path = join(fontsDirectory, name);
1800
+ writeFileSync(path, bytes, {
1801
+ flag: "wx",
1802
+ mode: 384
1803
+ });
1804
+ return path;
1805
+ }, (await snapshots.acquire(options, signal)).faces);
1806
+ preloadFonts(fonts, options, metadata, true);
1807
+ await prepareNativeFontProfile(profile, fonts.substitutions);
1808
+ progress("engine");
1809
+ prepared = await prepareNativeEngine(engine, profile);
1810
+ const selected = prepared.engine;
1811
+ transport = new EditorTransport(selected.executable, [
1812
+ "--operation",
1813
+ "edit",
1814
+ "--program-directory",
1815
+ selected.programDirectory,
1816
+ "--render-backend",
1817
+ renderBackend,
1818
+ "--graphite-cache-bytes",
1819
+ String(graphiteCacheBytes),
1820
+ "--input-bytes",
1821
+ String(source.byteLength),
1822
+ "--input-format",
1823
+ request.format,
1824
+ "--scratch-directory",
1825
+ scratch,
1826
+ "--profile-directory",
1827
+ profile,
1828
+ "--writable",
1829
+ String(writable),
1830
+ "--max-output-bytes",
1831
+ String(options.maxOutputBytes),
1832
+ "--max-image-resolution",
1833
+ String(options.maxImageResolution),
1834
+ ...fonts.files.flatMap((path) => ["--font-file", path])
1835
+ ], nativeEnvironment(profile, selected.programDirectory), options.timeoutMs, Math.min(options.maxOutputBytes, 67108864), signal, Math.max(1048576, options.maxOutputBytes), source, progress);
1836
+ const process = transport;
1837
+ const initialInfo = info(await process.opened());
1838
+ let revision = 0, closing = false, disposal, queuedBytes = 0;
1839
+ let tail = Promise.resolve();
1840
+ const listeners = /* @__PURE__ */ new Set();
1841
+ const emit = (event) => {
1842
+ for (const listener of listeners) try {
1843
+ listener(event);
1844
+ } catch (error) {
1845
+ globalThis.process.emitWarning(error instanceof Error ? error : String(error));
1846
+ }
1847
+ };
1848
+ const observeRevision = (next) => {
1849
+ if (next <= revision) return;
1850
+ revision = next;
1851
+ emit({
1852
+ kind: "revision",
1853
+ revision
1854
+ });
1855
+ };
1856
+ process.onEvent((event) => {
1857
+ if (event.kind === "revision") observeRevision(event.revision);
1858
+ else emit(event);
1859
+ });
1860
+ const call = async (control) => {
1861
+ const frame = await process.request(control);
1862
+ observeRevision(editorInteger(frame.control, "revision"));
1863
+ return frame;
1864
+ };
1865
+ const enqueue = (size, operation) => {
1866
+ if (closing) return Promise.reject(/* @__PURE__ */ new Error("Editor is closing."));
1867
+ if (queuedBytes + size > 8388608) return Promise.reject(/* @__PURE__ */ new Error("Editor input queue is full."));
1868
+ queuedBytes += size;
1869
+ const result = tail.then(operation).finally(() => {
1870
+ queuedBytes -= size;
1871
+ });
1872
+ tail = result.catch(() => {});
1873
+ return result;
1874
+ };
1875
+ const execute = (control) => enqueue(Buffer.byteLength(JSON.stringify(control)), () => call(control));
1876
+ const requireWritable = () => {
1877
+ if (!writable) throw new Error("Document is read-only.");
1878
+ };
1879
+ return {
1880
+ initialInfo,
1881
+ missingFonts: fonts.missingFonts,
1882
+ writable,
1883
+ processId: process.processId,
1884
+ async attachSurfaceTransport(endpoint) {
1885
+ await execute({
1886
+ op: "attachSurfaceTransport",
1887
+ endpoint
1888
+ });
1889
+ },
1890
+ async detachSurfaceTransport() {
1891
+ await execute({ op: "detachSurfaceTransport" });
1892
+ },
1893
+ async waitForInput(sequence) {
1894
+ await execute({
1895
+ op: "inputBarrier",
1896
+ sequence
1897
+ });
1898
+ },
1899
+ async renderSurface(rectangle, pixelWidth, pixelHeight, surface) {
1900
+ return surfaceResult(await execute({
1901
+ ...rectangle,
1902
+ op: "paintSurface",
1903
+ pixelWidth,
1904
+ pixelHeight,
1905
+ surface
1906
+ }));
1907
+ },
1908
+ async presentationSurface(surface) {
1909
+ return surfaceResult(await execute({
1910
+ op: "presentationSurface",
1911
+ surface
1912
+ }));
1913
+ },
1914
+ get revision() {
1915
+ return revision;
1916
+ },
1917
+ onEvent(listener) {
1918
+ listeners.add(listener);
1919
+ return () => listeners.delete(listener);
1920
+ },
1921
+ async getInfo() {
1922
+ return info(await execute({ op: "info" }));
1923
+ },
1924
+ async dispatch(command, arguments_ = {}) {
1925
+ if (!readCommands.has(command)) requireWritable();
1926
+ await execute({
1927
+ op: "command",
1928
+ command: `.uno:${command}`,
1929
+ arguments: JSON.stringify(arguments_)
1930
+ });
1931
+ },
1932
+ async input(event) {
1933
+ const navigation = event.op === "key" && event.character === 0 && [
1934
+ 1024,
1935
+ 1025,
1936
+ 1026,
1937
+ 1027,
1938
+ 1028,
1939
+ 1029,
1940
+ 1030,
1941
+ 1031,
1942
+ 1281,
1943
+ 1282
1944
+ ].includes(event.key & 4095);
1945
+ if (event.op !== "mouse" && !navigation) requireWritable();
1946
+ await execute(event);
1947
+ },
1948
+ async setViewport(viewport) {
1949
+ await execute({
1950
+ ...viewport,
1951
+ op: "viewport"
1952
+ });
1953
+ },
1954
+ async setPart(part) {
1955
+ return info(await execute({
1956
+ op: "part",
1957
+ part
1958
+ }));
1959
+ },
1960
+ async render(rectangle, pixelWidth, pixelHeight) {
1961
+ return decodeEditorPixels(await execute({
1962
+ ...rectangle,
1963
+ op: "paint",
1964
+ pixelWidth,
1965
+ pixelHeight
1966
+ }));
1967
+ },
1968
+ async getSelection(mime) {
1969
+ const frame = await execute({
1970
+ op: "selection",
1971
+ mime
1972
+ });
1973
+ if (typeof frame.control.text !== "string") throw new Error("Invalid native selection result.");
1974
+ return frame.control.text;
1975
+ },
1976
+ async getValues(command, area) {
1977
+ const frame = await execute({
1978
+ ...area,
1979
+ op: "values",
1980
+ command: `.uno:${command}`
1981
+ });
1982
+ if (typeof frame.control.value !== "string") throw new Error("Invalid native command result.");
1983
+ return frame.control.value;
1984
+ },
1985
+ async presentation(control) {
1986
+ await execute({
1987
+ ...control,
1988
+ op: "presentation"
1989
+ });
1990
+ },
1991
+ async presentationFrame() {
1992
+ return decodeEditorPixels(await execute({
1993
+ op: "presentation",
1994
+ action: "frame"
1995
+ }));
1996
+ },
1997
+ async exportSnapshot() {
1998
+ requireWritable();
1999
+ return enqueue(0, async () => {
2000
+ const path = join(scratch, `${randomUUID()}.${request.format}`);
2001
+ try {
2002
+ const frame = await call({
2003
+ op: "save",
2004
+ path,
2005
+ url: pathToFileURL(path).href,
2006
+ format: request.format
2007
+ });
2008
+ const bytes = await readFile(path);
2009
+ if (bytes.length > options.maxOutputBytes) throw new Error("Editor snapshot exceeds maxOutputBytes.");
2010
+ inspectDocument(bytes, request.format, options);
2011
+ return {
2012
+ bytes,
2013
+ format: request.format,
2014
+ revision: editorInteger(frame.control, "revision")
2015
+ };
2016
+ } finally {
2017
+ await rm(path, { force: true });
2018
+ }
2019
+ });
2020
+ },
2021
+ close() {
2022
+ disposal ??= (async () => {
2023
+ closing = true;
2024
+ await tail;
2025
+ try {
2026
+ await process.close();
2027
+ } finally {
2028
+ lifetime.abort();
2029
+ listeners.clear();
2030
+ try {
2031
+ await prepared?.release();
2032
+ } finally {
2033
+ await rm(scratch, {
2034
+ recursive: true,
2035
+ force: true
2036
+ });
2037
+ }
2038
+ }
2039
+ })();
2040
+ return disposal;
2041
+ }
2042
+ };
2043
+ } catch (error) {
2044
+ lifetime.abort(error);
2045
+ try {
2046
+ await transport?.close();
2047
+ } finally {
2048
+ try {
2049
+ await prepared?.release();
2050
+ } finally {
2051
+ await rm(scratch, {
2052
+ recursive: true,
2053
+ force: true
2054
+ });
2055
+ }
2056
+ }
2057
+ throw error;
2058
+ }
2059
+ }
2060
+ //#endregion
2061
+ export { openDocument };