import * as react_jsx_runtime from 'react/jsx-runtime'; import * as duckdb from '@duckdb/duckdb-wasm'; import { AsyncDuckDBConnection } from '@duckdb/duckdb-wasm'; import { ReactNode } from 'react'; interface SchemaColumn { column_name: string; column_type: string; } interface TableInfo { tableName: string; schema: SchemaColumn[]; } /** * Configuration for `@duckviz/db`. * * Passed as props to ``. There is no module-level * singleton — each provider instance resolves its own config. */ interface DuckvizDBConfig { /** * Enable IndexedDB persistence. * When `true`, tables are restored from IndexedDB on init and * `persistTable()` writes Parquet snapshots for refresh survival. * When `false`, `persistTable()` is a no-op and no restore runs. * @default false */ persistence?: boolean; /** * Prefer Arrow IPC for batch ingestion. * Falls back to JSON if an Arrow batch fails, so behavior is never * worse than the JSON path — only faster when Arrow succeeds. * @default true */ arrowIngest?: boolean; /** * Default batch size for the file-ingestion worker. * Larger batches reduce overhead but increase per-batch memory. * @default 5000 */ batchSize?: number; /** * Console output verbosity. * - `"silent"` — suppress all logs * - `"warn"` — warnings only (default) * - `"debug"` — verbose init/restore/persist logging * @default "warn" */ logLevel?: "silent" | "warn" | "debug"; /** * Hard row cap auto-appended to user/LLM-issued queries that don't already * declare an outer `LIMIT`. Guards against runaway result sets that crash * the renderer or pin the tab. Set to `0` to disable. Aggregate-only or * already-bounded queries are left untouched. * @default 0 */ defaultRowCap?: number; } type IngestProgressEvent = { type: "file-start"; path: string; } | { type: "file-phase"; path: string; phase: "reading" | "detecting" | "parsing"; } | { type: "file-batch"; path: string; tableName: string; rows: number; batchIndex: number; } | { type: "file-done"; path: string; tableName: string; totalRows: number; } | { type: "file-error"; path: string; error: string; } | { type: "ingest-stalled"; path: string; tableName: string; batchIndex: number; waitedMs: number; }; interface IngestFileInput { file: File; path: string; } interface IngestOptions { /** * Optional namespace tag stored alongside file statuses. Informational only — * tables are still keyed per-file via `pathToTableName(path)`. */ dataset?: string; /** Files to ingest through the Web Worker pipeline (CSV/XLSX/JSON/JSONL/XML). */ files?: IngestFileInput[]; /** Pre-parsed rows to ingest directly into a single table. */ rows?: Record[]; /** Table name for `rows` path (required when `rows` is provided). */ tableName?: string; /** Batch size for the worker. Defaults to 5000. */ batchSize?: number; /** Progress callback. Store writes still happen regardless. */ onProgress?: (event: IngestProgressEvent) => void; /** Fires after each table's `persistTable()` resolves — host memory monitors hook in here. */ onAfterPersist?: () => void; /** Abort signal — terminates the worker and rejects the promise. */ signal?: AbortSignal; } interface IngestResult { tables: string[]; totalRows: number; } interface IngestDeps { /** Used by the rows-only path (`ingest({ rows })`). */ ingestBatch: (rows: Record[], tableName: string, isFirstBatch: boolean) => Promise; /** * Used by the worker-driven file pipeline. Bytes arrive as a * Transferable Uint8Array (UTF-8 JSON) so we never re-serialize on * the main thread. */ ingestBatchBytes: (bytes: Uint8Array, tableName: string, isFirstBatch: boolean) => Promise; persistTable: (tableName: string, sourcePath?: string) => Promise; } declare function runIngest(options: IngestOptions, deps: IngestDeps): Promise; /** * Pre-execution SQL validation via DuckDB-WASM. * * Wraps a candidate query in `DESCRIBE ()`, which forces DuckDB to * parse + bind + plan the query but skips physical execution. We get back * the result column schema without paying for the full scan, and any * binder error (missing column, type mismatch, wrong UNNEST shape, …) * surfaces here instead of after the LLM round-trip. * * Used by widget-flow's pre-render gate: a query that fails dry-run is * sent to /api/widget-flow/fix-query with the binder error inline, * instead of running the full query and only catching the failure at * render time. */ interface DryRunOk { ok: true; /** Result-set column names + DuckDB type names, in declaration order. */ columns: Array<{ name: string; type: string; }>; } interface DryRunErr { ok: false; /** Trimmed DuckDB error message (e.g. `Binder Error: Referenced column …`). */ error: string; } type DryRunResult = DryRunOk | DryRunErr; /** * Validate a SELECT query without executing it. Returns the result * column list on success, or the binder error on failure. * * Strips a trailing semicolon so callers can pass user-facing SQL * verbatim. Multi-statement scripts are not supported — pass a single * SELECT. */ declare function dryRunQuery(conn: AsyncDuckDBConnection, sql: string): Promise; interface DuckDBContextValue { db: duckdb.AsyncDuckDB | null; conn: duckdb.AsyncDuckDBConnection | null; loading: boolean; /** True while restoring persisted tables from IndexedDB on page load. */ restoring: boolean; error: string | null; /** Convert file path to valid DuckDB table name */ pathToTableName: (path: string) => string; /** Ingest a JSON file into its own table. Runs in DuckDB worker. */ ingestJsonFile: (file: File, tableName: string) => Promise; /** Ingest pre-parsed rows (from CSV/XLSX/XML conversion) as a JSON table. */ ingestJsonRows: (rows: Record[], tableName: string) => Promise; /** Append rows to an existing table, merging schemas via UNION ALL BY NAME. */ appendJsonRows: (rows: Record[], tableName: string) => Promise; /** Get all rows from a table */ getTableData: (tableName: string) => Promise[]>; /** Get schema for a table */ getTableSchema: (tableName: string) => Promise; /** List all ingested tables */ listTables: () => Promise; /** Check if table exists */ tableExists: (tableName: string) => Promise; /** Clear all ingested tables (e.g. when files are cleared) */ clearAllTables: () => Promise; /** Drop a single table by name. */ dropTable: (tableName: string) => Promise; /** Run arbitrary SQL query. Returns rows as array of objects. */ runQuery: (sql: string) => Promise[]>; /** * Pre-execution validator: parse + bind + plan a SELECT in DuckDB-WASM * via `DESCRIBE ()`, returning the result columns on success or the * binder error on failure. Catches missing columns / wrong UNNEST shape / * type mismatches BEFORE the query runs, so widget-flow's auto-fix loop * gets the binder error directly instead of waiting for a full scan. */ dryRun: (sql: string) => Promise; /** Parser: Ingest parsed logs into the logs table */ ingestLogs: (parsedLogs: Record[]) => Promise; /** Parser: Clear the logs table */ clearLogs: () => Promise; /** Parser: Run SQL and return rows (same as runQuery) */ queryToRows: (sql: string) => Promise[]>; /** Ingest a batch of rows: CREATE for first batch, INSERT BY NAME for subsequent. */ ingestBatch: (rows: Record[], tableName: string, isFirstBatch: boolean) => Promise; /** Ingest a pre-serialized JSON string. Avoids JSON.stringify on the main thread. */ ingestBatchJson: (json: string, tableName: string, isFirstBatch: boolean) => Promise; /** * Ingest UTF-8 encoded JSON array bytes (typically transferred zero-copy * from the ingestion worker). Skips both JSON.stringify and TextEncoder * on the main thread. */ ingestBatchBytes: (bytes: Uint8Array, tableName: string, isFirstBatch: boolean) => Promise; /** Export a table as Parquet and store in IndexedDB for persistence across refreshes. */ persistTable: (tableName: string, sourcePath?: string) => Promise; /** * Unified ingestion entry point. Runs files through the bundled Web Worker * (CSV/XLSX/JSON/JSONL/XML), or ingests pre-parsed rows directly. Writes * per-file status into `useIngestionStore` and persists completed tables. */ ingest: (options: IngestOptions) => Promise; } interface DuckvizDBProviderProps extends DuckvizDBConfig { children: ReactNode; } declare function DuckvizDBProvider({ children, persistence, arrowIngest, batchSize, logLevel, defaultRowCap, }: DuckvizDBProviderProps): react_jsx_runtime.JSX.Element; declare function useDuckDB(): DuckDBContextValue; /** * Non-throwing variant of {@link useDuckDB}. Returns `null` when called * outside a `` subtree. Intended for components that * have a fallback path when DuckDB is not available (e.g. dashboards that * accept an explicit `dataProvider` prop). */ declare function useDuckDBOrNull(): DuckDBContextValue | null; /** * Async loader that returns rows on demand. Paired with `useAutoIngest`'s * `activeId` option to defer fetching / generation until the dataset is * actually selected. */ type DatasetRowsLoader = () => Promise[]>; /** * A named dataset with row data for auto-ingestion into DuckDB. * Table name is derived from `name` via `pathToTableName()` unless * an explicit `tableName` override is provided. */ interface DuckvizDataset { /** Display name — used in UI and to derive the DuckDB table name when `tableName` is omitted. */ name: string; /** * Row data for ingestion. Either a concrete array (ingested eagerly on * mount) or a loader function (ingested only when the dataset becomes * active — see `useAutoIngest({ activeId })`). */ data: Record[] | DatasetRowsLoader; /** * Explicit DuckDB table name. When omitted, derived from `name` via * `pathToTableName()`. Use this when you need the table name to match * specific SQL queries. */ tableName?: string; } interface UseAutoIngestOptions { /** Datasets to auto-ingest. Each dataset's name is used to derive the table name. */ datasets: DuckvizDataset[]; /** * Derived table name of the currently active dataset. Function-data * (lazy) datasets only ingest when their derived tableName matches * `activeId`. Array-data datasets ingest eagerly regardless. * Omit (or pass `null`) to keep the legacy eager behavior for every * dataset whose `data` is an array. */ activeId?: string | null; /** Drop auto-ingested tables on unmount. @default true */ dropOnUnmount?: boolean; } /** * Auto-ingest datasets into DuckDB. * * Derives table names from `dataset.name` via `pathToTableName()`. Uses * `CREATE OR REPLACE TABLE` so existing tables are overwritten. When * `dropOnUnmount` is true (default), tables are dropped when the component * unmounts. Handles React Strict Mode double-mount gracefully. * * When `data` is a function, rows are fetched lazily — only when the * dataset's derived tableName matches `activeId`. Loader output is cached * per-tableName for the lifetime of the hook so re-selecting a previously * loaded dataset does not re-fetch. * * No-ops when `datasets` is empty or when no `DuckvizDBProvider` is present. */ declare function useAutoIngest({ datasets, activeId, dropOnUnmount, }: UseAutoIngestOptions): { ready: boolean; ingesting: boolean; error: string | null; }; /** Sanitize file path to valid DuckDB table name. e.g. "data/users.json" -> "t_data_users" */ declare function pathToTableName(path: string): string; type LogType = { type: "kv"; separator: string; delimiter: string; } | { type: "delimited"; delimiter: string; columns?: string[]; } | { type: "json"; } | { type: "pattern"; pattern: string; } | { type: "xml_event"; }; type ParsingConfig = { logType: LogType; mappings: Record; }; /** * Shared types for the file-ingestion Web Worker ↔ main-thread protocol. */ type FileStatus = "pending" | "reading" | "detecting" | "parsing" | "ingesting" | "done" | "error"; export { type DatasetRowsLoader as D, type FileStatus as F, type LogType as L, type ParsingConfig as P, type SchemaColumn as S, type TableInfo as T, type UseAutoIngestOptions as U, type DryRunErr as a, type DryRunOk as b, type DryRunResult as c, type DuckDBContextValue as d, DuckvizDBProvider as e, type DuckvizDataset as f, dryRunQuery as g, useDuckDB as h, useDuckDBOrNull as i, pathToTableName as p, runIngest as r, useAutoIngest as u };