// This file is auto-generated by alef — DO NOT EDIT. // alef:hash:7e723dc88906267241296254002a983ed79eebe3ca5959fc6203f72917e562ce // To regenerate: alef generate // To verify freshness: alef verify /* eslint-disable */ export type JsonValue = string | number | boolean | null | JsonValue[] | { [key: string]: JsonValue }; /** * Classify a document's chunks and return the updated document. * * This owned form preserves the mutations when the document crosses a language-binding boundary. * Rust callers that already own a mutable document can use `classify_chunks` to avoid moving it. * @throws Returns the same validation and LLM errors as `classify_chunks`. */ export declare function classifyChunksOwned( config: ChunkClassificationConfig, result?: ExtractedDocument | undefined | null, ): Promise; /** * Clear all document extractors from the global registry. * * Calls `shutdown()` on every registered extractor, then empties the registry. * @throws - Any error returned by an extractor's `shutdown()` method. The first error * encountered stops processing of remaining extractors. */ export declare function clearDocumentExtractors(): void; /** * Clear all embedding backends from the global registry. * * Calls `shutdown()` on every registered backend, then empties the registry. * @throws - Any error returned by a backend's `shutdown()` method. The first error * encountered stops processing of remaining backends. */ export declare function clearEmbeddingBackends(): void; /** * Clear all OCR backends from the global registry. * * Removes all OCR backends and calls their `shutdown()` methods. * @returns - `Ok(())` if all backends were cleared successfully * - `Err(...)` if any shutdown method failed */ export declare function clearOcrBackends(): void; /** * Remove all registered post-processors. * * The next post-processed extraction restores enabled built-in processors before it snapshots * the processor cache. Custom processors remain removed. Use `unregister_post_processor` when * one named processor should remain absent while the rest of the registry stays intact. * Returns a retryable in-use error when an extraction is executing a processor snapshot. */ export declare function clearPostProcessors(): void; /** * Clear all renderers from the global registry. * * Removes every renderer, including the built-in defaults (markdown, html, * djot, plain). After calling this no renderers are registered; re-register * as needed. * @throws Returns an error if the registry lock is poisoned. */ export declare function clearRenderers(): void; /** * Clear all reranker backends from the global registry. * * Calls `shutdown()` on every registered backend, then empties the registry. * @throws - Any error returned by a backend's `shutdown()` method. The first error * encountered stops processing of remaining backends. */ export declare function clearRerankerBackends(): void; /** * Clear all tokenizer backends from the global registry. * * Calls `shutdown()` on every registered backend, then empties the registry. * @throws - Any error returned by a backend's `shutdown()` method. The first error * encountered stops processing of remaining backends. */ export declare function clearTokenizerBackends(): void; /** Remove all registered validators. */ export declare function clearValidators(): void; /** * Probe the backends and settings in `config` and report what will actually * execute on this host. * * Runs no downloads and no billable API calls. Backends that are not compiled * in or whose models are not cached report `Skip` rather than failing. */ export declare function doctor(config?: ExtractionConfig | undefined | null): DoctorReport; /** Extract content from a single bytes or URI input. */ export declare function extract( input?: ExtractInput | undefined | null, config?: ExtractionConfig | undefined | null, ): Promise; /** Extract content from multiple bytes or URI inputs. */ export declare function extractBatch( inputs: Array, config?: ExtractionConfig | undefined | null, ): Promise; /** * Find unmarked claims in markdown text. * * Returns lines that assert a claim but carry neither a footnote citation anchor (`[^...]`) * nor an inference marker (`[*inference*]`). * * The heuristic is simple: a line that contains alphabetic words, ends with sentence punctuation, * and is not a heading, blank line, or markup-only line is considered a claim. * Exclude lines that appear in the citation block (after `---` + ``). * @param markdown - The markdown text to search * * @returns A vector of trimmed line text strings for unmarked claims. */ export declare function findUnmarkedClaims(markdown: string): Array; /** * Hardware acceleration configuration for ONNX Runtime models. * * Controls which execution provider (CPU, CoreML, CUDA, TensorRT) is used * for inference in layout detection and embedding generation. */ export interface AccelerationConfig { /** Execution provider to use for ONNX inference. */ readonly provider?: ExecutionProviderType; /** GPU device ID (for CUDA/TensorRT). Ignored for CPU/CoreML/Auto. */ readonly deviceId?: number; } /** Types of inline text annotations. */ export type AnnotationKind = | { annotation_type: "bold" } | { annotation_type: "italic" } | { annotation_type: "underline" } | { annotation_type: "strikethrough" } | { annotation_type: "code" } | { annotation_type: "subscript" } | { annotation_type: "superscript" } | { annotation_type: "link"; url: string; title: string } | { annotation_type: "highlight" } | { annotation_type: "color"; value: string } | { annotation_type: "font_size"; value: string } | { annotation_type: "custom"; name: string; value: string }; /** * A single file extracted from an archive. * * When archives (ZIP, TAR, 7Z, GZIP) are extracted with recursive extraction * enabled, each processable file produces its own full `ExtractedDocument`. */ export interface ArchiveEntry { /** Archive-relative file path (e.g. "folder/document.pdf"). */ readonly path: string; /** Detected MIME type of the file. */ readonly mimeType: string; /** Full extraction result for this file. */ readonly result: ExtractedDocument; } /** * Archive (ZIP/TAR/7Z) metadata. * * Extracted from compressed archive files containing file lists and size information. */ export interface ArchiveMetadata { /** Archive format ("ZIP", "TAR", "7Z", etc.) */ readonly format?: string; /** Total number of files in the archive */ readonly fileCount?: number; /** List of file paths within the archive */ readonly fileList?: Array; /** Total uncompressed size in bytes */ readonly totalSize?: number; /** Compressed size in bytes (if available) */ readonly compressedSize?: number; } /** The category of a downloaded asset. */ export declare enum AssetCategory { /** A document file (PDF, DOC, etc.). */ Document = "document", /** An image file. */ Image = "image", /** An audio file. */ Audio = "audio", /** A video file. */ Video = "video", /** A font file. */ Font = "font", /** A CSS stylesheet. */ Stylesheet = "stylesheet", /** A JavaScript file. */ Script = "script", /** An archive file (ZIP, TAR, etc.). */ Archive = "archive", /** A data file (JSON, XML, CSV, etc.). */ Data = "data", /** An unrecognized asset type. */ Other = "other", } /** * Element attributes in Djot. * * Represents the attributes attached to elements using {.class #id key="value"} syntax. */ export interface Attributes { /** Element ID (#identifier) */ readonly id?: string; /** CSS classes (.class1 .class2) */ readonly classes?: Array; /** Key-value pairs (key="value") */ readonly keyValues?: Array; } /** * Audio/video file metadata. * * Populated from container tags (ID3v2, MP4 atoms, Vorbis comments, etc.) and * PCM decode properties. Available when the `transcription-types` feature is enabled. */ export interface AudioMetadata { /** Duration in milliseconds derived from the decoded audio stream. */ readonly durationMs?: number; /** Audio codec (e.g. "mp3", "aac", "opus", "flac"). */ readonly codec?: string; /** Container format (e.g. "mpeg", "mp4", "ogg", "wav"). */ readonly container?: string; /** Sample rate in Hz after decode (always 16000 when resampled for Whisper). */ readonly sampleRateHz?: number; /** Number of audio channels (1 = mono, 2 = stereo). */ readonly channels?: number; /** Audio bitrate in kbps from the source file tags/properties. */ readonly bitrate?: number; } /** Authentication configuration. */ export type AuthConfig = | { type: "basic"; username: string; password: string } | { type: "bearer"; token: string } | { type: "header"; name: string; value: string }; /** Bounding box in original image coordinates (x1, y1) top-left, (x2, y2) bottom-right. */ export interface BBox { /** Left edge (x-coordinate of the top-left corner). */ readonly x1: number; /** Top edge (y-coordinate of the top-left corner). */ readonly y1: number; /** Right edge (x-coordinate of the bottom-right corner). */ readonly x2: number; /** Bottom edge (y-coordinate of the bottom-right corner). */ readonly y2: number; } /** * AWS Bedrock configuration for `bedrock/`-prefixed models. * * Mirrors liter-llm's `BedrockConfig`. Every field is optional: anything left * unset falls back to the standard AWS environment variables * (`AWS_DEFAULT_REGION` / `AWS_REGION`, `AWS_ACCESS_KEY_ID`, * `AWS_SECRET_ACCESS_KEY`, `AWS_SESSION_TOKEN`, `BEDROCK_CROSS_REGION`) and the * default AWS credential chain. Leave the credential fields unset unless you * have an explicit reason to pin them. * @example * ```typescript * [ocr.vlm_config] * model = "bedrock/anthropic.claude-3-sonnet-20240229-v1:0" * * [ocr.vlm_config.bedrock] * region = "eu-central-1" * cross_region_prefix = "eu" * ``` * * `Debug` is implemented by hand so the three credential fields are never printed. */ export interface BedrockConfig { /** AWS region (e.g. `"us-east-1"`). */ readonly region?: string; /** Cross-region inference profile prefix (e.g. `"us"`). */ readonly crossRegionPrefix?: string; /** Explicit AWS access key ID. Secret — never logged. */ readonly accessKeyId?: string; /** Explicit AWS secret access key. Secret — never logged. */ readonly secretAccessKey?: string; /** Explicit AWS session token for temporary credentials. Secret — never logged. */ readonly sessionToken?: string; } /** BibTeX bibliography metadata. */ export interface BibtexMetadata { /** Number of entries in the bibliography. */ readonly entryCount?: number; /** BibTeX citation keys (e.g. `"knuth1984"`) for all entries. */ readonly citationKeys?: Array; /** Author names collected across all bibliography entries. */ readonly authors?: Array; /** Earliest and latest publication years found in the bibliography. */ readonly yearRange?: YearRange; /** Count of entries grouped by BibTeX entry type (e.g. `"article"` → 5). */ readonly entryTypes?: Record; } /** Types of block-level elements in Djot. */ export declare enum BlockType { /** Standard prose paragraph. */ Paragraph = "paragraph", /** Section heading (level stored in `FormattedBlock.level`). */ Heading = "heading", /** Block quotation container. */ Blockquote = "blockquote", /** Fenced or indented code block. */ CodeBlock = "code_block", /** Individual item within a list. */ ListItem = "list_item", /** Numbered (ordered) list container. */ OrderedList = "ordered_list", /** Unnumbered (bullet) list container. */ BulletList = "bullet_list", /** Task / checkbox list container. */ TaskList = "task_list", /** Definition list container. */ DefinitionList = "definition_list", /** Term part of a definition list entry. */ DefinitionTerm = "definition_term", /** Description / definition part of a definition list entry. */ DefinitionDescription = "definition_description", /** Generic `div` container with optional attributes. */ Div = "div", /** Logical section container, often associated with a heading. */ Section = "section", /** Horizontal rule / thematic break. */ ThematicBreak = "thematic_break", /** Raw content block in a specified format (e.g. HTML, LaTeX). */ RawBlock = "raw_block", /** Display-mode mathematical expression. */ MathDisplay = "math_display", } /** Reason for boundary detection. */ export declare enum BoundaryReason { /** Start of PDF. */ Start = "start", /** Page-one marker ("Page 1", "1 of N") detected. */ PageOneMarker = "page_one_marker", /** Letterhead reset after signature block. */ LetterheadReset = "letterhead_reset", /** Text density shift with low bigram overlap. */ DensityShift = "density_shift", /** End of PDF. */ End = "end", } /** Bounding box coordinates for element positioning. */ export interface BoundingBox { /** Left x-coordinate */ readonly x0?: number; /** Bottom y-coordinate */ readonly y0?: number; /** Right x-coordinate */ readonly x1?: number; /** Top y-coordinate */ readonly y1?: number; } /** Browser backend used for JavaScript rendering. */ export declare enum BrowserBackend { /** Existing Chromium/CDP backend powered by chromiumoxide. */ Chromiumoxide = "chromiumoxide", /** Crawlberg-owned native browser backend derived from Obscura. */ Native = "native", } /** Browser fallback configuration. */ export interface BrowserConfig { /** When to use the headless browser fallback. */ readonly mode?: BrowserMode; /** Browser backend used to render JavaScript-heavy pages. */ readonly backend?: BrowserBackend; /** CDP WebSocket endpoint for connecting to an external browser instance. */ readonly endpoint?: string; /** Timeout for browser page load and rendering (in milliseconds when serialized). */ readonly timeout?: number; /** Wait strategy after browser navigation. */ readonly wait?: BrowserWait; /** CSS selector to wait for when `wait` is `Selector`. */ readonly waitSelector?: string; /** Extra time to wait after the wait condition is met. */ readonly extraWait?: number; /** * Proxy for browser fetches. Overrides `CrawlConfig.proxy` when set. * Native backend supports http/https only (no SOCKS5). */ readonly proxy?: ProxyConfig; /** * URL patterns to block before the network request fires. Supports `*` * wildcards. Useful for skipping ads/analytics/large images. Honored by * `BrowserBackend.Native`; chromiumoxide ignores this field today. */ readonly blockUrlPatterns?: Array; /** * JavaScript snippet evaluated after navigation completes. * * Scraping captures the native backend result in `ScrapeResult.browser.eval_result`. * Interactions run this script before page actions on both browser backends but do * not include the script result in `InteractionResult`. */ readonly evalScript?: string; /** * User-agent used when fetching robots.txt. Defaults to `BrowserConfig.user_agent` * (or crawlberg's default) if unset. Native only. */ readonly robotsUserAgent?: string; /** * Capture the full network event stream into the result. Default false * (only the document event is captured). Native only. */ readonly captureNetworkEvents?: boolean; /** * Enable session affinity: reuse chromiumoxide Pages for same-domain * requests so cookies + fingerprint + solved challenges persist. * Default: true. When false, each request gets a fresh Page. */ readonly sessionAffinity?: boolean; } /** When to use the headless browser fallback. */ export declare enum BrowserMode { /** Automatically detect when JS rendering is needed and fall back to browser. */ Auto = "auto", /** Always use the browser for every request. */ Always = "always", /** Never use the browser fallback. */ Never = "never", /** * Always use the browser with all stealth surfaces enabled. * * Behaves like `Always` for escalation purposes * (every request is routed through the browser tier), but additionally * enables: * * - browser JavaScript stealth patches * - native-backend TLS fingerprint spoofing * - stealth-aware default user-agent when no explicit UA is set * - 1920×1080 viewport override * * Use this instead of setting the now-removed `BrowserConfig.stealth` * boolean field. */ Stealth = "stealth", } /** Wait strategy for browser page rendering. */ export declare enum BrowserWait { /** Wait until network activity is idle. */ NetworkIdle = "network_idle", /** Wait for a specific CSS selector to appear in the DOM. */ Selector = "selector", /** Wait for a fixed duration after navigation. */ Fixed = "fixed", } /** Aggregate statistics for a xberg cache directory. */ export interface CacheStats { /** Total number of files currently in the cache directory. */ readonly totalFiles: number; /** Combined size of all cache files in megabytes. */ readonly totalSizeMb: number; /** Free disk space available on the cache volume, in megabytes. */ readonly availableSpaceMb: number; /** Age of the oldest cache file in days (0.0 if the cache is empty). */ readonly oldestFileAgeDays: number; /** Age of the most recently written cache file in days (0.0 if the cache is empty). */ readonly newestFileAgeDays: number; } /** * How a structured-extraction preset is dispatched to the model. * * This is the preset-facing call mode (the `preferred_call_mode` field of a * `Preset`). The structured pipeline has a richer * runtime-only decision enum with skip and fallback states; this 3-variant * type is the stable, serializable surface presets and bindings depend on. */ export declare enum CallMode { /** Use the extracted text only. */ TextOnly = "text_only", /** Use rasterized page images only. */ VisionOnly = "vision_only", /** Provide both extracted text and page images to the model. */ TextPlusVision = "text_plus_vision", } /** Device selection shared by the typed candle backend option objects. */ export declare enum CandleDevicePreference { Auto = "auto", Cpu = "cpu", Cuda = "cuda", Metal = "metal", } /** TrOCR model variant accepted by `candle-trocr` backend options. */ export declare enum CandleTrocrVariant { BasePrinted = "base-printed", LargePrinted = "large-printed", BaseHandwritten = "base-handwritten", LargeHandwritten = "large-handwritten", } /** Configuration for the VLM captioning post-processor. */ export interface CaptioningConfig { /** LLM configuration used for the VLM call. */ readonly llm: LlmConfig; /** * Optional custom caption prompt. `None` uses the default `RegionKind.Caption` * prompt that ships with `crate.llm.region_extractor`. */ readonly prompt?: string; /** * Skip images whose `width * height` is below this threshold (in pixels). * Default `1_000` filters out icons and decorations. */ readonly minImageArea: number; } /** * A single changed cell within a table. * * Defined here (rather than only in `crate.diff`) so `RevisionDelta` can * reference it unconditionally, without requiring the `diff` Cargo feature. * `crate.diff` re-exports this type verbatim. */ export interface CellChange { /** Zero-based row index. */ readonly row: number; /** Zero-based column index. */ readonly col: number; /** Value before the change. */ readonly from: string; /** Value after the change. */ readonly to: string; } /** * A text chunk with optional embedding and metadata. * * Chunks are created when chunking is enabled in `ExtractionConfig`. Each chunk * contains the text content, optional embedding vector (if embedding generation * is configured), and metadata about its position in the document. */ export interface Chunk { /** The text content of this chunk. */ readonly content: string; /** * Semantic structural classification of this chunk. * * Assigned by the heuristic classifier based on content patterns and * heading context. Defaults to `ChunkType.Unknown` when no rule matches. */ readonly chunkType: ChunkType; /** * Optional embedding vector for this chunk. * * Only populated when `EmbeddingConfig` is provided in chunking configuration. * The dimensionality depends on the chosen embedding model. */ readonly embedding?: Array; /** * Optional sparse (SPLADE) learned embedding for this chunk. * * Only populated when sparse-embedding generation is configured for chunking. * `None` otherwise, including on builds without the `sparse-embeddings` feature. * * Uses the crate-root `SparseEmbedding` alias rather than * `crate.sparse_embeddings.SparseEmbedding` directly: the `sparse_embeddings` * module itself only compiles under `sparse-embeddings`/`sparse-embedding-presets`, * while the crate-root alias is always defined (a field-compatible stub on builds * without either feature), so this field — and `Chunk` itself — compiles on every * feature combination, including the crate's default features. */ readonly sparseEmbedding?: SparseEmbedding; /** * Optional ColBERT-style multi-vector (late-interaction) embedding for this chunk. * * Only populated when late-interaction embedding generation is configured for * chunking. `None` otherwise, including on builds without the `late-interaction` * feature. * * Uses the crate-root `MultiVectorEmbedding` alias for the same reason * `sparse_embedding` uses `SparseEmbedding` — see that field's docs. */ readonly lateInteraction?: MultiVectorEmbedding; /** Metadata about this chunk's position and properties. */ readonly metadata: ChunkMetadata; } /** * Configuration for the chunk-classification post-processor. * * Chunk classification is always multi-label: a chunk may match zero, one, or * many of the configured definitions. This is the chunk-level equivalent of * `PageClassificationConfig`, but scoped to individual chunks * (`ExtractedDocument.chunks`) rather than whole pages, and built for large * taxonomies where each label needs its own description rather than a bare name. */ export interface ChunkClassificationConfig { /** * Minijinja prompt template. Receives `{{ definitions }}` (rendered label + * description list) and `{{ chunks }}` (a numbered list of chunk texts in * the current batch) variables. `None` lets the backend pick a sensible * default. */ readonly promptTemplate?: string; /** * The set of label definitions the classifier may emit. Must contain at * least one entry. */ readonly definitions: Array; /** LLM configuration used for classification. */ readonly llm: LlmConfig; /** * Number of chunks batched into a single LLM request. * * Larger batches amortize the fixed prompt cost (definitions block) across * more chunks, at the risk of exceeding the model's context window for * very large taxonomies or chunk texts. Defaults to `DEFAULT_BATCH_SIZE`. */ readonly batchSize: number; /** * Maximum number of in-flight batch requests. * * Bounds concurrency against the configured LLM provider. Defaults to * `DEFAULT_MAX_CONCURRENCY`. */ readonly maxConcurrency: number; } /** * A single labeled definition the chunk classifier may emit. * * Unlike `PageClassificationConfig.labels` (bare label names), chunk * classification targets potentially large domain taxonomies where every * label carries its own semantic description, letting the LLM disambiguate * similarly named labels without relying on the label string alone. */ export interface ChunkClassificationDefinition { /** Label name returned in `ChunkMetadata.classifications`. */ readonly label: string; /** * Semantic description of when this label applies. Injected verbatim into * the classification prompt next to the label name. */ readonly description: string; } /** * Chunk-classification enrichment knob: how to multi-label individual chunks. * * Operates on `ExtractedDocument.chunks` in place — the caller must have * already produced chunks (e.g. via `ExtractionConfig.chunking`) for this * stage to have any effect; a document with no chunks is a no-op. */ export interface ChunkClassificationEnrichmentConfig { /** Label-definition set and LLM/batching settings for the chunk-classification stage. */ readonly config: ChunkClassificationConfig; } /** * Type of text chunker to use. * * # Variants * * * `Text` - Generic text splitter, splits on whitespace and punctuation * * `Markdown` - Markdown-aware splitter, preserves formatting and structure * * `Yaml` - YAML-aware splitter, creates one chunk per top-level key * * `Semantic` - Topic-aware chunker. With an `EmbeddingConfig`, splits at * embedding-based topic shifts tuned by `topic_threshold` (default 0.75, * lower = more splits). Without an embedding, falls back to a * structural-boundary heuristic (ALL-CAPS headers, numbered sections, * blank-line paragraphs) and merges groups into chunks capped at * `max_characters` (default 1000). `topic_threshold` has no effect in the * fallback path. For best results, pair with an embedding model. */ export declare enum ChunkerType { /** Generic whitespace- and punctuation-aware text splitter (default). */ Text = "text", /** Markdown-aware splitter that preserves heading and code-block boundaries. */ Markdown = "markdown", /** YAML-aware splitter that creates one chunk per top-level key. */ Yaml = "yaml", /** Topic-aware chunker that splits at embedding-based topic shifts. */ Semantic = "semantic", } /** Information about a single chunk. */ export interface ChunkInfo { /** Zero-based chunk index. */ readonly index: number; /** Page range for this chunk. */ readonly pages: PageRange; /** Estimated processing time for this chunk in milliseconds. */ readonly estimatedTimeMs: number; } /** * Chunking configuration. * * Configures text chunking for document content, including chunk size, * overlap, trimming behavior, and optional embeddings. * * Use `..Default.default()` when constructing to allow for future field additions: */ export interface ChunkingConfig { /** * Maximum size per chunk (in units determined by `sizing`). * * When `sizing` is `Characters` (default), this is the max character count. * When using token-based sizing, this is the max token count. * * Default: 1000 */ readonly maxCharacters?: number; /** * Overlap between chunks (in units determined by `sizing`). * * Default: 200 */ readonly overlap?: number; /** * Whether to trim whitespace from chunk boundaries. * * Default: true */ readonly trim?: boolean; /** * Type of chunker to use (Text or Markdown). * * Default: Text */ readonly chunkerType?: ChunkerType; /** Optional embedding configuration for chunk embeddings. */ readonly embedding?: EmbeddingConfig; /** * Optional sparse (SPLADE) embedding configuration for chunk embeddings. * * When set, sparse vectors are generated for each chunk's content and attached * via `sparse_embedding`. Requires the `sparse-embeddings` * feature; without it, a warning is emitted and no sparse vectors are attached. * * Config-file only: like `RerankerConfig` and the local-ONNX branch of * `embedding`, this has no CLI flag and no environment variable. Only the secret/identity * fields of LLM-routed configs (model, API key, base URL) get that reach. */ readonly sparseEmbedding?: SparseEmbeddingConfig; /** * Optional late-interaction (ColBERT) embedding configuration for chunk embeddings. * * When set, multi-vector embeddings are generated for each chunk's content and * attached via `late_interaction`. Requires the * `late-interaction` feature; without it, a warning is emitted and no * late-interaction vectors are attached. * * Config-file only, for the same reason as `sparse_embedding` above. */ readonly lateInteraction?: LateInteractionConfig; /** Use a preset configuration (overrides individual settings if provided). */ readonly preset?: string; /** * How to measure chunk size. * * Default: `Characters` (Unicode character count). * Enable `chunking-tiktoken` or `chunking-tokenizers` features for token-based sizing. */ readonly sizing?: ChunkSizing; /** * Optional cosine similarity threshold for semantic topic boundary detection. * * Only used when `chunker_type` is `Semantic` and an `EmbeddingConfig` is * provided. You almost never need to set this. When omitted, defaults to * `0.75` which works well for most documents. Lower values detect more * topic boundaries (more, smaller chunks); higher values detect fewer. * Range: `0.0..=1.0`. */ readonly topicThreshold?: number; /** * How to handle markdown tables that exceed the chunk size limit. * * Only applies when `chunker_type` is `Markdown`. * * * `Split` (default) — tables are split at row boundaries; continuation * chunks do not repeat the header. * * `RepeatHeader` — the table header row and separator are prepended to * every continuation chunk so each chunk is self-contained. * * Default: `Split` */ readonly tableChunking?: TableChunkingMode; } /** Reason for chunking a document. */ export type ChunkingReason = | { type: "LargeFile"; sizeBytes: number; thresholdBytes: number } | { type: "ManyPages"; pageCount: number; threshold: number } | { type: "OcrRequired"; pageCount: number; forceOcr: boolean } | { type: "LargeAndManyPages"; sizeBytes: number; pageCount: number }; /** Metadata about a chunk's position in the original document. */ export interface ChunkMetadata { /** Byte offset where this chunk starts in the original text (UTF-8 valid boundary). */ readonly byteStart: number; /** Byte offset where this chunk ends in the original text (UTF-8 valid boundary). */ readonly byteEnd: number; /** * Number of tokens in this chunk (if available). * * This is calculated by the embedding model's tokenizer if embeddings are enabled. */ readonly tokenCount?: number; /** Zero-based index of this chunk in the document. */ readonly chunkIndex: number; /** Total number of chunks in the document. */ readonly totalChunks: number; /** * First page number this chunk spans (1-indexed). * * Only populated when page tracking is enabled in extraction configuration. */ readonly firstPage?: number; /** * Last page number this chunk spans (1-indexed, equal to first_page for single-page chunks). * * Only populated when page tracking is enabled in extraction configuration. */ readonly lastPage?: number; /** * Heading context when using Markdown chunker. * * Contains the heading hierarchy this chunk falls under. * Only populated when `ChunkerType.Markdown` is used. */ readonly headingContext?: HeadingContext; /** * Flattened heading trail from document root to this chunk's section. * * Each element is a heading's text, outermost first. Derived from * `heading_context` when present; empty otherwise. * Provides a binding-friendly, RAG-shaped breadcrumb without requiring * callers to walk the nested `HeadingContext` structure. */ readonly headingPath: Array; /** * Indices into `ExtractedDocument.images` for images on pages covered by this chunk. * * Contains zero-based indices into the top-level `images` collection for every * image whose `page_number` falls within `[first_page, last_page]`. * Empty when image extraction is disabled or the chunk spans no pages with images. */ readonly imageIndices: Array; /** * Ids of the `DocumentNode`s * this chunk was derived from. * * Joins a chunk back to the structured document tree via * `DocumentNode.id`. * Populated from exact node provenance when available, with a textual * containment fallback for rendered chunks that do not retain byte offsets. */ readonly nodeIds: Array; /** * Per-page bounding-box spans this chunk covers, for viewer highlighting (#1295). * * One entry per page the chunk overlaps, in page order — the first and last entries' * `page` fields equal `first_page`/`last_page`. * Populated whenever page-boundary provenance is available (the same condition under * which `first_page`/`last_page` are populated); each entry's `bbox` is additionally * populated when the document's structured node tree (`ExtractedDocument.document`) is * available, as the union of that page's body-layer node bounding boxes found within this * chunk. Empty when page-boundary provenance is unavailable (mirrors `first_page`/ * `last_page` being `None`). */ readonly pageSpans: Array; /** * Multi-label classification result for this chunk. * * Populated by the chunk-classification post-processor when * `ExtractionConfig.chunk_classification` * is set. A chunk may match zero, one, or many of the configured label * definitions. Empty when chunk classification was not configured. */ readonly classifications: Array; } /** * How chunk size is measured. * * Defaults to `Characters` (Unicode character count). When using token-based sizing, * chunks are sized by token count according to the specified tokenizer. * * Token-based sizing uses HuggingFace tokenizers loaded at runtime, or a tokenizer * backend you register yourself. Any tokenizer available on HuggingFace Hub can be * used, including OpenAI-compatible tokenizers (e.g., `Xenova/gpt-4o`, * `Xenova/cl100k_base`). To size chunks with your own tokenizer instead (llama.cpp/GGUF * vocabularies, SentencePiece models, custom vocabs), register a `TokenizerBackend` * with `register_tokenizer_backend` and set `model` to the registered name. */ export type ChunkSizing = { type: "characters" } | { type: "tokenizer"; model: string; cacheDir: string }; /** * Semantic structural classification of a text chunk. * * Assigned by the heuristic classifier in `chunking.classifier`. * Defaults to `Unknown` when no rule matches. * Designed to be extended in future versions without breaking changes. */ export declare enum ChunkType { /** Section heading or document title. */ Heading = "heading", /** Party list: names, addresses, and signatories. */ PartyList = "party_list", /** Definition clause ("X means…", "X shall mean…"). */ Definitions = "definitions", /** Operative clause containing legal/contractual action verbs. */ OperativeClause = "operative_clause", /** Signature block with signatures, names, and dates. */ SignatureBlock = "signature_block", /** Schedule, annex, appendix, or exhibit section. */ Schedule = "schedule", /** Table-like content with aligned columns or repeated patterns. */ TableLike = "table_like", /** Mathematical formula or equation. */ Formula = "formula", /** Code block or preformatted content. */ CodeBlock = "code_block", /** Function or method definition (tree-sitter structured code chunking). */ Function = "function", /** Class, struct, interface, or trait definition (tree-sitter structured code chunking). */ Class = "class", /** Module, namespace, or top-level file scope (tree-sitter structured code chunking). */ Module = "module", /** Embedded or referenced image content. */ Image = "image", /** Organizational chart or hierarchy diagram. */ OrgChart = "org_chart", /** Diagram, figure, or visual illustration. */ Diagram = "diagram", /** Unclassified or mixed content. */ Unknown = "unknown", } /** * A structured citation from a citation block. * * Parsed from entries like: * `[^srcN]: source, locator, excerpt: "text"` */ export interface Citation { /** The label of the citation (e.g., "src1" in `[^src1]: ...`). */ readonly label: string; /** The source reference (path, URL, or identifier). */ readonly source: string; /** Optional locator within the source (e.g., "page 3" or "section 2.1"). */ readonly locator?: string; /** Optional excerpt — quoted text from the source. */ readonly excerpt?: string; } /** Citation file metadata (RIS, PubMed, EndNote). */ export interface CitationMetadata { /** Total number of citation records in the file. */ readonly citationCount?: number; /** Detected citation file format (e.g. `"ris"`, `"pubmed"`, `"endnote"`). */ readonly format?: string; /** Author names collected across all citation records. */ readonly authors?: Array; /** Earliest and latest publication years found in the file. */ readonly yearRange?: YearRange; /** DOI identifiers found in the citation records. */ readonly dois?: Array; /** Keywords collected from all citation records. */ readonly keywords?: Array; } /** A single label + confidence pair. */ export interface ClassificationLabel { /** Label name as configured in `PageClassificationConfig.labels`. */ readonly label: string; /** * Backend-reported confidence in `[0.0, 1.0]`. `None` when the backend (e.g. an LLM * prompt without explicit confidence schema) did not report one. */ readonly confidence?: number; } /** * Code block fence style in Markdown output. * * Determines how code blocks (`
`) are rendered in Markdown.
 */
export declare enum CodeBlockStyle {
  /** Indented code blocks (4 spaces). `CommonMark` standard. */
  Indented = "Indented",
  /** Fenced code blocks with triple backticks. Default (GFM). Supports language hints. */
  Backticks = "Backticks",
  /** Fenced code blocks with tildes (~~~). Supports language hints. */
  Tildes = "Tildes",
}

/**
 * A single structurally-meaningful code chunk produced by tree-sitter parsing.
 *
 * Purpose-built payload owned by xberg — deliberately does not expose the upstream
 * `tree_sitter_language_pack` types, so binding generators never need to resolve an
 * external crate's types across FFI/language boundaries.
 */
export interface CodeChunkInfo {
  /** The raw source text of this chunk. */
  readonly text: string;
  /** Hierarchical path of enclosing structural items (e.g. `["MyClass", "my_method"]`). */
  readonly contextPath: Array;
  /**
   * Tree-sitter node kinds that appear at the top level of this chunk (e.g.
   * `"function_definition"`, `"class_definition"`).
   */
  readonly nodeTypes: Array;
  /** Inclusive start byte offset of this chunk in the original source. */
  readonly byteStart: number;
  /** Exclusive end byte offset of this chunk in the original source. */
  readonly byteEnd: number;
}

/**
 * Content rendering mode for code extraction.
 *
 * Controls how extracted code content is represented in the `content` field
 * of `ExtractedDocument`.
 */
export declare enum CodeContentMode {
  /** Use TSLP semantic chunks as content (default). */
  Chunks = "chunks",
  /** Use raw source code as content. */
  Raw = "raw",
  /** Emit function/class headings + docstrings (no code bodies). */
  Structure = "structure",
}

/**
 * An XML-style attribute attached to an `Element` node.
 *
 * Populated only for `CodeDataNodeKind.Element`; always empty for `KeyValue` and
 * `Sequence` nodes.
 */
export interface CodeDataAttribute {
  /** Attribute name (e.g. `"class"`, `"href"`). */
  readonly name: string;
  /** Attribute value as a raw string (quotes stripped). */
  readonly value: string;
  /** Inclusive start byte offset of the `name="value"` attribute token. */
  readonly byteStart: number;
  /** Exclusive end byte offset of the `name="value"` attribute token. */
  readonly byteEnd: number;
}

/**
 * A node in the hierarchical data tree produced by data-format extraction.
 *
 * Purpose-built payload owned by xberg — mirrors
 * `tree_sitter_language_pack.DataNode` but flattens its `Span` down to plain byte
 * offsets, so binding generators never need to resolve an external crate's types
 * across FFI/language boundaries.
 */
export interface CodeDataNode {
  /** Whether this node is a key/value pair, XML element, or sequence item. */
  readonly kind: CodeDataNodeKind;
  /**
   * Key, attribute name, tag name, or positional index (`"0"`, `"1"`, …).
   * `None` at the document root.
   */
  readonly key?: string;
  /**
   * Leaf scalar value, if any. `None` for containers (objects, arrays, XML
   * elements with child elements).
   */
  readonly value?: string;
  /**
   * Attributes on element-shape nodes (XML `STag` attributes). Empty for all
   * other kinds.
   */
  readonly attributes: Array;
  /** Children for nested containers and XML element bodies. */
  readonly children: Array;
  /** Inclusive start byte offset of this node in the original source. */
  readonly byteStart: number;
  /** Exclusive end byte offset of this node in the original source. */
  readonly byteEnd: number;
}

/**
 * Discriminates the shape of a `CodeDataNode`.
 *
 * Purpose-built mirror of `tree_sitter_language_pack.DataNodeKind` — kept as an
 * xberg-owned type so binding generators never need to resolve the upstream crate's
 * types across FFI/language boundaries.
 */
export declare enum CodeDataNodeKind {
  /**
   * A key/value pair or mapping (JSON/TOML/properties/YAML/HCL/CUE/KDL pair, or a
   * wrapper "object"/"mapping" container).
   */
  KeyValue = "key_value",
  /** An XML element with a tag name in `key` and attributes in `attributes`. */
  Element = "element",
  /**
   * A positional sequence item (JSON array element, YAML block sequence item,
   * CSV/PSV row or cell).
   */
  Sequence = "sequence",
}

/**
 * Code-format metadata: the structural chunks produced by tree-sitter parsing.
 *
 * Wrapped by `FormatMetadata.Code`. Kept as a named struct (rather than an inline
 * enum-variant body) so serde can tag it under internal tagging and utoipa can emit a
 * referenceable `CodeMetadata` component in the OpenAPI schema.
 */
export interface CodeMetadata {
  /** Structural code chunks (function/class/module boundaries). */
  readonly chunks?: Array;
  /**
   * Hierarchical key/value data tree extracted from data-format source
   * (JSON, YAML, TOML, XML, CSV, etc.), when data extraction was enabled.
   */
  readonly data?: CodeDataNode;
}

/**
 * Controls thread usage for constrained environments.
 *
 * Set `max_threads` to cap all internal thread pools (Rayon, ONNX Runtime
 * intra-op) and batch concurrency to a single limit.
 *
 * # Default budget when `max_threads` is unset
 *
 * Without an explicit `max_threads`, the effective budget is
 * `min(detected_cpu_cores, 8)` — a deliberate ceiling chosen for
 * serverless/shared-tenant defaults, not a full-host auto-scale. On a host
 * with more than 8 cores this means the extra cores go **unused** unless one
 * of the following applies:
 *
 * - `max_threads` is set explicitly above 8 (the only way to exceed the
 *   ceiling on a bare-metal or VM host with no CPU quota).
 * - The process runs under a Linux cgroup CPU quota (containers, Kubernetes
 *   `resources.limits.cpu`); in that case the quota itself is used as the
 *   ceiling instead of the hardcoded 8, since the quota already reflects a
 *   deliberately-configured resource limit.
 *
 * When neither applies and the host has more than 8 cores, a single
 * `WARN`-level log is emitted the first time the budget is resolved,
 * naming the detected core count and the applied cap, so the ceiling is
 * discoverable without reading source.
 */
export interface ConcurrencyConfig {
  /**
   * Maximum number of threads for all internal thread pools.
   *
   * Caps Rayon global pool size, ONNX Runtime intra-op threads, and the
   * combined document/inner-task budget for batch extraction. When `None`,
   * the effective budget is `min(detected_cpu_cores, 8)` unless a Linux
   * cgroup CPU quota is present, in which case the quota is used as the
   * ceiling instead. On hosts with more than 8 cores and no cgroup quota,
   * set `max_threads` explicitly to use the additional cores — the
   * default will not scale past 8 on its own.
   */
  readonly maxThreads?: number;
}

/**
 * How a backend's reported page-level confidence must be interpreted.
 *
 * Backend confidence scores are not interchangeable. Tesseract's mean word confidence is a
 * classifier score validated to track legibility on a 0-100 scale. Sceptre (EasyOCR-based)
 * reports a length-penalised `custom_mean` that is rescaled into the same 0-100 range but is
 * *not* comparable — its ordering can be inverted relative to legibility (a dense prose page
 * can score lower than a nearly-blank one). A page-rejection gate calibrated on Tesseract's
 * scale was once applied unconditionally to sceptre's output and rejected every page of a
 * 16-page document, emptying it. This descriptor exists so gating code can ask a backend what
 * its number means instead of assuming.
 */
export type ConfidenceSemantics =
  | { type: "Legibility"; scaleMax: number }
  | { type: "Uncalibrated" }
  | { type: "None" };

/**
 * Content extraction and conversion configuration.
 *
 * Controls how HTML is converted to the output format. Uses
 * html-to-markdown-rs as the conversion engine for all formats
 * (markdown, plain text, djot).
 */
export interface ContentConfig {
  /** Output format: `"markdown"` (default), `"plain"`, `"djot"`. */
  readonly outputFormat?: string;
  /**
   * Preprocessing aggressiveness: `"minimal"`, `"standard"` (default), `"aggressive"`.
   *
   * - Minimal: only scripts/styles removed.
   * - Standard: also removes nav, nav-hinted headers/footers/asides, forms.
   * - Aggressive: removes all footers/asides unconditionally.
   */
  readonly preprocessingPreset?: string;
  /** Remove navigation elements (nav, breadcrumbs, menus). Default: `true`. */
  readonly removeNavigation?: boolean;
  /** Remove form elements. Default: `true`. */
  readonly removeForms?: boolean;
  /**
   * HTML tag names to strip (render children only, remove the tag wrapper).
   * Default: `[]`.
   */
  readonly stripTags?: Array;
  /** HTML tag names to preserve as raw HTML in output. */
  readonly preserveTags?: Array;
  /**
   * CSS selectors for elements to exclude entirely (element + all content).
   *
   * Unlike `strip_tags` (which removes the wrapper but keeps children),
   * excluded elements and all descendants are dropped. Supports CSS selectors:
   * `.class`, `#id`, `[attribute]`, compound selectors.
   *
   * Default: `["noscript"]`. `