@deepseek-ai/libreoffice-kit 0.0.2-rc5 → 0.0.2-rc7
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +3 -1
- package/assets/font-subset.json +4 -4
- package/lib/browser/assets.json +2 -2
- package/lib/browser/index.js +65 -16
- package/lib/browser/types/font-channel.d.ts +5 -4
- package/lib/browser/types/index.d.ts +2 -1
- package/lib/browser/types/office-engine.d.ts +2 -0
- package/lib/browser/types/preparation.d.ts +13 -0
- package/lib/browser/types/protocol.d.ts +7 -6
- package/lib/browser/types/types.d.ts +29 -8
- package/lib/browser/worker.js +138 -21
- package/lib/browser-assets.js +1 -1
- package/lib/cli.js +2 -2
- package/lib/font-source.js +19 -1
- package/lib/font-worker.js +133 -35
- package/lib/index.js +2 -2
- package/lib/types/engine.d.ts +1 -1
- package/lib/types/font-source-types.d.ts +11 -0
- package/lib/types/font-subsets.d.ts +5 -1
- package/lib/types/fonts.d.ts +1 -0
- package/lib/types/office-fonts.d.ts +6 -0
- package/lib/worker.js +7 -6
- package/package.json +2 -2
- package/sources/browser/packages/browser/package.json +1 -1
- package/sources/browser/packages/browser/src/connection.ts +8 -3
- package/sources/browser/packages/browser/src/font-channel.ts +75 -14
- package/sources/browser/packages/browser/src/index.ts +2 -1
- package/sources/browser/packages/browser/src/office-engine.ts +26 -2
- package/sources/browser/packages/browser/src/preparation.ts +41 -0
- package/sources/browser/packages/browser/src/protocol.ts +5 -3
- package/sources/browser/packages/browser/src/types.ts +23 -2
- package/sources/browser/packages/browser/src/worker.ts +19 -4
- package/sources/browser/scripts/build-browser.mjs +1 -1
- package/sources/font-subset/scripts/platform-matrix.mjs +1 -1
- package/sources/font-subset/scripts/verify-artifacts.mjs +3 -3
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
/** Bounded frames bridge asynchronous Host font reads and synchronous VCL callbacks. */
|
|
2
2
|
import { normalize } from '@deepseek-ai/libreoffice-kit/font-config'
|
|
3
3
|
import { FONT_CHUNK_BYTES, FONT_HEADER_BYTES, FontState } from './protocol.ts'
|
|
4
|
-
import type { FontHeader } from './protocol.ts'
|
|
4
|
+
import type { FontHeader, FontIdentity } from './protocol.ts'
|
|
5
5
|
import { BrowserRenderError } from './types.ts'
|
|
6
6
|
import type { BrowserFontRequest, BrowserFontResult } from './types.ts'
|
|
7
7
|
|
|
@@ -10,13 +10,25 @@ export function fontViews(channel: SharedArrayBuffer): { control: Int32Array; by
|
|
|
10
10
|
return { control: new Int32Array(channel, 0, 2), bytes: new Uint8Array(channel, FONT_HEADER_BYTES) }
|
|
11
11
|
}
|
|
12
12
|
|
|
13
|
-
/**
|
|
14
|
-
export function* fontFrames(result: BrowserFontResult): Generator<{ state: FontState; bytes: Uint8Array }> {
|
|
15
|
-
const
|
|
13
|
+
/** Only uninstalled content crosses the channel; each family retains its own alias. */
|
|
14
|
+
export function* fontFrames(result: BrowserFontResult, known: readonly FontIdentity[] = []): Generator<{ state: FontState; bytes: Uint8Array }> {
|
|
15
|
+
const identities = new Map(known.map(font => [font.id, font]))
|
|
16
|
+
const header: FontHeader = { fonts: result.fonts.map(font => {
|
|
17
|
+
const size = font.data === undefined ? font.bytes : font.data.byteLength
|
|
18
|
+
const identity: FontIdentity = { id: font.id, bytes: size, ...(font.format ? { format: font.format } : {}) }
|
|
19
|
+
const prior = identities.get(font.id)
|
|
20
|
+
if (prior && (prior.bytes !== identity.bytes || prior.format !== identity.format)) throw new BrowserRenderError('font-unavailable', 'Font identity has conflicting bytes or formats.')
|
|
21
|
+
if (!prior && font.data === undefined) throw new BrowserRenderError('font-unavailable', 'Font reference has not been installed.')
|
|
22
|
+
identities.set(font.id, identity)
|
|
23
|
+
return { ...identity, family: font.family, alias: font.alias, ...(prior ? { reference: true as const } : {}) }
|
|
24
|
+
}), ...(result.missingFamily === undefined ? {} : { missingFamily: result.missingFamily }) }
|
|
16
25
|
const encoded = new TextEncoder().encode(JSON.stringify(header))
|
|
17
26
|
if (encoded.length > FONT_CHUNK_BYTES) throw new BrowserRenderError('font-limit', 'Font response metadata exceeds the transfer limit.')
|
|
18
27
|
yield { state: FontState.Header, bytes: encoded }
|
|
19
|
-
for (const font of result.fonts) {
|
|
28
|
+
for (const [index, font] of result.fonts.entries()) {
|
|
29
|
+
if (header.fonts[index]!.reference) continue
|
|
30
|
+
/* v8 ignore next -- header validation rejects an unknown data-less font before iteration. */
|
|
31
|
+
if (font.data === undefined) throw new BrowserRenderError('font-unavailable', 'Font reference has not been installed.')
|
|
20
32
|
for (let offset = 0; offset < font.data.byteLength; offset += FONT_CHUNK_BYTES) {
|
|
21
33
|
yield { state: FontState.Bytes, bytes: font.data.subarray(offset, offset + FONT_CHUNK_BYTES) }
|
|
22
34
|
}
|
|
@@ -27,14 +39,38 @@ export function* fontFrames(result: BrowserFontResult): Generator<{ state: FontS
|
|
|
27
39
|
/** One MEMFS font face registered under a document-local family alias. */
|
|
28
40
|
export interface EngineFontFace { readonly path: string; readonly family: string }
|
|
29
41
|
|
|
30
|
-
|
|
42
|
+
const SCRIPT_GROUPS = [
|
|
43
|
+
['arabic', /\p{Script_Extensions=Arabic}/u], ['cyrillic', /\p{Script_Extensions=Cyrillic}/u],
|
|
44
|
+
['devanagari', /\p{Script_Extensions=Devanagari}/u], ['greek', /\p{Script_Extensions=Greek}/u],
|
|
45
|
+
['han', /\p{Script_Extensions=Han}/u], ['hangul', /\p{Script_Extensions=Hangul}/u],
|
|
46
|
+
['hebrew', /\p{Script_Extensions=Hebrew}/u], ['hiragana', /\p{Script_Extensions=Hiragana}/u],
|
|
47
|
+
['katakana', /\p{Script_Extensions=Katakana}/u], ['latin', /\p{Script_Extensions=Latin}/u],
|
|
48
|
+
['thai', /\p{Script_Extensions=Thai}/u], ['common', /[\p{Script=Common}\p{Script=Inherited}]/u],
|
|
49
|
+
] as const
|
|
50
|
+
|
|
51
|
+
function scriptGroup(point: number): string {
|
|
52
|
+
const character = String.fromCodePoint(point)
|
|
53
|
+
return SCRIPT_GROUPS.find(([, pattern]) => pattern.test(character))?.[0] ?? `other-${point >>> 8}`
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/** The synchronous reader installs immutable font assets before returning their MEMFS paths and aliases. */
|
|
31
57
|
export function createFontReader(channel: SharedArrayBuffer, timeoutMs: number, maxLoadedFontBytes: number,
|
|
32
|
-
declaredFamilies: ReadonlyMap<string, string>, request: (request: BrowserFontRequest) => void, next: () => void,
|
|
33
|
-
install: (path: string, bytes: Uint8Array) => void, missing: (families: readonly string[]) => void
|
|
58
|
+
declaredFamilies: ReadonlyMap<string, string>, request: (request: BrowserFontRequest, known: readonly FontIdentity[]) => void, next: () => void,
|
|
59
|
+
install: (path: string, bytes: Uint8Array) => void, missing: (families: readonly string[]) => void,
|
|
60
|
+
documentCodePoints: readonly number[] = []): (request: BrowserFontRequest) => EngineFontFace[] {
|
|
34
61
|
const { control, bytes } = fontViews(channel)
|
|
35
|
-
const installed = new Map<string, { face: EngineFontFace; format:
|
|
62
|
+
const installed = new Map<string, { face: EngineFontFace; bytes: number; format: FontIdentity['format'] }>()
|
|
36
63
|
const aliases = new Map<string, { id: string; family: string }>()
|
|
37
64
|
const requests = new Map<string, EngineFontFace[]>()
|
|
65
|
+
const coverage = new Map<string, { readonly points: Set<number>; readonly faces: EngineFontFace[]; complete: boolean }>()
|
|
66
|
+
const expanded = new Map<string, Set<string>>()
|
|
67
|
+
const documentGroups = new Map<string, number[]>()
|
|
68
|
+
for (const point of [...new Set(documentCodePoints)].sort((left, right) => left - right)) {
|
|
69
|
+
const group = scriptGroup(point)
|
|
70
|
+
const points = documentGroups.get(group)
|
|
71
|
+
if (points) points.push(point)
|
|
72
|
+
else documentGroups.set(group, [point])
|
|
73
|
+
}
|
|
38
74
|
const families = new Set<string>()
|
|
39
75
|
let loadedBytes = 0
|
|
40
76
|
function read(): { state: FontState; data: Uint8Array } {
|
|
@@ -55,11 +91,24 @@ export function createFontReader(channel: SharedArrayBuffer, timeoutMs: number,
|
|
|
55
91
|
}
|
|
56
92
|
return (attributes) => {
|
|
57
93
|
const canonical = aliases.get(normalize(attributes.family))?.family
|
|
58
|
-
const
|
|
94
|
+
const codePoints = [...new Set(attributes.codePoints)].sort((left, right) => left - right)
|
|
95
|
+
const original = { ...attributes, codePoints, ...(canonical === undefined ? {} : { family: canonical }) }
|
|
59
96
|
const key = JSON.stringify(original)
|
|
60
97
|
const cached = requests.get(key)
|
|
61
98
|
if (cached) return cached
|
|
62
|
-
|
|
99
|
+
const { codePoints: _points, ...base } = original
|
|
100
|
+
const coverageKey = JSON.stringify(base)
|
|
101
|
+
const covered = coverage.get(coverageKey)
|
|
102
|
+
if (codePoints.length > 0 && covered && (covered.complete || codePoints.every(point => covered.points.has(point)))) {
|
|
103
|
+
requests.set(key, covered.faces)
|
|
104
|
+
return covered.faces
|
|
105
|
+
}
|
|
106
|
+
const groups = new Set(codePoints.map(scriptGroup))
|
|
107
|
+
const expandedGroups = expanded.get(coverageKey)
|
|
108
|
+
const newGroups = original.mode === 'full' ? [] : [...groups].filter(group => !expandedGroups?.has(group))
|
|
109
|
+
const requestedPoints = newGroups.length === 0 ? codePoints : [...new Set([...codePoints,
|
|
110
|
+
...newGroups.flatMap(group => documentGroups.get(group) ?? [])])].sort((left, right) => left - right)
|
|
111
|
+
request({ ...original, codePoints: requestedPoints }, [...installed].map(([id, font]) => ({ id, bytes: font.bytes, ...(font.format ? { format: font.format } : {}) })))
|
|
63
112
|
const first = read()
|
|
64
113
|
if (first.state !== FontState.Header) throw new BrowserRenderError('font-unavailable', 'Expected font transfer metadata.')
|
|
65
114
|
let header: FontHeader
|
|
@@ -69,15 +118,17 @@ export function createFontReader(channel: SharedArrayBuffer, timeoutMs: number,
|
|
|
69
118
|
for (const font of header.fonts) {
|
|
70
119
|
if (typeof font.id !== 'string' || typeof font.family !== 'string' || font.family.length === 0 || typeof font.alias !== 'string' || font.alias.length === 0 || /[\x00\t\r\n]/.test(font.alias) || !Number.isSafeInteger(font.bytes) || font.bytes <= 0) throw new BrowserRenderError('font-unavailable', 'Invalid font file descriptor.')
|
|
71
120
|
if (font.format !== undefined && !['ttf', 'otf', 'ttc'].includes(font.format)) throw new BrowserRenderError('font-unavailable', 'Invalid full font format.')
|
|
121
|
+
if (font.reference !== undefined && font.reference !== true) throw new BrowserRenderError('font-unavailable', 'Invalid font reference descriptor.')
|
|
72
122
|
const prior = installed.get(font.id)
|
|
73
|
-
if (
|
|
123
|
+
if (font.reference && !prior) throw new BrowserRenderError('font-unavailable', 'Font reference has not been installed.')
|
|
124
|
+
if (prior && (prior.bytes !== font.bytes || prior.format !== font.format || (font.format === undefined && prior.face.family !== font.alias))) throw new BrowserRenderError('font-unavailable', 'Font identity has conflicting bytes, aliases or formats.')
|
|
74
125
|
const alias = normalize(font.alias)
|
|
75
126
|
const previousAlias = aliases.get(alias)
|
|
76
127
|
if (previousAlias && (previousAlias.family !== font.family || (font.format === undefined && previousAlias.id !== font.id))) throw new BrowserRenderError('font-unavailable', 'Font alias identifies conflicting subsets.')
|
|
77
128
|
if (!prior && loadedBytes + font.bytes > maxLoadedFontBytes) throw new BrowserRenderError('font-limit', 'Imported fonts exceed maxLoadedFontBytes.')
|
|
78
129
|
const buffer = prior ? undefined : new Uint8Array(font.bytes)
|
|
79
130
|
let received = 0
|
|
80
|
-
while (received < font.bytes) {
|
|
131
|
+
while (!font.reference && received < font.bytes) {
|
|
81
132
|
const frame = read()
|
|
82
133
|
if (frame.state !== FontState.Bytes || frame.data.length === 0 || received + frame.data.length > font.bytes) throw new BrowserRenderError('font-unavailable', 'Incomplete font file transfer.')
|
|
83
134
|
buffer?.set(frame.data, received)
|
|
@@ -86,7 +137,7 @@ export function createFontReader(channel: SharedArrayBuffer, timeoutMs: number,
|
|
|
86
137
|
// A full TTC asset can expose multiple families from the same installed bytes.
|
|
87
138
|
// Its requested family must not inherit the first family's alias.
|
|
88
139
|
const face = { path: prior?.face.path ?? (font.format === undefined ? `/dsh-fonts/${installed.size}.font` : `/usr/share/fonts/dsh-pdfium/${installed.size}.${font.format}`), family: font.alias }
|
|
89
|
-
if (buffer) { install(face.path, buffer); installed.set(font.id, { face, format: font.format }); loadedBytes += buffer.length }
|
|
140
|
+
if (buffer) { install(face.path, buffer); installed.set(font.id, { face, bytes: buffer.length, format: font.format }); loadedBytes += buffer.length }
|
|
90
141
|
aliases.set(alias, { id: font.id, family: font.family })
|
|
91
142
|
faces.push(face)
|
|
92
143
|
}
|
|
@@ -94,6 +145,16 @@ export function createFontReader(channel: SharedArrayBuffer, timeoutMs: number,
|
|
|
94
145
|
const absentFamily = header.missingFamily === undefined ? undefined : declaredFamilies.get(normalize(header.missingFamily))
|
|
95
146
|
if (absentFamily !== undefined && !families.has(absentFamily)) { families.add(absentFamily); missing([...families]) }
|
|
96
147
|
requests.set(key, faces)
|
|
148
|
+
if (newGroups.length > 0) expanded.set(coverageKey, new Set([...(expandedGroups ?? []), ...newGroups]))
|
|
149
|
+
if (requestedPoints.length > 0) {
|
|
150
|
+
const group = { points: new Set(covered?.points), faces: [...(covered?.faces ?? [])], complete: covered?.complete ?? false }
|
|
151
|
+
for (const point of requestedPoints) group.points.add(point)
|
|
152
|
+
for (const face of faces) {
|
|
153
|
+
if (!group.faces.some(existing => existing.path === face.path && existing.family === face.family)) group.faces.push(face)
|
|
154
|
+
}
|
|
155
|
+
group.complete ||= header.fonts.every(font => font.format !== undefined)
|
|
156
|
+
coverage.set(coverageKey, group)
|
|
157
|
+
}
|
|
97
158
|
return faces
|
|
98
159
|
}
|
|
99
160
|
}
|
|
@@ -4,8 +4,9 @@ import { BrowserRenderError } from './types.ts'
|
|
|
4
4
|
import type { BrowserDocument, BrowserDocumentOptions, BrowserTile, BrowserTileRequest } from './types.ts'
|
|
5
5
|
export { BrowserRenderError } from './types.ts'
|
|
6
6
|
export { openOfficeDocument } from './office.ts'
|
|
7
|
+
export { prepareOfficeBrowser } from './preparation.ts'
|
|
7
8
|
export type * from './office-types.ts'
|
|
8
|
-
export type { BrowserDocument, BrowserDocumentOptions, BrowserEngineAssets, BrowserFontRequest, BrowserFontResult, BrowserPage, BrowserRenderErrorCode, BrowserTile, BrowserTileRequest } from './types.ts'
|
|
9
|
+
export type { BrowserDocument, BrowserDocumentOptions, BrowserEngineAssets, BrowserFontIdentity, BrowserFontRequest, BrowserFontResult, BrowserPage, BrowserRenderErrorCode, BrowserResolvedFont, BrowserTile, BrowserTileRequest, PreparedBrowserEngine } from './types.ts'
|
|
9
10
|
|
|
10
11
|
/**
|
|
11
12
|
* Open a read-only document; each call owns an independent Worker.
|
|
@@ -42,6 +42,8 @@ export class OfficeEngine {
|
|
|
42
42
|
private stopped = false
|
|
43
43
|
private layoutWidth = 0
|
|
44
44
|
private viewport = ''
|
|
45
|
+
private captureView: number | undefined
|
|
46
|
+
private readingView: number | undefined
|
|
45
47
|
private commandResult: { name: string; resolve: () => void; reject: (error: unknown) => void } | undefined
|
|
46
48
|
|
|
47
49
|
constructor(private readonly module: EmscriptenModule, private readonly document: number,
|
|
@@ -71,6 +73,18 @@ export class OfficeEngine {
|
|
|
71
73
|
/** Enforce the native read-only view before accepting any input. */
|
|
72
74
|
async start(): Promise<void> {
|
|
73
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
|
+
}
|
|
74
88
|
this.configure({ mode: 'paginated' })
|
|
75
89
|
this.invoke('listen')
|
|
76
90
|
this.refreshGeometry()
|
|
@@ -126,12 +140,15 @@ export class OfficeEngine {
|
|
|
126
140
|
} finally { this.call('free', [pointer]) }
|
|
127
141
|
}
|
|
128
142
|
private pump(): void {
|
|
143
|
+
if (this.readingView !== undefined) this.invoke('set_view', [this.readingView])
|
|
129
144
|
const deadline = performance.now() + 8
|
|
130
145
|
for (let pass = 0; pass < 8; pass++) {
|
|
131
146
|
const result = this.call('dsh_lok_pump')
|
|
132
147
|
if (result < 0) throw new BrowserRenderError('render-failed', 'LibreOffice event processing failed.')
|
|
133
148
|
if (!result || performance.now() >= deadline) break
|
|
134
149
|
}
|
|
150
|
+
// Deferred native focus events can activate the capture view while pumping.
|
|
151
|
+
if (this.readingView !== undefined) this.invoke('set_view', [this.readingView])
|
|
135
152
|
this.flush()
|
|
136
153
|
}
|
|
137
154
|
private flush(): void {
|
|
@@ -189,6 +206,7 @@ export class OfficeEngine {
|
|
|
189
206
|
/** The Worker permits only these typed reading operations, including at runtime. */
|
|
190
207
|
async operation(operation: OfficeOperation): Promise<{ text?: string; layout?: OfficeDocumentLayoutResult }> {
|
|
191
208
|
this.requireOpen()
|
|
209
|
+
if (this.readingView !== undefined) this.invoke('set_view', [this.readingView])
|
|
192
210
|
if (!operation || typeof operation !== 'object') throw new BrowserRenderError('render-failed', 'Invalid Office reading operation.')
|
|
193
211
|
switch (operation.type) {
|
|
194
212
|
case 'pointer': {
|
|
@@ -288,12 +306,18 @@ export class OfficeEngine {
|
|
|
288
306
|
/** Direct tiles preserve the active view, navigation state and selection. */
|
|
289
307
|
render(request: OfficeDocumentTileRequest): BrowserTile {
|
|
290
308
|
this.requireOpen()
|
|
309
|
+
if (this.readingView !== undefined) this.invoke('set_view', [this.readingView])
|
|
291
310
|
this.flush()
|
|
292
311
|
const part = this.state.parts[integer(request.part, this.state.parts.length - 1)]!
|
|
293
|
-
|
|
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.')
|
|
294
314
|
try {
|
|
315
|
+
if (capture) this.invoke('set_view', [this.captureView!])
|
|
295
316
|
return renderRegion(this.module, this.document, { ...request, pageIndex: 0 }, [{ ...part, x: 0, y: 0,
|
|
296
317
|
part: this.state.documentType === 'text' ? -1 : request.part }], () => new BrowserRenderError('render-failed', 'Office tile rendering failed.'))
|
|
297
|
-
} finally {
|
|
318
|
+
} finally {
|
|
319
|
+
if (this.readingView !== undefined) this.invoke('set_view', [this.readingView])
|
|
320
|
+
this.flush()
|
|
321
|
+
}
|
|
298
322
|
}
|
|
299
323
|
}
|
|
@@ -0,0 +1,41 @@
|
|
|
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,5 +1,5 @@
|
|
|
1
1
|
/** Private messages exchanged by the document owner and its single engine Worker. */
|
|
2
|
-
import type { BrowserDocumentOptions, BrowserFontRequest, BrowserPage, BrowserRenderErrorCode, BrowserTile, BrowserTileRequest } from './types.ts'
|
|
2
|
+
import type { BrowserDocumentOptions, BrowserFontIdentity, BrowserFontRequest, BrowserPage, BrowserRenderErrorCode, BrowserTile, BrowserTileRequest } from './types.ts'
|
|
3
3
|
import type { OfficeDocumentEvent, OfficeDocumentNavigation, OfficeDocumentOptions, OfficeDocumentState, OfficeDocumentPointer, OfficeDocumentLayoutRequest, OfficeDocumentLayoutResult, OfficeDocumentTileRequest, OfficeDocumentRectangle } from './office-types.ts'
|
|
4
4
|
|
|
5
5
|
export const FONT_CHUNK_BYTES = 1024 * 1024
|
|
@@ -30,10 +30,12 @@ export type WorkerMessage =
|
|
|
30
30
|
| { readonly type: 'office-event'; readonly event: OfficeDocumentEvent }
|
|
31
31
|
| { readonly type: 'disposed'; readonly id: number }
|
|
32
32
|
| { readonly type: 'error'; readonly id: number; readonly code: BrowserRenderErrorCode; readonly message: string; readonly fatal: boolean }
|
|
33
|
-
| { readonly type: 'font'; readonly request: BrowserFontRequest }
|
|
33
|
+
| { readonly type: 'font'; readonly request: BrowserFontRequest; readonly known: readonly FontIdentity[] }
|
|
34
34
|
| { readonly type: 'font-next' }
|
|
35
35
|
| { readonly type: 'missing-fonts'; readonly families: readonly string[] }
|
|
36
|
+
/** Immutable bytes already installed in this document's MEMFS. */
|
|
37
|
+
export type FontIdentity = BrowserFontIdentity
|
|
36
38
|
export interface FontHeader {
|
|
37
|
-
readonly fonts: readonly
|
|
39
|
+
readonly fonts: readonly (FontIdentity & { readonly family: string; readonly alias: string; readonly reference?: true })[]
|
|
38
40
|
readonly missingFamily?: string
|
|
39
41
|
}
|
|
@@ -10,6 +10,10 @@ export interface BrowserEngineAssets {
|
|
|
10
10
|
readonly programDirectory: string
|
|
11
11
|
}
|
|
12
12
|
|
|
13
|
+
declare const preparedBrowserEngine: unique symbol
|
|
14
|
+
/** Compiled engine code bound to one WASM resource identity. */
|
|
15
|
+
export interface PreparedBrowserEngine { readonly [preparedBrowserEngine]: true }
|
|
16
|
+
|
|
13
17
|
/** VCL attributes passed unchanged to the Host's font matcher. */
|
|
14
18
|
export interface BrowserFontRequest {
|
|
15
19
|
readonly mode?: 'full'
|
|
@@ -23,9 +27,24 @@ export interface BrowserFontRequest {
|
|
|
23
27
|
readonly codePoints: readonly number[]
|
|
24
28
|
}
|
|
25
29
|
|
|
30
|
+
/** Immutable font content already installed in one document Worker. */
|
|
31
|
+
export interface BrowserFontIdentity {
|
|
32
|
+
readonly id: string
|
|
33
|
+
readonly bytes: number
|
|
34
|
+
readonly format?: 'ttf' | 'otf' | 'ttc'
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/** One new font body or a metadata-only reference to content already installed in the Worker. */
|
|
38
|
+
export type BrowserResolvedFont = {
|
|
39
|
+
readonly id: string
|
|
40
|
+
readonly family: string
|
|
41
|
+
readonly alias: string
|
|
42
|
+
readonly format?: 'ttf' | 'otf' | 'ttc'
|
|
43
|
+
} & ({ readonly data: Uint8Array; readonly bytes?: never } | { readonly data?: never; readonly bytes: number })
|
|
44
|
+
|
|
26
45
|
/** Immutable per-face font subsets; equal ids and aliases must identify equal bytes. */
|
|
27
46
|
export interface BrowserFontResult {
|
|
28
|
-
readonly fonts: readonly
|
|
47
|
+
readonly fonts: readonly BrowserResolvedFont[]
|
|
29
48
|
readonly missingFamily?: string
|
|
30
49
|
/** Missing scalars reported by the Host, independently of a substituted family. */
|
|
31
50
|
readonly unresolvedCodePoints?: readonly number[]
|
|
@@ -56,6 +75,8 @@ export interface BrowserDocumentOptions {
|
|
|
56
75
|
readonly data: Uint8Array
|
|
57
76
|
readonly extension: 'pdf'
|
|
58
77
|
readonly assets: BrowserEngineAssets
|
|
78
|
+
/** Optional compiled WASM code created by prepareOfficeBrowser for these assets. */
|
|
79
|
+
readonly preparedEngine?: PreparedBrowserEngine
|
|
59
80
|
/** Maximum time for each load, render, font request, or teardown operation. */
|
|
60
81
|
readonly timeoutMs: number
|
|
61
82
|
/** Maximum ZIP entries inspected before LibreOffice loads OOXML. */
|
|
@@ -67,7 +88,7 @@ export interface BrowserDocumentOptions {
|
|
|
67
88
|
/** The same ordered substitution groups used by the Host font matcher. */
|
|
68
89
|
readonly fontFallbacks: readonly (readonly string[])[]
|
|
69
90
|
/** Match fonts without blocking the browser's main thread. */
|
|
70
|
-
readonly resolveFonts: (request: BrowserFontRequest, signal: AbortSignal) => Promise<BrowserFontResult>
|
|
91
|
+
readonly resolveFonts: (request: BrowserFontRequest, known: readonly BrowserFontIdentity[], signal: AbortSignal) => Promise<BrowserFontResult>
|
|
71
92
|
/** Called with unavailable declared OOXML families; binary DOC/PPT have no font diagnostics. */
|
|
72
93
|
readonly onMissingFonts?: (families: readonly string[]) => void
|
|
73
94
|
}
|
|
@@ -2,6 +2,7 @@
|
|
|
2
2
|
import { inspectDocument } from '@deepseek-ai/libreoffice-kit/document-inspection'
|
|
3
3
|
import { memoryFontConfig } from '@deepseek-ai/libreoffice-kit/font-config'
|
|
4
4
|
import { createFontReader } from './font-channel.ts'
|
|
5
|
+
import { instantiatePreparedModule, preparedBrowserModule } from './preparation.ts'
|
|
5
6
|
import { BrowserRenderError } from './types.ts'
|
|
6
7
|
import type { BrowserRenderErrorCode, BrowserTileRequest } from './types.ts'
|
|
7
8
|
import type { OwnerMessage, WorkerMessage, WorkerOptions } from './protocol.ts'
|
|
@@ -39,8 +40,14 @@ function error(code: BrowserRenderErrorCode): BrowserRenderError {
|
|
|
39
40
|
|
|
40
41
|
async function open(options: WorkerOptions, channel: SharedArrayBuffer, reading = false): Promise<void> {
|
|
41
42
|
const { assets } = options
|
|
43
|
+
const prepared = options.preparedEngine === undefined ? undefined : preparedBrowserModule(options.preparedEngine, assets)
|
|
42
44
|
let metadata: ReturnType<typeof inspectDocument>
|
|
43
45
|
try { metadata = options.extension === 'pdf' ? { families: new Map(), codePoints: [] } : inspectDocument(options.data, options.extension, options) } catch (failure) { throw new BrowserRenderError('invalid-document', failure instanceof Error ? failure.message : String(failure)) }
|
|
46
|
+
const initialFont = { family: 'sans-serif', style: '', weight: 5, italic: 0, width: 5, pitch: 0, language: '', codePoints: [] }
|
|
47
|
+
let initialFontPending = options.extension !== 'pdf'
|
|
48
|
+
// Host font discovery runs while the engine downloads and compiles. The first
|
|
49
|
+
// synchronous font read consumes this response through the same bounded channel.
|
|
50
|
+
if (initialFontPending) send({ type: 'font', request: initialFont, known: [] })
|
|
44
51
|
const response = await fetch(assets.dataUrl, { credentials: 'same-origin', signal: lifetime.signal })
|
|
45
52
|
if (!response.ok) throw new BrowserRenderError('unavailable', `LibreOffice data request failed: ${response.status}`)
|
|
46
53
|
const data = await response.arrayBuffer()
|
|
@@ -61,6 +68,10 @@ async function open(options: WorkerOptions, channel: SharedArrayBuffer, reading
|
|
|
61
68
|
}
|
|
62
69
|
},
|
|
63
70
|
getPreloadedPackage: () => data,
|
|
71
|
+
...(prepared === undefined ? {} : { instantiateWasm(imports: WebAssembly.Imports,
|
|
72
|
+
receive: (instance: WebAssembly.Instance, compiled: WebAssembly.Module) => void) {
|
|
73
|
+
return instantiatePreparedModule(prepared, imports, receive)
|
|
74
|
+
} }),
|
|
64
75
|
dshResolveSystemFontFaces(request: Parameters<NonNullable<typeof resolveFonts>>[0]) {
|
|
65
76
|
if (!resolveFonts) throw new BrowserRenderError('font-unavailable', 'LibreOffice requested fonts before MEMFS initialization.')
|
|
66
77
|
try { return resolveFonts(request) } catch (failure) { fontFailure = failure; throw failure }
|
|
@@ -70,10 +81,14 @@ async function open(options: WorkerOptions, channel: SharedArrayBuffer, reading
|
|
|
70
81
|
loaded.FS.writeFile('/dsh/fonts.conf', new TextEncoder().encode(memoryFontConfig(options.fontFallbacks, metadata.families.values())))
|
|
71
82
|
Object.assign(loaded.ENV, { HOME: '/dsh/profile', TMPDIR: '/tmp', FONTCONFIG_FILE: '/dsh/fonts.conf', LOK_HOST_ALLOWLIST: '^$' })
|
|
72
83
|
resolveFonts = createFontReader(channel, options.timeoutMs, options.maxLoadedFontBytes, metadata.families,
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
84
|
+
(request, known) => {
|
|
85
|
+
if (initialFontPending) initialFontPending = false
|
|
86
|
+
else send({ type: 'font', request, known })
|
|
87
|
+
}, () => send({ type: 'font-next' }),
|
|
88
|
+
(path, bytes) => loaded.FS.writeFile(path, bytes), families => send({ type: 'missing-fonts', families }), metadata.codePoints)
|
|
89
|
+
if (options.extension === 'pdf') {
|
|
90
|
+
for (const family of new Set(options.fontFallbacks.flat())) resolveFonts({ ...initialFont, family, mode: 'full' })
|
|
91
|
+
} else resolveFonts(initialFont)
|
|
77
92
|
}],
|
|
78
93
|
onAbort() { fatal = true },
|
|
79
94
|
print() {}, printErr() {},
|
|
@@ -56,7 +56,7 @@ export function verifyBrowserPackage(target = directory, engineDirectory = join(
|
|
|
56
56
|
for (const helper of helpers) regularFile(target, `lib/${helper}.js`);
|
|
57
57
|
const declarations = join(target, 'lib/browser/types');
|
|
58
58
|
const declarationText = readdirSync(declarations).filter(name => name.endsWith('.d.ts')).map(name => readFileSync(join(declarations, name), 'utf8')).join('\n');
|
|
59
|
-
assert(declarationText.includes('openOfficeDocument') && !declarationText.includes('openEditor')
|
|
59
|
+
assert(declarationText.includes('openOfficeDocument') && declarationText.includes('prepareOfficeBrowser') && !declarationText.includes('openEditor')
|
|
60
60
|
&& !readdirSync(declarations).some(name => name.startsWith('editor')), 'Browser package retains a removed editing SDK');
|
|
61
61
|
const receipt = readJson(regularFile(target, 'lib/browser/assets.json'));
|
|
62
62
|
const worker = receipt.files?.worker;
|
|
@@ -53,7 +53,7 @@ export function releaseAssetUrl(version, file) {
|
|
|
53
53
|
/** Return the complete declared matrix, including targets without built assets. */
|
|
54
54
|
export function packageMatrix(repo = root) {
|
|
55
55
|
return readdirSync(join(repo, 'packages'), { withFileTypes: true })
|
|
56
|
-
.filter((entry) => entry.isDirectory() && !['entry', 'browser'].includes(entry.name))
|
|
56
|
+
.filter((entry) => entry.isDirectory() && !['entry', 'browser', 'fonts'].includes(entry.name))
|
|
57
57
|
.sort((a, b) => a.name.localeCompare(b.name))
|
|
58
58
|
.map((entry) => {
|
|
59
59
|
const dir = join(repo, 'packages', entry.name);
|
|
@@ -88,8 +88,8 @@ export function verifyEngineMetadata(manifest, prebuild) {
|
|
|
88
88
|
}
|
|
89
89
|
const exact = (actual, expected) => JSON.stringify(actual) === JSON.stringify(expected);
|
|
90
90
|
if (prebuild.platform === 'wasm') {
|
|
91
|
-
assert(
|
|
92
|
-
assert(engine?.kind === 'wasm' && engine.loader === 'assets/soffice.cjs' && engine.wasm === 'assets/
|
|
91
|
+
assert(manifest.os === undefined && manifest.cpu === undefined && manifest.libc === undefined, 'WASM package must install across operating systems, CPUs and libc variants');
|
|
92
|
+
assert(engine?.kind === 'wasm' && engine.loader === 'assets/soffice.cjs' && engine.wasm === 'assets/dsh-office.wasm'
|
|
93
93
|
&& engine.data === 'assets/soffice.data' && engine.metadata === 'assets/soffice.data.js.metadata'
|
|
94
94
|
&& engine.programDirectory === '/instdir/program', 'Unsupported WASM engine paths');
|
|
95
95
|
} else {
|
|
@@ -230,7 +230,7 @@ export function verifyEnginePackage(dir) {
|
|
|
230
230
|
for (const key of ['loader', 'wasm', 'data', 'metadata']) regularFile(dir, engine[key]);
|
|
231
231
|
const module = new WebAssembly.Module(readFileSync(join(dir, engine.wasm)));
|
|
232
232
|
const exports = new Set(WebAssembly.Module.exports(module).filter((entry) => entry.kind === 'function').map((entry) => entry.name.replace(/^_/, '')));
|
|
233
|
-
for (const name of ['dsh_lok_initialize', 'dsh_lok_document_load', 'dsh_lok_document_save_pdf', 'dsh_lok_document_destroy', 'dsh_lok_destroy', 'dsh_lok_error', 'malloc', 'free']) {
|
|
233
|
+
for (const name of ['dsh_lok_initialize', 'dsh_lok_document_load', 'dsh_lok_document_save_pdf', 'dsh_lok_document_export', 'dsh_lok_document_destroy', 'dsh_lok_destroy', 'dsh_lok_error', 'malloc', 'free']) {
|
|
234
234
|
assert(exports.has(name), `WASM engine missing conversion export: ${name}`);
|
|
235
235
|
}
|
|
236
236
|
const dataSize = statSync(join(dir, engine.data)).size;
|