@deepseek-ai/libreoffice-kit 0.0.2-rc8 → 0.0.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 (86) hide show
  1. package/NOTICE +0 -240
  2. package/README.md +53 -43
  3. package/README.zh.md +58 -35
  4. package/lib/cli.js +725 -132
  5. package/lib/index.js +757 -133
  6. package/lib/types/engine.d.ts +5 -5
  7. package/lib/types/font-loader.d.ts +18 -16
  8. package/lib/types/fonts.d.ts +38 -21
  9. package/lib/types/image-operations.d.ts +1 -1
  10. package/lib/types/index.d.ts +13 -7
  11. package/lib/types/native-image-renderer.d.ts +19 -0
  12. package/lib/types/native.d.ts +1 -1
  13. package/lib/types/options.d.ts +3 -1
  14. package/lib/types/wasm.d.ts +4 -1
  15. package/lib/types/worker.d.ts +2 -0
  16. package/lib/worker.js +420 -942
  17. package/package.json +13 -55
  18. package/assets/font-subset.json +0 -70
  19. package/assets/font-subset.wasm +0 -0
  20. package/lib/browser/assets.json +0 -10
  21. package/lib/browser/index.js +0 -491
  22. package/lib/browser/types/connection.d.ts +0 -20
  23. package/lib/browser/types/engine-rendering.d.ts +0 -3
  24. package/lib/browser/types/engine-types.d.ts +0 -17
  25. package/lib/browser/types/font-channel.d.ts +0 -21
  26. package/lib/browser/types/index.d.ts +0 -14
  27. package/lib/browser/types/office-engine.d.ts +0 -48
  28. package/lib/browser/types/office-types.d.ts +0 -107
  29. package/lib/browser/types/office.d.ts +0 -4
  30. package/lib/browser/types/preparation.d.ts +0 -13
  31. package/lib/browser/types/protocol.d.ts +0 -110
  32. package/lib/browser/types/rendering.d.ts +0 -4
  33. package/lib/browser/types/types.d.ts +0 -113
  34. package/lib/browser/types/worker.d.ts +0 -2
  35. package/lib/browser/worker.js +0 -3615
  36. package/lib/browser-assets.js +0 -119
  37. package/lib/document.js +0 -178
  38. package/lib/engine-rendering.js +0 -120
  39. package/lib/font-config.js +0 -46
  40. package/lib/font-source.js +0 -395
  41. package/lib/font-worker.js +0 -1481
  42. package/lib/rendering.js +0 -99
  43. package/lib/sheet-geometry.js +0 -111
  44. package/lib/types/browser-assets.d.ts +0 -15
  45. package/lib/types/default-fonts.d.ts +0 -3
  46. package/lib/types/font-config.d.ts +0 -24
  47. package/lib/types/font-preferences-data.d.ts +0 -16
  48. package/lib/types/font-preferences.d.ts +0 -29
  49. package/lib/types/font-request.d.ts +0 -12
  50. package/lib/types/font-source-types.d.ts +0 -95
  51. package/lib/types/font-source.d.ts +0 -10
  52. package/lib/types/font-subsets.d.ts +0 -39
  53. package/lib/types/font-worker.d.ts +0 -2
  54. package/lib/types/harfbuzz-subset.d.ts +0 -11
  55. package/lib/types/unicode-scripts.d.ts +0 -18
  56. package/licenses/font-subset/harfbuzz-COPYING +0 -42
  57. package/licenses/font-subset/harfbuzzjs-LICENSE +0 -19
  58. package/licenses/javascript/fflate-LICENSE +0 -21
  59. package/licenses/javascript/saxes-LICENSE +0 -64
  60. package/licenses/javascript/xmlchars-LICENSE +0 -18
  61. package/sources/browser/packages/browser/package.json +0 -22
  62. package/sources/browser/packages/browser/src/connection.ts +0 -171
  63. package/sources/browser/packages/browser/src/engine-rendering.ts +0 -2
  64. package/sources/browser/packages/browser/src/engine-types.ts +0 -14
  65. package/sources/browser/packages/browser/src/font-channel.ts +0 -160
  66. package/sources/browser/packages/browser/src/index.ts +0 -40
  67. package/sources/browser/packages/browser/src/office-engine.ts +0 -323
  68. package/sources/browser/packages/browser/src/office-types.ts +0 -77
  69. package/sources/browser/packages/browser/src/office.ts +0 -62
  70. package/sources/browser/packages/browser/src/preparation.ts +0 -41
  71. package/sources/browser/packages/browser/src/protocol.ts +0 -41
  72. package/sources/browser/packages/browser/src/rendering.ts +0 -3
  73. package/sources/browser/packages/browser/src/types.ts +0 -115
  74. package/sources/browser/packages/browser/src/worker.ts +0 -181
  75. package/sources/browser/packages/browser/tsconfig.json +0 -5
  76. package/sources/browser/packages/browser/tsdown.config.ts +0 -7
  77. package/sources/browser/scripts/build-browser.mjs +0 -82
  78. package/sources/font-subset/engine/font-subset/README.md +0 -23
  79. package/sources/font-subset/engine/font-subset/README.zh.md +0 -23
  80. package/sources/font-subset/engine/font-subset/source.json +0 -16
  81. package/sources/font-subset/harfbuzzjs/config-override-subset.h +0 -7
  82. package/sources/font-subset/harfbuzzjs/harfbuzz-subset.symbols +0 -34
  83. package/sources/font-subset/scripts/build-font-subset.mjs +0 -64
  84. package/sources/font-subset/scripts/pack-utils.mjs +0 -69
  85. package/sources/font-subset/scripts/platform-matrix.mjs +0 -100
  86. package/sources/font-subset/scripts/verify-artifacts.mjs +0 -260
@@ -1,323 +0,0 @@
1
- /** Worker-owned reading, bounded VCL event slices and immutable notifications. */
2
- import { BrowserRenderError } from './types.ts'
3
- import type { BrowserTile } from './types.ts'
4
- import type { EmscriptenModule } from './engine-types.ts'
5
- import type { OfficeOperation } from './protocol.ts'
6
- import type { OfficeDocumentEvent, OfficeDocumentFormat, OfficeDocumentState, OfficeDocumentTileRequest, OfficeDocumentRectangle, OfficeDocumentLayoutRequest, OfficeDocumentLayoutResult } from './office-types.ts'
7
- import { parseCellRange } from '@deepseek-ai/libreoffice-kit/internal/sheet-geometry'
8
- import { renderRegion } from './engine-rendering.ts'
9
- import { TWIPS_PER_CSS_PIXEL, writerPages } from './rendering.ts'
10
-
11
- function rectangle(payload: string): OfficeDocumentRectangle | null {
12
- if (payload.startsWith('{')) {
13
- const value: unknown = JSON.parse(payload)
14
- if (typeof value !== 'object' || value === null || !('rectangle' in value) || typeof value.rectangle !== 'string') return null
15
- payload = value.rectangle
16
- }
17
- if (!payload || payload.startsWith('EMPTY') || payload === 'INPLACE') return null
18
- const values = payload.split(',').slice(0, 4).map(Number)
19
- if (values.length !== 4 || values.some(value => !Number.isFinite(value))) return null
20
- const [x, y, width, height] = values.map(value => value / TWIPS_PER_CSS_PIXEL) as [number, number, number, number]
21
- return width >= 0 && height >= 0 ? { x, y, width, height } : null
22
- }
23
-
24
- function integer(value: number, max = 0x7fffffff): number {
25
- if (!Number.isSafeInteger(value) || value < 0 || value > max) throw new BrowserRenderError('render-failed', 'Office input contains an invalid integer.')
26
- return value
27
- }
28
-
29
- function twips(value: number): number {
30
- if (!Number.isFinite(value) || Math.abs(value * TWIPS_PER_CSS_PIXEL) > 0x7fffffff) throw new BrowserRenderError('render-failed', 'Office input lies outside document coordinates.')
31
- return Math.round(value * TWIPS_PER_CSS_PIXEL)
32
- }
33
-
34
- const navigationKeys = { down: 0x400, up: 0x401, left: 0x402, right: 0x403, home: 0x404, end: 0x405, pageUp: 0x406, pageDown: 0x407 } as const
35
-
36
- /** One read-only document, driven exclusively by its Worker's messages and timer. */
37
- export class OfficeEngine {
38
- state: OfficeDocumentState
39
- private timer: ReturnType<typeof setTimeout> | undefined
40
- private readonly callbacks: { type: number; payload: string }[] = []
41
- private geometryDirty = false
42
- private stopped = false
43
- private layoutWidth = 0
44
- private viewport = ''
45
- private captureView: number | undefined
46
- private readingView: number | undefined
47
- private commandResult: { name: string; resolve: () => void; reject: (error: unknown) => void } | undefined
48
-
49
- constructor(private readonly module: EmscriptenModule, private readonly document: number,
50
- format: OfficeDocumentFormat, private readonly emit: (event: OfficeDocumentEvent) => void,
51
- private readonly failure: (error: unknown) => void) {
52
- this.state = { documentType: format === 'docx' || format === 'doc' ? 'text' : format === 'xlsx' || format === 'xls' ? 'spreadsheet' : 'presentation',
53
- renderGeneration: 0, layoutGeneration: 0, layout: 'paginated', part: 0, parts: [], pages: [], cursor: null,
54
- selection: [], graphicSelection: null, cellAddress: '', cellFormula: '' }
55
- }
56
-
57
- private call(name: string, args: (number | string)[] = []): number {
58
- return this.module.ccall(name, 'number', args.map(value => typeof value), args)
59
- }
60
- private text(name: string, args: (number | string)[]): string {
61
- const pointer = this.call(name, args)
62
- if (!pointer) return ''
63
- try { return this.module.UTF8ToString(pointer) } finally { this.call('free', [pointer]) }
64
- }
65
- private invoke(name: string, args: (number | string)[] = []): void {
66
- if (!this.call(`dsh_lok_document_${name}`, [this.document, ...args])) throw new BrowserRenderError('render-failed', `LibreOffice could not complete ${name}.`)
67
- }
68
- private requireOpen(): void {
69
- if (this.stopped) throw new BrowserRenderError('disposed', 'Office document is closed.')
70
- }
71
- /** Collect callbacks without reentering LibreOffice inside its callback. */
72
- callback(type: number, payload: string): void { if (!this.stopped) this.callbacks.push({ type, payload }) }
73
- /** Enforce the native read-only view before accepting any input. */
74
- async start(): Promise<void> {
75
- this.requireOpen()
76
- if (this.state.documentType === 'presentation') {
77
- const view = this.call('dsh_lok_document_get_view', [this.document])
78
- try {
79
- const created = this.call('dsh_lok_document_create_view', [this.document])
80
- if (created < 0) throw new BrowserRenderError('render-failed', 'LibreOffice could not create a slide capture view.')
81
- this.captureView = created
82
- this.invoke('initialize_rendering')
83
- this.configure({ mode: 'paginated' })
84
- this.pump()
85
- } finally { this.invoke('set_view', [view]) }
86
- this.readingView = view
87
- }
88
- this.configure({ mode: 'paginated' })
89
- this.invoke('listen')
90
- this.refreshGeometry()
91
- this.pump()
92
- this.schedule()
93
- await this.command('.uno:ReportWhenIdle', { idleID: { type: 'string', value: 'office-open' } })
94
- }
95
- private schedule(): void {
96
- this.timer = setTimeout(() => {
97
- if (this.stopped) return
98
- try { this.pump(); this.schedule() } catch (error) { this.stop(); this.failure(error) }
99
- }, 16)
100
- }
101
- /** Stop event processing before destroying the document. */
102
- stop(): void {
103
- this.stopped = true
104
- clearTimeout(this.timer)
105
- this.callbacks.length = 0
106
- this.commandResult?.reject(new BrowserRenderError('disposed', 'Office document is closed.'))
107
- this.commandResult = undefined
108
- }
109
- /** Return the part whose cached coordinates changed, or -1 when part identities changed. */
110
- private refreshGeometry(): number | undefined {
111
- const count = this.state.documentType === 'text' ? 1 : this.call('dsh_lok_document_parts', [this.document])
112
- if (!Number.isSafeInteger(count) || count <= 0) throw new BrowserRenderError('invalid-document', 'Office document has no parts.')
113
- const pointer = this.call('malloc', [8])
114
- if (!pointer) throw new BrowserRenderError('render-failed', 'Office geometry allocation failed.')
115
- try {
116
- const part = Math.min(this.state.part, count - 1)
117
- this.invoke('size', [part, pointer, pointer + 4])
118
- const width = this.module.HEAPU32[pointer / 4]! / TWIPS_PER_CSS_PIXEL
119
- const height = this.module.HEAPU32[pointer / 4 + 1]! / TWIPS_PER_CSS_PIXEL
120
- if (!(width > 0 && height > 0)) throw new BrowserRenderError('invalid-document', 'Office returned empty document dimensions.')
121
- // Measure the selected part only, preserving navigation and selection.
122
- const parts = Array.from({ length: count }, (_, index) => ({
123
- name: this.state.documentType === 'text' ? '' : this.text('dsh_lok_document_part_name', [this.document, index]),
124
- width: index === part ? width : this.state.parts[index]?.width ?? width,
125
- height: index === part ? height : this.state.parts[index]?.height ?? height,
126
- }))
127
- const pages = this.state.documentType !== 'text' ? [] : this.state.layout === 'continuous'
128
- ? [{ x: 0, y: 0, width, height }]
129
- : writerPages(this.text('dsh_lok_document_page_rectangles', [this.document])).map(page => ({ x: page.x / TWIPS_PER_CSS_PIXEL,
130
- y: page.y / TWIPS_PER_CSS_PIXEL, width: page.width, height: page.height }))
131
- const previous = this.state
132
- const identitiesChanged = previous.parts.length > 0 && (previous.parts.length !== parts.length
133
- || parts.some((value, index) => value.name !== previous.parts[index]!.name))
134
- const measured = previous.parts[part]
135
- const geometryChanged = measured !== undefined && (measured.width !== width || measured.height !== height
136
- || JSON.stringify(previous.pages) !== JSON.stringify(pages))
137
- this.state = { ...previous, part, parts, pages }
138
- this.geometryDirty = false
139
- return identitiesChanged ? -1 : geometryChanged ? part : undefined
140
- } finally { this.call('free', [pointer]) }
141
- }
142
- private pump(): void {
143
- if (this.readingView !== undefined) this.invoke('set_view', [this.readingView])
144
- const deadline = performance.now() + 8
145
- for (let pass = 0; pass < 8; pass++) {
146
- const result = this.call('dsh_lok_pump')
147
- if (result < 0) throw new BrowserRenderError('render-failed', 'LibreOffice event processing failed.')
148
- if (!result || performance.now() >= deadline) break
149
- }
150
- // Deferred native focus events can activate the capture view while pumping.
151
- if (this.readingView !== undefined) this.invoke('set_view', [this.readingView])
152
- this.flush()
153
- }
154
- private flush(): void {
155
- if (this.callbacks.length === 0) return
156
- let changed = false
157
- const invalidations: { part: number; rectangle: OfficeDocumentRectangle | null }[] = []
158
- for (const { type, payload } of this.callbacks.splice(0)) {
159
- switch (type) {
160
- case 0: {
161
- const fields = payload.split(',')
162
- const index = fields[0]?.trim() === 'EMPTY' ? fields[1] : fields[4]
163
- const part = index !== undefined && /^\s*-?\d+\s*$/.test(index) ? Number(index) : this.state.part
164
- invalidations.push({ part, rectangle: rectangle(payload) })
165
- break
166
- }
167
- case 1: case 17: this.state = { ...this.state, cursor: rectangle(payload) }; changed = true; break
168
- case 2: this.state = { ...this.state, selection: payload.split(';').map(rectangle).filter((value): value is OfficeDocumentRectangle => value !== null) }; changed = true; break
169
- case 6: this.state = { ...this.state, graphicSelection: rectangle(payload) }; changed = true; break
170
- case 13: this.geometryDirty = true; break
171
- case 14: {
172
- const part = Number(payload)
173
- if (Number.isSafeInteger(part) && part >= 0 && part < this.state.parts.length) {
174
- this.state = { ...this.state, part }; this.viewport = ''; this.geometryDirty = true; changed = true
175
- }
176
- break
177
- }
178
- case 16: {
179
- const result: unknown = JSON.parse(payload)
180
- if (typeof result === 'object' && result !== null && 'commandName' in result && result.commandName === this.commandResult?.name) this.commandResult?.resolve()
181
- break
182
- }
183
- case 19: this.state = { ...this.state, cellFormula: payload }; changed = true; break
184
- case 34: this.state = { ...this.state, cellAddress: payload }; changed = true; break
185
- }
186
- }
187
- const geometry = this.geometryDirty ? this.refreshGeometry() : undefined
188
- if (geometry !== undefined) {
189
- this.state = { ...this.state, layoutGeneration: this.state.layoutGeneration + 1 }
190
- // A size notification need not be accompanied by LOK tile invalidation.
191
- // Keep other sheets' pixels, but never reuse coordinates from an old layout.
192
- if (!invalidations.some(value => value.rectangle === null && (value.part === -1 || value.part === geometry))) {
193
- for (let index = invalidations.length - 1; index >= 0; index--) {
194
- if (geometry === -1 || invalidations[index]!.part === geometry) invalidations.splice(index, 1)
195
- }
196
- invalidations.push({ part: geometry, rectangle: null })
197
- }
198
- }
199
- if (invalidations.length > 0) {
200
- this.state = { ...this.state, renderGeneration: this.state.renderGeneration + 1 }
201
- changed = true
202
- }
203
- if (changed) this.emit({ type: 'state', state: this.state })
204
- for (const invalidation of invalidations) this.emit({ type: 'invalidate', ...invalidation, generation: this.state.renderGeneration })
205
- }
206
- /** The Worker permits only these typed reading operations, including at runtime. */
207
- async operation(operation: OfficeOperation): Promise<{ text?: string; layout?: OfficeDocumentLayoutResult }> {
208
- this.requireOpen()
209
- if (this.readingView !== undefined) this.invoke('set_view', [this.readingView])
210
- if (!operation || typeof operation !== 'object') throw new BrowserRenderError('render-failed', 'Invalid Office reading operation.')
211
- switch (operation.type) {
212
- case 'pointer': {
213
- const event = operation.event
214
- if (!event || !['down', 'up', 'move'].includes(event.action) || ![0, 1].includes(event.buttons)
215
- || ![0, 0x1000, 0x2000, 0x3000].includes(event.modifiers)) throw new BrowserRenderError('render-failed', 'Invalid Office selection pointer.')
216
- this.invoke('mouse', [event.action === 'down' ? 0 : event.action === 'up' ? 1 : 2,
217
- twips(event.x), twips(event.y), integer(event.clicks, 3), event.buttons, event.modifiers])
218
- break
219
- }
220
- case 'navigate': {
221
- const event = operation.event
222
- if (!event || !Object.hasOwn(navigationKeys, event.key)
223
- || (event.extend !== undefined && typeof event.extend !== 'boolean') || (event.word !== undefined && typeof event.word !== 'boolean')) {
224
- throw new BrowserRenderError('render-failed', 'Invalid Office navigation key.')
225
- }
226
- const key = navigationKeys[event.key] | (event.extend ? 0x1000 : 0) | (event.word ? 0x2000 : 0)
227
- this.invoke('key', [0, 0, key]); this.invoke('key', [1, 0, key])
228
- break
229
- }
230
- case 'select-all': await this.command('.uno:SelectAll', {}); break
231
- case 'cell': {
232
- if (this.state.documentType !== 'spreadsheet' || typeof operation.address !== 'string') throw new BrowserRenderError('render-failed', 'Cell navigation requires a spreadsheet address.')
233
- try { parseCellRange(operation.address) } catch { throw new BrowserRenderError('render-failed', 'Cell navigation requires a bounded A1 cell or range.') }
234
- await this.command('.uno:GoToCell', { ToPoint: { type: 'string', value: operation.address } })
235
- break
236
- }
237
- case 'copy': this.pump(); return { text: this.text('dsh_lok_document_selection', [this.document]) }
238
- case 'part': {
239
- const part = integer(operation.part, this.state.parts.length - 1)
240
- if (part === this.state.part) break
241
- this.invoke('part', [part])
242
- this.viewport = ''
243
- this.state = { ...this.state, part, cursor: null, selection: [], graphicSelection: null, cellAddress: '', cellFormula: '' }
244
- const geometry = this.refreshGeometry()
245
- if (geometry !== undefined) this.state = { ...this.state, layoutGeneration: this.state.layoutGeneration + 1,
246
- renderGeneration: this.state.renderGeneration + 1 }
247
- this.emit({ type: 'state', state: this.state })
248
- if (geometry !== undefined) this.emit({ type: 'invalidate', part: geometry, rectangle: null, generation: this.state.renderGeneration })
249
- break
250
- }
251
- case 'viewport': {
252
- const { x, y, width, height } = operation.rectangle
253
- if (!(operation.scale > 0 && operation.scale <= 16 && width > 0 && height > 0)) throw new BrowserRenderError('render-failed', 'Office viewport is invalid.')
254
- const args = [Math.max(1, Math.round(256 * operation.scale)), 256 * TWIPS_PER_CSS_PIXEL, twips(x), twips(y), twips(width), twips(height)]
255
- const key = args.join(',')
256
- if (key !== this.viewport) { this.invoke('viewport', args); this.viewport = key }
257
- break
258
- }
259
- case 'layout': {
260
- const request = operation.request
261
- if (!request || !['paginated', 'continuous'].includes(request.mode) || (request.mode === 'continuous' && this.state.documentType !== 'text')) {
262
- throw new BrowserRenderError('render-failed', 'Continuous layout is only available for Writer documents.')
263
- }
264
- const width = request.mode === 'continuous' ? twips(request.width) : 0
265
- if (request.mode === 'continuous' && width <= 0) throw new BrowserRenderError('render-failed', 'Continuous layout requires a positive width.')
266
- if (request.anchor && (twips(request.anchor.x) < 0 || twips(request.anchor.y) < 0)) throw new BrowserRenderError('render-failed', 'Reading anchors must lie within positive document coordinates.')
267
- if (request.mode === this.state.layout && width === this.layoutWidth) return { layout: { changed: false } }
268
- const result = this.configure(request)
269
- this.layoutWidth = width
270
- this.viewport = ''
271
- this.state = { ...this.state, layout: request.mode, layoutGeneration: this.state.layoutGeneration + 1,
272
- renderGeneration: this.state.renderGeneration + 1 }
273
- // Establish the requested layout before its acknowledgement pumps any
274
- // matching size callback; that callback must not invalidate it twice.
275
- this.refreshGeometry()
276
- await this.command('.uno:ReportWhenIdle', { idleID: { type: 'string', value: 'office-layout' } })
277
- this.refreshGeometry()
278
- this.emit({ type: 'state', state: this.state })
279
- this.emit({ type: 'invalidate', part: -1, rectangle: null, generation: this.state.renderGeneration })
280
- return { layout: result }
281
- }
282
- default: throw new BrowserRenderError('render-failed', 'Unsupported Office reading operation.')
283
- }
284
- this.pump()
285
- return {}
286
- }
287
- private configure(request: OfficeDocumentLayoutRequest): OfficeDocumentLayoutResult {
288
- const raw = this.text('dsh_lok_document_configure_view', [this.document, 1, request.mode === 'continuous' ? 1 : 0,
289
- request.mode === 'continuous' ? twips(request.width) : 0, request.anchor ? twips(request.anchor.x) : -1, request.anchor ? twips(request.anchor.y) : -1])
290
- if (!raw) throw new BrowserRenderError('render-failed', 'LibreOffice could not configure its read-only view.')
291
- const result = JSON.parse(raw) as { changed: boolean; width: number; height: number; anchor?: OfficeDocumentRectangle }
292
- if (typeof result.changed !== 'boolean' || !(result.width > 0 && result.height > 0)) throw new BrowserRenderError('render-failed', 'LibreOffice returned an invalid reading layout.')
293
- if (result.anchor === undefined) return { changed: result.changed }
294
- const { x, y, width, height } = result.anchor
295
- if (![x, y, width, height].every(value => Number.isFinite(value) && value >= 0)) throw new BrowserRenderError('render-failed', 'LibreOffice returned an invalid reading anchor.')
296
- return { changed: result.changed, anchor: { x: x / TWIPS_PER_CSS_PIXEL, y: y / TWIPS_PER_CSS_PIXEL,
297
- width: width / TWIPS_PER_CSS_PIXEL, height: height / TWIPS_PER_CSS_PIXEL } }
298
- }
299
- /** Internal whitelist commands only; no arbitrary command crosses the public API. */
300
- private async command(name: '.uno:ReportWhenIdle' | '.uno:SelectAll' | '.uno:GoToCell', args: unknown): Promise<void> {
301
- const result = Promise.withResolvers<void>()
302
- this.commandResult = { name, resolve: () => result.resolve(), reject: result.reject }
303
- try { this.invoke('command', [name, JSON.stringify(args)]); this.pump(); await result.promise }
304
- finally { this.commandResult = undefined }
305
- }
306
- /** Direct tiles preserve the active view, navigation state and selection. */
307
- render(request: OfficeDocumentTileRequest): BrowserTile {
308
- this.requireOpen()
309
- if (this.readingView !== undefined) this.invoke('set_view', [this.readingView])
310
- this.flush()
311
- const part = this.state.parts[integer(request.part, this.state.parts.length - 1)]!
312
- const capture = request.part !== this.state.part
313
- if (capture && this.state.documentType !== 'presentation') throw new BrowserRenderError('stale-part', 'The Office tile belongs to an inactive worksheet.')
314
- try {
315
- if (capture) this.invoke('set_view', [this.captureView!])
316
- return renderRegion(this.module, this.document, { ...request, pageIndex: 0 }, [{ ...part, x: 0, y: 0,
317
- part: this.state.documentType === 'text' ? -1 : request.part }], () => new BrowserRenderError('render-failed', 'Office tile rendering failed.'))
318
- } finally {
319
- if (this.readingView !== undefined) this.invoke('set_view', [this.readingView])
320
- this.flush()
321
- }
322
- }
323
- }
@@ -1,77 +0,0 @@
1
- /** Retained Office reading sessions; this API never exposes document mutation. */
2
- import type { BrowserDocumentOptions, BrowserPage, BrowserRenderErrorCode, BrowserTile } from './types.ts'
3
-
4
- /** Office containers supported by the reading engine. */
5
- export type OfficeDocumentFormat = 'doc' | 'docx' | 'xls' | 'xlsx' | 'ppt' | 'pptx'
6
- /** Source bytes, engine resources and Host fonts; all sessions are read-only. */
7
- export type OfficeDocumentOptions = Omit<BrowserDocumentOptions, 'extension'> & { readonly extension: OfficeDocumentFormat }
8
- /** Document coordinates in CSS pixels at 96 DPI, independent of zoom. */
9
- export interface OfficeDocumentRectangle extends BrowserPage { readonly x: number; readonly y: number }
10
- /** One Writer document, Calc worksheet or Impress slide. */
11
- export interface OfficeDocumentPart extends BrowserPage { readonly name: string }
12
- /** Writer layout; other document types always remain paginated. */
13
- export type OfficeDocumentLayout = 'paginated' | 'continuous'
14
- /** A point in the previous layout, normally the upper visible line of body text. */
15
- export interface OfficeDocumentAnchor { readonly x: number; readonly y: number }
16
- /** Continuous width is the available content width in document CSS pixels. */
17
- export type OfficeDocumentLayoutRequest =
18
- | { readonly mode: 'paginated'; readonly anchor?: OfficeDocumentAnchor }
19
- | { readonly mode: 'continuous'; readonly width: number; readonly anchor?: OfficeDocumentAnchor }
20
- /** An optional body-text rectangle in the new layout for restoring reading position. */
21
- export interface OfficeDocumentLayoutResult { readonly changed: boolean; readonly anchor?: OfficeDocumentRectangle }
22
- /** Geometry and selection; cursor is a navigation/cell rectangle, never an editing caret. */
23
- export interface OfficeDocumentState {
24
- readonly documentType: 'text' | 'spreadsheet' | 'presentation'
25
- readonly renderGeneration: number
26
- readonly layoutGeneration: number
27
- readonly layout: OfficeDocumentLayout
28
- readonly part: number
29
- readonly parts: readonly OfficeDocumentPart[]
30
- /** Writer page rectangles in paginated mode; one continuous rectangle otherwise. */
31
- readonly pages: readonly OfficeDocumentRectangle[]
32
- readonly cursor: OfficeDocumentRectangle | null
33
- readonly selection: readonly OfficeDocumentRectangle[]
34
- readonly graphicSelection: OfficeDocumentRectangle | null
35
- readonly cellAddress: string
36
- readonly cellFormula: string
37
- }
38
- /** Primary-button selection; modifiers use LOK Shift (0x1000) / Control (0x2000). */
39
- export interface OfficeDocumentPointer {
40
- readonly action: 'down' | 'up' | 'move'
41
- readonly x: number
42
- readonly y: number
43
- readonly buttons: number
44
- readonly modifiers: number
45
- readonly clicks: number
46
- }
47
- /** Only navigation keys are accepted; no arbitrary character or key injection. */
48
- export interface OfficeDocumentNavigation {
49
- readonly key: 'left' | 'right' | 'up' | 'down' | 'home' | 'end' | 'pageUp' | 'pageDown'
50
- readonly extend?: boolean
51
- readonly word?: boolean
52
- }
53
- /** One region of the current part. Pixel density does not change document layout. */
54
- export interface OfficeDocumentTileRequest extends OfficeDocumentRectangle { readonly part: number; readonly scale: number }
55
- /** A null rectangle invalidates an entire part; negative part means every part. */
56
- export type OfficeDocumentEvent =
57
- | { readonly type: 'state'; readonly state: OfficeDocumentState }
58
- | { readonly type: 'invalidate'; readonly part: number; readonly rectangle: OfficeDocumentRectangle | null; readonly generation: number }
59
- | { readonly type: 'error'; readonly code: BrowserRenderErrorCode; readonly message: string }
60
- /** Retain this session while hidden; dispose only when the document is closed. */
61
- export interface OfficeDocument {
62
- readonly state: OfficeDocumentState
63
- subscribe(listener: (event: OfficeDocumentEvent) => void): () => void
64
- pointer(event: OfficeDocumentPointer): Promise<void>
65
- navigate(event: OfficeDocumentNavigation): Promise<void>
66
- selectAll(): Promise<void>
67
- copy(): Promise<string>
68
- /** Select a bounded A1 cell or range on the current worksheet. */
69
- goToCell(address: string): Promise<void>
70
- setPart(part: number): Promise<void>
71
- setViewport(rectangle: OfficeDocumentRectangle, scale: number): Promise<void>
72
- /** Coalesces pending widths; superseded callers observe the newest applied layout. */
73
- setLayout(request: OfficeDocumentLayoutRequest): Promise<OfficeDocumentLayoutResult>
74
- /** Only the current part can be painted; queued requests for a former part reject with stale-part without changing selection. */
75
- renderTile(request: OfficeDocumentTileRequest, signal?: AbortSignal): Promise<BrowserTile>
76
- dispose(): Promise<void>
77
- }
@@ -1,62 +0,0 @@
1
- /** Browser owner for a retained read-only Office model. */
2
- import { openBrowserConnection } from './connection.ts'
3
- import { BrowserRenderError } from './types.ts'
4
- import type { OfficeDocument, OfficeDocumentEvent, OfficeDocumentOptions, OfficeDocumentState, OfficeDocumentLayoutRequest, OfficeDocumentLayoutResult } from './office-types.ts'
5
- import type { OfficeOperation } from './protocol.ts'
6
-
7
- /** Open one read-only Office model; source bytes remain owned by the caller. */
8
- export async function openOfficeDocument(options: OfficeDocumentOptions, signal?: AbortSignal): Promise<OfficeDocument> {
9
- const listeners = new Set<(event: OfficeDocumentEvent) => void>()
10
- let state: OfficeDocumentState | undefined
11
- const connection = await openBrowserConnection(options, signal, true, (event) => {
12
- if (event.type === 'state') state = event.state
13
- for (const listener of listeners) {
14
- try { listener(event) } catch (error) { console.error('Office document observer failed', error) }
15
- }
16
- })
17
- state = connection.opened.office
18
- if (!state) { await connection.dispose(); throw new BrowserRenderError('invalid-document', 'LibreOffice returned no reading state.') }
19
- async function operate(operation: OfficeOperation) {
20
- const response = await connection.request({ type: 'office-operation', operation })
21
- if (response.type !== 'office-result') throw new BrowserRenderError('render-failed', 'LibreOffice returned an unexpected reading response.')
22
- return response
23
- }
24
- let layoutRunning = false
25
- let pendingLayout: { request: OfficeDocumentLayoutRequest; waiters: ReturnType<typeof Promise.withResolvers<OfficeDocumentLayoutResult>>[] } | undefined
26
- async function applyLayouts(): Promise<void> {
27
- layoutRunning = true
28
- while (pendingLayout) {
29
- const next = pendingLayout
30
- pendingLayout = undefined
31
- try {
32
- const response = await operate({ type: 'layout', request: next.request })
33
- if (!response.layout) throw new BrowserRenderError('render-failed', 'LibreOffice returned no layout result.')
34
- for (const waiter of next.waiters) waiter.resolve(response.layout)
35
- } catch (error) { for (const waiter of next.waiters) waiter.reject(error) }
36
- }
37
- layoutRunning = false
38
- }
39
- return {
40
- get state() { return state! },
41
- subscribe(listener) { listeners.add(listener); return () => { listeners.delete(listener) } },
42
- async pointer(event) { await operate({ type: 'pointer', event }) },
43
- async navigate(event) { await operate({ type: 'navigate', event }) },
44
- async selectAll() { await operate({ type: 'select-all' }) },
45
- async copy() { return (await operate({ type: 'copy' })).text ?? '' },
46
- async goToCell(address) { await operate({ type: 'cell', address }) },
47
- async setPart(part) { await operate({ type: 'part', part }) },
48
- async setViewport(rectangle, scale) { await operate({ type: 'viewport', rectangle, scale }) },
49
- setLayout(request) {
50
- const waiter = Promise.withResolvers<OfficeDocumentLayoutResult>()
51
- pendingLayout = { request, waiters: [...(pendingLayout?.waiters ?? []), waiter] }
52
- if (!layoutRunning) void applyLayouts()
53
- return waiter.promise
54
- },
55
- async renderTile(request, tileSignal) {
56
- const response = await connection.request({ type: 'office-tile', request }, tileSignal)
57
- if (response.type !== 'tile') throw new BrowserRenderError('render-failed', 'LibreOffice returned an unexpected tile response.')
58
- return response.tile
59
- },
60
- dispose() { listeners.clear(); return connection.dispose() },
61
- }
62
- }
@@ -1,41 +0,0 @@
1
- /** Browser-side WASM compilation without creating an Office Worker or memory. */
2
- import { BrowserRenderError } from './types.ts'
3
- import type { BrowserEngineAssets, PreparedBrowserEngine } from './types.ts'
4
-
5
- interface PreparedBrowserEngineRecord {
6
- readonly wasmUrl: string
7
- readonly module: WebAssembly.Module
8
- }
9
-
10
- /**
11
- * Compile the version-matched LibreOffice WASM module for later document Workers.
12
- * @param assets - Browser resources whose WASM URL identifies the compiled module.
13
- * @param signal - Cancels the resource request; compilation may finish before cancellation is observed.
14
- * @returns an opaque, structured-cloneable engine handle that allocates no WASM memory.
15
- */
16
- export async function prepareOfficeBrowser(assets: BrowserEngineAssets, signal?: AbortSignal): Promise<PreparedBrowserEngine> {
17
- signal?.throwIfAborted()
18
- if (typeof WebAssembly.compileStreaming !== 'function') throw new BrowserRenderError('unavailable', 'Streaming WebAssembly compilation is unavailable.')
19
- const response = await fetch(assets.wasmUrl, { credentials: 'same-origin', ...(signal === undefined ? {} : { signal }) })
20
- if (!response.ok) throw new BrowserRenderError('unavailable', `LibreOffice WASM request failed: ${response.status}`)
21
- const module = await WebAssembly.compileStreaming(Promise.resolve(response))
22
- signal?.throwIfAborted()
23
- return Object.freeze({ wasmUrl: assets.wasmUrl, module }) as unknown as PreparedBrowserEngine
24
- }
25
-
26
- /** Return the compiled module after validating the Worker-bound asset identity. */
27
- export function preparedBrowserModule(prepared: PreparedBrowserEngine, assets: BrowserEngineAssets): WebAssembly.Module {
28
- const record = prepared as unknown as PreparedBrowserEngineRecord
29
- if (record.wasmUrl !== assets.wasmUrl || !(record.module instanceof WebAssembly.Module)) {
30
- throw new TypeError('The prepared browser engine does not match the requested WASM asset.')
31
- }
32
- return record.module
33
- }
34
-
35
- /** Instantiate precompiled code through Emscripten's synchronous override. */
36
- export function instantiatePreparedModule(module: WebAssembly.Module, imports: WebAssembly.Imports,
37
- receive: (instance: WebAssembly.Instance, module: WebAssembly.Module) => void): WebAssembly.Exports {
38
- const instance = new WebAssembly.Instance(module, imports)
39
- receive(instance, module)
40
- return instance.exports
41
- }
@@ -1,41 +0,0 @@
1
- /** Private messages exchanged by the document owner and its single engine Worker. */
2
- import type { BrowserDocumentOptions, BrowserFontIdentity, BrowserFontRequest, BrowserPage, BrowserRenderErrorCode, BrowserTile, BrowserTileRequest } from './types.ts'
3
- import type { OfficeDocumentEvent, OfficeDocumentNavigation, OfficeDocumentOptions, OfficeDocumentState, OfficeDocumentPointer, OfficeDocumentLayoutRequest, OfficeDocumentLayoutResult, OfficeDocumentTileRequest, OfficeDocumentRectangle } from './office-types.ts'
4
-
5
- export const FONT_CHUNK_BYTES = 1024 * 1024
6
- export const FONT_HEADER_BYTES = 8
7
- export const enum FontState { Waiting, Header, Bytes, Done, Error, Cancelled }
8
- export type WorkerOptions = Omit<BrowserDocumentOptions | OfficeDocumentOptions, 'resolveFonts' | 'onMissingFonts'>
9
- export type OfficeOperation =
10
- | { readonly type: 'pointer'; readonly event: OfficeDocumentPointer }
11
- | { readonly type: 'navigate'; readonly event: OfficeDocumentNavigation }
12
- | { readonly type: 'select-all' }
13
- | { readonly type: 'cell'; readonly address: string }
14
- | { readonly type: 'copy' }
15
- | { readonly type: 'part'; readonly part: number }
16
- | { readonly type: 'viewport'; readonly rectangle: OfficeDocumentRectangle; readonly scale: number }
17
- | { readonly type: 'layout'; readonly request: OfficeDocumentLayoutRequest }
18
- export type OwnerMessage =
19
- | { readonly type: 'open'; readonly id: number; readonly options: WorkerOptions; readonly channel: SharedArrayBuffer; readonly office?: boolean }
20
- | { readonly type: 'tile'; readonly id: number; readonly request: BrowserTileRequest }
21
- | { readonly type: 'office-tile'; readonly id: number; readonly request: OfficeDocumentTileRequest }
22
- | { readonly type: 'office-operation'; readonly id: number; readonly operation: OfficeOperation }
23
- | { readonly type: 'dispose'; readonly id: number }
24
- type WithoutId<T> = T extends unknown ? Omit<T, 'id'> : never
25
- export type OwnerRequest = WithoutId<OwnerMessage>
26
- export type WorkerMessage =
27
- | { readonly type: 'opened'; readonly id: number; readonly pages: readonly BrowserPage[]; readonly office?: OfficeDocumentState }
28
- | { readonly type: 'tile'; readonly id: number; readonly tile: BrowserTile }
29
- | { readonly type: 'office-result'; readonly id: number; readonly text?: string; readonly layout?: OfficeDocumentLayoutResult }
30
- | { readonly type: 'office-event'; readonly event: OfficeDocumentEvent }
31
- | { readonly type: 'disposed'; readonly id: number }
32
- | { readonly type: 'error'; readonly id: number; readonly code: BrowserRenderErrorCode; readonly message: string; readonly fatal: boolean }
33
- | { readonly type: 'font'; readonly request: BrowserFontRequest; readonly known: readonly FontIdentity[] }
34
- | { readonly type: 'font-next' }
35
- | { readonly type: 'missing-fonts'; readonly families: readonly string[] }
36
- /** Immutable bytes already installed in this document's MEMFS. */
37
- export type FontIdentity = BrowserFontIdentity
38
- export interface FontHeader {
39
- readonly fonts: readonly (FontIdentity & { readonly family: string; readonly alias: string; readonly reference?: true })[]
40
- readonly missingFamily?: string
41
- }
@@ -1,3 +0,0 @@
1
- /** Geometry and RGBA conversion shared by every WASM consumer. */
2
- export { writerPages, tileDimensions, rgbaPixels, TWIPS_PER_CSS_PIXEL } from '@deepseek-ai/libreoffice-kit/internal/rendering'
3
- export type { EnginePage } from '@deepseek-ai/libreoffice-kit/internal/rendering'