@deepseek-ai/libreoffice-kit 0.0.2-rc6 → 0.0.2-rc9

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 (40) hide show
  1. package/README.md +2 -2
  2. package/README.zh.md +1 -1
  3. package/assets/font-subset.json +2 -2
  4. package/lib/browser/assets.json +2 -2
  5. package/lib/browser/index.js +333 -162
  6. package/lib/browser/types/connection.d.ts +28 -6
  7. package/lib/browser/types/font-channel.d.ts +16 -1
  8. package/lib/browser/types/index.d.ts +3 -2
  9. package/lib/browser/types/office-engine.d.ts +10 -2
  10. package/lib/browser/types/office-types.d.ts +60 -1
  11. package/lib/browser/types/office.d.ts +18 -3
  12. package/lib/browser/types/preparation.d.ts +13 -0
  13. package/lib/browser/types/protocol.d.ts +33 -10
  14. package/lib/browser/types/types.d.ts +31 -8
  15. package/lib/browser/worker.js +360 -106
  16. package/lib/browser-assets.js +1 -1
  17. package/lib/cli.js +2 -2
  18. package/lib/font-source.js +19 -1
  19. package/lib/font-worker.js +126 -29
  20. package/lib/index.js +2 -2
  21. package/lib/types/engine.d.ts +1 -1
  22. package/lib/types/font-source-types.d.ts +11 -0
  23. package/lib/types/font-subsets.d.ts +5 -1
  24. package/lib/types/fonts.d.ts +1 -0
  25. package/lib/types/office-fonts.d.ts +6 -0
  26. package/lib/worker.js +6 -5
  27. package/package.json +2 -2
  28. package/sources/browser/packages/browser/package.json +1 -1
  29. package/sources/browser/packages/browser/src/connection.ts +105 -34
  30. package/sources/browser/packages/browser/src/font-channel.ts +69 -9
  31. package/sources/browser/packages/browser/src/index.ts +3 -2
  32. package/sources/browser/packages/browser/src/office-engine.ts +80 -6
  33. package/sources/browser/packages/browser/src/office-types.ts +52 -1
  34. package/sources/browser/packages/browser/src/office.ts +118 -52
  35. package/sources/browser/packages/browser/src/preparation.ts +41 -0
  36. package/sources/browser/packages/browser/src/protocol.ts +19 -5
  37. package/sources/browser/packages/browser/src/types.ts +26 -2
  38. package/sources/browser/packages/browser/src/worker.ts +138 -53
  39. package/sources/browser/scripts/build-browser.mjs +6 -2
  40. package/sources/font-subset/scripts/verify-artifacts.mjs +1 -1
package/README.md CHANGED
@@ -52,7 +52,7 @@ CLI paths resolve against its working directory. Success writes one JSON object
52
52
 
53
53
  Node operations and the Host font service use bounded system-font discovery. Exact installed families and explicit aliases precede Unicode-script and regional body-text preferences, then other glyph-covering fonts. Windows preferences derive from pinned Chromium data; macOS/Linux use Fontconfig categories, with the other source supplying additional candidates. Unicode 17 Script/Script_Extensions data keeps mixed text independent of incorrectly declared document languages. Only unlisted Latin/CJK decorative faces are demoted; cursive writing traditions such as Urdu Nastaliq remain normal body fonts. No fonts are downloaded or bundled by these rules. Full original files retain shaping and encoding. Recreate the converter after changing installed fonts. `missingFonts` reports unavailable declared OOXML families; font-service `unresolvedCodePoints` separately reports scalars no installed face covers. The rule data and licenses are regenerated with `node scripts/generate-font-preferences.mjs` and retained in `NOTICE`.
54
54
 
55
- `createFontSource` from `@deepseek-ai/libreoffice-kit/fonts` provides an independent lazy Worker service. `resolve(attributes)` retains the Unicode-script subset behavior for interactive Office. `resolve({...attributes, mode:'full'})` returns opaque `full_…` identities, original family names and `format` (`ttf`, `otf`, `ttc`); `read(id)` returns complete original font bytes. Apple dfont resources are extracted as complete sfnt faces. Reads reject unknown or changed sources and do not expose host paths.
55
+ `createFontSource` from `@deepseek-ai/libreoffice-kit/fonts` provides an independent Worker service. `prepare()` builds its lifetime font snapshot before the first document request. Default discovery supplements normal system roots with a small compatibility set from an installed Microsoft Office on macOS or Windows; explicit `fontDirectories` replace all defaults. No font bytes or Host paths enter the package. `resolve(attributes)` retains the Unicode-script subset behavior for interactive Office. `resolve({...attributes, mode:'full'})` returns opaque `full_…` identities, original family names and `format` (`ttf`, `otf`, `ttc`); `read(id)` returns complete original font bytes. Apple dfont resources are extracted as complete sfnt faces. Reads reject unknown or changed sources and do not expose host paths.
56
56
 
57
57
  Full-mode selections from the same unchanged TTC share one file read and retained byte entry while keeping each selected family's name and alias. The existing cache budget counts unique full assets once; eviction may require a later read to regenerate them. Subsets and dfont resources remain specific to each physical face.
58
58
 
@@ -60,7 +60,7 @@ PDFium is an experimental direct raster path, separate from PDF.js and Office re
60
60
 
61
61
  ## Browser and font entries
62
62
 
63
- `@deepseek-ai/libreoffice-kit/browser` provides retained read-only Office sessions through `openOfficeDocument`, Writer paginated/continuous layouts, selection/copy, and standalone PDFium viewing. The rc5 browser API has no editing, snapshot-save or capture operations; Node/CLI conversion and recalculation retain their explicit output APIs. `@deepseek-ai/libreoffice-kit/browser-assets` resolves the local browser Worker and validates the assets in the exact-version WASM dependency. Host asset servers expose these resources as opaque URLs; the main package does not duplicate the LibreOffice payload.
63
+ `@deepseek-ai/libreoffice-kit/browser` provides read-only Office sessions through `openOfficeDocument` and reusable one-document-at-a-time engines through `openOfficeRuntime`. Documents can capture and restore typed reading state while applications retain any display snapshot. Writer paginated/continuous layouts, selection/copy and standalone PDFium viewing remain available. The browser API has no editing, snapshot-save or browser-capture operation; Node/CLI conversion and recalculation retain their explicit output APIs. `@deepseek-ai/libreoffice-kit/browser-assets` resolves the local browser Worker and validates the assets in the exact-version WASM dependency. Host asset servers expose these resources as opaque URLs; the main package does not duplicate the LibreOffice payload.
64
64
 
65
65
  `./fonts` provides the Host font service described above. Browser-safe `./font-config` and `./document-inspection` share font configuration and input validation with the Node API. `./internal/*` exports are implementation details used by the bundled browser Worker.
66
66
 
package/README.zh.md CHANGED
@@ -49,7 +49,7 @@ PDFium 直接图片渲染仍为实验能力,与 PDF.js 和 Office 阅读会话
49
49
 
50
50
  ## 浏览器与字体入口
51
51
 
52
- `@deepseek-ai/libreoffice-kit/browser` 通过 `openOfficeDocument` 提供常驻 Office 阅读会话、Writer 分页/连续重排、选择复制和独立 PDFium 查看。rc5 浏览器 API 不提供编辑、OOXML 保存快照或 capture;Node/CLI 的转换和重算仍保留显式输出能力。Node 端 `./browser-assets` 校验并解析主包中的 Worker,以及精确版本 WASM 依赖中的资源。Host 将其映射成资源 URL;主包不复制 LibreOffice 大文件。
52
+ `@deepseek-ai/libreoffice-kit/browser` 通过 `openOfficeDocument` 提供只读 Office 文档,并通过 `openOfficeRuntime` 提供一次只打开一个文档、可复用的运行时。文档可以捕获和恢复类型化阅读状态,显示快照仍由应用持有。Writer 分页/连续重排、选择复制和独立 PDFium 查看继续可用。浏览器 API 不提供编辑、OOXML 保存快照或浏览器画面捕获;Node/CLI 的转换和重算仍保留显式输出能力。Node 端 `./browser-assets` 校验并解析主包中的 Worker,以及精确版本 WASM 依赖中的资源。Host 将其映射成资源 URL;主包不复制 LibreOffice 大文件。
53
53
 
54
54
  `./fonts` 提供上文的字体服务。`./font-config` 与 `./document-inspection` 为浏览器和 Node 共用的纯逻辑;`./internal/*` 仅用于内部实现。字体子集采用 Unicode 17 数据和 HarfBuzz 布局闭包,内存缓存淘汰后从未变化的原字体重新生成。
55
55
 
@@ -39,8 +39,8 @@
39
39
  "sha256": "aa5368e0dd38d90459f0ef14e1d4b27740aef2f4e46617aca6d6fafed0577a44"
40
40
  },
41
41
  "sources/font-subset/scripts/verify-artifacts.mjs": {
42
- "bytes": 16017,
43
- "sha256": "b69af5760f7ebfedece94f198dba765def2fd840a4d46bdb8c8b7729fb4884ea"
42
+ "bytes": 16020,
43
+ "sha256": "bc3103bdeedc64c80487e7daf096a03e3b8c180e0b4fdc8986e987fb823a6d82"
44
44
  },
45
45
  "sources/font-subset/engine/font-subset/README.md": {
46
46
  "bytes": 2130,
@@ -3,8 +3,8 @@
3
3
  "files": {
4
4
  "worker": {
5
5
  "path": "lib/browser/worker.js",
6
- "bytes": 116577,
7
- "sha256": "81237217e64c708763b3e8c2128ed29c1d589ddd4753008c761396d69449eb43"
6
+ "bytes": 127167,
7
+ "sha256": "eb76230173a37f65af3dda31c515199de6520c534242c7fdffab4958c5fbf17b"
8
8
  }
9
9
  }
10
10
  }
@@ -26,13 +26,15 @@ function* fontFrames(result, known = []) {
26
26
  const identities = new Map(known.map((font) => [font.id, font]));
27
27
  const header = {
28
28
  fonts: result.fonts.map((font) => {
29
+ const size = font.data === void 0 ? font.bytes : font.data.byteLength;
29
30
  const identity = {
30
31
  id: font.id,
31
- bytes: font.data.byteLength,
32
+ bytes: size,
32
33
  ...font.format ? { format: font.format } : {}
33
34
  };
34
35
  const prior = identities.get(font.id);
35
36
  if (prior && (prior.bytes !== identity.bytes || prior.format !== identity.format)) throw new BrowserRenderError("font-unavailable", "Font identity has conflicting bytes or formats.");
37
+ if (!prior && font.data === void 0) throw new BrowserRenderError("font-unavailable", "Font reference has not been installed.");
36
38
  identities.set(font.id, identity);
37
39
  return {
38
40
  ...identity,
@@ -51,6 +53,8 @@ function* fontFrames(result, known = []) {
51
53
  };
52
54
  for (const [index, font] of result.fonts.entries()) {
53
55
  if (header.fonts[index].reference) continue;
56
+ /* v8 ignore next -- header validation rejects an unknown data-less font before iteration. */
57
+ if (font.data === void 0) throw new BrowserRenderError("font-unavailable", "Font reference has not been installed.");
54
58
  for (let offset = 0; offset < font.data.byteLength; offset += FONT_CHUNK_BYTES) yield {
55
59
  state: 2,
56
60
  bytes: font.data.subarray(offset, offset + FONT_CHUNK_BYTES)
@@ -62,15 +66,46 @@ function* fontFrames(result, known = []) {
62
66
  };
63
67
  }
64
68
  //#endregion
69
+ //#region lib/types/preparation.js
70
+ /** Browser-side WASM compilation without creating an Office Worker or memory. */
71
+ /**
72
+ * Compile the version-matched LibreOffice WASM module for later document Workers.
73
+ * @param assets - Browser resources whose WASM URL identifies the compiled module.
74
+ * @param signal - Cancels the resource request; compilation may finish before cancellation is observed.
75
+ * @returns an opaque, structured-cloneable engine handle that allocates no WASM memory.
76
+ */
77
+ async function prepareOfficeBrowser(assets, signal) {
78
+ signal?.throwIfAborted();
79
+ if (typeof WebAssembly.compileStreaming !== "function") throw new BrowserRenderError("unavailable", "Streaming WebAssembly compilation is unavailable.");
80
+ const response = await fetch(assets.wasmUrl, {
81
+ credentials: "same-origin",
82
+ ...signal === void 0 ? {} : { signal }
83
+ });
84
+ if (!response.ok) throw new BrowserRenderError("unavailable", `LibreOffice WASM request failed: ${response.status}`);
85
+ const module = await WebAssembly.compileStreaming(Promise.resolve(response));
86
+ signal?.throwIfAborted();
87
+ return Object.freeze({
88
+ wasmUrl: assets.wasmUrl,
89
+ module
90
+ });
91
+ }
92
+ /** Return the compiled module after validating the Worker-bound asset identity. */
93
+ function preparedBrowserModule(prepared, assets) {
94
+ const record = prepared;
95
+ if (record.wasmUrl !== assets.wasmUrl || !(record.module instanceof WebAssembly.Module)) throw new TypeError("The prepared browser engine does not match the requested WASM asset.");
96
+ return record.module;
97
+ }
98
+ //#endregion
65
99
  //#region lib/types/connection.js
66
- /** Browser document ownership, cancellation and asynchronous Host font delivery. */
100
+ /** Browser Worker ownership, document lifetime, cancellation and asynchronous Host font delivery. */
67
101
  /**
68
- * Load original Office bytes in a dedicated Worker with no intermediate PDF.
69
- * @param options - Resources, limits, source bytes and asynchronous Host font provider.
70
- * @param signal - Document lifetime; abort closes its Worker and all pending work.
71
- * @returns Initial geometry, ordered Worker requests and joined disposal.
102
+ * Start one LibreOffice Worker without loading a document.
103
+ * @param options - Engine resources, limits and asynchronous Host font provider.
104
+ * @param signal - Engine lifetime; abort closes its Worker and all pending work.
105
+ * @param onEvent - Reading notifications, including fatal Worker failures.
106
+ * @returns Document loading, Worker requests and joined disposal.
72
107
  */
73
- async function openBrowserConnection(options, signal, office = false, onEvent) {
108
+ async function openBrowserWorker(options, signal, onEvent) {
74
109
  signal?.throwIfAborted();
75
110
  if (!globalThis.crossOriginIsolated || typeof SharedArrayBuffer === "undefined" || typeof Worker === "undefined") throw new BrowserRenderError("unavailable", "LibreOffice requires an isolated secure browser context with Worker and SharedArrayBuffer support.");
76
111
  if (![
@@ -79,14 +114,7 @@ async function openBrowserConnection(options, signal, office = false, onEvent) {
79
114
  options.maxArchiveEntries,
80
115
  options.maxUncompressedBytes
81
116
  ].every((value) => Number.isSafeInteger(value) && value > 0) || options.timeoutMs > 2147483647) throw new TypeError("Document limits must be positive integers and timeoutMs must fit a browser timer.");
82
- if (!(office ? [
83
- "doc",
84
- "docx",
85
- "xls",
86
- "xlsx",
87
- "ppt",
88
- "pptx"
89
- ] : ["pdf"]).includes(options.extension) || options.data.byteLength === 0) throw new BrowserRenderError("invalid-document", "The document is empty or has an unsupported extension.");
117
+ if (options.preparedEngine !== void 0) preparedBrowserModule(options.preparedEngine, options.assets);
90
118
  const worker = new Worker(options.assets.workerUrl, { name: "libreoffice-document" });
91
119
  const channel = new SharedArrayBuffer(1048584);
92
120
  const { control, bytes } = fontViews(channel);
@@ -96,7 +124,8 @@ async function openBrowserConnection(options, signal, office = false, onEvent) {
96
124
  let closed = false;
97
125
  let disposal;
98
126
  let frames;
99
- let opened;
127
+ let resolveFonts;
128
+ let onMissingFonts;
100
129
  function failPending(error) {
101
130
  for (const entry of pending.values()) entry.reject(error);
102
131
  pending.clear();
@@ -137,7 +166,11 @@ async function openBrowserConnection(options, signal, office = false, onEvent) {
137
166
  return;
138
167
  case "font":
139
168
  if (closed) return;
140
- Promise.resolve().then(() => options.resolveFonts(message.request, lifetime.signal)).then((result) => {
169
+ if (!resolveFonts) {
170
+ sendFontError(new BrowserRenderError("font-unavailable", "No document font resolver is active."));
171
+ return;
172
+ }
173
+ Promise.resolve().then(() => resolveFonts(message.request, message.known, lifetime.signal)).then((result) => {
141
174
  if (closed) return;
142
175
  frames = fontFrames(result, message.known);
143
176
  pumpFonts();
@@ -147,7 +180,7 @@ async function openBrowserConnection(options, signal, office = false, onEvent) {
147
180
  pumpFonts();
148
181
  return;
149
182
  case "missing-fonts":
150
- if (!closed) options.onMissingFonts?.(message.families);
183
+ if (!closed) onMissingFonts?.(message.families);
151
184
  return;
152
185
  default: {
153
186
  const entry = pending.get(message.id);
@@ -224,6 +257,8 @@ async function openBrowserConnection(options, signal, office = false, onEvent) {
224
257
  signal?.removeEventListener("abort", aborted);
225
258
  lifetime.abort();
226
259
  frames = void 0;
260
+ resolveFonts = void 0;
261
+ onMissingFonts = void 0;
227
262
  Atomics.store(control, 0, 5);
228
263
  Atomics.notify(control, 0);
229
264
  failPending(new BrowserRenderError("disposed", "The document is closed."));
@@ -246,173 +281,309 @@ async function openBrowserConnection(options, signal, office = false, onEvent) {
246
281
  dispose();
247
282
  }
248
283
  signal?.addEventListener("abort", aborted, { once: true });
284
+ function request(message, operation, transfer = []) {
285
+ if (closed) return Promise.reject(new BrowserRenderError("disposed", "The document is closed."));
286
+ if (operation?.aborted) return Promise.reject(operation.reason);
287
+ const task = post({
288
+ ...message,
289
+ id: ++sequence
290
+ }, transfer);
291
+ if (!operation) return task;
292
+ return new Promise((resolve, reject) => {
293
+ const abort = () => {
294
+ reject(operation.reason);
295
+ };
296
+ operation.addEventListener("abort", abort, { once: true });
297
+ task.then(resolve, reject).finally(() => operation.removeEventListener("abort", abort));
298
+ });
299
+ }
300
+ const engineOptions = {
301
+ assets: options.assets,
302
+ ...options.preparedEngine === void 0 ? {} : { preparedEngine: options.preparedEngine },
303
+ timeoutMs: options.timeoutMs,
304
+ maxLoadedFontBytes: options.maxLoadedFontBytes,
305
+ fontFallbacks: options.fontFallbacks,
306
+ maxArchiveEntries: options.maxArchiveEntries,
307
+ maxUncompressedBytes: options.maxUncompressedBytes
308
+ };
249
309
  try {
250
- const data = new Uint8Array(options.data);
251
- const engineOptions = {
252
- data,
253
- extension: options.extension,
254
- assets: options.assets,
255
- timeoutMs: options.timeoutMs,
256
- maxLoadedFontBytes: options.maxLoadedFontBytes,
257
- fontFallbacks: options.fontFallbacks,
258
- maxArchiveEntries: options.maxArchiveEntries,
259
- maxUncompressedBytes: options.maxUncompressedBytes
260
- };
261
- const result = await post({
262
- type: "open",
310
+ if ((await post({
311
+ type: "start",
263
312
  id: ++sequence,
264
313
  options: engineOptions,
265
- channel,
266
- ...office ? { office: true } : {}
267
- }, [data.buffer]);
268
- if (result.type !== "opened") throw new BrowserRenderError("invalid-document", "LibreOffice returned an unexpected load response.");
269
- opened = result;
270
- if (opened.type !== "opened" || opened.pages.length === 0) throw new BrowserRenderError("invalid-document", "LibreOffice returned no document pages.");
314
+ channel
315
+ })).type !== "started") throw new BrowserRenderError("unavailable", "LibreOffice returned an unexpected start response.");
271
316
  signal?.throwIfAborted();
272
- } catch (error) {
317
+ } catch (failure) {
273
318
  await dispose();
274
319
  signal?.throwIfAborted();
275
- throw error;
320
+ throw failure;
276
321
  }
277
322
  return {
278
- opened,
279
- request(message, operation) {
280
- if (closed) return Promise.reject(new BrowserRenderError("disposed", "The document is closed."));
281
- if (operation?.aborted) return Promise.reject(operation.reason);
282
- const task = post({
283
- ...message,
284
- id: ++sequence
285
- });
286
- if (!operation) return task;
287
- return new Promise((resolve, reject) => {
288
- const abort = () => {
289
- reject(operation.reason);
290
- };
291
- operation.addEventListener("abort", abort, { once: true });
292
- task.then(resolve, reject).finally(() => operation.removeEventListener("abort", abort));
293
- });
323
+ async openDocument(documentOptions, documentSignal) {
324
+ if (closed) throw new BrowserRenderError("disposed", "The document is closed.");
325
+ if (![
326
+ "pdf",
327
+ "doc",
328
+ "docx",
329
+ "xls",
330
+ "xlsx",
331
+ "ppt",
332
+ "pptx"
333
+ ].includes(documentOptions.extension) || documentOptions.data.byteLength === 0) throw new BrowserRenderError("invalid-document", "The document is empty or has an unsupported extension.");
334
+ const data = new Uint8Array(documentOptions.data);
335
+ resolveFonts = documentOptions.resolveFonts;
336
+ onMissingFonts = documentOptions.onMissingFonts;
337
+ try {
338
+ const result = await request({
339
+ type: "open",
340
+ options: {
341
+ data,
342
+ extension: documentOptions.extension,
343
+ ...documentOptions.restore === void 0 ? {} : { restore: documentOptions.restore }
344
+ }
345
+ }, documentSignal, [data.buffer]);
346
+ if (result.type !== "opened") throw new BrowserRenderError("invalid-document", "LibreOffice returned an unexpected load response.");
347
+ if (result.pages.length === 0) throw new BrowserRenderError("invalid-document", "LibreOffice returned no document pages.");
348
+ documentSignal?.throwIfAborted();
349
+ return result;
350
+ } catch (failure) {
351
+ await dispose();
352
+ documentSignal?.throwIfAborted();
353
+ throw failure;
354
+ }
355
+ },
356
+ async closeDocument() {
357
+ if (closed) return;
358
+ try {
359
+ if ((await request({ type: "close-document" })).type !== "closed-document") throw new BrowserRenderError("render-failed", "LibreOffice returned an unexpected close response.");
360
+ } finally {
361
+ resolveFonts = void 0;
362
+ onMissingFonts = void 0;
363
+ }
294
364
  },
365
+ request,
295
366
  dispose
296
367
  };
297
368
  }
369
+ /**
370
+ * Load original PDF bytes in a dedicated Worker without Draw import.
371
+ * @param options - Resources, limits, source bytes and asynchronous Host font provider.
372
+ * @param signal - Document lifetime; abort closes its Worker and all pending work.
373
+ * @param onEvent - Reading notifications, including fatal Worker failures.
374
+ * @returns Initial geometry, ordered Worker requests and joined disposal.
375
+ */
376
+ async function openBrowserConnection(options, signal, onEvent) {
377
+ signal?.throwIfAborted();
378
+ if (options.extension !== "pdf" || options.data.byteLength === 0) throw new BrowserRenderError("invalid-document", "The document is empty or has an unsupported extension.");
379
+ const connected = await openBrowserWorker(options, signal, onEvent);
380
+ try {
381
+ return {
382
+ opened: await connected.openDocument({
383
+ data: options.data,
384
+ extension: options.extension,
385
+ resolveFonts: options.resolveFonts,
386
+ ...options.onMissingFonts === void 0 ? {} : { onMissingFonts: options.onMissingFonts }
387
+ }, signal),
388
+ request: connected.request,
389
+ dispose: connected.dispose
390
+ };
391
+ } catch (error) {
392
+ await connected.dispose();
393
+ throw error;
394
+ }
395
+ }
298
396
  //#endregion
299
397
  //#region lib/types/office.js
300
- /** Browser owner for a retained read-only Office model. */
301
- /** Open one read-only Office model; source bytes remain owned by the caller. */
302
- async function openOfficeDocument(options, signal) {
303
- const listeners = /* @__PURE__ */ new Set();
304
- let state;
305
- const connection = await openBrowserConnection(options, signal, true, (event) => {
306
- if (event.type === "state") state = event.state;
307
- for (const listener of listeners) try {
398
+ /** Browser owner for one shared engine Worker and its read-only Office documents. */
399
+ /**
400
+ * Start one read-only Office engine that opens documents one at a time.
401
+ * @param options - Engine resources and limits shared by every document.
402
+ * @param signal - Runtime lifetime; abort closes the Worker and its pthreads.
403
+ * @returns Sequential document loading and joined disposal.
404
+ */
405
+ async function openOfficeRuntime(options, signal) {
406
+ let current;
407
+ let disposed = false;
408
+ const worker = await openBrowserWorker(options, signal, (event) => {
409
+ if (event.type === "state") current?.update(event.state);
410
+ for (const listener of current?.listeners ?? []) try {
308
411
  listener(event);
309
412
  } catch (error) {
310
413
  console.error("Office document observer failed", error);
311
414
  }
312
415
  });
313
- state = connection.opened.office;
314
- if (!state) {
315
- await connection.dispose();
316
- throw new BrowserRenderError("invalid-document", "LibreOffice returned no reading state.");
317
- }
318
- async function operate(operation) {
319
- const response = await connection.request({
320
- type: "office-operation",
321
- operation
322
- });
323
- if (response.type !== "office-result") throw new BrowserRenderError("render-failed", "LibreOffice returned an unexpected reading response.");
324
- return response;
325
- }
326
- let layoutRunning = false;
327
- let pendingLayout;
328
- async function applyLayouts() {
329
- layoutRunning = true;
330
- while (pendingLayout) {
331
- const next = pendingLayout;
332
- pendingLayout = void 0;
333
- try {
334
- const response = await operate({
335
- type: "layout",
336
- request: next.request
337
- });
338
- if (!response.layout) throw new BrowserRenderError("render-failed", "LibreOffice returned no layout result.");
339
- for (const waiter of next.waiters) waiter.resolve(response.layout);
340
- } catch (error) {
341
- for (const waiter of next.waiters) waiter.reject(error);
416
+ const open = async (openOptions, documentSignal) => {
417
+ if (disposed) throw new BrowserRenderError("disposed", "The Office runtime is closed.");
418
+ if (current && !current.closed) current.closed = true;
419
+ current?.listeners.clear();
420
+ current = void 0;
421
+ await worker.closeDocument();
422
+ const opened = await worker.openDocument({
423
+ data: openOptions.data,
424
+ extension: openOptions.extension,
425
+ resolveFonts: openOptions.resolveFonts,
426
+ ...openOptions.onMissingFonts === void 0 ? {} : { onMissingFonts: openOptions.onMissingFonts },
427
+ ...openOptions.restore === void 0 ? {} : { restore: openOptions.restore }
428
+ }, documentSignal);
429
+ if (!opened.office) throw new BrowserRenderError("invalid-document", "LibreOffice returned no reading state.");
430
+ let reading = opened.office;
431
+ const record = {
432
+ closed: false,
433
+ listeners: /* @__PURE__ */ new Set(),
434
+ update(state) {
435
+ reading = state;
342
436
  }
343
- }
344
- layoutRunning = false;
345
- }
346
- return {
347
- get state() {
348
- return state;
349
- },
350
- subscribe(listener) {
351
- listeners.add(listener);
352
- return () => {
353
- listeners.delete(listener);
354
- };
355
- },
356
- async pointer(event) {
357
- await operate({
358
- type: "pointer",
359
- event
360
- });
361
- },
362
- async navigate(event) {
363
- await operate({
364
- type: "navigate",
365
- event
366
- });
367
- },
368
- async selectAll() {
369
- await operate({ type: "select-all" });
370
- },
371
- async copy() {
372
- return (await operate({ type: "copy" })).text ?? "";
373
- },
374
- async goToCell(address) {
375
- await operate({
376
- type: "cell",
377
- address
378
- });
379
- },
380
- async setPart(part) {
381
- await operate({
382
- type: "part",
383
- part
384
- });
385
- },
386
- async setViewport(rectangle, scale) {
387
- await operate({
388
- type: "viewport",
389
- rectangle,
390
- scale
437
+ };
438
+ current = record;
439
+ async function operate(operation) {
440
+ if (record.closed) throw new BrowserRenderError("disposed", "Office document is closed.");
441
+ const response = await worker.request({
442
+ type: "office-operation",
443
+ operation
391
444
  });
392
- },
393
- setLayout(request) {
394
- const waiter = Promise.withResolvers();
395
- pendingLayout = {
396
- request,
397
- waiters: [...pendingLayout?.waiters ?? [], waiter]
398
- };
399
- if (!layoutRunning) applyLayouts();
400
- return waiter.promise;
401
- },
402
- async renderTile(request, tileSignal) {
403
- const response = await connection.request({
404
- type: "office-tile",
405
- request
406
- }, tileSignal);
407
- if (response.type !== "tile") throw new BrowserRenderError("render-failed", "LibreOffice returned an unexpected tile response.");
408
- return response.tile;
409
- },
410
- dispose() {
411
- listeners.clear();
412
- return connection.dispose();
445
+ if (response.type !== "office-result") throw new BrowserRenderError("render-failed", "LibreOffice returned an unexpected reading response.");
446
+ return response;
447
+ }
448
+ let layoutRunning = false;
449
+ let pendingLayout;
450
+ async function applyLayouts() {
451
+ layoutRunning = true;
452
+ while (pendingLayout) {
453
+ const next = pendingLayout;
454
+ pendingLayout = void 0;
455
+ try {
456
+ const response = await operate({
457
+ type: "layout",
458
+ request: next.request
459
+ });
460
+ if (!response.layout) throw new BrowserRenderError("render-failed", "LibreOffice returned no layout result.");
461
+ for (const waiter of next.waiters) waiter.resolve(response.layout);
462
+ } catch (error) {
463
+ for (const waiter of next.waiters) waiter.reject(error);
464
+ }
465
+ }
466
+ layoutRunning = false;
413
467
  }
468
+ const close = async () => {
469
+ if (record.closed) return;
470
+ record.closed = true;
471
+ record.listeners.clear();
472
+ current = void 0;
473
+ await worker.closeDocument();
474
+ };
475
+ let disposal;
476
+ return {
477
+ get state() {
478
+ return reading;
479
+ },
480
+ subscribe(listener) {
481
+ if (record.closed) return () => {};
482
+ record.listeners.add(listener);
483
+ return () => {
484
+ record.listeners.delete(listener);
485
+ };
486
+ },
487
+ async pointer(event) {
488
+ await operate({
489
+ type: "pointer",
490
+ event
491
+ });
492
+ },
493
+ async navigate(event) {
494
+ await operate({
495
+ type: "navigate",
496
+ event
497
+ });
498
+ },
499
+ async selectAll() {
500
+ await operate({ type: "select-all" });
501
+ },
502
+ async copy() {
503
+ return (await operate({ type: "copy" })).text ?? "";
504
+ },
505
+ async goToCell(address) {
506
+ await operate({
507
+ type: "cell",
508
+ address
509
+ });
510
+ },
511
+ async setPart(part) {
512
+ await operate({
513
+ type: "part",
514
+ part
515
+ });
516
+ },
517
+ async setViewport(rectangle, scale) {
518
+ await operate({
519
+ type: "viewport",
520
+ rectangle,
521
+ scale
522
+ });
523
+ },
524
+ setLayout(request) {
525
+ const waiter = Promise.withResolvers();
526
+ pendingLayout = {
527
+ request,
528
+ waiters: [...pendingLayout?.waiters ?? [], waiter]
529
+ };
530
+ if (!layoutRunning) applyLayouts();
531
+ return waiter.promise;
532
+ },
533
+ async renderTile(request, tileSignal) {
534
+ if (record.closed) throw new BrowserRenderError("disposed", "Office document is closed.");
535
+ const response = await worker.request({
536
+ type: "office-tile",
537
+ request
538
+ }, tileSignal);
539
+ if (response.type !== "tile") throw new BrowserRenderError("render-failed", "LibreOffice returned an unexpected tile response.");
540
+ return response.tile;
541
+ },
542
+ async captureReadingState() {
543
+ if (record.closed) throw new BrowserRenderError("disposed", "Office document is closed.");
544
+ const response = await worker.request({ type: "reading-state" });
545
+ if (response.type !== "reading-state") throw new BrowserRenderError("render-failed", "LibreOffice returned an unexpected reading state.");
546
+ return response.state;
547
+ },
548
+ close,
549
+ dispose() {
550
+ return disposal ??= close().then(disposeRuntime);
551
+ }
552
+ };
553
+ };
554
+ const disposeRuntime = async () => {
555
+ if (disposed) return;
556
+ disposed = true;
557
+ current?.listeners.clear();
558
+ if (current && !current.closed) current.closed = true;
559
+ await worker.dispose();
560
+ };
561
+ return {
562
+ open,
563
+ dispose: disposeRuntime
414
564
  };
415
565
  }
566
+ /**
567
+ * Open one read-only Office document in its own engine; the runtime ends with the document.
568
+ * @param options - Source bytes, engine resources and Host fonts.
569
+ * @param signal - Document lifetime; abort closes its Worker and pthreads.
570
+ * @returns Immutable reading state and disposal.
571
+ */
572
+ async function openOfficeDocument(options, signal) {
573
+ const { data, extension, resolveFonts, onMissingFonts, ...runtime } = options;
574
+ const office = await openOfficeRuntime(runtime, signal);
575
+ try {
576
+ return await office.open({
577
+ data,
578
+ extension,
579
+ resolveFonts,
580
+ ...onMissingFonts === void 0 ? {} : { onMissingFonts }
581
+ }, signal);
582
+ } catch (error) {
583
+ await office.dispose();
584
+ throw error;
585
+ }
586
+ }
416
587
  //#endregion
417
588
  //#region lib/types/index.js
418
589
  /** Browser Office preview and retained reading entry points. */
@@ -452,4 +623,4 @@ async function openDocument(options, signal) {
452
623
  };
453
624
  }
454
625
  //#endregion
455
- export { BrowserRenderError, openDocument, openOfficeDocument };
626
+ export { BrowserRenderError, openDocument, openOfficeDocument, openOfficeRuntime, prepareOfficeBrowser };