@unni-craftsman/turso-fts
v0.7.6
Published
<p align="center"> <h1 align="center">Turso Database for JavaScript in Browser</h1> </p>
Readme
About
This package is the Turso embedded database library for JavaScript in Browser, forked to enable mutable FTS indexing in the wasm browser build.
It is intended for browser apps that run Turso from a single Web Worker with OPFS persistence. The FTS path supports creating FTS indexes, querying, inserts, updates, deletes, INSERT OR REPLACE, rollbacks, statement aborts, close/reopen persistence, and large text documents tested around 30k characters.
Turso Database runs in production today at multiple organizations. It has not yet reached 1.0, so as with any database we recommend keeping backups — see the FAQ for where the project stands.
Features
- SQLite compatible: SQLite query language and file format support (status).
- Browser FTS: FTS indexes are enabled in the wasm browser build.
- Persistent browser storage: Designed for OPFS-backed databases in a Web Worker.
- TypeScript support: Full TypeScript definitions included.
Browser FTS Compared With Native Turso
The browser FTS cache is enabled. Native Turso 0.7.2 validates cached FTS metadata by synchronously reading the backing B-tree; browser OPFS cannot use that blocking path, so this fork explicitly invalidates wasm caches on full and savepoint rollbacks. It also discards cursor-local Tantivy writes when a statement aborts. The main tradeoff compared with native Turso FTS is the writer implementation:
- Native Turso uses Tantivy's native
IndexWriterpath, including native filesystem and threading assumptions. - This browser build uses a wasm-compatible single-segment writer path and maintains delete bitsets explicitly.
- The browser path prioritizes correctness for single-Worker OPFS usage over native indexing throughput.
Use native Turso for server-side workloads, concurrent writers, multi-process access, or maximum FTS indexing performance. Use this package when you need FTS inside a browser Worker with persistent OPFS storage.
Validation
Browser FTS is covered by a Worker/OPFS smoke test:
npm run build --workspace=packages/wasm
npm test --workspace=packages/wasm
npm run test:fts-smoke --workspace=packages/wasmThe package suite runs in both Chromium and Firefox and covers lazy-init
memoization/retry, the pending native database proxy, normal API behavior, and
the OPFS cache-spill regression. The smoke command then runs the full mutable
FTS workload against both ./bundle and ./bundle-external.
The smoke test creates an OPFS-backed database in a Web Worker, creates FTS indexes, verifies single and multi-column search, fts_score, statement abort rollback, full rollback cache invalidation, savepoint rollback, inserts, updates, deletes, INSERT OR REPLACE, same-row mutation churn, rowid reuse, close/reopen persistence, bulk indexing, and a deterministic 30k+ character document insert/update/delete cycle.
Native FTS transaction regressions live in tests/integration/index_method/mod.rs and cover statement abort, full rollback, and savepoint rollback cache invalidation:
cargo test -p turso_tests --features fts test_fts_ --test integrationInstallation
npm install @unni-craftsman/turso-ftsGetting Started
Persistent Browser Database
import { connect } from '@unni-craftsman/turso-fts';
// Create or open an OPFS-backed database from a Web Worker.
const db = await connect('my-database.db');
await db.exec('CREATE TABLE documents (id INTEGER PRIMARY KEY, content TEXT)');
await db.exec('CREATE INDEX documents_fts ON documents USING fts (content)');
await db.prepare('INSERT INTO documents VALUES (?, ?)').run(
1,
'the quick brown fox'
);
const rows = await db
.prepare('SELECT id, content FROM documents WHERE fts_match(content, ?)')
.all('fox');
console.log(rows);
// [{ id: 1, content: 'the quick brown fox' }]Transactions
import { connect } from '@unni-craftsman/turso-fts';
const db = await connect('transactions.db');
// Using transactions for atomic operations
const transaction = db.transactionAsync(async (txn, users) => {
const insert = await txn.prepare('INSERT INTO users (name, email) VALUES (?, ?)');
for (const user of users) {
await insert.run(user.name, user.email);
}
});
// Execute transaction
await transaction([
{ name: 'Alice', email: '[email protected]' },
{ name: 'Bob', email: '[email protected]' }
]);Initialization, Bundling, And Worker Boot Failures
Lazy initialization
Importing this package (any entry: default, ./bundle, ./bundle-external,
./vite, ./turbopack) has no side effects. Nothing is fetched, no Worker is
spawned, and no wasm module is instantiated at import time. The wasm module
and its OPFS/thread-pool Worker boot lazily on first connect() (or the
underlying init(), if you call it directly), and that boot is memoized -
concurrent or later connect() calls share the same in-flight or already
booted Worker instead of spawning a new one each time.
A practical consequence: a boot failure (bad wasm bytes, a Worker script that
404s or is served with the wrong MIME type, a timed-out handshake) surfaces as
a rejection from connect(), not as a silent hang or an import-time crash. A
failed boot is not cached, so the next connect() call retries from scratch.
The failed attempt's Worker is terminated before that retry can start.
tursoOpts: overriding wasm source / worker factory / boot timeout
connect(path, opts, tursoOpts) and new Database(path, opts, tursoOpts)
both take an optional third parameter to override how the wasm binary is
fetched, how the Worker is created, and how long boot is allowed to take
before failing:
interface TursoInitOptions {
/** Overrides how the wasm binary bytes are obtained. Defaults to the entry's built-in source. */
wasmSource?: URL | string | ArrayBuffer | Response | Promise<ArrayBuffer>;
/** Overrides how the OPFS/thread-pool Worker is created. Defaults to the entry's built-in factory. */
createWorker?: () => Worker;
/** Overrides the worker boot/handshake timeout (ms). Defaults to 30_000. */
bootTimeoutMs?: number;
}Example - serving the wasm binary from your own CDN/path instead of the entry's default, and giving boot more time on a slow connection:
import { connect } from '@unni-craftsman/turso-fts/bundle-external';
const db = await connect('my-database.db', {}, {
wasmSource: 'https://cdn.example.com/turso.wasm32-wasi.wasm',
bootTimeoutMs: 60_000,
});wasmSource and createWorker are per-call overrides on top of whichever
entry you imported; you do not need to supply both if you only want to
override one. Because init is memoized per module instance, the override used
by the first connect()/init() call wins for the lifetime of that module
instance - later calls share the same booted Worker even if they pass
different tursoOpts.
Choosing ./bundle vs ./bundle-external
Both are self-contained vite build outputs of the same connect/Database
API, built from the same source, with the Worker inlined either way. They
differ only in how the wasm binary is packaged:
| | ./bundle | ./bundle-external |
|---|---|---|
| Shape | single main.es.js (wasm inlined as base64) | main.es.js + external turso.wasm32-wasi.wasm asset next to it |
| External requests | zero - nothing else to fetch or serve correctly | one - your bundler/server must serve the .wasm file next to the JS with the right path and content type |
| JS file size | large (wasm inflated ~33% by base64 encoding) | small (a few hundred KB) |
| Wasm delivery | decoded from a base64 string already in memory - no compileStreaming, a decode memory spike at boot | fetched as bytes; can be served/cached independently and is streaming-friendlier for the wasm compile step |
| Best for | drop-in use, unknown/uncontrolled hosting, "it just works" robustness | apps that control their static asset serving and want a smaller JS payload and independently cacheable wasm |
Use ./bundle when you are not sure your build/serving setup will correctly
serve an extra .wasm file (correct path resolution relative to the JS,
correct Content-Type: application/wasm, no unexpected rewriting) - it is the
more robust default. Use ./bundle-external when you control static asset
serving and want the smaller JS file and a separately cacheable wasm asset.
Both are covered by the Worker/OPFS FTS smoke test (see "Validation" above);
npm run test:fts-smoke --workspace=packages/wasm runs the same workload
against both.
Worker boot failures
If the Worker fails to boot - the worker script errors, is served as the
wrong MIME type (e.g. a 404/HTML page instead of JavaScript), or the
handshake never completes - connect()/init() reject with an actionable
Error instead of hanging indefinitely. The error message names which worker
failed, what happened (error event, unparseable messageerror, or a boot
timeout), and hints at the likely cause for bundler-served workers. The
default boot timeout is 30 seconds; override it via tursoOpts.bootTimeoutMs
if your environment is known to be slower.
API Reference
For complete API documentation, see JavaScript API Reference.
Related Packages
- The @tursodatabase/serverless package provides a serverless driver with the same API.
- The @tursodatabase/sync package provides bidirectional sync between a local Turso database and Turso Cloud.
License
This project is licensed under the MIT license.
