API reference
The public entry points and the APIs you are most likely to use.
Start with @minnowdb/core for the SQL engine and core schema declarations. Import the optional
typed-table renderer from @minnowdb/core/schema; SQL-only applications then do not ship its
statement builder. Add the Kysely, React, export, or devtools packages only when you need them. The
remaining core entry points expose workers, storage, planning, and testing tools. Your editor shows
the complete signatures from each package's declarations.
Every published subpath is covered by the same semantic-versioning contract after 1.0. The
audience labels explain who normally imports an entry point; extension, testing, and runtime
do not mean experimental. See the v1 support policy for the release
rules behind this table.
| Entry point | Audience | Contents |
|---|---|---|
@minnowdb/core | Application | SQL engine, schema DSL, catalog, migrations, and errors |
@minnowdb/core/client | Application | Main-thread worker client |
@minnowdb/core/query | Extension | SQL compiler, standalone executor, binding, and plan inspection |
@minnowdb/core/live | Application | Typed, keyed, and low-level live queries |
@minnowdb/core/schema | Application | Schema DSL, typed tables, and migrations without the engine |
@minnowdb/core/schema-wire | Extension | Schema serialization for workers and adapter tooling |
@minnowdb/core/worker | Runtime | Ready-made worker entry (side-effect import) |
@minnowdb/core/worker/{indexeddb,opfs,memory} | Runtime | Worker entry bundling one store only (side-effect import) |
@minnowdb/core/worker-host | Extension | Manual host for custom worker entry points |
@minnowdb/core/plan | Extension | Low-level plan construction and optimization tools |
@minnowdb/core/storage | Application | Block stores: IndexedDB, OPFS, in-memory, the storage interface |
@minnowdb/core/storage/{indexeddb,opfs,memory} | Application | One storage adapter without the other adapters |
@minnowdb/core/storage/contracts | Extension | Storage interfaces, records, limits, and errors |
@minnowdb/core/storage/snapshots | Application | Portable snapshot framing and streaming helpers |
@minnowdb/core/storage/persistence | Application | Browser origin-persistence policy |
@minnowdb/core/storage/toolkit | Extension | Building blocks for writing storage adapters |
@minnowdb/core/transactions | Extension | Snapshots, transactions, recovery (lower level) |
@minnowdb/core/block-format | Extension | Binary block containers and codecs (lower level) |
@minnowdb/core/worker-protocol | Extension | Versioned RPC frames (lower level) |
@minnowdb/core/testing | Testing | Fault injection and the shared block-store test kit |
@minnowdb/core/sql-feature-matrix.json | Metadata | Runnable SQL support and exclusion examples |
@minnowdb/core/postgres-feature-profile.json | Metadata | PostgreSQL compatibility classifications |
@minnowdb/core/package.json | Metadata | Package identity and export metadata |
@minnowdb/kysely | Application | Optional Kysely dialect using its PostgreSQL compiler |
@minnowdb/kysely/helpers | Application | Typed Minnow-native nested JSON projection helpers |
@minnowdb/react | Application | React external-store hook for typed live queries |
@minnowdb/export | Application | Backpressure-aware CSV and NDJSON query streams |
@minnowdb/devtools | Application | Embeddable database console and data browser |
Schema DSL
Core declarations come from @minnowdb/core or the smaller @minnowdb/core/schema entry.
typedTable comes only from the schema entry. See Schema & migrations.
| Export | Description |
|---|---|
table(name, columns, options) | Defines a table. Options include primaryKey, composite foreignKeys, and checks. The result carries inferred row types and a Standard Schema ~standard validator. |
column.boolean() / number() / string() / datetime() | Column builders for the four physical storage types. |
column.integer() / numeric() / json() / jsonb() / uuid() / date() / time() / interval() / array() | Builders retaining the SQL engine's domain metadata and exact boundary types. json/jsonb accept an optional declared document shape — column.jsonb<Shape>() — that types the Kysely adapter's ->/->> traversal. |
column.enum([...]) | A string column restricted to a closed value set, typed as the literal union and validated on every write. Migrations may add values, never remove. |
column.sqlEnum(name, values) | Per-column named enum metadata, typed as the values' literal union. It does not create a reusable CREATE TYPE object. |
.unique() / .nullable() / .renamedFrom() | Column modifiers: unique key, NULL widening, stable-ID rename. |
.references(table, column, options?) | Declares a FOREIGN KEY. onDelete controls an enforced key; { enforced: false } records catalog-only relationship metadata with no row validation or delete action. |
.autoIncrement() / .default(value) / .defaultSql(expression) | Catalog-owned default values: an atomic integer-key counter, a literal, or a validated variable-free SQL expression evaluated once per omitted row. Explicit NULL is preserved. |
.generatedSql(expression) | Stored immutable expression over sibling columns, recomputed on every write and excluded from inferred insert/update inputs. |
schema(tables, { views }) | Bundles tables and views into a SchemaDefinition for migrate(). |
view(name, { sql, columns }) | Declares a read-only view. The engine verifies the declared columns against the query's inferred output at migration time. |
typedTable(database, tableDef) (@minnowdb/core/schema) | Thin schema-typed handle that renders parameterized SQL for inserts, upserts, keyed updates/deletes, and reads. |
planMigration(catalog, definition) | Computes the metadata-only MigrationPlan that migrate() executes. |
InferRow / InferInsertRow / InferUpdateChanges | Per-table select / insert / keyed-update shapes. |
SchemaDefinition, TableSchema, AnyTable, ColumnBuilder, SchemaColumnType, MigrationStep, MigrationPlan, JsonShape | Supporting types. JsonShape<Shape> is the branded JSON-text select type of a column with a declared document shape. |
Catalog introspection
From @minnowdb/core. See Extending Minnow.
| Export | Description |
|---|---|
database.introspect() | The published catalog: stable column IDs, key identity, foreign keys (including their enforced flag), checks, secondary indexes, triggers, and views. |
Catalog, CatalogTable, CatalogColumn, CatalogView | Its types. |
CatalogForeignKey, CatalogCheck, CatalogIndex, CatalogTrigger | Constraint, index, and trigger entries. |
toCatalog(records) | Projects storage table records into a Catalog; sorted by name so a diff is stable. |
MinnowSqlExecutor | Structural query / queryCursor / execute contract for SQL-emitting clients. |
MinnowSqlDriver | MinnowSqlExecutor plus introspect() for schema-aware adapters. |
Live queries
From @minnowdb/core/live.
| Export | Description |
|---|---|
class LiveQuery<TRow> | Typed external store and async iterable with loading / ready / error snapshots, stable identity, and refresh(). |
class KeyedLiveQuery<TRow, TKey> | Exact keyed insert / update / delete / move changes, with optional row-bound enforcement. |
class LiveQueryManager / createLiveQueryManager | Owns one shared observer backend and creates typed queries from adapter-provided LiveQuerySource values. |
class LiveQuerySet | Low-level SQL/plan set from database.liveQueries(): subscribe, subscribePatches, observer-only observe (optionally suppressUnchanged), refresh, stats, and close. |
LiveSnapshot / LiveChangesSnapshot / LiveResultChange / LiveKeyOf | Typed snapshot, patch, and key-selection types. |
LiveQuerySource / LiveQueryBackend / LiveQueryDriver | Structural contracts for query-library adapters. |
LiveQuerySetOptions / LiveQueryStats / LiveQueryGroupStats / LiveQueryInput | Hint/poll/sharedResults and maxRetainedBytes configuration, execution and retained-byte counters, per-statement maintenance groups (maintainable, reasons, reruns, maintained, fallbacks), and low-level query inputs. |
LiveQueryHost / LiveQueryExecuteContext | The probe, manifest, dependency, execution, and incremental-maintenance contract a LiveQuerySet runs over. |
LiveQueryDelivery / LiveMaintainedExecution / LiveMaintainedChange | What a delivered result reflects, and a maintainable execution's result and opaque state. |
See Live queries for Kysely composition, keyed changes, windows, cross-tab invalidation, and teardown.
The engine — MinnowDatabase
From @minnowdb/core. See Writes & transactions.
new MinnowDatabase(store: BlockStore, options?: MinnowDatabaseOptions)MinnowDatabaseOptions covers the schema the database is typed against, compression, block size,
write retries, query spilling, idle SQL transactions, caching, automatic full-text indexing,
background maintenance, and onBackgroundError, which hears failures of work no call owns.
maintenanceStatus() also exposes a bounded background failure history and total count. The full option
table is on The database API. bufferPoolBytes defaults to 64 MiB and
limits one shared cache of decoded blocks and reusable query work; 0 disables it. Compiled SQL
plans are cached separately by statement text.
MAX_SQL_TEXT_CHARACTERS, MAX_SQL_TOKENS, MAX_SQL_NESTING_DEPTH, MAX_SQL_PARAMETERS,
MAX_SQL_PATTERN_CHARACTERS, MAX_SQL_PATTERN_MATCH_STEPS, MAX_SQL_NUMERIC_DIGITS,
MAX_SQL_SCALAR_RESULT_CHARACTERS,
MAX_SQL_STRUCTURED_VALUE_ITEMS, and MAX_SQL_STRUCTURED_VALUE_DEPTH publish the fixed
compilation and value safety limits.
| Group | Methods |
|---|---|
| Catalog | createTable, listTables, introspect(), migrate(schema), createIndex, dropIndex, createView, dropView, dropColumn, dropTable |
| Writes | insertBatch, insert, upsertBatch, upsert, updateBatch, update, deleteBatch, delete, bufferedWriter(table, options) |
| Reads | readTable(table, { columns, version? }), listVisibleSegmentPage(table, { cursor?, version?, limit? }). Segment pages contain at most 64 records in lexical segment-ID order. The first page captures and returns a manifest version; following its cursor keeps later pages on that exact version while writers commit to the same table. An empty page can still have a cursor when its bounded physical window contained only historical records. Dropping or replacing the table invalidates its cursor and throws VisibleSegmentCursorStaleError instead of returning a partial scan. |
| SQL | query(sql, { signal?, onStats?, ...options }), queryCursor(sql, { batchRows, signal?, onStats?, ...options }), snapshot(callback), write(callback, { signal? }), explain(sql), execute(sql, params?, { signal?, onStats?, memoize?, executionMemoryBudgetBytes? }), plus the lower-level run(typedQuery) and runStatement(statement). Cancellation stops between bounded batches, returns no partial result, and cleans up reader/spill ownership. A SELECT through execute honors every control in its options; other statements check signal once before running, so an already-aborted execute never mutates anything. A write() session offers query with the same controls, execute, and the batch mutation calls; it publishes every staged change as one commit and reads its own staged rows — see write scopes. execute() also accepts BEGIN, COMMIT, and ROLLBACK; idle transactions roll back after transactionIdleTimeoutMs. CREATE TRIGGER / DROP TRIGGER save row triggers that run inside the same commit — see triggers. Statements cover INSERT ... SELECT, ON CONFLICT (key) DO NOTHING / DO UPDATE SET <expression>, and RETURNING on every mutation; placeholders (?/$n) bind through options.params or the execute parameter list, including full-text search text after AGAINST. |
| Snapshots | exportSnapshot(options?) and importSnapshot(bytes, options?) are byte-array conveniences. exportSnapshotStream(options?) and importSnapshotStream(source, options?) keep large files pull-driven and bounded. All take progress/abort options — see snapshots. |
| Search | buildFtsIndex(table, column) builds an index now; ordinary MATCH queries can also schedule one automatically. |
| Live | liveQueries(options?) |
| Compaction | compactTable, compactTableStep, resumeCompactionJob, listCompactionJobs, cancelCompactionJob |
| GC | collectGarbage, collectGarbageStep, resumeGarbageCollectionJob, listGarbageCollectionJobs, cleanupQuerySpill, maintenanceStatus(), writeCoordination (how far the writer turn reaches: cross-context, context, or instance) |
| Diagnostics | checkIntegrity({ mode, maxIssues? }), storageStats(), inspectInterruptedImport(), abortInterruptedImport(identity) |
| Lifecycle | close() stops background work and live queries, rolls back an open SQL transaction, releases the reader lease, and clears resident caches. The injected store remains caller-owned. |
readTable() returns only the table's declared public columns. Engine-maintained row locators,
including the scalar locator used for a composite primary key, cannot be selected by name or
appear in a wildcard result.
Notable supporting exports:
BufferedTableWriter—add(row),flush(),requestFlush(),close(),discard(), stats; configured byBufferedWriterOptions(mode,maxRows,maxBytes,maxAgeMs,onError).attachLifecycleFlush(writerProxy, options)— requests flushes onvisibilitychange/pagehide.QueryOptionsandQueryCursorOptions— including execution memory, spill, batch, abort, and execution-stat callback configuration;QueryResult/QueryRow/QueryValuefor results.QueryResult.columnDomainsis aligned withcolumnsand exposes eachSqlDomain(ornullfor an ordinary primitive), including aliased JSON constructors. Mutation results withRETURNINGcarry the equivalent alignedreturnedColumnsandreturnedColumnDomains;WriteMetricsappears on every batch result.- Plan tooling from
@minnowdb/core/query—compileQuery,compileStatement,executeQuery,bindPlanParameters,bindStatementParameters,optimizePlan,renderPlan,referencedColumns,CompiledQuery,CompiledStatement. - Input/result types —
CreateTableInput,InsertBatchInput/Result,UpsertBatchResult,UpsertOptions,UpsertConflictWhere,UpdateBatchInput/Result,DeleteBatchInput/Result,ReadTableOptions,TableDefinition,CompactTableOptions/Result,CollectGarbageOptions,GarbageCollectionResult, and friends.
Errors
| Error | Thrown when |
|---|---|
UniqueConstraintError | A write violates the table's unique key. |
MissingKeyError | A keyed update/delete names a key that does not exist. |
UnknownTableError | An operation names a table absent from the current catalog; carries tableName. |
SqlCompileError | SQL fails to compile; carries offset and length. |
QueryMemoryBudgetError | A statement cannot execute or spill inside its memory budget. |
MaintenanceBacklogError | Automatic collection repeatedly fails and storage-growth backpressure refuses another write. |
DatabaseReadBacklogError | One database already has its bounded maximum of active reads. |
LiveQueryLimitError | A live-query owner reaches its set, group, or subscription resource ceiling. |
CompactionMemoryBudgetError, CompactionWriteAmplificationError, CompactionJobCancelledError | Compaction limits or cancellation. |
DatabaseWorkerTimeoutError, DatabaseWorkerOutcomeUnknownError | A worker call passed its deadline; a mutation's reply was lost, so it may have published. |
DatabaseWorkerFailedError | The Worker raised an error it did not handle, or sent an unreadable frame; carries reason. |
DatabaseStoreUnavailableError | An auto store's remembered kind cannot open here (store, databaseName); the database is not reopened empty elsewhere. |
StorageUnresponsiveError | The store answered nothing for its whole deadline; the browser has wedged the database and the remedy is to reload the page. |
UnknownOutcomeError, ConnectionLostError | Marker bases: "the operation may have happened" and "this connection is finished". |
classifyError(error) | { kind, mayHavePublished, retry, connectionUsable } for any error; see Errors. |
The worker client recreates these errors on the main thread, so instanceof works there too,
with their cause chain, and a DOMException stays a DOMException.
@minnowdb/core/worker-host
Manual worker-host exports live in this subpath so the main engine entry does not retain every
storage adapter. See Workers & multi-tab. Schema serialization has its own
@minnowdb/core/schema-wire entry.
| Export | Description |
|---|---|
exposeDatabase(database, scope, options?) | Serves the full client protocol for a database you constructed. writeHandleIdleTimeoutMs bounds abandoned explicit writes; match it to the database's transactionIdleTimeoutMs. |
attachDatabaseWorker(scope, options?) | What the stock @minnowdb/core/worker entry calls: builds the database from the client's init frame. options.createStore replaces the stock any-store factory; options.indexedDB injects an IDBFactory for tests. |
singleStoreFactory(kind, open) | Builds a WorkerStoreFactory that opens one store kind through open(descriptor, options) and refuses every other kind, naming the per-store entry that supports it. |
WorkerStoreFactory, WorkerStoreOptions | The store factory signature (descriptor, options) => BlockStore | OpenedStore | Promise<…> and its options (indexedDB?, onDiagnostic?). Returning OpenedStore ({ store, kind }) tells the client which OpenedStoreKind opened when the descriptor did not name it. |
openAutoStore(name, open), resolveAutoStoreKind(name), forgetStoreChoice(name), AutoStoreKind | The auto descriptor's resolution: OPFS where the worker can hold synchronous access handles, else IndexedDB, remembered per name in a small IndexedDB record. forgetStoreChoice (also exported from @minnowdb/core for the main thread) clears the memory when the database is deleted. |
StoreDescriptor | { kind: "indexeddb", name, durability?, uniqueKeyCacheBytes? } | { kind: "opfs", name, … } | { kind: "auto", name, opfs?, indexeddb? } | { kind: "memory" } — the cloneable store config; auto picks OPFS where the worker can hold it, else IndexedDB, remembered per name. Omitted, it defaults to { kind: "indexeddb", name: "minnow" }. |
WireDatabaseOptions, DatabaseInitPayload | The cloneable subset of MinnowDatabaseOptions and the init frame shape. |
@minnowdb/core/schema-wire
serializeSchema, deserializeSchema, and serializeMigrationSteps expose the schema DSL wire
format used automatically by client.migrate().
@minnowdb/core/client
| Export | Description |
|---|---|
class MinnowDatabaseClient | Main-thread worker proxy. Construct with a Worker (any ClientTransport) and MinnowDatabaseClientOptions (store, wire options). |
.ready() | Surfaces store-open failures eagerly; calls may be issued before it resolves. |
.storeKind() | The kind of store the worker opened — what { kind: "auto" } resolved to, or the kind the descriptor named. |
| Mirrored API | Queries, pull-driven query cursors, writes, catalog and index helpers, migrations, reads, live queries, snapshots, and maintenance. |
.close({ terminateWorker? }) | Tears down handles, optionally terminating the worker. |
.reopen(transport?), onConnectionLost | After a lost connection: a fresh worker behind the same client (pass a transport, or construct with a factory); the hook fires once. |
ClientBufferedWriter, ClientLiveQuerySet, ClientLiveSubscription, ClientWriteSession, ClientSnapshotSession | Handle proxies; synchronous getters become methods (stats(), memoryUsage()). |
onWorkerError | Option: hears every worker failure that belongs to no call, as a DatabaseWorkerErrorEvent; defaults to console.error. |
ClientTransport, ClientLiveQueryOptions, CloseClientOptions, ClientMigrationResult, DatabaseWorkerErrorEvent | Supporting types. |
@minnowdb/core/worker
A side-effect module: importing it inside a module worker attaches the database host to
self. Point a Worker at it and pass the store descriptor from the client — see
the quick start.
@minnowdb/core/worker/indexeddb, @minnowdb/core/worker/opfs, and @minnowdb/core/worker/memory
attach the same host with one store bundled statically, for bundlers that cannot split worker
code; each refuses an init frame for another store kind. @minnowdb/core/worker/auto bundles
the two durable stores and serves { kind: "auto" } as well as either of them by name. See
per-store worker entries.
@minnowdb/core/plan
Tools for building a typed layer over the engine. They are the same plan-building functions and checks used by the SQL parser, so a hand-built plan is checked just like parsed SQL. See Extending Minnow.
| Export | Description |
|---|---|
assembleSelectBlock, compoundSelectBlock, derivedTableSource | Assemble one select block, a set operation, a subquery. |
splitCondition, validateLimit, validateOffset, validateFtsQuery, hasAggregate | Checks and helpers used by the parser. |
optimizePlan, renderPlan | Optimize a plan; render one for display. |
CompiledQuery, Expression, JoinPlan, Predicate, SelectItem, SetOperator, TableSource | Plan types. |
AggregateName, PredicateOperator, WindowFunctionName, QueryValue, QueryRow, QueryResult | Supporting types. |
@minnowdb/kysely
The optional Kysely dialect. Installed separately with Kysely itself; see Kysely.
| Export | Description |
|---|---|
createKysely({ driver, schema, resultDecoding? }) | Creates an inferred Kysely DB; decoding can convert NUMERIC to number and parse JSON/JSONB results. |
jsonBuildObject / jsonArrayFrom / jsonObjectFrom | Fully typed JSON object and correlated row projections; also exported from @minnowdb/kysely/helpers. |
search.match(eb, columns, query) / search.rank(…) | Type-safe, parameterized MATCH predicate and numeric BM25 ranking expression; columns must be visible and non-empty. |
createKyselyLiveQueries({ driver, db?, ...options }) | Callable typed live wrapper; with db, decodes engine-delivered results through the dialect and plugins. Supports query.$call(live), changes(query, { key }), and ordered bounded window(). |
InferKyselyDatabase / InferKyselyTable / InferKyselyView | Converts schema metadata to Kysely select, insert, update, and operand types. |
MinnowResultDecoding / MinnowJsonValue | Native NUMERIC/JSON result options and the recursively typed parsed JSON value. |
MinnowColumnType / MinnowOperandType | Kysely metadata for exact NUMERIC operands and Minnow-specific aggregate and built-in function result inference. |
MinnowDialect | Kysely Dialect using PostgreSQL SQL syntax over a MinnowSqlDriver. |
MinnowDialectConfig | { driver, schema?, resultDecoding? }; decoding applies to buffered, streamed, and RETURNING rows. |
MinnowQueryCompiler | PostgreSQL compiler that keeps omission and DEFAULT visible; generated values stay catalog-owned. |
MinnowKyselyDriver | The single-connection Kysely driver; usually constructed by MinnowDialect. |
MinnowKyselyIntrospector | Catalog-backed table/view metadata with no invented schemas. |
@minnowdb/react
| Export | Description |
|---|---|
useLiveQuery(query, options?) | Concurrent external-store read. Options add cold-start Suspense and previous-store stale-while-revalidate behavior. |
useSuspenseLiveQuery(query, options?) | Suspense-first form whose result type excludes the cold loading snapshot. |
useLiveSelector(query, { select, isEqual? }) | Reads one derived value and re-renders only when it changes; isEqual defaults to Object.is. |
LiveExternalStore<TSnapshot> | The minimal structural getSnapshot / subscribe contract. |
RefreshableLiveExternalStore<TSnapshot> | Adds the refresh() promise required by Suspense. |
UseLiveQueryOptions, UseLiveSelectorOptions, SettledLiveSnapshot | React binding option and settled-result types. |
@minnowdb/export
| Export | Description |
|---|---|
streamCsv(source, sql, options?) | ReadableStream<Uint8Array> with header, delimiter, newline, NULL, batch, parameter, and abort options. |
streamNdjson(source, sql, options?) | Exact finite SQL scalars as one JSON object per line. |
QueryCursorSource | Structural queryCursor() source implemented by the direct engine and worker client. |
@minnowdb/core/storage
The complete barrel remains convenient for tooling. Application code should normally import its
chosen adapter from @minnowdb/core/storage/indexeddb, /opfs, or /memory; contracts,
snapshot helpers, and origin-persistence policy likewise have adapter-free /contracts,
/snapshots, and /persistence entry points. The subpaths preserve the same exports while making
adapter isolation explicit even to conservative bundlers.
| Export | Description |
|---|---|
class IndexedDbBlockStore | The IndexedDB store. open({ name, durability?, uniqueKeyCacheBytes? }); close(). |
class OpfsBlockStore | The OPFS store, worker-only. OpfsBlockStore.open({ name, durability?, … }); close(). |
deleteOpfsDatabase({ name }) | Removes an OPFS database's directory entirely. |
class MemoryBlockStore | Same interface, in memory — the unit-test store. |
ensureOriginPersistence(policy?) | Checks or requests browser protection from automatic whole-origin eviction. "required" throws OriginPersistenceRequiredError unless protection is present; "request" returns the grant status; "best-effort" never prompts. |
readSnapshotSummary(bytes), SNAPSHOT_FORMAT_VERSION | Validates the bounded canonical header of a materialized snapshot for confirmation UI, and exposes the framed-container version. |
class OpfsTree | The OPFS adapter's file helper: cached directory handles, whole-file reads and writes, plus the browser differences around retries and locked files. It implements the toolkit's ExtentFiles interface. |
BlockStore | The complete storage interface shared by all three adapters. It combines block, catalog, transaction, lease, maintenance, full-text, and temporary-page operations. See Writing a storage adapter. |
Manifest, TableRecord, TableColumnRecord, TableForeignKeyRecord, SegmentRecord, RowIdSpan, LeaseRecord, … | The persistent record types. TableForeignKeyRecord.enforced is absent/true for enforced keys and false for informational metadata. |
MAX_CATALOG_RECORDS, MAX_MANIFEST_RECORDS, and the other MAX_* storage exports | Fixed per-call, control-record, owner, journal, spill, metadata, accelerator, pin, and obsolete-history limits used by every adapter. |
StorageCorruptionError | A durable adapter consumed malformed control metadata or a corrupt payload and failed closed; carries backend and location. |
StorageFormatVersionError | Stored bytes use a recognized but unsupported version; carries backend, location, actual/supported versions, and their relation. Version refusal never implies automatic deletion. |
IndexedDbSchemaUpgradeBlockedError | A native IndexedDB schema upgrade is waiting for an older open connection; carries the database name and old/requested versions so the UI can ask the user to close older tabs and retry. |
StorageResourceLimitError | An atomic storage mutation would cross a fixed count or byte growth fuse; carries the resource, attempted count, and limit. |
StorageUnresponsiveError, INDEXEDDB_UNRESPONSIVE_AFTER_MS | The connection answered nothing for its whole deadline while work was outstanding; carries backend, database name, and the wait. Reload the page — see A store that stops answering. |
OpfsUncertainOutcomeError | A leader vanished with this mutation in flight and the recovered log can neither answer it nor rule it out (sent before the ledger's coverage, or the leader died between the mutation's frame and its result frame). Reconcile stable ids or revisions before retrying. |
SchemaConflictError, WriteConflictError, TableRecordConflictError, OriginPersistenceRequiredError | Structural-schema and manifest conflicts, table-record conflicts, and a refused required origin-persistence policy. |
StorageIntegrityReport, StorageStats, InterruptedSnapshotImport | Bounded integrity results, logical/physical growth accounting, and resumable-import inspection. |
SimpleDataType, simpleDataTypes | The four physical storage types as a value and union. |
SqlDomain, validateSqlDomain | Logical numeric, JSON, UUID, DATE, TIME, interval, array, enum, and collation descriptors used by schema, catalog, and query-result metadata. |
Record and job types beyond these (compaction plans, GC cursors, temp-run pages) are exported for tooling but are storage internals. Their TypeScript API may still change during 0.x; the bytes written by the locked block-format 2, snapshot-format 1, IndexedDB-schema 4, and OPFS-layout 9 writers are separate format contracts and cannot be reinterpreted in place.
@minnowdb/core/storage/toolkit
The adapter toolkit: the building blocks the memory and OPFS adapters are assembled from, published for writing new adapters. Deliberately separate from the required storage interface. The engine never imports it, and a custom adapter does not have to use it.
| Export | Description |
|---|---|
class RecordCore | The in-memory record engine used by the memory and OPFS adapters. It has one method per operation, dump()/load() for checkpoints (and dumpSliced(pause) / loadSliced(state, pause, { owned? }), which copy, check, and build large key memberships and index changes a slice at a time), prepareCommit(input, pause) to do a large commit's work a slice at a time before the commit reuses it — UNIQUE keys checked and applied to their memberships behind a mask, index changes checked, new blocks checksummed — and discardPreparedCommit(pause) for a commit that does not follow, and a PhysicalBlocks interface for checking stored bytes. The core keeps the index postings a commit hands it rather than copying them. |
class WalWriter / replayWalFrames(handle) / iterateWalFrames(handle, acknowledgedEndOffset?) | Checksummed WAL frames over a held SyncFileHandle. The optional independently verified acknowledgement boundary refuses missing or corrupt bytes before that offset; only an unacknowledged incomplete or zero suffix can be ignored. appendEncoded(bytes, flush) appends a payload already encoded, so a large frame can be encoded a slice at a time beforehand. A payload larger than one frame goes in continuation frames: appendEncodedSliced(bytes, flush, pause) writes them a piece at a time, or appendContinuation(piece, flush) writes pieces and the next appendEncoded completes them; rewind(offset) takes back pieces whose payload failed. Replay joins the pieces, and treats pieces with nothing after them as an unwritten tail. |
iterateWalFramesSliced(handle, acknowledgedEndOffset, pause) / WAL_CONTINUATION_PIECE_BYTES | iterateWalFrames as an async iterator that pauses between frames and pieces and decodes a large payload a slice at a time; the piece size the sliced writer uses. A reader from before continuation frames refuses them as foreign bytes, so gate older readers with your own format marker before writing them. |
class ExtentPool | Packed append-only extent files for bulk bytes, addressed by checksummed Placements; verified recovery reads, sealing, live-byte accounting, fragmentation detection, and a read-handle cache. Opens files through ExtentFiles. |
encodeRecordJson / decodeRecordJson | JSON with bigints ({"$n":"…"}) — the codec frames and checkpoints use. |
appendTransactionJournal(record, additions) | Extends a transaction record's journal by the staged ids without re-validating what it already holds; the caller proves the additions are new, so a staging call costs what it stages. |
encodeSyncCheckpoint / decodeSyncCheckpoint, encodeChunk / decodeChunk | Checksummed, versioned envelopes for checkpoint payloads and immutable artifact chunks; torn bytes decode as "not written". |
encodeSyncCheckpointSliced(state, pause) / decodeSyncCheckpointSliced(bytes, pause) | The same bytes and values as encodeSyncCheckpoint / decodeSyncCheckpoint, worked a bounded piece at a time with pause() awaited between pieces, so a large checkpoint does not hold the thread; an encoded state must not change until it settles. |
SyncFileHandle | The small file interface used by the toolkit: positioned read, write, truncate, flush, and close. A browser FileSystemSyncAccessHandle already has this shape. |
readFully / writeFully | Complete positioned transfers across short I/O without copying; reject invalid or overflowing ranges before I/O, plus EOF, zero progress, and invalid byte counts. |
RecordCoreState, PhysicalBlocks, ExtentFiles, ExtentMeta, Placement, LOG_FORMAT_VERSION | Supporting types and the on-disk envelope version. |
@minnowdb/core/transactions
The commit machinery under the engine — useful for storage-level tooling and tests, not needed for application code.
| Export | Description |
|---|---|
class TransactionManager | Opens snapshots and transactions over a BlockStore; recovery. |
class DatabaseTransaction | Staged blocks + atomic manifest publication. setUniqueKeyChangesSliced(changes, { distinct? }) records a large key list a slice at a time, and setFtsChangesSliced(changes, { owned? }) an index delta; with distinct or owned the caller hands over a list it built for the call, which is kept as given. A transaction's key and index changes have no size limit. |
class Snapshot / class LeasedSnapshot | Immutable read views; leased snapshots persist expiry records. |
TransactionClosedError | Use after commit/abort. |
TransactionManagerOptions, RecoveryOptions, RecoveryReport, OpenLeasedSnapshotOptions | Supporting types. |
@minnowdb/core/block-format
The versioned binary containers: block headers, column encodings, codec registry, checksums, zone-map statistics, and physical-type mapping. Everything here is re-exported for tooling and inspection. Block-format 2 is the first locked byte contract: incompatible future writers must use a new format number and retain its reader.
@minnowdb/core/worker-protocol
The versioned, structured-clone-safe RPC frames between client and worker: protocolVersion,
request/response/event frame types, parseRpcRequest / parseRpcResponse,
serializeError / rehydrateError, the worker diagnostic frame (workerErrorEvent,
WorkerErrorReport), and the frame constructors. Method dispatch is whitelisted per handle — the
worker never dispatches arbitrary property access. Query results and live change events travel
inside these frames in a columnar form (one array per column, typed arrays transferred) that the
client turns back into QueryResult rows; see Workers.
@minnowdb/core/testing
| Export | Description |
|---|---|
class FaultInjectingBlockStore | Wraps any BlockStore; new FaultInjectingBlockStore(inner, inject) calls inject(point) around storage operations. |
blockStoreConformanceCases() / runBlockStoreConformance(target) | The shared storage test kit: cases any BlockStore implementation must pass, ready to use with any test framework. |
faultPoints, FaultPoint | The named points: beforeBlockWrite, afterBlockWrite, beforeBlockRead, afterBlockRead, beforeManifestCommit, afterManifestCommit, beforeTransactionCommit, afterTransactionCommit. |
FaultInjector | (point: FaultPoint) => void | Promise<void> — throw to simulate the crash. |
class MemoryOpfs | An in-memory origin-private file system for Node tests: exclusive sync-access locks with real DOMException identities, plus setWriteFault for quota and crash injection. |
parseSqlLogicTest() / parseSqlLogicTestLines() | Strict in-memory and streaming parsers for the original SQLite SQLLogicTest format, with source locations on every record. |
runSqlLogicTest() | Runs SQLLogicTest records against an adapter and checks types, sorting, hashes, labels, expected errors, and conditional directives. |
generateSimulationPlan() / parseSimulationPlan() | Creates or validates a bounded, JSON-serializable deterministic concurrency and fault plan. |
runSimulation() / DeterministicScheduler | Replays the plan through real MinnowDatabase clients while choosing storage completions from the seed and checking a reference model plus final storage bounds. |
@minnowdb/devtools
The optional console and data browser. See Devtools for the complete setup and options.
| Export | Description |
|---|---|
mountMinnowDevtools(target, options?) | Mounts a floating launcher or inline panel and returns a MountedDevtools handle. |
createDevtools(root, target, options?) | Builds the panel in an existing shadow root. Useful when your application owns the host element. |
defineMinnowDevtools(name?), MinnowDevtoolsElement, elementName | Registers or uses the custom element. The default tag is <minnow-devtools>. |
DevtoolsOptions | mode, corner, hotkey, defaultOpen, zIndex, permissions, initialQuery, storageKey, theme, and inline height. |
DevtoolsHandle, MountedDevtools | Controls for open, close, toggle, setQuery, setTheme, isOpen, and destroy; a mounted handle also exposes its element. |
DevtoolsAttachable, DevtoolsTarget, DevtoolsPermissions, and more | Supporting types for accepted databases, worker clients, themes, layout, and permissions. |
@minnowdb/core/sql-feature-matrix.json
The compatibility data rendered at PostgreSQL compatibility. Every tracked form has a support status and runnable example. The excluded forms conflict with Minnow's embedded model. This file does not claim to enumerate PostgreSQL's whole grammar. Engine tests report drift against it, so the docs and implementation stay aligned.
@minnowdb/core/postgres-feature-profile.json
The executable dialect overlay for the same feature IDs. It classifies each form as
compatible, different, extension, unsupported, or inapplicable, records the PGlite
oracle version, and explains every deliberate PostgreSQL divergence.
LiveQueryPatch and LiveQueryPatchOptions describe low-level reset/patch delivery. Patches carry changed row payloads and a retained-position map; resets carry a complete result.