@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
@@ -2457,14 +2457,47 @@ ${XMLNS_NAMESPACE}.`);
2457
2457
  bytes: new Uint8Array(channel, 8)
2458
2458
  };
2459
2459
  }
2460
+ /** @returns Empty runtime-owned font state shared by successive documents. */
2461
+ function createEngineFontCache() {
2462
+ return {
2463
+ installed: /* @__PURE__ */ new Map(),
2464
+ aliases: /* @__PURE__ */ new Map(),
2465
+ loadedBytes: 0
2466
+ };
2467
+ }
2468
+ const SCRIPT_GROUPS = [
2469
+ ["arabic", /\p{Script_Extensions=Arabic}/u],
2470
+ ["cyrillic", /\p{Script_Extensions=Cyrillic}/u],
2471
+ ["devanagari", /\p{Script_Extensions=Devanagari}/u],
2472
+ ["greek", /\p{Script_Extensions=Greek}/u],
2473
+ ["han", /\p{Script_Extensions=Han}/u],
2474
+ ["hangul", /\p{Script_Extensions=Hangul}/u],
2475
+ ["hebrew", /\p{Script_Extensions=Hebrew}/u],
2476
+ ["hiragana", /\p{Script_Extensions=Hiragana}/u],
2477
+ ["katakana", /\p{Script_Extensions=Katakana}/u],
2478
+ ["latin", /\p{Script_Extensions=Latin}/u],
2479
+ ["thai", /\p{Script_Extensions=Thai}/u],
2480
+ ["common", /[\p{Script=Common}\p{Script=Inherited}]/u]
2481
+ ];
2482
+ function scriptGroup(point) {
2483
+ const character = String.fromCodePoint(point);
2484
+ return SCRIPT_GROUPS.find(([, pattern]) => pattern.test(character))?.[0] ?? `other-${point >>> 8}`;
2485
+ }
2460
2486
  /** The synchronous reader installs immutable font assets before returning their MEMFS paths and aliases. */
2461
- function createFontReader(channel, timeoutMs, maxLoadedFontBytes, declaredFamilies, request, next, install, missing) {
2487
+ function createFontReader(channel, timeoutMs, maxLoadedFontBytes, declaredFamilies, request, next, install, missing, documentCodePoints = [], cache = createEngineFontCache()) {
2462
2488
  const { control, bytes } = fontViews(channel);
2463
- const installed = /* @__PURE__ */ new Map();
2464
- const aliases = /* @__PURE__ */ new Map();
2489
+ const { installed, aliases } = cache;
2465
2490
  const requests = /* @__PURE__ */ new Map();
2491
+ const coverage = /* @__PURE__ */ new Map();
2492
+ const expanded = /* @__PURE__ */ new Map();
2493
+ const documentGroups = /* @__PURE__ */ new Map();
2494
+ for (const point of [...new Set(documentCodePoints)].sort((left, right) => left - right)) {
2495
+ const group = scriptGroup(point);
2496
+ const points = documentGroups.get(group);
2497
+ if (points) points.push(point);
2498
+ else documentGroups.set(group, [point]);
2499
+ }
2466
2500
  const families = /* @__PURE__ */ new Set();
2467
- let loadedBytes = 0;
2468
2501
  function read() {
2469
2502
  const started = performance.now();
2470
2503
  while (Atomics.load(control, 0) === 0) {
@@ -2486,14 +2519,30 @@ ${XMLNS_NAMESPACE}.`);
2486
2519
  }
2487
2520
  return (attributes) => {
2488
2521
  const canonical = aliases.get(normalize(attributes.family))?.family;
2522
+ const codePoints = [...new Set(attributes.codePoints)].sort((left, right) => left - right);
2489
2523
  const original = {
2490
2524
  ...attributes,
2525
+ codePoints,
2491
2526
  ...canonical === void 0 ? {} : { family: canonical }
2492
2527
  };
2493
2528
  const key = JSON.stringify(original);
2494
2529
  const cached = requests.get(key);
2495
2530
  if (cached) return cached;
2496
- request(original, [...installed].map(([id, font]) => ({
2531
+ const { codePoints: _points, ...base } = original;
2532
+ const coverageKey = JSON.stringify(base);
2533
+ const covered = coverage.get(coverageKey);
2534
+ if (codePoints.length > 0 && covered && (covered.complete || codePoints.every((point) => covered.points.has(point)))) {
2535
+ requests.set(key, covered.faces);
2536
+ return covered.faces;
2537
+ }
2538
+ const groups = new Set(codePoints.map(scriptGroup));
2539
+ const expandedGroups = expanded.get(coverageKey);
2540
+ const newGroups = original.mode === "full" ? [] : [...groups].filter((group) => !expandedGroups?.has(group));
2541
+ const requestedPoints = newGroups.length === 0 ? codePoints : [.../* @__PURE__ */ new Set([...codePoints, ...newGroups.flatMap((group) => documentGroups.get(group) ?? [])])].sort((left, right) => left - right);
2542
+ request({
2543
+ ...original,
2544
+ codePoints: requestedPoints
2545
+ }, [...installed].map(([id, font]) => ({
2497
2546
  id,
2498
2547
  bytes: font.bytes,
2499
2548
  ...font.format ? { format: font.format } : {}
@@ -2522,7 +2571,7 @@ ${XMLNS_NAMESPACE}.`);
2522
2571
  const alias = normalize(font.alias);
2523
2572
  const previousAlias = aliases.get(alias);
2524
2573
  if (previousAlias && (previousAlias.family !== font.family || font.format === void 0 && previousAlias.id !== font.id)) throw new BrowserRenderError("font-unavailable", "Font alias identifies conflicting subsets.");
2525
- if (!prior && loadedBytes + font.bytes > maxLoadedFontBytes) throw new BrowserRenderError("font-limit", "Imported fonts exceed maxLoadedFontBytes.");
2574
+ if (!prior && cache.loadedBytes + font.bytes > maxLoadedFontBytes) throw new BrowserRenderError("font-limit", "Imported fonts exceed maxLoadedFontBytes.");
2526
2575
  const buffer = prior ? void 0 : new Uint8Array(font.bytes);
2527
2576
  let received = 0;
2528
2577
  while (!font.reference && received < font.bytes) {
@@ -2542,7 +2591,7 @@ ${XMLNS_NAMESPACE}.`);
2542
2591
  bytes: buffer.length,
2543
2592
  format: font.format
2544
2593
  });
2545
- loadedBytes += buffer.length;
2594
+ cache.loadedBytes += buffer.length;
2546
2595
  }
2547
2596
  aliases.set(alias, {
2548
2597
  id: font.id,
@@ -2557,10 +2606,36 @@ ${XMLNS_NAMESPACE}.`);
2557
2606
  missing([...families]);
2558
2607
  }
2559
2608
  requests.set(key, faces);
2609
+ if (newGroups.length > 0) expanded.set(coverageKey, /* @__PURE__ */ new Set([...expandedGroups ?? [], ...newGroups]));
2610
+ if (requestedPoints.length > 0) {
2611
+ const group = {
2612
+ points: new Set(covered?.points),
2613
+ faces: [...covered?.faces ?? []],
2614
+ complete: covered?.complete ?? false
2615
+ };
2616
+ for (const point of requestedPoints) group.points.add(point);
2617
+ for (const face of faces) if (!group.faces.some((existing) => existing.path === face.path && existing.family === face.family)) group.faces.push(face);
2618
+ group.complete ||= header.fonts.every((font) => font.format !== void 0);
2619
+ coverage.set(coverageKey, group);
2620
+ }
2560
2621
  return faces;
2561
2622
  };
2562
2623
  }
2563
2624
  //#endregion
2625
+ //#region lib/types/preparation.js
2626
+ /** Return the compiled module after validating the Worker-bound asset identity. */
2627
+ function preparedBrowserModule(prepared, assets) {
2628
+ const record = prepared;
2629
+ if (record.wasmUrl !== assets.wasmUrl || !(record.module instanceof WebAssembly.Module)) throw new TypeError("The prepared browser engine does not match the requested WASM asset.");
2630
+ return record.module;
2631
+ }
2632
+ /** Instantiate precompiled code through Emscripten's synchronous override. */
2633
+ function instantiatePreparedModule(module, imports, receive) {
2634
+ const instance = new WebAssembly.Instance(module, imports);
2635
+ receive(instance, module);
2636
+ return instance.exports;
2637
+ }
2638
+ //#endregion
2564
2639
  //#region ../entry/lib/sheet-geometry.js
2565
2640
  const MAX_COLUMN = 16383;
2566
2641
  const MAX_ROW = 1048575;
@@ -2757,7 +2832,8 @@ ${XMLNS_NAMESPACE}.`);
2757
2832
  geometryDirty = false;
2758
2833
  stopped = false;
2759
2834
  layoutWidth = 0;
2760
- viewport = "";
2835
+ viewportKey = "";
2836
+ viewportState = null;
2761
2837
  captureView;
2762
2838
  readingView;
2763
2839
  commandResult;
@@ -2959,7 +3035,8 @@ ${XMLNS_NAMESPACE}.`);
2959
3035
  ...this.state,
2960
3036
  part
2961
3037
  };
2962
- this.viewport = "";
3038
+ this.viewportKey = "";
3039
+ this.viewportState = null;
2963
3040
  this.geometryDirty = true;
2964
3041
  changed = true;
2965
3042
  }
@@ -3081,7 +3158,8 @@ ${XMLNS_NAMESPACE}.`);
3081
3158
  const part = integer(operation.part, this.state.parts.length - 1);
3082
3159
  if (part === this.state.part) break;
3083
3160
  this.invoke("part", [part]);
3084
- this.viewport = "";
3161
+ this.viewportKey = "";
3162
+ this.viewportState = null;
3085
3163
  this.state = {
3086
3164
  ...this.state,
3087
3165
  part,
@@ -3121,9 +3199,13 @@ ${XMLNS_NAMESPACE}.`);
3121
3199
  twips(height)
3122
3200
  ];
3123
3201
  const key = args.join(",");
3124
- if (key !== this.viewport) {
3202
+ if (key !== this.viewportKey) {
3125
3203
  this.invoke("viewport", args);
3126
- this.viewport = key;
3204
+ this.viewportKey = key;
3205
+ this.viewportState = {
3206
+ rectangle: { ...operation.rectangle },
3207
+ scale: operation.scale
3208
+ };
3127
3209
  }
3128
3210
  break;
3129
3211
  }
@@ -3136,7 +3218,8 @@ ${XMLNS_NAMESPACE}.`);
3136
3218
  if (request.mode === this.state.layout && width === this.layoutWidth) return { layout: { changed: false } };
3137
3219
  const result = this.configure(request);
3138
3220
  this.layoutWidth = width;
3139
- this.viewport = "";
3221
+ this.viewportKey = "";
3222
+ this.viewportState = null;
3140
3223
  this.state = {
3141
3224
  ...this.state,
3142
3225
  layout: request.mode,
@@ -3212,6 +3295,98 @@ ${XMLNS_NAMESPACE}.`);
3212
3295
  this.commandResult = void 0;
3213
3296
  }
3214
3297
  }
3298
+ /** Read the part and selection the next open of these bytes must restore. */
3299
+ capture() {
3300
+ this.requireOpen();
3301
+ if (this.readingView !== void 0) this.invoke("set_view", [this.readingView]);
3302
+ this.flush();
3303
+ const raw = this.text("dsh_lok_document_capture_reading_selection", [this.document]);
3304
+ let text = null;
3305
+ let cell = null;
3306
+ let object = null;
3307
+ if (raw !== null && raw !== "") {
3308
+ const selection = JSON.parse(raw);
3309
+ if (selection.kind === "text") text = {
3310
+ pointNode: integer(selection.pointNode),
3311
+ pointOffset: integer(selection.pointOffset),
3312
+ markNode: integer(selection.markNode),
3313
+ markOffset: integer(selection.markOffset)
3314
+ };
3315
+ else if (selection.kind === "cell" && typeof selection.range === "string") {
3316
+ parseCellRange(selection.range);
3317
+ cell = selection.range;
3318
+ } else if (selection.kind === "object" && typeof selection.paths === "string") {
3319
+ const paths = selection.paths.split(",");
3320
+ if (paths.some((path) => path === "" || path.split("/").some((value) => value === ""))) throw new BrowserRenderError("render-failed", "LibreOffice returned an invalid object selection.");
3321
+ object = paths.map((path) => path.split("/").map((value) => integer(Number(value))));
3322
+ }
3323
+ }
3324
+ const layout = this.state.layout === "continuous" ? {
3325
+ mode: "continuous",
3326
+ width: this.layoutWidth / 15
3327
+ } : { mode: "paginated" };
3328
+ return {
3329
+ version: 1,
3330
+ documentType: this.state.documentType,
3331
+ part: this.state.part,
3332
+ layout,
3333
+ viewport: this.viewportState,
3334
+ text,
3335
+ cell,
3336
+ object
3337
+ };
3338
+ }
3339
+ /**
3340
+ * Apply a reading position captured from the same bytes.
3341
+ * @param state - Part and selection captured before this document closed.
3342
+ */
3343
+ async restore(state) {
3344
+ this.requireOpen();
3345
+ if (state.version !== 1 || state.documentType !== this.state.documentType) throw new BrowserRenderError("render-failed", "The captured reading state belongs to another document.");
3346
+ if (this.state.documentType === "text") {
3347
+ if (state.layout.mode === "continuous") {
3348
+ const anchor = state.viewport === null ? void 0 : {
3349
+ x: state.viewport.rectangle.x,
3350
+ y: state.viewport.rectangle.y
3351
+ };
3352
+ await this.operation({
3353
+ type: "layout",
3354
+ request: {
3355
+ mode: "continuous",
3356
+ width: state.layout.width,
3357
+ ...anchor === void 0 ? {} : { anchor }
3358
+ }
3359
+ });
3360
+ } else if (state.layout.mode !== "paginated") throw new BrowserRenderError("render-failed", "The captured reading layout is invalid.");
3361
+ } else if (state.layout.mode !== "paginated") throw new BrowserRenderError("render-failed", "The captured reading layout belongs to a Writer document.");
3362
+ if (this.state.documentType !== "text" && state.part !== this.state.part) await this.operation({
3363
+ type: "part",
3364
+ part: state.part
3365
+ });
3366
+ if (state.text && this.state.documentType === "text") {
3367
+ const { pointNode, pointOffset, markNode, markOffset } = state.text;
3368
+ this.invoke("restore_reading_text_selection", [
3369
+ integer(pointNode),
3370
+ integer(pointOffset),
3371
+ integer(markNode),
3372
+ integer(markOffset)
3373
+ ]);
3374
+ }
3375
+ if (state.cell && this.state.documentType === "spreadsheet") await this.operation({
3376
+ type: "cell",
3377
+ address: state.cell
3378
+ });
3379
+ if (state.object && this.state.documentType === "presentation") {
3380
+ const paths = state.object.map((path) => path.map((value) => integer(value)).join("/")).join(",");
3381
+ if (!paths) throw new BrowserRenderError("render-failed", "The captured object selection is invalid.");
3382
+ this.invoke("restore_reading_object_selection", [paths]);
3383
+ }
3384
+ if (state.viewport !== null) await this.operation({
3385
+ type: "viewport",
3386
+ ...state.viewport
3387
+ });
3388
+ this.pump();
3389
+ }
3215
3390
  /** Direct tiles preserve the active view, navigation state and selection. */
3216
3391
  render(request) {
3217
3392
  this.requireOpen();
@@ -3239,8 +3414,19 @@ ${XMLNS_NAMESPACE}.`);
3239
3414
  };
3240
3415
  //#endregion
3241
3416
  //#region lib/types/worker.js
3242
- /** Classic Worker entry: serializes one LibreOffice instance and owns its pthreads. */
3417
+ /** Classic Worker entry: serializes one LibreOffice instance, its documents and its pthreads. */
3243
3418
  const scope = globalThis;
3419
+ /** Host font request that installs a fallback face before LibreOffice resolves any family. */
3420
+ const initialFont = {
3421
+ family: "sans-serif",
3422
+ style: "",
3423
+ weight: 5,
3424
+ italic: 0,
3425
+ width: 5,
3426
+ pitch: 0,
3427
+ language: "",
3428
+ codePoints: []
3429
+ };
3244
3430
  let module;
3245
3431
  let office = 0;
3246
3432
  let document = 0;
@@ -3251,6 +3437,12 @@ ${XMLNS_NAMESPACE}.`);
3251
3437
  let fontFailure;
3252
3438
  let serial = Promise.resolve();
3253
3439
  const lifetime = new AbortController();
3440
+ let runtime;
3441
+ let resolveFonts;
3442
+ /** MEMFS path of the open document; removed when its model is released. */
3443
+ let source;
3444
+ /** Font identities and files retained until this runtime is destroyed. */
3445
+ const fontCache = createEngineFontCache();
3254
3446
  function send(message, transfer = []) {
3255
3447
  scope.postMessage(message, transfer);
3256
3448
  }
@@ -3268,33 +3460,31 @@ ${XMLNS_NAMESPACE}.`);
3268
3460
  call("free", [pointer]);
3269
3461
  }
3270
3462
  }
3271
- async function open(options, channel, reading = false) {
3463
+ /**
3464
+ * Bind one document's declared families to the runtime's font channel.
3465
+ * The first synchronous read of a request consumes the Host response that was
3466
+ * requested before the engine's filesystem was configured.
3467
+ */
3468
+ function installFonts(loaded, options, families, codePoints, consumeInitial) {
3469
+ loaded.FS.writeFile("/dsh/fonts.conf", new TextEncoder().encode(memoryFontConfig(options.fontFallbacks, families.values())));
3470
+ return createFontReader(runtime.channel, options.timeoutMs, options.maxLoadedFontBytes, families, (request, known) => {
3471
+ if (consumeInitial.pending) consumeInitial.pending = false;
3472
+ else send({
3473
+ type: "font",
3474
+ request,
3475
+ known
3476
+ });
3477
+ }, () => send({ type: "font-next" }), (path, bytes) => {
3478
+ loaded.FS.writeFile(path, bytes);
3479
+ }, (missing) => send({
3480
+ type: "missing-fonts",
3481
+ families: missing
3482
+ }), codePoints, fontCache);
3483
+ }
3484
+ /** Create this runtime's WASM module, filesystem configuration and office instance once. */
3485
+ async function createEngine(options, families, codePoints, consumeInitial, portableDocument) {
3272
3486
  const { assets } = options;
3273
- let metadata;
3274
- try {
3275
- metadata = options.extension === "pdf" ? {
3276
- families: /* @__PURE__ */ new Map(),
3277
- codePoints: []
3278
- } : inspectDocument(options.data, options.extension, options);
3279
- } catch (failure) {
3280
- throw new BrowserRenderError("invalid-document", failure instanceof Error ? failure.message : String(failure));
3281
- }
3282
- const initialFont = {
3283
- family: "sans-serif",
3284
- style: "",
3285
- weight: 5,
3286
- italic: 0,
3287
- width: 5,
3288
- pitch: 0,
3289
- language: "",
3290
- codePoints: []
3291
- };
3292
- let initialFontPending = options.extension !== "pdf";
3293
- if (initialFontPending) send({
3294
- type: "font",
3295
- request: initialFont,
3296
- known: []
3297
- });
3487
+ const prepared = options.preparedEngine === void 0 ? void 0 : preparedBrowserModule(options.preparedEngine, assets);
3298
3488
  const response = await fetch(assets.dataUrl, {
3299
3489
  credentials: "same-origin",
3300
3490
  signal: lifetime.signal
@@ -3302,8 +3492,7 @@ ${XMLNS_NAMESPACE}.`);
3302
3492
  if (!response.ok) throw new BrowserRenderError("unavailable", `LibreOffice data request failed: ${response.status}`);
3303
3493
  const data = await response.arrayBuffer();
3304
3494
  scope.importScripts(assets.loaderUrl);
3305
- let resolveFonts;
3306
- module = await scope.createLibreOfficeModule({
3495
+ const created = await scope.createLibreOfficeModule({
3307
3496
  noInitialRun: true,
3308
3497
  dshOnCallback(type, payload) {
3309
3498
  reader?.callback(type, payload);
@@ -3321,6 +3510,9 @@ ${XMLNS_NAMESPACE}.`);
3321
3510
  }
3322
3511
  },
3323
3512
  getPreloadedPackage: () => data,
3513
+ ...prepared === void 0 ? {} : { instantiateWasm(imports, receive) {
3514
+ return instantiatePreparedModule(prepared, imports, receive);
3515
+ } },
3324
3516
  dshResolveSystemFontFaces(request) {
3325
3517
  if (!resolveFonts) throw new BrowserRenderError("font-unavailable", "LibreOffice requested fonts before MEMFS initialization.");
3326
3518
  try {
@@ -3337,30 +3529,19 @@ ${XMLNS_NAMESPACE}.`);
3337
3529
  "/dsh-fonts",
3338
3530
  "/usr/share/fonts/dsh-pdfium"
3339
3531
  ]) loaded.FS.mkdirTree(path);
3340
- loaded.FS.writeFile("/dsh/fonts.conf", new TextEncoder().encode(memoryFontConfig(options.fontFallbacks, metadata.families.values())));
3532
+ resolveFonts = installFonts(loaded, options, families, codePoints, consumeInitial);
3533
+ if (portableDocument) for (const family of new Set(options.fontFallbacks.flat())) resolveFonts({
3534
+ ...initialFont,
3535
+ family,
3536
+ mode: "full"
3537
+ });
3538
+ else resolveFonts(initialFont);
3341
3539
  Object.assign(loaded.ENV, {
3342
3540
  HOME: "/dsh/profile",
3343
3541
  TMPDIR: "/tmp",
3344
3542
  FONTCONFIG_FILE: "/dsh/fonts.conf",
3345
3543
  LOK_HOST_ALLOWLIST: "^$"
3346
3544
  });
3347
- resolveFonts = createFontReader(channel, options.timeoutMs, options.maxLoadedFontBytes, metadata.families, (request, known) => {
3348
- if (initialFontPending) initialFontPending = false;
3349
- else send({
3350
- type: "font",
3351
- request,
3352
- known
3353
- });
3354
- }, () => send({ type: "font-next" }), (path, bytes) => loaded.FS.writeFile(path, bytes), (families) => send({
3355
- type: "missing-fonts",
3356
- families
3357
- }));
3358
- if (options.extension === "pdf") for (const family of new Set(options.fontFallbacks.flat())) resolveFonts({
3359
- ...initialFont,
3360
- family,
3361
- mode: "full"
3362
- });
3363
- else resolveFonts(initialFont);
3364
3545
  }],
3365
3546
  onAbort() {
3366
3547
  fatal = true;
@@ -3368,12 +3549,42 @@ ${XMLNS_NAMESPACE}.`);
3368
3549
  print() {},
3369
3550
  printErr() {}
3370
3551
  });
3371
- if (options.extension === "pdf") {
3372
- const pointer = call("malloc", [options.data.byteLength]);
3552
+ module = created;
3553
+ office = created.ccall("dsh_lok_initialize", "number", ["string", "string"], [assets.programDirectory, "file:///dsh/profile"]);
3554
+ if (!office) throw error("unavailable");
3555
+ }
3556
+ /** Load one document into the already initialized engine. */
3557
+ async function openDocument(options) {
3558
+ if (!runtime) throw new BrowserRenderError("disposed", "LibreOffice Worker has not been started.");
3559
+ const engine = runtime.options;
3560
+ const reading = options.extension !== "pdf";
3561
+ let metadata;
3562
+ try {
3563
+ metadata = reading ? inspectDocument(options.data, options.extension, engine) : {
3564
+ families: /* @__PURE__ */ new Map(),
3565
+ codePoints: []
3566
+ };
3567
+ } catch (failure) {
3568
+ throw new BrowserRenderError("invalid-document", failure instanceof Error ? failure.message : String(failure));
3569
+ }
3570
+ if (reading) send({
3571
+ type: "font",
3572
+ request: initialFont,
3573
+ known: []
3574
+ });
3575
+ const consumeInitial = { pending: reading };
3576
+ if (!module) await createEngine(engine, metadata.families, metadata.codePoints, consumeInitial, !reading);
3577
+ else {
3578
+ resolveFonts = installFonts(module, engine, metadata.families, metadata.codePoints, consumeInitial);
3579
+ if (reading) resolveFonts(initialFont);
3580
+ }
3581
+ const loaded = module;
3582
+ if (!reading) {
3583
+ const pointer = loaded.ccall("malloc", "number", ["number"], [options.data.byteLength]);
3373
3584
  if (!pointer) throw error("invalid-document");
3374
3585
  try {
3375
- new Uint8Array(module.HEAPU32.buffer, pointer, options.data.byteLength).set(options.data);
3376
- pdf = module.ccall("dsh_pdf_open", "number", [
3586
+ new Uint8Array(loaded.HEAPU32.buffer, pointer, options.data.byteLength).set(options.data);
3587
+ pdf = loaded.ccall("dsh_pdf_open", "number", [
3377
3588
  "number",
3378
3589
  "number",
3379
3590
  "string"
@@ -3386,14 +3597,13 @@ ${XMLNS_NAMESPACE}.`);
3386
3597
  call("free", [pointer]);
3387
3598
  }
3388
3599
  if (!pdf) throw error("invalid-document");
3389
- pages = pdfPages(module, pdf, () => error("invalid-document"));
3600
+ pages = pdfPages(loaded, pdf, () => error("invalid-document"));
3390
3601
  return;
3391
3602
  }
3392
3603
  const input = `/dsh/document.${options.extension}`;
3393
- module.FS.writeFile(input, options.data);
3394
- office = module.ccall("dsh_lok_initialize", "number", ["string", "string"], [assets.programDirectory, "file:///dsh/profile"]);
3395
- if (!office) throw error("invalid-document");
3396
- document = module.ccall("dsh_lok_document_load", "number", [
3604
+ loaded.FS.writeFile(input, options.data);
3605
+ source = input;
3606
+ document = loaded.ccall("dsh_lok_document_load", "number", [
3397
3607
  "number",
3398
3608
  "string",
3399
3609
  "string"
@@ -3405,38 +3615,31 @@ ${XMLNS_NAMESPACE}.`);
3405
3615
  if (!document || !call("dsh_lok_document_initialize_rendering", [document])) throw error("invalid-document");
3406
3616
  const type = call("dsh_lok_document_type", [document]);
3407
3617
  if (type !== (options.extension === "docx" || options.extension === "doc" ? 0 : options.extension === "xlsx" || options.extension === "xls" ? 1 : 2)) throw new BrowserRenderError("invalid-document", "The document type does not match its extension.");
3408
- if (reading) {
3409
- reader = new OfficeEngine(module, document, options.extension, (event) => send({
3618
+ const engineReader = reader = new OfficeEngine(loaded, document, options.extension, (event) => send({
3619
+ type: "office-event",
3620
+ event
3621
+ }), (failure) => {
3622
+ fatal ||= failure instanceof WebAssembly.RuntimeError;
3623
+ send({
3410
3624
  type: "office-event",
3411
- event
3412
- }), (failure) => {
3413
- fatal ||= failure instanceof WebAssembly.RuntimeError;
3414
- send({
3415
- type: "office-event",
3416
- event: {
3417
- type: "error",
3418
- code: "render-failed",
3419
- message: failure instanceof Error ? failure.message : String(failure)
3420
- }
3421
- });
3625
+ event: {
3626
+ type: "error",
3627
+ code: "render-failed",
3628
+ message: failure instanceof Error ? failure.message : String(failure)
3629
+ }
3422
3630
  });
3423
- await reader.start();
3424
- pages = reader.state.parts.map((part, index) => ({
3425
- ...part,
3426
- x: 0,
3427
- y: 0,
3428
- part: type === 0 ? -1 : index
3429
- }));
3430
- return;
3431
- }
3432
- throw new BrowserRenderError("invalid-document", "Office documents require a retained session.");
3433
- }
3434
- function render(request) {
3435
- if (fatal) throw new BrowserRenderError("render-failed", "LibreOffice Worker has aborted.");
3436
- if (!pdf || !module) throw new BrowserRenderError("disposed", "The document is closed.");
3437
- return renderRegion(module, pdf, request, pages, () => error("render-failed"), true);
3631
+ });
3632
+ await engineReader.start();
3633
+ if (options.restore) await engineReader.restore(options.restore);
3634
+ pages = engineReader.state.parts.map((part, index) => ({
3635
+ ...part,
3636
+ x: 0,
3637
+ y: 0,
3638
+ part: type === 0 ? -1 : index
3639
+ }));
3438
3640
  }
3439
- function dispose() {
3641
+ /** Release the open document's model, MEMFS bytes and installed fonts; keep the engine. */
3642
+ function closeDocument() {
3440
3643
  reader?.stop();
3441
3644
  reader = void 0;
3442
3645
  try {
@@ -3451,19 +3654,44 @@ ${XMLNS_NAMESPACE}.`);
3451
3654
  document = 0;
3452
3655
  if (!call("dsh_lok_document_destroy", [value])) throw error("render-failed");
3453
3656
  }
3454
- if (office) {
3455
- const value = office;
3456
- office = 0;
3457
- if (!call("dsh_lok_destroy", [value])) throw error("render-failed");
3458
- }
3657
+ if (source !== void 0) unlink(source);
3459
3658
  }
3460
3659
  } finally {
3461
- module?.PThread.terminateAllThreads();
3462
- module = void 0;
3660
+ resolveFonts = void 0;
3661
+ pages = [];
3662
+ source = void 0;
3463
3663
  document = 0;
3464
3664
  pdf = 0;
3665
+ }
3666
+ }
3667
+ /** Remove one MEMFS path; a missing file means the engine already released it. */
3668
+ function unlink(path) {
3669
+ try {
3670
+ module?.FS.unlink(path);
3671
+ } catch (failure) {
3672
+ if (!(failure instanceof Error) || !/no such file|does not exist/i.test(failure.message)) throw failure;
3673
+ }
3674
+ }
3675
+ function render(request) {
3676
+ if (fatal) throw new BrowserRenderError("render-failed", "LibreOffice Worker has aborted.");
3677
+ if (!pdf || !module) throw new BrowserRenderError("disposed", "The document is closed.");
3678
+ return renderRegion(module, pdf, request, pages, () => error("render-failed"), true);
3679
+ }
3680
+ /** Destroy the office instance and every pthread after the documents are closed. */
3681
+ function dispose() {
3682
+ closeDocument();
3683
+ try {
3684
+ if (module && !fatal && office) {
3685
+ const value = office;
3686
+ office = 0;
3687
+ if (!call("dsh_lok_destroy", [value])) throw error("render-failed");
3688
+ }
3689
+ } finally {
3690
+ module?.PThread.terminateAllThreads();
3691
+ module = void 0;
3465
3692
  office = 0;
3466
3693
  pages = [];
3694
+ runtime = void 0;
3467
3695
  }
3468
3696
  }
3469
3697
  scope.onmessage = (event) => {
@@ -3475,8 +3703,19 @@ ${XMLNS_NAMESPACE}.`);
3475
3703
  serial = serial.then(async () => {
3476
3704
  try {
3477
3705
  switch (message.type) {
3706
+ case "start":
3707
+ runtime = {
3708
+ options: message.options,
3709
+ channel: message.channel
3710
+ };
3711
+ send({
3712
+ type: "started",
3713
+ id: message.id
3714
+ });
3715
+ break;
3478
3716
  case "open":
3479
- await open(message.options, message.channel, message.office);
3717
+ if (document || pdf) closeDocument();
3718
+ await openDocument(message.options);
3480
3719
  send({
3481
3720
  type: "opened",
3482
3721
  id: message.id,
@@ -3487,6 +3726,21 @@ ${XMLNS_NAMESPACE}.`);
3487
3726
  ...reader ? { office: reader.state } : {}
3488
3727
  });
3489
3728
  break;
3729
+ case "close-document":
3730
+ closeDocument();
3731
+ send({
3732
+ type: "closed-document",
3733
+ id: message.id
3734
+ });
3735
+ break;
3736
+ case "reading-state":
3737
+ if (!reader) throw new BrowserRenderError("disposed", "Office document is closed.");
3738
+ send({
3739
+ type: "reading-state",
3740
+ id: message.id,
3741
+ state: reader.capture()
3742
+ });
3743
+ break;
3490
3744
  case "tile": {
3491
3745
  const tile = render(message.request);
3492
3746
  send({
@@ -47,7 +47,7 @@ async function readEngine(packageFile) {
47
47
  const root = dirname(packageFile);
48
48
  const [pkg, manifest] = await Promise.all([readFile(packageFile, "utf8").then((text) => JSON.parse(text)), readFile(resolve(root, "prebuilds.json"), "utf8").then((text) => JSON.parse(text))]);
49
49
  const engine = manifest.engine;
50
- if (pkg.name !== `${ENGINE_PREFIX}-wasm` || pkg.version !== "0.0.2-rc6" || manifest.version !== pkg.version || manifest.schemaVersion !== 1 || manifest.status !== "built" || engine === void 0 || engine.kind !== "wasm" || manifest.platform !== "wasm") throw new Error("Installed LibreOfficeKit wasm package has an incompatible or incomplete manifest.");
50
+ if (pkg.name !== `${ENGINE_PREFIX}-wasm` || pkg.version !== "0.0.2-rc9" || manifest.version !== pkg.version || manifest.schemaVersion !== 1 || manifest.status !== "built" || engine === void 0 || engine.kind !== "wasm" || manifest.platform !== "wasm") throw new Error("Installed LibreOfficeKit wasm package has an incompatible or incomplete manifest.");
51
51
  if (engine.glibcMinimum !== void 0) throw new Error("Installed LibreOfficeKit engine has an invalid glibcMinimum.");
52
52
  return {
53
53
  backend: "wasm",