docxodus 12.4.0 → 12.5.0

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 (119) hide show
  1. package/README.md +101 -0
  2. package/dist/core.d.ts +924 -0
  3. package/dist/core.d.ts.map +1 -0
  4. package/dist/core.js +1915 -0
  5. package/dist/core.js.map +1 -0
  6. package/dist/docxodus.worker.js +280 -7
  7. package/dist/docxodus.worker.js.map +1 -1
  8. package/dist/editor-reconcile.d.ts +5 -0
  9. package/dist/editor-reconcile.d.ts.map +1 -1
  10. package/dist/editor-reconcile.js.map +1 -1
  11. package/dist/editor.bundle.js +157 -15
  12. package/dist/editor.d.ts +44 -0
  13. package/dist/editor.d.ts.map +1 -1
  14. package/dist/editor.js +209 -22
  15. package/dist/editor.js.map +1 -1
  16. package/dist/embed.bundle.js +12565 -12222
  17. package/dist/embed.iife.js +12532 -12189
  18. package/dist/export-assets.json +48 -48
  19. package/dist/export-browser.bundle.js +101 -4
  20. package/dist/external-annotation-wire.d.ts +19 -0
  21. package/dist/external-annotation-wire.d.ts.map +1 -0
  22. package/dist/external-annotation-wire.js +139 -0
  23. package/dist/external-annotation-wire.js.map +1 -0
  24. package/dist/index.d.ts +2 -922
  25. package/dist/index.d.ts.map +1 -1
  26. package/dist/index.js +2 -2093
  27. package/dist/index.js.map +1 -1
  28. package/dist/session.bundle.js +258 -7
  29. package/dist/session.d.ts +61 -12
  30. package/dist/session.d.ts.map +1 -1
  31. package/dist/session.js +234 -7
  32. package/dist/session.js.map +1 -1
  33. package/dist/types.d.ts +371 -4
  34. package/dist/types.d.ts.map +1 -1
  35. package/dist/types.js.map +1 -1
  36. package/dist/verification-request.d.ts +9 -0
  37. package/dist/verification-request.d.ts.map +1 -0
  38. package/dist/verification-request.js +37 -0
  39. package/dist/verification-request.js.map +1 -0
  40. package/dist/wasm/_framework/Docxodus.wasm +0 -0
  41. package/dist/wasm/_framework/Docxodus.wasm.br +0 -0
  42. package/dist/wasm/_framework/DocxodusWasm.wasm +0 -0
  43. package/dist/wasm/_framework/DocxodusWasm.wasm.br +0 -0
  44. package/dist/wasm/_framework/System.Collections.Concurrent.wasm +0 -0
  45. package/dist/wasm/_framework/System.Collections.Concurrent.wasm.br +0 -0
  46. package/dist/wasm/_framework/System.Collections.Immutable.wasm +0 -0
  47. package/dist/wasm/_framework/System.Collections.Immutable.wasm.br +0 -0
  48. package/dist/wasm/_framework/System.Collections.NonGeneric.wasm +0 -0
  49. package/dist/wasm/_framework/System.Collections.NonGeneric.wasm.br +0 -0
  50. package/dist/wasm/_framework/System.Collections.Specialized.wasm +0 -0
  51. package/dist/wasm/_framework/System.Collections.Specialized.wasm.br +0 -0
  52. package/dist/wasm/_framework/System.Collections.wasm +0 -0
  53. package/dist/wasm/_framework/System.Collections.wasm.br +0 -0
  54. package/dist/wasm/_framework/System.ComponentModel.Primitives.wasm +0 -0
  55. package/dist/wasm/_framework/System.ComponentModel.Primitives.wasm.br +0 -0
  56. package/dist/wasm/_framework/System.ComponentModel.TypeConverter.wasm +0 -0
  57. package/dist/wasm/_framework/System.ComponentModel.TypeConverter.wasm.br +0 -0
  58. package/dist/wasm/_framework/System.ComponentModel.wasm +0 -0
  59. package/dist/wasm/_framework/System.ComponentModel.wasm.br +0 -0
  60. package/dist/wasm/_framework/System.Console.wasm +0 -0
  61. package/dist/wasm/_framework/System.Console.wasm.br +0 -0
  62. package/dist/wasm/_framework/System.IO.Compression.wasm +0 -0
  63. package/dist/wasm/_framework/System.IO.Compression.wasm.br +0 -0
  64. package/dist/wasm/_framework/System.IO.Pipelines.wasm +0 -0
  65. package/dist/wasm/_framework/System.IO.Pipelines.wasm.br +0 -0
  66. package/dist/wasm/_framework/System.Linq.Expressions.wasm +0 -0
  67. package/dist/wasm/_framework/System.Linq.Expressions.wasm.br +0 -0
  68. package/dist/wasm/_framework/System.Linq.wasm +0 -0
  69. package/dist/wasm/_framework/System.Linq.wasm.br +0 -0
  70. package/dist/wasm/_framework/System.Memory.wasm +0 -0
  71. package/dist/wasm/_framework/System.Memory.wasm.br +0 -0
  72. package/dist/wasm/_framework/System.Net.Http.wasm +0 -0
  73. package/dist/wasm/_framework/System.Net.Http.wasm.br +0 -0
  74. package/dist/wasm/_framework/System.Net.Primitives.wasm +0 -0
  75. package/dist/wasm/_framework/System.Net.Primitives.wasm.br +0 -0
  76. package/dist/wasm/_framework/System.ObjectModel.wasm +0 -0
  77. package/dist/wasm/_framework/System.ObjectModel.wasm.br +0 -0
  78. package/dist/wasm/_framework/System.Private.CoreLib.wasm +0 -0
  79. package/dist/wasm/_framework/System.Private.CoreLib.wasm.br +0 -0
  80. package/dist/wasm/_framework/System.Private.Uri.wasm +0 -0
  81. package/dist/wasm/_framework/System.Private.Uri.wasm.br +0 -0
  82. package/dist/wasm/_framework/System.Private.Xml.Linq.wasm +0 -0
  83. package/dist/wasm/_framework/System.Private.Xml.Linq.wasm.br +0 -0
  84. package/dist/wasm/_framework/System.Private.Xml.wasm +0 -0
  85. package/dist/wasm/_framework/System.Private.Xml.wasm.br +0 -0
  86. package/dist/wasm/_framework/System.Runtime.InteropServices.JavaScript.wasm +0 -0
  87. package/dist/wasm/_framework/System.Runtime.InteropServices.JavaScript.wasm.br +0 -0
  88. package/dist/wasm/_framework/System.Runtime.wasm +0 -0
  89. package/dist/wasm/_framework/System.Runtime.wasm.br +0 -0
  90. package/dist/wasm/_framework/System.Security.Cryptography.wasm +0 -0
  91. package/dist/wasm/_framework/System.Security.Cryptography.wasm.br +0 -0
  92. package/dist/wasm/_framework/System.Text.Encodings.Web.wasm +0 -0
  93. package/dist/wasm/_framework/System.Text.Encodings.Web.wasm.br +0 -0
  94. package/dist/wasm/_framework/System.Text.Json.wasm +0 -0
  95. package/dist/wasm/_framework/System.Text.Json.wasm.br +0 -0
  96. package/dist/wasm/_framework/System.Text.RegularExpressions.wasm +0 -0
  97. package/dist/wasm/_framework/System.Text.RegularExpressions.wasm.br +0 -0
  98. package/dist/wasm/_framework/System.Xml.Linq.wasm +0 -0
  99. package/dist/wasm/_framework/System.Xml.Linq.wasm.br +0 -0
  100. package/dist/wasm/_framework/System.Xml.XDocument.wasm +0 -0
  101. package/dist/wasm/_framework/System.Xml.XDocument.wasm.br +0 -0
  102. package/dist/wasm/_framework/System.wasm +0 -0
  103. package/dist/wasm/_framework/System.wasm.br +0 -0
  104. package/dist/wasm/_framework/dotnet.boot.js +34 -34
  105. package/dist/wasm/_framework/dotnet.boot.js.br +0 -0
  106. package/dist/wasm/_framework/dotnet.js +1 -1
  107. package/dist/wasm/_framework/dotnet.js.br +0 -0
  108. package/dist/wasm/_framework/dotnet.native.js +3 -3
  109. package/dist/wasm/_framework/dotnet.native.js.br +0 -0
  110. package/dist/wasm/_framework/dotnet.native.wasm +0 -0
  111. package/dist/wasm/_framework/dotnet.native.wasm.br +0 -0
  112. package/dist/wasm/_framework/dotnet.runtime.js +1 -1
  113. package/dist/wasm/_framework/dotnet.runtime.js.br +0 -0
  114. package/dist/worker-proxy.bundle.js +101 -4
  115. package/dist/worker-proxy.d.ts +21 -3
  116. package/dist/worker-proxy.d.ts.map +1 -1
  117. package/dist/worker-proxy.js +57 -2
  118. package/dist/worker-proxy.js.map +1 -1
  119. package/package.json +8 -1
package/dist/core.js ADDED
@@ -0,0 +1,1915 @@
1
+ import { openDocxSession as openDocxSessionImpl } from "./session.js";
2
+ import { serializeVerificationRequest } from "./verification-request.js";
3
+ import { readExternalAnnotationSet, readExternalAnnotationValidation, readOpenContractExport, readProjectedHtml, } from "./external-annotation-wire.js";
4
+ import { DocxHistoryArchive, DocxHistoryClient, installHistoryStorageImports } from './history.js';
5
+ export * from './history.js';
6
+ export * from './history-checkpoints.js';
7
+ export * from './history-indexeddb.js';
8
+ export * from './history-controls.js';
9
+ /** Open history over host-owned storage after initialize(). No network layer is installed. */
10
+ export function openDocxHistory(storage) {
11
+ const bridge = ensureInitialized().HistoryBridge;
12
+ if (!bridge)
13
+ throw new Error('This WASM build does not include history bindings.');
14
+ return new DocxHistoryClient(bridge, storage);
15
+ }
16
+ /** Open a self-contained readonly .docxhistory file after initialize(); no storage adapter needed. */
17
+ export function openDocxHistoryArchive(bytes) {
18
+ const bridge = ensureInitialized().HistoryBridge;
19
+ if (!bridge)
20
+ throw new Error('This WASM build does not include history bindings.');
21
+ return DocxHistoryArchive.open(bridge, bytes);
22
+ }
23
+ export { DocxSession } from "./session.js";
24
+ export { PlaceholderKinds, ContextBoundary } from "./types.js";
25
+ export { DiffFormat } from "./types.js";
26
+ /**
27
+ * Open a {@link DocxSession} for surgical mutation of a DOCX. Requires
28
+ * {@link initialize} to have been called and awaited.
29
+ *
30
+ * The returned session keeps the document in WASM memory; call
31
+ * {@link DocxSession.close} when done.
32
+ */
33
+ export function openDocxSession(bytes, settings) {
34
+ const wasm = ensureInitialized();
35
+ return openDocxSessionImpl(bytes, wasm, settings);
36
+ }
37
+ /**
38
+ * Mint a complete, blank single-paragraph DOCX (Normal style, US-Letter section) as bytes —
39
+ * a "New document" seed for editors that draft from scratch. Requires {@link initialize}.
40
+ */
41
+ export function createBlankDocx() {
42
+ return ensureInitialized().DocxSessionBridge.CreateBlankDocx();
43
+ }
44
+ import { CommentRenderMode, PaginationMode, AnnotationLabelMode, RevisionType, DocxDiffRevisionGranularity, DocxDiffFormatComparison, ConflictResolution, ProjectionScopes, AnchorRenderMode, TableRenderMode, TrackedChangeMode, EmptyParagraphMode, AnchorIdRendering, ProjectionDepth, DocumentElementType, ComparisonLogLevel, ComparisonLogCodes, isInsertion, isDeletion, isMove, isFormatChange, findElementById, findElementsByType, getParagraphs, getTables, getTableColumns, targetElement, targetParagraph, targetParagraphRange, targetRun, targetTable, targetTableRow, targetTableCell, targetTableColumn, targetSearch, targetSearchInElement, } from "./types.js";
45
+ export { PaginationEngine, clearPageCitationHighlight, createUnavailablePageMap, navigateToPageCitation, paginateHtml, } from "./pagination.js";
46
+ // Page geometry is the document's own page setup (w:sectPr), read off the section wrappers
47
+ // the converter stamps in every render mode, plus the fit-to-width zoom a view applies to it.
48
+ export { DEFAULT_MARGIN, DEFAULT_PAGE_HEIGHT, DEFAULT_PAGE_WIDTH, fitScale, parseSectionDimensions, ptToPx, pxToPt, } from "./page-geometry.js";
49
+ export { DocumentViewport } from "./viewport.js";
50
+ export { CommentRenderMode, PaginationMode, AnnotationLabelMode, RevisionType, DocxDiffRevisionGranularity, DocxDiffFormatComparison, ConflictResolution, ProjectionScopes, AnchorRenderMode, TableRenderMode, TrackedChangeMode, EmptyParagraphMode, AnchorIdRendering, ProjectionDepth, DocumentElementType, ComparisonLogLevel, ComparisonLogCodes, isInsertion, isDeletion, isMove, isFormatChange,
51
+ // Document structure helpers
52
+ findElementById, findElementsByType, getParagraphs, getTables, getTableColumns,
53
+ // Annotation target factory functions
54
+ targetElement, targetParagraph, targetParagraphRange, targetRun, targetTable, targetTableRow, targetTableCell, targetTableColumn, targetSearch, targetSearchInElement, };
55
+ let wasmExports = null;
56
+ let initPromise = null;
57
+ /**
58
+ * Yields to the browser's main thread, allowing pending UI updates to render.
59
+ *
60
+ * This is critical for WASM operations: since WASM runs synchronously on the
61
+ * main thread, React state updates (like loading spinners) won't paint unless
62
+ * we yield before the blocking work begins.
63
+ *
64
+ * Uses requestAnimationFrame which fires just before the next paint, ensuring
65
+ * any queued state updates are committed to the DOM.
66
+ *
67
+ * @internal
68
+ */
69
+ async function yieldToMain() {
70
+ // In non-browser environments (SSR, tests), skip yielding
71
+ if (typeof requestAnimationFrame === "undefined") {
72
+ return;
73
+ }
74
+ // Double-rAF ensures the browser has fully painted before we continue
75
+ // First rAF: scheduled for next frame
76
+ // Second rAF: ensures first frame actually painted
77
+ await new Promise((resolve) => {
78
+ requestAnimationFrame(() => {
79
+ requestAnimationFrame(() => resolve());
80
+ });
81
+ });
82
+ }
83
+ /**
84
+ * Derive the WASM base path from this module's URL.
85
+ * Works whether loaded from node_modules, CDN, or bundled.
86
+ */
87
+ function getDefaultWasmBasePath() {
88
+ try {
89
+ // import.meta.url gives us the URL of this module
90
+ // e.g., "https://cdn.jsdelivr.net/npm/docxodus@12.3.0/dist/core.js"
91
+ // or "file:///path/to/node_modules/docxodus/dist/core.js"
92
+ const moduleUrl = import.meta.url;
93
+ // Remove the filename to get the directory
94
+ const baseDir = moduleUrl.substring(0, moduleUrl.lastIndexOf('/') + 1);
95
+ // WASM files are in ./wasm/ relative to dist/
96
+ return baseDir + "wasm/";
97
+ }
98
+ catch {
99
+ // Fallback if import.meta.url is not available
100
+ return "";
101
+ }
102
+ }
103
+ /**
104
+ * Current base path for WASM files.
105
+ * Empty string means auto-detect from module URL.
106
+ */
107
+ export let wasmBasePath = "";
108
+ /**
109
+ * Set custom base path for WASM files.
110
+ * Pass empty string or don't call this to auto-detect from module location.
111
+ *
112
+ * @param path - Custom path to WASM files, or empty string for auto-detection
113
+ */
114
+ export function setWasmBasePath(path) {
115
+ wasmBasePath = path && !path.endsWith("/") ? path + "/" : path;
116
+ }
117
+ /**
118
+ * Initialize the Docxodus WASM runtime.
119
+ * Must be called before using any conversion/comparison functions.
120
+ * Safe to call multiple times - will only initialize once.
121
+ *
122
+ * By default, WASM files are auto-detected from the module's location
123
+ * (works with CDN, npm, or local hosting).
124
+ * Pass a basePath to load from a custom location instead.
125
+ *
126
+ * @param basePath - Optional custom path to WASM files. Leave empty for auto-detection.
127
+ */
128
+ export async function initialize(basePath) {
129
+ if (wasmExports)
130
+ return;
131
+ if (initPromise) {
132
+ return initPromise;
133
+ }
134
+ if (basePath !== undefined) {
135
+ setWasmBasePath(basePath);
136
+ }
137
+ // Clear the cached promise on failure so a caller can retry with a
138
+ // different base path (a rejected initialize() used to be permanent).
139
+ initPromise = loadWasm().catch((e) => {
140
+ initPromise = null;
141
+ throw e;
142
+ });
143
+ return initPromise;
144
+ }
145
+ /**
146
+ * Try to load WASM from a specific base path
147
+ */
148
+ async function tryLoadFromPath(basePath) {
149
+ try {
150
+ const dotnetPath = basePath + "_framework/dotnet.js";
151
+ const { dotnet } = await import(/* webpackIgnore: true */ /* @vite-ignore */ dotnetPath);
152
+ const { getAssemblyExports, getConfig, setModuleImports } = await dotnet
153
+ .withDiagnosticTracing(false)
154
+ .create();
155
+ installHistoryStorageImports(setModuleImports);
156
+ const config = getConfig();
157
+ const exports = await getAssemblyExports(config.mainAssemblyName);
158
+ wasmExports = {
159
+ DocumentConverter: exports.DocxodusWasm.DocumentConverter,
160
+ DocumentComparer: exports.DocxodusWasm.DocumentComparer,
161
+ DocxDiffBridge: exports.DocxodusWasm.DocxDiffBridge,
162
+ DocxSessionBridge: exports.DocxodusWasm.DocxSessionBridge,
163
+ HistoryBridge: exports.DocxodusWasm.HistoryBridge,
164
+ };
165
+ return true;
166
+ }
167
+ catch {
168
+ return false;
169
+ }
170
+ }
171
+ async function loadWasm() {
172
+ // If a custom path is set, use it directly
173
+ if (wasmBasePath) {
174
+ const success = await tryLoadFromPath(wasmBasePath);
175
+ if (success)
176
+ return;
177
+ throw new Error(`Failed to load WASM from custom path: ${wasmBasePath}. ` +
178
+ `Ensure the WASM files are served at this location.`);
179
+ }
180
+ // Try to auto-detect from module URL (works for CDN and local imports)
181
+ const autoDetectedPath = getDefaultWasmBasePath();
182
+ if (autoDetectedPath) {
183
+ const success = await tryLoadFromPath(autoDetectedPath);
184
+ if (success) {
185
+ wasmBasePath = autoDetectedPath;
186
+ return;
187
+ }
188
+ }
189
+ // Auto-detection failed
190
+ throw new Error(`Failed to load WASM files. ` +
191
+ `Auto-detected path: ${autoDetectedPath || "(none)"}. ` +
192
+ `You can specify a custom path by calling initialize("/path/to/wasm/").`);
193
+ }
194
+ function ensureInitialized() {
195
+ if (!wasmExports) {
196
+ throw new Error("Docxodus not initialized. Call initialize() first and await it.");
197
+ }
198
+ return wasmExports;
199
+ }
200
+ function isErrorResponse(result) {
201
+ try {
202
+ const parsed = JSON.parse(result);
203
+ return typeof parsed === "object" && "Error" in parsed;
204
+ }
205
+ catch {
206
+ return false;
207
+ }
208
+ }
209
+ function parseError(result) {
210
+ const parsed = JSON.parse(result);
211
+ return {
212
+ error: parsed.Error || parsed.error,
213
+ type: parsed.Type || parsed.type,
214
+ stackTrace: parsed.StackTrace || parsed.stackTrace,
215
+ };
216
+ }
217
+ /**
218
+ * Convert a File or Uint8Array to Uint8Array
219
+ */
220
+ async function toBytes(input) {
221
+ if (input instanceof Uint8Array) {
222
+ return input;
223
+ }
224
+ const buffer = await input.arrayBuffer();
225
+ return new Uint8Array(buffer);
226
+ }
227
+ /**
228
+ * Generate a deterministic, non-mutating verification manifest from DOCX bytes.
229
+ * Invalid, malformed, and encrypted packages are represented by structured findings.
230
+ */
231
+ export async function generatePackageManifest(document) {
232
+ const exports = ensureInitialized();
233
+ const bytes = await toBytes(document);
234
+ await yieldToMain();
235
+ return JSON.parse(exports.DocumentConverter.GeneratePackageManifest(bytes));
236
+ }
237
+ /**
238
+ * Run the default bounded deliverable-verification policy on exact DOCX bytes.
239
+ * Invalid, malformed, encrypted, and safety-limited packages are returned as
240
+ * structured report findings rather than editable-session errors. When supplied,
241
+ * the exact baseline bytes are used to classify pre-existing, new, and resolved findings.
242
+ */
243
+ export async function verifyDeliverable(document, baseline, request) {
244
+ const exports = ensureInitialized();
245
+ const bytes = await toBytes(document);
246
+ const baselineBytes = baseline === undefined ? undefined : await toBytes(baseline);
247
+ await yieldToMain();
248
+ if (request !== undefined) {
249
+ // The full request (issue #747): the same wire shape every transport parses.
250
+ const requestJson = serializeVerificationRequest(request);
251
+ const converter = exports.DocumentConverter;
252
+ if (!converter.VerifyDeliverableWithRequest || !converter.VerifyDeliverableWithBaselineAndRequest) {
253
+ throw new Error("This WASM bundle predates full verification requests; rebuild docxodus.");
254
+ }
255
+ return JSON.parse(baselineBytes === undefined
256
+ ? converter.VerifyDeliverableWithRequest(bytes, requestJson)
257
+ : converter.VerifyDeliverableWithBaselineAndRequest(baselineBytes, bytes, requestJson));
258
+ }
259
+ return JSON.parse(baselineBytes === undefined
260
+ ? exports.DocumentConverter.VerifyDeliverable(bytes)
261
+ : exports.DocumentConverter.VerifyDeliverableWithBaseline(baselineBytes, bytes));
262
+ }
263
+ /**
264
+ * Verify a portable JSON delivery change receipt against supplied artifact bytes.
265
+ *
266
+ * The receipt travels as its JSON envelope string; `artifacts` maps each artifact id
267
+ * the receipt records to the exact bytes to independently re-hash against it. Omitted
268
+ * artifacts report `"missing"`. Malformed input yields a structured invalid verdict
269
+ * whose findings carry the reason — never a thrown error.
270
+ */
271
+ export async function verifyDeliveryReceipt(receiptJson, artifacts) {
272
+ const exports = ensureInitialized();
273
+ const artifactsJson = artifacts === undefined
274
+ ? ""
275
+ : JSON.stringify(Object.fromEntries(Object.entries(artifacts).map(([artifactId, bytes]) => [
276
+ artifactId,
277
+ bytesToBase64(bytes),
278
+ ])));
279
+ await yieldToMain();
280
+ return JSON.parse(exports.DocumentConverter.VerifyDeliveryReceipt(receiptJson, artifactsJson));
281
+ }
282
+ /**
283
+ * Prove that a redline's generated revisions accept to the intended final and reject to the
284
+ * selected baseline without consuming pre-existing review state.
285
+ *
286
+ * Three packages are inspected and two rebuilt, so on a UI thread prefer the worker proxy's
287
+ * `proveRedlineReversibility`. Malformed, encrypted, and safety-limited packages are reported as
288
+ * structured proof findings rather than thrown errors. The rebuilt packages are not returned:
289
+ * the proof carries their digests and the divergences between them and each expected document.
290
+ *
291
+ * @param baseline - The document the redline was generated against
292
+ * @param intendedFinal - The document accepting the generated revisions must reproduce
293
+ * @param redline - The generated redline under proof
294
+ */
295
+ export async function proveRedlineReversibility(baseline, intendedFinal, redline) {
296
+ const exports = ensureInitialized();
297
+ const baselineBytes = await toBytes(baseline);
298
+ const intendedFinalBytes = await toBytes(intendedFinal);
299
+ const redlineBytes = await toBytes(redline);
300
+ await yieldToMain();
301
+ return JSON.parse(exports.DocumentConverter.ProveRedlineReversibility(baselineBytes, intendedFinalBytes, redlineBytes));
302
+ }
303
+ /**
304
+ * Convert a DOCX document to HTML.
305
+ *
306
+ * @param document - DOCX file as File object or Uint8Array
307
+ * @param options - Conversion options
308
+ * @returns HTML string
309
+ * @throws Error if conversion fails
310
+ *
311
+ * @example
312
+ * ```typescript
313
+ * // Basic conversion
314
+ * const html = await convertDocxToHtml(docxFile);
315
+ *
316
+ * // With pagination (PDF.js-style page view)
317
+ * const html = await convertDocxToHtml(docxFile, {
318
+ * paginationMode: PaginationMode.Paginated,
319
+ * paginationScale: 0.8
320
+ * });
321
+ *
322
+ * // With annotations rendered
323
+ * const html = await convertDocxToHtml(docxFile, {
324
+ * renderAnnotations: true,
325
+ * annotationLabelMode: AnnotationLabelMode.Above
326
+ * });
327
+ *
328
+ * // With footnotes and endnotes
329
+ * const html = await convertDocxToHtml(docxFile, {
330
+ * renderFootnotesAndEndnotes: true
331
+ * });
332
+ *
333
+ * // With headers and footers
334
+ * const html = await convertDocxToHtml(docxFile, {
335
+ * renderHeadersAndFooters: true
336
+ * });
337
+ *
338
+ * // With tracked changes (redlines visible)
339
+ * const html = await convertDocxToHtml(docxFile, {
340
+ * renderTrackedChanges: true,
341
+ * showDeletedContent: true,
342
+ * renderMoveOperations: true
343
+ * });
344
+ * ```
345
+ */
346
+ /**
347
+ * Render a single document block to faithful HTML, addressed by its anchor.
348
+ *
349
+ * The anchor is the `data-anchor` value stamped on a block during a full
350
+ * conversion (a bare 32-hex Unid), or a full `kind:scope:unid` anchor — either
351
+ * form works. Powers the editor's incremental per-block re-render: apply an edit
352
+ * to a DocxSession, then re-render only the changed block instead of the whole
353
+ * document. Returns the block's HTML element (no `<html>`/`<head>` wrapper).
354
+ */
355
+ export async function renderBlockHtml(document, anchorId, options) {
356
+ const exports = ensureInitialized();
357
+ const bytes = await toBytes(document);
358
+ await yieldToMain();
359
+ const result = exports.DocumentConverter.RenderBlockHtml(bytes, anchorId, options?.cssPrefix ?? "docx-", options?.fabricateClasses ?? false);
360
+ if (isErrorResponse(result)) {
361
+ throw new Error(`Block rendering failed: ${parseError(result).error}`);
362
+ }
363
+ return result;
364
+ }
365
+ export async function convertDocxToHtml(document, options) {
366
+ const exports = ensureInitialized();
367
+ const bytes = await toBytes(document);
368
+ // Yield to browser before heavy WASM work - allows loading states to render
369
+ await yieldToMain();
370
+ let result;
371
+ // Check if any of the new complete options are specified
372
+ const needsCompleteMethod = options?.renderFootnotesAndEndnotes !== undefined ||
373
+ options?.renderHeadersAndFooters !== undefined ||
374
+ options?.renderTrackedChanges !== undefined ||
375
+ options?.showDeletedContent !== undefined ||
376
+ options?.renderMoveOperations !== undefined ||
377
+ options?.renderUnsupportedContentPlaceholders !== undefined ||
378
+ options?.documentLanguage !== undefined ||
379
+ options?.stampAnchors !== undefined;
380
+ // Use complete method when any new options are specified (most comprehensive)
381
+ if (needsCompleteMethod || options?.renderAnnotations) {
382
+ result = exports.DocumentConverter.ConvertDocxToHtmlComplete(bytes, options?.pageTitle ?? "Document", options?.cssPrefix ?? "docx-", options?.fabricateClasses ?? true, options?.additionalCss ?? "", options?.commentRenderMode ?? CommentRenderMode.Disabled, options?.commentCssClassPrefix ?? "comment-", options?.paginationMode ?? PaginationMode.None, options?.paginationScale ?? 1.0, options?.paginationCssClassPrefix ?? "page-", options?.renderAnnotations ?? false, options?.annotationLabelMode ?? AnnotationLabelMode.Above, options?.annotationCssClassPrefix ?? "annot-", options?.renderFootnotesAndEndnotes ?? false, options?.renderHeadersAndFooters ?? false, options?.renderTrackedChanges ?? false, options?.showDeletedContent ?? true, options?.renderMoveOperations ?? true, options?.renderUnsupportedContentPlaceholders ?? false, options?.documentLanguage ?? null, options?.stampAnchors ?? false);
383
+ }
384
+ // Use pagination-aware method when pagination is requested
385
+ else if (options?.paginationMode !== undefined && options.paginationMode !== PaginationMode.None) {
386
+ result = exports.DocumentConverter.ConvertDocxToHtmlWithPagination(bytes, options.pageTitle ?? "Document", options.cssPrefix ?? "docx-", options.fabricateClasses ?? true, options.additionalCss ?? "", options.commentRenderMode ?? CommentRenderMode.Disabled, options.commentCssClassPrefix ?? "comment-", options.paginationMode, options.paginationScale ?? 1.0, options.paginationCssClassPrefix ?? "page-");
387
+ }
388
+ else if (options) {
389
+ result = exports.DocumentConverter.ConvertDocxToHtmlWithOptions(bytes, options.pageTitle ?? "Document", options.cssPrefix ?? "docx-", options.fabricateClasses ?? true, options.additionalCss ?? "", options.commentRenderMode ?? CommentRenderMode.Disabled, options.commentCssClassPrefix ?? "comment-");
390
+ }
391
+ else {
392
+ result = exports.DocumentConverter.ConvertDocxToHtml(bytes);
393
+ }
394
+ if (isErrorResponse(result)) {
395
+ const error = parseError(result);
396
+ throw new Error(`Conversion failed: ${error.error}`);
397
+ }
398
+ return result;
399
+ }
400
+ /**
401
+ * Compare two DOCX documents and return the redlined result as a DOCX.
402
+ *
403
+ * @param original - Original DOCX document
404
+ * @param modified - Modified DOCX document
405
+ * @param options - Comparison options
406
+ * @returns Redlined DOCX as Uint8Array
407
+ * @throws Error if comparison fails
408
+ */
409
+ export async function compareDocuments(original, modified, options) {
410
+ const exports = ensureInitialized();
411
+ const originalBytes = await toBytes(original);
412
+ const modifiedBytes = await toBytes(modified);
413
+ // Yield to browser before heavy WASM work - allows loading states to render
414
+ await yieldToMain();
415
+ let result;
416
+ if (options?.caseInsensitive) {
417
+ result = exports.DocumentComparer.CompareDocumentsWithOptions(originalBytes, modifiedBytes, options?.authorName ?? "Docxodus", options.caseInsensitive);
418
+ }
419
+ else {
420
+ result = exports.DocumentComparer.CompareDocuments(originalBytes, modifiedBytes, options?.authorName ?? "Docxodus");
421
+ }
422
+ if (result.length === 0) {
423
+ throw new Error("Comparison failed - empty result");
424
+ }
425
+ return result;
426
+ }
427
+ /**
428
+ * Compare two DOCX documents and return the result as HTML.
429
+ *
430
+ * @param original - Original DOCX document
431
+ * @param modified - Modified DOCX document
432
+ * @param options - Comparison options
433
+ * @returns HTML string with redlined content
434
+ * @throws Error if comparison fails
435
+ */
436
+ export async function compareDocumentsToHtml(original, modified, options) {
437
+ const exports = ensureInitialized();
438
+ const originalBytes = await toBytes(original);
439
+ const modifiedBytes = await toBytes(modified);
440
+ // Yield to browser before heavy WASM work - allows loading states to render
441
+ await yieldToMain();
442
+ const renderTrackedChanges = options?.renderTrackedChanges ?? true;
443
+ let result;
444
+ if (options?.caseInsensitive !== undefined) {
445
+ result = exports.DocumentComparer.CompareDocumentsToHtmlFull(originalBytes, modifiedBytes, options?.authorName ?? "Docxodus", options.caseInsensitive, renderTrackedChanges);
446
+ }
447
+ else {
448
+ result = exports.DocumentComparer.CompareDocumentsToHtmlWithOptions(originalBytes, modifiedBytes, options?.authorName ?? "Docxodus", renderTrackedChanges);
449
+ }
450
+ if (isErrorResponse(result)) {
451
+ const error = parseError(result);
452
+ throw new Error(`Comparison failed: ${error.error}`);
453
+ }
454
+ return result;
455
+ }
456
+ /**
457
+ * Get revisions from a compared document.
458
+ *
459
+ * @param document - A document that has been through comparison (has tracked changes)
460
+ * @param options - Optional move detection configuration
461
+ * @returns Array of revisions
462
+ * @throws Error if operation fails
463
+ *
464
+ * @example
465
+ * ```typescript
466
+ * // Default settings (move detection enabled, 80% threshold)
467
+ * const revisions = await getRevisions(comparedDoc);
468
+ *
469
+ * // Custom move detection settings
470
+ * const revisions = await getRevisions(comparedDoc, {
471
+ * detectMoves: true,
472
+ * moveSimilarityThreshold: 0.9, // Require 90% word overlap
473
+ * moveMinimumWordCount: 5, // Only consider phrases of 5+ words
474
+ * caseInsensitive: true // Ignore case when matching
475
+ * });
476
+ *
477
+ * // Disable move detection entirely
478
+ * const revisions = await getRevisions(comparedDoc, { detectMoves: false });
479
+ * ```
480
+ */
481
+ export async function getRevisions(document) {
482
+ const exports = ensureInitialized();
483
+ const bytes = await toBytes(document);
484
+ // Yield to browser before WASM work - allows loading states to render
485
+ await yieldToMain();
486
+ const result = exports.DocumentComparer.GetRevisionsJson(bytes);
487
+ if (isErrorResponse(result)) {
488
+ const error = parseError(result);
489
+ throw new Error(`Failed to get revisions: ${error.error}`);
490
+ }
491
+ // The payload is the session's own revision wire shape, so it needs no remapping.
492
+ return JSON.parse(result);
493
+ }
494
+ // ─── DocxDiff (IR diff engine) ──────────────────────────────────────────────
495
+ //
496
+ // The structure-aware default comparison engine. Its specialized APIs add
497
+ // anchor-addressed revisions and the diff-as-data edit script. Settings flow as
498
+ // a JSON object; an empty `{}` (or omitted options) uses the engine defaults.
499
+ /** Serialize DocxDiffSettings to the wire JSON the bridge parses (empty string when undefined). */
500
+ function docxDiffSettingsJson(settings) {
501
+ return settings ? JSON.stringify(settings) : "";
502
+ }
503
+ /**
504
+ * Compare two DOCX documents with the IR diff engine and return the redlined
505
+ * result as a DOCX (native w:ins/w:del/w:moveFrom/w:moveTo/w:rPrChange markup).
506
+ *
507
+ * @param left - The earlier/original document.
508
+ * @param right - The later/revised document.
509
+ * @param settings - Optional {@link DocxDiffSettings}; omit for engine defaults.
510
+ * @returns Redlined DOCX as Uint8Array.
511
+ * @throws Error if comparison fails.
512
+ */
513
+ export async function docxDiffCompare(left, right, settings) {
514
+ const exports = ensureInitialized();
515
+ const leftBytes = await toBytes(left);
516
+ const rightBytes = await toBytes(right);
517
+ await yieldToMain();
518
+ const result = exports.DocxDiffBridge.Compare(leftBytes, rightBytes, docxDiffSettingsJson(settings));
519
+ if (result.length === 0) {
520
+ throw new Error("DocxDiff comparison failed - empty result");
521
+ }
522
+ return result;
523
+ }
524
+ /**
525
+ * Compare two DOCX documents with the IR diff engine and return the
526
+ * anchor-addressed revision list.
527
+ *
528
+ * @param left - The earlier/original document.
529
+ * @param right - The later/revised document.
530
+ * @param settings - Optional {@link DocxDiffSettings}; omit for engine defaults.
531
+ * @returns Array of {@link DocxDiffRevision} (each carrying its left/right block anchors).
532
+ * @throws Error if the operation fails.
533
+ */
534
+ export async function docxDiffGetRevisions(left, right, settings) {
535
+ const exports = ensureInitialized();
536
+ const leftBytes = await toBytes(left);
537
+ const rightBytes = await toBytes(right);
538
+ await yieldToMain();
539
+ const result = exports.DocxDiffBridge.GetRevisionsJson(leftBytes, rightBytes, docxDiffSettingsJson(settings));
540
+ if (isErrorResponse(result)) {
541
+ const error = parseError(result);
542
+ throw new Error(`Failed to get DocxDiff revisions: ${error.error}`);
543
+ }
544
+ const parsed = JSON.parse(result);
545
+ return (parsed.revisions || parsed.Revisions || []).map(mapDocxDiffRevision);
546
+ }
547
+ /**
548
+ * Compare two DOCX documents ONCE and return every requested data product from
549
+ * that single memoized pass (issue #594). Where a review pipeline calling
550
+ * {@link docxDiffCompare}, {@link docxDiffGetRevisions}, and
551
+ * {@link docxDiffGetEditScript} separately pays for the alignment per call, this
552
+ * runs it once — each product identical to its standalone counterpart (the edit
553
+ * script is handed over parsed rather than as the serialized string).
554
+ *
555
+ * @param left - The earlier/original document.
556
+ * @param right - The later/revised document.
557
+ * @param settings - Optional {@link DocxDiffSettings}; omit for engine defaults.
558
+ * @param products - Products to compute; omit for all four.
559
+ * @throws Error if the operation fails.
560
+ */
561
+ export async function docxDiffCompareProducts(left, right, settings, products) {
562
+ const exports = ensureInitialized();
563
+ const leftBytes = await toBytes(left);
564
+ const rightBytes = await toBytes(right);
565
+ await yieldToMain();
566
+ const result = exports.DocxDiffBridge.CompareProductsJson(leftBytes, rightBytes, docxDiffSettingsJson(settings), products ? JSON.stringify(products) : "");
567
+ if (isErrorResponse(result)) {
568
+ const error = parseError(result);
569
+ throw new Error(`Failed to compare products: ${error.error}`);
570
+ }
571
+ const parsed = JSON.parse(result);
572
+ return {
573
+ redline: typeof parsed.redlineB64 === "string"
574
+ ? Uint8Array.from(atob(parsed.redlineB64), c => c.charCodeAt(0))
575
+ : undefined,
576
+ revisions: Array.isArray(parsed.revisions)
577
+ ? parsed.revisions.map(mapDocxDiffRevision)
578
+ : undefined,
579
+ editScript: parsed.editScript !== undefined
580
+ ? parsed.editScript
581
+ : undefined,
582
+ semanticChanges: parsed.semanticChanges !== undefined
583
+ ? parsed.semanticChanges
584
+ : undefined,
585
+ };
586
+ }
587
+ /**
588
+ * Compare ONE baseline against MANY candidates, reading the baseline once (issue #617).
589
+ *
590
+ * The read is the single largest stage of a comparison, and a fan-out — one negotiated
591
+ * draft against every counterparty's markup — otherwise re-reads the baseline for each
592
+ * one. This reads it once and compares every candidate against that snapshot; each
593
+ * result is identical to what {@link docxDiffCompareProducts} returns for the same pair.
594
+ *
595
+ * A candidate that fails carries an `error` instead of products; the rest of the batch
596
+ * still comes back, because one malformed markup should not cost the other ninety-nine.
597
+ *
598
+ * @param baseline - The shared left-hand document.
599
+ * @param candidates - The documents to compare against it, in order.
600
+ * @param settings - Optional {@link DocxDiffSettings}; omit for engine defaults.
601
+ * @param products - Products to compute; omit for all four.
602
+ * @throws Error if the batch itself fails (a bad baseline, malformed settings).
603
+ */
604
+ export async function docxDiffCompareBatch(baseline, candidates, settings, products) {
605
+ const exports = ensureInitialized();
606
+ const baselineBytes = await toBytes(baseline);
607
+ const payload = [];
608
+ for (let i = 0; i < candidates.length; i++) {
609
+ const bytes = await toBytes(candidates[i].document);
610
+ payload.push({
611
+ name: candidates[i].name ?? String(i),
612
+ docB64: bytesToBase64(bytes),
613
+ });
614
+ }
615
+ await yieldToMain();
616
+ const result = exports.DocxDiffBridge.CompareBatchJson(baselineBytes, JSON.stringify(payload), docxDiffSettingsJson(settings), products ? JSON.stringify(products) : "");
617
+ if (isErrorResponse(result)) {
618
+ const error = parseError(result);
619
+ throw new Error(`Failed to compare batch: ${error.error}`);
620
+ }
621
+ const parsed = JSON.parse(result);
622
+ return (parsed.results ?? []).map((entry) => ({
623
+ name: String(entry.name ?? ""),
624
+ error: typeof entry.error === "string" ? entry.error : undefined,
625
+ redline: typeof entry.redlineB64 === "string"
626
+ ? Uint8Array.from(atob(entry.redlineB64), c => c.charCodeAt(0))
627
+ : undefined,
628
+ revisions: Array.isArray(entry.revisions)
629
+ ? entry.revisions.map(mapDocxDiffRevision)
630
+ : undefined,
631
+ editScript: entry.editScript !== undefined
632
+ ? entry.editScript
633
+ : undefined,
634
+ semanticChanges: entry.semanticChanges !== undefined
635
+ ? entry.semanticChanges
636
+ : undefined,
637
+ }));
638
+ }
639
+ /**
640
+ * Compare two DOCX documents with the IR diff engine and return the edit script
641
+ * as a JSON string — the diff-as-data differentiator. The script is the
642
+ * anchor-addressed list of block operations the markup and revision renderers
643
+ * both consume: stable and machine-readable for storage, transport, and audit.
644
+ *
645
+ * @param left - The earlier/original document.
646
+ * @param right - The later/revised document.
647
+ * @param settings - Optional {@link DocxDiffSettings}; omit for engine defaults.
648
+ * @returns The edit script serialized as indented JSON.
649
+ * @throws Error if the operation fails.
650
+ */
651
+ export async function docxDiffGetEditScript(left, right, settings) {
652
+ const exports = ensureInitialized();
653
+ const leftBytes = await toBytes(left);
654
+ const rightBytes = await toBytes(right);
655
+ await yieldToMain();
656
+ const result = exports.DocxDiffBridge.GetEditScriptJson(leftBytes, rightBytes, docxDiffSettingsJson(settings));
657
+ if (isErrorResponse(result)) {
658
+ const error = parseError(result);
659
+ throw new Error(`Failed to get DocxDiff edit script: ${error.error}`);
660
+ }
661
+ return result;
662
+ }
663
+ /**
664
+ * Compare two DOCX documents and return the stable, versioned semantic-change
665
+ * schema. This is the audit/verification surface; it classifies document meaning
666
+ * beyond the renderer's internal edit script and preserves unknown package changes.
667
+ */
668
+ export async function docxDiffGetSemanticChanges(left, right, settings) {
669
+ const exports = ensureInitialized();
670
+ const leftBytes = await toBytes(left);
671
+ const rightBytes = await toBytes(right);
672
+ await yieldToMain();
673
+ const result = exports.DocxDiffBridge.GetSemanticChangesJson(leftBytes, rightBytes, docxDiffSettingsJson(settings));
674
+ if (isErrorResponse(result)) {
675
+ const error = parseError(result);
676
+ throw new Error(`Failed to get semantic changes: ${error.error}`);
677
+ }
678
+ return JSON.parse(result);
679
+ }
680
+ /**
681
+ * Accept every tracked revision in a redlined DOCX and return the resulting bytes
682
+ * (materializes the "right"/revised side). The byte-in, byte-out counterpart of
683
+ * {@link docxDiffCompare}: `docxDiffAcceptRevisions(await docxDiffCompare(left, right))`
684
+ * equals `right` at the per-block text level — so callers can verify the round-trip
685
+ * contract of a redline, not just inspect its shape.
686
+ *
687
+ * @param redline - A DOCX carrying tracked-changes markup (e.g. {@link docxDiffCompare} output).
688
+ * @returns The DOCX bytes with all revisions accepted.
689
+ * @throws Error if the operation fails.
690
+ */
691
+ export async function docxDiffAcceptRevisions(redline) {
692
+ const exports = ensureInitialized();
693
+ const bytes = await toBytes(redline);
694
+ await yieldToMain();
695
+ const result = exports.DocxDiffBridge.AcceptRevisions(bytes);
696
+ if (result.length === 0) {
697
+ throw new Error("DocxDiff accept-revisions failed - empty result");
698
+ }
699
+ return result;
700
+ }
701
+ /**
702
+ * Reject every tracked revision in a redlined DOCX and return the resulting bytes
703
+ * (materializes the "left"/original side): `docxDiffRejectRevisions(await
704
+ * docxDiffCompare(left, right))` equals `left` at the per-block text level.
705
+ *
706
+ * @param redline - A DOCX carrying tracked-changes markup (e.g. {@link docxDiffCompare} output).
707
+ * @returns The DOCX bytes with all revisions rejected.
708
+ * @throws Error if the operation fails.
709
+ */
710
+ export async function docxDiffRejectRevisions(redline) {
711
+ const exports = ensureInitialized();
712
+ const bytes = await toBytes(redline);
713
+ await yieldToMain();
714
+ const result = exports.DocxDiffBridge.RejectRevisions(bytes);
715
+ if (result.length === 0) {
716
+ throw new Error("DocxDiff reject-revisions failed - empty result");
717
+ }
718
+ return result;
719
+ }
720
+ // ─── DocxDiff consolidate (composite N-way) ─────────────────────────────────
721
+ //
722
+ // Merge several reviewers' edits against one shared base DOCX. Each reviewer is
723
+ // base64-encoded into the `[{author,docB64}]` wire shape the host base64-DECODES
724
+ // (standard base64, not url-safe). Settings flow as the diff-settings JSON object
725
+ // extended with an optional integer `conflictResolution`.
726
+ /**
727
+ * Encode a Uint8Array to a standard (non-url-safe) base64 string. Uses a chunked
728
+ * binary string so large documents don't blow the call-stack limit of
729
+ * `String.fromCharCode(...bytes)`, and works in both browser (`btoa`) and Node
730
+ * (`Buffer`) hosts.
731
+ */
732
+ function bytesToBase64(bytes) {
733
+ if (typeof btoa === "function") {
734
+ let binary = "";
735
+ const chunkSize = 0x8000; // 32 KB per chunk keeps the spread small
736
+ for (let i = 0; i < bytes.length; i += chunkSize) {
737
+ const chunk = bytes.subarray(i, i + chunkSize);
738
+ binary += String.fromCharCode.apply(null, chunk);
739
+ }
740
+ return btoa(binary);
741
+ }
742
+ // Node fallback (e.g. unit tests outside a browser).
743
+ return Buffer.from(bytes).toString("base64");
744
+ }
745
+ /** Serialize reviewers to the `[{author,docB64}]` wire JSON the host expects. */
746
+ async function reviewersJson(reviewers) {
747
+ const arr = await Promise.all(reviewers.map(async (r) => ({
748
+ author: r.author,
749
+ docB64: bytesToBase64(await toBytes(r.document)),
750
+ })));
751
+ return JSON.stringify(arr);
752
+ }
753
+ /**
754
+ * Serialize DocxDiffConsolidateSettings to the wire JSON the bridge parses. Same
755
+ * shape as {@link docxDiffSettingsJson} plus the integer `conflictResolution`
756
+ * when present (empty string when undefined).
757
+ */
758
+ function docxDiffConsolidateSettingsJson(settings) {
759
+ return settings ? JSON.stringify(settings) : "";
760
+ }
761
+ /** Map a single revision wire object (camelCase or PascalCase) to {@link DocxDiffRevision}. */
762
+ function mapDocxDiffRevision(r) {
763
+ return {
764
+ revisionType: r.revisionType ?? r.RevisionType,
765
+ text: r.text ?? r.Text,
766
+ author: r.author ?? r.Author,
767
+ date: r.date ?? r.Date,
768
+ moveGroupId: r.moveGroupId ?? r.MoveGroupId ?? undefined,
769
+ isMoveSource: r.isMoveSource ?? r.IsMoveSource ?? undefined,
770
+ formatChange: (r.formatChange || r.FormatChange) ? {
771
+ oldProperties: r.formatChange?.oldProperties ?? r.FormatChange?.OldProperties,
772
+ newProperties: r.formatChange?.newProperties ?? r.FormatChange?.NewProperties,
773
+ changedPropertyNames: r.formatChange?.changedPropertyNames ?? r.FormatChange?.ChangedPropertyNames,
774
+ } : undefined,
775
+ leftAnchor: r.leftAnchor ?? r.LeftAnchor ?? undefined,
776
+ rightAnchor: r.rightAnchor ?? r.RightAnchor ?? undefined,
777
+ };
778
+ }
779
+ /**
780
+ * Consolidate several reviewers' edits against a shared base DOCX and return the
781
+ * merged redlined result as a DOCX (native multi-author tracked-changes markup).
782
+ *
783
+ * @param base - The shared base document all reviewers edited from.
784
+ * @param reviewers - The reviewers' edited copies + author names.
785
+ * @param settings - Optional {@link DocxDiffConsolidateSettings}; omit for engine defaults.
786
+ * @returns Consolidated redlined DOCX as Uint8Array.
787
+ * @throws Error if consolidation fails.
788
+ */
789
+ export async function docxDiffConsolidate(base, reviewers, settings) {
790
+ const exports = ensureInitialized();
791
+ const baseBytes = await toBytes(base);
792
+ const reviewersJsonStr = await reviewersJson(reviewers);
793
+ await yieldToMain();
794
+ const result = exports.DocxDiffBridge.Consolidate(baseBytes, reviewersJsonStr, docxDiffConsolidateSettingsJson(settings));
795
+ if (result.length === 0) {
796
+ throw new Error("DocxDiff consolidation failed - empty result");
797
+ }
798
+ return result;
799
+ }
800
+ /**
801
+ * Consolidate several reviewers' edits against a shared base DOCX and return the
802
+ * per-token conflict report — every base span two or more reviewers edited
803
+ * incompatibly, with each reviewer's competing variant.
804
+ *
805
+ * @param base - The shared base document all reviewers edited from.
806
+ * @param reviewers - The reviewers' edited copies + author names.
807
+ * @param settings - Optional {@link DocxDiffConsolidateSettings}; omit for engine defaults.
808
+ * @returns Array of {@link DocxDiffConflict}.
809
+ * @throws Error if the operation fails.
810
+ */
811
+ export async function docxDiffGetConflicts(base, reviewers, settings) {
812
+ const exports = ensureInitialized();
813
+ const baseBytes = await toBytes(base);
814
+ const reviewersJsonStr = await reviewersJson(reviewers);
815
+ await yieldToMain();
816
+ const result = exports.DocxDiffBridge.GetConflictsJson(baseBytes, reviewersJsonStr, docxDiffConsolidateSettingsJson(settings));
817
+ if (isErrorResponse(result)) {
818
+ const error = parseError(result);
819
+ throw new Error(`Failed to get DocxDiff conflicts: ${error.error}`);
820
+ }
821
+ const parsed = JSON.parse(result);
822
+ return (parsed.conflicts || parsed.Conflicts || []).map((c) => ({
823
+ id: c.id ?? c.Id,
824
+ baseAnchor: c.baseAnchor ?? c.BaseAnchor,
825
+ tokenStart: c.tokenStart ?? c.TokenStart,
826
+ tokenEnd: c.tokenEnd ?? c.TokenEnd,
827
+ policy: c.policy ?? c.Policy,
828
+ competitors: (c.competitors || c.Competitors || []).map((comp) => ({
829
+ author: comp.author ?? comp.Author,
830
+ resultText: comp.resultText ?? comp.ResultText,
831
+ })),
832
+ }));
833
+ }
834
+ /**
835
+ * Consolidate several reviewers' edits against a shared base DOCX and return the
836
+ * merged revision list — each revision carrying its author, block anchors, and
837
+ * (when contested) the {@link DocxDiffConsolidatedRevision.conflictId} linking it
838
+ * to a {@link DocxDiffConflict}.
839
+ *
840
+ * @param base - The shared base document all reviewers edited from.
841
+ * @param reviewers - The reviewers' edited copies + author names.
842
+ * @param settings - Optional {@link DocxDiffConsolidateSettings}; omit for engine defaults.
843
+ * @returns Array of {@link DocxDiffConsolidatedRevision}.
844
+ * @throws Error if the operation fails.
845
+ */
846
+ export async function docxDiffGetConsolidatedRevisions(base, reviewers, settings) {
847
+ const exports = ensureInitialized();
848
+ const baseBytes = await toBytes(base);
849
+ const reviewersJsonStr = await reviewersJson(reviewers);
850
+ await yieldToMain();
851
+ const result = exports.DocxDiffBridge.GetConsolidatedRevisionsJson(baseBytes, reviewersJsonStr, docxDiffConsolidateSettingsJson(settings));
852
+ if (isErrorResponse(result)) {
853
+ const error = parseError(result);
854
+ throw new Error(`Failed to get DocxDiff consolidated revisions: ${error.error}`);
855
+ }
856
+ const parsed = JSON.parse(result);
857
+ return (parsed.revisions || parsed.Revisions || []).map((r) => ({
858
+ ...mapDocxDiffRevision(r),
859
+ conflictId: r.conflictId ?? r.ConflictId ?? undefined,
860
+ }));
861
+ }
862
+ /**
863
+ * Consolidate several reviewers' edits against a shared base DOCX and return the
864
+ * merged edit script as a JSON string — the diff-as-data view of the
865
+ * consolidation (the anchor-addressed list of composite block operations).
866
+ *
867
+ * @param base - The shared base document all reviewers edited from.
868
+ * @param reviewers - The reviewers' edited copies + author names.
869
+ * @param settings - Optional {@link DocxDiffConsolidateSettings}; omit for engine defaults.
870
+ * @returns The consolidated edit script serialized as indented JSON.
871
+ * @throws Error if the operation fails.
872
+ */
873
+ export async function docxDiffGetConsolidatedEditScript(base, reviewers, settings) {
874
+ const exports = ensureInitialized();
875
+ const baseBytes = await toBytes(base);
876
+ const reviewersJsonStr = await reviewersJson(reviewers);
877
+ await yieldToMain();
878
+ const result = exports.DocxDiffBridge.GetConsolidatedEditScriptJson(baseBytes, reviewersJsonStr, docxDiffConsolidateSettingsJson(settings));
879
+ if (isErrorResponse(result)) {
880
+ const error = parseError(result);
881
+ throw new Error(`Failed to get DocxDiff consolidated edit script: ${error.error}`);
882
+ }
883
+ return result;
884
+ }
885
+ /**
886
+ * Get version information about the library.
887
+ */
888
+ export function getVersion() {
889
+ const exports = ensureInitialized();
890
+ const result = exports.DocumentConverter.GetVersion();
891
+ const parsed = JSON.parse(result);
892
+ return {
893
+ library: parsed.Library || parsed.library,
894
+ dotnetVersion: parsed.DotnetVersion || parsed.dotnetVersion,
895
+ platform: parsed.Platform || parsed.platform,
896
+ };
897
+ }
898
+ /**
899
+ * Check if the WASM runtime is initialized.
900
+ */
901
+ export function isInitialized() {
902
+ return wasmExports !== null;
903
+ }
904
+ /**
905
+ * The raw WASM bridge exports (DocumentConverter, DocxSessionBridge, ...).
906
+ *
907
+ * For consumers that drive a bridge class directly — most notably
908
+ * `DocxEditor.open(container, bytes, exports)`, which needs the exports object
909
+ * rather than the wrapped functions in this module. Requires `initialize()` to
910
+ * have completed; throws otherwise.
911
+ */
912
+ export function getWasmExports() {
913
+ return ensureInitialized();
914
+ }
915
+ /**
916
+ * Get all annotations from a document.
917
+ *
918
+ * @param document - DOCX file as File object or Uint8Array
919
+ * @returns Array of annotations
920
+ * @throws Error if operation fails
921
+ *
922
+ * @example
923
+ * ```typescript
924
+ * const annotations = await getAnnotations(docxFile);
925
+ * for (const annot of annotations) {
926
+ * console.log(`${annot.label}: "${annot.annotatedText}"`);
927
+ * }
928
+ * ```
929
+ */
930
+ export async function getAnnotations(document) {
931
+ const exports = ensureInitialized();
932
+ const bytes = await toBytes(document);
933
+ const result = exports.DocumentConverter.GetAnnotations(bytes);
934
+ if (isErrorResponse(result)) {
935
+ const error = parseError(result);
936
+ throw new Error(`Failed to get annotations: ${error.error}`);
937
+ }
938
+ const parsed = JSON.parse(result);
939
+ return (parsed.Annotations || parsed.annotations || []).map((a) => ({
940
+ id: a.Id || a.id,
941
+ labelId: a.LabelId || a.labelId,
942
+ label: a.Label || a.label,
943
+ color: a.Color || a.color,
944
+ author: a.Author || a.author,
945
+ created: a.Created || a.created,
946
+ bookmarkName: a.BookmarkName || a.bookmarkName,
947
+ startPage: a.StartPage ?? a.startPage,
948
+ endPage: a.EndPage ?? a.endPage,
949
+ annotatedText: a.AnnotatedText || a.annotatedText,
950
+ metadata: a.Metadata || a.metadata,
951
+ }));
952
+ }
953
+ /**
954
+ * Add an annotation to a document.
955
+ *
956
+ * @param document - DOCX file as File object or Uint8Array
957
+ * @param request - Annotation details including search text or paragraph indices
958
+ * @returns Response with modified document bytes and annotation info
959
+ * @throws Error if operation fails
960
+ *
961
+ * @example
962
+ * ```typescript
963
+ * // Annotate by searching for text
964
+ * const result = await addAnnotation(docxFile, {
965
+ * id: "annot-1",
966
+ * labelId: "CLAUSE_A",
967
+ * label: "Important Clause",
968
+ * color: "#FFEB3B",
969
+ * searchText: "shall not be liable",
970
+ * occurrence: 1
971
+ * });
972
+ *
973
+ * // Annotate by paragraph range
974
+ * const result = await addAnnotation(docxFile, {
975
+ * id: "annot-2",
976
+ * labelId: "SECTION_1",
977
+ * label: "Introduction",
978
+ * color: "#4CAF50",
979
+ * startParagraphIndex: 0,
980
+ * endParagraphIndex: 2
981
+ * });
982
+ *
983
+ * // Get modified document
984
+ * const modifiedDocBytes = base64ToBytes(result.documentBytes);
985
+ * ```
986
+ */
987
+ export async function addAnnotation(document, request) {
988
+ const exports = ensureInitialized();
989
+ const bytes = await toBytes(document);
990
+ // Yield to browser before WASM work - allows loading states to render
991
+ await yieldToMain();
992
+ const requestJson = JSON.stringify({
993
+ Id: request.id,
994
+ LabelId: request.labelId,
995
+ Label: request.label,
996
+ Color: request.color ?? "#FFEB3B",
997
+ Author: request.author,
998
+ SearchText: request.searchText,
999
+ Occurrence: request.occurrence ?? 1,
1000
+ StartParagraphIndex: request.startParagraphIndex,
1001
+ EndParagraphIndex: request.endParagraphIndex,
1002
+ Metadata: request.metadata,
1003
+ });
1004
+ const result = exports.DocumentConverter.AddAnnotation(bytes, requestJson);
1005
+ if (isErrorResponse(result)) {
1006
+ const error = parseError(result);
1007
+ throw new Error(`Failed to add annotation: ${error.error}`);
1008
+ }
1009
+ const parsed = JSON.parse(result);
1010
+ const annotation = parsed.Annotation || parsed.annotation;
1011
+ return {
1012
+ success: parsed.Success ?? parsed.success ?? true,
1013
+ documentBytes: parsed.DocumentBytes || parsed.documentBytes,
1014
+ annotation: annotation ? {
1015
+ id: annotation.Id || annotation.id,
1016
+ labelId: annotation.LabelId || annotation.labelId,
1017
+ label: annotation.Label || annotation.label,
1018
+ color: annotation.Color || annotation.color,
1019
+ author: annotation.Author || annotation.author,
1020
+ created: annotation.Created || annotation.created,
1021
+ bookmarkName: annotation.BookmarkName || annotation.bookmarkName,
1022
+ annotatedText: annotation.AnnotatedText || annotation.annotatedText,
1023
+ } : undefined,
1024
+ };
1025
+ }
1026
+ /**
1027
+ * Remove an annotation from a document.
1028
+ *
1029
+ * @param document - DOCX file as File object or Uint8Array
1030
+ * @param annotationId - The ID of the annotation to remove
1031
+ * @returns Response with modified document bytes
1032
+ * @throws Error if operation fails
1033
+ *
1034
+ * @example
1035
+ * ```typescript
1036
+ * const result = await removeAnnotation(docxFile, "annot-1");
1037
+ * const modifiedDocBytes = base64ToBytes(result.documentBytes);
1038
+ * ```
1039
+ */
1040
+ export async function removeAnnotation(document, annotationId) {
1041
+ const exports = ensureInitialized();
1042
+ const bytes = await toBytes(document);
1043
+ const result = exports.DocumentConverter.RemoveAnnotation(bytes, annotationId);
1044
+ if (isErrorResponse(result)) {
1045
+ const error = parseError(result);
1046
+ throw new Error(`Failed to remove annotation: ${error.error}`);
1047
+ }
1048
+ const parsed = JSON.parse(result);
1049
+ return {
1050
+ success: parsed.Success ?? parsed.success ?? true,
1051
+ documentBytes: parsed.DocumentBytes || parsed.documentBytes,
1052
+ };
1053
+ }
1054
+ /**
1055
+ * Check if a document has any annotations.
1056
+ *
1057
+ * @param document - DOCX file as File object or Uint8Array
1058
+ * @returns true if the document has annotations
1059
+ * @throws Error if operation fails
1060
+ *
1061
+ * @example
1062
+ * ```typescript
1063
+ * if (await hasAnnotations(docxFile)) {
1064
+ * const annotations = await getAnnotations(docxFile);
1065
+ * console.log(`Document has ${annotations.length} annotations`);
1066
+ * }
1067
+ * ```
1068
+ */
1069
+ export async function hasAnnotations(document) {
1070
+ const exports = ensureInitialized();
1071
+ const bytes = await toBytes(document);
1072
+ const result = exports.DocumentConverter.HasAnnotations(bytes);
1073
+ if (isErrorResponse(result)) {
1074
+ const error = parseError(result);
1075
+ throw new Error(`Failed to check annotations: ${error.error}`);
1076
+ }
1077
+ const parsed = JSON.parse(result);
1078
+ return parsed.HasAnnotations ?? parsed.hasAnnotations ?? false;
1079
+ }
1080
+ /**
1081
+ * Get the document structure for element-based annotation targeting.
1082
+ *
1083
+ * @param document - DOCX file as File object or Uint8Array
1084
+ * @returns Document structure with element tree
1085
+ * @throws Error if operation fails
1086
+ *
1087
+ * @example
1088
+ * ```typescript
1089
+ * const structure = await getDocumentStructure(docxFile);
1090
+ *
1091
+ * // Navigate the structure tree
1092
+ * console.log(`Document has ${structure.root.children.length} top-level elements`);
1093
+ *
1094
+ * // Find all paragraphs
1095
+ * const paragraphs = getParagraphs(structure);
1096
+ * console.log(`Found ${paragraphs.length} paragraphs`);
1097
+ *
1098
+ * // Find all tables
1099
+ * const tables = getTables(structure);
1100
+ * for (const table of tables) {
1101
+ * const columns = getTableColumns(structure, table.id);
1102
+ * console.log(`Table ${table.id} has ${columns.length} columns`);
1103
+ * }
1104
+ *
1105
+ * // Look up element by ID
1106
+ * const element = findElementById(structure, "doc/p-0");
1107
+ * if (element) {
1108
+ * console.log(`First paragraph: "${element.textPreview}"`);
1109
+ * }
1110
+ * ```
1111
+ */
1112
+ export async function getDocumentStructure(document) {
1113
+ const exports = ensureInitialized();
1114
+ const bytes = await toBytes(document);
1115
+ // Yield to browser before WASM work - allows loading states to render
1116
+ await yieldToMain();
1117
+ const result = exports.DocumentConverter.GetDocumentStructure(bytes);
1118
+ if (isErrorResponse(result)) {
1119
+ const error = parseError(result);
1120
+ throw new Error(`Failed to get document structure: ${error.error}`);
1121
+ }
1122
+ const parsed = JSON.parse(result);
1123
+ // Convert from PascalCase to camelCase
1124
+ const convertElement = (el) => ({
1125
+ id: el.Id || el.id,
1126
+ anchorId: el.AnchorId || el.anchorId,
1127
+ type: el.Type || el.type,
1128
+ textPreview: el.TextPreview || el.textPreview,
1129
+ index: el.Index ?? el.index,
1130
+ rowIndex: el.RowIndex ?? el.rowIndex,
1131
+ columnIndex: el.ColumnIndex ?? el.columnIndex,
1132
+ rowSpan: el.RowSpan ?? el.rowSpan,
1133
+ columnSpan: el.ColumnSpan ?? el.columnSpan,
1134
+ children: (el.Children || el.children || []).map(convertElement),
1135
+ });
1136
+ const convertTableColumn = (col) => ({
1137
+ tableId: col.TableId || col.tableId,
1138
+ anchorId: col.AnchorId || col.anchorId,
1139
+ tableAnchorId: col.TableAnchorId || col.tableAnchorId,
1140
+ isVirtual: col.IsVirtual ?? col.isVirtual ?? false,
1141
+ columnIndex: col.ColumnIndex ?? col.columnIndex,
1142
+ cellIds: col.CellIds || col.cellIds || [],
1143
+ cellAnchorIds: col.CellAnchorIds || col.cellAnchorIds || [],
1144
+ rowCount: col.RowCount ?? col.rowCount,
1145
+ });
1146
+ const root = convertElement(parsed.Root || parsed.root);
1147
+ // Convert elementsById dictionary
1148
+ const elementsById = {};
1149
+ const rawElementsById = parsed.ElementsById || parsed.elementsById || {};
1150
+ for (const [key, el] of Object.entries(rawElementsById)) {
1151
+ elementsById[key] = convertElement(el);
1152
+ }
1153
+ // Convert tableColumns dictionary
1154
+ const tableColumns = {};
1155
+ const rawTableColumns = parsed.TableColumns || parsed.tableColumns || {};
1156
+ for (const [key, col] of Object.entries(rawTableColumns)) {
1157
+ tableColumns[key] = convertTableColumn(col);
1158
+ }
1159
+ return {
1160
+ root,
1161
+ elementsById,
1162
+ tableColumns,
1163
+ };
1164
+ }
1165
+ /**
1166
+ * Get document metadata for lazy loading pagination.
1167
+ * This is a fast operation that extracts structure information without full HTML rendering.
1168
+ *
1169
+ * @param document - DOCX file as File object or Uint8Array
1170
+ * @returns Document metadata including sections, dimensions, and content counts
1171
+ * @throws Error if operation fails
1172
+ *
1173
+ * @example
1174
+ * ```typescript
1175
+ * const metadata = await getDocumentMetadata(docxFile);
1176
+ *
1177
+ * // Check document overview
1178
+ * console.log(`Document has ${metadata.totalParagraphs} paragraphs`);
1179
+ * console.log(`Document has ${metadata.sections.length} sections`);
1180
+ * console.log(`Estimated ${metadata.estimatedPageCount} pages`);
1181
+ *
1182
+ * // Check section properties
1183
+ * for (const section of metadata.sections) {
1184
+ * console.log(`Section ${section.sectionIndex}: ${section.pageWidthPt}x${section.pageHeightPt}pt`);
1185
+ * console.log(` Paragraphs: ${section.paragraphCount}, Tables: ${section.tableCount}`);
1186
+ * console.log(` Has header: ${section.hasHeader}, Has footer: ${section.hasFooter}`);
1187
+ * }
1188
+ *
1189
+ * // Check document features
1190
+ * if (metadata.hasTrackedChanges) {
1191
+ * console.log("Document has tracked changes");
1192
+ * }
1193
+ * if (metadata.hasFootnotes) {
1194
+ * console.log("Document has footnotes");
1195
+ * }
1196
+ * ```
1197
+ */
1198
+ export async function getDocumentMetadata(document) {
1199
+ const exports = ensureInitialized();
1200
+ const bytes = await toBytes(document);
1201
+ // Yield to browser before WASM work - allows loading states to render
1202
+ await yieldToMain();
1203
+ const result = exports.DocumentConverter.GetDocumentMetadata(bytes);
1204
+ if (isErrorResponse(result)) {
1205
+ const error = parseError(result);
1206
+ throw new Error(`Failed to get document metadata: ${error.error}`);
1207
+ }
1208
+ const parsed = JSON.parse(result);
1209
+ // Convert from PascalCase to camelCase
1210
+ const convertSection = (s) => ({
1211
+ sectionIndex: s.SectionIndex ?? s.sectionIndex,
1212
+ pageWidthPt: s.PageWidthPt ?? s.pageWidthPt,
1213
+ pageHeightPt: s.PageHeightPt ?? s.pageHeightPt,
1214
+ marginTopPt: s.MarginTopPt ?? s.marginTopPt,
1215
+ marginRightPt: s.MarginRightPt ?? s.marginRightPt,
1216
+ marginBottomPt: s.MarginBottomPt ?? s.marginBottomPt,
1217
+ marginLeftPt: s.MarginLeftPt ?? s.marginLeftPt,
1218
+ contentWidthPt: s.ContentWidthPt ?? s.contentWidthPt,
1219
+ contentHeightPt: s.ContentHeightPt ?? s.contentHeightPt,
1220
+ headerPt: s.HeaderPt ?? s.headerPt,
1221
+ footerPt: s.FooterPt ?? s.footerPt,
1222
+ paragraphCount: s.ParagraphCount ?? s.paragraphCount,
1223
+ tableCount: s.TableCount ?? s.tableCount,
1224
+ hasHeader: s.HasHeader ?? s.hasHeader,
1225
+ hasFooter: s.HasFooter ?? s.hasFooter,
1226
+ hasFirstPageHeader: s.HasFirstPageHeader ?? s.hasFirstPageHeader,
1227
+ hasFirstPageFooter: s.HasFirstPageFooter ?? s.hasFirstPageFooter,
1228
+ hasEvenPageHeader: s.HasEvenPageHeader ?? s.hasEvenPageHeader,
1229
+ hasEvenPageFooter: s.HasEvenPageFooter ?? s.hasEvenPageFooter,
1230
+ startParagraphIndex: s.StartParagraphIndex ?? s.startParagraphIndex,
1231
+ endParagraphIndex: s.EndParagraphIndex ?? s.endParagraphIndex,
1232
+ startTableIndex: s.StartTableIndex ?? s.startTableIndex,
1233
+ endTableIndex: s.EndTableIndex ?? s.endTableIndex,
1234
+ });
1235
+ return {
1236
+ sections: (parsed.Sections || parsed.sections || []).map(convertSection),
1237
+ totalParagraphs: parsed.TotalParagraphs ?? parsed.totalParagraphs,
1238
+ totalTables: parsed.TotalTables ?? parsed.totalTables,
1239
+ hasFootnotes: parsed.HasFootnotes ?? parsed.hasFootnotes,
1240
+ hasEndnotes: parsed.HasEndnotes ?? parsed.hasEndnotes,
1241
+ hasTrackedChanges: parsed.HasTrackedChanges ?? parsed.hasTrackedChanges,
1242
+ hasComments: parsed.HasComments ?? parsed.hasComments,
1243
+ estimatedPageCount: parsed.EstimatedPageCount ?? parsed.estimatedPageCount,
1244
+ estimatedPageCountSource: parsed.EstimatedPageCountSource ?? parsed.estimatedPageCountSource ?? "heuristic",
1245
+ };
1246
+ }
1247
+ /**
1248
+ * Export document to OpenContracts format.
1249
+ *
1250
+ * This provides complete document text, structure, and layout information
1251
+ * compatible with the OpenContracts ecosystem for document analysis.
1252
+ *
1253
+ * @param document - DOCX file as File object or Uint8Array
1254
+ * @returns OpenContractDocExport with complete document data
1255
+ * @throws Error if export fails
1256
+ *
1257
+ * @example
1258
+ * ```typescript
1259
+ * const result = await exportToOpenContract(docxFile);
1260
+ *
1261
+ * // Access complete document text
1262
+ * console.log(`Content length: ${result.content.length} characters`);
1263
+ *
1264
+ * // Get document structure
1265
+ * console.log(`Pages: ${result.pageCount}`);
1266
+ * console.log(`Structural annotations: ${result.labelledText.filter(a => a.structural).length}`);
1267
+ *
1268
+ * // Access PAWLS layout data
1269
+ * for (const page of result.pawlsFileContent) {
1270
+ * console.log(`Page ${page.page.index}: ${page.tokens.length} tokens`);
1271
+ * }
1272
+ * ```
1273
+ */
1274
+ export async function exportToOpenContract(document) {
1275
+ const exports = ensureInitialized();
1276
+ const bytes = await toBytes(document);
1277
+ // Yield to browser before WASM work - allows loading states to render
1278
+ await yieldToMain();
1279
+ const result = exports.DocumentConverter.ExportToOpenContract(bytes);
1280
+ if (isErrorResponse(result)) {
1281
+ const error = parseError(result);
1282
+ throw new Error(`Failed to export to OpenContract format: ${error.error}`);
1283
+ }
1284
+ return readOpenContractExport(JSON.parse(result));
1285
+ }
1286
+ /**
1287
+ * Convert a DOCX file to an anchor-addressed Markdown projection.
1288
+ *
1289
+ * The projection is a deterministic, anchor-keyed Markdown rendering of the document,
1290
+ * suitable for LLM editing pipelines, structured search indexers, and diff/review UIs.
1291
+ * Every paragraph, heading, list item, table, table cell, footnote, endnote, and
1292
+ * comment is addressable by an `{#kind:scope:unid}` anchor that survives reformatting.
1293
+ *
1294
+ * See `docs/architecture/markdown_projection.md` for the projection spec.
1295
+ *
1296
+ * @param document - DOCX file as `File` or `Uint8Array`
1297
+ * @param settings - Optional projection settings (defaults: all scopes, anchor blocks, accept tracked changes)
1298
+ * @throws Error if conversion fails
1299
+ *
1300
+ * @example
1301
+ * ```typescript
1302
+ * const result = await convertWmlToMarkdown(docxFile);
1303
+ * console.log(result.markdown);
1304
+ * for (const [id, target] of Object.entries(result.anchorIndex)) {
1305
+ * console.log(id, target.partUri);
1306
+ * }
1307
+ * ```
1308
+ */
1309
+ export async function convertWmlToMarkdown(document, settings = {}) {
1310
+ const exports = ensureInitialized();
1311
+ const bytes = await toBytes(document);
1312
+ await yieldToMain();
1313
+ const settingsJson = JSON.stringify({
1314
+ Scopes: settings.scopes ?? ProjectionScopes.All,
1315
+ HeadingLevelOffset: settings.headingLevelOffset ?? 0,
1316
+ AnchorMode: settings.anchorMode ?? AnchorRenderMode.Block,
1317
+ TableMode: settings.tableMode ?? TableRenderMode.GfmWithOpaqueFallback,
1318
+ TableInlineCellMax: settings.tableInlineCellMax ?? 80,
1319
+ TrackedChanges: settings.trackedChanges ?? TrackedChangeMode.Accept,
1320
+ ResolveNumbering: settings.resolveNumbering ?? true,
1321
+ EmptyParagraphs: settings.emptyParagraphs ?? EmptyParagraphMode.AnchorOnly,
1322
+ });
1323
+ const result = exports.DocumentConverter.ConvertWmlToMarkdown(bytes, settingsJson);
1324
+ if (isErrorResponse(result)) {
1325
+ const error = parseError(result);
1326
+ throw new Error(`Failed to convert document to markdown: ${error.error}`);
1327
+ }
1328
+ const parsed = JSON.parse(result);
1329
+ const rawIndex = parsed.AnchorIndex ?? parsed.anchorIndex ?? {};
1330
+ const anchorIndex = {};
1331
+ for (const [key, value] of Object.entries(rawIndex)) {
1332
+ const v = value;
1333
+ anchorIndex[key] = {
1334
+ id: v.Id ?? v.id,
1335
+ kind: v.Kind ?? v.kind,
1336
+ scope: v.Scope ?? v.scope,
1337
+ unid: v.Unid ?? v.unid,
1338
+ partUri: v.PartUri ?? v.partUri,
1339
+ textPreview: v.TextPreview ?? v.textPreview ?? "",
1340
+ };
1341
+ }
1342
+ return {
1343
+ markdown: parsed.Markdown ?? parsed.markdown ?? "",
1344
+ anchorIndex,
1345
+ };
1346
+ }
1347
+ /**
1348
+ * Add an annotation using flexible targeting (element ID, indices, or text search).
1349
+ *
1350
+ * @param document - DOCX file as File object or Uint8Array
1351
+ * @param request - Annotation details with target specification
1352
+ * @returns Response with modified document bytes and annotation info
1353
+ * @throws Error if operation fails
1354
+ *
1355
+ * @example
1356
+ * ```typescript
1357
+ * // First get the document structure to find target elements
1358
+ * const structure = await getDocumentStructure(docxFile);
1359
+ *
1360
+ * // Annotate a specific paragraph by element ID
1361
+ * const result1 = await addAnnotationWithTarget(docxFile, {
1362
+ * id: "annot-1",
1363
+ * labelId: "INTRO",
1364
+ * label: "Introduction",
1365
+ * color: "#4CAF50",
1366
+ * target: targetElement("doc/p-0")
1367
+ * });
1368
+ *
1369
+ * // Annotate a table cell
1370
+ * const result2 = await addAnnotationWithTarget(docxFile, {
1371
+ * id: "annot-2",
1372
+ * labelId: "CELL_HIGHLIGHT",
1373
+ * label: "Important Cell",
1374
+ * color: "#FFEB3B",
1375
+ * target: targetTableCell(0, 1, 2) // Table 0, Row 1, Cell 2
1376
+ * });
1377
+ *
1378
+ * // Annotate a table column
1379
+ * const result3 = await addAnnotationWithTarget(docxFile, {
1380
+ * id: "annot-3",
1381
+ * labelId: "COLUMN_DATA",
1382
+ * label: "Values Column",
1383
+ * color: "#2196F3",
1384
+ * target: targetTableColumn(0, 1) // Table 0, Column 1
1385
+ * });
1386
+ *
1387
+ * // Search for text within a specific element
1388
+ * const result4 = await addAnnotationWithTarget(docxFile, {
1389
+ * id: "annot-4",
1390
+ * labelId: "KEYWORD",
1391
+ * label: "Keyword",
1392
+ * color: "#FF5722",
1393
+ * target: targetSearchInElement("doc/p-2", "important", 1)
1394
+ * });
1395
+ * ```
1396
+ */
1397
+ export async function addAnnotationWithTarget(document, request) {
1398
+ const exports = ensureInitialized();
1399
+ const bytes = await toBytes(document);
1400
+ // Yield to browser before WASM work - allows loading states to render
1401
+ await yieldToMain();
1402
+ const requestJson = JSON.stringify({
1403
+ Id: request.id,
1404
+ LabelId: request.labelId,
1405
+ Label: request.label,
1406
+ Color: request.color ?? "#FFEB3B",
1407
+ Author: request.author,
1408
+ Metadata: request.metadata,
1409
+ ElementId: request.target.elementId,
1410
+ ElementType: request.target.elementType,
1411
+ ParagraphIndex: request.target.paragraphIndex,
1412
+ RunIndex: request.target.runIndex,
1413
+ TableIndex: request.target.tableIndex,
1414
+ RowIndex: request.target.rowIndex,
1415
+ CellIndex: request.target.cellIndex,
1416
+ ColumnIndex: request.target.columnIndex,
1417
+ SearchText: request.target.searchText,
1418
+ Occurrence: request.target.occurrence ?? 1,
1419
+ RangeEndParagraphIndex: request.target.rangeEndParagraphIndex,
1420
+ });
1421
+ const result = exports.DocumentConverter.AddAnnotationWithTarget(bytes, requestJson);
1422
+ if (isErrorResponse(result)) {
1423
+ const error = parseError(result);
1424
+ throw new Error(`Failed to add annotation: ${error.error}`);
1425
+ }
1426
+ const parsed = JSON.parse(result);
1427
+ const annotation = parsed.Annotation || parsed.annotation;
1428
+ return {
1429
+ success: parsed.Success ?? parsed.success ?? true,
1430
+ documentBytes: parsed.DocumentBytes || parsed.documentBytes,
1431
+ annotation: annotation ? {
1432
+ id: annotation.Id || annotation.id,
1433
+ labelId: annotation.LabelId || annotation.labelId,
1434
+ label: annotation.Label || annotation.label,
1435
+ color: annotation.Color || annotation.color,
1436
+ author: annotation.Author || annotation.author,
1437
+ created: annotation.Created || annotation.created,
1438
+ bookmarkName: annotation.BookmarkName || annotation.bookmarkName,
1439
+ annotatedText: annotation.AnnotatedText || annotation.annotatedText,
1440
+ metadata: annotation.Metadata || annotation.metadata,
1441
+ } : undefined,
1442
+ };
1443
+ }
1444
+ // ============================================================================
1445
+ // External Annotation Functions (Issue #57)
1446
+ // ============================================================================
1447
+ /**
1448
+ * Compute the SHA256 hash of a document for integrity validation.
1449
+ *
1450
+ * @param document - DOCX file as File object or Uint8Array
1451
+ * @returns SHA256 hash as lowercase hex string
1452
+ * @throws Error if operation fails
1453
+ *
1454
+ * @example
1455
+ * ```typescript
1456
+ * const hash = await computeDocumentHash(docxFile);
1457
+ * console.log(`Document hash: ${hash}`);
1458
+ *
1459
+ * // Later, verify the document hasn't changed
1460
+ * const currentHash = await computeDocumentHash(docxFile);
1461
+ * if (currentHash !== storedHash) {
1462
+ * console.log("Document has been modified");
1463
+ * }
1464
+ * ```
1465
+ */
1466
+ export async function computeDocumentHash(document) {
1467
+ const exports = ensureInitialized();
1468
+ const bytes = await toBytes(document);
1469
+ const result = exports.DocumentConverter.ComputeDocumentHash(bytes);
1470
+ if (isErrorResponse(result)) {
1471
+ const error = parseError(result);
1472
+ throw new Error(`Failed to compute document hash: ${error.error}`);
1473
+ }
1474
+ const parsed = JSON.parse(result);
1475
+ return parsed.Hash ?? parsed.hash;
1476
+ }
1477
+ /**
1478
+ * Create an ExternalAnnotationSet from a document.
1479
+ * This extracts the document structure and computes the hash for integrity validation.
1480
+ *
1481
+ * @param document - DOCX file as File object or Uint8Array
1482
+ * @param documentId - Unique identifier for the document (filename, UUID, etc.)
1483
+ * @returns ExternalAnnotationSet ready for adding annotations
1484
+ * @throws Error if operation fails
1485
+ *
1486
+ * @example
1487
+ * ```typescript
1488
+ * // Create an annotation set
1489
+ * const set = await createExternalAnnotationSet(docxFile, "contract-v1.0");
1490
+ *
1491
+ * // Access document text for searching
1492
+ * console.log(`Document length: ${set.content.length} chars`);
1493
+ *
1494
+ * // Add label definitions
1495
+ * set.textLabels["IMPORTANT"] = {
1496
+ * id: "IMPORTANT",
1497
+ * text: "Important",
1498
+ * color: "#FF0000",
1499
+ * description: "Important text",
1500
+ * icon: "",
1501
+ * labelType: "text"
1502
+ * };
1503
+ *
1504
+ * // Create annotations using the content
1505
+ * const annotation = createAnnotationFromSearch(
1506
+ * "ann-001", "IMPORTANT", set.content, "shall not be liable"
1507
+ * );
1508
+ * if (annotation) {
1509
+ * set.labelledText.push(annotation);
1510
+ * }
1511
+ *
1512
+ * // Serialize for storage
1513
+ * const json = JSON.stringify(set);
1514
+ * ```
1515
+ */
1516
+ export async function createExternalAnnotationSet(document, documentId) {
1517
+ const exports = ensureInitialized();
1518
+ const bytes = await toBytes(document);
1519
+ // Yield to browser before WASM work - allows loading states to render
1520
+ await yieldToMain();
1521
+ const result = exports.DocumentConverter.CreateExternalAnnotationSet(bytes, documentId);
1522
+ if (isErrorResponse(result)) {
1523
+ const error = parseError(result);
1524
+ throw new Error(`Failed to create external annotation set: ${error.error}`);
1525
+ }
1526
+ return readExternalAnnotationSet(JSON.parse(result));
1527
+ }
1528
+ /**
1529
+ * Validate an external annotation set against a document.
1530
+ * Checks hash match and verifies each annotation's text still matches.
1531
+ *
1532
+ * @param document - DOCX file as File object or Uint8Array
1533
+ * @param annotationSet - The annotation set to validate
1534
+ * @returns Validation result with any issues found
1535
+ * @throws Error if operation fails
1536
+ *
1537
+ * @example
1538
+ * ```typescript
1539
+ * const result = await validateExternalAnnotations(docxFile, annotationSet);
1540
+ *
1541
+ * if (!result.isValid) {
1542
+ * if (result.hashMismatch) {
1543
+ * console.log("Document has been modified since annotations were created");
1544
+ * }
1545
+ * for (const issue of result.issues) {
1546
+ * console.log(`${issue.issueType}: ${issue.description}`);
1547
+ * }
1548
+ * }
1549
+ * ```
1550
+ */
1551
+ export async function validateExternalAnnotations(document, annotationSet) {
1552
+ const exports = ensureInitialized();
1553
+ const bytes = await toBytes(document);
1554
+ // Yield to browser before WASM work - allows loading states to render
1555
+ await yieldToMain();
1556
+ const annotationSetJson = JSON.stringify(annotationSet);
1557
+ const result = exports.DocumentConverter.ValidateExternalAnnotations(bytes, annotationSetJson);
1558
+ if (isErrorResponse(result)) {
1559
+ const error = parseError(result);
1560
+ throw new Error(`Failed to validate external annotations: ${error.error}`);
1561
+ }
1562
+ return readExternalAnnotationValidation(JSON.parse(result));
1563
+ }
1564
+ /**
1565
+ * Convert a DOCX document to HTML with external annotations projected.
1566
+ *
1567
+ * @param document - DOCX file as File object or Uint8Array
1568
+ * @param annotationSet - The external annotation set to project
1569
+ * @param conversionOptions - HTML conversion options
1570
+ * @param projectionOptions - Annotation projection options
1571
+ * @returns HTML string with annotations projected
1572
+ * @throws Error if operation fails
1573
+ *
1574
+ * @example
1575
+ * ```typescript
1576
+ * // Basic usage
1577
+ * const html = await convertDocxToHtmlWithExternalAnnotations(
1578
+ * docxFile,
1579
+ * annotationSet
1580
+ * );
1581
+ *
1582
+ * // With custom options
1583
+ * const html = await convertDocxToHtmlWithExternalAnnotations(
1584
+ * docxFile,
1585
+ * annotationSet,
1586
+ * { pageTitle: "Annotated Document" },
1587
+ * { labelMode: AnnotationLabelMode.Inline, cssClassPrefix: "my-annot-" }
1588
+ * );
1589
+ * ```
1590
+ */
1591
+ export async function convertDocxToHtmlWithExternalAnnotations(document, annotationSet, conversionOptions, projectionOptions) {
1592
+ const exports = ensureInitialized();
1593
+ const bytes = await toBytes(document);
1594
+ // Yield to browser before WASM work - allows loading states to render
1595
+ await yieldToMain();
1596
+ const annotationSetJson = JSON.stringify(annotationSet);
1597
+ const result = exports.DocumentConverter.ConvertDocxToHtmlWithExternalAnnotations(bytes, annotationSetJson, conversionOptions?.pageTitle ?? "Document", conversionOptions?.cssPrefix ?? "docx-", conversionOptions?.fabricateClasses ?? true, conversionOptions?.additionalCss ?? "", projectionOptions?.cssClassPrefix ?? "ext-annot-", projectionOptions?.labelMode ?? AnnotationLabelMode.Above);
1598
+ if (isErrorResponse(result)) {
1599
+ const error = parseError(result);
1600
+ throw new Error(`Failed to convert with external annotations: ${error.error}`);
1601
+ }
1602
+ return readProjectedHtml(JSON.parse(result));
1603
+ }
1604
+ /**
1605
+ * Search for text in a document and return character offsets.
1606
+ * Useful for finding text locations to create annotations.
1607
+ *
1608
+ * @param document - DOCX file as File object or Uint8Array
1609
+ * @param searchText - Text to search for
1610
+ * @param maxResults - Maximum number of results (default: 100)
1611
+ * @returns Array of TextSpan objects with offsets
1612
+ * @throws Error if operation fails
1613
+ *
1614
+ * @example
1615
+ * ```typescript
1616
+ * const occurrences = await searchTextOffsets(docxFile, "liability");
1617
+ * console.log(`Found ${occurrences.length} occurrences`);
1618
+ *
1619
+ * for (const span of occurrences) {
1620
+ * console.log(`"${span.text}" at offset ${span.start}-${span.end}`);
1621
+ * }
1622
+ * ```
1623
+ */
1624
+ export async function searchTextOffsets(document, searchText, maxResults = 100) {
1625
+ const exports = ensureInitialized();
1626
+ const bytes = await toBytes(document);
1627
+ // Yield to browser before WASM work - allows loading states to render
1628
+ await yieldToMain();
1629
+ const result = exports.DocumentConverter.SearchTextOffsets(bytes, searchText, maxResults);
1630
+ if (isErrorResponse(result)) {
1631
+ const error = parseError(result);
1632
+ throw new Error(`Failed to search text: ${error.error}`);
1633
+ }
1634
+ const parsed = JSON.parse(result);
1635
+ return (parsed.Results || parsed.results || []).map((r) => ({
1636
+ id: r.Id ?? r.id,
1637
+ start: r.Start ?? r.start,
1638
+ end: r.End ?? r.end,
1639
+ text: r.Text ?? r.text,
1640
+ }));
1641
+ }
1642
+ /**
1643
+ * Create an annotation from character offsets.
1644
+ * This is a client-side helper - no WASM call needed.
1645
+ *
1646
+ * @param id - Unique identifier for the annotation
1647
+ * @param labelId - Label/category ID for the annotation
1648
+ * @param documentText - Full document text (from annotationSet.content)
1649
+ * @param startOffset - Start character offset (0-indexed, inclusive)
1650
+ * @param endOffset - End character offset (exclusive)
1651
+ * @returns OpenContractsAnnotation ready to add to an annotation set
1652
+ * @throws Error if offsets are invalid
1653
+ *
1654
+ * @example
1655
+ * ```typescript
1656
+ * const set = await createExternalAnnotationSet(docxFile, "doc-1");
1657
+ * const annotation = createAnnotation("ann-001", "IMPORTANT", set.content, 100, 150);
1658
+ * set.labelledText.push(annotation);
1659
+ * ```
1660
+ */
1661
+ export function createAnnotation(id, labelId, documentText, startOffset, endOffset) {
1662
+ if (startOffset < 0) {
1663
+ throw new Error("Start offset must be non-negative");
1664
+ }
1665
+ if (endOffset < startOffset) {
1666
+ throw new Error("End offset must be >= start offset");
1667
+ }
1668
+ if (endOffset > documentText.length) {
1669
+ throw new Error("End offset exceeds document length");
1670
+ }
1671
+ const rawText = documentText.substring(startOffset, endOffset);
1672
+ return {
1673
+ id,
1674
+ annotationLabel: labelId,
1675
+ rawText,
1676
+ page: 0,
1677
+ annotationJson: {
1678
+ id,
1679
+ start: startOffset,
1680
+ end: endOffset,
1681
+ text: rawText,
1682
+ },
1683
+ annotationType: "text",
1684
+ structural: false,
1685
+ };
1686
+ }
1687
+ /**
1688
+ * Create an annotation by searching for text in the document.
1689
+ * This is a client-side helper - no WASM call needed.
1690
+ *
1691
+ * @param id - Unique identifier for the annotation
1692
+ * @param labelId - Label/category ID for the annotation
1693
+ * @param documentText - Full document text (from annotationSet.content)
1694
+ * @param searchText - Text to search for
1695
+ * @param occurrence - Which occurrence to use (1-based, default: 1)
1696
+ * @returns OpenContractsAnnotation, or null if text not found
1697
+ *
1698
+ * @example
1699
+ * ```typescript
1700
+ * const set = await createExternalAnnotationSet(docxFile, "doc-1");
1701
+ *
1702
+ * // Find first occurrence
1703
+ * const ann1 = createAnnotationFromSearch("ann-001", "LIABILITY", set.content, "shall not be liable");
1704
+ * if (ann1) set.labelledText.push(ann1);
1705
+ *
1706
+ * // Find second occurrence
1707
+ * const ann2 = createAnnotationFromSearch("ann-002", "LIABILITY", set.content, "shall not be liable", 2);
1708
+ * if (ann2) set.labelledText.push(ann2);
1709
+ * ```
1710
+ */
1711
+ export function createAnnotationFromSearch(id, labelId, documentText, searchText, occurrence = 1) {
1712
+ if (occurrence < 1) {
1713
+ throw new Error("Occurrence must be >= 1");
1714
+ }
1715
+ const offsets = findTextOccurrences(documentText, searchText);
1716
+ if (occurrence > offsets.length) {
1717
+ return null;
1718
+ }
1719
+ const { start, end } = offsets[occurrence - 1];
1720
+ return createAnnotation(id, labelId, documentText, start, end);
1721
+ }
1722
+ /**
1723
+ * Find all occurrences of a text string in the document.
1724
+ * This is a client-side helper - no WASM call needed.
1725
+ *
1726
+ * @param documentText - Full document text
1727
+ * @param searchText - Text to search for
1728
+ * @param maxResults - Maximum number of results (default: 100)
1729
+ * @returns Array of { start, end } offsets
1730
+ *
1731
+ * @example
1732
+ * ```typescript
1733
+ * const occurrences = findTextOccurrences(set.content, "the");
1734
+ * console.log(`Found ${occurrences.length} occurrences of "the"`);
1735
+ * ```
1736
+ */
1737
+ export function findTextOccurrences(documentText, searchText, maxResults = 100) {
1738
+ if (!searchText)
1739
+ return [];
1740
+ const results = [];
1741
+ let index = 0;
1742
+ while (results.length < maxResults) {
1743
+ index = documentText.indexOf(searchText, index);
1744
+ if (index < 0)
1745
+ break;
1746
+ results.push({ start: index, end: index + searchText.length });
1747
+ index += 1; // Move past start to find overlapping matches
1748
+ }
1749
+ return results;
1750
+ }
1751
+ // Helper function to convert PascalCase response to camelCase ExternalAnnotationSet
1752
+ // ============================================================================
1753
+ // Incremental Annotation Overlay API (Issue #106)
1754
+ // ============================================================================
1755
+ /**
1756
+ * Project external annotations onto already-converted HTML.
1757
+ * This avoids full DOCX re-conversion when only annotations change.
1758
+ *
1759
+ * Workflow:
1760
+ * 1. Convert DOCX to HTML once using `convertDocxToHtml()`
1761
+ * 2. Use this function to overlay annotations on the cached HTML
1762
+ * 3. When annotations change, call this again with the same base HTML
1763
+ *
1764
+ * @param html - HTML string (previously converted via convertDocxToHtml)
1765
+ * @param annotationSet - The external annotation set to project
1766
+ * @param projectionOptions - Projection settings (CSS prefix, label mode, etc.)
1767
+ * @returns HTML string with annotations projected
1768
+ * @throws Error if projection fails
1769
+ *
1770
+ * @example
1771
+ * ```typescript
1772
+ * // Step 1: Convert once
1773
+ * const baseHtml = await convertDocxToHtml(docxFile);
1774
+ *
1775
+ * // Step 2: Project annotations (fast, no DOCX re-conversion)
1776
+ * const annotatedHtml = await projectAnnotationsOntoHtml(baseHtml, annotationSet);
1777
+ *
1778
+ * // Step 3: When annotations change, project again on the same base HTML
1779
+ * annotationSet.labelledText.push(newAnnotation);
1780
+ * const updatedHtml = await projectAnnotationsOntoHtml(baseHtml, annotationSet);
1781
+ * ```
1782
+ */
1783
+ export async function projectAnnotationsOntoHtml(html, annotationSet, projectionOptions) {
1784
+ const exports = ensureInitialized();
1785
+ await yieldToMain();
1786
+ const annotationSetJson = JSON.stringify(annotationSet);
1787
+ const result = exports.DocumentConverter.ProjectAnnotationsOntoHtml(html, annotationSetJson, projectionOptions?.cssClassPrefix ?? "ext-annot-", projectionOptions?.labelMode ?? AnnotationLabelMode.Above);
1788
+ if (isErrorResponse(result)) {
1789
+ const error = parseError(result);
1790
+ throw new Error(`Failed to project annotations: ${error.error}`);
1791
+ }
1792
+ return readProjectedHtml(JSON.parse(result));
1793
+ }
1794
+ /**
1795
+ * Add a single annotation to existing HTML without re-converting the document.
1796
+ * This is the fastest way to add one annotation to already-rendered HTML.
1797
+ *
1798
+ * @param html - HTML string (with or without existing annotations)
1799
+ * @param annotation - The annotation to add
1800
+ * @param label - Label definition for the annotation (optional, for color/text)
1801
+ * @param projectionOptions - Projection settings
1802
+ * @returns HTML string with the annotation added
1803
+ * @throws Error if operation fails
1804
+ *
1805
+ * @example
1806
+ * ```typescript
1807
+ * const annotation = createAnnotation("ann-new", "CLAUSE", set.content, 100, 150);
1808
+ * const label = { id: "CLAUSE", text: "Clause", color: "#FF5722" };
1809
+ * const updatedHtml = await addAnnotationToHtml(currentHtml, annotation, label);
1810
+ * ```
1811
+ */
1812
+ export async function addAnnotationToHtml(html, annotation, label, projectionOptions) {
1813
+ const exports = ensureInitialized();
1814
+ await yieldToMain();
1815
+ const annotationJson = JSON.stringify(annotation);
1816
+ const labelJson = label ? JSON.stringify(label) : "";
1817
+ const result = exports.DocumentConverter.AddAnnotationToHtml(html, annotationJson, labelJson, projectionOptions?.cssClassPrefix ?? "ext-annot-", projectionOptions?.labelMode ?? AnnotationLabelMode.Above);
1818
+ if (isErrorResponse(result)) {
1819
+ const error = parseError(result);
1820
+ throw new Error(`Failed to add annotation to HTML: ${error.error}`);
1821
+ }
1822
+ return readProjectedHtml(JSON.parse(result));
1823
+ }
1824
+ /**
1825
+ * Remove a single annotation from HTML by annotation ID.
1826
+ * Unwraps annotation spans back to plain text.
1827
+ *
1828
+ * @param html - HTML string with annotations
1829
+ * @param annotationId - ID of the annotation to remove
1830
+ * @param cssClassPrefix - CSS class prefix used for annotations (default: "ext-annot-")
1831
+ * @returns HTML string with the annotation removed
1832
+ * @throws Error if operation fails
1833
+ *
1834
+ * @example
1835
+ * ```typescript
1836
+ * const updatedHtml = await removeAnnotationFromHtml(currentHtml, "ann-001");
1837
+ * ```
1838
+ */
1839
+ export async function removeAnnotationFromHtml(html, annotationId, cssClassPrefix) {
1840
+ const exports = ensureInitialized();
1841
+ await yieldToMain();
1842
+ const result = exports.DocumentConverter.RemoveAnnotationFromHtml(html, annotationId, cssClassPrefix ?? "ext-annot-");
1843
+ if (isErrorResponse(result)) {
1844
+ const error = parseError(result);
1845
+ throw new Error(`Failed to remove annotation from HTML: ${error.error}`);
1846
+ }
1847
+ return readProjectedHtml(JSON.parse(result));
1848
+ }
1849
+ /**
1850
+ * Generate CSS to hide annotations with specific label IDs.
1851
+ * Enables CSS-based label filtering without re-rendering HTML.
1852
+ *
1853
+ * Apply the returned CSS to your document (e.g., via a `<style>` element)
1854
+ * to hide/show annotations by label. This is much faster than re-projecting
1855
+ * all annotations.
1856
+ *
1857
+ * @param hiddenLabelIds - Array of label IDs to hide
1858
+ * @param cssClassPrefix - CSS class prefix (default: "ext-annot-")
1859
+ * @returns CSS string that hides the specified labels
1860
+ * @throws Error if operation fails
1861
+ *
1862
+ * @example
1863
+ * ```typescript
1864
+ * // Hide annotations with label "DRAFT" and "INTERNAL"
1865
+ * const css = await generateAnnotationVisibilityCss(["DRAFT", "INTERNAL"]);
1866
+ *
1867
+ * // Apply to a <style> element in the DOM
1868
+ * const styleEl = document.getElementById("visibility-overrides");
1869
+ * styleEl.textContent = css;
1870
+ *
1871
+ * // To show all annotations again, clear the style:
1872
+ * styleEl.textContent = "";
1873
+ * ```
1874
+ */
1875
+ export async function generateAnnotationVisibilityCss(hiddenLabelIds, cssClassPrefix) {
1876
+ const exports = ensureInitialized();
1877
+ await yieldToMain();
1878
+ const result = exports.DocumentConverter.GenerateAnnotationVisibilityCss(JSON.stringify(hiddenLabelIds), cssClassPrefix ?? "ext-annot-");
1879
+ if (isErrorResponse(result)) {
1880
+ const error = parseError(result);
1881
+ throw new Error(`Failed to generate visibility CSS: ${error.error}`);
1882
+ }
1883
+ const parsed = JSON.parse(result);
1884
+ return parsed.Css ?? parsed.css;
1885
+ }
1886
+ /**
1887
+ * Generate annotation CSS for a set of labels.
1888
+ * Useful when managing CSS separately from HTML content.
1889
+ *
1890
+ * @param labels - Label definitions (keyed by label ID)
1891
+ * @param projectionOptions - Projection settings
1892
+ * @returns CSS string for the annotation styles
1893
+ * @throws Error if operation fails
1894
+ *
1895
+ * @example
1896
+ * ```typescript
1897
+ * const labels = {
1898
+ * "CLAUSE": { id: "CLAUSE", text: "Clause", color: "#FF5722" },
1899
+ * "TERM": { id: "TERM", text: "Term", color: "#2196F3" },
1900
+ * };
1901
+ * const css = await generateAnnotationCss(labels);
1902
+ * ```
1903
+ */
1904
+ export async function generateAnnotationCss(labels, projectionOptions) {
1905
+ const exports = ensureInitialized();
1906
+ await yieldToMain();
1907
+ const result = exports.DocumentConverter.GenerateAnnotationCss(JSON.stringify(labels), projectionOptions?.cssClassPrefix ?? "ext-annot-", projectionOptions?.labelMode ?? AnnotationLabelMode.Above);
1908
+ if (isErrorResponse(result)) {
1909
+ const error = parseError(result);
1910
+ throw new Error(`Failed to generate annotation CSS: ${error.error}`);
1911
+ }
1912
+ const parsed = JSON.parse(result);
1913
+ return parsed.Css ?? parsed.css;
1914
+ }
1915
+ //# sourceMappingURL=core.js.map