import { Readable, Transform, TransformCallback } from 'node:stream'; import pino, { Logger } from 'pino'; import { ReadStream } from 'node:fs'; /** * Universal Document Model (UDM) — Type Definitions * * The UDM is the single internal representation for ALL document formats. * Every parser outputs UDM. Every processor consumes UDM. * This is the most critical type definition in the entire library. */ interface BoundingBox { readonly x: number; readonly y: number; readonly width: number; readonly height: number; } interface SourceLocation { readonly page?: number; readonly pagePosition?: number; readonly boundingBox?: BoundingBox; readonly column?: number; readonly slide?: number; readonly sheet?: string; readonly lineStart?: number; readonly lineEnd?: number; } type TextFormattingType = 'bold' | 'italic' | 'underline' | 'strikethrough' | 'highlight' | 'superscript' | 'subscript' | 'code'; interface TextFormatting { readonly type: TextFormattingType; readonly start: number; readonly end: number; } interface LinkInfo { readonly text: string; readonly url: string; readonly start: number; readonly end: number; } type TextElementType = 'heading' | 'paragraph' | 'list' | 'code' | 'equation' | 'footnote' | 'callout'; type VisualElementType = 'table' | 'image' | 'chart'; type ElementType = TextElementType | VisualElementType | 'page_break' | 'audio_segment'; interface DocumentElement { readonly id: string; readonly type: ElementType; readonly sourceLocation: SourceLocation; readonly confidence: number; readonly parentHeadingRef?: string; readonly sectionPath: readonly string[]; readonly flags: readonly string[]; } interface HeadingElement extends DocumentElement { readonly type: 'heading'; readonly level: 1 | 2 | 3 | 4 | 5 | 6; readonly content: string; readonly numbering?: string; readonly isAutoDetected: boolean; } interface ParagraphElement extends DocumentElement { readonly type: 'paragraph'; readonly content: string; readonly formatting: readonly TextFormatting[]; readonly links: readonly LinkInfo[]; readonly isContinuation: boolean; } interface ListItem { readonly content: string; readonly level: number; readonly marker?: string; readonly children?: readonly ListItem[]; } interface ListElement extends DocumentElement { readonly type: 'list'; readonly listType: 'ordered' | 'unordered' | 'definition'; readonly items: readonly ListItem[]; readonly introText?: string; } interface CodeElement extends DocumentElement { readonly type: 'code'; readonly language?: string; readonly content: string; readonly isInline: boolean; readonly description?: string; readonly lineCount: number; } interface EquationElement extends DocumentElement { readonly type: 'equation'; readonly latex: string; readonly plainText: string; readonly isInline: boolean; readonly equationNumber?: string; } interface FootnoteElement extends DocumentElement { readonly type: 'footnote'; readonly marker: string; readonly content: string; readonly referencedFrom?: string; } interface CalloutElement extends DocumentElement { readonly type: 'callout'; readonly calloutType: 'note' | 'warning' | 'tip' | 'important' | 'example' | 'definition'; readonly title?: string; readonly content: string; } interface TableCell { readonly content: string; readonly rowSpan: number; readonly colSpan: number; readonly isHeader: boolean; readonly dataType: 'text' | 'number' | 'date' | 'currency' | 'percentage' | 'empty'; readonly formatting?: readonly TextFormatting[]; } interface TableElement extends DocumentElement { readonly type: 'table'; readonly caption?: string; readonly headers: readonly TableCell[]; readonly rows: readonly (readonly TableCell[])[]; readonly rowCount: number; readonly colCount: number; readonly hasMergedCells: boolean; readonly naturalLanguage?: string; readonly structuredData?: readonly Record[]; readonly summary?: string; } type ImageType = 'photograph' | 'chart' | 'diagram' | 'flowchart' | 'logo' | 'signature' | 'screenshot' | 'icon' | 'infographic' | 'map' | 'handwritten' | 'form' | 'decorative' | 'unknown'; interface ImageElement extends DocumentElement { readonly type: 'image'; readonly imageType: ImageType; readonly imageRef: string; readonly imageHash?: string; readonly dimensions?: { readonly width: number; readonly height: number; }; readonly format?: string; readonly caption?: string; readonly altText?: string; readonly ocrText?: string; readonly aiDescription?: string; readonly containsText: boolean; readonly containsData: boolean; readonly isDecorative: boolean; readonly nearbyContext?: string; readonly visualContextSummary?: string; } type ChartType = 'bar' | 'stacked_bar' | 'grouped_bar' | 'horizontal_bar' | 'line' | 'multi_line' | 'area' | 'pie' | 'donut' | 'scatter' | 'bubble' | 'waterfall' | 'funnel' | 'radar' | 'heatmap' | 'treemap' | 'histogram' | 'box_plot' | 'gantt' | 'flowchart' | 'org_chart' | 'network' | 'sankey' | 'timeline' | 'unknown'; interface ChartAxes { readonly xLabel?: string; readonly yLabel?: string; readonly xType?: 'category' | 'numeric' | 'date'; readonly yType?: 'numeric' | 'percentage' | 'currency'; } interface ChartDataPoint { readonly label: string; readonly value: number; readonly formatted?: string; } interface ChartDataSeries { readonly name: string; readonly points: readonly ChartDataPoint[]; } interface ChartElement extends DocumentElement { readonly type: 'chart'; readonly chartType: ChartType; readonly title?: string; readonly axes?: ChartAxes; readonly legend?: readonly { readonly label: string; readonly color?: string; }[]; readonly dataSeries: readonly ChartDataSeries[]; readonly annotations?: readonly string[]; readonly underlyingTable?: TableElement; readonly naturalLanguageSummary?: string; readonly keyInsights?: readonly string[]; readonly imageRef?: string; readonly extractionConfidence: number; } interface AudioSegmentElement extends DocumentElement { readonly type: 'audio_segment'; readonly speaker?: string; readonly content: string; readonly timestampStart: number; readonly timestampEnd: number; readonly language?: string; } interface PageBreakElement extends DocumentElement { readonly type: 'page_break'; readonly fromPage: number; readonly toPage: number; } type AnyDocumentElement = HeadingElement | ParagraphElement | ListElement | TableElement | ImageElement | ChartElement | CodeElement | EquationElement | FootnoteElement | CalloutElement | PageBreakElement | AudioSegmentElement; interface OutlineNode { readonly level: number; readonly title: string; readonly elementRef: string; readonly children: readonly OutlineNode[]; } interface TOCEntry { readonly title: string; readonly level: number; readonly page?: number; readonly elementRef?: string; } interface GlossaryEntry { readonly term: string; readonly definition: string; readonly firstOccurrence?: string; } interface CrossReference { readonly fromElement: string; readonly toElement: string; readonly referenceText: string; readonly referenceType: 'section' | 'table' | 'figure' | 'footnote' | 'citation' | 'external'; } interface ProcessingNote { readonly severity: 'info' | 'warning' | 'error'; readonly stage: string; readonly message: string; readonly elementRef?: string; readonly page?: number; readonly details?: Readonly>; } interface DocumentStructure { readonly outline: readonly OutlineNode[]; readonly tableOfContents?: readonly TOCEntry[]; readonly glossary: readonly GlossaryEntry[]; } interface DocumentSource { readonly filename: string; readonly mimeType: string; readonly fileSize: number; readonly fileHash: string; readonly encoding?: string; readonly format: string; readonly formatConfidence: number; } interface DocumentMetadata { readonly title?: string; readonly author?: string; readonly createdDate?: string; readonly modifiedDate?: string; readonly pageCount?: number; readonly wordCount?: number; readonly language: string; readonly languages: readonly string[]; readonly hasImages: boolean; readonly hasTables: boolean; readonly hasCharts: boolean; readonly hasCode: boolean; readonly hasEquations: boolean; readonly hasAudio: boolean; readonly isScanned: boolean; readonly securityClassification?: string; readonly custom: Readonly>; } interface DocumentUDM { readonly id: string; readonly source: DocumentSource; readonly metadata: DocumentMetadata; readonly structure: DocumentStructure; readonly elements: readonly AnyDocumentElement[]; readonly crossReferences: readonly CrossReference[]; readonly processingNotes: readonly ProcessingNote[]; } /** * Chunk Type Definitions * * These types define the output of the chunking + enrichment pipeline. * Every chunk carries enough context to be useful in isolation for RAG. */ type ChunkContentType = 'text' | 'table' | 'chart' | 'image' | 'code' | 'audio' | 'mixed'; type ChunkQualityFlags = 'low_confidence_ocr' | 'possible_noise' | 'truncated_table' | 'incomplete_chart_data' | 'missing_image_description' | 'heading_only' | 'very_short' | 'very_long' | 'low_coherence' | 'possible_prompt_injection' | 'pii_scan_incomplete' | 'merged_from_small_chunks' | 'split_from_large_element'; interface ChunkRelationship { readonly chunkId: string; readonly type: 'continues_from' | 'continued_by' | 'references' | 'referenced_by' | 'parent' | 'child' | 'sibling' | 'related'; } interface Chunk { readonly chunkId: string; readonly documentId: string; readonly documentName: string; readonly documentHash: string; readonly content: string; readonly contentType: ChunkContentType; readonly contentElements: readonly ElementType[]; readonly sectionPath: readonly string[]; readonly headingTrail: string; readonly depthLevel: number; readonly documentPosition: number; readonly pageNumbers: readonly number[]; readonly sourceElementIds: readonly string[]; readonly chunkIndex: number; readonly totalChunks: number; readonly previousChunkId: string | null; readonly nextChunkId: string | null; readonly parentChunkId: string | null; readonly childChunkIds: readonly string[]; readonly relationships: readonly ChunkRelationship[]; readonly keywords: readonly string[]; readonly entities: readonly { readonly text: string; readonly type: string; readonly normalizedForm?: string; }[]; readonly topics: readonly string[]; readonly language: string; readonly summary?: string; readonly hypotheticalQuestions?: readonly string[]; readonly tokenCount: number; readonly confidenceScore: number; readonly importanceScore: number; readonly qualityScore: number; readonly qualityFlags: readonly ChunkQualityFlags[]; readonly piiDetected: boolean; readonly piiTypes: readonly string[]; readonly piiMasked: boolean; readonly securityClassification?: string; readonly promptInjectionRisk: boolean; readonly processingTimestamp: string; readonly libraryVersion: string; readonly configHash: string; readonly chunkingStrategy: string; readonly metadata: Readonly>; } /** * Plugin System Type Definitions * * All plugin interfaces that third-party code must implement. * Each plugin type has a clear contract and lifecycle. */ type PluginType = 'parser' | 'cleaner' | 'chunking' | 'chunking_strategy' | 'enrichment' | 'enricher' | 'pii_provider' | 'ocr_provider' | 'llm_provider' | 'output' | 'output_formatter' | 'transcription_provider' | 'cache_provider' | 'audit_logger' | 'security' | 'security_scanner'; interface PluginContext { readonly logger: { readonly debug: (msg: string, data?: Record) => void; readonly info: (msg: string, data?: Record) => void; readonly warn: (msg: string, data?: Record) => void; readonly error: (msg: string, data?: Record) => void; }; readonly config: Readonly>; readonly documentId: string; } interface Plugin { readonly name: string; readonly version: string; readonly type: PluginType; init?(context: PluginContext): Promise; destroy?(): Promise; } interface ParserPlugin extends Plugin { readonly type: 'parser'; readonly supportedFormats: readonly string[]; canParse(mimeType: string, buffer: Buffer): boolean; parse(buffer: Buffer, filename: string, context: PluginContext): Promise; } interface CleanerPlugin extends Plugin { readonly type: 'cleaner'; clean(udm: DocumentUDM, context: PluginContext): Promise; } interface ChunkingStrategyPlugin extends Plugin { readonly type: 'chunking_strategy'; readonly strategyName: string; chunk(elements: readonly AnyDocumentElement[], config: Readonly>, context: PluginContext): Promise; } interface EnricherPlugin extends Plugin { readonly type: 'enricher'; enrich(chunks: readonly Chunk[], context: PluginContext): Promise; } interface PIIProviderPlugin extends Plugin { readonly type: 'pii_provider'; readonly adapter: PIIProviderAdapter; } interface OCRProviderPlugin extends Plugin { readonly type: 'ocr_provider'; recognize(imageBuffer: Buffer, languages: readonly string[], context: PluginContext): Promise; } interface LLMDescribeImageResult { readonly description: string; readonly imageType?: string; readonly confidence: number; } interface LLMSummaryResult { readonly summary: string; readonly confidence: number; } interface LLMQuestionsResult { readonly questions: readonly string[]; readonly confidence: number; } interface LLMProviderPlugin extends Plugin { readonly type: 'llm_provider'; describeImage?(imageBuffer: Buffer, context: string, pluginContext: PluginContext): Promise; summarize?(text: string, maxTokens: number, pluginContext: PluginContext): Promise; generateQuestions?(text: string, maxQuestions: number, pluginContext: PluginContext): Promise; extractChartData?(imageBuffer: Buffer, pluginContext: PluginContext): Promise>; } interface OutputFormatterPlugin extends Plugin { readonly type: 'output_formatter'; readonly formatName: string; format(chunks: readonly Chunk[], options: Readonly>, context: PluginContext): Promise; } interface TranscriptionSegment { readonly text: string; readonly start: number; readonly end: number; readonly speaker?: string; readonly confidence: number; readonly language?: string; } interface TranscriptionResult { readonly fullText: string; readonly segments: readonly TranscriptionSegment[]; readonly language: string; readonly duration: number; readonly speakers?: readonly string[]; } interface TranscriptionProviderPlugin extends Plugin { readonly type: 'transcription_provider'; transcribe(audioBuffer: Buffer, mimeType: string, context: PluginContext): Promise; } interface CacheProviderPlugin extends Plugin { readonly type: 'cache_provider'; get(key: string): Promise; set(key: string, value: T, ttlMs?: number): Promise; has(key: string): Promise; delete(key: string): Promise; clear(): Promise; } interface AuditLogEntry { readonly timestamp: string; readonly eventType: string; readonly documentId?: string; readonly stage?: string; readonly action: string; readonly details: Readonly>; readonly correlationId?: string; readonly tenantId?: string; } interface AuditLoggerPlugin extends Plugin { readonly type: 'audit_logger'; log(entry: AuditLogEntry): Promise; query?(filters: Readonly>): Promise; } interface DocParserPlugin { readonly name: string; readonly version: string; readonly type: PluginType; readonly description?: string; readonly failBehavior?: 'skip' | 'throw'; init?(config: DocumentParserConfig): Promise; destroy?(): Promise; hooks?: ParserPluginHooks | ChunkingPluginHooks | EnrichmentPluginHooks | OutputPluginHooks | SecurityPluginHooks; } interface ParserPluginHooks { /** Called before parsing — can modify buffer or add preprocessing. */ beforeParse?(input: { buffer: Buffer; filename: string; mimeType: string; }): Promise<{ buffer: Buffer; filename: string; mimeType: string; }>; /** Called after parsing — can modify or enrich the UDM. */ afterParse?(udm: DocumentUDM): Promise; /** Custom parser for additional formats. */ customParser?(buffer: Buffer, filename: string, mimeType: string): Promise; } interface ChunkingPluginHooks { /** Called before chunking — can modify UDM. */ beforeChunk?(udm: DocumentUDM): Promise; /** Called after chunking — can modify chunks. */ afterChunk?(chunks: Chunk[]): Promise; } interface EnrichmentPluginHooks { /** Enrich a single chunk. */ enrichChunk?(chunk: Chunk): Promise; /** Enrich all chunks at once. */ enrichAll?(chunks: Chunk[]): Promise; } interface OutputPluginHooks { /** Custom output formatter. */ format?(chunks: readonly Chunk[]): unknown; } interface SecurityPluginHooks { /** Additional security scan. */ scan?(buffer: Buffer, filename: string): Promise<{ passed: boolean; threats: string[]; }>; } interface PIIMatch { readonly type: string; readonly text: string; readonly start: number; readonly end: number; readonly confidence: number; } interface PIIProviderAdapter { readonly name: string; detect(text: string): Promise; mask(text: string, matches: readonly PIIMatch[]): Promise; redact(text: string, matches: readonly PIIMatch[]): Promise; supportedTypes(): string[]; configure?(options: Readonly>): void; } interface OCRResult { readonly text: string; readonly confidence: number; readonly blocks: readonly OCRBlock[]; readonly lines?: readonly OCRLine[]; readonly paragraphs?: readonly OCRParagraph[]; readonly words?: readonly OCRWord[]; readonly symbols?: readonly OCRSymbol[]; readonly detection?: OCRDetectionResult; } interface OCRBoundingBox { readonly x: number; readonly y: number; readonly width: number; readonly height: number; } interface OCRGeometryElement { readonly text: string; readonly confidence: number; readonly bbox: OCRBoundingBox; } interface OCRBlock extends OCRGeometryElement { } interface OCRLine extends OCRGeometryElement { } interface OCRParagraph extends OCRGeometryElement { readonly isLeftToRight?: boolean; } interface OCRWord extends OCRGeometryElement { readonly language?: string; readonly direction?: string; readonly isNumeric?: boolean; readonly fontName?: string; readonly fontSize?: number; readonly isBold?: boolean; readonly isItalic?: boolean; readonly isUnderlined?: boolean; readonly isMonospace?: boolean; readonly isSerif?: boolean; readonly isSmallCaps?: boolean; } interface OCRSymbol extends OCRGeometryElement { readonly isSuperscript?: boolean; readonly isSubscript?: boolean; readonly isDropCap?: boolean; } interface OCRDetectionResult { readonly script?: string; readonly scriptConfidence?: number; readonly orientationDegrees?: number; readonly orientationConfidence?: number; readonly appliedRotationDegrees?: number; } type OCRQualityLevel = 'fast' | 'balanced' | 'thorough' | 'extreme'; interface OCRRecognitionOptions { readonly engineMode?: 'legacy' | 'lstm' | 'both'; readonly pageSegMode?: 'auto' | 'single_block' | 'single_line' | 'single_word' | 'sparse_text'; readonly preserveInterwordSpaces?: boolean; readonly userDefinedDpi?: number; } interface OCRProviderAdapter { readonly name: string; recognize(imageBuffer: Buffer, language?: string, options?: OCRRecognitionOptions): Promise; supportedLanguages(): string[]; isAvailable?(): Promise; } interface LLMRequest { readonly prompt: string; readonly maxTokens?: number; readonly temperature?: number; readonly model?: string; } interface LLMResponse { readonly text: string; readonly tokensUsed: number; readonly model: string; } interface LLMProviderAdapter { readonly name: string; complete(request: LLMRequest): Promise; embed(texts: string[]): Promise; isAvailable(): Promise; } interface EmbeddingProviderAdapter { readonly name: string; readonly dimensions: number; embed(texts: string[]): Promise; embedSingle(text: string): Promise; } /** * Configuration Type Definitions * * Comprehensive configuration for every aspect of document processing. * All fields are optional — sensible defaults are applied. */ type PresetName = 'general' | 'financial' | 'legal' | 'technical' | 'medical' | 'conversational' | 'research'; type ChunkingStrategyName = 'hierarchical' | 'semantic_similarity' | 'sliding_window' | 'element_aware' | 'topic_modeling' | 'entity_centric' | 'paragraph_context' | 'hybrid_auto' | 'speaker_turn' | 'custom'; type PIIAction = 'detect' | 'mask' | 'redact' | 'hash' | 'encrypt' | 'custom'; type PIIScanTarget = 'text_content' | 'table_cells' | 'ocr_text' | 'image_descriptions' | 'metadata_fields' | 'file_names' | 'email_headers' | 'audio_transcription'; type PromptInjectionAction = 'flag' | 'sanitize' | 'wrap' | 'quarantine' | 'block'; type SecurityLevel = 'public' | 'internal' | 'confidential' | 'restricted'; type PerformanceMode = 'fast' | 'balanced' | 'thorough'; type RuntimePipelinePresetName = 'standard' | 'fast' | 'quality' | 'llm_light'; type TokenCounterType = 'tiktoken_cl100k' | 'tiktoken_o200k' | 'approximate' | 'custom'; type ProviderProtocol = 'openai' | 'anthropic' | 'ollama'; type ProcessingStage = 'started' | 'security' | 'parsing' | 'table_nl' | 'cleaning' | 'chunking' | 'enrichment' | 'pii_scan' | 'security_scan' | 'coverage' | 'quality_report' | 'complete'; type ProgressDetails = Readonly<{ stage: ProcessingStage | (string & {}); percentage: number; filename?: string; inputBytes?: number; mimeType?: string; fileHash?: string; documentId?: string; durationMs?: number; itemsProcessed?: number; totalChunks?: number; strategyUsed?: string; coveragePercentage?: number; qualityScore?: number; warningsCount?: number; errorsCount?: number; } & Record>; interface PDFParsingConfig { readonly extractImages?: boolean; readonly extractTables?: boolean; readonly ocrScannedPages?: boolean; readonly detectMultiColumn?: boolean; readonly detectHeadersFooters?: boolean; readonly imageDpi?: number; } interface DOCXParsingConfig { readonly extractImages?: boolean; readonly extractTables?: boolean; readonly followStyles?: boolean; readonly includeComments?: boolean; readonly includeTrackChanges?: boolean; } interface HTMLParsingConfig { readonly sanitize?: boolean; readonly removeScripts?: boolean; readonly removeStyles?: boolean; readonly removeBoilerplate?: boolean; readonly followLinks?: boolean; readonly maxDepth?: number; } interface XLSXParsingConfig { readonly includeFormulas?: boolean; readonly includeCharts?: boolean; readonly sheetSelection?: 'all' | 'first' | readonly number[]; readonly emptyCellHandling?: 'skip' | 'empty_string' | 'null'; } interface PPTXParsingConfig { readonly includeNotes?: boolean; readonly includeHiddenSlides?: boolean; } interface OCRConfig { readonly engine?: 'tesseract' | 'custom'; readonly languages?: readonly string[]; readonly confidenceThreshold?: number; readonly preprocess?: boolean; readonly dpi?: number; } interface TesseractProviderConfig { readonly kind: 'tesseract'; readonly languages?: readonly string[]; readonly dataPath?: string; readonly engineMode?: 'legacy' | 'lstm' | 'both'; readonly pageSegMode?: 'auto' | 'single_block' | 'single_line' | 'single_word' | 'sparse_text'; readonly workerCount?: number; readonly detectOrientationScript?: boolean; readonly preserveInterwordSpaces?: boolean; readonly userDefinedDpi?: number; } interface NativeTesseractProviderConfig { readonly kind: 'native_tesseract'; readonly executablePath?: string; readonly tessdataDir?: string; readonly workingDirectory?: string; readonly tempDir?: string; readonly timeoutMs?: number; readonly languages?: readonly string[]; readonly engineMode?: 'legacy' | 'lstm' | 'both'; readonly pageSegMode?: 'auto' | 'single_block' | 'single_line' | 'single_word' | 'sparse_text'; readonly detectOrientationScript?: boolean; readonly preserveInterwordSpaces?: boolean; readonly userDefinedDpi?: number; } interface ProviderRetryPolicyConfig { readonly maxAttempts?: number; readonly initialDelayMs?: number; readonly maxDelayMs?: number; readonly backoffMultiplier?: number; readonly retryOnStatus?: readonly number[]; readonly retryOnNetworkErrors?: boolean; readonly retryOnTimeout?: boolean; } interface ProviderHealthCheckConfig { readonly validateOnStartup?: boolean; readonly failOnUnhealthy?: boolean; } interface OllamaProviderConfig { readonly kind: 'ollama'; readonly baseUrl?: string; readonly model: string; readonly embeddingModel?: string; readonly timeoutMs?: number; readonly keepAlive?: string; readonly healthPath?: string; readonly retry?: ProviderRetryPolicyConfig; readonly headers?: Readonly>; } interface ClaudeProviderConfig { readonly kind: 'claude'; readonly apiKey?: string; readonly model: string; readonly baseUrl?: string; readonly anthropicVersion?: string; readonly maxTokens?: number; readonly timeoutMs?: number; readonly healthPath?: string; readonly retry?: ProviderRetryPolicyConfig; readonly headers?: Readonly>; readonly betaHeaders?: readonly string[]; } interface OpenRouterProviderConfig { readonly kind: 'openrouter'; readonly apiKey?: string; readonly model: string; readonly baseUrl?: string; readonly embeddingModel?: string; readonly timeoutMs?: number; readonly maxTokens?: number; readonly healthPath?: string; readonly retry?: ProviderRetryPolicyConfig; readonly headers?: Readonly>; readonly referer?: string; readonly appName?: string; } interface OrganizationGatewayProviderConfig { readonly kind: 'organization_gateway'; readonly protocol: ProviderProtocol; readonly baseUrl: string; readonly apiKey?: string; readonly model: string; readonly embeddingModel?: string; readonly timeoutMs?: number; readonly maxTokens?: number; readonly retry?: ProviderRetryPolicyConfig; readonly headers?: Readonly>; readonly healthPath?: string; } type BuiltInLLMProviderConfig = OllamaProviderConfig | ClaudeProviderConfig | OpenRouterProviderConfig | OrganizationGatewayProviderConfig; type BuiltInOCRProviderConfig = TesseractProviderConfig | NativeTesseractProviderConfig | OllamaProviderConfig | ClaudeProviderConfig | OpenRouterProviderConfig | OrganizationGatewayProviderConfig; type OCRRoutingImageType = 'photograph' | 'logo' | 'chart' | 'graph' | 'table' | 'diagram' | 'screenshot' | 'form' | 'handwritten' | 'signature' | 'infographic' | 'icon' | 'decorative' | 'map' | (string & {}); interface OCRProviderPipelineConfig { readonly qualityLevel?: 'fast' | 'balanced' | 'thorough' | 'extreme'; readonly preprocessing?: { readonly preset?: 'fast' | 'scanned-document' | 'photo-receipt' | 'low-contrast' | 'medical-form'; readonly targetDPI?: number; readonly grayscale?: boolean; readonly normalizeContrast?: boolean; readonly sharpen?: boolean; readonly denoise?: boolean; readonly deskew?: boolean; readonly binarize?: boolean; readonly binarizeThreshold?: number; readonly maxDimension?: number; }; readonly recognition?: { readonly engineMode?: 'legacy' | 'lstm' | 'both'; readonly pageSegMode?: 'auto' | 'single_block' | 'single_line' | 'single_word' | 'sparse_text'; readonly preserveInterwordSpaces?: boolean; readonly userDefinedDpi?: number; }; readonly minConfidence?: number; readonly skipNonTextImages?: boolean; readonly maxPages?: number; readonly autoRotateFromDetection?: boolean; readonly useBuiltInRetryProfiles?: boolean; readonly evaluateAllProfiles?: boolean; readonly earlyExitConfidence?: number; } interface OCRProviderRoutingConfig { readonly preferDocumentLanguage?: boolean; readonly forceImageTypes?: readonly OCRRoutingImageType[]; readonly skipImageTypes?: readonly OCRRoutingImageType[]; readonly contextHints?: readonly string[]; } interface OCRProviderRegistrationConfig { readonly enabled?: boolean; readonly provider?: BuiltInOCRProviderConfig | OCRProviderAdapter; readonly pipeline?: OCRProviderPipelineConfig; readonly routing?: OCRProviderRoutingConfig; readonly healthCheck?: ProviderHealthCheckConfig; readonly processEmbeddedImages?: boolean; readonly processImagePDFs?: boolean; } interface LLMProviderRegistrationConfig { readonly enabled?: boolean; readonly provider?: BuiltInLLMProviderConfig | LLMProviderAdapter; readonly healthCheck?: ProviderHealthCheckConfig; readonly model?: string; readonly generateSummary?: boolean; readonly generateQuestions?: boolean; readonly maxQuestions?: number; readonly summaryMaxTokens?: number; readonly temperature?: number; readonly importanceThreshold?: number; readonly concurrency?: number; readonly maxChunks?: number; } interface EmbeddingProviderRegistrationConfig { readonly enabled?: boolean; readonly provider?: BuiltInLLMProviderConfig | LLMProviderAdapter | EmbeddingProviderAdapter; readonly healthCheck?: ProviderHealthCheckConfig; readonly batchSize?: number; readonly maxConcurrentBatches?: number; readonly dimensions?: number; } interface ProviderConfig { readonly ocr?: OCRProviderRegistrationConfig; readonly llm?: LLMProviderRegistrationConfig; readonly embeddings?: EmbeddingProviderRegistrationConfig; } interface ImageParsingConfig { readonly classifyType?: boolean; readonly extractTextOcr?: boolean; readonly generateDescriptions?: boolean; readonly skipDecorative?: boolean; readonly minSize?: { readonly width: number; readonly height: number; }; } interface ChartParsingConfig { readonly extractData?: boolean; readonly generateSummary?: boolean; readonly convertToTable?: boolean; } interface ParsingConfig { readonly pdf?: PDFParsingConfig; readonly docx?: DOCXParsingConfig; readonly html?: HTMLParsingConfig; readonly xlsx?: XLSXParsingConfig; readonly pptx?: PPTXParsingConfig; readonly ocr?: OCRConfig; readonly images?: ImageParsingConfig; readonly charts?: ChartParsingConfig; } interface InputConfig { readonly allowedFormats?: readonly string[]; readonly maxFileSize?: number; readonly maxPages?: number; readonly maxElements?: number; readonly password?: string; readonly urlFetchTimeout?: number; readonly urlFetchHeaders?: Readonly>; readonly encodingOverride?: string; } interface CleaningConfig { readonly normalizeUnicode?: boolean; readonly fixHyphenation?: boolean; readonly mergeBrokenParagraphs?: boolean; readonly removeWatermarks?: boolean; readonly removeHeadersFooters?: boolean; readonly removePageNumbers?: boolean; readonly normalizeWhitespace?: boolean; readonly normalizeDates?: boolean; readonly normalizeCurrencies?: boolean; readonly buildGlossary?: boolean; readonly customPatternsToRemove?: readonly string[]; readonly customPatternsToFlag?: readonly string[]; readonly preserveFormattingIn?: readonly ('code' | 'quotes' | 'tables')[]; } interface OverlapConfig { readonly enabled?: boolean; readonly tokens?: number; readonly strategy?: 'raw' | 'sentence_boundary' | 'heading_repeat'; } interface HeadingContextConfig { readonly includeParentHeadings?: boolean; readonly maxHeadingDepth?: number; readonly separator?: string; } interface AdaptiveChunkingConfig { readonly enabled?: boolean; } interface ChunkingConfig { readonly strategy?: ChunkingStrategyName; readonly customStrategy?: (elements: readonly unknown[], config: unknown) => unknown[]; readonly adaptive?: AdaptiveChunkingConfig; readonly tokenCounter?: TokenCounterType; readonly customTokenCounter?: (text: string) => number; readonly minChunkTokens?: number; readonly maxChunkTokens?: number; readonly targetChunkTokens?: number; readonly overlap?: OverlapConfig; readonly headingContext?: HeadingContextConfig; readonly tableHandling?: 'own_chunk' | 'with_context' | 'natural_language_only'; readonly chartHandling?: 'own_chunk' | 'with_context' | 'natural_language_only'; readonly imageHandling?: 'own_chunk' | 'with_context' | 'skip_decorative'; readonly codeHandling?: 'own_chunk' | 'with_context' | 'inline_if_small'; readonly mergeSmallChunks?: boolean; readonly neverSplit?: readonly ('table' | 'code' | 'chart' | 'image' | 'list')[]; /** Semantic strategy: similarity threshold below which a new chunk boundary is created. */ readonly semanticThreshold?: number; /** Semantic strategy: window size (in sentences) used for similarity comparison. */ readonly semanticWindowSize?: number; } interface EnrichmentFeedbackConfig { readonly enabled?: boolean; readonly preferredTerms?: readonly string[]; readonly deprioritizedTerms?: readonly string[]; readonly prioritizedEntityTypes?: readonly string[]; readonly preferredTermBoost?: number; readonly deprioritizedTermPenalty?: number; readonly entityTypeBoost?: number; } interface EnrichmentSemanticDedupConfig { readonly enabled?: boolean; readonly similarityThreshold?: number; readonly minSharedTerms?: number; readonly maxRelatedChunks?: number; } interface EnrichmentConfig { readonly extractKeywords?: boolean; readonly keywordMethod?: 'tfidf' | 'rake' | 'textrank'; readonly maxKeywords?: number; readonly extractEntities?: boolean; readonly entityTypes?: readonly string[]; readonly detectTopics?: boolean; readonly generateSummary?: boolean; readonly summaryMaxTokens?: number; readonly generateQuestions?: boolean; readonly maxQuestions?: number; readonly computeImportance?: boolean; readonly resolveCrossReferences?: boolean; readonly linkChunks?: boolean; readonly feedback?: EnrichmentFeedbackConfig; readonly semanticDedup?: EnrichmentSemanticDedupConfig; readonly customEnrichers?: readonly ((chunk: unknown) => unknown)[]; } interface PIIConfig { readonly enabled?: boolean; readonly provider?: unknown; readonly mode?: PIIAction; readonly maxConcurrentScans?: number; readonly scanTargets?: readonly PIIScanTarget[]; readonly maskFormat?: string; readonly allowlist?: readonly string[]; readonly customPatterns?: readonly { readonly name: string; readonly pattern: string; }[]; readonly encryptionKey?: string; } interface PromptInjectionConfig { readonly enabled?: boolean; readonly action?: PromptInjectionAction; readonly customPatterns?: readonly string[]; readonly sensitivity?: 'low' | 'medium' | 'high'; } interface DataLifecycleConfig { readonly encryptTempFiles?: boolean; readonly secureDelete?: boolean; readonly clearMemoryAfter?: boolean; readonly maxCacheTtl?: number; } interface AuditConfig { readonly enabled?: boolean; readonly logDestination?: 'memory' | 'file' | 'custom'; readonly customLogger?: unknown; readonly includeDocumentName?: boolean; readonly anonymizeDocumentName?: boolean; } interface SecurityClassificationConfig { readonly enabled?: boolean; readonly defaultLevel?: SecurityLevel; readonly rules?: readonly { readonly pattern: string; readonly level: SecurityLevel; }[]; } interface SecurityConfig { readonly maxFileSize?: number; readonly allowedFormats?: readonly string[]; readonly blockMacros?: boolean; readonly blockJavascriptInPdf?: boolean; readonly blockXxe?: boolean; readonly blockPolyglots?: boolean; readonly virusScanHook?: (buffer: Buffer) => Promise; readonly sandboxParsing?: boolean; readonly maxMemoryPerDoc?: number; readonly maxProcessingTime?: number; readonly maxTempDisk?: number; readonly pii?: PIIConfig; readonly promptInjection?: PromptInjectionConfig; readonly dataLifecycle?: DataLifecycleConfig; readonly audit?: AuditConfig; readonly classification?: SecurityClassificationConfig; } type OutputFormat = 'json' | 'jsonl' | 'csv' | 'structured_json' | 'prescription_json' | 'medical_summary_json' | 'text' | 'markdown' | 'pinecone' | 'chroma' | 'weaviate' | 'qdrant' | 'langchain' | 'llamaindex' | 'custom'; interface VectorDBOutputConfig { readonly namespace?: string; readonly collection?: string; readonly index?: string; readonly batchSize?: number; } interface OutputConfig { readonly format?: OutputFormat; readonly formats?: readonly OutputFormat[]; readonly customFormatter?: (chunks: readonly unknown[]) => unknown; readonly includeFields?: readonly string[]; readonly excludeFields?: readonly string[]; readonly includeQualityReport?: boolean; readonly includeProcessingReceipt?: boolean; readonly flattenMetadata?: boolean; readonly vectorDb?: VectorDBOutputConfig; } interface CacheConfig$1 { readonly enabled?: boolean; readonly backend?: 'memory' | 'filesystem' | 'redis' | 'custom'; readonly maxSize?: number; readonly maxItems?: number; readonly ttl?: number; readonly cacheParsing?: boolean; readonly cacheChunking?: boolean; readonly isolateCachedValues?: boolean; readonly customBackend?: unknown; } interface PerformanceConfig { readonly mode?: PerformanceMode; readonly workerThreads?: number; readonly maxConcurrentDocs?: number; readonly streaming?: boolean; readonly streamingThreshold?: number; readonly cache?: CacheConfig$1; readonly memoryBudget?: number; } interface PipelineStageConfig { readonly tableNl?: boolean; readonly cleaning?: boolean; readonly enrichment?: boolean; readonly piiScan?: boolean; readonly promptInjection?: boolean; } interface PipelineConfig { readonly runtimePreset?: RuntimePipelinePresetName; readonly stages?: PipelineStageConfig; } interface DebugConfig { readonly enabled?: boolean; readonly visualOutput?: boolean; readonly visualOutputPath?: string; readonly profilePerformance?: boolean; readonly verboseLogging?: boolean; readonly dumpUdm?: boolean; readonly dumpUdmPath?: string; } interface HooksConfig { readonly onProgress?: (stage: ProcessingStage | (string & {}), percentage: number, details?: ProgressDetails) => void; readonly onWarning?: (warning: { message: string; stage: string; details?: Record; }) => void; readonly onError?: (error: Error) => void; readonly onChunkReady?: (chunk: unknown) => void; readonly onDocumentComplete?: (receipt: unknown) => void; readonly onGovernanceEvent?: (event: AuditLogEntry) => void | Promise; } type PluginFactory = () => DocParserPlugin | Promise; interface PluginModuleConfig { readonly module: string; readonly exportName?: string; } type PluginRegistration = DocParserPlugin | PluginFactory | PluginModuleConfig | string; interface DocumentParserConfig { readonly preset?: PresetName; readonly input?: InputConfig; readonly parsing?: ParsingConfig; readonly cleaning?: CleaningConfig; readonly chunking?: ChunkingConfig; readonly enrichment?: EnrichmentConfig; readonly security?: SecurityConfig; readonly output?: OutputConfig; readonly performance?: PerformanceConfig; readonly pipeline?: PipelineConfig; readonly providers?: ProviderConfig; readonly plugins?: readonly PluginRegistration[]; readonly hooks?: HooksConfig; readonly debug?: DebugConfig; } /** * Processing Result Type Definitions * * Types for everything returned from document processing. */ interface StageMetrics { readonly stage: string; readonly durationMs: number; readonly memoryUsedBytes?: number; readonly itemsProcessed?: number; readonly itemsFailed?: number; } interface ProcessingMetrics { readonly totalDurationMs: number; readonly stages: readonly StageMetrics[]; readonly peakMemoryBytes?: number; readonly workerThreadsUsed?: number; } interface ExplainabilityEvidence { readonly stage: string; readonly kind: 'text_normalized' | 'hyphenation_fixed' | 'header_removed' | 'footer_removed' | 'boilerplate_removed' | 'paragraph_merged' | 'warning' | 'error' | 'coverage_gap'; readonly before?: string; readonly after?: string; readonly preview?: string; readonly message?: string; readonly count?: number; readonly elementRef?: string; readonly page?: number; } interface ExplainabilityStageSummary { readonly stage: string; readonly durationMs: number; readonly status: 'completed' | 'skipped' | 'cached'; readonly itemsProcessed?: number; } interface ExplainabilityReport { readonly summary: { readonly totalTransformations: number; readonly textNormalizations: number; readonly hyphenationsFixed: number; readonly paragraphsMerged: number; readonly headersRemoved: number; readonly footersRemoved: number; readonly boilerplateRemoved: number; readonly totalWarnings: number; readonly totalErrors: number; readonly skippedStages: number; readonly cachedStages: number; }; readonly stages: readonly ExplainabilityStageSummary[]; readonly evidence: readonly ExplainabilityEvidence[]; } interface CoverageReport { readonly totalSourceCharacters: number; readonly coveredCharacters: number; readonly coveragePercentage: number; readonly missingSegments: readonly { readonly page?: number; readonly elementId: string; readonly preview: string; }[]; } interface ChunkQualityDetail { readonly chunkId: string; readonly sizeScore: number; readonly coherenceScore: number; readonly completenessScore: number; readonly contextScore: number; readonly overallScore: number; readonly flags: readonly string[]; } interface QualityReport { readonly totalChunks: number; readonly averageQualityScore: number; readonly averageTokenCount: number; readonly minTokenCount: number; readonly maxTokenCount: number; readonly tokenCountDistribution: Readonly>; readonly chunksByContentType: Readonly>; readonly chunksBelowQualityThreshold: number; readonly flaggedChunks: readonly ChunkQualityDetail[]; readonly coverage: CoverageReport; readonly deduplicates: readonly { readonly chunkId1: string; readonly chunkId2: string; readonly similarity: number; }[]; readonly strategyUsed: string; readonly recommendations: readonly string[]; } interface PIIDetectionSummary { readonly type: string; readonly count: number; readonly action: string; readonly locations: readonly string[]; } interface PIIReport { readonly scanned: boolean; readonly totalDetections: number; readonly detectionsByType: readonly PIIDetectionSummary[]; readonly scanTargetsUsed: readonly string[]; readonly providerUsed: string; readonly scanDurationMs: number; } interface ThreatReport { readonly scanned: boolean; readonly threatsDetected: number; readonly threats: readonly { readonly type: string; readonly severity: 'low' | 'medium' | 'high' | 'critical'; readonly action: string; readonly details: string; }[]; readonly promptInjectionRisks: number; readonly promptInjectionDetails: readonly { readonly chunkId?: string; readonly pattern: string; readonly action: string; }[]; } interface SecurityReport { readonly inputValidation: { readonly passed: boolean; readonly checks: readonly { readonly check: string; readonly passed: boolean; readonly details?: string; }[]; }; readonly threats: ThreatReport; readonly pii: PIIReport; readonly classification: string; readonly auditEventsCount: number; } interface OCRDiagnosticsSummary { readonly processedImages: number; readonly autoRotatedImages: number; readonly scriptsDetected: readonly string[]; readonly orientationsDetected: readonly number[]; readonly geometryTotals: { readonly blocks: number; readonly lines: number; readonly paragraphs: number; readonly words: number; readonly symbols: number; }; } interface ProcessingReceipt { readonly documentId: string; readonly inputFile: string; readonly inputHash: string; readonly inputSize: number; readonly detectedFormat: string; readonly processingTimeMs: number; readonly totalPages: number; readonly processedPages: number; readonly failedPages: readonly number[]; readonly totalElements: number; readonly processedElements: number; readonly failedElements: readonly { readonly type: string; readonly location: string; readonly error: string; }[]; readonly totalChunks: number; readonly chunkingStrategy: string; readonly warnings: readonly { readonly stage: string; readonly message: string; }[]; readonly errors: readonly { readonly stage: string; readonly message: string; readonly recoverable: boolean; }[]; readonly coverageScore: number; readonly qualityScore: number; readonly confidenceScore: number; readonly securitySummary: { readonly piiDetected: boolean; readonly piiCount: number; readonly threatsDetected: number; readonly promptInjectionRisks: number; readonly classification: string; }; readonly ocrDiagnostics?: OCRDiagnosticsSummary; readonly metrics: ProcessingMetrics; readonly configHash: string; readonly libraryVersion: string; readonly timestamp: string; } interface ProcessingResult { readonly chunks: readonly Chunk[]; readonly receipt: ProcessingReceipt; readonly qualityReport: QualityReport; readonly securityReport: SecurityReport; readonly explainabilityReport: ExplainabilityReport; readonly documentId: string; } interface InspectionResult { readonly udm: DocumentUDM; readonly securityReport: SecurityReport; readonly warnings: readonly { readonly stage: string; readonly message: string; }[]; readonly errors: readonly { readonly stage: string; readonly message: string; readonly recoverable: boolean; }[]; readonly metrics: { readonly inputBytes: number; readonly processingTimeMs: number; readonly mimeType: string; readonly fileHash: string; readonly configHash: string; readonly parsingCached: boolean; readonly stages: readonly StageMetrics[]; }; } /** * Base class for all output formatters. */ declare abstract class BaseFormatter { protected readonly config: OutputConfig; constructor(config?: OutputConfig); abstract readonly formatName: string; abstract format(chunks: readonly Chunk[]): unknown; createReadable(_chunks: readonly Chunk[]): Readable | undefined; /** * Apply field inclusion/exclusion filters. */ protected filterFields(chunk: Chunk): Record; } type StructuredRelationshipType = ChunkRelationship['type'] | 'previous' | 'next'; type ValidationSeverity$2 = 'info' | 'warning' | 'error'; type ValidationReferenceType = 'document' | 'section' | 'content_item' | 'page'; interface StructuredJSONDocumentRow { readonly document_id: string; readonly document_name: string; readonly document_hash: string; readonly total_content_items: number; readonly total_sections: number; readonly total_pages: number; readonly page_numbers: readonly number[]; readonly languages: readonly string[]; readonly content_types: readonly string[]; readonly chunking_strategies: readonly string[]; readonly average_confidence_score: number; readonly average_quality_score: number; readonly average_importance_score: number; readonly pii_detected: boolean; readonly pii_types: readonly string[]; readonly prompt_injection_risk: boolean; readonly quality_flags: readonly string[]; readonly first_processed_at: string | null; readonly last_processed_at: string | null; } interface StructuredJSONSectionRow { readonly section_id: string; readonly document_id: string; readonly title: string; readonly section_path: readonly string[]; readonly section_path_key: string; readonly depth: number; readonly parent_section_id: string | null; readonly is_synthetic: boolean; readonly order_index: number; readonly first_content_id: string | null; readonly last_content_id: string | null; readonly direct_content_item_count: number; readonly descendant_content_item_count: number; readonly has_direct_content: boolean; readonly page_start: number | null; readonly page_end: number | null; readonly page_numbers: readonly number[]; readonly content_types: readonly string[]; readonly average_confidence_score: number; readonly average_quality_score: number; readonly average_importance_score: number; readonly quality_flags: readonly string[]; } interface StructuredJSONContentItemRow { readonly content_id: string; readonly document_id: string; readonly section_id: string; readonly section_path: readonly string[]; readonly section_path_key: string; readonly section_leaf: string | null; readonly section_ordinal_path: string | null; readonly section_numbering: string | null; readonly section_label: string | null; readonly heading_trail: string; readonly content_type: string; readonly content_elements: readonly string[]; readonly order_index: number; readonly document_position: number; readonly parent_content_id: string | null; readonly previous_content_id: string | null; readonly next_content_id: string | null; readonly child_content_ids: readonly string[]; readonly page_start: number | null; readonly page_end: number | null; readonly page_numbers: readonly number[]; readonly source_element_ids: readonly string[]; readonly content: string; readonly token_count: number; readonly language: string; readonly summary: string | null; readonly topics: readonly string[]; readonly hypothetical_questions: readonly string[]; readonly confidence_score: number; readonly importance_score: number; readonly quality_score: number; readonly quality_flags: readonly string[]; readonly pii_detected: boolean; readonly pii_types: readonly string[]; readonly pii_masked: boolean; readonly security_classification: string | null; readonly prompt_injection_risk: boolean; readonly keyword_count: number; readonly entity_count: number; readonly chunking_strategy: string; readonly processing_timestamp: string; readonly library_version: string; readonly config_hash: string; readonly metadata: Readonly>; } interface StructuredJSONKeywordRow { readonly keyword_id: string; readonly document_id: string; readonly content_id: string; readonly section_id: string; readonly keyword: string; readonly keyword_rank: number; } interface StructuredJSONEntityRow { readonly entity_id: string; readonly document_id: string; readonly content_id: string; readonly section_id: string; readonly entity_text: string; readonly entity_type: string; readonly normalized_form: string | null; readonly entity_rank: number; } interface StructuredJSONRelationshipRow { readonly relationship_id: string; readonly document_id: string; readonly from_content_id: string; readonly to_content_id: string; readonly relationship_type: StructuredRelationshipType; readonly is_derived: boolean; } interface StructuredJSONPageRow { readonly page_id: string; readonly document_id: string; readonly page_number: number; readonly content_item_count: number; readonly first_content_id: string | null; readonly last_content_id: string | null; readonly section_ids: readonly string[]; readonly section_path_keys: readonly string[]; readonly content_item_ids: readonly string[]; } interface StructuredJSONValidationIssueRow { readonly issue_id: string; readonly document_id: string; readonly severity: ValidationSeverity$2; readonly issue_type: string; readonly reference_type: ValidationReferenceType; readonly reference_id: string; readonly message: string; readonly details: Readonly>; } interface StructuredJSONOutput { readonly schema_version: 'structured_json.v1'; readonly generated_at: string; readonly summary: { readonly document_count: number; readonly section_count: number; readonly content_item_count: number; readonly keyword_count: number; readonly entity_count: number; readonly relationship_count: number; readonly page_count: number; readonly validation_issue_count: number; }; readonly tables: { readonly documents: readonly StructuredJSONDocumentRow[]; readonly sections: readonly StructuredJSONSectionRow[]; readonly content_items: readonly StructuredJSONContentItemRow[]; readonly content_keywords: readonly StructuredJSONKeywordRow[]; readonly content_entities: readonly StructuredJSONEntityRow[]; readonly content_relationships: readonly StructuredJSONRelationshipRow[]; readonly page_index: readonly StructuredJSONPageRow[]; readonly validation_issues: readonly StructuredJSONValidationIssueRow[]; }; readonly ingestion_hints: { readonly load_order: readonly string[]; readonly primary_keys: Readonly>; readonly foreign_keys: readonly { readonly table: string; readonly columns: readonly string[]; readonly references: string; readonly nullable?: boolean; }[]; readonly suggested_indexes: readonly { readonly table: string; readonly columns: readonly string[]; readonly unique?: boolean; }[]; }; } /** * StructuredJSONFormatter — Emits DB-friendly normalized JSON tables. */ declare class StructuredJSONFormatter extends BaseFormatter { readonly formatName = "structured_json"; format(chunks: readonly Chunk[]): StructuredJSONOutput; } interface StructuredOutputProjector { readonly projectionName: string; project(structured: StructuredJSONOutput): TOutput; } declare class StructuredProjectionFormatter extends BaseFormatter { readonly formatName: string; private readonly structuredFormatter; private readonly projector; constructor(formatName: string, projector: StructuredOutputProjector, config?: OutputConfig); format(chunks: readonly Chunk[]): TOutput; } /** * DocParser — The main entry point for document processing. * * Usage: * ```ts * const parser = new DocParser({ preset: 'financial' }); * const result = await parser.process(buffer, 'report.pdf'); * console.log(result.chunks); * console.log(result.receipt); * ``` */ declare class DocParser { private readonly config; private readonly logger; private readonly securityGate; private readonly parserRegistry; private readonly cleaningPipeline; private readonly tableNLGenerator; private readonly chunkingEngine; private readonly coverageVerifier; private readonly enrichmentPipeline; private readonly piiScanner; private readonly promptInjectionDetector; private readonly outputRouter; private readonly receiptGenerator; private readonly pluginManager; private readonly cacheManager; private configuredPluginsLoaded; private configuredPluginsLoading?; constructor(userConfig?: DocumentParserConfig); /** * Process a document through the full pipeline. * * This is the ONE-CALL API. Document in → Intelligence out. * * @param input - File buffer or string content * @param filename - Original filename (used for format detection) * @returns Full processing result with chunks, receipt, and reports */ process(input: Buffer | string, filename: string): Promise; /** * Process a file path through the full pipeline. * Uses file-backed security validation and parsing for streamable text-like formats. */ processFile(filePath: string): Promise; private runProcessPipeline; private resolveProcessBuffer; private shouldUseFileBackedProcessing; /** * Inspect a document through security, parse, and clean stages without chunking. */ inspect(input: Buffer | string, filename: string): Promise; /** * Inspect a file path through security, parse, and clean stages without chunking. */ inspectFile(filePath: string): Promise; private runInspectionPipeline; /** * Format the output using the configured formatter. */ formatOutput(result: ProcessingResult): unknown; /** * Format the same processing result into multiple outputs. */ formatOutputs(result: ProcessingResult, formats: readonly OutputFormat[]): Partial>; /** * Project structured_json output into a custom domain-specific shape. */ projectStructuredOutput(result: ProcessingResult, projector: StructuredOutputProjector): TOutput; /** * Project structured_json output into multiple custom domain-specific shapes. */ projectStructuredOutputs(result: ProcessingResult, projectors: readonly StructuredOutputProjector[]): Record; /** * Register a named structured projector for reuse across formatting calls. */ registerStructuredProjector(projector: StructuredOutputProjector, projectionName?: string): void; /** * Project structured_json output using a registered projector name. */ projectStructuredOutputByName(result: ProcessingResult, projectionName: string): unknown; /** * Project structured_json output using multiple registered projector names. */ projectStructuredOutputsByName(result: ProcessingResult, projectionNames: readonly string[]): Record; /** * List registered structured projector names. */ listStructuredProjectors(): string[]; /** * Create a readable stream for streamable output formats. */ createOutputReadable(result: ProcessingResult, format?: OutputFormat): Readable | undefined; /** * Get the resolved configuration. */ getConfig(): Readonly; /** * Get the configuration hash. */ getConfigHash(): string; /** * Get incremental reprocessing cache statistics. */ getCacheStats(): { hits: number; misses: number; hitRate: number; parseSize: number; chunkSize: number; }; /** * Clear all incremental reprocessing cache entries. */ clearCache(): void; /** * Register a plugin. * * @example * ```ts * const parser = new DocParser(); * parser.use(myOCRPlugin); * parser.use(myLLMEnricher); * ``` */ use(plugin: DocParserPlugin): Promise; /** * Dynamically load and register a plugin from a config registration source. */ loadPlugin(pluginRegistration: PluginRegistration): Promise; /** * Remove a plugin. */ removePlugin(name: string): Promise; /** * Get all registered plugins. */ getPlugins(): DocParserPlugin[]; /** * Destroy the parser and all plugins. */ destroy(): Promise; private resolveCacheConfig; private applyGovernancePolicy; private maxSecurityLevel; private ensureConfiguredPluginsLoaded; private registerPlugin; private resolvePluginRegistration; private isPluginModuleConfig; private importPluginModule; private resolveResolvedPlugin; private normalizePluginModuleSpecifier; } /** * Library constants. */ declare const LIBRARY_NAME = "docparser-core"; declare const LIBRARY_VERSION = "2.0.0"; declare const LIBRARY_LICENSE = "Apache-2.0"; /** * Error Type Definitions */ type DocParserErrorCode = 'ERR_INPUT_FILE_TOO_LARGE' | 'ERR_INPUT_UNSUPPORTED_FORMAT' | 'ERR_INPUT_CORRUPT_FILE' | 'ERR_INPUT_PASSWORD_REQUIRED' | 'ERR_INPUT_PASSWORD_INCORRECT' | 'ERR_INPUT_ENCODING_INVALID' | 'ERR_INPUT_EMPTY_FILE' | 'ERR_SECURITY_ZIP_BOMB' | 'ERR_SECURITY_PATH_TRAVERSAL' | 'ERR_SECURITY_MALICIOUS_MACRO' | 'ERR_SECURITY_JAVASCRIPT_IN_PDF' | 'ERR_SECURITY_XXE_DETECTED' | 'ERR_SECURITY_POLYGLOT_DETECTED' | 'ERR_SECURITY_VIRUS_DETECTED' | 'ERR_SECURITY_SYMLINK_IN_ARCHIVE' | 'ERR_SECURITY_POLICY_VIOLATION' | 'ERR_PARSE_FAILED' | 'ERR_PARSE_PAGE_FAILED' | 'ERR_PARSE_ELEMENT_FAILED' | 'ERR_PARSE_OCR_FAILED' | 'ERR_PARSE_TIMEOUT' | 'ERR_PARSE_OUT_OF_MEMORY' | 'ERR_CHUNK_FAILED' | 'ERR_CHUNK_STRATEGY_NOT_FOUND' | 'ERR_ENRICH_FAILED' | 'ERR_PII_PROCESSING_FAILED' | 'ERR_PROMPT_INJECTION_BLOCKED' | 'ERR_PLUGIN_INIT_FAILED' | 'ERR_PLUGIN_EXECUTION_FAILED' | 'ERR_PLUGIN_NOT_FOUND' | 'ERR_PLUGIN_INCOMPATIBLE' | 'ERR_OUTPUT_FORMAT_FAILED' | 'ERR_OUTPUT_VALIDATION_FAILED' | 'ERR_TIMEOUT' | 'ERR_OUT_OF_MEMORY' | 'ERR_INTERNAL'; interface DocParserErrorContext { readonly documentId?: string; readonly stage?: string; readonly page?: number; readonly elementId?: string; readonly elementType?: string; readonly pluginName?: string; readonly format?: string; readonly details?: Readonly>; } /** * Base error class for all DocParser errors. * * SECURITY: Error messages NEVER contain document content. * Only structural information (page numbers, element types, stage names). */ declare class DocParserError extends Error { readonly code: DocParserErrorCode; readonly context: DocParserErrorContext; readonly recoverable: boolean; readonly timestamp: string; constructor(code: DocParserErrorCode, message: string, context?: DocParserErrorContext, recoverable?: boolean, cause?: Error); /** * Returns a safe string representation that contains NO document content. */ toSafeString(): string; toJSON(): Record; } declare class InputValidationError extends DocParserError { constructor(message: string, context?: DocParserErrorContext, cause?: Error); } declare class FileTooLargeError extends DocParserError { readonly fileSize: number; readonly maxSize: number; constructor(fileSize: number, maxSize: number, context?: DocParserErrorContext); } declare class UnsupportedFormatError extends DocParserError { readonly detectedFormat: string; readonly allowedFormats: readonly string[]; constructor(detectedFormat: string, allowedFormats: readonly string[], context?: DocParserErrorContext); } declare class CorruptFileError extends DocParserError { constructor(message: string, context?: DocParserErrorContext, cause?: Error); } declare class PasswordRequiredError extends DocParserError { constructor(context?: DocParserErrorContext); } declare class EmptyFileError extends DocParserError { constructor(context?: DocParserErrorContext); } declare class SecurityError extends DocParserError { constructor(code: DocParserErrorCode, message: string, context?: DocParserErrorContext, cause?: Error); } declare class ZipBombError extends DocParserError { constructor(compressionRatio: number, context?: DocParserErrorContext); } declare class MaliciousContentError extends DocParserError { readonly threatType: string; constructor(threatType: string, message: string, context?: DocParserErrorContext); } declare class ParsingError extends DocParserError { constructor(message: string, context?: DocParserErrorContext, cause?: Error); } declare class PageParsingError extends DocParserError { readonly pageNumber: number; constructor(pageNumber: number, message: string, context?: DocParserErrorContext, cause?: Error); } declare class ElementParsingError extends DocParserError { constructor(elementType: string, message: string, context?: DocParserErrorContext, cause?: Error); } declare class ChunkingError extends DocParserError { constructor(message: string, context?: DocParserErrorContext, cause?: Error); } declare class EnrichmentError extends DocParserError { constructor(message: string, context?: DocParserErrorContext, cause?: Error); } declare class PIIProcessingError extends DocParserError { constructor(message: string, context?: DocParserErrorContext, cause?: Error); } declare class PluginError extends DocParserError { readonly pluginName: string; constructor(pluginName: string, message: string, context?: DocParserErrorContext, cause?: Error); } declare class TimeoutError extends DocParserError { readonly timeoutMs: number; constructor(stage: string, timeoutMs: number, context?: DocParserErrorContext); } declare class OutOfMemoryError extends DocParserError { constructor(stage: string, context?: DocParserErrorContext); } /** * Detected format information from file analysis. */ interface DetectedFormat { readonly mimeType: string; readonly extension: string; readonly confidence: number; readonly method: 'magic_bytes' | 'extension' | 'content_sniff' | 'declared'; } interface FileValidationOptions { readonly maxFileSize: number; readonly allowedFormats: readonly string[]; } interface FileValidationResult { readonly valid: boolean; readonly format: DetectedFormat; readonly fileSize: number; readonly hash: string; } declare class FileValidator { private readonly logger; constructor(logger: pino.Logger); /** * Validates and identifies a file buffer. * * Checks: * 1. Not empty * 2. Within size limits * 3. Format detection via magic bytes * 4. Format is in allowed list * * @throws EmptyFileError * @throws FileTooLargeError * @throws UnsupportedFormatError * @throws CorruptFileError */ validate(buffer: Buffer, filename: string, options: FileValidationOptions): Promise; validateFile(filePath: string, filename: string, options: FileValidationOptions): Promise; /** * Detects file format using multiple methods: * 1. Magic bytes (highest confidence) * 2. Extension mapping (medium confidence) * 3. Content sniffing (lower confidence) */ detectFormat(buffer: Buffer, filename: string): Promise; private detectFormatFromSample; private detectFormatInternal; /** * Extracts the file extension (lowercase, with dot). */ private extractExtension; /** * Detects common supported binary formats by signature without third-party parsing. */ private detectMagicFormat; private magic; private startsWithAscii; private startsWithBytes; /** * Basic content validation for text-based formats. */ private validateTextContent; /** * Content sniffing for formats not caught by magic bytes or extension. */ private sniffContent; /** * Checks if buffer is valid UTF-8 text. */ private isValidUtf8; /** * Checks if a MIME type is in the allowed list. */ private isFormatAllowed; /** * Computes SHA-256 hash of the file buffer. */ private computeHash; private computeFileHash; private readFileHead; } /** * Threat detection result for a single check. */ interface ThreatCheckResult { readonly check: string; readonly passed: boolean; readonly threatType?: string; readonly severity?: 'low' | 'medium' | 'high' | 'critical'; readonly details?: string; } /** * Overall threat scan result. */ interface ThreatScanResult { readonly safe: boolean; readonly checks: readonly ThreatCheckResult[]; readonly threats: readonly ThreatCheckResult[]; } interface ThreatDetectionOptions { readonly blockMacros: boolean; readonly blockJavascriptInPdf: boolean; readonly blockXxe: boolean; readonly blockPolyglots: boolean; } /** * Detects various threats in document files. * * Checks for: * - ZIP bombs (excessive compression ratio) * - PDF JavaScript injection * - Office macros (VBA) * - XML External Entity (XXE) attacks * - Path traversal in archives * - Polyglot files * - Symlinks in archives */ declare class ThreatDetector { private readonly logger; constructor(logger: pino.Logger); /** * Run all threat detection checks on a file buffer. * * @throws ZipBombError * @throws MaliciousContentError */ scan(buffer: Buffer, mimeType: string, filename: string, options: ThreatDetectionOptions): Promise; scanFile(filePath: string, mimeType: string, filename: string, options: ThreatDetectionOptions): Promise; private checkPdfJavascript; private checkPdfLaunchActions; private checkPdfEmbeddedFiles; private checkOfficeMacros; private checkXxe; private checkHtmlScripts; private checkArchiveBomb; private checkPathTraversal; private checkPolyglot; private isOfficeFormat; private isXmlBased; private isArchiveFormat; private isZipBasedArchive; private checkPdfJavascriptFile; private checkPdfLaunchActionsFile; private checkPdfEmbeddedFilesFile; private checkOfficeMacrosFile; private checkXxeFile; private checkArchiveBombFile; private checkPathTraversalFile; private finalizeScan; private supportsSampleBasedFileScan; private getFileScanSampleBytes; private readFileHead; private fileContainsAnyPattern; } /** * Security validation result returned from the gate. */ interface SecurityGateResult { readonly passed: boolean; readonly validation: FileValidationResult; readonly threatScan: ThreatScanResult; readonly report: SecurityReport; } /** * SecurityGate — the first stage of the processing pipeline. * * NOTHING gets processed without passing through security first. * This gate validates, scans, and reports on every input file. */ declare class SecurityGate { private readonly logger; private readonly fileValidator; private readonly threatDetector; private readonly config; constructor(parentLogger: pino.Logger, config?: SecurityConfig); /** * Validate a file through all security checks. * * @param buffer - The file content * @param filename - Original filename (for format detection) * @returns SecurityGateResult with validation details * @throws Various security errors for critical threats */ validate(buffer: Buffer, filename: string): Promise; validateFile(filePath: string, filename: string): Promise; private finalizeValidation; } interface PromptInjectionResult { readonly detected: boolean; readonly matches: readonly PromptInjectionMatch[]; readonly sanitizedText?: string; readonly riskScore: number; } interface PromptInjectionMatch { /** Canonical name of the matched pattern (e.g. 'enter_special_mode'). */ readonly name: string; /** Back-compat alias for name. */ readonly pattern: string; readonly category: string; readonly position: number; readonly length: number; readonly severity: 'low' | 'medium' | 'high'; } /** * Detects prompt injection attempts in document content. * * Documents being fed to RAG → LLM may contain adversarial text * designed to manipulate the LLM. This detector flags such content. */ declare class PromptInjectionDetector { private readonly logger; private readonly patterns; constructor(logger: pino.Logger, customPatterns?: readonly string[]); /** * Scan text for prompt injection patterns. */ detect(text: string, sensitivity?: 'low' | 'medium' | 'high'): PromptInjectionResult; /** * Sanitize text by removing detected injection patterns. */ sanitize(text: string, sensitivity?: 'low' | 'medium' | 'high'): string; /** * Wrap suspicious content in safety markers. */ wrapContent(text: string): string; private getBuiltInPatterns; private compileCustomPatterns; private detectInvisibleCharacters; private calculateRiskScore; } /** * PIIScanner — Scans chunks for PII and applies configured action. */ declare class PIIScanner { private readonly logger; private readonly config; private readonly provider; private readonly allowlist; constructor(parentLogger: pino.Logger, config?: PIIConfig); /** * Scan an array of chunks for PII. * Returns modified chunks and a PII report. */ scan(chunks: readonly TChunk[]): Promise<{ chunks: (TChunk & { piiDetected: boolean; piiTypes: readonly string[]; piiMasked: boolean; })[]; report: PIIReport; }>; private hashPII; private scanChunk; private mapWithConcurrency; private emptyReport; } /** * ConfigManager handles configuration resolution, merging, and validation. * * Config hierarchy (later overrides earlier): * 1. Built-in defaults * 2. Preset config * 3. User-provided global config * 4. Per-document config overrides */ declare class ConfigManager { private readonly logger; private readonly resolvedConfig; private readonly configHash; constructor(userConfig?: DocumentParserConfig, parentLogger?: pino.Logger); /** * Get the fully resolved configuration. */ getConfig(): Readonly; /** * Get the deterministic hash of the configuration. * Used for cache keys and reproducibility. */ getConfigHash(): string; /** * Create a new ConfigManager with per-document overrides. */ withOverrides(overrides: Partial): ConfigManager; /** * Resolve config: defaults → preset → user config */ private resolve; /** * Load a named preset configuration. */ private loadPreset; /** * Load a runtime pipeline preset configuration. */ private loadRuntimePipelinePreset; /** * Deep merge two objects. Source values override target. * Arrays are replaced, not concatenated. * undefined values in source are skipped. */ private deepMerge; /** * Compute a deterministic hash of the configuration. */ private computeHash; } /** * Default configuration — sensible production defaults. * * These values represent the "general" preset. * Security features are ON by default. */ declare const DEFAULT_CONFIG: Readonly>; type BaseElementInput = { readonly sourceLocation?: SourceLocation; readonly confidence?: number; readonly parentHeadingRef?: string; readonly sectionPath?: readonly string[]; readonly flags?: readonly string[]; }; declare class UDMBuilder { private readonly id; private source; private metadata; private structure; private elements; private crossReferences; private processingNotes; constructor(options?: { readonly id?: string; readonly source?: Partial & Pick; }); /** * Set/override document source metadata. * * Tests and some pipelines use this to construct UDMs manually. */ setSource(source: DocumentSource): this; setMetadata(meta: Partial> & { readonly custom?: Readonly>; }): this; setPageCount(pageCount: number): this; addWarning(stage: string, message: string, elementRef?: string, page?: number): this; addError(stage: string, message: string, elementRef?: string, page?: number): this; addHeading(input: { readonly level: 1 | 2 | 3 | 4 | 5 | 6; readonly content: string; readonly numbering?: string; readonly isAutoDetected?: boolean; } & BaseElementInput): HeadingElement; addParagraph(input: { readonly content: string; readonly formatting?: readonly TextFormatting[]; readonly links?: readonly LinkInfo[]; readonly isContinuation?: boolean; } & BaseElementInput): ParagraphElement; addList(input: { readonly listType: 'ordered' | 'unordered' | 'definition'; readonly items: readonly ListItem[]; readonly introText?: string; } & BaseElementInput): ListElement; addCode(input: { readonly content: string; readonly language?: string; readonly isInline?: boolean; readonly description?: string; } & BaseElementInput): CodeElement; addTable(input: { readonly caption?: string; readonly headers: readonly TableCell[]; readonly rows: readonly (readonly TableCell[])[]; readonly hasMergedCells?: boolean; readonly naturalLanguage?: string; readonly structuredData?: readonly Record[]; readonly summary?: string; } & BaseElementInput): TableElement; addImage(input: { readonly imageType: ImageElement['imageType']; readonly imageRef: string; readonly imageHash?: string; readonly dimensions?: { readonly width: number; readonly height: number; }; readonly format?: string; readonly caption?: string; readonly altText?: string; readonly ocrText?: string; readonly aiDescription?: string; readonly containsText: boolean; readonly containsData: boolean; readonly isDecorative: boolean; readonly nearbyContext?: string; readonly visualContextSummary?: string; } & BaseElementInput): ImageElement; addCallout(input: { readonly calloutType: CalloutElement['calloutType']; readonly title?: string; readonly content: string; } & BaseElementInput): CalloutElement; addPageBreak(fromPage: number, toPage: number, input?: BaseElementInput): PageBreakElement; build(): DocumentUDM; private baseElement; private addOutlineNode; } interface UDMValidationResult { readonly valid: boolean; readonly errors: readonly string[]; } declare class UDMValidator { static validate(udm: DocumentUDM): UDMValidationResult; } declare abstract class BaseParser { protected readonly logger: pino.Logger; protected readonly config: DocumentParserConfig; abstract readonly name: string; abstract readonly supportedMimeTypes: readonly string[]; constructor(logger: pino.Logger, config: DocumentParserConfig); canParse(mimeType: string): boolean; protected createBuilder(filename: string, fileHash: string, mimeType: string, fileSize: number, formatConfidence: number): UDMBuilder; abstract parse(buffer: Buffer, filename: string, fileHash: string, mimeType: string): Promise; parseFile(filePath: string, filename: string, fileHash: string, mimeType: string): Promise; private guessFormat; } /** * ParserRegistry manages all available parsers and routes documents * to the correct parser based on detected MIME type. */ declare class ParserRegistry { private readonly parsers; private readonly logger; constructor(parentLogger: pino.Logger, config: DocumentParserConfig); getParser(mimeType: string): BaseParser; parse(buffer: Buffer, filename: string, fileHash: string, mimeType: string): Promise; parseFile(filePath: string, filename: string, fileHash: string, mimeType: string): Promise; registerParser(parser: BaseParser): void; getSupportedMimeTypes(): string[]; } declare class PlainTextParser extends BaseParser { readonly name = "PlainTextParser"; readonly supportedMimeTypes: readonly ["text/plain", "application/yaml", "text/x-rst", "text/asciidoc", "application/x-latex", "application/rtf", "text/vtt", "application/x-subrip", "message/rfc822"]; private readonly largeFileReader; constructor(logger: pino.Logger, config: DocumentParserConfig); parse(buffer: Buffer, filename: string, fileHash: string, mimeType: string): Promise; parseFile(filePath: string, filename: string, fileHash: string, mimeType: string): Promise; private addParagraphsFromText; } declare class MarkdownParser extends BaseParser { readonly name = "MarkdownParser"; readonly supportedMimeTypes: readonly ["text/markdown", "text/x-markdown"]; private readonly largeFileReader; constructor(logger: pino.Logger, config: DocumentParserConfig); parse(buffer: Buffer, filename: string, fileHash: string, mimeType: string): Promise; parseFile(filePath: string, filename: string, fileHash: string, mimeType: string): Promise; private parseMarkdownText; } declare class CSVParser extends BaseParser { readonly name = "CSVParser"; readonly supportedMimeTypes: readonly ["text/csv", "application/csv", "text/tab-separated-values"]; private readonly largeFileReader; constructor(logger: pino.Logger, config: DocumentParserConfig); parse(buffer: Buffer, filename: string, fileHash: string, mimeType: string): Promise; parseFile(filePath: string, filename: string, fileHash: string, mimeType: string): Promise; private addTableFromLines; private resolveDelimiter; } declare class HTMLParser extends BaseParser { readonly name = "HTMLParser"; readonly supportedMimeTypes: readonly ["text/html", "application/xhtml+xml"]; private readonly largeFileReader; constructor(logger: pino.Logger, config: DocumentParserConfig); parse(buffer: Buffer, filename: string, fileHash: string, mimeType: string): Promise; parseFile(filePath: string, filename: string, fileHash: string, mimeType: string): Promise; private parseHtmlContent; } declare class PDFParser extends BaseParser { readonly name = "PDFParser"; readonly supportedMimeTypes: readonly ["application/pdf"]; constructor(logger: pino.Logger, config: DocumentParserConfig); parse(buffer: Buffer, filename: string, fileHash: string, mimeType: string): Promise; parseFile(filePath: string, filename: string, fileHash: string, mimeType: string): Promise; private populateBuilderFromLoadingTask; private extractMetadata; private extractPageText; private rasterizePage; private getRasterScale; } declare class ImageParser extends BaseParser { readonly name = "ImageParser"; readonly supportedMimeTypes: readonly ["image/png", "image/jpeg", "image/tiff", "image/webp"]; constructor(logger: pino.Logger, config: DocumentParserConfig); parse(buffer: Buffer, filename: string, fileHash: string, mimeType: string): Promise; } declare class DOCXParser extends BaseParser { readonly name = "DOCXParser"; readonly supportedMimeTypes: readonly ["application/vnd.openxmlformats-officedocument.wordprocessingml.document"]; private readonly ooxml; constructor(logger: pino.Logger, config: DocumentParserConfig); parse(buffer: Buffer, filename: string, fileHash: string, mimeType: string): Promise; parseFile(filePath: string, filename: string, fileHash: string, mimeType: string): Promise; private populateBuilderFromArchive; private extractDocumentText; private normalizeDocumentTextFragment; private extractEmbeddedImages; private extractImageReferences; private collectImageReferences; } /** * PPTX Parser — Extracts structured content from PowerPoint files. * * PPTX structure: * - ppt/presentation.xml — slide order + metadata * - ppt/slides/slideN.xml — individual slide content * - ppt/notesSlides/ — speaker notes * - ppt/charts/ — chart data * - ppt/media/ — embedded images/media * * Each slide becomes a section. Elements extracted per slide: * - Title → heading * - Body text → paragraphs + lists * - Tables → table elements * - Charts → chart elements with data * - Images → image references * - Speaker notes → callout elements */ declare class PPTXParser extends BaseParser { readonly name = "PPTXParser"; readonly supportedMimeTypes: readonly ["application/vnd.openxmlformats-officedocument.presentationml.presentation"]; private readonly ooxml; constructor(logger: pino.Logger, config: DocumentParserConfig); parse(buffer: Buffer, filename: string, fileHash: string, mimeType: string): Promise; parseFile(filePath: string, filename: string, fileHash: string, mimeType: string): Promise; private populateBuilderFromArchive; private processSlide; private extractSlideTitle; private extractTable; private extractSpeakerNotes; private getSlideRIds; private detectCellDataType; } /** * XLSX Parser — Extracts structured content from Excel files. * * XLSX structure: * - xl/workbook.xml — sheet names + order * - xl/worksheets/sheetN.xml — cell data * - xl/sharedStrings.xml — shared string table * - xl/styles.xml — cell formatting * - xl/charts/ — embedded charts * * Each worksheet becomes a separate table element. * Features: * - Shared string resolution * - Data type detection per cell * - Empty row/column trimming * - Multi-sheet support * - Natural language generation per sheet */ declare class XLSXParser extends BaseParser { readonly name = "XLSXParser"; readonly supportedMimeTypes: readonly ["application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"]; private readonly ooxml; constructor(logger: pino.Logger, config: DocumentParserConfig); parse(buffer: Buffer, filename: string, fileHash: string, mimeType: string): Promise; parseFile(filePath: string, filename: string, fileHash: string, mimeType: string): Promise; private populateBuilderFromArchive; private processSheet; private loadSharedStrings; private getCellValue; private getInlineString; private colRefToIndex; private trimAndSplit; private isEmptyRow; private generateSheetNL; private detectCellDataType; private getSheetInfo; } interface OOXMLArchive { readText(path: string): Promise; readBinary(path: string): Promise; listFiles(pattern: RegExp): string[]; close(): Promise; } declare class OOXMLUtils { private readonly parser; constructor(); /** * Extract and parse an XML part from the ZIP. */ extractXML(archive: OOXMLArchive, path: string): Promise; /** * Extract binary content (images, etc.) from the ZIP. */ extractBinary(archive: OOXMLArchive, path: string): Promise; /** * List all files in the ZIP matching a pattern. */ listFiles(archive: OOXMLArchive, pattern: RegExp): string[]; /** * Extract core document properties (title, author, dates). */ extractCoreProperties(archive: OOXMLArchive): Promise<{ title?: string; author?: string; subject?: string; description?: string; createdDate?: string; modifiedDate?: string; lastModifiedBy?: string; keywords?: string; category?: string; }>; /** * Extract text from a rich-text paragraph array (DrawingML ). */ extractDrawingMLText(paragraphs: any[] | any): { text: string; isBold?: boolean; level?: number; }[]; /** * Extract relationships from a .rels file. */ extractRelationships(archive: OOXMLArchive, relsPath: string): Promise>; getTextValue(node: any): string | undefined; toArray(value: T | T[] | undefined | null): T[]; } interface CleaningResult { readonly udm: DocumentUDM; readonly stats: CleaningStats; } interface CleaningSample { readonly kind: 'text_normalized' | 'hyphenation_fixed' | 'header_removed' | 'footer_removed' | 'boilerplate_removed' | 'paragraph_merged'; readonly before?: string; readonly after?: string; readonly preview?: string; readonly count?: number; } interface CleaningStats { readonly elementsProcessed: number; readonly textNormalizations: number; readonly paragraphsMerged: number; readonly headersRemoved: number; readonly footersRemoved: number; readonly boilerplateRemoved: number; readonly hyphenationsFixed: number; readonly durationMs: number; readonly samples: readonly CleaningSample[]; } /** * CleaningPipeline — Orchestrates all cleaning and normalization steps. * * Cleaning order: * 1. Text cleaning (unicode, whitespace, quotes, etc.) * 2. Hyphenation fixing * 3. Header/footer removal * 4. Repeated boilerplate removal * 5. Custom pattern removal * 6. Paragraph merging */ declare class CleaningPipeline { private readonly logger; private readonly config; private readonly textCleaner; private readonly hyphenationFixer; private readonly paragraphMerger; private readonly headerFooterDetector; private readonly repeatedBoilerplateDetector; constructor(parentLogger: pino.Logger, config?: CleaningConfig); /** * Clean a DocumentUDM by processing all text content. */ clean(udm: DocumentUDM): CleaningResult; /** * Check if an element should be preserved as-is (no cleaning). */ private shouldPreserve; /** * Clean the text content of a single element. */ private cleanElement; /** * Remove elements matching custom patterns. */ private removeCustomPatterns; /** * Count total content length across all text elements. */ private countContent; private toPreview; } /** * TextCleaner — Normalizes and cleans raw text content. * * Handles: * - Unicode normalization (NFC) * - Whitespace normalization * - Control character removal * - Quote/dash normalization * - Soft hyphen removal * - Zero-width character removal */ declare class TextCleaner { /** * Apply all text cleaning steps. */ clean(text: string, options?: TextCleaningOptions): string; /** * NFC Unicode normalization — ensures consistent character representation. * e.g., "é" composed vs decomposed forms become consistent. */ normalizeUnicode(text: string): string; /** * Remove control characters except common whitespace. * Preserves: \n, \r, \t * Removes: \x00-\x08, \x0B, \x0C, \x0E-\x1F, \x7F */ removeControlCharacters(text: string): string; /** * Remove zero-width and invisible characters. * These can be used for prompt injection attacks. */ removeZeroWidthCharacters(text: string): string; /** * Remove soft hyphens (used for line-break hints, not real hyphens). */ removeSoftHyphens(text: string): string; /** * Normalize fancy/curly quotes to straight quotes. */ normalizeQuotes(text: string): string; /** * Normalize various dash types. * Em-dash (—) → " — " (with spaces) * En-dash (–) → "-" when between numbers, " – " otherwise */ normalizeDashes(text: string): string; /** * Normalize ellipsis character. */ normalizeEllipsis(text: string): string; /** * Normalize whitespace: * - Multiple spaces → single space * - Multiple newlines → double newline (paragraph break) * - Tabs → single space * - Trim lines * - Non-breaking space → regular space */ normalizeWhitespace(text: string): string; } interface TextCleaningOptions { readonly normalizeUnicode?: boolean; readonly removeControlCharacters?: boolean; readonly removeZeroWidthCharacters?: boolean; readonly removeSoftHyphens?: boolean; readonly normalizeQuotes?: boolean; readonly normalizeDashes?: boolean; readonly normalizeEllipsis?: boolean; readonly normalizeWhitespace?: boolean; } /** * HyphenationFixer — Repairs words broken across lines by hyphenation. * * PDF and other document extractors often produce: * "docu-\nment" or "imple-\r\nmentation" * This fixer merges them back: "document", "implementation" * * Rules: * - Only merge when hyphen is at line end * - Don't merge if both parts are standalone words (e.g., "well-\nknown") * - Don't merge compound words that should stay hyphenated */ declare class HyphenationFixer { private static readonly COMPOUND_WORDS; /** * Fix line-break hyphenation in text. */ fix(text: string): string; } /** * ParagraphMerger — Merges paragraphs that were broken across pages or columns. * * PDF extraction often produces broken paragraphs: * - A paragraph split across two pages becomes two paragraph elements * - A paragraph in a multi-column layout gets fragmented * * This merger detects and reconnects them based on: * - Paragraph doesn't end with sentence-ending punctuation * - Next paragraph doesn't start with a capital letter (unless after period) * - Paragraphs are adjacent in the element sequence * - Continuation flag from parser */ declare class ParagraphMerger { /** * Merge broken paragraphs in element list. * Returns a new list with merged paragraphs. */ merge(elements: readonly AnyDocumentElement[]): AnyDocumentElement[]; /** * Determine if two adjacent paragraphs should be merged. */ private shouldMerge; private hasHardBoundary; private looksLikeStandaloneLabel; /** * Merge two paragraph elements into one. */ private mergeParagraphs; } /** * HeaderFooterDetector — Detects and marks repeating page headers/footers. * * Strategy: * 1. Group text elements by their page position (top/bottom of page) * 2. Look for content that repeats across multiple pages * 3. Mark repeating content for removal * * Common patterns: * - Document title repeated at top of every page * - Page numbers ("Page 1 of 10", "- 3 -") * - Company name / confidentiality notice * - Chapter titles * - Date stamps */ declare class HeaderFooterDetector { private readonly repeatThreshold; /** * @param repeatThreshold - Minimum number of pages content must appear on * to be considered a header/footer (default: 3) */ constructor(repeatThreshold?: number); /** * Detect and remove header/footer elements. * Returns filtered elements and list of removed content. */ detectAndRemove(elements: readonly AnyDocumentElement[]): { elements: AnyDocumentElement[]; removedHeaders: string[]; removedFooters: string[]; }; /** * Group elements by page, separating top and bottom sections. */ private groupByPage; /** * Find text that repeats across multiple pages at the same position. */ private findRepeatingPatterns; /** * Build a regex pattern that matches common page number formats. */ private buildPageNumberPattern; /** * Normalize text for comparison (case-insensitive, whitespace-normalized). */ private normalizeForComparison; } /** * TableNLGenerator — Converts tables into natural language descriptions. * * This is a KEY DIFFERENTIATOR. Docling outputs structured tables. * We output structured tables AND searchable natural language text. * * Strategies: * - Small tables (≤5 rows): describe every row * - Medium tables (6-20 rows): summary + key statistics * - Large tables (>20 rows): high-level summary + statistics */ declare class TableNLGenerator { /** * Generate a natural language description of a table. */ generate(table: TableElement): string; /** * Generate a brief summary (for metadata). */ generateSummary(table: TableElement): string; private generateOpening; private generateSmallTableDescription; private generateMediumTableDescription; private generateLargeTableDescription; private generateStatistics; private findNotableValues; private extractNumericValues; private formatNumber; } interface TokenCounter { count(text: string): Promise; } declare function approximateTokenCount(text: string): number; declare function createTokenCounter(type: TokenCounterType, customTokenCounter?: ((text: string) => number) | undefined): TokenCounter; interface ChunkingResult { readonly chunks: Chunk[]; readonly strategyUsed: string; readonly stats: { readonly totalChunks: number; readonly averageTokens: number; readonly minTokens: number; readonly maxTokens: number; readonly durationMs: number; }; } /** * ChunkingEngine — Orchestrates the chunking process. * * Pipeline: * 1. Select strategy (based on config or auto-detect) * 2. Generate raw chunks * 3. Merge small chunks * 4. Count tokens * 5. Build final Chunk objects with navigation links * 6. Validate coverage */ declare class ChunkingEngine { private readonly logger; private readonly config; private readonly tokenCounter; constructor(parentLogger: pino.Logger, config: ChunkingConfig, tokenCounter: TokenCounter); /** * Chunk a document using the configured strategy. */ chunk(udm: DocumentUDM, configHash: string): Promise; /** * Merge chunks that are below the minimum token threshold. */ private mergeSmallChunks; /** * Merge two raw chunks into one. */ private mergeRawChunks; /** * Build final Chunk objects from raw chunks. */ private buildFinalChunks; private buildSectionMetadataMap; private createDefaultSectionMetadata; private buildSectionPathKey; private createStrategies; private resolveRuntimeConfig; private selectAdaptiveProfile; private getAdaptiveOverrides; /** * Link chunks with prev/next navigation. */ private linkChunks; /** * Calculate quality score for a chunk. */ private calculateQualityScore; } /** * ChunkBuilder — Fluent builder for creating Chunk objects. */ declare class ChunkBuilder { private chunk; private readonly documentId; private readonly configHash; constructor(documentId: string, configHash: string); private updateChunkId; setContent(content: string): this; setContentType(type: ChunkContentType): this; setContentElements(types: ElementType[]): this; setDocumentName(name: string): this; setDocumentHash(hash: string): this; setSectionPath(path: string[]): this; setPageNumbers(pages: number[]): this; setSourceElementIds(ids: string[]): this; setPosition(index: number, total: number): this; setNavigation(prev: string | null, next: string | null): this; setParent(parentId: string | null): this; setChildren(childIds: string[]): this; setRelationships(relationships: ChunkRelationship[]): this; setTokenCount(count: number): this; setLanguage(lang: string): this; setConfidence(score: number): this; setImportance(score: number): this; setQuality(score: number): this; addQualityFlag(flag: ChunkQualityFlags): this; setChunkingStrategy(strategy: string): this; setPII(detected: boolean, types?: string[], masked?: boolean): this; setPromptInjectionRisk(risk: boolean): this; setSecurityClassification(level: string): this; setKeywords(keywords: string[]): this; setEntities(entities: { text: string; type: string; normalizedForm?: string; }[]): this; setSummary(summary: string): this; setQuestions(questions: string[]): this; setMetadata(key: string, value: unknown): this; build(): Chunk; } /** * CoverageVerifier — Verifies that 100% of source document content * is represented in at least one chunk. * * This is a critical quality check that ensures no content is lost * during the chunking process. */ declare class CoverageVerifier { /** * Verify content coverage between source document and chunks. */ verify(udm: DocumentUDM, chunks: readonly Chunk[]): CoverageReport; /** * Extract all text segments from document elements. */ private extractSourceSegments; /** * Normalize text for comparison. */ private normalize; } /** * RawChunk — Intermediate representation before final Chunk is built. */ interface RawChunkAudit { readonly creationReason: string; readonly splitReason?: 'max_tokens' | 'element_boundary' | 'overlap_window'; readonly sourceStrategy?: string; readonly mergedSmallChunks?: boolean; readonly mergedChunkCount?: number; } interface RawChunk { readonly content: string; readonly contentType: 'text' | 'table' | 'chart' | 'image' | 'code' | 'audio' | 'mixed'; readonly elementIds: string[]; readonly elementTypes: ElementType[]; readonly sectionPath: string[]; readonly pageNumbers: number[]; readonly confidence: number; readonly importance: number; readonly audit?: RawChunkAudit; } /** * BaseStrategy — Abstract base for all chunking strategies. */ declare abstract class BaseStrategy { protected readonly logger: pino.Logger; protected readonly config: ChunkingConfig; protected readonly tokenCounter: TokenCounter; constructor(logger: pino.Logger, config: ChunkingConfig, tokenCounter: TokenCounter); abstract readonly name: string; /** * Chunk the document's elements into raw chunks. */ abstract chunk(udm: DocumentUDM): Promise; /** * Get the text content of an element for chunking purposes. */ protected getElementText(element: AnyDocumentElement): string; /** * Convert table to plain text (fallback when no NL is available). */ protected tableToText(table: { headers: readonly { content: string; }[]; rows: readonly (readonly { content: string; }[])[]; }): string; /** * Count tokens in text. */ protected countTokens(text: string): Promise; /** * Get heading context string for a section path. */ protected buildHeadingContext(sectionPath: readonly string[]): string; /** * Split text at sentence boundaries. */ protected splitSentences(text: string): string[]; protected splitOversizedText(text: string, headingPrefix: string, maxTokens: number): Promise; private buildTextUnits; private expandTextUnits; private splitByWords; /** * Determine element importance for scoring. */ protected getElementImportance(element: AnyDocumentElement): number; } /** * HierarchicalStrategy — Chunks based on document heading structure. * * Algorithm: * 1. Group elements under their parent headings * 2. Each heading section becomes a chunk * 3. If a section exceeds max tokens, split at sub-heading boundaries * 4. If still too large, split at paragraph boundaries * 5. If still too large, split at sentence boundaries */ declare class HierarchicalStrategy extends BaseStrategy { readonly name = "hierarchical"; constructor(logger: pino.Logger, config: ChunkingConfig, tokenCounter: TokenCounter); chunk(udm: DocumentUDM): Promise; /** * Group elements into sections based on heading hierarchy. */ private groupBySections; /** * Chunk a single section. If too large, recursively split. */ private chunkSection; /** * Split elements into chunks that fit within token limits. */ private splitByElements; /** * Split a single text element when it exceeds max tokens. */ private splitOversizedElement; private isAtomicElement; private getElementContentType; private detectContentType; private buildRawChunk; private averageConfidence; private averageImportance; } /** * SlidingWindowStrategy — Token-based window with smart boundaries. * * Enhanced sliding window that: * - Never splits mid-sentence * - Respects element boundaries for atomic elements * - Provides configurable overlap * - Includes heading context */ declare class SlidingWindowStrategy extends BaseStrategy { readonly name = "sliding_window"; constructor(logger: pino.Logger, config: ChunkingConfig, tokenCounter: TokenCounter); chunk(udm: DocumentUDM): Promise; private buildSegments; private buildWindowChunk; private isAtomicElement; private segmentContentType; } /** * ElementAwareStrategy — THE primary strategy for mixed-content documents. * * Key principle: Visual elements (tables, charts, images) are NEVER split. * They become self-contained chunks with full context. * * Algorithm: * 1. Walk through elements in reading order * 2. Accumulate text elements into text chunks * 3. When a visual element is encountered: * a. Flush accumulated text as a text chunk * b. Create a self-contained chunk for the visual element * c. Include heading context and surrounding text * 4. Heading elements start new chunk accumulation groups */ declare class ElementAwareStrategy extends BaseStrategy { readonly name = "element_aware"; constructor(logger: pino.Logger, config: ChunkingConfig, tokenCounter: TokenCounter); chunk(udm: DocumentUDM): Promise; private createOversizedTextChunks; /** * Create a self-contained chunk for a visual element (table, chart, image). */ private createVisualChunk; /** * Create a chunk for a code block. */ private createCodeChunk; private isVisualElement; private getVisualContentType; } /** * HybridAutoStrategy — Automatically selects the best strategy. * * Analyzes document characteristics and chooses: * - Well-structured (many headings) → Hierarchical * - Mixed content (tables, charts, images) → Element-Aware * - Unstructured text → Sliding Window * - Mix of both → Element-Aware (best default) */ declare class HybridAutoStrategy extends BaseStrategy { readonly name = "hybrid_auto"; private lastSelectedStrategyName; private readonly hierarchical; private readonly slidingWindow; private readonly elementAware; constructor(logger: pino.Logger, config: ChunkingConfig, tokenCounter: TokenCounter); chunk(udm: DocumentUDM): Promise; getLastSelectedStrategyName(): string; /** * Analyze document and select best strategy. */ private selectStrategy; } /** * SemanticStrategy — Chunks based on content similarity/topic shifts. * * Algorithm (without embeddings — using lexical similarity): * 1. Split document into sentences * 2. Compute sentence-to-sentence similarity (Jaccard on word n-grams) * 3. Detect topic boundaries where similarity drops below threshold * 4. Group sentences between boundaries into chunks * 5. Apply min/max token constraints * * When an embedding function is provided (via plugin), uses * cosine similarity instead of Jaccard for much better results. */ declare class SemanticStrategy extends BaseStrategy { readonly name = "semantic_similarity"; private readonly similarityThreshold; private readonly windowSize; private readonly embedFn?; constructor(logger: pino.Logger, config: ChunkingConfig, tokenCounter: TokenCounter, embedFn?: (text: string) => Promise); chunk(udm: DocumentUDM): Promise; private extractSentences; private computeSimilarities; private computeJaccardSimilarities; private computeEmbeddingSimilarities; private findBoundaries; private groupByBoundaries; private splitGroup; private buildGroupChunk; private getBigrams; private cosineSimilarity; } interface EnrichmentResult { readonly chunks: Chunk[]; readonly stats: EnrichmentStats; } interface EnrichmentStats { readonly chunksEnriched: number; readonly totalKeywords: number; readonly totalEntities: number; readonly durationMs: number; } /** * EnrichmentPipeline — Adds metadata, keywords, entities, and scores to chunks. * * Steps: * 1. Keyword extraction (TF-IDF across all chunks) * 2. Entity extraction (regex NER) * 3. Importance scoring * 4. Cross-reference linking */ declare class EnrichmentPipeline { private readonly logger; private readonly config; private readonly keywordExtractor; private readonly entityExtractor; private readonly importanceScorer; constructor(parentLogger: pino.Logger, config?: EnrichmentConfig); /** * Enrich all chunks with keywords, entities, scores, and links. */ enrich(chunks: readonly Chunk[], udm: DocumentUDM): EnrichmentResult; private enrichKeywords; private enrichEntities; private enrichImportance; private applyFeedbackSignals; private enrichCrossReferences; private applySemanticDedup; private collectSemanticSignals; private collectSharedTerms; private calculateJaccardSimilarity; private tokenizeSemanticContent; private normalizeSemanticTerm; } declare class KeywordExtractor { private readonly stopWords; private readonly language; constructor(language?: string); /** * Extract keywords from a single text using term frequency. * Use when you only have one chunk / no corpus. */ extractFromText(text: string, maxKeywords?: number): string[]; /** * Extract keywords using TF-IDF across a corpus of chunks. * Returns keywords per chunk index. */ extractFromCorpus(texts: readonly string[], maxKeywords?: number): string[][]; /** * Tokenize text into terms, removing stop words and short tokens. */ private tokenize; /** * Compute term frequency (normalized by document length). */ private computeTF; /** * Compute inverse document frequency across corpus. */ private computeIDF; } /** * EntityExtractor — Regex-based named entity recognition. * * Detects common entity types without any ML model: * - EMAIL * - PHONE * - URL * - DATE * - MONEY / CURRENCY * - PERCENTAGE * - IP_ADDRESS * - CREDIT_CARD (basic pattern) * - SSN (basic pattern) * * For full NER (PERSON, ORGANIZATION, LOCATION), use the * @docparser/models-nlp plugin with ONNX models. */ interface ExtractedEntity { readonly text: string; readonly type: string; readonly start: number; readonly end: number; readonly normalizedForm?: string; } declare class EntityExtractor { private readonly patterns; private readonly enabledTypes; constructor(entityTypes?: readonly string[]); /** * Extract entities from text. */ extract(text: string): ExtractedEntity[]; /** * Get all entity types this extractor can detect. */ getSupportedTypes(): string[]; private buildPatterns; /** * Remove overlapping entity matches, keeping the longest. */ private deduplicateEntities; } /** * ImportanceScorer — Computes importance score per chunk. * * Factors: * - Document position (intro + conclusion > middle) * - Heading level (higher heading = more important) * - Content type (tables/charts > plain text) * - Section depth (shallower = more important) * - Entity density (more entities = more important) * - Keyword density */ declare class ImportanceScorer { /** * Compute importance score for a chunk (0.0 to 1.0). */ score(chunk: Chunk): number; /** * Score all chunks in batch, with relative ranking. */ scoreAll(chunks: readonly Chunk[]): number[]; private positionFactor; private contentTypeFactor; private depthFactor; } interface LLMEnrichmentConfig { /** Generate chunk summaries */ readonly generateSummary?: boolean; /** Generate hypothetical questions */ readonly generateQuestions?: boolean; /** Max questions per chunk */ readonly maxQuestions?: number; /** Max tokens for summary */ readonly summaryMaxTokens?: number; /** Model to use (provider-specific) */ readonly model?: string; /** Temperature for generation */ readonly temperature?: number; /** Only enrich chunks with importance > threshold */ readonly importanceThreshold?: number; /** Max concurrent LLM calls */ readonly concurrency?: number; /** Max chunks to enrich (cost control) */ readonly maxChunks?: number; } /** * LLMEnricher — Uses an LLM to generate summaries and hypothetical questions. * * This is separate from the enrichment pipeline so it can be: * 1. Optionally enabled (costs money / requires API) * 2. Plugged into any LLM provider * 3. Run independently * * Generated content: * - `chunk.summary`: A 1-2 sentence summary * - `chunk.hypotheticalQuestions`: Questions this chunk could answer */ declare class LLMEnricher { private readonly logger; private readonly provider; private readonly config; constructor(parentLogger: pino.Logger, provider: LLMProviderAdapter, config?: LLMEnrichmentConfig); /** * Enrich chunks with LLM-generated content. */ enrich(chunks: Chunk[]): Promise; private enrichSingleChunk; private generateSummary; private generateQuestions; } /** * EmbeddingEnricher — Generates embeddings for chunks. * * This enricher adds vector embeddings to chunk metadata * for direct insertion into vector databases. */ declare class EmbeddingEnricher { private readonly logger; private readonly provider; private readonly batchSize; private readonly maxConcurrentBatches; constructor(parentLogger: pino.Logger, provider: EmbeddingProviderAdapter, batchSize?: number, maxConcurrentBatches?: number); /** * Generate embeddings for all chunks. * Adds embedding to chunk.metadata.embedding. */ enrich(chunks: Chunk[]): Promise; private mapWithConcurrency; } interface LanguageDetection { /** ISO 639-3 language code (e.g., 'eng', 'fra', 'deu') */ readonly iso639_3: string; /** ISO 639-1 code (e.g., 'en', 'fr', 'de') */ readonly iso639_1: string; /** Human-readable name (e.g., 'English', 'French') */ readonly name: string; /** Detection confidence (0-1) */ readonly confidence: number; /** Script (e.g., 'Latin', 'Cyrillic', 'CJK') */ readonly script: string; /** Reading direction */ readonly direction: 'ltr' | 'rtl'; } interface MultiLanguageResult { /** Primary (dominant) language */ readonly primary: LanguageDetection; /** All detected languages with confidence */ readonly detected: readonly LanguageDetection[]; /** True if document contains multiple languages */ readonly isMultilingual: boolean; /** Language confidence map per text segment */ readonly segmentLanguages?: readonly { text: string; language: LanguageDetection; }[]; } /** * LanguageDetector — Detects document and chunk languages. * * Uses franc (trigram-based) for initial detection, then * refines with script analysis. * * Features: * - Full document language detection * - Per-chunk language detection * - Multi-language document support * - Script detection (Latin, Cyrillic, CJK, Arabic) * - Reading direction detection */ declare class LanguageDetector { private readonly logger; private francDetect; constructor(parentLogger: pino.Logger); /** * Lazy-load franc to avoid import issues. */ private loadFranc; /** * Detect the primary language of a text. */ detect(text: string): Promise; /** * Detect languages in a document (combined text from all chunks). * Also performs per-segment detection for multilingual documents. */ detectDocument(texts: readonly string[]): Promise; private buildDetection; private getScript; private detectByScript; /** * Simple heuristic fallback when franc isn't available. */ private heuristicDetect; } /** * StopWordProvider — Provides stop words for multiple languages. * * Used by KeywordExtractor to filter language-specific stop words. */ declare class StopWordProvider { private static readonly STOP_WORDS; /** * Get stop words for a language. */ static getStopWords(languageCode: string): ReadonlySet; /** * Get all supported language codes. */ static getSupportedLanguages(): string[]; } /** * PluginManager — Manages the lifecycle and execution of plugins. * * Plugin registration order determines execution priority. * Plugins are validated on registration (not at runtime). * * Usage: * ```ts * const parser = new DocParser(); * parser.use(myOCRPlugin); * parser.use(myLLMPlugin); * ``` */ declare class PluginManager { private readonly logger; private readonly plugins; private initialized; constructor(parentLogger: pino.Logger); /** * Register a plugin. */ register(plugin: DocParserPlugin, config: DocumentParserConfig): Promise; /** * Unregister a plugin. */ unregister(name: string): Promise; /** * Get all plugins of a specific type. */ getPlugins(type: T): DocParserPlugin[]; /** * Get all registered plugins (any type). */ getAllPlugins(): DocParserPlugin[]; /** * Execute a hook across all applicable plugins. * Runs in registration order. */ executeHook(hookName: string, input: T, pluginType?: PluginType): Promise; /** * Check if a specific plugin is registered. */ has(name: string): boolean; /** * Enable/disable a plugin. */ setEnabled(name: string, enabled: boolean): void; /** * Get plugin count. */ get count(): number; /** * Destroy all plugins. */ destroyAll(): Promise; private validatePlugin; } /** * Create an LLM enrichment plugin from any LLM provider adapter. * * @example * ```ts * import { createLLMPlugin } from 'docparser-core'; * * const plugin = createLLMPlugin(myOpenAIAdapter, { * generateSummary: true, * generateQuestions: true, * maxChunks: 50, * }); * * const parser = new DocParser(); * await parser.use(plugin); * ``` */ declare function createLLMPlugin(provider: LLMProviderAdapter, config?: LLMEnrichmentConfig): DocParserPlugin; interface EmbeddingPluginConfig { readonly batchSize?: number; readonly maxConcurrentBatches?: number; } /** * Create an embedding plugin from any embedding provider adapter. * * @example * ```ts * import { createEmbeddingPlugin } from 'docparser-core'; * * const plugin = createEmbeddingPlugin(myOpenAIEmbedder, { * batchSize: 100, * maxConcurrentBatches: 2, * }); * * const parser = new DocParser(); * await parser.use(plugin); * ``` */ declare function createEmbeddingPlugin(provider: EmbeddingProviderAdapter, config?: EmbeddingPluginConfig): DocParserPlugin; declare function createEmbeddingPlugin(provider: EmbeddingProviderAdapter, batchSize: number, maxConcurrentBatches?: number): DocParserPlugin; interface TesseractConfig { readonly languages?: readonly string[]; readonly dataPath?: string; readonly engineMode?: 'legacy' | 'lstm' | 'both'; readonly pageSegMode?: 'auto' | 'single_block' | 'single_line' | 'single_word' | 'sparse_text'; readonly workerCount?: number; readonly detectOrientationScript?: boolean; readonly preserveInterwordSpaces?: boolean; readonly userDefinedDpi?: number; } interface NativeTesseractConfig { readonly executablePath?: string; readonly tessdataDir?: string; readonly workingDirectory?: string; readonly tempDir?: string; readonly timeoutMs?: number; readonly languages?: readonly string[]; readonly engineMode?: 'legacy' | 'lstm' | 'both'; readonly pageSegMode?: 'auto' | 'single_block' | 'single_line' | 'single_word' | 'sparse_text'; readonly detectOrientationScript?: boolean; readonly preserveInterwordSpaces?: boolean; readonly userDefinedDpi?: number; } interface OCRPipelineConfig { readonly qualityLevel?: OCRQualityLevel; readonly preprocessing?: { readonly preset?: 'fast' | 'scanned-document' | 'photo-receipt' | 'low-contrast' | 'medical-form'; readonly targetDPI?: number; readonly grayscale?: boolean; readonly normalizeContrast?: boolean; readonly sharpen?: boolean; readonly denoise?: boolean; readonly deskew?: boolean; readonly binarize?: boolean; readonly binarizeThreshold?: number; readonly maxDimension?: number; }; readonly recognition?: { readonly engineMode?: TesseractConfig['engineMode']; readonly pageSegMode?: TesseractConfig['pageSegMode']; readonly preserveInterwordSpaces?: boolean; readonly userDefinedDpi?: number; }; readonly minConfidence?: number; readonly skipNonTextImages?: boolean; readonly maxPages?: number; readonly autoRotateFromDetection?: boolean; readonly useBuiltInRetryProfiles?: boolean; readonly evaluateAllProfiles?: boolean; readonly earlyExitConfidence?: number; readonly retryProfiles?: readonly { readonly name?: string; readonly preprocessing?: OCRPipelineConfig['preprocessing']; readonly recognition?: { readonly engineMode?: TesseractConfig['engineMode']; readonly pageSegMode?: TesseractConfig['pageSegMode']; readonly preserveInterwordSpaces?: boolean; readonly userDefinedDpi?: number; }; readonly minConfidence?: number; }[]; } interface OCRRoutingConfig { readonly preferDocumentLanguage?: boolean; readonly forceImageTypes?: readonly ImageElement['imageType'][]; readonly skipImageTypes?: readonly ImageElement['imageType'][]; readonly contextHints?: readonly string[]; } interface OCRPluginConfig { /** Select the built-in OCR engine when no custom provider is supplied */ readonly engine?: 'tesseract-js' | 'native-tesseract'; /** Use built-in Tesseract.js (default) or provide your own adapter */ readonly provider?: OCRProviderAdapter; /** Tesseract configuration (if using built-in) */ readonly tesseract?: TesseractConfig; /** Local native Tesseract CLI configuration (if using built-in native engine) */ readonly nativeTesseract?: NativeTesseractConfig; /** OCR pipeline configuration */ readonly pipeline?: Partial; /** Smart routing rules for deciding which images should be OCR'd */ readonly routing?: OCRRoutingConfig; /** Process images embedded in documents (default: true) */ readonly processEmbeddedImages?: boolean; /** Process image-based PDFs (default: true) */ readonly processImagePDFs?: boolean; } /** * Create an OCR plugin that automatically OCRs images in documents. * * @example * ```ts * import { DocParser, createOCRPlugin } from 'docparser-core'; * * const parser = new DocParser(); * await parser.use(createOCRPlugin({ * tesseract: { languages: ['eng', 'fra'] }, * })); * * const result = await parser.process(scannedPDF, 'scan.pdf'); * ``` */ declare function createOCRPlugin(config?: OCRPluginConfig): DocParserPlugin; type VisionOCRProviderConfig = Exclude; interface OpenAICompatibleProviderOptions { readonly name: string; readonly baseUrl: string; readonly apiKey?: string; readonly model: string; readonly embeddingModel?: string; readonly timeoutMs?: number; readonly maxTokens?: number; readonly headers?: Readonly>; readonly healthPath?: string; readonly retry?: ProviderRetryPolicyConfig; readonly referer?: string; readonly appName?: string; } interface AnthropicProviderOptions { readonly name: string; readonly baseUrl: string; readonly apiKey?: string; readonly model: string; readonly timeoutMs?: number; readonly maxTokens?: number; readonly headers?: Readonly>; readonly healthPath?: string; readonly retry?: ProviderRetryPolicyConfig; readonly anthropicVersion?: string; readonly betaHeaders?: readonly string[]; } interface OllamaProviderOptions { readonly name: string; readonly baseUrl: string; readonly model: string; readonly embeddingModel?: string; readonly timeoutMs?: number; readonly headers?: Readonly>; readonly keepAlive?: string; readonly healthPath?: string; readonly retry?: ProviderRetryPolicyConfig; } interface ProviderHealthCheckResult { readonly healthy: boolean; readonly endpoint: string; readonly checkedAt: string; readonly latencyMs: number; readonly error?: string; } interface ConfiguredProviderHealthCheckResult extends ProviderHealthCheckResult { readonly role: 'ocr' | 'llm' | 'embedding'; readonly providerName: string; readonly supported: boolean; } declare class OpenAICompatibleLLMProvider implements LLMProviderAdapter { readonly name: string; private readonly options; constructor(options: OpenAICompatibleProviderOptions); complete(request: LLMRequest): Promise; embed(texts: string[]): Promise; healthCheck(): Promise; isAvailable(): Promise; } declare class OpenAICompatibleOCRProvider implements OCRProviderAdapter { readonly name: string; private readonly options; constructor(options: OpenAICompatibleProviderOptions); recognize(imageBuffer: Buffer, language?: string): Promise; supportedLanguages(): string[]; healthCheck(): Promise; isAvailable(): Promise; } declare class AnthropicLLMProvider implements LLMProviderAdapter { readonly name: string; private readonly options; constructor(options: AnthropicProviderOptions); complete(request: LLMRequest): Promise; embed(): Promise; healthCheck(): Promise; isAvailable(): Promise; } declare class AnthropicOCRProvider implements OCRProviderAdapter { readonly name: string; private readonly options; constructor(options: AnthropicProviderOptions); recognize(imageBuffer: Buffer, language?: string): Promise; supportedLanguages(): string[]; healthCheck(): Promise; isAvailable(): Promise; } declare class OllamaLLMProvider implements LLMProviderAdapter { readonly name: string; private readonly options; constructor(options: OllamaProviderOptions); complete(request: LLMRequest): Promise; embed(texts: string[]): Promise; healthCheck(): Promise; isAvailable(): Promise; } declare class OllamaOCRProvider implements OCRProviderAdapter { readonly name: string; private readonly options; constructor(options: OllamaProviderOptions); recognize(imageBuffer: Buffer, language?: string): Promise; supportedLanguages(): string[]; healthCheck(): Promise; isAvailable(): Promise; } declare function createBuiltInLLMProvider(config: BuiltInLLMProviderConfig): LLMProviderAdapter; declare function createBuiltInOCRProvider(config: VisionOCRProviderConfig): OCRProviderAdapter; declare function createConfiguredProviderPlugins(documentConfig: Readonly): DocParserPlugin[]; declare function checkConfiguredProvidersHealth(documentConfig: Readonly, options?: { readonly startupOnly?: boolean; }): Promise; interface BatchItem { readonly buffer?: Buffer; readonly loadBuffer?: () => Promise; readonly filePath?: string; readonly filename: string; readonly metadata?: Record; } interface BatchResult { readonly results: BatchItemResult[]; readonly stats: BatchStats; } interface BatchItemResult { readonly filename: string; readonly success: boolean; readonly result?: ProcessingResult; readonly error?: string; readonly durationMs: number; } interface BatchStats { readonly total: number; readonly succeeded: number; readonly failed: number; readonly totalDurationMs: number; readonly averageDurationMs: number; readonly totalChunks: number; } interface BatchOptions { /** Max concurrent processes (default: 3) */ readonly concurrency?: number; /** Continue on individual file failure (default: true) */ readonly continueOnError?: boolean; /** Progress callback */ readonly onProgress?: (completed: number, total: number, filename: string) => void; /** Per-item completion callback */ readonly onItemComplete?: (result: BatchItemResult) => void; } /** * BatchProcessor — Process multiple documents in parallel. * * Features: * - Configurable concurrency * - Error isolation per document * - Progress tracking * - Aggregated statistics */ declare class BatchProcessor { private readonly logger; private readonly parser; constructor(parentLogger: pino.Logger, config?: DocumentParserConfig); /** * Process a batch of documents. */ process(items: readonly BatchItem[], options?: BatchOptions): Promise; private resolveBuffer; } /** * StreamProcessor — Process documents as Node.js streams. * * Use cases: * 1. Process files from disk without loading entirely into memory * 2. Pipe processed chunks to downstream systems * 3. Handle large files that don't fit in RAM * 4. Process files from network streams (S3, HTTP, etc.) * * @example * ```ts * import { StreamProcessor } from 'docparser-core'; * import { createReadStream, createWriteStream } from 'fs'; * * const processor = new StreamProcessor(); * * // Stream file → chunks → JSONL file * const stream = processor.createChunkStream('report.pdf'); * createReadStream('report.pdf') * .pipe(stream) * .pipe(createWriteStream('chunks.jsonl')); * * // Or collect all chunks * const result = await processor.processStream( * createReadStream('large-file.pdf'), * 'large-file.pdf', * ); * ``` */ declare class StreamProcessor { private readonly logger; private readonly parser; private readonly config?; constructor(parentLogger?: pino.Logger, config?: DocumentParserConfig); /** * Process a readable stream and return the full result. * Buffers the entire stream, then processes. * * For truly large files (>1GB), use createChunkStream instead. */ processStream(input: Readable, filename: string): Promise; /** * Create a Transform stream that accepts file bytes and emits chunks. * * Input: raw file bytes * Output: JSONL-encoded Chunk objects (one per line) */ createChunkStream(filename: string, options?: { objectMode?: boolean; }): ChunkTransform; /** * Create a Readable stream that emits chunks from a buffer. */ createChunkReadable(chunks: readonly Chunk[]): Readable; /** * Create a Readable that emits chunks as JSONL strings. */ createJSONLReadable(chunks: readonly Chunk[]): Readable; private materializeStreamInput; } /** * ChunkTransform — Transform stream that buffers input bytes, * then processes and emits chunks. */ declare class ChunkTransform extends Transform { private readonly parser; private readonly filename; private readonly logger; private readonly accumulator; constructor(filename: string, logger: pino.Logger, config?: DocumentParserConfig, options?: { objectMode?: boolean; }); _transform(chunk: Buffer | string, encoding: string, callback: TransformCallback): void; _flush(callback: TransformCallback): Promise; private emitChunk; } interface LargeFileInfo { readonly path: string; readonly size: number; readonly estimatedPages?: number; readonly requiresChunkedProcessing: boolean; } /** * LargeFileReader — Memory-efficient file reading for large documents. * * For files that fit in memory (<100MB), use standard Buffer. * For larger files, this reader provides streaming capabilities. * * Strategy per format: * - Text/CSV/Markdown: Stream line-by-line * - PDF: Process page-by-page (requires full load) * - DOCX/PPTX/XLSX: ZIP random access (requires full load) * - HTML: Stream with SAX parser (future) */ declare class LargeFileReader { private readonly logger; private readonly memoryThreshold; /** * @param memoryThreshold Maximum bytes to load into memory (default: 100MB) */ constructor(parentLogger: pino.Logger, memoryThreshold?: number); /** * Analyze a file and determine processing strategy. */ analyze(filePath: string): Promise; /** * Create a readable stream for a file. */ createStream(filePath: string, options?: { highWaterMark?: number; }): ReadStream; /** * Read a text file line-by-line (for CSV, TXT, etc.) * Yields lines without loading the entire file. */ readLines(filePath: string): AsyncGenerator; /** * Read file in fixed-size chunks. */ readChunks(filePath: string, chunkSize?: number): AsyncGenerator<{ data: Buffer; offset: number; index: number; }>; /** * Estimate memory usage for processing a file. */ estimateMemoryUsage(fileSize: number, format: string): { peakMemoryMB: number; requiresStreaming: boolean; }; private getAvailableMemoryMB; } /** * JSON Formatter — Outputs chunks as a JSON array. */ declare class JSONFormatter extends BaseFormatter { readonly formatName = "json"; constructor(config?: OutputConfig); format(chunks: readonly Chunk[]): string; createReadable(chunks: readonly Chunk[]): Readable; private createJSONArrayParts; } /** * JSONL Formatter — Outputs one chunk per line (JSON Lines). */ declare class JSONLFormatter extends BaseFormatter { readonly formatName = "jsonl"; constructor(config?: OutputConfig); format(chunks: readonly Chunk[]): string; createReadable(chunks: readonly Chunk[]): Readable; private createJSONLParts; } type ValidationSeverity$1 = 'info' | 'warning' | 'error'; type PrescriptionEntityType = 'patient' | 'provider' | 'prescription' | 'medication'; interface PrescriptionPatientRow { readonly patient_id: string; readonly document_id: string; readonly prescription_id: string; readonly full_name: string | null; readonly date_of_birth: string | null; readonly age_years: number | null; readonly sex: string | null; readonly patient_identifier: string | null; readonly phone: string | null; readonly email: string | null; readonly source_content_ids: readonly string[]; readonly validation_flags: readonly string[]; } interface PrescriptionProviderRow { readonly provider_id: string; readonly document_id: string; readonly prescription_id: string; readonly full_name: string | null; readonly organization_name: string | null; readonly registration_number: string | null; readonly phone: string | null; readonly email: string | null; readonly source_content_ids: readonly string[]; readonly validation_flags: readonly string[]; } interface PrescriptionRow { readonly prescription_id: string; readonly document_id: string; readonly patient_id: string | null; readonly provider_id: string | null; readonly rx_number: string | null; readonly issue_date: string | null; readonly diagnosis: string | null; readonly medication_count: number; readonly source_content_ids: readonly string[]; readonly validation_flags: readonly string[]; } interface PrescriptionMedicationRow { readonly medication_id: string; readonly document_id: string; readonly prescription_id: string; readonly patient_id: string | null; readonly provider_id: string | null; readonly medication_name: string; readonly dosage_raw: string | null; readonly dosage_value: number | null; readonly dosage_unit: string | null; readonly dosage_form: string | null; readonly administration_amount: number | null; readonly administration_unit: string | null; readonly frequency_raw: string | null; readonly frequency_per_day: number | null; readonly duration_raw: string | null; readonly duration_days: number | null; readonly route: string | null; readonly instructions: string | null; readonly source_content_id: string; readonly source_section_id: string; readonly source_page_numbers: readonly number[]; readonly validation_flags: readonly string[]; } interface PrescriptionValidationIssueRow { readonly issue_id: string; readonly document_id: string; readonly prescription_id: string; readonly entity_type: PrescriptionEntityType; readonly entity_id: string; readonly field: string; readonly severity: ValidationSeverity$1; readonly code: string; readonly message: string; readonly source_content_id: string | null; readonly source_value: string | null; readonly normalized_value: string | null; } interface PrescriptionExtractionOutput { readonly schema_version: 'prescription_tables.v1'; readonly source_schema_version: StructuredJSONOutput['schema_version']; readonly generated_at: string; readonly summary: { readonly document_count: number; readonly patient_count: number; readonly provider_count: number; readonly prescription_count: number; readonly medication_count: number; readonly validation_issue_count: number; }; readonly tables: { readonly documents: readonly StructuredJSONDocumentRow[]; readonly patients: readonly PrescriptionPatientRow[]; readonly providers: readonly PrescriptionProviderRow[]; readonly prescriptions: readonly PrescriptionRow[]; readonly medications: readonly PrescriptionMedicationRow[]; readonly validation_issues: readonly PrescriptionValidationIssueRow[]; }; readonly ingestion_hints: { readonly load_order: readonly string[]; readonly primary_keys: Readonly>; readonly foreign_keys: readonly { readonly table: string; readonly columns: readonly string[]; readonly references: string; readonly nullable?: boolean; }[]; readonly suggested_indexes: readonly { readonly table: string; readonly columns: readonly string[]; readonly unique?: boolean; }[]; }; } declare class PrescriptionExtractor implements StructuredOutputProjector { readonly projectionName = "prescription"; project(structured: StructuredJSONOutput): PrescriptionExtractionOutput; extract(structured: StructuredJSONOutput): PrescriptionExtractionOutput; } declare function extractPrescriptionTables(structured: StructuredJSONOutput): PrescriptionExtractionOutput; declare class PrescriptionJSONFormatter extends StructuredProjectionFormatter { constructor(config?: OutputConfig); } type ValidationSeverity = 'info' | 'warning' | 'error'; type MedicalDocumentType = 'prescription' | 'op_advice' | 'lab_report' | 'discharge_summary' | 'referral_letter' | 'insurance_form' | 'unknown'; interface MedicalSummaryDocumentRow { readonly medical_document_id: string; readonly document_id: string; readonly document_name: string; readonly detected_document_type: MedicalDocumentType; readonly document_type_confidence: number; readonly patient_name: string | null; readonly date_of_birth: string | null; readonly provider_name: string | null; readonly encounter_date: string | null; readonly diagnoses: readonly string[]; readonly medication_names: readonly string[]; readonly lab_test_names: readonly string[]; readonly referral_specialties: readonly string[]; readonly insurance_payer: string | null; readonly review_required: boolean; readonly review_score: number; readonly source_content_ids: readonly string[]; readonly validation_flags: readonly string[]; } interface MedicalSummaryValidationIssueRow { readonly issue_id: string; readonly document_id: string; readonly medical_document_id: string; readonly severity: ValidationSeverity; readonly code: string; readonly message: string; } interface MedicalSummaryReviewFindingRow { readonly finding_id: string; readonly document_id: string; readonly medical_document_id: string; readonly field: 'document_type' | 'patient_name' | 'provider_name' | 'encounter_date' | 'date_of_birth' | 'lab_tests'; readonly severity: ValidationSeverity; readonly reason: 'low_confidence_document_type' | 'missing_required_field' | 'low_confidence_field' | 'suppressed_noisy_candidate'; readonly confidence_score: number; readonly extracted_value: string | null; readonly source_content_id: string | null; readonly suggested_action: 'confirm' | 'correct' | 'ignore'; } interface MedicalSummaryMedicationSafetyRow { readonly safety_id: string; readonly document_id: string; readonly medical_document_id: string; readonly medication_name: string; readonly normalized_medication_name: string; readonly risk_level: 'low' | 'medium' | 'high'; readonly duplicate_therapy_flag: boolean; readonly interaction_signal: string | null; readonly rationale: string; readonly source_content_id: string | null; readonly suggested_action: 'confirm' | 'correct' | 'ignore'; } interface MedicalSummaryLabObservationRow { readonly observation_id: string; readonly document_id: string; readonly medical_document_id: string; readonly test_name: string; readonly normalized_test_code: string | null; readonly value_numeric: number | null; readonly value_text: string | null; readonly unit: string | null; readonly reference_range: string | null; readonly abnormal_flag: 'low' | 'high' | 'critical' | 'normal' | 'unknown'; readonly observed_at: string | null; readonly source_content_id: string | null; } interface MedicalSummaryLabTrendRow { readonly trend_id: string; readonly document_id: string; readonly medical_document_id: string; readonly normalized_test_code: string; readonly test_name: string; readonly observation_count: number; readonly latest_value: number; readonly delta_value: number; readonly trend_direction: 'up' | 'down' | 'stable'; readonly confidence_score: number; } interface MedicalSummaryTimelineEventRow { readonly event_id: string; readonly document_id: string; readonly medical_document_id: string; readonly event_type: 'encounter' | 'birth' | 'lab_observation' | 'follow_up'; readonly event_date: string; readonly label: string; readonly source_content_id: string | null; readonly confidence_score: number; } interface MedicalSummaryReferralRow { readonly referral_id: string; readonly document_id: string; readonly medical_document_id: string; readonly specialty: string; readonly referred_provider: string | null; readonly source_content_id: string | null; } interface MedicalSummaryInsuranceRow { readonly insurance_id: string; readonly document_id: string; readonly medical_document_id: string; readonly payer: string | null; readonly policy_number: string | null; readonly member_id: string | null; readonly claim_number: string | null; readonly source_content_id: string | null; } interface MedicalSummaryOutput { readonly schema_version: 'medical_summary.v1'; readonly source_schema_version: StructuredJSONOutput['schema_version']; readonly generated_at: string; readonly summary: { readonly document_count: number; readonly unknown_document_count: number; readonly validation_issue_count: number; readonly review_required_count: number; readonly review_finding_count: number; readonly medication_safety_count: number; readonly lab_observation_count: number; readonly lab_trend_count: number; readonly timeline_event_count: number; readonly referral_count: number; readonly insurance_count: number; }; readonly tables: { readonly medical_documents: readonly MedicalSummaryDocumentRow[]; readonly validation_issues: readonly MedicalSummaryValidationIssueRow[]; readonly review_findings: readonly MedicalSummaryReviewFindingRow[]; readonly medication_safety: readonly MedicalSummaryMedicationSafetyRow[]; readonly lab_observations: readonly MedicalSummaryLabObservationRow[]; readonly lab_trends: readonly MedicalSummaryLabTrendRow[]; readonly timeline_events: readonly MedicalSummaryTimelineEventRow[]; readonly referrals: readonly MedicalSummaryReferralRow[]; readonly insurance_coverages: readonly MedicalSummaryInsuranceRow[]; }; readonly ingestion_hints: { readonly load_order: readonly string[]; readonly primary_keys: Readonly>; readonly foreign_keys: readonly { readonly table: string; readonly columns: readonly string[]; readonly references: string; }[]; }; } declare class MedicalSummaryExtractor implements StructuredOutputProjector { readonly projectionName = "medical_summary"; project(structured: StructuredJSONOutput): MedicalSummaryOutput; } declare function extractMedicalSummary(structured: StructuredJSONOutput): MedicalSummaryOutput; declare class MedicalSummaryJSONFormatter extends StructuredProjectionFormatter { constructor(config?: OutputConfig); } interface PineconeVector { readonly id: string; readonly values?: number[]; readonly metadata: Record; } interface PineconeUpsertPayload { readonly vectors: PineconeVector[]; readonly namespace?: string; } /** * PineconeFormatter — Formats chunks for Pinecone upsert API. * * NOTE: We do NOT generate embeddings. The user provides embeddings * or uses their own embedding pipeline. We provide the metadata structure * that Pinecone expects, plus the text content for embedding. */ declare class PineconeFormatter extends BaseFormatter { readonly formatName = "pinecone"; constructor(config?: OutputConfig); format(chunks: readonly Chunk[]): PineconeUpsertPayload; private buildMetadata; } interface ChromaAddPayload { readonly ids: string[]; readonly documents: string[]; readonly metadatas: Record[]; } /** * ChromaFormatter — Formats chunks for ChromaDB's add() API. */ declare class ChromaFormatter extends BaseFormatter { readonly formatName = "chroma"; constructor(config?: OutputConfig); format(chunks: readonly Chunk[]): ChromaAddPayload; private buildMetadata; } interface LangChainDocument { readonly pageContent: string; readonly metadata: Record; } /** * LangChainFormatter — Formats chunks as LangChain Document objects. */ declare class LangChainFormatter extends BaseFormatter { readonly formatName = "langchain"; constructor(config?: OutputConfig); format(chunks: readonly Chunk[]): LangChainDocument[]; } interface WeaviateObject { readonly class: string; readonly properties: Record; readonly id?: string; } /** * WeaviateFormatter — Formats chunks for Weaviate batch import. */ declare class WeaviateFormatter extends BaseFormatter { readonly formatName = "weaviate"; constructor(config?: OutputConfig); format(chunks: readonly Chunk[]): WeaviateObject[]; } interface QdrantPoint { readonly id: string; readonly vector?: number[]; readonly payload: Record; } /** * QdrantFormatter — Formats chunks for Qdrant upsert. */ declare class QdrantFormatter extends BaseFormatter { readonly formatName = "qdrant"; constructor(config?: OutputConfig); format(chunks: readonly Chunk[]): QdrantPoint[]; } /** * OutputRouter — Routes to the correct formatter based on config. */ declare class OutputRouter { private readonly formatters; private readonly config; private readonly structuredFormatter; private readonly structuredProjectors; constructor(config?: OutputConfig); /** * Format chunks using configured output format. */ format(chunks: readonly Chunk[]): unknown; /** * Format the same chunk set into multiple outputs without changing the router config. */ formatMany(chunks: readonly Chunk[], formatNames: readonly OutputFormat[]): Partial>; /** * Project a structured_json document into a custom domain-specific shape. */ formatProjected(chunks: readonly Chunk[], projector: StructuredOutputProjector): TOutput; /** * Project one structured_json document into multiple custom domain-specific shapes. */ formatProjectedMany(chunks: readonly Chunk[], projectors: readonly StructuredOutputProjector[]): Record; /** * Register a reusable structured projector under a stable name. */ registerStructuredProjector(projector: StructuredOutputProjector, projectionName?: string): void; /** * Project a structured_json document using a registered projector name. */ formatProjectedByName(chunks: readonly Chunk[], projectionName: string): unknown; /** * Project a structured_json document using multiple registered projector names. */ formatProjectedManyByName(chunks: readonly Chunk[], projectionNames: readonly string[]): Record; /** * List registered structured projector names. */ listStructuredProjectors(): string[]; /** * Create a readable stream for streamable formatters. */ createReadable(chunks: readonly Chunk[], formatName?: OutputFormat): Readable | undefined; private formatWith; /** * Get formatter by name. */ getFormatter(name: string): BaseFormatter | undefined; private formatStructured; } /** * CloudStorageAdapter — Interface for cloud storage providers. * * Implement this interface to integrate DocParser with: * - AWS S3 * - Google Cloud Storage * - Azure Blob Storage * - MinIO * - Any S3-compatible storage */ interface CloudStorageAdapter { readonly name: string; /** Read a file from cloud storage */ read(path: string): Promise; /** Write data to cloud storage */ write(path: string, data: Buffer | string): Promise; /** List files matching a prefix/pattern */ list(prefix: string, options?: { extensions?: string[]; }): Promise; /** Check if a file exists */ exists(path: string): Promise; /** Get file metadata */ metadata(path: string): Promise; /** Delete a file */ delete(path: string): Promise; } interface CloudFile { readonly path: string; readonly name: string; readonly size: number; readonly lastModified: Date; } interface CloudFileMetadata { readonly path: string; readonly size: number; readonly contentType?: string; readonly lastModified: Date; readonly etag?: string; readonly metadata?: Record; } interface CloudProcessingOptions { /** Input prefix/folder in cloud storage */ readonly inputPrefix: string; /** Output prefix/folder in cloud storage */ readonly outputPrefix: string; /** Output format */ readonly format?: string; /** File extensions to process */ readonly extensions?: readonly string[]; /** Max concurrent processes */ readonly concurrency?: number; /** Progress callback */ readonly onProgress?: (completed: number, total: number, filename: string) => void; /** Write receipt alongside output */ readonly writeReceipt?: boolean; /** Write quality report alongside output */ readonly writeQuality?: boolean; } /** * CloudProcessor — Process documents directly from/to cloud storage. * * @example * ```ts * const s3 = new S3Adapter({ bucket: 'my-docs' }); * const processor = new CloudProcessor(logger, s3); * * await processor.processFolder({ * inputPrefix: 'raw-docs/', * outputPrefix: 'chunks/', * format: 'jsonl', * concurrency: 5, * }); * ``` */ declare class CloudProcessor { private readonly logger; private readonly storage; private readonly parser; constructor(parentLogger: pino.Logger, storage: CloudStorageAdapter, config?: DocumentParserConfig); /** * Process a single file from cloud storage. */ processFile(inputPath: string, outputPath: string): Promise; /** * Process all files in a cloud storage folder. */ processFolder(options: CloudProcessingOptions): Promise<{ total: number; succeeded: number; failed: number; results: { path: string; success: boolean; chunks?: number; error?: string; }[]; }>; } /** * Serverless handler for AWS Lambda, Google Cloud Functions, Azure Functions. * * @example AWS Lambda: * ```ts * import { createHandler } from 'docparser-core'; * * export const handler = createHandler({ preset: 'financial' }); * ``` * * @example Google Cloud Function: * ```ts * import { createHTTPHandler } from 'docparser-core'; * * export const processDocument = createHTTPHandler({ preset: 'general' }); * ``` */ interface ServerlessEvent { /** Base64-encoded file content */ readonly body?: string; /** Filename */ readonly filename?: string; /** Is body base64 encoded */ readonly isBase64Encoded?: boolean; /** Headers */ readonly headers?: Record; /** Query parameters */ readonly queryStringParameters?: Record; } interface ServerlessResponse { readonly statusCode: number; readonly headers: Record; readonly body: string; readonly isBase64Encoded?: boolean; } /** * Create a serverless handler for document processing. */ declare function createHandler(config?: DocumentParserConfig): (event: ServerlessEvent) => Promise; /** * Create an HTTP handler (for Express, Fastify, Cloud Functions). */ declare function createHTTPHandler(config?: DocumentParserConfig): (req: any, res: any) => Promise; /** * Create a realtime HTTP handler that streams progress, chunks, and final results via SSE. */ declare function createRealtimeHTTPHandler(config?: DocumentParserConfig): (req: any, res: any) => Promise; interface CacheConfig { /** Enable caching (default: true) */ readonly enabled?: boolean; /** Max cached items (default: 100) */ readonly maxItems?: number; /** TTL in milliseconds (default: 30 minutes) */ readonly ttlMs?: number; /** Cache parse results (default: true) */ readonly cacheParsing?: boolean; /** Cache chunk results (default: true) */ readonly cacheChunking?: boolean; /** * Clone cached values on write and read to prevent hook-side mutations from leaking back * into the cache. Disable only when callers can guarantee cached objects stay immutable. * (default: true) */ readonly isolateCachedValues?: boolean; } /** * CacheManager — In-memory LRU cache for parse and chunk results. * * Cache keys are based on: * - File content hash * - Configuration hash * * Same file + same config = cache hit → skip expensive re-processing. */ declare class CacheManager { private readonly logger; private readonly config; private readonly parseCache; private readonly chunkCache; private hits; private misses; constructor(parentLogger: pino.Logger, config?: CacheConfig); getParseResult(fileHash: string): DocumentUDM | null; setParseResult(fileHash: string, udm: DocumentUDM): void; getChunkResult(fileHash: string, configHash: string): { chunks: Chunk[]; strategyUsed: string; } | null; setChunkResult(fileHash: string, configHash: string, chunks: Chunk[], strategyUsed: string): void; private copyIfNeeded; getStats(): { hits: number; misses: number; hitRate: number; parseSize: number; chunkSize: number; }; /** * Clear all caches. */ clear(): void; } /** * ReceiptGenerator — Creates the processing receipt and quality report. * * The processing receipt is ALWAYS returned, even on failure. * It contains zero document content — only structural metadata. */ declare class ReceiptGenerator { /** * Generate the processing receipt. */ generateReceipt(params: { udm: DocumentUDM; chunks: readonly Chunk[]; configHash: string; strategyUsed: string; stageMetrics: StageMetrics[]; securityReport: SecurityReport; coverageReport: CoverageReport; qualityScore: number; warnings: { stage: string; message: string; }[]; errors: { stage: string; message: string; recoverable: boolean; }[]; }): ProcessingReceipt; /** * Generate the quality report. */ generateQualityReport(chunks: readonly Chunk[], coverageReport: CoverageReport, strategyUsed: string): QualityReport; generateExplainabilityReport(params: { stageMetrics: readonly StageMetrics[]; stageStatuses: Readonly>; cleaningStats?: CleaningStats; processingNotes: DocumentUDM['processingNotes']; warnings: readonly { stage: string; message: string; }[]; errors: readonly { stage: string; message: string; recoverable: boolean; }[]; coverageReport: CoverageReport; }): ExplainabilityReport; private detectNearDuplicates; private jaccardSimilarity; private generateRecommendations; } /** * Secure Logger * * CRITICAL SECURITY RULES: * 1. NEVER log document content (text, paragraphs, data) * 2. NEVER log PII values (names, emails, SSNs) * 3. NEVER log file paths (only file names if configured) * 4. NEVER log API keys, tokens, credentials * 5. ONLY log: IDs, types, counts, stages, metrics, element types */ interface LoggerOptions { readonly level?: 'fatal' | 'error' | 'warn' | 'info' | 'debug' | 'trace' | 'silent'; readonly name?: string; readonly prettyPrint?: boolean; } declare function createLogger(options?: LoggerOptions): Logger; /** * Create a child logger scoped to a specific processing stage. */ declare function createStageLogger(parent: Logger, stage: string, documentId?: string): Logger; declare function sha256(input: string | Buffer): string; declare function shortHash(input: string | Buffer, length?: number): string; /** * Generates a stable deterministic ID from one or more parts. * * Note: This is NOT meant to be cryptographically unpredictable — only stable. */ declare function deterministicId(...parts: readonly (string | Buffer | number | boolean | null | undefined)[]): string; export { type AdaptiveChunkingConfig, AnthropicLLMProvider, AnthropicOCRProvider, type AnyDocumentElement, type AudioSegmentElement, type AuditConfig, type AuditLogEntry, type AuditLoggerPlugin, BaseFormatter, BaseParser, type BatchItem, type BatchItemResult, type BatchOptions, BatchProcessor, type BatchResult, type BatchStats, type BoundingBox, CSVParser, type CacheConfig, CacheManager, type CacheProviderPlugin, type CalloutElement, type ChartAxes, type ChartDataPoint, type ChartDataSeries, type ChartElement, type ChartParsingConfig, ChromaFormatter, type Chunk, ChunkBuilder, type ChunkContentType, type ChunkQualityDetail, type ChunkQualityFlags, type ChunkRelationship, type ChunkingConfig, ChunkingEngine, ChunkingError, type ChunkingPluginHooks, type ChunkingStrategyName, type ChunkingStrategyPlugin, type ClaudeProviderConfig, type CleanerPlugin, type CleaningConfig, CleaningPipeline, type CloudFile, type CloudFileMetadata, type CloudProcessingOptions, CloudProcessor, type CloudStorageAdapter, type CodeElement, ConfigManager, type ConfiguredProviderHealthCheckResult, CorruptFileError, type CoverageReport, CoverageVerifier, type CrossReference, DEFAULT_CONFIG, DOCXParser, type DOCXParsingConfig, type DataLifecycleConfig, type DebugConfig, DocParser, DocParserError, type DocParserErrorCode, type DocParserErrorContext, type DocParserPlugin, type DocumentElement, type DocumentMetadata, type DocumentParserConfig, type DocumentSource, type DocumentStructure, type DocumentUDM, ElementAwareStrategy, ElementParsingError, type ElementType, EmbeddingEnricher, EmptyFileError, type EnricherPlugin, type EnrichmentConfig, EnrichmentError, type EnrichmentFeedbackConfig, EnrichmentPipeline, type EnrichmentPluginHooks, EntityExtractor, type EquationElement, type ExplainabilityEvidence, type ExplainabilityReport, type ExplainabilityStageSummary, FileTooLargeError, FileValidator, type FootnoteElement, type GlossaryEntry, HTMLParser, type HTMLParsingConfig, HeaderFooterDetector, type HeadingContextConfig, type HeadingElement, HierarchicalStrategy, type HooksConfig, HybridAutoStrategy, HyphenationFixer, type ImageElement, ImageParser, type ImageParsingConfig, ImportanceScorer, type InputConfig, InputValidationError, type InspectionResult, JSONFormatter, JSONLFormatter, KeywordExtractor, LIBRARY_LICENSE, LIBRARY_NAME, LIBRARY_VERSION, type LLMDescribeImageResult, LLMEnricher, type LLMProviderPlugin, type LLMProviderRegistrationConfig, type LLMQuestionsResult, type LLMSummaryResult, LangChainFormatter, LanguageDetector, LargeFileReader, type LinkInfo, type ListElement, type ListItem, MaliciousContentError, MarkdownParser, type MedicalDocumentType, MedicalSummaryExtractor, type MedicalSummaryInsuranceRow, MedicalSummaryJSONFormatter, type MedicalSummaryLabObservationRow, type MedicalSummaryLabTrendRow, type MedicalSummaryMedicationSafetyRow, type MedicalSummaryOutput, type MedicalSummaryReferralRow, type MedicalSummaryTimelineEventRow, type NativeTesseractProviderConfig, type OCRBlock, type OCRBoundingBox, type OCRConfig, type OCRDetectionResult, type OCRDiagnosticsSummary, type OCRLine, type OCRParagraph, type OCRProviderAdapter, type OCRProviderPipelineConfig, type OCRProviderPlugin, type OCRProviderRegistrationConfig, type OCRProviderRoutingConfig, type OCRQualityLevel, type OCRRecognitionOptions, type OCRResult, type OCRSymbol, type OCRWord, OOXMLUtils, OllamaLLMProvider, OllamaOCRProvider, type OllamaProviderConfig, OpenAICompatibleLLMProvider, OpenAICompatibleOCRProvider, type OpenRouterProviderConfig, type OrganizationGatewayProviderConfig, OutOfMemoryError, type OutlineNode, type OutputConfig, type OutputFormatterPlugin, type OutputPluginHooks, OutputRouter, type OverlapConfig, PDFParser, type PDFParsingConfig, type PIIAction, type PIIConfig, type PIIDetectionSummary, type PIIMatch, PIIProcessingError, type PIIProviderAdapter, type PIIProviderPlugin, type PIIReport, type PIIScanTarget, PIIScanner, PPTXParser, type PPTXParsingConfig, type PageBreakElement, PageParsingError, type ParagraphElement, ParagraphMerger, type ParserPlugin, type ParserPluginHooks, ParserRegistry, type ParsingConfig, ParsingError, PasswordRequiredError, type PerformanceConfig, type PerformanceMode, PineconeFormatter, type PipelineConfig, type PipelineStageConfig, PlainTextParser, type Plugin, type PluginContext, PluginError, type PluginFactory, PluginManager, type PluginModuleConfig, type PluginRegistration, type PluginType, type PrescriptionExtractionOutput, PrescriptionExtractor, PrescriptionJSONFormatter, type PresetName, type ProcessingMetrics, type ProcessingNote, type ProcessingReceipt, type ProcessingResult, type ProcessingStage, type ProgressDetails, type PromptInjectionAction, type PromptInjectionConfig, PromptInjectionDetector, type ProviderConfig, type ProviderHealthCheckConfig, type ProviderHealthCheckResult, type ProviderProtocol, type ProviderRetryPolicyConfig, QdrantFormatter, type QualityReport, ReceiptGenerator, type RuntimePipelinePresetName, type SecurityClassificationConfig, type SecurityConfig, SecurityError, SecurityGate, type SecurityLevel, type SecurityPluginHooks, type SecurityReport, SemanticStrategy, SlidingWindowStrategy, type SourceLocation, type StageMetrics, StopWordProvider, StreamProcessor, StructuredJSONFormatter, type StructuredJSONOutput, type TOCEntry, type TableCell, type TableElement, TableNLGenerator, type TesseractProviderConfig, TextCleaner, type TextElementType, type TextFormatting, type TextFormattingType, ThreatDetector, type ThreatReport, TimeoutError, type TokenCounterType, type TranscriptionProviderPlugin, type TranscriptionResult, type TranscriptionSegment, UDMBuilder, UDMValidator, UnsupportedFormatError, type VectorDBOutputConfig, type VisualElementType, WeaviateFormatter, XLSXParser, type XLSXParsingConfig, ZipBombError, approximateTokenCount, checkConfiguredProvidersHealth, createBuiltInLLMProvider, createBuiltInOCRProvider, createConfiguredProviderPlugins, createEmbeddingPlugin, createHTTPHandler, createHandler, createLLMPlugin, createLogger, createOCRPlugin, createRealtimeHTTPHandler, createStageLogger, createTokenCounter, deterministicId, extractMedicalSummary, extractPrescriptionTables, sha256, shortHash };