@deepseek-ai/libreoffice-kit 0.1.2 → 0.1.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/cli.js CHANGED
@@ -2,11 +2,14 @@
2
2
  import { createRequire } from "node:module";
3
3
  import { parseArgs } from "node:util";
4
4
  import { dirname, extname, isAbsolute, join, posix, relative, resolve, sep, win32 } from "node:path";
5
- import { constants, lstatSync, readdirSync } from "node:fs";
6
- import { lstat, mkdir, mkdtemp, open, readFile, rm, stat, unlink, writeFile } from "node:fs/promises";
5
+ import { closeSync, constants, createWriteStream, lstatSync, readSync, readdirSync } from "node:fs";
6
+ import { copyFile, lstat, mkdir, mkdtemp, open, readFile, rm, stat, symlink, unlink, writeFile } from "node:fs/promises";
7
7
  import { homedir, tmpdir } from "node:os";
8
8
  import { Worker } from "node:worker_threads";
9
9
  import { spawn } from "node:child_process";
10
+ import { EventEmitter } from "node:events";
11
+ import { Readable } from "node:stream";
12
+ import { finished } from "node:stream/promises";
10
13
  import { createHash, randomUUID } from "node:crypto";
11
14
  import { createInterface } from "node:readline";
12
15
  import { zlibSync } from "fflate";
@@ -317,6 +320,164 @@ function selectedPages(pages, count, limit) {
317
320
  return result;
318
321
  }
319
322
  //#endregion
323
+ //#region lib/types/native-process.js
324
+ /** Native helper stdio; Windows anonymous pipes retain the caller's restricted-token permissions. */
325
+ function windowsPipes() {
326
+ const koffi = createRequire(import.meta.url)("koffi");
327
+ const kernel = koffi.load("kernel32.dll"), node = koffi.load(null);
328
+ const createPipe = kernel.func("int __stdcall CreatePipe(_Out_ void **read, _Out_ void **write, void *attributes, uint32 size)");
329
+ const closeHandle = kernel.func("int __stdcall CloseHandle(void *handle)");
330
+ const peek = kernel.func("int __stdcall PeekNamedPipe(void *pipe, void *buffer, uint32 size, void *read, _Out_ uint32 *available, void *remaining)");
331
+ const lastError = kernel.func("uint32 __stdcall GetLastError()");
332
+ const openFd = node.func("int uv_open_osfhandle(void *handle)");
333
+ function pipe() {
334
+ const reads = [null], writes = [null];
335
+ if (!createPipe(reads, writes, null, 0)) throw new Error(`CreatePipe failed: ${lastError()}`);
336
+ const read = openFd(reads[0]);
337
+ if (read < 0) {
338
+ closeHandle(reads[0]);
339
+ closeHandle(writes[0]);
340
+ throw new Error("Cannot open anonymous input descriptor");
341
+ }
342
+ const write = openFd(writes[0]);
343
+ if (write < 0) {
344
+ closeSync(read);
345
+ closeHandle(writes[0]);
346
+ throw new Error("Cannot open anonymous output descriptor");
347
+ }
348
+ let timer;
349
+ let ended = false;
350
+ const readable = new Readable({
351
+ read() {
352
+ if (timer === void 0 && !ended) poll();
353
+ },
354
+ destroy(error, callback) {
355
+ ended = true;
356
+ clearTimeout(timer);
357
+ try {
358
+ closeSync(read);
359
+ callback(error);
360
+ } catch (cause) {
361
+ callback(error ?? cause);
362
+ }
363
+ }
364
+ });
365
+ function poll() {
366
+ timer = void 0;
367
+ try {
368
+ const available = [0];
369
+ if (!peek(reads[0], null, 0, null, available, null)) {
370
+ const code = lastError();
371
+ if (code !== 109) throw new Error(`PeekNamedPipe failed: ${code}`);
372
+ ended = true;
373
+ readable.push(null);
374
+ return;
375
+ }
376
+ if (available[0] > 0) {
377
+ const buffer = Buffer.allocUnsafe(Math.min(available[0], 65536));
378
+ const count = readSync(read, buffer, 0, buffer.length, null);
379
+ if (!readable.push(buffer.subarray(0, count))) return;
380
+ }
381
+ timer = setTimeout(poll, 5);
382
+ } catch (error) {
383
+ readable.destroy(error);
384
+ }
385
+ }
386
+ return {
387
+ read,
388
+ write,
389
+ readable
390
+ };
391
+ }
392
+ return { pipe };
393
+ }
394
+ /**
395
+ * Spawn with inherited token and Job restrictions; pipe creation never requests a new sandbox policy.
396
+ * @param executable - Verified native helper executable.
397
+ * @param args - Helper protocol arguments.
398
+ * @param env - Filtered operation environment.
399
+ * @returns Helper streams and process lifetime, with output drained before close.
400
+ */
401
+ function spawnNative(executable, args, env) {
402
+ if (process.platform !== "win32") return spawn(executable, args, {
403
+ stdio: "pipe",
404
+ windowsHide: true,
405
+ env
406
+ });
407
+ const { pipe } = windowsPipes();
408
+ const owned = [];
409
+ let child;
410
+ try {
411
+ const input = pipe();
412
+ owned.push(input);
413
+ const output = pipe();
414
+ owned.push(output);
415
+ const error = pipe();
416
+ owned.push(error);
417
+ child = spawn(executable, args, {
418
+ stdio: [
419
+ input.read,
420
+ output.write,
421
+ error.write
422
+ ],
423
+ windowsHide: true,
424
+ env
425
+ });
426
+ } catch (error) {
427
+ for (const entry of owned) {
428
+ entry.readable.destroy();
429
+ closeSync(entry.write);
430
+ }
431
+ throw error;
432
+ }
433
+ const [input, output, error] = owned;
434
+ input.readable.destroy();
435
+ closeSync(output.write);
436
+ closeSync(error.write);
437
+ const stdin = createWriteStream("", {
438
+ fd: input.write,
439
+ autoClose: true
440
+ });
441
+ const helper = new class extends EventEmitter {
442
+ stdin = stdin;
443
+ stdout = output.readable;
444
+ stderr = error.readable;
445
+ get exitCode() {
446
+ return child.exitCode;
447
+ }
448
+ get signalCode() {
449
+ return child.signalCode;
450
+ }
451
+ kill(signal) {
452
+ return child.kill(signal);
453
+ }
454
+ }();
455
+ let failure;
456
+ const fail = (cause) => {
457
+ failure ??= cause;
458
+ child.kill("SIGKILL");
459
+ };
460
+ stdin.on("error", fail);
461
+ output.readable.on("error", fail);
462
+ error.readable.on("error", fail);
463
+ const drained = Promise.allSettled([
464
+ finished(stdin),
465
+ finished(output.readable),
466
+ finished(error.readable)
467
+ ]);
468
+ child.once("error", (cause) => {
469
+ failure ??= cause;
470
+ });
471
+ child.once("close", (code, signal) => {
472
+ stdin.destroy();
473
+ drained.then(() => {
474
+ if (failure !== void 0) helper.emit("error", failure);
475
+ helper.emit("close", code, signal);
476
+ });
477
+ });
478
+ return helper;
479
+ }
480
+ //#endregion
320
481
  //#region lib/types/profile.js
321
482
  /** Private headless profile used by both native and WASM conversions. */
322
483
  /**
@@ -561,6 +722,30 @@ function nativeEnvironment(profile, programDirectory, source = process.env, plat
561
722
  });
562
723
  }
563
724
  /**
725
+ * Keep Windows engine resources reachable through a short profile-owned path until the helper exits.
726
+ * @param engine - Verified engine installation; its resources remain in place.
727
+ * @param profile - Private operation directory that owns the temporary executable and junction.
728
+ * @param run - Operation that settles only after its helper closes.
729
+ * @returns The operation result after removing the resource junction.
730
+ */
731
+ async function withNativeEngine(engine, profile, run) {
732
+ if (process.platform !== "win32" || engine.executable.length < 260 && engine.programDirectory.length < 260) return run(engine);
733
+ const root = join(profile, "engine");
734
+ await symlink(engine.root, root, "junction");
735
+ try {
736
+ const executable = join(profile, "libreoffice-kit.exe");
737
+ await copyFile(engine.executable, executable, constants.COPYFILE_EXCL);
738
+ return await run({
739
+ ...engine,
740
+ root,
741
+ executable,
742
+ programDirectory: join(root, relative(engine.root, engine.programDirectory))
743
+ });
744
+ } finally {
745
+ await unlink(root);
746
+ }
747
+ }
748
+ /**
564
749
  * Run one native conversion and await bounded result transport.
565
750
  * @param engine - Resolved native engine installation.
566
751
  * @param options - Validated conversion limits.
@@ -580,77 +765,73 @@ async function runNative(engine, options, input, output, profile, fonts, substit
580
765
  signal.throwIfAborted();
581
766
  await prepareNativeFontProfile(profile, substitutions);
582
767
  signal.throwIfAborted();
583
- const env = nativeEnvironment(profile, engine.programDirectory);
584
- const child = spawn(engine.executable, [
585
- "--program-directory",
586
- engine.programDirectory,
587
- "--input-path",
588
- input,
589
- "--output-path",
590
- output,
591
- "--profile-directory",
592
- profile,
593
- "--max-output-bytes",
594
- String(options.maxOutputBytes),
595
- "--max-image-resolution",
596
- String(options.maxImageResolution),
597
- "--format",
598
- operation.format,
599
- "--recalculate",
600
- String(operation.recalculate),
601
- ...operation.sheet === void 0 ? [] : ["--sheet", operation.sheet],
602
- ...fonts.flatMap((path) => ["--font-file", path])
603
- ], {
604
- stdio: [
605
- "ignore",
606
- "pipe",
607
- "pipe"
608
- ],
609
- windowsHide: true,
610
- env
611
- });
612
- let stdout = "";
613
- let stderr = "";
614
- let failure;
615
- const abort = () => {
616
- failure ??= signal.reason;
617
- child.kill("SIGKILL");
618
- };
619
- signal.addEventListener("abort", abort, { once: true });
620
- child.stdout.setEncoding("utf8");
621
- child.stderr.setEncoding("utf8");
622
- child.stdout.on("data", (chunk) => {
623
- stdout += chunk;
624
- if (stdout.length > 65536) {
625
- failure ??= /* @__PURE__ */ new Error("LibreOffice helper exceeded its response limit.");
768
+ return withNativeEngine(engine, profile, async (engine) => {
769
+ signal.throwIfAborted();
770
+ const env = nativeEnvironment(profile, engine.programDirectory);
771
+ const child = spawnNative(engine.executable, [
772
+ "--program-directory",
773
+ engine.programDirectory,
774
+ "--input-path",
775
+ input,
776
+ "--output-path",
777
+ output,
778
+ "--profile-directory",
779
+ profile,
780
+ "--max-output-bytes",
781
+ String(options.maxOutputBytes),
782
+ "--max-image-resolution",
783
+ String(options.maxImageResolution),
784
+ "--format",
785
+ operation.format,
786
+ "--recalculate",
787
+ String(operation.recalculate),
788
+ ...operation.sheet === void 0 ? [] : ["--sheet", operation.sheet],
789
+ ...fonts.flatMap((path) => ["--font-file", path])
790
+ ], env);
791
+ child.stdin.end();
792
+ let stdout = "";
793
+ let stderr = "";
794
+ let failure;
795
+ const abort = () => {
796
+ failure ??= signal.reason;
626
797
  child.kill("SIGKILL");
627
- }
628
- });
629
- child.stderr.on("data", (chunk) => {
630
- stderr = (stderr + chunk).slice(-65536);
631
- });
632
- try {
633
- const code = await new Promise((resolve, reject) => {
634
- child.once("error", (error) => {
635
- failure ??= error;
636
- });
637
- child.once("close", (code, signal) => {
638
- if (signal === "SIGXFSZ") failure ??= new ConversionError("output-too-large", "LibreOffice exceeded its output file-size limit.");
639
- if (failure) reject(failure);
640
- else resolve(code);
641
- });
798
+ };
799
+ signal.addEventListener("abort", abort, { once: true });
800
+ child.stdout.setEncoding("utf8");
801
+ child.stderr.setEncoding("utf8");
802
+ child.stdout.on("data", (chunk) => {
803
+ stdout += chunk;
804
+ if (stdout.length > 65536) {
805
+ failure ??= /* @__PURE__ */ new Error("LibreOffice helper exceeded its response limit.");
806
+ child.kill("SIGKILL");
807
+ }
808
+ });
809
+ child.stderr.on("data", (chunk) => {
810
+ stderr = (stderr + chunk).slice(-65536);
642
811
  });
643
- signal.throwIfAborted();
644
- let result;
645
812
  try {
646
- result = JSON.parse(stdout);
647
- } catch (cause) {
648
- throw new Error(`LibreOffice helper returned an invalid response (exit ${code}). ${stderr}`, { cause });
813
+ const code = await new Promise((resolve, reject) => {
814
+ child.once("error", (error) => {
815
+ failure ??= error;
816
+ });
817
+ child.once("close", (code, signal) => {
818
+ if (signal === "SIGXFSZ") failure ??= new ConversionError("output-too-large", "LibreOffice exceeded its output file-size limit.");
819
+ if (failure) reject(failure);
820
+ else resolve(code);
821
+ });
822
+ });
823
+ signal.throwIfAborted();
824
+ let result;
825
+ try {
826
+ result = JSON.parse(stdout);
827
+ } catch (cause) {
828
+ throw new Error(`LibreOffice helper returned an invalid response (exit ${code}). ${stderr}`, { cause });
829
+ }
830
+ if (code !== 0 || result.ok !== true) throw new ConversionError(failureCode(result), `LibreOffice native conversion failed: ${result.error ?? stderr}`);
831
+ } finally {
832
+ signal.removeEventListener("abort", abort);
649
833
  }
650
- if (code !== 0 || result.ok !== true) throw new ConversionError(failureCode(result), `LibreOffice native conversion failed: ${result.error ?? stderr}`);
651
- } finally {
652
- signal.removeEventListener("abort", abort);
653
- }
834
+ });
654
835
  }
655
836
  //#endregion
656
837
  //#region lib/types/png.js
@@ -787,179 +968,210 @@ async function renderImagesWithNative(request) {
787
968
  signal.throwIfAborted();
788
969
  await mkdir(profile, { mode: 448 });
789
970
  await prepareNativeFontProfile(profile, substitutions);
790
- const child = spawn(engine.executable, [
791
- "--operation",
792
- "render-images",
793
- "--program-directory",
794
- engine.programDirectory,
795
- "--input-path",
796
- inputPath,
797
- "--scratch-directory",
798
- scratch,
799
- "--profile-directory",
800
- profile,
801
- "--max-output-bytes",
802
- String(options.maxOutputBytes),
803
- "--max-image-resolution",
804
- String(options.maxImageResolution),
805
- ...fonts.flatMap((path) => ["--font-file", path])
806
- ], {
807
- stdio: [
808
- "pipe",
809
- "pipe",
810
- "pipe"
811
- ],
812
- windowsHide: true,
813
- env: nativeEnvironment(profile, engine.programDirectory)
814
- });
815
- const lines = [];
816
- const waiters = [];
817
- const output = createInterface({ input: child.stdout });
818
- output.on("line", (line) => {
819
- const waiter = waiters.shift();
820
- if (waiter) waiter(line);
821
- else lines.push(line);
822
- });
823
- let stderr = "";
824
- let stopped;
825
- child.stderr.setEncoding("utf8");
826
- child.stderr.on("data", (chunk) => {
827
- stderr = (stderr + chunk).slice(-65536);
828
- });
829
- const closed = new Promise((resolve, reject) => {
830
- child.once("error", reject);
831
- child.once("close", resolve);
832
- });
833
- const abort = () => {
834
- stopped ??= signal.reason;
835
- child.kill("SIGKILL");
836
- };
837
- signal.addEventListener("abort", abort, { once: true });
838
- const next = async () => {
971
+ return withNativeEngine(engine, profile, async (engine) => {
839
972
  signal.throwIfAborted();
840
- if (lines.length > 0) return lines.shift();
841
- return new Promise((resolve, reject) => {
842
- const done = (line) => {
843
- signal.removeEventListener("abort", cancel);
844
- resolve(line);
845
- };
846
- const cancel = () => {
847
- const index = waiters.indexOf(done);
848
- if (index >= 0) waiters.splice(index, 1);
849
- reject(signal.reason);
850
- };
851
- signal.addEventListener("abort", cancel, { once: true });
852
- waiters.push(done);
973
+ const child = spawnNative(engine.executable, [
974
+ "--operation",
975
+ "render-images",
976
+ "--program-directory",
977
+ engine.programDirectory,
978
+ "--input-path",
979
+ inputPath,
980
+ "--scratch-directory",
981
+ scratch,
982
+ "--profile-directory",
983
+ profile,
984
+ "--max-output-bytes",
985
+ String(options.maxOutputBytes),
986
+ "--max-image-resolution",
987
+ String(options.maxImageResolution),
988
+ ...fonts.flatMap((path) => ["--font-file", path])
989
+ ], nativeEnvironment(profile, engine.programDirectory));
990
+ const lines = [];
991
+ const waiters = [];
992
+ const output = createInterface({ input: child.stdout });
993
+ output.on("line", (line) => {
994
+ const waiter = waiters.shift();
995
+ if (waiter) waiter(line);
996
+ else lines.push(line);
853
997
  });
854
- };
855
- const response = async () => {
856
- const line = await next();
857
- let value;
858
- try {
859
- value = JSON.parse(line);
860
- } catch (cause) {
861
- throw new Error(`LibreOffice native renderer returned invalid JSON. ${stderr}`, { cause });
862
- }
863
- if (!value.ok) throw failure(value, stderr);
864
- return value;
865
- };
866
- try {
867
- const ready = await response();
868
- if (ready.kind !== "ready") throw new Error("LibreOffice native renderer did not initialize.");
869
- const planned = plan(ready, operation);
870
- const scale = operation.dpi / 96;
871
- const selected = [];
872
- for (const region of planned.regions) if (region.sheet === void 0) selected.push(region);
873
- else {
874
- let rectangles;
998
+ let stderr = "";
999
+ let stopped;
1000
+ child.stderr.setEncoding("utf8");
1001
+ child.stderr.on("data", (chunk) => {
1002
+ stderr = (stderr + chunk).slice(-65536);
1003
+ });
1004
+ const closed = new Promise((resolve, reject) => {
1005
+ let failure;
1006
+ child.once("error", (error) => {
1007
+ failure = error;
1008
+ });
1009
+ child.once("close", (code) => {
1010
+ if (failure) reject(failure);
1011
+ else resolve(code);
1012
+ });
1013
+ });
1014
+ const abort = () => {
1015
+ stopped ??= signal.reason;
1016
+ child.kill("SIGKILL");
1017
+ };
1018
+ signal.addEventListener("abort", abort, { once: true });
1019
+ const next = async () => {
1020
+ signal.throwIfAborted();
1021
+ if (lines.length > 0) return lines.shift();
1022
+ return new Promise((resolve, reject) => {
1023
+ const done = (line) => {
1024
+ signal.removeEventListener("abort", cancel);
1025
+ resolve(line);
1026
+ };
1027
+ const fail = (error) => {
1028
+ const index = waiters.indexOf(done);
1029
+ if (index >= 0) waiters.splice(index, 1);
1030
+ signal.removeEventListener("abort", cancel);
1031
+ reject(error);
1032
+ };
1033
+ const cancel = () => {
1034
+ fail(signal.reason);
1035
+ };
1036
+ signal.addEventListener("abort", cancel, { once: true });
1037
+ waiters.push(done);
1038
+ closed.then((code) => {
1039
+ fail(/* @__PURE__ */ new Error(`LibreOffice native renderer exited ${code ?? child.signalCode} before responding. ${stderr}`));
1040
+ }, fail);
1041
+ });
1042
+ };
1043
+ const response = async () => {
1044
+ const line = await next();
1045
+ let value;
875
1046
  try {
876
- rectangles = splitRasterRectangle(region.rectangle, scale, {
877
- maxPixels: operation.maxPixels,
878
- maxDimension: operation.maxDimension,
879
- maxTiles: operation.maxPages - selected.length
880
- });
1047
+ value = JSON.parse(line);
881
1048
  } catch (cause) {
882
- throw new ConversionError("output-too-large", String(cause), { cause });
1049
+ throw new Error(`LibreOffice native renderer returned invalid JSON. ${stderr}`, { cause });
883
1050
  }
884
- selected.push(...rectangles.map((rectangle) => ({
885
- ...region,
886
- rectangle
887
- })));
888
- }
889
- for (const { page, rectangle } of selected) {
890
- const { width, height } = tileDimensions({
891
- pageIndex: 0,
892
- ...rectangle,
893
- scale
894
- }, [page]);
895
- if (width > operation.maxDimension || height > operation.maxDimension || width * height > operation.maxPixels) throw new ConversionError("output-too-large", "Selected page exceeds maxPixels or maxDimension; reduce DPI or raise the image limits.");
896
- }
897
- const images = [];
898
- let total = 0;
899
- for (const region of selected) {
900
- signal.throwIfAborted();
901
- const { width, height } = tileDimensions({
902
- pageIndex: 0,
903
- ...region.rectangle,
904
- scale
905
- }, [region.page]);
906
- const x = region.page.x + Math.round(region.rectangle.x * 15);
907
- const y = region.page.y + Math.round(region.rectangle.y * 15);
908
- const twipsWidth = Math.max(1, Math.round(region.rectangle.width * 15));
909
- const twipsHeight = Math.max(1, Math.round(region.rectangle.height * 15));
910
- const index = images.length + 1;
911
- child.stdin.write(`P ${index} ${region.page.part} ${width} ${height} ${x} ${y} ${twipsWidth} ${twipsHeight}\n`);
912
- const painted = await response();
913
- if (painted.kind !== "paint" || painted.index !== index || painted.width !== width || painted.height !== height) throw new Error("LibreOffice native renderer returned inconsistent tile metadata.");
914
- if (resolve(painted.path) !== resolve(scratch, `tile-${index}.rgba`)) throw new Error("LibreOffice native renderer returned a tile outside its scratch directory.");
915
- const raw = await readFile(painted.path);
916
- if (raw.byteLength !== width * height * 4) throw new Error("LibreOffice native renderer returned incomplete pixels.");
917
- const png = encodePng(width, height, ready.documentType === "pdf" ? new Uint8ClampedArray(raw) : rgbaPixels(raw, ready.tileMode));
918
- total += png.byteLength;
919
- if (total > options.maxOutputBytes) throw new ConversionError("output-too-large", "PNG batch exceeds maxOutputBytes.");
920
- const path = join(operation.outputDir, `page-${String(index).padStart(4, "0")}.png`);
921
- await writeFile(path, png, {
922
- flag: "wx",
923
- mode: 384
924
- });
925
- images.push({
926
- index,
927
- ...region.number === void 0 ? {} : { page: region.number },
928
- ...region.sheet === void 0 ? {} : {
929
- sheet: region.sheet,
930
- range: region.range,
931
- rtl: region.rtl
932
- },
933
- path,
934
- width,
935
- height,
936
- rectangle: region.rectangle,
937
- byteLength: png.byteLength
938
- });
939
- }
940
- child.stdin.end("DONE\n");
941
- if ((await response()).kind !== "done") throw new Error("LibreOffice native renderer did not finish.");
942
- const code = await closed;
943
- if (code !== 0) throw new Error(`LibreOffice native renderer exited ${code}. ${stderr}`);
944
- return {
945
- schemaVersion: 1,
946
- backend: "native",
947
- rasterEngine: ready.documentType === "pdf" ? "pdfium" : "libreoffice",
948
- source: "saved",
949
- inputPath: operation.inputPath,
950
- sourceSha256: createHash("sha256").update(source).digest("hex"),
951
- dpi: operation.dpi,
952
- pageCount: planned.count,
953
- images,
954
- missingFonts: [...missingFonts]
1051
+ if (!value.ok) throw failure(value, stderr);
1052
+ return value;
955
1053
  };
956
- } finally {
957
- signal.removeEventListener("abort", abort);
958
- output.close();
959
- if (child.exitCode === null) child.kill("SIGKILL");
960
- await closed.catch(() => {});
961
- if (stopped !== void 0) throw stopped;
962
- }
1054
+ try {
1055
+ const ready = await response();
1056
+ if (ready.kind !== "ready") throw new Error("LibreOffice native renderer did not initialize.");
1057
+ const planned = plan(ready, operation);
1058
+ const scale = operation.dpi / 96;
1059
+ const selected = [];
1060
+ for (const region of planned.regions) if (region.sheet === void 0) selected.push(region);
1061
+ else {
1062
+ let rectangles;
1063
+ try {
1064
+ rectangles = splitRasterRectangle(region.rectangle, scale, {
1065
+ maxPixels: operation.maxPixels,
1066
+ maxDimension: operation.maxDimension,
1067
+ maxTiles: operation.maxPages - selected.length
1068
+ });
1069
+ } catch (cause) {
1070
+ throw new ConversionError("output-too-large", String(cause), { cause });
1071
+ }
1072
+ selected.push(...rectangles.map((rectangle) => ({
1073
+ ...region,
1074
+ rectangle
1075
+ })));
1076
+ }
1077
+ for (const { page, rectangle } of selected) {
1078
+ const { width, height } = tileDimensions({
1079
+ pageIndex: 0,
1080
+ ...rectangle,
1081
+ scale
1082
+ }, [page]);
1083
+ if (width > operation.maxDimension || height > operation.maxDimension || width * height > operation.maxPixels) throw new ConversionError("output-too-large", "Selected page exceeds maxPixels or maxDimension; reduce DPI or raise the image limits.");
1084
+ }
1085
+ const images = [];
1086
+ let total = 0;
1087
+ for (const region of selected) {
1088
+ signal.throwIfAborted();
1089
+ const { width, height } = tileDimensions({
1090
+ pageIndex: 0,
1091
+ ...region.rectangle,
1092
+ scale
1093
+ }, [region.page]);
1094
+ const x = region.page.x + Math.round(region.rectangle.x * 15);
1095
+ const y = region.page.y + Math.round(region.rectangle.y * 15);
1096
+ const twipsWidth = Math.max(1, Math.round(region.rectangle.width * 15));
1097
+ const twipsHeight = Math.max(1, Math.round(region.rectangle.height * 15));
1098
+ const index = images.length + 1;
1099
+ child.stdin.write(`P ${index} ${region.page.part} ${width} ${height} ${x} ${y} ${twipsWidth} ${twipsHeight}\n`);
1100
+ const painted = await response();
1101
+ if (painted.kind !== "paint" || painted.index !== index || painted.width !== width || painted.height !== height) throw new Error("LibreOffice native renderer returned inconsistent tile metadata.");
1102
+ if (resolve(painted.path) !== resolve(scratch, `tile-${index}.rgba`)) throw new Error("LibreOffice native renderer returned a tile outside its scratch directory.");
1103
+ const raw = await readFile(painted.path);
1104
+ if (raw.byteLength !== width * height * 4) throw new Error("LibreOffice native renderer returned incomplete pixels.");
1105
+ const png = encodePng(width, height, ready.documentType === "pdf" ? new Uint8ClampedArray(raw) : rgbaPixels(raw, ready.tileMode));
1106
+ total += png.byteLength;
1107
+ if (total > options.maxOutputBytes) throw new ConversionError("output-too-large", "PNG batch exceeds maxOutputBytes.");
1108
+ const path = join(operation.outputDir, `page-${String(index).padStart(4, "0")}.png`);
1109
+ await writeFile(path, png, {
1110
+ flag: "wx",
1111
+ mode: 384
1112
+ });
1113
+ images.push({
1114
+ index,
1115
+ ...region.number === void 0 ? {} : { page: region.number },
1116
+ ...region.sheet === void 0 ? {} : {
1117
+ sheet: region.sheet,
1118
+ range: region.range,
1119
+ rtl: region.rtl
1120
+ },
1121
+ path,
1122
+ width,
1123
+ height,
1124
+ rectangle: region.rectangle,
1125
+ byteLength: png.byteLength
1126
+ });
1127
+ }
1128
+ child.stdin.end("DONE\n");
1129
+ if ((await response()).kind !== "done") throw new Error("LibreOffice native renderer did not finish.");
1130
+ const code = await closed;
1131
+ if (code !== 0) throw new Error(`LibreOffice native renderer exited ${code}. ${stderr}`);
1132
+ return {
1133
+ schemaVersion: 1,
1134
+ backend: "native",
1135
+ rasterEngine: ready.documentType === "pdf" ? "pdfium" : "libreoffice",
1136
+ source: "saved",
1137
+ inputPath: operation.inputPath,
1138
+ sourceSha256: createHash("sha256").update(source).digest("hex"),
1139
+ dpi: operation.dpi,
1140
+ pageCount: planned.count,
1141
+ images,
1142
+ missingFonts: [...missingFonts]
1143
+ };
1144
+ } finally {
1145
+ signal.removeEventListener("abort", abort);
1146
+ output.close();
1147
+ if (child.exitCode === null) child.kill("SIGKILL");
1148
+ await closed.catch(() => {});
1149
+ if (stopped !== void 0) throw stopped;
1150
+ }
1151
+ });
1152
+ }
1153
+ //#endregion
1154
+ //#region lib/types/font-file-identity.js
1155
+ /** Preserve 64-bit device and inode values without JavaScript integer rounding. */
1156
+ function fontFileIdentity(status) {
1157
+ return {
1158
+ dev: status.dev.toString(),
1159
+ ino: status.ino.toString(),
1160
+ size: Number(status.size),
1161
+ mtimeMs: Number(status.mtimeNs) / 1e6,
1162
+ ctimeMs: Number(status.ctimeNs) / 1e6
1163
+ };
1164
+ }
1165
+ /** Compare a source descriptor's exact identity with its indexed font metadata. */
1166
+ function matchesFontFile(status, expected) {
1167
+ const current = fontFileIdentity(status);
1168
+ return [
1169
+ "dev",
1170
+ "ino",
1171
+ "size",
1172
+ "mtimeMs",
1173
+ "ctimeMs"
1174
+ ].every((key) => current[key] === expected[key]);
963
1175
  }
964
1176
  //#endregion
965
1177
  //#region lib/types/fonts.js
@@ -1212,16 +1424,16 @@ function resolveOptions(input = {}) {
1212
1424
  /** Resolve installed, version-matched engine packages without downloads or compilation. */
1213
1425
  const require = createRequire(import.meta.url);
1214
1426
  /** Node API release version returned by runtime discovery. */
1215
- const ENGINE_VERSION = "0.1.2";
1427
+ const ENGINE_VERSION = "0.1.4";
1216
1428
  /** Exact compatible engine versions; unchanged platforms retain their published packages. */
1217
1429
  const ENGINE_VERSIONS = Object.freeze({
1218
- "darwin-arm64": "0.1.1",
1219
- "darwin-x64": "0.1.1",
1430
+ "darwin-arm64": "0.1.4",
1431
+ "darwin-x64": "0.1.4",
1220
1432
  "linux-arm64-glibc": "0.1.1",
1221
1433
  "linux-x64-glibc": "0.1.1",
1222
- "win32-arm64": "0.1.2",
1223
- "win32-x64": "0.1.2",
1224
- wasm: "0.1.1"
1434
+ "win32-arm64": "0.1.4",
1435
+ "win32-x64": "0.1.4",
1436
+ wasm: "0.1.4"
1225
1437
  });
1226
1438
  /** npm scope and name prefix shared by the engine packages this adapter installs. */
1227
1439
  const ENGINE_PREFIX = "@deepseek-ai/libreoffice-kit";
@@ -1528,14 +1740,8 @@ var FontSnapshotState = class {
1528
1740
  async function validateFontSnapshot(snapshot) {
1529
1741
  await Promise.all(snapshot.records.map(async (record) => {
1530
1742
  try {
1531
- const current = await lstat(record.path);
1532
- if (current.isFile() && [
1533
- "dev",
1534
- "ino",
1535
- "size",
1536
- "mtimeMs",
1537
- "ctimeMs"
1538
- ].every((key) => current[key] === record[key])) return;
1743
+ const current = await lstat(record.path, { bigint: true });
1744
+ if (current.isFile() && matchesFontFile(current, record)) return;
1539
1745
  } catch {}
1540
1746
  throw new ConversionError("failed", "A system font changed during conversion; retry the operation.");
1541
1747
  }));
@@ -1942,7 +2148,7 @@ async function main() {
1942
2148
  "convert",
1943
2149
  "recalculate",
1944
2150
  "render"
1945
- ].includes(command)) throw new TypeError("Usage: libreoffice-kit capabilities --json | render --input <file> --output-dir <fresh-directory> [--pages all|1,3] [--sheet <name> --range A1:D20] [--dpi 144] | convert --input <file> --output <file> [--sheet <name>] | recalculate --input <workbook> --output <xlsx|ods>");
2151
+ ].includes(command)) throw new TypeError("Usage: dsoffice capabilities --json | render --input <file> --output-dir <fresh-directory> [--pages all|1,3] [--sheet <name> --range A1:D20] [--dpi 144] | convert --input <file> --output <file> [--sheet <name>] | recalculate --input <workbook> --output <xlsx|ods>");
1946
2152
  if (command === "capabilities") {
1947
2153
  if (Object.keys(values).some((key) => key !== "json")) throw new TypeError("capabilities accepts only --json.");
1948
2154
  process.stdout.write(`${JSON.stringify({