@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/package.json CHANGED
@@ -1,6 +1,71 @@
1
1
  {
2
2
  "name": "@deepseek-ai/dsh-office-kit",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "description": "Shared Office rendering, conversion, and recalculation with bounded queues and caching",
4
+ "version": "0.2.2-rc.3",
5
+ "publishConfig": {
6
+ "access": "public"
7
+ },
8
+ "type": "module",
9
+ "main": "lib/index.js",
10
+ "types": "lib/types/index.d.ts",
11
+ "license": "MIT",
12
+ "repository": {
13
+ "type": "git",
14
+ "url": "git+https://github.com/deepseek-ai/deepseek-harness.git",
15
+ "directory": "packages/document/office-kit"
16
+ },
17
+ "exports": {
18
+ ".": {
19
+ "types": "./lib/types/index.d.ts",
20
+ "default": "./lib/index.js"
21
+ },
22
+ "./src/*": "./src/*",
23
+ "./package.json": "./package.json",
24
+ "./types": {
25
+ "types": "./lib/types/types.d.ts",
26
+ "default": "./lib/types/types.js"
27
+ },
28
+ "./remote": {
29
+ "types": "./lib/typert.remote-client.d.ts",
30
+ "default": "./lib/typert.remote-client.js"
31
+ },
32
+ "./typert": {
33
+ "types": "./lib/typert.host.d.ts",
34
+ "default": "./lib/typert.host.js"
35
+ },
36
+ "./locale/*.json": "./locale/*.json"
37
+ },
38
+ "files": [
39
+ "locale/*.json",
40
+ "lib/index.js",
41
+ "lib/types/**/*.js",
42
+ "lib/types/**/*.d.ts",
43
+ "lib/types/**/*.d.ts.map",
44
+ "lib/**/*.js.map",
45
+ "lib/typert.host.js",
46
+ "lib/typert.host.d.ts",
47
+ "lib/typert.remote-client.js",
48
+ "lib/typert.remote-client.d.ts",
49
+ "lib/typert.remote-client.d.ts.map",
50
+ "src"
51
+ ],
52
+ "peerDependencies": {
53
+ "@deepseek-ai/cordis": "~4.1.0"
54
+ },
55
+ "devDependencies": {
56
+ "@deepseek-ai/cordis": "~4.1.0",
57
+ "@deepseek-ai/cordis-plugin-loader": "~1.1.0",
58
+ "@deepseek-ai/cordis-plugin-include": "~1.1.0",
59
+ "@deepseek-ai/dsh-api-workspace-files": "0.2.2-rc.3",
60
+ "@deepseek-ai/dsh-fs": "0.2.2-rc.3",
61
+ "@deepseek-ai/dsh-session": "0.2.2-rc.3"
62
+ },
63
+ "dependencies": {
64
+ "@deepseek-ai/libreoffice-kit": "0.2.3",
65
+ "@deepseek-ai/schemastery": "~3.19.0",
66
+ "@deepseek-ai/dsh-brand": "0.2.2-rc.3",
67
+ "@deepseek-ai/dsh-typert-protocol": "0.2.2-rc.3",
68
+ "zod": "4.6.6",
69
+ "@deepseek-ai/dsh-home-paths": "0.2.2-rc.3"
70
+ }
6
71
  }
package/src/errors.ts ADDED
@@ -0,0 +1,15 @@
1
+ /** Classified failures shared by conversion and its consumers. */
2
+ import type { OfficeKitErrorCode } from './types.ts'
3
+
4
+ /** Classified conversion failure; engine details stay in the cause. */
5
+ export class OfficeKitError extends Error {
6
+ /**
7
+ * @param code - category suitable for a conversion consumer.
8
+ * @param message - diagnostic explaining the failed conversion.
9
+ * @param options - underlying engine or filesystem failure.
10
+ */
11
+ constructor(readonly code: OfficeKitErrorCode, message: string, options?: ErrorOptions) {
12
+ super(message, options)
13
+ this.name = 'OfficeKitError'
14
+ }
15
+ }
@@ -0,0 +1,31 @@
1
+ /** Source locators and converter-owned identities for shared PDF reuse. */
2
+ import { brandString, type Branded } from '@deepseek-ai/dsh-brand'
3
+
4
+ /** Authorized execution scope and canonical source path, encoded by the consumer. */
5
+ export type OfficeSourceKey = Branded<'OfficeSourceKey'>
6
+ /**
7
+ * Label an authorized source locator for pre-read deduplication.
8
+ * @param key - unambiguous encoding of authorization scope, execution world, and canonical path.
9
+ * @returns branded source locator; source authorization remains the caller's responsibility.
10
+ */
11
+ export function OfficeSourceKey(key: string): OfficeSourceKey { return brandString<OfficeSourceKey>(key) }
12
+
13
+ /** One provider lifetime, including its engine, rendering settings, and font configuration. */
14
+ export type OfficeKitGeneration = Branded<'OfficeKitGeneration'>
15
+ /**
16
+ * Label a provider lifetime.
17
+ * @param value - unique generation created by the provider.
18
+ * @returns branded converter generation.
19
+ */
20
+ export function OfficeKitGeneration(value: string): OfficeKitGeneration {
21
+ return brandString<OfficeKitGeneration>(value)
22
+ }
23
+
24
+ /** Provider generation and source-content digest; consumers must not parse it. */
25
+ export type OfficeKitKey = Branded<'OfficeKitKey'>
26
+ /**
27
+ * Label a converter-owned content identity.
28
+ * @param value - generation and content identity created by the provider.
29
+ * @returns branded conversion identity.
30
+ */
31
+ export function OfficeKitKey(value: string): OfficeKitKey { return brandString<OfficeKitKey>(value) }
package/src/index.ts ADDED
@@ -0,0 +1,484 @@
1
+ /** Host LibreOffice Kit provider with reusable converters, shared admission, and private disk input/output. */
2
+ import { randomUUID } from 'node:crypto'
3
+ import { mkdtemp, rm, writeFile } from 'node:fs/promises'
4
+ import { tmpdir } from 'node:os'
5
+ import { extname, isAbsolute, join, relative, sep } from 'node:path'
6
+ import { Context } from '@deepseek-ai/cordis'
7
+ import type { Converter, ConverterOptions } from '@deepseek-ai/libreoffice-kit'
8
+ import z from '@deepseek-ai/schemastery'
9
+ import type { WorkspaceFileScope, WorkspaceFileStat } from '@deepseek-ai/dsh-api-workspace-files'
10
+ import type {} from '@deepseek-ai/dsh-fs'
11
+ import type {} from '@deepseek-ai/dsh-session'
12
+ import { dshHomePath } from '@deepseek-ai/dsh-home-paths'
13
+ import { brandString } from '@deepseek-ai/dsh-brand'
14
+ import { resolveKitModule } from './locate.ts'
15
+ import { Remote, RemoteError, TypertRemoteService } from '@deepseek-ai/dsh-typert-protocol'
16
+ import { OfficeKitError } from './errors.ts'
17
+ import { OfficeKitGeneration, type OfficeSourceKey } from './identity.ts'
18
+ import type {
19
+ OfficeConversionRequest, OfficeFileResult, OfficeImagesRequest, OfficeImagesResult, OfficeKitRequest, OfficeKitResult,
20
+ OfficeKitPriority, OfficeOutputTarget, OfficeRecalculationRequest, RenderedDocumentBytes,
21
+ } from './types.ts'
22
+ import { readOutput, readPdf, readPng } from './output.ts'
23
+ import { OutputStore } from './outputs.ts'
24
+ import { ConversionQueue, type OfficeOperation, type OfficeOperationOutput, type QueueRequest } from './queue.ts'
25
+
26
+ export * from './errors.ts'
27
+ export * from './identity.ts'
28
+ export * from './types.ts'
29
+
30
+ declare module '@deepseek-ai/cordis' {
31
+ interface Context {
32
+ /** Shared Office rendering, conversion, recalculation, and authorized workspace-file previews. */
33
+ officeKit: OfficeKit
34
+ }
35
+ }
36
+
37
+ /** Provider concurrency and kit rendering/font configuration. */
38
+ export interface Config {
39
+ /** Maximum simultaneous conversions; queued callers remain cancellable. */
40
+ maxConcurrentConversions: number
41
+ /** Maximum metadata-only jobs awaiting source admission. */
42
+ maxQueuedJobs: number
43
+ /** Maximum outstanding conversion readers. */
44
+ maxReaders: number
45
+ /** Maximum reserved bytes across admitted source reads and conversions. */
46
+ maxSourceBytes: number
47
+ /** Maximum concurrent background jobs; zero refuses speculative work. */
48
+ maxBackgroundConversions: number
49
+ /** Maximum retained content-addressed outputs. */
50
+ maxCachedEntries: number
51
+ /** Maximum retained output bytes. */
52
+ maxCachedBytes: number
53
+ /** Maximum retained source-version aliases to cached content. */
54
+ maxSourceEntries: number
55
+ /** Absolute directory for converted and recalculated files, with one subdirectory per Session. */
56
+ outputDirectory: string
57
+ /** Milliseconds a converted or recalculated file is kept. */
58
+ outputRetentionMs: number
59
+ /** Maximum bytes across retained converted and recalculated files; the oldest leave first. */
60
+ maxOutputStoreBytes: number
61
+ /** Conversion deadline in milliseconds; excludes the DSH queue. */
62
+ timeoutMs: number
63
+ /** Maximum authorized source bytes. */
64
+ maxInputBytes: number
65
+ /** Maximum complete PDF, converted, or recalculated file bytes. */
66
+ maxOutputBytes: number
67
+ /** Image resolution in DPI of PDF exports; `renderImages()` takes its resolution from each request's `dpi`. */
68
+ maxImageResolution: number
69
+ /** Maximum OOXML ZIP entries. */
70
+ maxArchiveEntries: number
71
+ /** Maximum total declared uncompressed OOXML bytes. */
72
+ maxUncompressedBytes: number
73
+ /** Absolute font roots; omission uses the kit's platform defaults. */
74
+ fontDirectories?: string[]
75
+ /** Ordered font-family preference groups; omission retains the kit defaults. */
76
+ fontFallbacks?: string[][]
77
+ /** Maximum physical font files indexed by each converter. */
78
+ maxFontFiles: number
79
+ /** Maximum individual font-file bytes. */
80
+ maxFontFileBytes: number
81
+ /** Maximum original font bytes loaded for a conversion. */
82
+ maxLoadedFontBytes: number
83
+ }
84
+
85
+ /** Deployment defaults resolved before provider construction. */
86
+ export const Config: z<Partial<Config>, Config> = z.object({
87
+ maxConcurrentConversions: z.natural().min(1).max(Number.MAX_SAFE_INTEGER).default(2),
88
+ maxQueuedJobs: z.natural().min(1).max(Number.MAX_SAFE_INTEGER).default(8),
89
+ maxReaders: z.natural().min(1).max(Number.MAX_SAFE_INTEGER).default(32),
90
+ maxSourceBytes: z.natural().min(1).max(Number.MAX_SAFE_INTEGER).default(104857600),
91
+ maxBackgroundConversions: z.natural().min(0).max(Number.MAX_SAFE_INTEGER).default(1),
92
+ maxCachedEntries: z.natural().min(1).max(Number.MAX_SAFE_INTEGER).default(8),
93
+ maxCachedBytes: z.natural().min(1).max(Number.MAX_SAFE_INTEGER).default(134217728),
94
+ maxSourceEntries: z.natural().min(1).max(Number.MAX_SAFE_INTEGER).default(64),
95
+ outputDirectory: z.string().min(1).default(dshHomePath('office-kit', 'outputs')),
96
+ outputRetentionMs: z.natural().min(1).max(2_147_483_647).default(24 * 60 * 60 * 1000),
97
+ maxOutputStoreBytes: z.natural().min(1).max(Number.MAX_SAFE_INTEGER).default(512 * 1024 * 1024),
98
+ timeoutMs: z.natural().min(1).max(2_147_483_647).default(60_000),
99
+ maxInputBytes: z.natural().min(1).max(Number.MAX_SAFE_INTEGER - 1).default(50 * 1024 * 1024),
100
+ maxOutputBytes: z.natural().min(1).max(Number.MAX_SAFE_INTEGER - 1).default(100 * 1024 * 1024),
101
+ maxImageResolution: z.natural().min(1).max(2_147_483_647).default(192),
102
+ maxArchiveEntries: z.natural().min(1).max(Number.MAX_SAFE_INTEGER).default(10_000),
103
+ maxUncompressedBytes: z.natural().min(1).max(Number.MAX_SAFE_INTEGER).default(250 * 1024 * 1024),
104
+ fontDirectories: z.array(z.string().min(1)).extra('default', undefined),
105
+ fontFallbacks: z.array(z.array(z.string().pattern(/\S/)).min(2)).extra('default', undefined),
106
+ maxFontFiles: z.natural().min(1).max(Number.MAX_SAFE_INTEGER).default(20_000),
107
+ maxFontFileBytes: z.natural().min(1).max(Number.MAX_SAFE_INTEGER).default(256 * 1024 * 1024),
108
+ maxLoadedFontBytes: z.natural().min(1).max(Number.MAX_SAFE_INTEGER).default(512 * 1024 * 1024),
109
+ })
110
+
111
+ /** Kit operations loaded from the provider's Kit entry. */
112
+ type KitModule = Pick<typeof import('@deepseek-ai/libreoffice-kit'), 'createConverter'>
113
+
114
+ /** Imported Kit operations with the engine resolver anchored at the same Kit entry. */
115
+ interface LoadedKit extends KitModule {
116
+ readonly resolveEnginePackage: NonNullable<ConverterOptions['resolveEnginePackage']>
117
+ }
118
+
119
+ const KIT_INSTALL_HINT = 'This deployment does not provide LibreOffice Kit; install or enable it as this deployment requires, then retry.'
120
+
121
+ interface Slot {
122
+ busy: boolean
123
+ converter?: Promise<Converter>
124
+ }
125
+
126
+ /** A provider lifetime owns all converters, queued calls, and temporary files. */
127
+ export class OfficeKit extends TypertRemoteService {
128
+ static Config = Config
129
+ /** Changes whenever engine, font, or conversion configuration is replaced. */
130
+ readonly generation: OfficeKitGeneration = OfficeKitGeneration(randomUUID())
131
+ /** Absolute Host directory holding converted and recalculated files; consumers check that their execution world reads it. */
132
+ readonly outputDirectory: string
133
+ private readonly remoteLifetime = new AbortController()
134
+ private readonly remoteRequests = new Set<Promise<RenderedDocumentBytes>>()
135
+ private readonly slots: Slot[] = []
136
+ private readonly queue: ConversionQueue
137
+ private readonly outputs: OutputStore
138
+ private readonly options: Omit<ConverterOptions, 'resolveEnginePackage'>
139
+ private loadedKit?: Promise<LoadedKit>
140
+ private readonly reportedKitFailures = new Set<string>()
141
+
142
+ /**
143
+ * @param ctx - owning Host context.
144
+ * @param config - resolved rendering, font, and concurrency limits.
145
+ */
146
+ constructor(ctx: Context, private readonly config: Config) {
147
+ super(ctx, 'officeKit')
148
+ if (config.fontDirectories?.some(path => !isAbsolute(path))) throw new Error('fontDirectories must contain absolute paths.')
149
+ if (config.maxSourceBytes < config.maxInputBytes) throw new Error('maxSourceBytes must be at least maxInputBytes.')
150
+ if (!isAbsolute(config.outputDirectory)) throw new Error('outputDirectory must be an absolute path.')
151
+ const { fontDirectories, fontFallbacks, timeoutMs, maxInputBytes, maxOutputBytes, maxImageResolution,
152
+ maxArchiveEntries, maxUncompressedBytes, maxFontFiles, maxFontFileBytes, maxLoadedFontBytes } = config
153
+ this.options = { timeoutMs, maxInputBytes, maxOutputBytes, maxImageResolution,
154
+ maxArchiveEntries, maxUncompressedBytes, maxFontFiles, maxFontFileBytes, maxLoadedFontBytes,
155
+ ...(fontDirectories === undefined ? {} : { fontDirectories }),
156
+ ...(fontFallbacks === undefined ? {} : { fontFallbacks }),
157
+ }
158
+ this.queue = new ConversionQueue(config, this.generation, (bytes, request, signal) => this.runOperation(bytes, request, signal))
159
+ this.outputDirectory = config.outputDirectory
160
+ this.outputs = new OutputStore({ root: config.outputDirectory, retentionMs: config.outputRetentionMs,
161
+ maxBytes: config.maxOutputStoreBytes }, ctx.logger.warn.bind(ctx.logger))
162
+ // The output store records this release, and its disposal below waits for the release to settle.
163
+ ctx.on('session/disposed', (session) => { void this.outputs.release(session.id) })
164
+ ctx.effect(() => async () => {
165
+ this.remoteLifetime.abort()
166
+ await this.queue.dispose()
167
+ await this.outputs.dispose()
168
+ await Promise.allSettled(this.remoteRequests)
169
+ const results = await Promise.allSettled(this.slots.map(async (slot) => {
170
+ const converter = await slot.converter
171
+ await converter?.dispose()
172
+ }))
173
+ const failures = results.filter(result => result.status === 'rejected')
174
+ if (failures.length > 0) throw new AggregateError(failures.map((result): unknown => result.reason), 'LibreOffice converter disposal failed.')
175
+ })
176
+ }
177
+
178
+ /**
179
+ * Convert Office bytes to PDF without modifying the source or writing Session events.
180
+ * @param request - authorized metadata and deferred bounded source read.
181
+ * @param signal - caller cancellation; provider disposal also stops active work.
182
+ * @returns caller-owned PDF bytes after conversion and scratch cleanup settle; canceled readers reject independently.
183
+ * @throws {OfficeKitError} Invalid input, unusable output, or engine failure; cancellation rejects with its reason.
184
+ */
185
+ async convert(request: OfficeKitRequest, signal?: AbortSignal): Promise<OfficeKitResult> {
186
+ const { kind: _kind, ...result } = await this.queue.read({ ...request, operation: { kind: 'pdf' } }, signal)
187
+ return result
188
+ }
189
+
190
+ /**
191
+ * Render selected pages, slides, or worksheet areas of one document as PNG images. Requests share the admission
192
+ * queue, concurrency, source-byte reservation, and cache with previews, and run at foreground priority.
193
+ * @param request - authorized metadata, deferred bounded source read, selection, and complete-result limits.
194
+ * @param signal - caller cancellation; provider disposal also stops active work.
195
+ * @returns caller-owned images in document order whose count, per-image size, and total bytes satisfy the limits.
196
+ * @throws {OfficeKitError} `invalid-request` for a selection the engine rejects, `output-too-large` when the
197
+ * selection exceeds a limit, and the other conversion codes; cancellation rejects with its reason.
198
+ */
199
+ async renderImages(request: OfficeImagesRequest, signal?: AbortSignal): Promise<OfficeImagesResult> {
200
+ const { extension, source, pages, sheet, range, dpi, maxImages, maxPixels, maxDimension, maxBytes } = request
201
+ const result = await this.queue.read({ extension, priority: 'foreground', source, operation: {
202
+ kind: 'images',
203
+ ...(pages === undefined ? {} : { pages: [...pages] }),
204
+ ...(sheet === undefined ? {} : { sheet }),
205
+ ...(range === undefined ? {} : { range }),
206
+ ...(dpi === undefined ? {} : { dpi }),
207
+ maxImages, maxPixels, maxDimension, maxBytes,
208
+ } }, signal)
209
+ return { images: result.images, pageCount: result.pageCount, dpi: result.dpi, missingFonts: result.missingFonts }
210
+ }
211
+
212
+ /**
213
+ * Convert one document to another format at foreground priority, sharing admission, concurrency, and cache with
214
+ * previews, and save the result in the provider's output store.
215
+ * @param request - authorized metadata, deferred bounded source read, target format, and output owner and name.
216
+ * @param signal - caller cancellation; provider disposal also stops active work.
217
+ * @returns the saved file's absolute Host path and size; the file is deleted after `outputRetentionMs`, when older
218
+ * outputs need `maxOutputStoreBytes`, when the Session whose id is `output.owner` is disposed, or when the provider is disposed.
219
+ * @throws {OfficeKitError} `invalid-request` for a format or sheet the engine rejects and the other conversion
220
+ * codes; cancellation rejects with its reason.
221
+ */
222
+ async convertTo(request: OfficeConversionRequest, signal?: AbortSignal): Promise<OfficeFileResult> {
223
+ const { extension, source, format, sheet, output } = request
224
+ return this.saveFile(output, await this.queue.read({ extension, priority: 'foreground', source,
225
+ operation: { kind: 'convert', format, ...(sheet === undefined ? {} : { sheet }) } }, signal), signal)
226
+ }
227
+
228
+ /**
229
+ * Recalculate every formula of one workbook at foreground priority and save formulas with refreshed cached results, sharing admission,
230
+ * concurrency, and cache with previews, and save the workbook in the provider's output store. This does not validate
231
+ * formulas or business data.
232
+ * @param request - authorized workbook metadata, deferred bounded source read, output format, and output owner and name.
233
+ * @param signal - caller cancellation; provider disposal also stops active work.
234
+ * @returns the saved workbook's absolute Host path and size, retained like {@link convertTo} outputs.
235
+ * @throws {OfficeKitError} Invalid input, unusable output, or engine failure; cancellation rejects with its reason.
236
+ */
237
+ async recalculate(request: OfficeRecalculationRequest, signal?: AbortSignal): Promise<OfficeFileResult> {
238
+ const { extension, source, format, output } = request
239
+ return this.saveFile(output, await this.queue.read({ extension, priority: 'foreground', source, operation: { kind: 'recalculate', format } }, signal), signal)
240
+ }
241
+
242
+ private async saveFile(
243
+ output: OfficeOutputTarget, result: Extract<OfficeOperationOutput, { kind: 'file' }>,
244
+ signal: AbortSignal | undefined,
245
+ ): Promise<OfficeFileResult> {
246
+ signal?.throwIfAborted()
247
+ const path = await this.outputs.save(output.owner, output.name, result.data)
248
+ return { path, bytes: result.data.byteLength, ...(result.pageCount === undefined ? {} : { pageCount: result.pageCount }),
249
+ missingFonts: result.missingFonts }
250
+ }
251
+
252
+ /**
253
+ * Read and convert one Office file using the Session's ordinary filesystem authorization.
254
+ * @param workspaceFileScope - Session header lookup shared with workspaceFiles.
255
+ * @param path - absolute or workspace-relative Office path.
256
+ * @param priority - foreground preview or speculative background work.
257
+ * @param signal - Remote cancellation; disposal also cancels outstanding reads and conversions.
258
+ * @returns complete PDF bytes with original source identity and missing font families.
259
+ */
260
+ @Remote
261
+ async render(
262
+ workspaceFileScope: WorkspaceFileScope, path: string, priority: OfficeKitPriority, signal: AbortSignal,
263
+ ): Promise<RenderedDocumentBytes> {
264
+ const upstream = AbortSignal.any([signal, this.remoteLifetime.signal])
265
+ const operation = this.renderFile(workspaceFileScope, path, priority, upstream)
266
+ this.remoteRequests.add(operation)
267
+ try { return await operation } finally { this.remoteRequests.delete(operation) }
268
+ }
269
+
270
+ /**
271
+ * Read the current rendering generation before reusing a Client PDF.
272
+ * @param signal - Remote caller cancellation.
273
+ * @returns provider lifetime, replaced with rendering, font, or engine configuration.
274
+ */
275
+ @Remote('generation')
276
+ getGeneration(signal: AbortSignal): OfficeKitGeneration { signal.throwIfAborted(); return this.generation }
277
+
278
+ private async renderFile(
279
+ scope: WorkspaceFileScope, path: string, priority: OfficeKitPriority, signal: AbortSignal,
280
+ ): Promise<RenderedDocumentBytes> {
281
+ try {
282
+ signal.throwIfAborted()
283
+ const extension = extname(path).slice(1).toLowerCase()
284
+ if (extension !== 'doc' && extension !== 'docx' && extension !== 'xls'
285
+ && extension !== 'xlsx' && extension !== 'ppt' && extension !== 'pptx') {
286
+ throw new OfficeKitError('unsupported-format', 'The path must end in doc, docx, xls, xlsx, ppt, or pptx.')
287
+ }
288
+ const files = this.ctx.get('workspaceFiles')
289
+ const fs = this.ctx.get('fs')
290
+ if (files === undefined || fs === undefined) throw new OfficeKitError('unavailable', 'Office file rendering requires workspaceFiles and fs.')
291
+ const authorized = await files.readBytes(scope, path, { range: { offset: 0, length: 1 } }, signal)
292
+ const source = await files.stat(scope, path, signal)
293
+ const assertUnchanged = (current: WorkspaceFileStat): void => {
294
+ if (current.absolutePath !== source.absolutePath || current.version !== source.version) {
295
+ throw new OfficeKitError('source-changed', 'The source changed.')
296
+ }
297
+ }
298
+ assertUnchanged(authorized)
299
+ signal.throwIfAborted()
300
+ const result = await this.convert({ extension, priority, source: {
301
+ key: brandString<OfficeSourceKey>(JSON.stringify([scope.sessionId, scope.workspaceRoot, source.absolutePath])),
302
+ version: source.version, ...(source.bytes === undefined ? {} : { bytes: source.bytes }),
303
+ read: async (upstream, maxBytes) => {
304
+ const target = await fs.resolve(source.absolutePath, { signal: upstream })
305
+ const info = await fs.stat(target, upstream)
306
+ if (info === undefined || info.type !== 'file') throw new OfficeKitError('source-changed', 'The source changed.')
307
+ assertUnchanged({ absolutePath: fs.processPath(target), version: info.version })
308
+ const bytes = await fs.readBytes(target, upstream, maxBytes).catch(async (cause: unknown) => {
309
+ if (typeof cause === 'object' && cause !== null && 'code' in cause && cause.code === 'FS_TOO_LARGE') {
310
+ assertUnchanged(await files.stat(scope, path, upstream))
311
+ throw new OfficeKitError('input-too-large', 'The source exceeds the reserved byte capacity.', { cause })
312
+ }
313
+ throw cause
314
+ })
315
+ upstream.throwIfAborted()
316
+ const after = await files.stat(scope, path, upstream)
317
+ assertUnchanged(after)
318
+ return { bytes, version: source.version }
319
+ },
320
+ } }, signal)
321
+ signal.throwIfAborted()
322
+ return { absolutePath: source.absolutePath, version: source.version,
323
+ offset: 0, eof: true, bytes: result.pdf.byteLength, data: result.pdf,
324
+ missingFonts: result.missingFonts, generation: result.generation }
325
+ } catch (cause) {
326
+ if (signal.aborted) throw new RemoteError('gateway/cancelled', 'The document preview was cancelled.', {}, { cause })
327
+ if (cause instanceof OfficeKitError) {
328
+ throw new RemoteError('document-render/failed', 'Office conversion failed.', { reason: cause.code }, { cause })
329
+ }
330
+ throw cause
331
+ }
332
+ }
333
+
334
+ /**
335
+ * Locate and import Kit for a converter. A successful import is reused for the provider lifetime; a missing or
336
+ * unloadable Kit rejects as `unavailable` without being retained, so the next converter request locates Kit again.
337
+ */
338
+ private loadKit(): Promise<LoadedKit> {
339
+ if (this.loadedKit !== undefined) return this.loadedKit
340
+ const loading = this.importKit()
341
+ this.loadedKit = loading
342
+ loading.catch(() => { delete this.loadedKit })
343
+ return loading
344
+ }
345
+
346
+ private async importKit(): Promise<LoadedKit> {
347
+ const kit = resolveKitModule(() => import.meta.resolve('@deepseek-ai/libreoffice-kit'))
348
+ if (kit.kind === 'missing') throw this.unavailableKit('LibreOffice Kit is not installed.', kit.error)
349
+ let createConverter: KitModule['createConverter']
350
+ try {
351
+ ({ createConverter } = await import(kit.entry) as KitModule)
352
+ } catch (cause) {
353
+ throw this.unavailableKit('LibreOffice Kit could not be loaded.', cause)
354
+ }
355
+ return { createConverter, resolveEnginePackage: kit.resolveEnginePackage }
356
+ }
357
+
358
+ /** Classify a Kit failure as `unavailable`, logging each distinct message and cause once per provider lifetime. */
359
+ private unavailableKit(message: string, cause: unknown): OfficeKitError {
360
+ const error = new OfficeKitError('unavailable', `${message} ${KIT_INSTALL_HINT}`, { cause })
361
+ const key = `${message}\n${cause instanceof Error ? `${cause.name}: ${cause.message}` : String(cause)}`
362
+ if (!this.reportedKitFailures.has(key)) {
363
+ this.reportedKitFailures.add(key)
364
+ this.ctx.logger.warn(error)
365
+ }
366
+ return error
367
+ }
368
+
369
+ private async runOperation(
370
+ bytes: Uint8Array, request: Pick<QueueRequest, 'extension' | 'operation'>, signal: AbortSignal,
371
+ ): Promise<OfficeOperationOutput> {
372
+ signal.throwIfAborted()
373
+ let slot = this.slots.find(candidate => !candidate.busy)
374
+ if (slot === undefined) { slot = { busy: false }; this.slots.push(slot) }
375
+ slot.busy = true
376
+ let directory: string | undefined
377
+ try {
378
+ if (slot.converter === undefined) {
379
+ slot.converter = this.loadKit().then(({ createConverter, resolveEnginePackage }) =>
380
+ createConverter({ ...this.options, resolveEnginePackage })).catch((error: unknown) => {
381
+ delete slot.converter
382
+ throw error
383
+ })
384
+ }
385
+ const converter = await slot.converter
386
+ signal.throwIfAborted()
387
+ directory = await mkdtemp(join(tmpdir(), 'dsh-office-kit-'))
388
+ const inputPath = join(directory, `source.${request.extension}`)
389
+ await writeFile(inputPath, bytes, { flag: 'wx', mode: 0o600, signal })
390
+ signal.throwIfAborted()
391
+ const output = await this.runEngine(converter, inputPath, directory, request.operation, signal)
392
+ signal.throwIfAborted()
393
+ return output
394
+ } catch (cause) {
395
+ signal.throwIfAborted()
396
+ if (cause instanceof OfficeKitError) throw cause
397
+ if (cause instanceof TypeError || cause instanceof RangeError) throw new OfficeKitError('invalid-request', cause.message, { cause })
398
+ const code = typeof cause === 'object' && cause !== null && 'code' in cause ? cause.code : undefined
399
+ switch (code) {
400
+ case 'input-too-large': case 'output-too-large': case 'invalid-document': case 'unsupported-format':
401
+ case 'invalid-output': case 'timeout': case 'unavailable':
402
+ throw new OfficeKitError(code, cause instanceof Error ? cause.message : 'LibreOffice conversion failed.', { cause })
403
+ default: throw new OfficeKitError('failed', 'LibreOffice conversion failed.', { cause })
404
+ }
405
+ } finally {
406
+ try { if (directory !== undefined) await rm(directory, { recursive: true, force: true }) }
407
+ finally { slot.busy = false }
408
+ }
409
+ }
410
+
411
+ /** Run one engine operation in a private scratch directory and read its complete, bounded output. */
412
+ private async runEngine(
413
+ converter: Converter, inputPath: string, directory: string, operation: OfficeOperation, signal: AbortSignal,
414
+ ): Promise<OfficeOperationOutput> {
415
+ switch (operation.kind) {
416
+ case 'pdf': {
417
+ const outputPath = join(directory, 'converted.pdf')
418
+ const result = await converter.render({ inputPath, outputPath }, signal)
419
+ return { kind: 'pdf', pdf: await this.readFile(outputPath, 'pdf', signal), missingFonts: result.missingFonts }
420
+ }
421
+ case 'convert': case 'recalculate': {
422
+ const outputPath = join(directory, `output.${operation.format}`)
423
+ const result = operation.kind === 'convert'
424
+ ? await converter.convert({ inputPath, outputPath, ...(operation.sheet === undefined ? {} : { sheet: operation.sheet }) }, signal)
425
+ : await converter.recalculate({ inputPath, outputPath }, signal)
426
+ return { kind: 'file', data: await this.readFile(outputPath, operation.format, signal),
427
+ ...(result.pageCount === undefined ? {} : { pageCount: result.pageCount }), missingFonts: result.missingFonts }
428
+ }
429
+ case 'images': return this.renderPng(converter, inputPath, directory, operation, signal)
430
+ /* v8 ignore next -- OfficeOperation is a closed union */
431
+ default: throw new Error(`Unexpected Office operation: ${JSON.stringify(operation satisfies never)}`)
432
+ }
433
+ }
434
+
435
+ private async readFile(path: string, format: string, signal: AbortSignal): Promise<Uint8Array> {
436
+ try {
437
+ return format === 'pdf' ? await readPdf(path, this.config.maxOutputBytes, signal) : await readOutput(path, this.config.maxOutputBytes, signal)
438
+ } catch (cause) {
439
+ if (cause instanceof OfficeKitError) throw cause
440
+ throw new OfficeKitError('invalid-output', 'The converter output could not be read.', { cause })
441
+ }
442
+ }
443
+
444
+ private async renderPng(
445
+ converter: Converter, inputPath: string, directory: string, operation: Extract<OfficeOperation, { kind: 'images' }>,
446
+ signal: AbortSignal,
447
+ ): Promise<OfficeOperationOutput> {
448
+ const outputDir = join(directory, 'images')
449
+ const result = await converter.renderImages({
450
+ inputPath, outputDir,
451
+ ...(operation.pages === undefined ? {} : { pages: operation.pages }),
452
+ ...(operation.sheet === undefined ? {} : { sheet: operation.sheet }),
453
+ ...(operation.range === undefined ? {} : { range: operation.range }),
454
+ ...(operation.dpi === undefined ? {} : { dpi: operation.dpi }),
455
+ maxPages: operation.maxImages, maxPixels: operation.maxPixels, maxDimension: operation.maxDimension,
456
+ }, signal)
457
+ const declared = result.images.reduce((sum, image) => sum + image.byteLength, 0)
458
+ if (declared > operation.maxBytes) {
459
+ throw new OfficeKitError('output-too-large', `The rendered images total ${declared} bytes, above the ${operation.maxBytes}-byte limit.`)
460
+ }
461
+ const images = []
462
+ let remaining = operation.maxBytes
463
+ for (const image of [...result.images].sort((left, right) => left.index - right.index)) {
464
+ const within = relative(outputDir, image.path)
465
+ if (within === '' || within === '..' || within.startsWith(`..${sep}`) || isAbsolute(within)) {
466
+ throw new OfficeKitError('invalid-output', 'The converter reported an image outside its output directory.')
467
+ }
468
+ let png: Uint8Array
469
+ try { png = await readPng(image.path, remaining, signal) }
470
+ catch (cause) {
471
+ if (cause instanceof OfficeKitError) throw cause
472
+ throw new OfficeKitError('invalid-output', 'The rendered image could not be read.', { cause })
473
+ }
474
+ remaining -= png.byteLength
475
+ images.push({ png, width: image.width, height: image.height,
476
+ ...(image.page === undefined ? {} : { page: image.page }),
477
+ ...(image.sheet === undefined ? {} : { sheet: image.sheet }),
478
+ ...(image.range === undefined ? {} : { range: image.range }) })
479
+ }
480
+ return { kind: 'images', images, pageCount: result.pageCount, dpi: result.dpi, missingFonts: result.missingFonts }
481
+ }
482
+ }
483
+
484
+ export default OfficeKit