@deepseek-ai/dsh-office-kit 0.0.0-stage → 0.2.2-rc.3

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 (59) hide show
  1. package/LICENSE +21 -0
  2. package/README.i18n.yaml +37 -0
  3. package/README.md +128 -2
  4. package/README.zh.md +129 -0
  5. package/lib/index.js +1234 -0
  6. package/lib/typert.host.d.ts +3 -0
  7. package/lib/typert.host.js +346 -0
  8. package/lib/typert.remote-client.d.ts +30 -0
  9. package/lib/typert.remote-client.d.ts.map +1 -0
  10. package/lib/typert.remote-client.js +162 -0
  11. package/lib/types/errors.d.ts +13 -0
  12. package/lib/types/errors.d.ts.map +1 -0
  13. package/lib/types/errors.js +15 -0
  14. package/lib/types/errors.js.map +1 -0
  15. package/lib/types/identity.d.ts +27 -0
  16. package/lib/types/identity.d.ts.map +1 -0
  17. package/lib/types/identity.js +23 -0
  18. package/lib/types/identity.js.map +1 -0
  19. package/lib/types/index.d.ts +157 -0
  20. package/lib/types/index.d.ts.map +1 -0
  21. package/lib/types/index.js +459 -0
  22. package/lib/types/index.js.map +1 -0
  23. package/lib/types/locate.d.ts +48 -0
  24. package/lib/types/locate.d.ts.map +1 -0
  25. package/lib/types/locate.js +65 -0
  26. package/lib/types/locate.js.map +1 -0
  27. package/lib/types/output.d.ts +26 -0
  28. package/lib/types/output.d.ts.map +1 -0
  29. package/lib/types/output.js +75 -0
  30. package/lib/types/output.js.map +1 -0
  31. package/lib/types/outputs.d.ts +75 -0
  32. package/lib/types/outputs.d.ts.map +1 -0
  33. package/lib/types/outputs.js +198 -0
  34. package/lib/types/outputs.js.map +1 -0
  35. package/lib/types/queue.d.ts +106 -0
  36. package/lib/types/queue.d.ts.map +1 -0
  37. package/lib/types/queue.js +276 -0
  38. package/lib/types/queue.js.map +1 -0
  39. package/lib/types/types.d.ts +151 -0
  40. package/lib/types/types.d.ts.map +1 -0
  41. package/lib/types/types.js +2 -0
  42. package/lib/types/types.js.map +1 -0
  43. package/locale/de.json +6 -0
  44. package/locale/en.json +6 -0
  45. package/locale/es.json +6 -0
  46. package/locale/fr.json +6 -0
  47. package/locale/ja.json +6 -0
  48. package/locale/pt.json +6 -0
  49. package/locale/ru.json +6 -0
  50. package/locale/zh.json +6 -0
  51. package/package.json +68 -3
  52. package/src/errors.ts +15 -0
  53. package/src/identity.ts +31 -0
  54. package/src/index.ts +484 -0
  55. package/src/locate.ts +93 -0
  56. package/src/output.ts +69 -0
  57. package/src/outputs.ts +218 -0
  58. package/src/queue.ts +316 -0
  59. package/src/types.ts +168 -0
package/lib/index.js ADDED
@@ -0,0 +1,1234 @@
1
+ import { createRequire } from "node:module";
2
+ import { createHash, randomUUID } from "node:crypto";
3
+ import { lstat, mkdir, mkdtemp, open, readdir, rm, rmdir, writeFile } from "node:fs/promises";
4
+ import { tmpdir } from "node:os";
5
+ import { basename, extname, isAbsolute, join, relative, sep } from "node:path";
6
+ import z from "@deepseek-ai/schemastery";
7
+ import { dshHomePath } from "@deepseek-ai/dsh-home-paths";
8
+ import { brandString } from "@deepseek-ai/dsh-brand";
9
+ import { constants, lstatSync } from "node:fs";
10
+ import { Remote, RemoteError, TypertRemoteService } from "@deepseek-ai/dsh-typert-protocol";
11
+ //#region lib/types/locate.js
12
+ /** Locate LibreOffice Kit and its engine packages from the consumer's Kit installation without module hooks. */
13
+ /**
14
+ * Locate Kit for a consumer that loads it with a dynamic `import()`.
15
+ * @param lookupKitEntry - Consumer's Kit lookup; anchoring at the consumer, not this library, selects the installation the consumer uses.
16
+ * @returns `available` with the entry file URL and an engine resolver created by {@link createEnginePackageResolver},
17
+ * or `missing` when the lookup throws.
18
+ * @throws Node's error if a returned entry cannot be used by `createRequire`.
19
+ */
20
+ function resolveKitModule(lookupKitEntry) {
21
+ const located = lookupEntry(lookupKitEntry);
22
+ if (located.kind === "missing") return located;
23
+ return {
24
+ kind: "available",
25
+ entry: located.entry,
26
+ resolveEnginePackage: createEnginePackageResolver(located.entry)
27
+ };
28
+ }
29
+ /**
30
+ * Anchor engine resolution to the Kit entry actually used by the consumer, not this package's installation.
31
+ * Each returned callback retains its own Node resolver and installs no module hooks.
32
+ * @param kitEntry - Absolute Kit entry path or file URL, normally the consumer's `import.meta.resolve('@deepseek-ai/libreoffice-kit')`.
33
+ * @returns A callback for Kit's `resolveEnginePackage` option. Native paths map the first ASAR segment to its unpacked copy;
34
+ * WASM and paths outside archives stay unchanged. Kit validates the returned manifest and required engine assets.
35
+ * @throws Node's error if `kitEntry` cannot be used by `createRequire`.
36
+ * On invocation, the callback preserves Node errors for absent packages and other resolution failures.
37
+ * An installed package with an unresolvable manifest throws an incomplete-installation Error with the Node error as its cause,
38
+ * preventing engine fallback. Filesystem inspection errors propagate unchanged.
39
+ */
40
+ function createEnginePackageResolver(kitEntry) {
41
+ const fromKit = createRequire(kitEntry);
42
+ return (name) => {
43
+ let manifest;
44
+ try {
45
+ manifest = fromKit.resolve(`${name}/package.json`);
46
+ } catch (error) {
47
+ if (error instanceof Error && "code" in error && error.code === "MODULE_NOT_FOUND") {
48
+ if ((fromKit.resolve.paths(name) ?? []).some((directory) => lstatSync(join(directory, name), { throwIfNoEntry: false }) !== void 0)) throw new Error(`Installed LibreOfficeKit package is incomplete: ${name}. Reinstall the package.`, { cause: error });
49
+ }
50
+ throw error;
51
+ }
52
+ return name === "@deepseek-ai/libreoffice-kit-wasm" ? manifest : unpackedPath(manifest);
53
+ };
54
+ }
55
+ function lookupEntry(lookupKitEntry) {
56
+ let entry;
57
+ try {
58
+ entry = lookupKitEntry();
59
+ } catch (error) {
60
+ return {
61
+ kind: "missing",
62
+ error
63
+ };
64
+ }
65
+ return {
66
+ kind: "found",
67
+ entry: typeof entry === "string" ? entry : entry.href
68
+ };
69
+ }
70
+ /**
71
+ * Map an ASAR path to its physical unpacked copy for native files read outside Electron's archive support.
72
+ * @param path - Filesystem path, including paths with Windows separators.
73
+ * @returns The path with its first `.asar` segment replaced by `.asar.unpacked`; already-unpacked paths stay unchanged.
74
+ */
75
+ function unpackedPath(path) {
76
+ return path.replace(/\.asar(?=[\\/]|$)/, ".asar.unpacked");
77
+ }
78
+ //#endregion
79
+ //#region lib/types/errors.js
80
+ /** Classified conversion failure; engine details stay in the cause. */
81
+ var OfficeKitError = class extends Error {
82
+ code;
83
+ /**
84
+ * @param code - category suitable for a conversion consumer.
85
+ * @param message - diagnostic explaining the failed conversion.
86
+ * @param options - underlying engine or filesystem failure.
87
+ */
88
+ constructor(code, message, options) {
89
+ super(message, options);
90
+ this.code = code;
91
+ this.name = "OfficeKitError";
92
+ }
93
+ };
94
+ //#endregion
95
+ //#region lib/types/identity.js
96
+ /** Source locators and converter-owned identities for shared PDF reuse. */
97
+ /**
98
+ * Label an authorized source locator for pre-read deduplication.
99
+ * @param key - unambiguous encoding of authorization scope, execution world, and canonical path.
100
+ * @returns branded source locator; source authorization remains the caller's responsibility.
101
+ */
102
+ function OfficeSourceKey(key) {
103
+ return brandString(key);
104
+ }
105
+ /**
106
+ * Label a provider lifetime.
107
+ * @param value - unique generation created by the provider.
108
+ * @returns branded converter generation.
109
+ */
110
+ function OfficeKitGeneration(value) {
111
+ return brandString(value);
112
+ }
113
+ /**
114
+ * Label a converter-owned content identity.
115
+ * @param value - generation and content identity created by the provider.
116
+ * @returns branded conversion identity.
117
+ */
118
+ function OfficeKitKey(value) {
119
+ return brandString(value);
120
+ }
121
+ //#endregion
122
+ //#region lib/types/output.js
123
+ /** Read only bounded, regular output files created inside a private task directory. */
124
+ const PNG_SIGNATURE = Buffer.from([
125
+ 137,
126
+ 80,
127
+ 78,
128
+ 71,
129
+ 13,
130
+ 10,
131
+ 26,
132
+ 10
133
+ ]);
134
+ /**
135
+ * Refuse missing, link-shaped, oversized, and truncated output.
136
+ * @param path - kit output path in the provider-owned scratch directory.
137
+ * @param limit - inclusive byte limit.
138
+ * @param signal - conversion lifetime.
139
+ * @returns complete bytes independent of the scratch file.
140
+ * @throws {OfficeKitError} `invalid-output` for a non-regular or changing file and `output-too-large` above `limit`.
141
+ */
142
+ async function readOutput(path, limit, signal) {
143
+ signal.throwIfAborted();
144
+ if (!(await lstat(path)).isFile()) throw new OfficeKitError("invalid-output", "The converter output is not a regular file.");
145
+ const file = await open(path, constants.O_RDONLY | constants.O_NOFOLLOW);
146
+ try {
147
+ const info = await file.stat();
148
+ if (!info.isFile()) throw new OfficeKitError("invalid-output", "The converter output is not a regular file.");
149
+ if (info.size > limit) throw new OfficeKitError("output-too-large", "The converter output exceeds its byte limit.");
150
+ const bytes = Buffer.alloc(info.size + 1);
151
+ let length = 0;
152
+ while (length < bytes.length) {
153
+ signal.throwIfAborted();
154
+ const read = await file.read(bytes, length, bytes.length - length, null);
155
+ if (read.bytesRead === 0) break;
156
+ length += read.bytesRead;
157
+ }
158
+ signal.throwIfAborted();
159
+ if (length > limit) throw new OfficeKitError("output-too-large", "The converter output exceeds its byte limit.");
160
+ if (length !== info.size) throw new OfficeKitError("invalid-output", "The converter output changed while it was read.");
161
+ return bytes.subarray(0, length);
162
+ } finally {
163
+ await file.close();
164
+ }
165
+ }
166
+ /**
167
+ * Refuse missing, link-shaped, oversized, truncated, and non-PDF output.
168
+ * @param path - kit output path in the provider-owned scratch directory.
169
+ * @param limit - inclusive PDF byte limit.
170
+ * @param signal - conversion lifetime.
171
+ * @returns complete bytes independent of the scratch file.
172
+ */
173
+ async function readPdf(path, limit, signal) {
174
+ const pdf = await readOutput(path, limit, signal);
175
+ if (!pdf.subarray(0, 8).toString("ascii").match(/^%PDF-\d\.\d/u) || !pdf.subarray(-1024).toString("ascii").trimEnd().endsWith("%%EOF")) throw new OfficeKitError("invalid-output", "The converter did not produce a complete PDF.");
176
+ return pdf;
177
+ }
178
+ /**
179
+ * Refuse missing, link-shaped, oversized, and non-PNG image output.
180
+ * @param path - kit image path in the provider-owned scratch directory.
181
+ * @param limit - inclusive PNG byte limit.
182
+ * @param signal - rendering lifetime.
183
+ * @returns complete PNG bytes independent of the scratch file.
184
+ */
185
+ async function readPng(path, limit, signal) {
186
+ const png = await readOutput(path, limit, signal);
187
+ if (!png.subarray(0, PNG_SIGNATURE.length).equals(PNG_SIGNATURE)) throw new OfficeKitError("invalid-output", "The converter did not produce a PNG image.");
188
+ return png;
189
+ }
190
+ //#endregion
191
+ //#region lib/types/outputs.js
192
+ /** Private, bounded, Session-owned files for converted and recalculated Office outputs. */
193
+ /** Names {@link ownerDirectory} generates. */
194
+ const OWNER_DIRECTORY = /^session-[0-9a-f]{24}$/u;
195
+ /** Names of per-output directories, which `randomUUID()` generates. */
196
+ const OUTPUT_DIRECTORY = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/u;
197
+ /** Directory name for one owner, independent of characters the owner id may contain. */
198
+ function ownerDirectory(owner) {
199
+ return `session-${createHash("sha256").update(owner).digest("hex").slice(0, 24)}`;
200
+ }
201
+ /** Create an output's private directory and write its file, removing the directory when either step fails. */
202
+ async function writeOutput(directory, path, data) {
203
+ try {
204
+ await mkdir(directory, {
205
+ recursive: true,
206
+ mode: 448
207
+ });
208
+ await writeFile(path, data, {
209
+ flag: "wx",
210
+ mode: 384
211
+ });
212
+ } catch (error) {
213
+ await rm(directory, {
214
+ recursive: true,
215
+ force: true
216
+ });
217
+ throw error;
218
+ }
219
+ }
220
+ function isMissingPath(error) {
221
+ return typeof error === "object" && error !== null && "code" in error && error.code === "ENOENT";
222
+ }
223
+ /**
224
+ * Keeps each saved output in its own private directory under a per-owner directory. Files leave when their retention
225
+ * expires, when newer files need the byte budget, when their owner is released, and when the store is disposed. A file
226
+ * counts toward the byte budget until its deletion succeeds; a failed deletion is reported and retried by later
227
+ * eviction, release, and disposal. Only files this store saved are deleted, apart from a startup sweep of expired
228
+ * leftovers of earlier processes. The sweep considers only real directories, never links or junctions, whose names this
229
+ * store generates: `session-` and 24 lowercase hexadecimal digits under the root, and a lowercase UUID v4 below that.
230
+ */
231
+ var OutputStore = class {
232
+ options;
233
+ warn;
234
+ entries = /* @__PURE__ */ new Map();
235
+ bytes = 0;
236
+ disposed = false;
237
+ sweep;
238
+ saving = Promise.resolve();
239
+ /** Deletions and releases in progress, awaited by disposal. */
240
+ pending = /* @__PURE__ */ new Set();
241
+ /**
242
+ * @param options - root directory, retention, and byte budget.
243
+ * @param warn - receives contained cleanup failures.
244
+ */
245
+ constructor(options, warn) {
246
+ this.options = options;
247
+ this.warn = warn;
248
+ this.sweep = this.sweepExpired();
249
+ }
250
+ /**
251
+ * Save one output for an owner.
252
+ * @param owner - opaque owner identity, such as a Session id.
253
+ * @param name - file name shown to the consumer; only its final path component is used.
254
+ * @param data - complete output bytes.
255
+ * @returns the absolute path of the saved file.
256
+ * @throws {OfficeKitError} `output-too-large` when the file alone exceeds the byte budget, and `unavailable` after
257
+ * disposal or when retained files whose deletion failed leave too little of the budget.
258
+ */
259
+ save(owner, name, data) {
260
+ const saved = this.saving.then(() => this.saveNow(owner, name, data));
261
+ this.saving = saved.catch((_failedSave) => void 0);
262
+ return saved;
263
+ }
264
+ /** Saves run one at a time so the byte budget covers every retained file. */
265
+ async saveNow(owner, name, data) {
266
+ await this.sweep;
267
+ if (this.disposed) throw new OfficeKitError("unavailable", "The document converter is unavailable.");
268
+ if (data.byteLength > this.options.maxBytes) throw new OfficeKitError("output-too-large", `The output exceeds the ${this.options.maxBytes}-byte output store limit.`);
269
+ for (const entry of [...this.entries.values()]) {
270
+ if (this.bytes + data.byteLength <= this.options.maxBytes) break;
271
+ await this.remove(entry);
272
+ }
273
+ if (this.bytes + data.byteLength > this.options.maxBytes) throw new OfficeKitError("unavailable", "Earlier outputs could not be deleted to make room for this output.");
274
+ const directory = join(this.options.root, ownerDirectory(owner), randomUUID());
275
+ const path = join(directory, basename(name));
276
+ await writeOutput(directory, path, data).catch((error) => {
277
+ if (!isMissingPath(error)) throw error;
278
+ return writeOutput(directory, path, data);
279
+ });
280
+ const timer = setTimeout(() => {
281
+ this.remove(entry);
282
+ }, this.options.retentionMs);
283
+ timer.unref();
284
+ const entry = {
285
+ path,
286
+ directory,
287
+ owner,
288
+ bytes: data.byteLength,
289
+ timer
290
+ };
291
+ this.entries.set(path, entry);
292
+ this.bytes += data.byteLength;
293
+ return path;
294
+ }
295
+ /**
296
+ * Delete every file saved for an owner. Disposal waits for a release in progress.
297
+ * @param owner - owner whose files are released.
298
+ * @returns completion after deletion settles; failed deletions are reported and retained for retry.
299
+ */
300
+ release(owner) {
301
+ return this.track(this.releaseNow(owner));
302
+ }
303
+ async releaseNow(owner) {
304
+ await Promise.all([...this.entries.values()].filter((entry) => entry.owner === owner).map((entry) => this.remove(entry)));
305
+ await this.removeEmpty(join(this.options.root, ownerDirectory(owner)));
306
+ }
307
+ /**
308
+ * Refuse further saves, wait for deletions and releases in progress, and delete every file this store saved,
309
+ * retrying earlier failed deletions once more.
310
+ * @returns completion after deletion settles; files that still cannot be deleted are reported.
311
+ */
312
+ async dispose() {
313
+ this.disposed = true;
314
+ await this.sweep;
315
+ await this.saving;
316
+ await this.settle();
317
+ const owners = new Set([...this.entries.values()].map((entry) => entry.owner));
318
+ await Promise.all([...owners].map((owner) => this.release(owner)));
319
+ await this.settle();
320
+ }
321
+ /** Wait until no deletion or release is in progress, including ones started while waiting. */
322
+ async settle() {
323
+ while (this.pending.size > 0) await Promise.all(this.pending);
324
+ }
325
+ /** Record a non-rejecting deletion or release as in progress until it settles. */
326
+ track(operation) {
327
+ this.pending.add(operation);
328
+ const settled = () => {
329
+ this.pending.delete(operation);
330
+ };
331
+ operation.then(settled, settled);
332
+ return operation;
333
+ }
334
+ /**
335
+ * Delete one saved file, sharing a deletion already in progress. The entry and its bytes leave the store only after
336
+ * the deletion succeeds; a failure is reported and leaves the entry for a later retry.
337
+ * @returns whether the file is gone.
338
+ */
339
+ remove(entry) {
340
+ if (entry.removal !== void 0) return entry.removal;
341
+ if (this.entries.get(entry.path) !== entry) return Promise.resolve(true);
342
+ clearTimeout(entry.timer);
343
+ const removal = this.track(rm(entry.directory, {
344
+ recursive: true,
345
+ force: true
346
+ }).then(() => {
347
+ this.entries.delete(entry.path);
348
+ this.bytes -= entry.bytes;
349
+ return true;
350
+ }, (error) => {
351
+ this.warn(`office-kit: could not delete output ${entry.path}: ${String(error)}`);
352
+ return false;
353
+ }).finally(() => {
354
+ delete entry.removal;
355
+ }));
356
+ entry.removal = removal;
357
+ return removal;
358
+ }
359
+ async removeEmpty(directory) {
360
+ try {
361
+ await rmdir(directory);
362
+ } catch (_notEmptyOrMissing) {}
363
+ }
364
+ /**
365
+ * Delete output directories, including those of earlier processes, whose files are older than the retention. Only
366
+ * real directories with store-generated names are considered; links, junctions, and other entries stay untouched.
367
+ */
368
+ async sweepExpired() {
369
+ const cutoff = Date.now() - this.options.retentionMs;
370
+ for (const owner of await generatedDirectories(this.options.root, OWNER_DIRECTORY)) {
371
+ for (const directory of await generatedDirectories(owner, OUTPUT_DIRECTORY)) try {
372
+ if ((await lstat(directory)).mtimeMs < cutoff) await rm(directory, {
373
+ recursive: true,
374
+ force: true
375
+ });
376
+ } catch (error) {
377
+ this.warn(`office-kit: could not sweep output ${directory}: ${String(error)}`);
378
+ }
379
+ await this.removeEmpty(owner);
380
+ }
381
+ }
382
+ };
383
+ /**
384
+ * List the real subdirectories of `directory` whose names match `name`.
385
+ * @param directory - directory to list; a missing or unreadable directory has none.
386
+ * @param name - names the store generates at this level.
387
+ * @returns absolute paths, excluding links, junctions, and non-directories.
388
+ */
389
+ async function generatedDirectories(directory, name) {
390
+ return (await readdir(directory, { withFileTypes: true }).catch((_missingDirectory) => [])).filter((entry) => entry.isDirectory() && name.test(entry.name)).map((entry) => join(directory, entry.name));
391
+ }
392
+ //#endregion
393
+ //#region lib/types/queue.js
394
+ /** Bounded source admission, shared content conversion, and caller-owned output delivery. */
395
+ /** Bytes a retained output occupies. */
396
+ function outputBytes(output) {
397
+ switch (output.kind) {
398
+ case "pdf": return output.pdf.byteLength;
399
+ case "file": return output.data.byteLength;
400
+ case "images": return output.images.reduce((sum, image) => sum + image.png.byteLength, 0);
401
+ /* v8 ignore next -- OfficeOperationOutput is a closed union */
402
+ default: return exhausted(output);
403
+ }
404
+ }
405
+ /** Independent copy of every byte array and list in an output. */
406
+ function copyOutput(result) {
407
+ switch (result.kind) {
408
+ case "pdf": return {
409
+ ...result,
410
+ pdf: Uint8Array.from(result.pdf),
411
+ missingFonts: [...result.missingFonts]
412
+ };
413
+ case "file": return {
414
+ ...result,
415
+ data: Uint8Array.from(result.data),
416
+ missingFonts: [...result.missingFonts]
417
+ };
418
+ case "images": return {
419
+ ...result,
420
+ missingFonts: [...result.missingFonts],
421
+ images: result.images.map((image) => ({
422
+ ...image,
423
+ png: Uint8Array.from(image.png)
424
+ }))
425
+ };
426
+ /* v8 ignore next -- OfficeOperationOutput is a closed union */
427
+ default: return exhausted(result);
428
+ }
429
+ }
430
+ /* v8 ignore next 3 -- reached only through an unchecked closed-union member */
431
+ function exhausted(value) {
432
+ throw new Error(`Unexpected Office output: ${JSON.stringify(value)}`);
433
+ }
434
+ /** One converter generation owns every queued source, conversion, reader, and retained PDF. */
435
+ var ConversionQueue = class {
436
+ config;
437
+ generation;
438
+ convert;
439
+ ready = /* @__PURE__ */ new Map();
440
+ aliases = /* @__PURE__ */ new Map();
441
+ sources = /* @__PURE__ */ new Map();
442
+ digests = /* @__PURE__ */ new Map();
443
+ queue = [];
444
+ tasks = /* @__PURE__ */ new Set();
445
+ jobs = /* @__PURE__ */ new Set();
446
+ cachedBytes = 0;
447
+ sourceBytes = 0;
448
+ running = 0;
449
+ background = 0;
450
+ readers = 0;
451
+ disposed = false;
452
+ /**
453
+ * @param config - validated queue, source, reader, and completed-result limits.
454
+ * @param generation - provider lifetime; prevents reuse after engine or font replacement.
455
+ * @param convert - executes one admitted conversion and settles after scratch cleanup.
456
+ */
457
+ constructor(config, generation, convert) {
458
+ this.config = config;
459
+ this.generation = generation;
460
+ this.convert = convert;
461
+ }
462
+ /**
463
+ * Admit metadata before loading source bytes and share conversion across authorized readers.
464
+ * @param request - already-authorized metadata and deferred bounded source read.
465
+ * @param signal - this reader's cancellation; the final reader cancels shared work.
466
+ * @returns independent output bytes; busy or canceled readers reject without releasing active engine capacity early.
467
+ */
468
+ async read(request, signal) {
469
+ return await this.readStored(request, signal);
470
+ }
471
+ async readStored(request, signal) {
472
+ signal?.throwIfAborted();
473
+ if (this.disposed) throw this.unavailable();
474
+ if (request.source.bytes !== void 0 && request.source.bytes > this.config.maxInputBytes) throw new OfficeKitError("input-too-large", "The Office source exceeds maxInputBytes.");
475
+ const operation = JSON.stringify(request.operation);
476
+ const source = JSON.stringify([
477
+ request.source.key,
478
+ request.source.version,
479
+ request.extension,
480
+ operation
481
+ ]);
482
+ const alias = this.aliases.get(source);
483
+ const cached = alias === void 0 ? void 0 : this.ready.get(alias);
484
+ if (cached !== void 0) {
485
+ this.ready.delete(cached.cacheKey);
486
+ this.ready.set(cached.cacheKey, cached);
487
+ this.aliases.delete(source);
488
+ this.aliases.set(source, cached.cacheKey);
489
+ return this.copy(cached);
490
+ }
491
+ const readerLimit = request.priority === "background" ? this.config.maxReaders - 1 : this.config.maxReaders;
492
+ if (this.readers >= readerLimit) throw this.busy();
493
+ if (request.priority === "background" && this.config.maxBackgroundConversions === 0) throw this.busy();
494
+ let job = this.sources.get(source);
495
+ if (job === void 0) {
496
+ if (this.queue.length >= this.config.maxQueuedJobs) {
497
+ const obsolete = request.priority === "foreground" ? this.queue.find((item) => item.priority === "background") : void 0;
498
+ if (obsolete === void 0) throw this.busy();
499
+ this.fail(obsolete, this.busy());
500
+ }
501
+ job = {
502
+ request,
503
+ operation,
504
+ priority: request.priority,
505
+ controller: new AbortController(),
506
+ readers: /* @__PURE__ */ new Set(),
507
+ sources: new Set([source]),
508
+ state: "queued"
509
+ };
510
+ this.sources.set(source, job);
511
+ this.jobs.add(job);
512
+ this.queue.push(job);
513
+ }
514
+ const shared = job;
515
+ if (request.priority === "foreground") shared.priority = "foreground";
516
+ this.readers++;
517
+ const promise = new Promise((resolve, reject) => {
518
+ const abort = () => {
519
+ this.release(reader);
520
+ const reason = signal?.reason;
521
+ reject(reason instanceof Error ? reason : new Error("Office conversion cancelled", { cause: reason }));
522
+ if (reader.job.readers.size === 0) this.cancel(reader.job);
523
+ this.drain();
524
+ };
525
+ const reader = {
526
+ job: shared,
527
+ source,
528
+ priority: request.priority,
529
+ resolve,
530
+ reject,
531
+ cleanup: () => signal?.removeEventListener("abort", abort)
532
+ };
533
+ shared.readers.add(reader);
534
+ signal?.addEventListener("abort", abort, { once: true });
535
+ });
536
+ this.drain();
537
+ return promise;
538
+ }
539
+ /** Cancel all readers and wait until actual reads, conversions, and scratch cleanup finish. */
540
+ async dispose() {
541
+ this.disposed = true;
542
+ for (const job of this.jobs) this.fail(job, this.unavailable());
543
+ this.ready.clear();
544
+ this.aliases.clear();
545
+ this.cachedBytes = 0;
546
+ await Promise.allSettled(this.tasks);
547
+ }
548
+ busy() {
549
+ return new OfficeKitError("busy", "The document converter has reached its admission limit.");
550
+ }
551
+ unavailable() {
552
+ return new OfficeKitError("unavailable", "The document converter is unavailable.");
553
+ }
554
+ copy(result) {
555
+ return copyOutput(result);
556
+ }
557
+ release(reader) {
558
+ reader.job.readers.delete(reader);
559
+ if (reader.job.state === "queued") reader.job.priority = [...reader.job.readers].some((other) => other.priority === "foreground") ? "foreground" : "background";
560
+ if (![...reader.job.readers].some((other) => other.source === reader.source)) {
561
+ reader.job.sources.delete(reader.source);
562
+ if (this.sources.get(reader.source) === reader.job) this.sources.delete(reader.source);
563
+ }
564
+ reader.cleanup();
565
+ this.readers--;
566
+ }
567
+ cancel(job) {
568
+ job.controller.abort();
569
+ if (job.state === "queued") {
570
+ this.queue.splice(this.queue.indexOf(job), 1);
571
+ job.state = "finished";
572
+ this.jobs.delete(job);
573
+ }
574
+ }
575
+ fail(job, error) {
576
+ for (const reader of job.readers) {
577
+ this.release(reader);
578
+ reader.reject(error);
579
+ }
580
+ this.cancel(job);
581
+ }
582
+ reservation(job) {
583
+ return Math.max(1, job.request.source.bytes ?? this.config.maxInputBytes);
584
+ }
585
+ drain() {
586
+ while (!this.disposed && this.running < this.config.maxConcurrentConversions) {
587
+ const eligible = (job) => this.sourceBytes + this.reservation(job) <= this.config.maxSourceBytes && (job.priority === "foreground" || this.background < Math.min(this.config.maxBackgroundConversions, Math.max(1, this.config.maxConcurrentConversions - 1)));
588
+ const foregroundWaiting = this.queue.some((item) => item.priority === "foreground");
589
+ const job = this.queue.find((item) => (!foregroundWaiting || item.priority === "foreground") && eligible(item));
590
+ if (job === void 0) return;
591
+ this.queue.splice(this.queue.indexOf(job), 1);
592
+ job.state = "running";
593
+ const background = job.priority === "background";
594
+ const reserved = this.reservation(job);
595
+ this.running++;
596
+ if (background) this.background++;
597
+ this.sourceBytes += reserved;
598
+ const task = this.execute(job, reserved).catch((error) => {
599
+ this.fail(job, error);
600
+ }).finally(() => {
601
+ this.running--;
602
+ if (background) this.background--;
603
+ this.sourceBytes -= reserved;
604
+ job.state = "finished";
605
+ this.jobs.delete(job);
606
+ this.tasks.delete(task);
607
+ this.drain();
608
+ });
609
+ this.tasks.add(task);
610
+ }
611
+ }
612
+ async execute(job, reserved) {
613
+ const signal = job.controller.signal;
614
+ signal.throwIfAborted();
615
+ const input = await job.request.source.read(signal, reserved);
616
+ signal.throwIfAborted();
617
+ if (input.version !== job.request.source.version) throw new OfficeKitError("source-changed", "The source changed while waiting for conversion.");
618
+ if (input.bytes.byteLength > reserved) throw new OfficeKitError("input-too-large", "The source exceeds its reserved read capacity.");
619
+ const digest = createHash("sha256").update(job.request.extension).update("\0").update(job.operation).update("\0").update(input.bytes).digest("hex");
620
+ const key = OfficeKitKey(`${this.generation}:${digest}`);
621
+ const cached = this.ready.get(key);
622
+ if (cached !== void 0) {
623
+ this.ready.delete(key);
624
+ this.ready.set(key, cached);
625
+ this.finish(job, cached);
626
+ return;
627
+ }
628
+ const existing = this.digests.get(key);
629
+ if (existing !== void 0 && !existing.controller.signal.aborted) {
630
+ if (job.priority === "foreground") existing.priority = "foreground";
631
+ for (const reader of job.readers) {
632
+ reader.job = existing;
633
+ existing.readers.add(reader);
634
+ }
635
+ job.readers.clear();
636
+ for (const source of job.sources) {
637
+ existing.sources.add(source);
638
+ this.sources.set(source, existing);
639
+ }
640
+ job.sources.clear();
641
+ return;
642
+ }
643
+ this.digests.set(key, job);
644
+ try {
645
+ const converted = await this.convert(input.bytes, job.request, signal);
646
+ signal.throwIfAborted();
647
+ const result = {
648
+ ...converted,
649
+ cacheKey: key,
650
+ generation: this.generation
651
+ };
652
+ this.retain(result);
653
+ this.finish(job, result);
654
+ } finally {
655
+ if (this.digests.get(key) === job) this.digests.delete(key);
656
+ }
657
+ }
658
+ finish(job, result) {
659
+ for (const source of job.sources) this.sources.delete(source);
660
+ if (this.ready.has(result.cacheKey)) for (const source of job.sources) {
661
+ this.aliases.delete(source);
662
+ this.aliases.set(source, result.cacheKey);
663
+ while (this.aliases.size > this.config.maxSourceEntries) this.aliases.delete(this.aliases.keys().next().value);
664
+ }
665
+ for (const reader of job.readers) {
666
+ this.release(reader);
667
+ reader.resolve(this.copy(result));
668
+ }
669
+ }
670
+ retain(result) {
671
+ const bytes = outputBytes(result);
672
+ if (bytes > this.config.maxCachedBytes) return;
673
+ while (this.ready.size >= this.config.maxCachedEntries || this.cachedBytes + bytes > this.config.maxCachedBytes) {
674
+ const [key, oldest] = this.ready.entries().next().value;
675
+ this.ready.delete(key);
676
+ this.cachedBytes -= outputBytes(oldest);
677
+ for (const [source, digest] of this.aliases) if (digest === key) this.aliases.delete(source);
678
+ }
679
+ this.ready.set(result.cacheKey, result);
680
+ this.cachedBytes += bytes;
681
+ }
682
+ };
683
+ //#endregion
684
+ //#region lib/types/index.js
685
+ /** Host LibreOffice Kit provider with reusable converters, shared admission, and private disk input/output. */
686
+ var __runInitializers = function(thisArg, initializers, value) {
687
+ var useValue = arguments.length > 2;
688
+ for (var i = 0; i < initializers.length; i++) value = useValue ? initializers[i].call(thisArg, value) : initializers[i].call(thisArg);
689
+ return useValue ? value : void 0;
690
+ };
691
+ var __esDecorate = function(ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) {
692
+ function accept(f) {
693
+ if (f !== void 0 && typeof f !== "function") throw new TypeError("Function expected");
694
+ return f;
695
+ }
696
+ var kind = contextIn.kind, key = kind === "getter" ? "get" : kind === "setter" ? "set" : "value";
697
+ var target = !descriptorIn && ctor ? contextIn["static"] ? ctor : ctor.prototype : null;
698
+ var descriptor = descriptorIn || (target ? Object.getOwnPropertyDescriptor(target, contextIn.name) : {});
699
+ var _, done = false;
700
+ for (var i = decorators.length - 1; i >= 0; i--) {
701
+ var context = {};
702
+ for (var p in contextIn) context[p] = p === "access" ? {} : contextIn[p];
703
+ for (var p in contextIn.access) context.access[p] = contextIn.access[p];
704
+ context.addInitializer = function(f) {
705
+ if (done) throw new TypeError("Cannot add initializers after decoration has completed");
706
+ extraInitializers.push(accept(f || null));
707
+ };
708
+ var result = (0, decorators[i])(kind === "accessor" ? {
709
+ get: descriptor.get,
710
+ set: descriptor.set
711
+ } : descriptor[key], context);
712
+ if (kind === "accessor") {
713
+ if (result === void 0) continue;
714
+ if (result === null || typeof result !== "object") throw new TypeError("Object expected");
715
+ if (_ = accept(result.get)) descriptor.get = _;
716
+ if (_ = accept(result.set)) descriptor.set = _;
717
+ if (_ = accept(result.init)) initializers.unshift(_);
718
+ } else if (_ = accept(result)) if (kind === "field") initializers.unshift(_);
719
+ else descriptor[key] = _;
720
+ }
721
+ if (target) Object.defineProperty(target, contextIn.name, descriptor);
722
+ done = true;
723
+ };
724
+ /** Deployment defaults resolved before provider construction. */
725
+ const Config = z.object({
726
+ maxConcurrentConversions: z.natural().min(1).max(Number.MAX_SAFE_INTEGER).default(2),
727
+ maxQueuedJobs: z.natural().min(1).max(Number.MAX_SAFE_INTEGER).default(8),
728
+ maxReaders: z.natural().min(1).max(Number.MAX_SAFE_INTEGER).default(32),
729
+ maxSourceBytes: z.natural().min(1).max(Number.MAX_SAFE_INTEGER).default(104857600),
730
+ maxBackgroundConversions: z.natural().min(0).max(Number.MAX_SAFE_INTEGER).default(1),
731
+ maxCachedEntries: z.natural().min(1).max(Number.MAX_SAFE_INTEGER).default(8),
732
+ maxCachedBytes: z.natural().min(1).max(Number.MAX_SAFE_INTEGER).default(134217728),
733
+ maxSourceEntries: z.natural().min(1).max(Number.MAX_SAFE_INTEGER).default(64),
734
+ outputDirectory: z.string().min(1).default(dshHomePath("office-kit", "outputs")),
735
+ outputRetentionMs: z.natural().min(1).max(2147483647).default(1440 * 60 * 1e3),
736
+ maxOutputStoreBytes: z.natural().min(1).max(Number.MAX_SAFE_INTEGER).default(512 * 1024 * 1024),
737
+ timeoutMs: z.natural().min(1).max(2147483647).default(6e4),
738
+ maxInputBytes: z.natural().min(1).max(Number.MAX_SAFE_INTEGER - 1).default(50 * 1024 * 1024),
739
+ maxOutputBytes: z.natural().min(1).max(Number.MAX_SAFE_INTEGER - 1).default(100 * 1024 * 1024),
740
+ maxImageResolution: z.natural().min(1).max(2147483647).default(192),
741
+ maxArchiveEntries: z.natural().min(1).max(Number.MAX_SAFE_INTEGER).default(1e4),
742
+ maxUncompressedBytes: z.natural().min(1).max(Number.MAX_SAFE_INTEGER).default(250 * 1024 * 1024),
743
+ fontDirectories: z.array(z.string().min(1)).extra("default", void 0),
744
+ fontFallbacks: z.array(z.array(z.string().pattern(/\S/)).min(2)).extra("default", void 0),
745
+ maxFontFiles: z.natural().min(1).max(Number.MAX_SAFE_INTEGER).default(2e4),
746
+ maxFontFileBytes: z.natural().min(1).max(Number.MAX_SAFE_INTEGER).default(256 * 1024 * 1024),
747
+ maxLoadedFontBytes: z.natural().min(1).max(Number.MAX_SAFE_INTEGER).default(512 * 1024 * 1024)
748
+ });
749
+ const KIT_INSTALL_HINT = "This deployment does not provide LibreOffice Kit; install or enable it as this deployment requires, then retry.";
750
+ /** A provider lifetime owns all converters, queued calls, and temporary files. */
751
+ let OfficeKit = (() => {
752
+ let _classSuper = TypertRemoteService;
753
+ let _instanceExtraInitializers = [];
754
+ let _render_decorators;
755
+ let _getGeneration_decorators;
756
+ return class OfficeKit extends _classSuper {
757
+ static {
758
+ const _metadata = typeof Symbol === "function" && Symbol.metadata ? Object.create(_classSuper[Symbol.metadata] ?? null) : void 0;
759
+ _render_decorators = [Remote];
760
+ _getGeneration_decorators = [Remote("generation")];
761
+ __esDecorate(this, null, _render_decorators, {
762
+ kind: "method",
763
+ name: "render",
764
+ static: false,
765
+ private: false,
766
+ access: {
767
+ has: (obj) => "render" in obj,
768
+ get: (obj) => obj.render
769
+ },
770
+ metadata: _metadata
771
+ }, null, _instanceExtraInitializers);
772
+ __esDecorate(this, null, _getGeneration_decorators, {
773
+ kind: "method",
774
+ name: "getGeneration",
775
+ static: false,
776
+ private: false,
777
+ access: {
778
+ has: (obj) => "getGeneration" in obj,
779
+ get: (obj) => obj.getGeneration
780
+ },
781
+ metadata: _metadata
782
+ }, null, _instanceExtraInitializers);
783
+ if (_metadata) Object.defineProperty(this, Symbol.metadata, {
784
+ enumerable: true,
785
+ configurable: true,
786
+ writable: true,
787
+ value: _metadata
788
+ });
789
+ }
790
+ config = __runInitializers(this, _instanceExtraInitializers);
791
+ static Config = Config;
792
+ /** Changes whenever engine, font, or conversion configuration is replaced. */
793
+ generation = OfficeKitGeneration(randomUUID());
794
+ /** Absolute Host directory holding converted and recalculated files; consumers check that their execution world reads it. */
795
+ outputDirectory;
796
+ remoteLifetime = new AbortController();
797
+ remoteRequests = /* @__PURE__ */ new Set();
798
+ slots = [];
799
+ queue;
800
+ outputs;
801
+ options;
802
+ loadedKit;
803
+ reportedKitFailures = /* @__PURE__ */ new Set();
804
+ /**
805
+ * @param ctx - owning Host context.
806
+ * @param config - resolved rendering, font, and concurrency limits.
807
+ */
808
+ constructor(ctx, config) {
809
+ super(ctx, "officeKit");
810
+ this.config = config;
811
+ if (config.fontDirectories?.some((path) => !isAbsolute(path))) throw new Error("fontDirectories must contain absolute paths.");
812
+ if (config.maxSourceBytes < config.maxInputBytes) throw new Error("maxSourceBytes must be at least maxInputBytes.");
813
+ if (!isAbsolute(config.outputDirectory)) throw new Error("outputDirectory must be an absolute path.");
814
+ const { fontDirectories, fontFallbacks, timeoutMs, maxInputBytes, maxOutputBytes, maxImageResolution, maxArchiveEntries, maxUncompressedBytes, maxFontFiles, maxFontFileBytes, maxLoadedFontBytes } = config;
815
+ this.options = {
816
+ timeoutMs,
817
+ maxInputBytes,
818
+ maxOutputBytes,
819
+ maxImageResolution,
820
+ maxArchiveEntries,
821
+ maxUncompressedBytes,
822
+ maxFontFiles,
823
+ maxFontFileBytes,
824
+ maxLoadedFontBytes,
825
+ ...fontDirectories === void 0 ? {} : { fontDirectories },
826
+ ...fontFallbacks === void 0 ? {} : { fontFallbacks }
827
+ };
828
+ this.queue = new ConversionQueue(config, this.generation, (bytes, request, signal) => this.runOperation(bytes, request, signal));
829
+ this.outputDirectory = config.outputDirectory;
830
+ this.outputs = new OutputStore({
831
+ root: config.outputDirectory,
832
+ retentionMs: config.outputRetentionMs,
833
+ maxBytes: config.maxOutputStoreBytes
834
+ }, ctx.logger.warn.bind(ctx.logger));
835
+ ctx.on("session/disposed", (session) => {
836
+ this.outputs.release(session.id);
837
+ });
838
+ ctx.effect(() => async () => {
839
+ this.remoteLifetime.abort();
840
+ await this.queue.dispose();
841
+ await this.outputs.dispose();
842
+ await Promise.allSettled(this.remoteRequests);
843
+ const failures = (await Promise.allSettled(this.slots.map(async (slot) => {
844
+ await (await slot.converter)?.dispose();
845
+ }))).filter((result) => result.status === "rejected");
846
+ if (failures.length > 0) throw new AggregateError(failures.map((result) => result.reason), "LibreOffice converter disposal failed.");
847
+ });
848
+ }
849
+ /**
850
+ * Convert Office bytes to PDF without modifying the source or writing Session events.
851
+ * @param request - authorized metadata and deferred bounded source read.
852
+ * @param signal - caller cancellation; provider disposal also stops active work.
853
+ * @returns caller-owned PDF bytes after conversion and scratch cleanup settle; canceled readers reject independently.
854
+ * @throws {OfficeKitError} Invalid input, unusable output, or engine failure; cancellation rejects with its reason.
855
+ */
856
+ async convert(request, signal) {
857
+ const { kind: _kind, ...result } = await this.queue.read({
858
+ ...request,
859
+ operation: { kind: "pdf" }
860
+ }, signal);
861
+ return result;
862
+ }
863
+ /**
864
+ * Render selected pages, slides, or worksheet areas of one document as PNG images. Requests share the admission
865
+ * queue, concurrency, source-byte reservation, and cache with previews, and run at foreground priority.
866
+ * @param request - authorized metadata, deferred bounded source read, selection, and complete-result limits.
867
+ * @param signal - caller cancellation; provider disposal also stops active work.
868
+ * @returns caller-owned images in document order whose count, per-image size, and total bytes satisfy the limits.
869
+ * @throws {OfficeKitError} `invalid-request` for a selection the engine rejects, `output-too-large` when the
870
+ * selection exceeds a limit, and the other conversion codes; cancellation rejects with its reason.
871
+ */
872
+ async renderImages(request, signal) {
873
+ const { extension, source, pages, sheet, range, dpi, maxImages, maxPixels, maxDimension, maxBytes } = request;
874
+ const result = await this.queue.read({
875
+ extension,
876
+ priority: "foreground",
877
+ source,
878
+ operation: {
879
+ kind: "images",
880
+ ...pages === void 0 ? {} : { pages: [...pages] },
881
+ ...sheet === void 0 ? {} : { sheet },
882
+ ...range === void 0 ? {} : { range },
883
+ ...dpi === void 0 ? {} : { dpi },
884
+ maxImages,
885
+ maxPixels,
886
+ maxDimension,
887
+ maxBytes
888
+ }
889
+ }, signal);
890
+ return {
891
+ images: result.images,
892
+ pageCount: result.pageCount,
893
+ dpi: result.dpi,
894
+ missingFonts: result.missingFonts
895
+ };
896
+ }
897
+ /**
898
+ * Convert one document to another format at foreground priority, sharing admission, concurrency, and cache with
899
+ * previews, and save the result in the provider's output store.
900
+ * @param request - authorized metadata, deferred bounded source read, target format, and output owner and name.
901
+ * @param signal - caller cancellation; provider disposal also stops active work.
902
+ * @returns the saved file's absolute Host path and size; the file is deleted after `outputRetentionMs`, when older
903
+ * outputs need `maxOutputStoreBytes`, when the Session whose id is `output.owner` is disposed, or when the provider is disposed.
904
+ * @throws {OfficeKitError} `invalid-request` for a format or sheet the engine rejects and the other conversion
905
+ * codes; cancellation rejects with its reason.
906
+ */
907
+ async convertTo(request, signal) {
908
+ const { extension, source, format, sheet, output } = request;
909
+ return this.saveFile(output, await this.queue.read({
910
+ extension,
911
+ priority: "foreground",
912
+ source,
913
+ operation: {
914
+ kind: "convert",
915
+ format,
916
+ ...sheet === void 0 ? {} : { sheet }
917
+ }
918
+ }, signal), signal);
919
+ }
920
+ /**
921
+ * Recalculate every formula of one workbook at foreground priority and save formulas with refreshed cached results, sharing admission,
922
+ * concurrency, and cache with previews, and save the workbook in the provider's output store. This does not validate
923
+ * formulas or business data.
924
+ * @param request - authorized workbook metadata, deferred bounded source read, output format, and output owner and name.
925
+ * @param signal - caller cancellation; provider disposal also stops active work.
926
+ * @returns the saved workbook's absolute Host path and size, retained like {@link convertTo} outputs.
927
+ * @throws {OfficeKitError} Invalid input, unusable output, or engine failure; cancellation rejects with its reason.
928
+ */
929
+ async recalculate(request, signal) {
930
+ const { extension, source, format, output } = request;
931
+ return this.saveFile(output, await this.queue.read({
932
+ extension,
933
+ priority: "foreground",
934
+ source,
935
+ operation: {
936
+ kind: "recalculate",
937
+ format
938
+ }
939
+ }, signal), signal);
940
+ }
941
+ async saveFile(output, result, signal) {
942
+ signal?.throwIfAborted();
943
+ return {
944
+ path: await this.outputs.save(output.owner, output.name, result.data),
945
+ bytes: result.data.byteLength,
946
+ ...result.pageCount === void 0 ? {} : { pageCount: result.pageCount },
947
+ missingFonts: result.missingFonts
948
+ };
949
+ }
950
+ /**
951
+ * Read and convert one Office file using the Session's ordinary filesystem authorization.
952
+ * @param workspaceFileScope - Session header lookup shared with workspaceFiles.
953
+ * @param path - absolute or workspace-relative Office path.
954
+ * @param priority - foreground preview or speculative background work.
955
+ * @param signal - Remote cancellation; disposal also cancels outstanding reads and conversions.
956
+ * @returns complete PDF bytes with original source identity and missing font families.
957
+ */
958
+ async render(workspaceFileScope, path, priority, signal) {
959
+ const upstream = AbortSignal.any([signal, this.remoteLifetime.signal]);
960
+ const operation = this.renderFile(workspaceFileScope, path, priority, upstream);
961
+ this.remoteRequests.add(operation);
962
+ try {
963
+ return await operation;
964
+ } finally {
965
+ this.remoteRequests.delete(operation);
966
+ }
967
+ }
968
+ /**
969
+ * Read the current rendering generation before reusing a Client PDF.
970
+ * @param signal - Remote caller cancellation.
971
+ * @returns provider lifetime, replaced with rendering, font, or engine configuration.
972
+ */
973
+ getGeneration(signal) {
974
+ signal.throwIfAborted();
975
+ return this.generation;
976
+ }
977
+ async renderFile(scope, path, priority, signal) {
978
+ try {
979
+ signal.throwIfAborted();
980
+ const extension = extname(path).slice(1).toLowerCase();
981
+ if (extension !== "doc" && extension !== "docx" && extension !== "xls" && extension !== "xlsx" && extension !== "ppt" && extension !== "pptx") throw new OfficeKitError("unsupported-format", "The path must end in doc, docx, xls, xlsx, ppt, or pptx.");
982
+ const files = this.ctx.get("workspaceFiles");
983
+ const fs = this.ctx.get("fs");
984
+ if (files === void 0 || fs === void 0) throw new OfficeKitError("unavailable", "Office file rendering requires workspaceFiles and fs.");
985
+ const authorized = await files.readBytes(scope, path, { range: {
986
+ offset: 0,
987
+ length: 1
988
+ } }, signal);
989
+ const source = await files.stat(scope, path, signal);
990
+ const assertUnchanged = (current) => {
991
+ if (current.absolutePath !== source.absolutePath || current.version !== source.version) throw new OfficeKitError("source-changed", "The source changed.");
992
+ };
993
+ assertUnchanged(authorized);
994
+ signal.throwIfAborted();
995
+ const result = await this.convert({
996
+ extension,
997
+ priority,
998
+ source: {
999
+ key: brandString(JSON.stringify([
1000
+ scope.sessionId,
1001
+ scope.workspaceRoot,
1002
+ source.absolutePath
1003
+ ])),
1004
+ version: source.version,
1005
+ ...source.bytes === void 0 ? {} : { bytes: source.bytes },
1006
+ read: async (upstream, maxBytes) => {
1007
+ const target = await fs.resolve(source.absolutePath, { signal: upstream });
1008
+ const info = await fs.stat(target, upstream);
1009
+ if (info === void 0 || info.type !== "file") throw new OfficeKitError("source-changed", "The source changed.");
1010
+ assertUnchanged({
1011
+ absolutePath: fs.processPath(target),
1012
+ version: info.version
1013
+ });
1014
+ const bytes = await fs.readBytes(target, upstream, maxBytes).catch(async (cause) => {
1015
+ if (typeof cause === "object" && cause !== null && "code" in cause && cause.code === "FS_TOO_LARGE") {
1016
+ assertUnchanged(await files.stat(scope, path, upstream));
1017
+ throw new OfficeKitError("input-too-large", "The source exceeds the reserved byte capacity.", { cause });
1018
+ }
1019
+ throw cause;
1020
+ });
1021
+ upstream.throwIfAborted();
1022
+ assertUnchanged(await files.stat(scope, path, upstream));
1023
+ return {
1024
+ bytes,
1025
+ version: source.version
1026
+ };
1027
+ }
1028
+ }
1029
+ }, signal);
1030
+ signal.throwIfAborted();
1031
+ return {
1032
+ absolutePath: source.absolutePath,
1033
+ version: source.version,
1034
+ offset: 0,
1035
+ eof: true,
1036
+ bytes: result.pdf.byteLength,
1037
+ data: result.pdf,
1038
+ missingFonts: result.missingFonts,
1039
+ generation: result.generation
1040
+ };
1041
+ } catch (cause) {
1042
+ if (signal.aborted) throw new RemoteError("gateway/cancelled", "The document preview was cancelled.", {}, { cause });
1043
+ if (cause instanceof OfficeKitError) throw new RemoteError("document-render/failed", "Office conversion failed.", { reason: cause.code }, { cause });
1044
+ throw cause;
1045
+ }
1046
+ }
1047
+ /**
1048
+ * Locate and import Kit for a converter. A successful import is reused for the provider lifetime; a missing or
1049
+ * unloadable Kit rejects as `unavailable` without being retained, so the next converter request locates Kit again.
1050
+ */
1051
+ loadKit() {
1052
+ if (this.loadedKit !== void 0) return this.loadedKit;
1053
+ const loading = this.importKit();
1054
+ this.loadedKit = loading;
1055
+ loading.catch(() => {
1056
+ delete this.loadedKit;
1057
+ });
1058
+ return loading;
1059
+ }
1060
+ async importKit() {
1061
+ const kit = resolveKitModule(() => import.meta.resolve("@deepseek-ai/libreoffice-kit"));
1062
+ if (kit.kind === "missing") throw this.unavailableKit("LibreOffice Kit is not installed.", kit.error);
1063
+ let createConverter;
1064
+ try {
1065
+ ({createConverter} = await import(kit.entry));
1066
+ } catch (cause) {
1067
+ throw this.unavailableKit("LibreOffice Kit could not be loaded.", cause);
1068
+ }
1069
+ return {
1070
+ createConverter,
1071
+ resolveEnginePackage: kit.resolveEnginePackage
1072
+ };
1073
+ }
1074
+ /** Classify a Kit failure as `unavailable`, logging each distinct message and cause once per provider lifetime. */
1075
+ unavailableKit(message, cause) {
1076
+ const error = new OfficeKitError("unavailable", `${message} ${KIT_INSTALL_HINT}`, { cause });
1077
+ const key = `${message}\n${cause instanceof Error ? `${cause.name}: ${cause.message}` : String(cause)}`;
1078
+ if (!this.reportedKitFailures.has(key)) {
1079
+ this.reportedKitFailures.add(key);
1080
+ this.ctx.logger.warn(error);
1081
+ }
1082
+ return error;
1083
+ }
1084
+ async runOperation(bytes, request, signal) {
1085
+ signal.throwIfAborted();
1086
+ let slot = this.slots.find((candidate) => !candidate.busy);
1087
+ if (slot === void 0) {
1088
+ slot = { busy: false };
1089
+ this.slots.push(slot);
1090
+ }
1091
+ slot.busy = true;
1092
+ let directory;
1093
+ try {
1094
+ if (slot.converter === void 0) slot.converter = this.loadKit().then(({ createConverter, resolveEnginePackage }) => createConverter({
1095
+ ...this.options,
1096
+ resolveEnginePackage
1097
+ })).catch((error) => {
1098
+ delete slot.converter;
1099
+ throw error;
1100
+ });
1101
+ const converter = await slot.converter;
1102
+ signal.throwIfAborted();
1103
+ directory = await mkdtemp(join(tmpdir(), "dsh-office-kit-"));
1104
+ const inputPath = join(directory, `source.${request.extension}`);
1105
+ await writeFile(inputPath, bytes, {
1106
+ flag: "wx",
1107
+ mode: 384,
1108
+ signal
1109
+ });
1110
+ signal.throwIfAborted();
1111
+ const output = await this.runEngine(converter, inputPath, directory, request.operation, signal);
1112
+ signal.throwIfAborted();
1113
+ return output;
1114
+ } catch (cause) {
1115
+ signal.throwIfAborted();
1116
+ if (cause instanceof OfficeKitError) throw cause;
1117
+ if (cause instanceof TypeError || cause instanceof RangeError) throw new OfficeKitError("invalid-request", cause.message, { cause });
1118
+ const code = typeof cause === "object" && cause !== null && "code" in cause ? cause.code : void 0;
1119
+ switch (code) {
1120
+ case "input-too-large":
1121
+ case "output-too-large":
1122
+ case "invalid-document":
1123
+ case "unsupported-format":
1124
+ case "invalid-output":
1125
+ case "timeout":
1126
+ case "unavailable": throw new OfficeKitError(code, cause instanceof Error ? cause.message : "LibreOffice conversion failed.", { cause });
1127
+ default: throw new OfficeKitError("failed", "LibreOffice conversion failed.", { cause });
1128
+ }
1129
+ } finally {
1130
+ try {
1131
+ if (directory !== void 0) await rm(directory, {
1132
+ recursive: true,
1133
+ force: true
1134
+ });
1135
+ } finally {
1136
+ slot.busy = false;
1137
+ }
1138
+ }
1139
+ }
1140
+ /** Run one engine operation in a private scratch directory and read its complete, bounded output. */
1141
+ async runEngine(converter, inputPath, directory, operation, signal) {
1142
+ switch (operation.kind) {
1143
+ case "pdf": {
1144
+ const outputPath = join(directory, "converted.pdf");
1145
+ const result = await converter.render({
1146
+ inputPath,
1147
+ outputPath
1148
+ }, signal);
1149
+ return {
1150
+ kind: "pdf",
1151
+ pdf: await this.readFile(outputPath, "pdf", signal),
1152
+ missingFonts: result.missingFonts
1153
+ };
1154
+ }
1155
+ case "convert":
1156
+ case "recalculate": {
1157
+ const outputPath = join(directory, `output.${operation.format}`);
1158
+ const result = operation.kind === "convert" ? await converter.convert({
1159
+ inputPath,
1160
+ outputPath,
1161
+ ...operation.sheet === void 0 ? {} : { sheet: operation.sheet }
1162
+ }, signal) : await converter.recalculate({
1163
+ inputPath,
1164
+ outputPath
1165
+ }, signal);
1166
+ return {
1167
+ kind: "file",
1168
+ data: await this.readFile(outputPath, operation.format, signal),
1169
+ ...result.pageCount === void 0 ? {} : { pageCount: result.pageCount },
1170
+ missingFonts: result.missingFonts
1171
+ };
1172
+ }
1173
+ case "images": return this.renderPng(converter, inputPath, directory, operation, signal);
1174
+ /* v8 ignore next -- OfficeOperation is a closed union */
1175
+ default: throw new Error(`Unexpected Office operation: ${JSON.stringify(operation)}`);
1176
+ }
1177
+ }
1178
+ async readFile(path, format, signal) {
1179
+ try {
1180
+ return format === "pdf" ? await readPdf(path, this.config.maxOutputBytes, signal) : await readOutput(path, this.config.maxOutputBytes, signal);
1181
+ } catch (cause) {
1182
+ if (cause instanceof OfficeKitError) throw cause;
1183
+ throw new OfficeKitError("invalid-output", "The converter output could not be read.", { cause });
1184
+ }
1185
+ }
1186
+ async renderPng(converter, inputPath, directory, operation, signal) {
1187
+ const outputDir = join(directory, "images");
1188
+ const result = await converter.renderImages({
1189
+ inputPath,
1190
+ outputDir,
1191
+ ...operation.pages === void 0 ? {} : { pages: operation.pages },
1192
+ ...operation.sheet === void 0 ? {} : { sheet: operation.sheet },
1193
+ ...operation.range === void 0 ? {} : { range: operation.range },
1194
+ ...operation.dpi === void 0 ? {} : { dpi: operation.dpi },
1195
+ maxPages: operation.maxImages,
1196
+ maxPixels: operation.maxPixels,
1197
+ maxDimension: operation.maxDimension
1198
+ }, signal);
1199
+ const declared = result.images.reduce((sum, image) => sum + image.byteLength, 0);
1200
+ if (declared > operation.maxBytes) throw new OfficeKitError("output-too-large", `The rendered images total ${declared} bytes, above the ${operation.maxBytes}-byte limit.`);
1201
+ const images = [];
1202
+ let remaining = operation.maxBytes;
1203
+ for (const image of [...result.images].sort((left, right) => left.index - right.index)) {
1204
+ const within = relative(outputDir, image.path);
1205
+ if (within === "" || within === ".." || within.startsWith(`..${sep}`) || isAbsolute(within)) throw new OfficeKitError("invalid-output", "The converter reported an image outside its output directory.");
1206
+ let png;
1207
+ try {
1208
+ png = await readPng(image.path, remaining, signal);
1209
+ } catch (cause) {
1210
+ if (cause instanceof OfficeKitError) throw cause;
1211
+ throw new OfficeKitError("invalid-output", "The rendered image could not be read.", { cause });
1212
+ }
1213
+ remaining -= png.byteLength;
1214
+ images.push({
1215
+ png,
1216
+ width: image.width,
1217
+ height: image.height,
1218
+ ...image.page === void 0 ? {} : { page: image.page },
1219
+ ...image.sheet === void 0 ? {} : { sheet: image.sheet },
1220
+ ...image.range === void 0 ? {} : { range: image.range }
1221
+ });
1222
+ }
1223
+ return {
1224
+ kind: "images",
1225
+ images,
1226
+ pageCount: result.pageCount,
1227
+ dpi: result.dpi,
1228
+ missingFonts: result.missingFonts
1229
+ };
1230
+ }
1231
+ };
1232
+ })();
1233
+ //#endregion
1234
+ export { Config, OfficeKit, OfficeKit as default, OfficeKitError, OfficeKitGeneration, OfficeKitKey, OfficeSourceKey };