import { Table } from '@uwdata/flechette'; export { Table } from '@uwdata/flechette'; /** * Shared type definitions for Ducklings * @packageDocumentation */ /** * DuckDB type constants mapping to the C API type IDs. * @category Types */ declare const DuckDBType: { readonly INVALID: 0; readonly BOOLEAN: 1; readonly TINYINT: 2; readonly SMALLINT: 3; readonly INTEGER: 4; readonly BIGINT: 5; readonly UTINYINT: 6; readonly USMALLINT: 7; readonly UINTEGER: 8; readonly UBIGINT: 9; readonly FLOAT: 10; readonly DOUBLE: 11; readonly TIMESTAMP: 12; readonly DATE: 13; readonly TIME: 14; readonly INTERVAL: 15; readonly HUGEINT: 16; readonly UHUGEINT: 32; readonly VARCHAR: 17; readonly BLOB: 18; readonly DECIMAL: 19; readonly TIMESTAMP_S: 20; readonly TIMESTAMP_MS: 21; readonly TIMESTAMP_NS: 22; readonly ENUM: 23; readonly LIST: 24; readonly STRUCT: 25; readonly MAP: 26; readonly ARRAY: 33; readonly UUID: 27; readonly UNION: 28; readonly BIT: 29; readonly TIME_TZ: 30; readonly TIMESTAMP_TZ: 31; }; /** * Type ID from DuckDB type constants. * @category Types */ type DuckDBTypeId = (typeof DuckDBType)[keyof typeof DuckDBType]; /** * Database access mode. * @category Configuration */ declare enum AccessMode { /** DuckDB determines mode based on context (resolves to READ_WRITE for in-memory) */ AUTOMATIC = "automatic", /** Read-only mode - all write operations are blocked */ READ_ONLY = "read_only", /** Read-write mode - allows both reads and writes */ READ_WRITE = "read_write" } /** * DuckDB configuration options. * @category Configuration */ interface DuckDBConfig { /** * Database access mode. * Use READ_ONLY to prevent any data modification. * @default AccessMode.AUTOMATIC */ accessMode?: AccessMode; /** * Enable external access (file I/O, httpfs, etc.). * Set to false to prevent all external data access. * WARNING: Setting to false will disable httpfs functionality. * @default true */ enableExternalAccess?: boolean; /** * Lock configuration after startup. * Prevents runtime configuration changes via SQL SET commands. * @default true (secure default) */ lockConfiguration?: boolean; /** * Custom configuration options. * Key-value pairs passed directly to duckdb_set_config. * @see https://duckdb.org/docs/configuration/overview */ customConfig?: Record; } /** * Column metadata for query results. * @category Types */ interface ColumnInfo { /** Column name */ name: string; /** DuckDB type ID */ type: DuckDBTypeId; /** Type alias (e.g., "JSON" for aliased types) */ alias?: string; } /** * Options for initializing the DuckDB WASM module. * @category Types */ interface InitOptions { /** * URL to the WASM file (for browser environments). * If not provided, uses the default bundled WASM location. */ wasmUrl?: string; /** * URL to the Emscripten JS file (duckdb.js). * Required for proper bundler support. */ wasmJsUrl?: string; /** * URL to the worker script (for browser environments). * If not provided, uses the default bundled worker location. */ workerUrl?: string; /** * Pre-created Worker instance. * Use {@link createWorker} for CDN loading to work around cross-origin restrictions. * * @example * ```typescript * import { createWorker, getJsDelivrBundle, init } from '@ducklings/browser'; * * const bundle = getJsDelivrBundle(); * const worker = await createWorker(bundle.mainWorker); * await init({ worker, wasmUrl: bundle.wasmModule, wasmJsUrl: bundle.wasmJs }); * ``` */ worker?: Worker; /** * Pre-compiled WebAssembly.Module (for Cloudflare Workers). * In Workers, import the WASM file directly and pass it here. */ wasmModule?: WebAssembly.Module; /** * Whether to use the main thread instead of a Web Worker. * Defaults to false (use Web Worker). * Note: Main thread mode blocks the UI during operations. */ useMainThread?: boolean; /** * DuckDB configuration options. * Controls access mode, security settings, and custom configuration. */ config?: DuckDBConfig; } /** * File information returned by globFiles. * @category Types */ interface FileInfo { /** File name/path */ name: string; /** File size in bytes */ size: number; } /** * Options for CSV insertion. * @category Types */ interface CSVInsertOptions { /** Whether the CSV has a header row */ header?: boolean; /** Column delimiter */ delimiter?: string; /** Quote character */ quote?: string; /** Escape character */ escape?: string; /** Skip rows at start */ skip?: number; /** Column names (if no header) */ columns?: string[]; } /** * Options for JSON insertion. * @category Types */ interface JSONInsertOptions { /** JSON format: 'auto', 'records', 'values', or 'newline_delimited' */ format?: 'auto' | 'records' | 'values' | 'newline_delimited'; /** Column names */ columns?: string[]; } /** * Worker message protocol for Ducklings * @packageDocumentation */ /** * Request types sent from main thread to worker. */ declare enum WorkerRequestType { PING = "PING", INSTANTIATE = "INSTANTIATE", GET_VERSION = "GET_VERSION", OPEN = "OPEN", CLOSE = "CLOSE", CONNECT = "CONNECT", DISCONNECT = "DISCONNECT", QUERY = "QUERY", QUERY_ARROW = "QUERY_ARROW", QUERY_STREAMING = "QUERY_STREAMING", EXECUTE = "EXECUTE", FETCH_CHUNK = "FETCH_CHUNK", CLOSE_STREAMING_RESULT = "CLOSE_STREAMING_RESULT", RESET_STREAMING_RESULT = "RESET_STREAMING_RESULT", PREPARE = "PREPARE", RUN_PREPARED = "RUN_PREPARED", EXECUTE_PREPARED = "EXECUTE_PREPARED", CLOSE_PREPARED = "CLOSE_PREPARED", BEGIN_TRANSACTION = "BEGIN_TRANSACTION", COMMIT = "COMMIT", ROLLBACK = "ROLLBACK", REGISTER_FILE_URL = "REGISTER_FILE_URL", REGISTER_FILE_BUFFER = "REGISTER_FILE_BUFFER", REGISTER_FILE_HANDLE = "REGISTER_FILE_HANDLE", REGISTER_FILE_TEXT = "REGISTER_FILE_TEXT", DROP_FILE = "DROP_FILE", DROP_FILES = "DROP_FILES", FLUSH_FILES = "FLUSH_FILES", COPY_FILE_TO_BUFFER = "COPY_FILE_TO_BUFFER", COPY_FILE_TO_PATH = "COPY_FILE_TO_PATH", GLOB_FILES = "GLOB_FILES", INSERT_ARROW_FROM_IPC = "INSERT_ARROW_FROM_IPC", INSERT_CSV_FROM_PATH = "INSERT_CSV_FROM_PATH", INSERT_JSON_FROM_PATH = "INSERT_JSON_FROM_PATH" } /** * Async Prepared Statement class * * @packageDocumentation */ /** * A prepared SQL statement with parameter binding. * * Prepared statements are more secure (prevent SQL injection) and can be * more efficient when executing the same query multiple times with different parameters. * * Bind methods are synchronous (store locally), while run() and execute() are async * (send to worker). * * @category Query Results * @example * ```typescript * const stmt = await conn.prepare('SELECT * FROM users WHERE id = ? AND active = ?'); * stmt.bindInt32(1, userId); * stmt.bindBoolean(2, true); * const result = await stmt.run(); * await stmt.close(); * ``` */ declare class PreparedStatement { private db; private connectionId; private preparedStatementId; private closed; private bindings; /** * @internal */ constructor(db: DuckDB, connectionId: number, preparedStatementId: number, _sql: string); private checkClosed; /** * Clear all parameter bindings. */ clearBindings(): void; /** * Bind a NULL value to a parameter. * * @param index - 1-based parameter index */ bindNull(index: number): void; /** * Bind a boolean value to a parameter. * * @param index - 1-based parameter index * @param value - The boolean value */ bindBoolean(index: number, value: boolean): void; /** * Bind an 8-bit signed integer to a parameter. * * @param index - 1-based parameter index * @param value - The integer value (-128 to 127) */ bindInt8(index: number, value: number): void; /** * Bind a 16-bit signed integer to a parameter. * * @param index - 1-based parameter index * @param value - The integer value (-32768 to 32767) */ bindInt16(index: number, value: number): void; /** * Bind a 32-bit signed integer to a parameter. * * @param index - 1-based parameter index * @param value - The integer value */ bindInt32(index: number, value: number): void; /** * Bind a 64-bit signed integer to a parameter. * * @param index - 1-based parameter index * @param value - The integer value (BigInt or number) */ bindInt64(index: number, value: bigint | number): void; /** * Bind an 8-bit unsigned integer to a parameter. * * @param index - 1-based parameter index * @param value - The integer value (0 to 255) */ bindUInt8(index: number, value: number): void; /** * Bind a 16-bit unsigned integer to a parameter. * * @param index - 1-based parameter index * @param value - The integer value (0 to 65535) */ bindUInt16(index: number, value: number): void; /** * Bind a 32-bit unsigned integer to a parameter. * * @param index - 1-based parameter index * @param value - The integer value */ bindUInt32(index: number, value: number): void; /** * Bind a 64-bit unsigned integer to a parameter. * * @param index - 1-based parameter index * @param value - The integer value (BigInt or number) */ bindUInt64(index: number, value: bigint | number): void; /** * Bind a 32-bit float to a parameter. * * @param index - 1-based parameter index * @param value - The float value */ bindFloat(index: number, value: number): void; /** * Bind a 64-bit double to a parameter. * * @param index - 1-based parameter index * @param value - The double value */ bindDouble(index: number, value: number): void; /** * Bind a string value to a parameter. * * @param index - 1-based parameter index * @param value - The string value */ bindVarchar(index: number, value: string): void; /** * Bind a blob (binary) value to a parameter. * * @param index - 1-based parameter index * @param value - The binary data */ bindBlob(index: number, value: Uint8Array): void; /** * Execute the prepared statement and return results. * * @returns Promise resolving to array of result rows as objects * * @example * ```typescript * const stmt = await conn.prepare('SELECT * FROM users WHERE id = ?'); * stmt.bindInt32(1, 42); * const rows = await stmt.run(); * ``` */ run>(): Promise; /** * Execute the prepared statement and return the number of affected rows. * * Use this for INSERT, UPDATE, DELETE statements. * * @returns Promise resolving to the number of rows affected * * @example * ```typescript * const stmt = await conn.prepare('DELETE FROM users WHERE id = ?'); * stmt.bindInt32(1, 42); * const deleted = await stmt.execute(); * ``` */ execute(): Promise; /** * Close the prepared statement and release resources. */ close(): Promise; } /** * Data Chunk class * * @packageDocumentation */ /** * A chunk of data from a streaming query result. * * DataChunks contain a fixed number of rows and provide methods to * access the data in various formats. * * @category Query Results * @example * ```typescript * for await (const chunk of stream) { * console.log(`Chunk has ${chunk.rowCount} rows`); * * // Get as array of objects * for (const row of chunk.toArray()) { * console.log(row); * } * * // Or access raw columnar data * const column = chunk.getColumn(0); * console.log(column); * } * ``` */ declare class DataChunk { private columns; private rows; private _rowCount; /** * @internal */ constructor(columns: ColumnInfo[], rows: unknown[][], rowCount: number); /** * Get the number of rows in this chunk. */ get rowCount(): number; /** * Get the number of columns. */ get columnCount(): number; /** * Get the column information. */ getColumns(): ColumnInfo[]; /** * Get the raw row data. * * Each row is an array of values in column order. */ getRows(): unknown[][]; /** * Get a single column's values. * * @param index - The 0-based column index * @returns Array of values for that column */ getColumn(index: number): unknown[]; /** * Get a single column's values by name. * * @param name - The column name * @returns Array of values for that column */ getColumnByName(name: string): unknown[]; /** * Get a single row. * * @param index - The 0-based row index * @returns The row as an array of values */ getRow(index: number): unknown[]; /** * Get a single row as an object. * * @param index - The 0-based row index * @returns The row as an object with column names as keys */ getRowObject>(index: number): T; /** * Convert all rows to an array of objects. * * @returns Array of row objects with column names as keys */ toArray>(): T[]; /** * Iterate over rows as objects. */ [Symbol.iterator](): Iterator>; } /** * Async Streaming Result class * * @packageDocumentation */ /** * An async streaming query result. * * This class allows you to process large result sets in chunks, * which is more memory-efficient than loading everything at once. * * Implements AsyncIterable for use with `for await...of`. * * @category Query Results * @example * ```typescript * const stream = await conn.queryStreaming('SELECT * FROM large_table'); * * // Using for await...of * for await (const chunk of stream) { * console.log(`Processing ${chunk.rowCount} rows`); * for (const row of chunk.toArray()) { * processRow(row); * } * } * * // Or manually * let chunk; * while ((chunk = await stream.nextChunk()) !== null) { * console.log(chunk.rowCount); * } * * await stream.close(); * ``` */ declare class AsyncStreamingResult implements AsyncIterable { private db; private connectionId; private streamingResultId; private columns; private closed; private done; /** * @internal */ constructor(db: DuckDB, connectionId: number, streamingResultId: number, columns: ColumnInfo[]); /** * Get the column information for this result. */ getColumns(): ColumnInfo[]; /** * Check if the result has been fully consumed. */ isDone(): boolean; /** * Check if the result is closed. */ isClosed(): boolean; private checkClosed; /** * Fetch the next chunk of data. * * @returns Promise resolving to the next DataChunk, or null if no more data */ nextChunk(): Promise; /** * Collect all remaining chunks into an array of objects. * * Warning: This loads all data into memory. Use nextChunk() or * for await...of for large result sets. * * @returns Promise resolving to array of all result rows */ toArray>(): Promise; /** * Collect all remaining chunks into an Arrow Table. * * Warning: This loads all data into memory. * * @returns Promise resolving to Arrow Table with all results */ toArrowTable(): Promise; /** * Close the streaming result and release resources. */ close(): Promise; /** * Returns an async iterator for this streaming result. */ [Symbol.asyncIterator](): AsyncIterator; } /** * Async Connection class * * @packageDocumentation */ /** * A connection to a DuckDB database. * * Connections are used to execute queries and manage transactions. * All operations are async as they communicate with a Web Worker. * * @category Connection * @example * ```typescript * const conn = await db.connect(); * * // Query returns array of objects * const rows = await conn.query('SELECT * FROM range(10)'); * * // Query returns Arrow Table * const table = await conn.queryArrow('SELECT * FROM range(1000)'); * * // Streaming for large results * const stream = await conn.queryStreaming('SELECT * FROM large_table'); * for await (const chunk of stream) { * console.log(chunk.rowCount); * } * * await conn.close(); * ``` */ declare class Connection { private db; private connectionId; private closed; /** * @internal */ constructor(db: DuckDB, connectionId: number); /** * Get the connection ID. * @internal */ getConnectionId(): number; /** * Get the database instance. * @internal */ getDB(): DuckDB; private checkClosed; /** * Executes a SQL query and returns the results as an array of objects. * * @param sql - The SQL query to execute * @returns Promise resolving to array of result rows as objects * * @example * ```typescript * const rows = await conn.query<{ id: number; name: string }>( * 'SELECT * FROM users WHERE active = true' * ); * for (const row of rows) { * console.log(row.id, row.name); * } * ``` */ query>(sql: string): Promise; /** * Executes a SQL query and returns results as a Flechette Arrow Table. * * This method is more efficient for large result sets and provides * proper Arrow/columnar data representation. * * @param sql - The SQL query to execute * @returns Promise resolving to Arrow Table with query results * * @example * ```typescript * const table = await conn.queryArrow('SELECT * FROM range(1000000)'); * console.log(table.numRows); * ``` */ queryArrow(sql: string): Promise
; /** * Executes a SQL query and returns a streaming result. * * This method is more memory-efficient for large result sets as it * processes data in chunks rather than loading everything at once. * * @param sql - The SQL query to execute * @returns Promise resolving to AsyncStreamingResult that can be iterated over * * @example * ```typescript * const stream = await conn.queryStreaming('SELECT * FROM large_table'); * for await (const chunk of stream) { * console.log(`Processing ${chunk.rowCount} rows`); * for (const row of chunk.toArray()) { * processRow(row); * } * } * await stream.close(); * ``` */ queryStreaming(sql: string): Promise; /** * Executes a SQL statement and returns the number of affected rows. * * Use this for INSERT, UPDATE, DELETE, or other statements where you * don't need to read result rows. * * @param sql - The SQL statement to execute * @returns Promise resolving to the number of rows affected * * @example * ```typescript * const deleted = await conn.execute('DELETE FROM users WHERE inactive = true'); * console.log(`Deleted ${deleted} users`); * ``` */ execute(sql: string): Promise; /** * Prepares a SQL statement for execution. * * Prepared statements are more secure (prevent SQL injection) and can be * more efficient when executing the same query multiple times with different parameters. * * @param sql - The SQL statement with parameter placeholders (?) * @returns Promise resolving to a PreparedStatement instance * * @example * ```typescript * const stmt = await conn.prepare('SELECT * FROM users WHERE id = ?'); * stmt.bindInt32(1, 42); * const rows = await stmt.run(); * await stmt.close(); * ``` */ prepare(sql: string): Promise; /** * Begins a new transaction. * * @example * ```typescript * await conn.beginTransaction(); * try { * await conn.execute('INSERT INTO users (name) VALUES ($1)', ['Alice']); * await conn.execute('UPDATE balances SET amount = amount - 100 WHERE user = $1', ['Alice']); * await conn.commit(); * } catch (e) { * await conn.rollback(); * throw e; * } * ``` */ beginTransaction(): Promise; /** * Commits the current transaction. */ commit(): Promise; /** * Rolls back the current transaction. */ rollback(): Promise; /** * Execute a function within a transaction. * * The transaction is automatically committed on success or rolled back on error. * * @param fn - The function to execute within the transaction * @returns Promise resolving to the function's return value * * @example * ```typescript * const result = await conn.transaction(async () => { * await conn.execute('INSERT INTO users (name) VALUES ($1)', ['Alice']); * return await conn.query('SELECT * FROM users WHERE name = $1', ['Alice']); * }); * ``` */ transaction(fn: () => Promise): Promise; /** * Insert data from an Arrow IPC stream buffer into a table. * * Creates a new table with the given name from the Arrow IPC data. If the table * already exists, the call is a no-op (uses `CREATE TABLE IF NOT EXISTS`). * * **Important:** The IPC stream must not contain dictionary-encoded columns. * Flechette's `tableFromArrays()` defaults to `dictionary(utf8())` for string * columns. Use explicit `utf8()` types to avoid this. * * @param tableName - The name of the table to create * @param ipcBuffer - Arrow IPC stream bytes (use `tableToIPC(table, { format: 'stream' })`) * @throws When the connection is closed or the IPC data is invalid * * @example * ```typescript * import { tableFromArrays, tableToIPC, utf8 } from '@ducklings/browser'; * * const table = tableFromArrays( * { id: [1, 2, 3], name: ['Alice', 'Bob', 'Charlie'] }, * { types: { name: utf8() } } // Required for string columns * ); * const ipcBuffer = tableToIPC(table, { format: 'stream' }); * await conn.insertArrowFromIPCStream('users', ipcBuffer); * ``` * * @category Data Insertion */ insertArrowFromIPCStream(tableName: string, ipcBuffer: Uint8Array): Promise; /** * Insert data from a CSV file. * * @param tableName - The name of the table to insert into * @param path - The virtual file path of the CSV * @param options - Optional CSV parsing options * * @example * ```typescript * await db.registerFileBuffer('data.csv', csvData); * await conn.insertCSVFromPath('my_table', 'data.csv', { header: true }); * ``` */ insertCSVFromPath(tableName: string, path: string, options?: CSVInsertOptions): Promise; /** * Insert data from a JSON file. * * Requires a custom Ducklings build with DuckDB's `json` extension enabled. * The default published browser and workers packages omit that extension to * stay within Cloudflare deployment size limits. * * @param tableName - The name of the table to insert into * @param path - The virtual file path of the JSON * @param options - Optional JSON parsing options * * @example * ```typescript * await db.registerFileBuffer('data.json', jsonData); * await conn.insertJSONFromPath('my_table', 'data.json'); * ``` */ insertJSONFromPath(tableName: string, path: string, options?: JSONInsertOptions): Promise; /** * Closes the connection and releases resources. */ close(): Promise; } /** * Async DuckDB bindings for the main thread * * @packageDocumentation */ /** * Initialize the DuckDB WASM module. * * This function must be called before creating any DuckDB instances. * It spawns a Web Worker and initializes the WebAssembly module inside it. * * URLs for worker, WASM, and JS files are automatically resolved from the * library location. You can override them if needed. * * @category Database * @param options - Optional initialization options * @returns Promise that resolves when initialization is complete * * @example * ```typescript * import { init, DuckDB } from '@ducklings/browser'; * * await init(); * const db = new DuckDB(); * const conn = await db.connect(); * * const rows = await conn.query('SELECT 42 as answer'); * console.log(rows); * * await conn.close(); * await db.close(); * ``` */ declare function init(options?: string | InitOptions): Promise; /** * Returns the DuckDB library version. * * @category Database * @returns Promise resolving to version string * @throws DuckDBError if WASM module is not initialized */ declare function version(): Promise; /** * Get the global DuckDB instance. * * @category Database * @returns The global DuckDB instance * @throws DuckDBError if not initialized */ declare function getDB(): DuckDB; /** * DuckDB database instance. * * This is the main entry point for using DuckDB in WASM. * Create a database instance, then create connections to execute queries. * * @category Database * @example * ```typescript * import { init, DuckDB } from '@ducklings/browser'; * * await init(); * * const db = new DuckDB(); * const conn = await db.connect(); * * const result = await conn.query('SELECT 42 as answer'); * console.log(result); * * await conn.close(); * await db.close(); * ``` */ declare class DuckDB { private worker; private pendingRequests; private nextMessageId; private closed; /** * Creates a new DuckDB instance. * * @param worker - The Web Worker to use for DuckDB operations * @internal Use init() instead of creating directly */ constructor(worker?: Worker); private setupMessageHandler; /** * Post a request to the worker and return a promise for the response. * * @internal */ postTask(type: WorkerRequestType, data?: unknown, transfer?: Transferable[]): Promise; /** * Instantiate the WASM module in the worker. * * @internal */ instantiate(wasmUrl?: string, wasmJsUrl?: string): Promise; /** * Open the database. * * @param config - Optional configuration options * @internal */ open(config?: DuckDBConfig): Promise; /** * Get the DuckDB library version. */ getVersion(): Promise; /** * Creates a new connection to this database. * * Multiple connections can be created to the same database. * Each connection maintains its own transaction state. * * @returns Promise resolving to a new Connection instance */ connect(): Promise; /** * Creates a new DuckDB database and initializes the WASM module if needed. * * This is a convenience method that combines init() and connect(). * * @returns Promise that resolves to a new Connection instance * * @example * ```typescript * const conn = await DuckDB.createConnection(); * const rows = await conn.query('SELECT 42 as answer'); * ``` */ static createConnection(): Promise; /** * Register a remote file by URL. * * @param name - The virtual file name to use * @param url - The URL to fetch the file from * @param protocol - Optional protocol hint ('HTTP' or 'HTTPS') * @param directIO - Whether to use direct I/O * * @example * ```typescript * await db.registerFileURL('data.parquet', 'https://example.com/data.parquet'); * const rows = await conn.query("SELECT * FROM 'data.parquet'"); * ``` */ registerFileURL(name: string, url: string, protocol?: string, directIO?: boolean): Promise; /** * Register an in-memory buffer as a virtual file. * * @param name - The virtual file name to use * @param buffer - The file contents * * @example * ```typescript * const csvData = new TextEncoder().encode('id,name\n1,Alice\n2,Bob'); * await db.registerFileBuffer('data.csv', csvData); * const rows = await conn.query("SELECT * FROM read_csv('/data.csv')"); * ``` */ registerFileBuffer(name: string, buffer: Uint8Array): Promise; /** * Register a text string as a virtual file. * * @param name - The virtual file name to use * @param text - The file contents as a string */ registerFileText(name: string, text: string): Promise; /** * Remove a registered file. * * @param name - The virtual file name to remove */ dropFile(name: string): Promise; /** * Remove all registered files. */ dropFiles(): Promise; /** * Flush all file buffers. */ flushFiles(): Promise; /** * Export a file to a buffer. * * @param name - The virtual file name to export * @returns The file contents */ copyFileToBuffer(name: string): Promise; /** * Copy a file to another path. * * @param srcName - The source file name * @param dstPath - The destination path */ copyFileToPath(srcName: string, dstPath: string): Promise; /** * List files matching a glob pattern. * * @param pattern - The glob pattern to match * @returns List of matching files */ globFiles(pattern: string): Promise; /** * Closes the database and releases all resources. */ close(): Promise; } /** * CDN utilities for loading DuckDB from CDNs like jsDelivr * * When loading the library from a CDN, browsers block cross-origin Worker creation. * Use {@link createWorker} to work around this limitation. * * @packageDocumentation */ /** * Bundle URLs for loading from CDN * * @category CDN */ interface DuckDBBundle { /** URL to the main library entry point */ mainModule: string; /** URL to the worker script */ mainWorker: string; /** URL to the WASM binary */ wasmModule: string; /** URL to the Emscripten JS glue */ wasmJs: string; } /** * Get pre-configured bundle URLs for loading from jsDelivr CDN * * @category CDN * @param version - Optional version to use (defaults to current package version) * @returns Bundle URLs for jsDelivr * * @example * ```typescript * import { getJsDelivrBundle, createWorker, init } from '@ducklings/browser'; * * const bundle = getJsDelivrBundle(); * const worker = await createWorker(bundle.mainWorker); * * await init({ * worker, * wasmUrl: bundle.wasmModule, * wasmJsUrl: bundle.wasmJs, * }); * ``` */ declare function getJsDelivrBundle(version?: string): DuckDBBundle; /** * Get pre-configured bundle URLs for loading from unpkg CDN * * @category CDN * @param version - Optional version to use (defaults to current package version) * @returns Bundle URLs for unpkg */ declare function getUnpkgBundle(version?: string): DuckDBBundle; /** * Create a Worker from a cross-origin URL using Blob URL workaround. * * Browsers block creating Workers from cross-origin scripts (like those served from CDNs). * This function fetches the worker script and creates a same-origin Blob URL from it. * * @category CDN * @param url - URL to the worker script (can be cross-origin) * @returns Promise resolving to a same-origin Worker * * @example * ```typescript * import { createWorker, getJsDelivrBundle, init } from '@ducklings/browser'; * * const bundle = getJsDelivrBundle(); * const worker = await createWorker(bundle.mainWorker); * * await init({ worker }); * ``` */ declare function createWorker(url: string): Promise; /** * Error handling for Ducklings * @packageDocumentation */ /** * Error thrown by DuckDB operations. * * This error is thrown when DuckDB encounters an error during query execution, * connection management, or other database operations. * * @example * ```typescript * try { * await conn.query('SELECT * FROM nonexistent_table'); * } catch (e) { * if (e instanceof DuckDBError) { * console.error('DuckDB error:', e.message); * console.error('Query:', e.query); * } * } * ``` */ declare class DuckDBError extends Error { /** Error code if available */ readonly code?: string; /** The SQL query that caused the error */ readonly query?: string; constructor(message: string, code?: string, query?: string); /** * Create a DuckDBError from a plain object (for worker message deserialization). * @internal */ static fromObject(obj: { message: string; code?: string; query?: string; }): DuckDBError; /** * Convert to a plain object for worker message serialization. * @internal */ toObject(): { message: string; code?: string; query?: string; }; } /** * Package version constants * * These are injected at build time via tsup's define option. * * @packageDocumentation */ /** Package name for CDN URL generation */ declare const PACKAGE_NAME: string; /** Package version for CDN URL generation */ declare const PACKAGE_VERSION: string; export { AccessMode, type CSVInsertOptions, type ColumnInfo, Connection, DataChunk, DuckDB, type DuckDBBundle, type DuckDBConfig, DuckDBError, DuckDBType, type DuckDBTypeId, type FileInfo, type InitOptions, type JSONInsertOptions, PACKAGE_NAME, PACKAGE_VERSION, PreparedStatement, AsyncStreamingResult as StreamingResult, createWorker, getDB, getJsDelivrBundle, getUnpkgBundle, init, version };