import type { ConversionOptions, CompareOptions, Revision, VersionInfo, ErrorResponse, CompareResult, DocxodusWasmExports, GetRevisionsOptions, FormatChangeDetails, DocxDiffSettings, DocxDiffRevision, DocxDiffReviewer, DocxDiffConsolidateSettings, DocxDiffConflict, DocxDiffConflictCompetitor, DocxDiffConsolidatedRevision, Annotation, AddAnnotationRequest, AddAnnotationResponse, RemoveAnnotationResponse, AnnotationOptions, DocumentStructure, DocumentElement, TableColumnInfo, AnnotationTarget, AddAnnotationWithTargetRequest, DocumentMetadata, SectionMetadata, OpenContractDocExport, PawlsPage, PawlsPageBoundary, PawlsToken, OpenContractsAnnotation, OpenContractsSinglePageAnnotation, BoundingBox, TokenId, TextSpan, OpenContractsRelationship, AnnotationLabel, ExternalAnnotationSet, ExternalAnnotationValidationResult, ExternalAnnotationValidationIssue, ExternalAnnotationProjectionSettings, ComparisonLogEntry, CompareResultWithLog, CompareToHtmlResultWithLog, MarkdownProjectionSettings, MarkdownAnchorTarget, MarkdownProjection, DocxSessionSettings } from "./types.js"; import { DocxSession } from "./session.js"; export { DocxSession } from "./session.js"; export type { AnchorInfo, AnchorRef, AnchorTargetRef, BlockMetadata, CharSpan, CommentListEntry, DocumentAnnotation, DocxSessionProjection, DocxSessionSettings, EditError, EditErrorCode, EditResult, FindOptions, FormatOp, LineSpacingRule, ListMembership, MarkdownPatch, NumberFormat, PageNumberField, PageNumberingOp, ParagraphBorderEdge, ParagraphFormatOp, RevisionListEntry, SectionInfo, SessionRevisionType, TableBorderScope, TableBorderSpec, TableInsertOptions, TableMergeContent, TableShadingScope, } from "./types.js"; export type { FillOptions, BulkEditResult } from "./types.js"; export { PlaceholderKinds, ContextBoundary } from "./types.js"; export { DiffFormat } from "./types.js"; export type { EditSummary, DiffEntry } from "./types.js"; /** * Open a {@link DocxSession} for surgical mutation of a DOCX. Requires * {@link initialize} to have been called and awaited. * * The returned session keeps the document in WASM memory; call * {@link DocxSession.close} when done. */ export declare function openDocxSession(bytes: Uint8Array, settings?: DocxSessionSettings): DocxSession; /** * Mint a complete, blank single-paragraph DOCX (Normal style, US-Letter section) as bytes — * a "New document" seed for editors that draft from scratch. Requires {@link initialize}. */ export declare function createBlankDocx(): Uint8Array; import { CommentRenderMode, PaginationMode, AnnotationLabelMode, RevisionType, ComparisonEngine, DocxDiffRevisionGranularity, DocxDiffFormatComparison, ConflictResolution, ProjectionScopes, AnchorRenderMode, TableRenderMode, TrackedChangeMode, EmptyParagraphMode, AnchorIdRendering, ProjectionDepth, DocumentElementType, ComparisonLogLevel, ComparisonLogCodes, isInsertion, isDeletion, isMove, isMoveSource, isMoveDestination, findMovePair, isFormatChange, findElementById, findElementsByType, getParagraphs, getTables, getTableColumns, targetElement, targetParagraph, targetParagraphRange, targetRun, targetTable, targetTableRow, targetTableCell, targetTableColumn, targetSearch, targetSearchInElement } from "./types.js"; export type { PageDimensions, MeasuredBlock, PageInfo, PaginationResult, PaginationOptions, } from "./pagination.js"; export { PaginationEngine, paginateHtml } from "./pagination.js"; export { DocxEditor } from "./editor.js"; export type { DocxEditorOptions, DocxEditorExports } from "./editor.js"; export { mountRibbon } from "./ribbon.js"; export type { RibbonEditor, RibbonOptions, RibbonChromeMode, RibbonState, RibbonLoader, RibbonLoaderOptions, RibbonLoaderStage, RibbonLoaderFeature, } from "./ribbon.js"; export type { ConversionOptions, CompareOptions, Revision, VersionInfo, ErrorResponse, CompareResult, GetRevisionsOptions, FormatChangeDetails, Annotation, AddAnnotationRequest, AddAnnotationResponse, RemoveAnnotationResponse, AnnotationOptions, DocumentStructure, DocumentElement, TableColumnInfo, AnnotationTarget, AddAnnotationWithTargetRequest, DocumentMetadata, SectionMetadata, OpenContractDocExport, PawlsPage, PawlsPageBoundary, PawlsToken, OpenContractsAnnotation, OpenContractsSinglePageAnnotation, BoundingBox, TokenId, TextSpan, OpenContractsRelationship, AnnotationLabel, ExternalAnnotationSet, ExternalAnnotationValidationResult, ExternalAnnotationValidationIssue, ExternalAnnotationProjectionSettings, ComparisonLogEntry, CompareResultWithLog, CompareToHtmlResultWithLog, MarkdownProjectionSettings, MarkdownAnchorTarget, MarkdownProjection, DocxDiffSettings, DocxDiffRevision, DocxDiffReviewer, DocxDiffConsolidateSettings, DocxDiffConflict, DocxDiffConflictCompetitor, DocxDiffConsolidatedRevision, }; export { CommentRenderMode, PaginationMode, AnnotationLabelMode, RevisionType, ComparisonEngine, DocxDiffRevisionGranularity, DocxDiffFormatComparison, ConflictResolution, ProjectionScopes, AnchorRenderMode, TableRenderMode, TrackedChangeMode, EmptyParagraphMode, AnchorIdRendering, ProjectionDepth, DocumentElementType, ComparisonLogLevel, ComparisonLogCodes, isInsertion, isDeletion, isMove, isMoveSource, isMoveDestination, findMovePair, isFormatChange, findElementById, findElementsByType, getParagraphs, getTables, getTableColumns, targetElement, targetParagraph, targetParagraphRange, targetRun, targetTable, targetTableRow, targetTableCell, targetTableColumn, targetSearch, targetSearchInElement, }; /** * Current base path for WASM files. * Empty string means auto-detect from module URL. */ export declare let wasmBasePath: string; /** * Set custom base path for WASM files. * Pass empty string or don't call this to auto-detect from module location. * * @param path - Custom path to WASM files, or empty string for auto-detection */ export declare function setWasmBasePath(path: string): void; /** * Initialize the Docxodus WASM runtime. * Must be called before using any conversion/comparison functions. * Safe to call multiple times - will only initialize once. * * By default, WASM files are auto-detected from the module's location * (works with CDN, npm, or local hosting). * Pass a basePath to load from a custom location instead. * * @param basePath - Optional custom path to WASM files. Leave empty for auto-detection. */ export declare function initialize(basePath?: string): Promise; /** * Convert a DOCX document to HTML. * * @param document - DOCX file as File object or Uint8Array * @param options - Conversion options * @returns HTML string * @throws Error if conversion fails * * @example * ```typescript * // Basic conversion * const html = await convertDocxToHtml(docxFile); * * // With pagination (PDF.js-style page view) * const html = await convertDocxToHtml(docxFile, { * paginationMode: PaginationMode.Paginated, * paginationScale: 0.8 * }); * * // With annotations rendered * const html = await convertDocxToHtml(docxFile, { * renderAnnotations: true, * annotationLabelMode: AnnotationLabelMode.Above * }); * * // With footnotes and endnotes * const html = await convertDocxToHtml(docxFile, { * renderFootnotesAndEndnotes: true * }); * * // With headers and footers * const html = await convertDocxToHtml(docxFile, { * renderHeadersAndFooters: true * }); * * // With tracked changes (redlines visible) * const html = await convertDocxToHtml(docxFile, { * renderTrackedChanges: true, * showDeletedContent: true, * renderMoveOperations: true * }); * ``` */ /** * Render a single document block to faithful HTML, addressed by its anchor. * * The anchor is the `data-anchor` value stamped on a block during a full * conversion (a bare 32-hex Unid), or a full `kind:scope:unid` anchor — either * form works. Powers the editor's incremental per-block re-render: apply an edit * to a DocxSession, then re-render only the changed block instead of the whole * document. Returns the block's HTML element (no ``/`` wrapper). */ export declare function renderBlockHtml(document: File | Uint8Array, anchorId: string, options?: { cssPrefix?: string; fabricateClasses?: boolean; }): Promise; export declare function convertDocxToHtml(document: File | Uint8Array, options?: ConversionOptions): Promise; /** * Compare two DOCX documents and return the redlined result as a DOCX. * * @param original - Original DOCX document * @param modified - Modified DOCX document * @param options - Comparison options * @returns Redlined DOCX as Uint8Array * @throws Error if comparison fails */ export declare function compareDocuments(original: File | Uint8Array, modified: File | Uint8Array, options?: CompareOptions): Promise; /** * Compare two DOCX documents and return the result as HTML. * * @param original - Original DOCX document * @param modified - Modified DOCX document * @param options - Comparison options * @returns HTML string with redlined content * @throws Error if comparison fails */ export declare function compareDocumentsToHtml(original: File | Uint8Array, modified: File | Uint8Array, options?: CompareOptions): Promise; /** * Compare two DOCX documents with logging enabled. * Returns both the redlined document and a log of any warnings/errors encountered. * This allows the comparison to continue past recoverable issues (like orphaned footnotes) * while providing visibility into what was fixed or skipped. * * @param original - Original DOCX document * @param modified - Modified DOCX document * @param options - Comparison options * @returns Result with document bytes and log entries * * @example * ```typescript * const result = await compareDocumentsWithLog(original, modified, { * authorName: "Reviewer", * detailThreshold: 0.15 * }); * * if (result.success) { * // Use result.document (Uint8Array) * if (result.hasWarnings) { * console.log("Warnings during comparison:"); * for (const entry of result.log) { * console.log(` [${entry.level}] ${entry.code}: ${entry.message}`); * } * } * } else { * console.error(`Comparison failed: ${result.error}`); * } * ``` */ export declare function compareDocumentsWithLog(original: File | Uint8Array, modified: File | Uint8Array, options?: CompareOptions): Promise; /** * Compare two DOCX documents to HTML with logging enabled. * Returns both the HTML output and a log of any warnings/errors encountered. * * @param original - Original DOCX document * @param modified - Modified DOCX document * @param options - Comparison options * @returns Result with HTML and log entries * * @example * ```typescript * const result = await compareDocumentsToHtmlWithLog(original, modified, { * authorName: "Reviewer", * renderTrackedChanges: true * }); * * if (result.success) { * document.getElementById("viewer").innerHTML = result.html; * if (result.hasWarnings) { * console.log(`${result.log.length} warnings during comparison`); * } * } * ``` */ export declare function compareDocumentsToHtmlWithLog(original: File | Uint8Array, modified: File | Uint8Array, options?: CompareOptions): Promise; /** * Get revisions from a compared document. * * @param document - A document that has been through comparison (has tracked changes) * @param options - Optional move detection configuration * @returns Array of revisions * @throws Error if operation fails * * @example * ```typescript * // Default settings (move detection enabled, 80% threshold) * const revisions = await getRevisions(comparedDoc); * * // Custom move detection settings * const revisions = await getRevisions(comparedDoc, { * detectMoves: true, * moveSimilarityThreshold: 0.9, // Require 90% word overlap * moveMinimumWordCount: 5, // Only consider phrases of 5+ words * caseInsensitive: true // Ignore case when matching * }); * * // Disable move detection entirely * const revisions = await getRevisions(comparedDoc, { detectMoves: false }); * ``` */ export declare function getRevisions(document: File | Uint8Array, options?: GetRevisionsOptions): Promise; /** * Compare two DOCX documents with the IR diff engine and return the redlined * result as a DOCX (native w:ins/w:del/w:moveFrom/w:moveTo/w:rPrChange markup). * * @param left - The earlier/original document. * @param right - The later/revised document. * @param settings - Optional {@link DocxDiffSettings}; omit for engine defaults. * @returns Redlined DOCX as Uint8Array. * @throws Error if comparison fails. */ export declare function docxDiffCompare(left: File | Uint8Array, right: File | Uint8Array, settings?: DocxDiffSettings): Promise; /** * Compare two DOCX documents with the IR diff engine and return the * anchor-addressed revision list. * * @param left - The earlier/original document. * @param right - The later/revised document. * @param settings - Optional {@link DocxDiffSettings}; omit for engine defaults. * @returns Array of {@link DocxDiffRevision} (each carrying its left/right block anchors). * @throws Error if the operation fails. */ export declare function docxDiffGetRevisions(left: File | Uint8Array, right: File | Uint8Array, settings?: DocxDiffSettings): Promise; /** * Compare two DOCX documents with the IR diff engine and return the edit script * as a JSON string — the diff-as-data differentiator. The script is the * anchor-addressed list of block operations the markup and revision renderers * both consume: stable and machine-readable for storage, transport, and audit. * * @param left - The earlier/original document. * @param right - The later/revised document. * @param settings - Optional {@link DocxDiffSettings}; omit for engine defaults. * @returns The edit script serialized as indented JSON. * @throws Error if the operation fails. */ export declare function docxDiffGetEditScript(left: File | Uint8Array, right: File | Uint8Array, settings?: DocxDiffSettings): Promise; /** * Accept every tracked revision in a redlined DOCX and return the resulting bytes * (materializes the "right"/revised side). The byte-in, byte-out counterpart of * {@link docxDiffCompare}: `docxDiffAcceptRevisions(await docxDiffCompare(left, right))` * equals `right` at the per-block text level — so callers can verify the round-trip * contract of a redline, not just inspect its shape. * * @param redline - A DOCX carrying tracked-changes markup (e.g. {@link docxDiffCompare} output). * @returns The DOCX bytes with all revisions accepted. * @throws Error if the operation fails. */ export declare function docxDiffAcceptRevisions(redline: File | Uint8Array): Promise; /** * Reject every tracked revision in a redlined DOCX and return the resulting bytes * (materializes the "left"/original side): `docxDiffRejectRevisions(await * docxDiffCompare(left, right))` equals `left` at the per-block text level. * * @param redline - A DOCX carrying tracked-changes markup (e.g. {@link docxDiffCompare} output). * @returns The DOCX bytes with all revisions rejected. * @throws Error if the operation fails. */ export declare function docxDiffRejectRevisions(redline: File | Uint8Array): Promise; /** * Consolidate several reviewers' edits against a shared base DOCX and return the * merged redlined result as a DOCX (native multi-author tracked-changes markup). * * @param base - The shared base document all reviewers edited from. * @param reviewers - The reviewers' edited copies + author names. * @param settings - Optional {@link DocxDiffConsolidateSettings}; omit for engine defaults. * @returns Consolidated redlined DOCX as Uint8Array. * @throws Error if consolidation fails. */ export declare function docxDiffConsolidate(base: File | Uint8Array, reviewers: DocxDiffReviewer[], settings?: DocxDiffConsolidateSettings): Promise; /** * Consolidate several reviewers' edits against a shared base DOCX and return the * per-token conflict report — every base span two or more reviewers edited * incompatibly, with each reviewer's competing variant. * * @param base - The shared base document all reviewers edited from. * @param reviewers - The reviewers' edited copies + author names. * @param settings - Optional {@link DocxDiffConsolidateSettings}; omit for engine defaults. * @returns Array of {@link DocxDiffConflict}. * @throws Error if the operation fails. */ export declare function docxDiffGetConflicts(base: File | Uint8Array, reviewers: DocxDiffReviewer[], settings?: DocxDiffConsolidateSettings): Promise; /** * Consolidate several reviewers' edits against a shared base DOCX and return the * merged revision list — each revision carrying its author, block anchors, and * (when contested) the {@link DocxDiffConsolidatedRevision.conflictId} linking it * to a {@link DocxDiffConflict}. * * @param base - The shared base document all reviewers edited from. * @param reviewers - The reviewers' edited copies + author names. * @param settings - Optional {@link DocxDiffConsolidateSettings}; omit for engine defaults. * @returns Array of {@link DocxDiffConsolidatedRevision}. * @throws Error if the operation fails. */ export declare function docxDiffGetConsolidatedRevisions(base: File | Uint8Array, reviewers: DocxDiffReviewer[], settings?: DocxDiffConsolidateSettings): Promise; /** * Consolidate several reviewers' edits against a shared base DOCX and return the * merged edit script as a JSON string — the diff-as-data view of the * consolidation (the anchor-addressed list of composite block operations). * * @param base - The shared base document all reviewers edited from. * @param reviewers - The reviewers' edited copies + author names. * @param settings - Optional {@link DocxDiffConsolidateSettings}; omit for engine defaults. * @returns The consolidated edit script serialized as indented JSON. * @throws Error if the operation fails. */ export declare function docxDiffGetConsolidatedEditScript(base: File | Uint8Array, reviewers: DocxDiffReviewer[], settings?: DocxDiffConsolidateSettings): Promise; /** * Get version information about the library. */ export declare function getVersion(): VersionInfo; /** * Check if the WASM runtime is initialized. */ export declare function isInitialized(): boolean; /** * The raw WASM bridge exports (DocumentConverter, DocxSessionBridge, ...). * * For consumers that drive a bridge class directly — most notably * `DocxEditor.open(container, bytes, exports)`, which needs the exports object * rather than the wrapped functions in this module. Requires `initialize()` to * have completed; throws otherwise. */ export declare function getWasmExports(): DocxodusWasmExports; /** * Get all annotations from a document. * * @param document - DOCX file as File object or Uint8Array * @returns Array of annotations * @throws Error if operation fails * * @example * ```typescript * const annotations = await getAnnotations(docxFile); * for (const annot of annotations) { * console.log(`${annot.label}: "${annot.annotatedText}"`); * } * ``` */ export declare function getAnnotations(document: File | Uint8Array): Promise; /** * Add an annotation to a document. * * @param document - DOCX file as File object or Uint8Array * @param request - Annotation details including search text or paragraph indices * @returns Response with modified document bytes and annotation info * @throws Error if operation fails * * @example * ```typescript * // Annotate by searching for text * const result = await addAnnotation(docxFile, { * id: "annot-1", * labelId: "CLAUSE_A", * label: "Important Clause", * color: "#FFEB3B", * searchText: "shall not be liable", * occurrence: 1 * }); * * // Annotate by paragraph range * const result = await addAnnotation(docxFile, { * id: "annot-2", * labelId: "SECTION_1", * label: "Introduction", * color: "#4CAF50", * startParagraphIndex: 0, * endParagraphIndex: 2 * }); * * // Get modified document * const modifiedDocBytes = base64ToBytes(result.documentBytes); * ``` */ export declare function addAnnotation(document: File | Uint8Array, request: AddAnnotationRequest): Promise; /** * Remove an annotation from a document. * * @param document - DOCX file as File object or Uint8Array * @param annotationId - The ID of the annotation to remove * @returns Response with modified document bytes * @throws Error if operation fails * * @example * ```typescript * const result = await removeAnnotation(docxFile, "annot-1"); * const modifiedDocBytes = base64ToBytes(result.documentBytes); * ``` */ export declare function removeAnnotation(document: File | Uint8Array, annotationId: string): Promise; /** * Check if a document has any annotations. * * @param document - DOCX file as File object or Uint8Array * @returns true if the document has annotations * @throws Error if operation fails * * @example * ```typescript * if (await hasAnnotations(docxFile)) { * const annotations = await getAnnotations(docxFile); * console.log(`Document has ${annotations.length} annotations`); * } * ``` */ export declare function hasAnnotations(document: File | Uint8Array): Promise; /** * Get the document structure for element-based annotation targeting. * * @param document - DOCX file as File object or Uint8Array * @returns Document structure with element tree * @throws Error if operation fails * * @example * ```typescript * const structure = await getDocumentStructure(docxFile); * * // Navigate the structure tree * console.log(`Document has ${structure.root.children.length} top-level elements`); * * // Find all paragraphs * const paragraphs = getParagraphs(structure); * console.log(`Found ${paragraphs.length} paragraphs`); * * // Find all tables * const tables = getTables(structure); * for (const table of tables) { * const columns = getTableColumns(structure, table.id); * console.log(`Table ${table.id} has ${columns.length} columns`); * } * * // Look up element by ID * const element = findElementById(structure, "doc/p-0"); * if (element) { * console.log(`First paragraph: "${element.textPreview}"`); * } * ``` */ export declare function getDocumentStructure(document: File | Uint8Array): Promise; /** * Get document metadata for lazy loading pagination. * This is a fast operation that extracts structure information without full HTML rendering. * * @param document - DOCX file as File object or Uint8Array * @returns Document metadata including sections, dimensions, and content counts * @throws Error if operation fails * * @example * ```typescript * const metadata = await getDocumentMetadata(docxFile); * * // Check document overview * console.log(`Document has ${metadata.totalParagraphs} paragraphs`); * console.log(`Document has ${metadata.sections.length} sections`); * console.log(`Estimated ${metadata.estimatedPageCount} pages`); * * // Check section properties * for (const section of metadata.sections) { * console.log(`Section ${section.sectionIndex}: ${section.pageWidthPt}x${section.pageHeightPt}pt`); * console.log(` Paragraphs: ${section.paragraphCount}, Tables: ${section.tableCount}`); * console.log(` Has header: ${section.hasHeader}, Has footer: ${section.hasFooter}`); * } * * // Check document features * if (metadata.hasTrackedChanges) { * console.log("Document has tracked changes"); * } * if (metadata.hasFootnotes) { * console.log("Document has footnotes"); * } * ``` */ export declare function getDocumentMetadata(document: File | Uint8Array): Promise; /** * Export document to OpenContracts format. * * This provides complete document text, structure, and layout information * compatible with the OpenContracts ecosystem for document analysis. * * @param document - DOCX file as File object or Uint8Array * @returns OpenContractDocExport with complete document data * @throws Error if export fails * * @example * ```typescript * const result = await exportToOpenContract(docxFile); * * // Access complete document text * console.log(`Content length: ${result.content.length} characters`); * * // Get document structure * console.log(`Pages: ${result.pageCount}`); * console.log(`Structural annotations: ${result.labelledText.filter(a => a.structural).length}`); * * // Access PAWLS layout data * for (const page of result.pawlsFileContent) { * console.log(`Page ${page.page.index}: ${page.tokens.length} tokens`); * } * ``` */ export declare function exportToOpenContract(document: File | Uint8Array): Promise; /** * Convert a DOCX file to an anchor-addressed Markdown projection. * * The projection is a deterministic, anchor-keyed Markdown rendering of the document, * suitable for LLM editing pipelines, structured search indexers, and diff/review UIs. * Every paragraph, heading, list item, table, table cell, footnote, endnote, and * comment is addressable by an `{#kind:scope:unid}` anchor that survives reformatting. * * See `docs/architecture/markdown_projection.md` for the projection spec. * * @param document - DOCX file as `File` or `Uint8Array` * @param settings - Optional projection settings (defaults: all scopes, anchor blocks, accept tracked changes) * @throws Error if conversion fails * * @example * ```typescript * const result = await convertWmlToMarkdown(docxFile); * console.log(result.markdown); * for (const [id, target] of Object.entries(result.anchorIndex)) { * console.log(id, target.partUri); * } * ``` */ export declare function convertWmlToMarkdown(document: File | Uint8Array, settings?: MarkdownProjectionSettings): Promise; /** * Add an annotation using flexible targeting (element ID, indices, or text search). * * @param document - DOCX file as File object or Uint8Array * @param request - Annotation details with target specification * @returns Response with modified document bytes and annotation info * @throws Error if operation fails * * @example * ```typescript * // First get the document structure to find target elements * const structure = await getDocumentStructure(docxFile); * * // Annotate a specific paragraph by element ID * const result1 = await addAnnotationWithTarget(docxFile, { * id: "annot-1", * labelId: "INTRO", * label: "Introduction", * color: "#4CAF50", * target: targetElement("doc/p-0") * }); * * // Annotate a table cell * const result2 = await addAnnotationWithTarget(docxFile, { * id: "annot-2", * labelId: "CELL_HIGHLIGHT", * label: "Important Cell", * color: "#FFEB3B", * target: targetTableCell(0, 1, 2) // Table 0, Row 1, Cell 2 * }); * * // Annotate a table column * const result3 = await addAnnotationWithTarget(docxFile, { * id: "annot-3", * labelId: "COLUMN_DATA", * label: "Values Column", * color: "#2196F3", * target: targetTableColumn(0, 1) // Table 0, Column 1 * }); * * // Search for text within a specific element * const result4 = await addAnnotationWithTarget(docxFile, { * id: "annot-4", * labelId: "KEYWORD", * label: "Keyword", * color: "#FF5722", * target: targetSearchInElement("doc/p-2", "important", 1) * }); * ``` */ export declare function addAnnotationWithTarget(document: File | Uint8Array, request: AddAnnotationWithTargetRequest): Promise; /** * Compute the SHA256 hash of a document for integrity validation. * * @param document - DOCX file as File object or Uint8Array * @returns SHA256 hash as lowercase hex string * @throws Error if operation fails * * @example * ```typescript * const hash = await computeDocumentHash(docxFile); * console.log(`Document hash: ${hash}`); * * // Later, verify the document hasn't changed * const currentHash = await computeDocumentHash(docxFile); * if (currentHash !== storedHash) { * console.log("Document has been modified"); * } * ``` */ export declare function computeDocumentHash(document: File | Uint8Array): Promise; /** * Create an ExternalAnnotationSet from a document. * This extracts the document structure and computes the hash for integrity validation. * * @param document - DOCX file as File object or Uint8Array * @param documentId - Unique identifier for the document (filename, UUID, etc.) * @returns ExternalAnnotationSet ready for adding annotations * @throws Error if operation fails * * @example * ```typescript * // Create an annotation set * const set = await createExternalAnnotationSet(docxFile, "contract-v1.0"); * * // Access document text for searching * console.log(`Document length: ${set.content.length} chars`); * * // Add label definitions * set.textLabels["IMPORTANT"] = { * id: "IMPORTANT", * text: "Important", * color: "#FF0000", * description: "Important text", * icon: "", * labelType: "text" * }; * * // Create annotations using the content * const annotation = createAnnotationFromSearch( * "ann-001", "IMPORTANT", set.content, "shall not be liable" * ); * if (annotation) { * set.labelledText.push(annotation); * } * * // Serialize for storage * const json = JSON.stringify(set); * ``` */ export declare function createExternalAnnotationSet(document: File | Uint8Array, documentId: string): Promise; /** * Validate an external annotation set against a document. * Checks hash match and verifies each annotation's text still matches. * * @param document - DOCX file as File object or Uint8Array * @param annotationSet - The annotation set to validate * @returns Validation result with any issues found * @throws Error if operation fails * * @example * ```typescript * const result = await validateExternalAnnotations(docxFile, annotationSet); * * if (!result.isValid) { * if (result.hashMismatch) { * console.log("Document has been modified since annotations were created"); * } * for (const issue of result.issues) { * console.log(`${issue.issueType}: ${issue.description}`); * } * } * ``` */ export declare function validateExternalAnnotations(document: File | Uint8Array, annotationSet: ExternalAnnotationSet): Promise; /** * Convert a DOCX document to HTML with external annotations projected. * * @param document - DOCX file as File object or Uint8Array * @param annotationSet - The external annotation set to project * @param conversionOptions - HTML conversion options * @param projectionOptions - Annotation projection options * @returns HTML string with annotations projected * @throws Error if operation fails * * @example * ```typescript * // Basic usage * const html = await convertDocxToHtmlWithExternalAnnotations( * docxFile, * annotationSet * ); * * // With custom options * const html = await convertDocxToHtmlWithExternalAnnotations( * docxFile, * annotationSet, * { pageTitle: "Annotated Document" }, * { labelMode: AnnotationLabelMode.Inline, cssClassPrefix: "my-annot-" } * ); * ``` */ export declare function convertDocxToHtmlWithExternalAnnotations(document: File | Uint8Array, annotationSet: ExternalAnnotationSet, conversionOptions?: ConversionOptions, projectionOptions?: ExternalAnnotationProjectionSettings): Promise; /** * Search for text in a document and return character offsets. * Useful for finding text locations to create annotations. * * @param document - DOCX file as File object or Uint8Array * @param searchText - Text to search for * @param maxResults - Maximum number of results (default: 100) * @returns Array of TextSpan objects with offsets * @throws Error if operation fails * * @example * ```typescript * const occurrences = await searchTextOffsets(docxFile, "liability"); * console.log(`Found ${occurrences.length} occurrences`); * * for (const span of occurrences) { * console.log(`"${span.text}" at offset ${span.start}-${span.end}`); * } * ``` */ export declare function searchTextOffsets(document: File | Uint8Array, searchText: string, maxResults?: number): Promise; /** * Create an annotation from character offsets. * This is a client-side helper - no WASM call needed. * * @param id - Unique identifier for the annotation * @param labelId - Label/category ID for the annotation * @param documentText - Full document text (from annotationSet.content) * @param startOffset - Start character offset (0-indexed, inclusive) * @param endOffset - End character offset (exclusive) * @returns OpenContractsAnnotation ready to add to an annotation set * @throws Error if offsets are invalid * * @example * ```typescript * const set = await createExternalAnnotationSet(docxFile, "doc-1"); * const annotation = createAnnotation("ann-001", "IMPORTANT", set.content, 100, 150); * set.labelledText.push(annotation); * ``` */ export declare function createAnnotation(id: string, labelId: string, documentText: string, startOffset: number, endOffset: number): OpenContractsAnnotation; /** * Create an annotation by searching for text in the document. * This is a client-side helper - no WASM call needed. * * @param id - Unique identifier for the annotation * @param labelId - Label/category ID for the annotation * @param documentText - Full document text (from annotationSet.content) * @param searchText - Text to search for * @param occurrence - Which occurrence to use (1-based, default: 1) * @returns OpenContractsAnnotation, or null if text not found * * @example * ```typescript * const set = await createExternalAnnotationSet(docxFile, "doc-1"); * * // Find first occurrence * const ann1 = createAnnotationFromSearch("ann-001", "LIABILITY", set.content, "shall not be liable"); * if (ann1) set.labelledText.push(ann1); * * // Find second occurrence * const ann2 = createAnnotationFromSearch("ann-002", "LIABILITY", set.content, "shall not be liable", 2); * if (ann2) set.labelledText.push(ann2); * ``` */ export declare function createAnnotationFromSearch(id: string, labelId: string, documentText: string, searchText: string, occurrence?: number): OpenContractsAnnotation | null; /** * Find all occurrences of a text string in the document. * This is a client-side helper - no WASM call needed. * * @param documentText - Full document text * @param searchText - Text to search for * @param maxResults - Maximum number of results (default: 100) * @returns Array of { start, end } offsets * * @example * ```typescript * const occurrences = findTextOccurrences(set.content, "the"); * console.log(`Found ${occurrences.length} occurrences of "the"`); * ``` */ export declare function findTextOccurrences(documentText: string, searchText: string, maxResults?: number): Array<{ start: number; end: number; }>; /** * Project external annotations onto already-converted HTML. * This avoids full DOCX re-conversion when only annotations change. * * Workflow: * 1. Convert DOCX to HTML once using `convertDocxToHtml()` * 2. Use this function to overlay annotations on the cached HTML * 3. When annotations change, call this again with the same base HTML * * @param html - HTML string (previously converted via convertDocxToHtml) * @param annotationSet - The external annotation set to project * @param projectionOptions - Projection settings (CSS prefix, label mode, etc.) * @returns HTML string with annotations projected * @throws Error if projection fails * * @example * ```typescript * // Step 1: Convert once * const baseHtml = await convertDocxToHtml(docxFile); * * // Step 2: Project annotations (fast, no DOCX re-conversion) * const annotatedHtml = await projectAnnotationsOntoHtml(baseHtml, annotationSet); * * // Step 3: When annotations change, project again on the same base HTML * annotationSet.labelledText.push(newAnnotation); * const updatedHtml = await projectAnnotationsOntoHtml(baseHtml, annotationSet); * ``` */ export declare function projectAnnotationsOntoHtml(html: string, annotationSet: ExternalAnnotationSet, projectionOptions?: ExternalAnnotationProjectionSettings): Promise; /** * Add a single annotation to existing HTML without re-converting the document. * This is the fastest way to add one annotation to already-rendered HTML. * * @param html - HTML string (with or without existing annotations) * @param annotation - The annotation to add * @param label - Label definition for the annotation (optional, for color/text) * @param projectionOptions - Projection settings * @returns HTML string with the annotation added * @throws Error if operation fails * * @example * ```typescript * const annotation = createAnnotation("ann-new", "CLAUSE", set.content, 100, 150); * const label = { id: "CLAUSE", text: "Clause", color: "#FF5722" }; * const updatedHtml = await addAnnotationToHtml(currentHtml, annotation, label); * ``` */ export declare function addAnnotationToHtml(html: string, annotation: OpenContractsAnnotation, label?: AnnotationLabel, projectionOptions?: ExternalAnnotationProjectionSettings): Promise; /** * Remove a single annotation from HTML by annotation ID. * Unwraps annotation spans back to plain text. * * @param html - HTML string with annotations * @param annotationId - ID of the annotation to remove * @param cssClassPrefix - CSS class prefix used for annotations (default: "ext-annot-") * @returns HTML string with the annotation removed * @throws Error if operation fails * * @example * ```typescript * const updatedHtml = await removeAnnotationFromHtml(currentHtml, "ann-001"); * ``` */ export declare function removeAnnotationFromHtml(html: string, annotationId: string, cssClassPrefix?: string): Promise; /** * Generate CSS to hide annotations with specific label IDs. * Enables CSS-based label filtering without re-rendering HTML. * * Apply the returned CSS to your document (e.g., via a `