Merge 'add basic examples for database-wasm package' from Nikita Sivukhin

Closes #3558
This commit is contained in:
Pekka Enberg
2025-10-03 17:21:25 +03:00
committed by GitHub
31 changed files with 1897 additions and 710 deletions

View File

@@ -199,3 +199,9 @@ Cargo.lock
npm
bundle
*.db
*.db-wal
*.db-changes
*.db-wal-revert
*.db-info

View File

@@ -0,0 +1,12 @@
# database-node
This is a minimal example showing how to use [`@tursodatabase/database`](https://www.npmjs.com/package/@tursodatabase/database) in the node.js
---
## Usage
```bash
npm install
node index.mjs
```

View File

@@ -0,0 +1,21 @@
import { connect } from "@tursodatabase/database";
const db = await connect("local.db", {
timeout: 1000, // busy timeout for handling high-concurrency write cases
});
// execute multiple SQL statements with exec(...)
await db.exec(`
CREATE TABLE IF NOT EXISTS guestbook (comment TEXT, created_at DEFAULT (unixepoch()));
CREATE INDEX IF NOT EXISTS guestbook_idx ON guestbook (created_at);
`);
// use prepared statements and bind args to placeholders later
const insert = db.prepare(`INSERT INTO guestbook(comment) VALUES (?)`);
// use run(...) method if query only need to be executed till completion
await insert.run([`hello, turso at ${Math.floor(Date.now() / 1000)}`]);
const select = db.prepare(`SELECT * FROM guestbook ORDER BY created_at DESC LIMIT ?`);
// use all(...) or get(...) methods to get all or one row from the query
console.info(await select.all([5]))

View File

@@ -0,0 +1,16 @@
{
"name": "database-node",
"version": "1.0.0",
"main": "index.mjs",
"author": "",
"license": "ISC",
"description": "",
"scripts": {
"tsc-build": "echo 'no tsc-build'",
"build": "echo 'no build'",
"test": "echo 'no tests'"
},
"dependencies": {
"@tursodatabase/database": "^0.2.0"
}
}

View File

@@ -0,0 +1 @@
.vercel

View File

@@ -0,0 +1,63 @@
# database-wasm-vite
This is a minimal example showing how to use [`@tursodatabase/database-wasm`](https://www.npmjs.com/package/@tursodatabase/database-wasm) in the browser with [Vite](https://vite.dev/).
---
## Usage
```bash
npm install
npm run dev
# or build assets and serve them with simple node.js server
npm run build
npm run serve
```
---
## Important: COOP / COEP Headers
Because `@tursodatabase/database-wasm` relies on **SharedArrayBuffer**, you need Cross-Origin headers in development and production:
### Vite dev server config (`vite.config.js`)
```js
import { defineConfig } from 'vite'
export default defineConfig({
server: {
headers: {
'Cross-Origin-Opener-Policy': 'same-origin',
'Cross-Origin-Embedder-Policy': 'require-corp',
}
}
})
```
### Static production server (`server.mjs`)
When serving the `dist/` build, also make sure your server sets these headers:
```js
res.setHeader("Cross-Origin-Opener-Policy", "same-origin");
res.setHeader("Cross-Origin-Embedder-Policy", "require-corp");
```
### Vercel deployment
If you deploy to [**Vercel**](https://vercel.com/), add a `vercel.json` file to ensure COOP / COEP headers are set:
```json
{
"headers": [
{
"source": "/(.*)",
"headers": [
{ "key": "Cross-Origin-Opener-Policy", "value": "same-origin" },
{ "key": "Cross-Origin-Embedder-Policy", "value": "require-corp" }
]
}
]
}
```

View File

@@ -0,0 +1,95 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>Guestbook</title>
<style>
body {
font-family: sans-serif;
max-width: 600px;
margin: 2rem auto;
}
#comments {
border: 1px solid #ddd;
border-radius: 6px;
padding: 0;
list-style: none;
}
#comments li {
padding: 8px;
border-top: 1px solid #eee;
}
#comments li:first-child {
border-top: none;
}
.time {
font-size: 0.8em;
color: gray;
}
</style>
</head>
<body>
<h1>Guestbook</h1>
<form id="form">
<input id="comment" placeholder="Write a comment..." style="width:70%; padding:6px;" />
<button type="submit">Add</button>
</form>
<ul id="comments"></ul>
<script type="module">
import { connect } from "@tursodatabase/database-wasm/vite";
let db = await connect("local.db", {
timeout: 1000 // busy timeout for handling high-concurrency write cases
});
// execute multiple SQL statements with exec(...)
await db.exec(`
CREATE TABLE IF NOT EXISTS guestbook ( comment TEXT, created_at DEFAULT (unixepoch()) );
CREATE INDEX IF NOT EXISTS guestbook_idx ON guestbook (created_at);
`);
await refresh();
async function addComment() {
// use prepared statements and bind args to placeholders later
const insert = db.prepare(`INSERT INTO guestbook(comment) VALUES (?)`);
const input = document.getElementById("comment");
const text = input.value.trim();
input.value = "";
// use run(...) method if query only need to be executed till completion
await insert.run([text]);
await refresh();
}
document.getElementById("form").addEventListener("submit", (e) => {
e.preventDefault();
addComment();
});
async function refresh() {
const select = db.prepare(`SELECT comment, created_at FROM guestbook ORDER BY created_at DESC LIMIT ?`);
// use all(...) or get(...) methods to get all or one row from the query
const rows = await select.all([5]);
const ul = document.getElementById("comments");
ul.innerHTML = "";
rows.forEach((row) => {
const li = document.createElement("li");
li.innerHTML = `
<div>${row.comment}</div>
<div class="time">${new Date(row.created_at * 1000).toLocaleString()}</div>
`;
ul.appendChild(li);
});
}
</script>
</body>
</html>

View File

@@ -1,19 +1,21 @@
{
"name": "wasm",
"name": "database-wasm-vite",
"version": "1.0.0",
"main": "index.js",
"scripts": {
"dev": "vite",
"build": "vite build",
"preview": "vite preview"
"serve": "node server.mjs",
"tsc-build": "echo 'no tsc-build'",
"test": "echo 'no tests'"
},
"author": "",
"license": "ISC",
"description": "",
"devDependencies": {
"vite": "^7.1.4"
"vite": "^7.1.9"
},
"dependencies": {
"@tursodatabase/database": "../.."
"@tursodatabase/database-wasm": "^0.2.0"
}
}

View File

@@ -0,0 +1,34 @@
import http from "http";
import { readFile } from "fs/promises";
import { extname, join } from "path";
import { fileURLToPath } from "url";
const root = fileURLToPath(new URL("./dist", import.meta.url));
const port = 8080;
const mimeTypes = { ".html": "text/html", ".js": "application/javascript" };
const server = http.createServer(async (req, res) => {
// COOP / COEP headers necessary for shared WASM memory
res.setHeader("Cross-Origin-Opener-Policy", "same-origin");
res.setHeader("Cross-Origin-Embedder-Policy", "require-corp");
try {
const url = new URL(req.url, `http://${req.headers.host}`);
const pathname = url.pathname;
const filePath = pathname === "/" ? "index.html" : pathname;
const fullPath = join(root, filePath);
const data = await readFile(fullPath);
const ext = extname(fullPath).toLowerCase();
const contentType = mimeTypes[ext] || "application/octet-stream";
res.writeHead(200, { "Content-Type": contentType });
res.end(data);
} catch (err) {
res.writeHead(404, { "Content-Type": "text/plain" });
res.end("Not found");
}
});
server.listen(port, "0.0.0.0", () => console.log(`Serving on http://localhost:${port}`));

View File

@@ -0,0 +1,11 @@
{
"headers": [
{
"source": "/(.*)",
"headers": [
{ "key": "Cross-Origin-Opener-Policy", "value": "same-origin" },
{ "key": "Cross-Origin-Embedder-Policy", "value": "require-corp" }
]
}
]
}

View File

@@ -0,0 +1,10 @@
import { defineConfig } from 'vite'
export default defineConfig({
server: {
headers: {
'Cross-Origin-Opener-Policy': 'same-origin',
'Cross-Origin-Embedder-Policy': 'require-corp',
}
}
})

View File

@@ -0,0 +1,30 @@
# sync-node
This is a minimal example showing how to use [`@tursodatabase/sync`](https://www.npmjs.com/package/@tursodatabase/database) in the node.js
The `@tursodatabase/sync` package extends a regular database with **bidirectional synchronization** between a local file and a remote [Turso Cloud](https://turso.tech/) database.
It allows you to:
* **`pull()`**: fetch and apply remote changes into your local database.
This ensures your local state reflects the latest server-side updates.
* **`push()`**: upload local changes back to the remote database.
This is useful when youve made inserts/updates locally and want to replicate them to the cloud.
Together, these methods make it possible to work **offline-first** (mutating the local database) and later sync your changes to Turso Cloud, while also bringing in any updates from other clients.
---
## Usage
```bash
npm install
TURSO_AUTH_TOKEN=$(turso db tokens create <db-name>) # create auth token for the database in the Turso Cloud
TURSO_DATABASE_URL=$(turso db show <db-name> --url) # fetch URL for the database in the Turso Cloud
node index.mjs
```
Heres a version of your README with a short high-level explanation of what the **sync package** does, and what `pull`/`push` mean in practice:

View File

@@ -0,0 +1,40 @@
import { connect } from "@tursodatabase/sync";
const db = await connect({
path: "local.db", // local path to store database
authToken: process.env.TURSO_AUTH_TOKEN, // Turso Cloud auth token
url: process.env.TURSO_DATABASE_URL, // Turso Cloud database url
longPollTimeoutMs: 0, // optional long-polling interval for pull operation; useful in case when pull called in a loop
});
// execute multiple SQL statements with exec(...)
await db.exec(`
CREATE TABLE IF NOT EXISTS guestbook (comment TEXT, created_at DEFAULT (unixepoch()));
CREATE INDEX IF NOT EXISTS guestbook_idx ON guestbook (created_at);
`);
// use prepared statements and bind args to placeholders later
const select1 = db.prepare(`SELECT * FROM guestbook ORDER BY created_at DESC LIMIT ?`);
// use all(...) or get(...) methods to get all or one row from the query
console.info(await select1.all([5]))
try {
// pull new changes from the remote
await db.pull();
} catch (e) {
console.error('pull failed', e);
}
const insert = db.prepare(`INSERT INTO guestbook(comment) VALUES (?)`);
// use run(...) method if query only need to be executed till completion
await insert.run([`hello, turso at ${Math.floor(Date.now() / 1000)}`]);
const select2 = db.prepare(`SELECT * FROM guestbook ORDER BY created_at DESC LIMIT ?`);
console.info(await select2.all([5]))
try {
// push local changes to the remote
await db.push();
} catch (e) {
console.error('pull failed', e);
}

View File

@@ -0,0 +1,16 @@
{
"name": "sync-node",
"version": "1.0.0",
"main": "index.mjs",
"author": "",
"license": "ISC",
"description": "",
"scripts": {
"tsc-build": "echo 'no tsc-build'",
"build": "echo 'no build'",
"test": "echo 'no tests'"
},
"dependencies": {
"@tursodatabase/sync": "^0.2.0"
}
}

View File

@@ -0,0 +1 @@
.vercel

View File

@@ -0,0 +1,84 @@
# sync-wasm-vite
This is a minimal example showing how to use [`@tursodatabase/sync-wasm`](https://www.npmjs.com/package/@tursodatabase/sync-wasm) in the browser with [Vite](https://vite.dev/).
The `@tursodatabase/sync-wasm` package extends a regular database with **bidirectional synchronization** between a local file and a remote [Turso Cloud](https://turso.tech/) database.
It allows you to:
* **`pull()`**: fetch and apply remote changes into your local database.
This ensures your local state reflects the latest server-side updates.
* **`push()`**: upload local changes back to the remote database.
This is useful when youve made inserts/updates locally and want to replicate them to the cloud.
Together, these methods make it possible to work **offline-first** (mutating the local database) and later sync your changes to Turso Cloud, while also bringing in any updates from other clients.
---
## Usage
```bash
npm install
export VITE_TURSO_AUTH_TOKEN=$(turso db tokens create <db-name>) # create auth token for the database in the Turso Cloud
export VITE_TURSO_DATABASE_URL=$(turso db show <db-name> --url) # fetch URL for the database in the Turso Cloud
npm run dev
# or build assets and serve them with simple node.js server
npm run build
npm run serve
```
> **⚠️ Warning:** When using `VITE_TURSO_AUTH_TOKEN` in the browser, **this token will be bundled into your client-side code**.
That means it is **publicly visible to anyone** who loads your site.
> - Do **not** treat this token as a secret.
> - Only use it with databases or roles that are safe to expose (e.g., read-only, demo instances).
---
## Important: COOP / COEP Headers
Because `@tursodatabase/database-wasm` relies on **SharedArrayBuffer**, you need Cross-Origin headers in development and production:
### Vite dev server config (`vite.config.js`)
```js
import { defineConfig } from 'vite'
export default defineConfig({
server: {
headers: {
'Cross-Origin-Opener-Policy': 'same-origin',
'Cross-Origin-Embedder-Policy': 'require-corp',
}
}
})
```
### Static production server (`server.mjs`)
When serving the `dist/` build, also make sure your server sets these headers:
```js
res.setHeader("Cross-Origin-Opener-Policy", "same-origin");
res.setHeader("Cross-Origin-Embedder-Policy", "require-corp");
```
### Vercel deployment
If you deploy to [**Vercel**](https://vercel.com/), add a `vercel.json` file to ensure COOP / COEP headers are set:
```json
{
"headers": [
{
"source": "/(.*)",
"headers": [
{ "key": "Cross-Origin-Opener-Policy", "value": "same-origin" },
{ "key": "Cross-Origin-Embedder-Policy", "value": "require-corp" }
]
}
]
}
```

View File

@@ -0,0 +1,128 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>Guestbook</title>
<style>
body {
font-family: sans-serif;
max-width: 600px;
margin: 2rem auto;
}
#comments {
border: 1px solid #ddd;
border-radius: 6px;
padding: 0;
list-style: none;
}
#comments li {
padding: 8px;
border-top: 1px solid #eee;
}
#comments li:first-child {
border-top: none;
}
.time {
font-size: 0.8em;
color: gray;
}
</style>
</head>
<body>
<h1>Guestbook</h1>
<form id="form">
<input id="comment" placeholder="Write a comment..." style="width:70%; padding:6px;" />
<button type="submit">Add</button>
</form>
<ul id="comments"></ul>
<script type="module">
import { connect } from "@tursodatabase/sync-wasm/vite";
console.info(import.meta.env.VITE_TURSO_AUTH_TOKEN);
console.info(import.meta.env.VITE_TURSO_DATABASE_URL);
let db = await connect({
path: "sync-guestbook.db", // local path to store database
authToken: import.meta.env.VITE_TURSO_AUTH_TOKEN, // Turso Cloud auth token, WARNING: Bundled into browser code, so it is NOT secret. Use carefully.
url: import.meta.env.VITE_TURSO_DATABASE_URL, // Turso Cloud database url
longPollTimeoutMs: 5000, // optional long-polling interval for pull operation; useful in case when pull called in a loop
});
// execute multiple SQL statements with exec(...)
await db.exec(`
CREATE TABLE IF NOT EXISTS guestbook ( comment TEXT, created_at DEFAULT (unixepoch()) );
CREATE INDEX IF NOT EXISTS guestbook_idx ON guestbook (created_at);
`);
await refresh();
async function pull() {
try {
// pull new data from remote
await db.pull();
await refresh();
} catch (e) {
console.error('pull error', e);
} finally {
setTimeout(pull, 0);
}
}
async function push() {
try {
// if there is something new for push
if ((await db.stats()).operations > 0) {
// push new data to remote
await db.push();
}
} catch (e) {
console.error('push error', e);
} finally {
setTimeout(push, 10);
}
}
pull();
push();
async function addComment() {
// use prepared statements and bind args to placeholders later
const insert = db.prepare(`INSERT INTO guestbook(comment) VALUES (?)`);
const input = document.getElementById("comment");
const text = input.value.trim();
input.value = "";
// use run(...) method if query only need to be executed till completion
await insert.run([text]);
await refresh();
}
document.getElementById("form").addEventListener("submit", (e) => {
e.preventDefault();
addComment();
});
async function refresh() {
const select = db.prepare(`SELECT comment, created_at FROM guestbook ORDER BY created_at DESC LIMIT ?`);
// use all(...) or get(...) methods to get all or one row from the query
const rows = await select.all([5]);
const ul = document.getElementById("comments");
ul.innerHTML = "";
rows.forEach((row) => {
const li = document.createElement("li");
li.innerHTML = `
<div>${row.comment}</div>
<div class="time">${new Date(row.created_at * 1000).toLocaleString()}</div>
`;
ul.appendChild(li);
});
}
</script>
</body>
</html>

File diff suppressed because it is too large Load Diff

View File

@@ -1,19 +1,21 @@
{
"name": "wasm",
"name": "sync-wasm-vite",
"version": "1.0.0",
"main": "index.js",
"scripts": {
"dev": "vite",
"build": "vite build",
"preview": "vite preview"
"serve": "node server.mjs",
"tsc-build": "echo 'no tsc-build'",
"test": "echo 'no tests'"
},
"author": "",
"license": "ISC",
"description": "",
"devDependencies": {
"vite": "^7.1.4"
"vite": "^7.1.9"
},
"dependencies": {
"@tursodatabase/database-wasm": "../../browser"
"@tursodatabase/sync-wasm": "^0.2.0"
}
}

View File

@@ -0,0 +1,34 @@
import http from "http";
import { readFile } from "fs/promises";
import { extname, join } from "path";
import { fileURLToPath } from "url";
const root = fileURLToPath(new URL("./dist", import.meta.url));
const port = 8080;
const mimeTypes = { ".html": "text/html", ".js": "application/javascript" };
const server = http.createServer(async (req, res) => {
// COOP / COEP headers necessary for shared WASM memory
res.setHeader("Cross-Origin-Opener-Policy", "same-origin");
res.setHeader("Cross-Origin-Embedder-Policy", "require-corp");
try {
const url = new URL(req.url, `http://${req.headers.host}`);
const pathname = url.pathname;
const filePath = pathname === "/" ? "index.html" : pathname;
const fullPath = join(root, filePath);
const data = await readFile(fullPath);
const ext = extname(fullPath).toLowerCase();
const contentType = mimeTypes[ext] || "application/octet-stream";
res.writeHead(200, { "Content-Type": contentType });
res.end(data);
} catch (err) {
res.writeHead(404, { "Content-Type": "text/plain" });
res.end("Not found");
}
});
server.listen(port, "0.0.0.0", () => console.log(`Serving on http://localhost:${port}`));

View File

@@ -0,0 +1,11 @@
{
"headers": [
{
"source": "/(.*)",
"headers": [
{ "key": "Cross-Origin-Opener-Policy", "value": "same-origin" },
{ "key": "Cross-Origin-Embedder-Policy", "value": "require-corp" }
]
}
]
}

View File

@@ -0,0 +1,10 @@
import { defineConfig } from 'vite'
export default defineConfig({
server: {
headers: {
'Cross-Origin-Opener-Policy': 'same-origin',
'Cross-Origin-Embedder-Policy': 'require-corp',
}
}
})

View File

@@ -1,34 +0,0 @@
<html>
<head>
<meta content="text/html;charset=utf-8" http-equiv="Content-Type"/>
</head>
<body>
<button id="run">Run</button>
<script type="module">
import { Database, opfsSetup } from "@tursodatabase/database";
var opfs = await opfsSetup("local.db");
console.info(opfs);
async function consume() {
console.info('take', opfs.take());
setTimeout(consume, 1000);
}
consume();
async function tick() {
console.info('tick');
setTimeout(tick, 1000);
}
tick();
async function run() {
const db = new Database(opfs);
console.info('inited');
await new Promise(resolve => setTimeout(resolve, 5000));
await db.exec("CREATE TABLE IF NOT EXISTS t(x)");
console.info('created');
await db.exec("INSERT INTO t VALUES (1)");
console.info('inserted');
}
document.getElementById("run").onclick = run;
</script>
</body>
</html>

View File

@@ -1,26 +0,0 @@
import { defineConfig, searchForWorkspaceRoot } from 'vite'
export default defineConfig({
build: {
minify: false, // Set this to false to disable minification
},
resolve: {
alias: {
'@tursodatabase/database-wasm32-wasi': '../../turso.wasi-wasm.js'
},
},
server: {
fs: {
allow: ['.']
},
headers: {
'Cross-Origin-Opener-Policy': 'same-origin',
'Cross-Origin-Embedder-Policy': 'require-corp',
}
},
optimizeDeps: {
exclude: [
"@tursodatabase/database-wasm32-wasi",
]
},
})

View File

@@ -1,272 +0,0 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Brutal DB Viewer</title>
<style>
:root {
--fg: #000;
--bg: #fff;
}
* {
box-sizing: border-box;
}
html,
body {
margin: 0 10%;
padding: 0;
background: var(--bg);
color: var(--fg);
font: 14px/1.4 ui-monospace, SFMono-Regular, Menlo, Consolas, "Liberation Mono", monospace;
}
header {
border-bottom: 2px solid #000;
padding: 12px 16px;
font-weight: 700;
letter-spacing: .03em;
text-transform: uppercase;
}
main {
padding: 16px;
display: grid;
gap: 12px;
}
label {
display: block;
margin-bottom: 6px;
}
textarea {
width: 100%;
min-height: 128px;
max-height: 60vh;
resize: vertical;
border: 1px solid #000;
padding: 8px;
background: #fff;
color: #000;
}
.controls {
display: flex;
align-items: center;
gap: 8px;
margin-top: 8px;
}
button {
appearance: none;
background: #fff;
color: #000;
border: 1px solid #000;
padding: 6px 10px;
cursor: pointer;
font: inherit;
}
button:hover {
transform: translate(-1px, -1px);
box-shadow: 2px 2px 0 #000;
}
button:active {
transform: translate(0, 0);
box-shadow: none;
}
.status {
margin-left: auto;
opacity: .9;
}
#result {
border-top: 2px solid #000;
padding-top: 12px;
}
.meta {
margin-bottom: 8px;
}
.error {
border: 1px solid #000;
padding: 8px;
margin-bottom: 8px;
white-space: pre-wrap;
}
.table-wrap {
overflow: auto;
border: 1px solid #000;
max-height: 65vh;
}
table {
width: 100%;
border-collapse: collapse;
}
thead th {
position: sticky;
top: 0;
background: #fff;
}
th,
td {
border: 1px solid #000;
padding: 6px 8px;
vertical-align: top;
white-space: pre;
}
.sr-only {
position: absolute;
width: 1px;
height: 1px;
padding: 0;
margin: -1px;
overflow: hidden;
clip: rect(0, 0, 0, 0);
border: 0;
}
</style>
</head>
<body>
<header>DB Viewer</header>
<main>
<section>
<label for="sql">Query</label>
<textarea id="sql" spellcheck="false" placeholder="SELECT * FROM people;">SELECT 'hello, world';</textarea>
<div class="controls">
<button id="run" type="button" title="Run (Ctrl/⌘ + Enter)">Run</button>
<div class="status" id="status">Ready</div>
</div>
<div class="sr-only" aria-live="polite" id="live"></div>
</section>
<section id="result">
<div class="meta" id="meta">No results yet.</div>
<div id="error" class="error" hidden></div>
<div class="table-wrap">
<table id="table" role="table" aria-label="Query results">
<thead></thead>
<tbody></tbody>
</table>
</div>
</section>
</main>
<script type="module">
import { connect } from "@tursodatabase/database-wasm";
const db = await connect('data.db');
// --- Wire your DB here --------------------------------------------------
// Provide window.executeQuery = async (sql) => ({ columns: string[], rows: any[][] })
// If not provided, a tiny mock dataset is used for demo purposes.
(function () {
const $ = (sel) => document.querySelector(sel);
const sqlEl = $('#sql');
const runBtn = $('#run');
const statusEl = $('#status');
const liveEl = $('#live');
const metaEl = $('#meta');
const errEl = $('#error');
const thead = $('#table thead');
const tbody = $('#table tbody');
function fmt(v) {
if (v === null || v === undefined) return 'NULL';
if (typeof v === 'object') {
try { return JSON.stringify(v); } catch { return String(v); }
}
return String(v);
}
function clearTable() { thead.innerHTML = ''; tbody.innerHTML = ''; }
function renderTable(result) {
clearTable();
const { columns = [], rows = [] } = result || {};
// Header
const trh = document.createElement('tr');
for (const name of columns) {
const th = document.createElement('th');
th.textContent = String(name);
trh.appendChild(th);
}
thead.appendChild(trh);
// Body
const frag = document.createDocumentFragment();
for (const r of rows) {
const tr = document.createElement('tr');
for (let i = 0; i < columns.length; i++) {
const td = document.createElement('td');
td.textContent = fmt(r[i] ?? null);
tr.appendChild(td);
}
frag.appendChild(tr);
}
tbody.appendChild(frag);
metaEl.textContent = rows.length
? `${rows.length} row${rows.length === 1 ? '' : 's'} × ${columns.length} column${columns.length === 1 ? '' : 's'}`
: 'No rows.';
}
async function run(sql) {
// errEl.hidden = true; errEl.textContent = '';
// statusEl.textContent = 'Running…';
let t0 = performance.now();
try {
for (let i = 0; i < 1; i++) {
await db.pingSync();
}
const res = {};
// const stmt = await scheduler.postTask(async () => await db.prepare(sql), { priority: 'user-blocking' });
// const columns = await scheduler.postTask(async () => (await stmt.columns()).map(x => x.name), { priority: 'user-blocking' });
// const rows = await scheduler.postTask(async () => await stmt.all(), { priority: 'user-blocking' });
// const res = {
// columns: columns,
// rows: rows.map(r => columns.map(c => r[c]))
// };
const t1 = performance.now();
renderTable(res);
const took = Math.max(0, t1 - t0);
statusEl.textContent = `OK (${took}ms)`;
liveEl.textContent = `Query finished in ${took} milliseconds.`;
} catch (e) {
clearTable();
statusEl.textContent = 'ERROR';
const msg = (e && (e.message || e.toString())) || 'Unknown error';
errEl.textContent = 'ERROR: ' + msg;
errEl.hidden = false;
liveEl.textContent = 'Query failed.';
}
}
runBtn.addEventListener('click', () => run(sqlEl.value));
sqlEl.addEventListener('keydown', (e) => {
if ((e.ctrlKey || e.metaKey) && e.key === 'Enter') {
e.preventDefault();
run(sqlEl.value);
}
});
// Initial demo run
run(sqlEl.value);
})();
</script>
</body>
</html>

View File

@@ -1,335 +0,0 @@
{
"name": "wasm",
"version": "1.0.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "wasm",
"version": "1.0.0",
"license": "ISC",
"dependencies": {
"@tursodatabase/database-wasm": "../../packages/browser"
},
"devDependencies": {
"vite": "^7.1.4"
}
},
"../../packages/browser": {
"name": "@tursodatabase/database-wasm",
"version": "0.1.5",
"license": "MIT",
"dependencies": {
"@napi-rs/wasm-runtime": "^1.0.3",
"@tursodatabase/database-wasm-common": "^0.1.5",
"@tursodatabase/database-common": "^0.1.5"
},
"devDependencies": {
"@napi-rs/cli": "^3.1.5",
"@vitest/browser": "^3.2.4",
"playwright": "^1.55.0",
"typescript": "^5.9.2",
"vitest": "^3.2.4"
}
},
"node_modules/@esbuild/linux-arm64": {
"version": "0.25.9",
"cpu": [
"arm64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@rollup/rollup-linux-arm64-gnu": {
"version": "4.50.0",
"cpu": [
"arm64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"linux"
]
},
"node_modules/@rollup/rollup-linux-arm64-musl": {
"version": "4.50.0",
"cpu": [
"arm64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"linux"
]
},
"node_modules/@tursodatabase/database-wasm": {
"resolved": "../../packages/browser",
"link": true
},
"node_modules/@types/estree": {
"version": "1.0.8",
"dev": true,
"license": "MIT"
},
"node_modules/esbuild": {
"version": "0.25.9",
"dev": true,
"hasInstallScript": true,
"license": "MIT",
"bin": {
"esbuild": "bin/esbuild"
},
"engines": {
"node": ">=18"
},
"optionalDependencies": {
"@esbuild/aix-ppc64": "0.25.9",
"@esbuild/android-arm": "0.25.9",
"@esbuild/android-arm64": "0.25.9",
"@esbuild/android-x64": "0.25.9",
"@esbuild/darwin-arm64": "0.25.9",
"@esbuild/darwin-x64": "0.25.9",
"@esbuild/freebsd-arm64": "0.25.9",
"@esbuild/freebsd-x64": "0.25.9",
"@esbuild/linux-arm": "0.25.9",
"@esbuild/linux-arm64": "0.25.9",
"@esbuild/linux-ia32": "0.25.9",
"@esbuild/linux-loong64": "0.25.9",
"@esbuild/linux-mips64el": "0.25.9",
"@esbuild/linux-ppc64": "0.25.9",
"@esbuild/linux-riscv64": "0.25.9",
"@esbuild/linux-s390x": "0.25.9",
"@esbuild/linux-x64": "0.25.9",
"@esbuild/netbsd-arm64": "0.25.9",
"@esbuild/netbsd-x64": "0.25.9",
"@esbuild/openbsd-arm64": "0.25.9",
"@esbuild/openbsd-x64": "0.25.9",
"@esbuild/openharmony-arm64": "0.25.9",
"@esbuild/sunos-x64": "0.25.9",
"@esbuild/win32-arm64": "0.25.9",
"@esbuild/win32-ia32": "0.25.9",
"@esbuild/win32-x64": "0.25.9"
}
},
"node_modules/fdir": {
"version": "6.5.0",
"dev": true,
"license": "MIT",
"engines": {
"node": ">=12.0.0"
},
"peerDependencies": {
"picomatch": "^3 || ^4"
},
"peerDependenciesMeta": {
"picomatch": {
"optional": true
}
}
},
"node_modules/nanoid": {
"version": "3.3.11",
"dev": true,
"funding": [
{
"type": "github",
"url": "https://github.com/sponsors/ai"
}
],
"license": "MIT",
"bin": {
"nanoid": "bin/nanoid.cjs"
},
"engines": {
"node": "^10 || ^12 || ^13.7 || ^14 || >=15.0.1"
}
},
"node_modules/picocolors": {
"version": "1.1.1",
"dev": true,
"license": "ISC"
},
"node_modules/picomatch": {
"version": "4.0.3",
"dev": true,
"license": "MIT",
"engines": {
"node": ">=12"
},
"funding": {
"url": "https://github.com/sponsors/jonschlinkert"
}
},
"node_modules/postcss": {
"version": "8.5.6",
"dev": true,
"funding": [
{
"type": "opencollective",
"url": "https://opencollective.com/postcss/"
},
{
"type": "tidelift",
"url": "https://tidelift.com/funding/github/npm/postcss"
},
{
"type": "github",
"url": "https://github.com/sponsors/ai"
}
],
"license": "MIT",
"dependencies": {
"nanoid": "^3.3.11",
"picocolors": "^1.1.1",
"source-map-js": "^1.2.1"
},
"engines": {
"node": "^10 || ^12 || >=14"
}
},
"node_modules/rollup": {
"version": "4.50.0",
"dev": true,
"license": "MIT",
"dependencies": {
"@types/estree": "1.0.8"
},
"bin": {
"rollup": "dist/bin/rollup"
},
"engines": {
"node": ">=18.0.0",
"npm": ">=8.0.0"
},
"optionalDependencies": {
"@rollup/rollup-android-arm-eabi": "4.50.0",
"@rollup/rollup-android-arm64": "4.50.0",
"@rollup/rollup-darwin-arm64": "4.50.0",
"@rollup/rollup-darwin-x64": "4.50.0",
"@rollup/rollup-freebsd-arm64": "4.50.0",
"@rollup/rollup-freebsd-x64": "4.50.0",
"@rollup/rollup-linux-arm-gnueabihf": "4.50.0",
"@rollup/rollup-linux-arm-musleabihf": "4.50.0",
"@rollup/rollup-linux-arm64-gnu": "4.50.0",
"@rollup/rollup-linux-arm64-musl": "4.50.0",
"@rollup/rollup-linux-loongarch64-gnu": "4.50.0",
"@rollup/rollup-linux-ppc64-gnu": "4.50.0",
"@rollup/rollup-linux-riscv64-gnu": "4.50.0",
"@rollup/rollup-linux-riscv64-musl": "4.50.0",
"@rollup/rollup-linux-s390x-gnu": "4.50.0",
"@rollup/rollup-linux-x64-gnu": "4.50.0",
"@rollup/rollup-linux-x64-musl": "4.50.0",
"@rollup/rollup-openharmony-arm64": "4.50.0",
"@rollup/rollup-win32-arm64-msvc": "4.50.0",
"@rollup/rollup-win32-ia32-msvc": "4.50.0",
"@rollup/rollup-win32-x64-msvc": "4.50.0",
"fsevents": "~2.3.2"
}
},
"node_modules/source-map-js": {
"version": "1.2.1",
"dev": true,
"license": "BSD-3-Clause",
"engines": {
"node": ">=0.10.0"
}
},
"node_modules/tinyglobby": {
"version": "0.2.14",
"dev": true,
"license": "MIT",
"dependencies": {
"fdir": "^6.4.4",
"picomatch": "^4.0.2"
},
"engines": {
"node": ">=12.0.0"
},
"funding": {
"url": "https://github.com/sponsors/SuperchupuDev"
}
},
"node_modules/vite": {
"version": "7.1.4",
"dev": true,
"license": "MIT",
"dependencies": {
"esbuild": "^0.25.0",
"fdir": "^6.5.0",
"picomatch": "^4.0.3",
"postcss": "^8.5.6",
"rollup": "^4.43.0",
"tinyglobby": "^0.2.14"
},
"bin": {
"vite": "bin/vite.js"
},
"engines": {
"node": "^20.19.0 || >=22.12.0"
},
"funding": {
"url": "https://github.com/vitejs/vite?sponsor=1"
},
"optionalDependencies": {
"fsevents": "~2.3.3"
},
"peerDependencies": {
"@types/node": "^20.19.0 || >=22.12.0",
"jiti": ">=1.21.0",
"less": "^4.0.0",
"lightningcss": "^1.21.0",
"sass": "^1.70.0",
"sass-embedded": "^1.70.0",
"stylus": ">=0.54.8",
"sugarss": "^5.0.0",
"terser": "^5.16.0",
"tsx": "^4.8.1",
"yaml": "^2.4.2"
},
"peerDependenciesMeta": {
"@types/node": {
"optional": true
},
"jiti": {
"optional": true
},
"less": {
"optional": true
},
"lightningcss": {
"optional": true
},
"sass": {
"optional": true
},
"sass-embedded": {
"optional": true
},
"stylus": {
"optional": true
},
"sugarss": {
"optional": true
},
"terser": {
"optional": true
},
"tsx": {
"optional": true
},
"yaml": {
"optional": true
}
}
}
}
}

View File

@@ -1,22 +0,0 @@
import { defineConfig, searchForWorkspaceRoot } from 'vite'
export default defineConfig({
server: {
fs: {
allow: ['.', '../../']
},
define:
{
'process.env.NODE_DEBUG_NATIVE': 'false', // string replace at build-time
},
headers: {
'Cross-Origin-Opener-Policy': 'same-origin',
'Cross-Origin-Embedder-Policy': 'require-corp',
}
},
optimizeDeps: {
esbuildOptions: {
define: { 'process.env.NODE_DEBUG_NATIVE': 'false' },
},
},
})

View File

@@ -13,9 +13,47 @@
"packages/wasm",
"sync/packages/common",
"sync/packages/native",
"sync/packages/wasm"
"sync/packages/wasm",
"examples/database-node",
"examples/database-wasm-vite",
"examples/sync-node",
"examples/sync-wasm-vite"
]
},
"examples/database-node": {
"version": "1.0.0",
"license": "ISC",
"dependencies": {
"@tursodatabase/database": "^0.2.0"
}
},
"examples/database-wasm-vite": {
"version": "1.0.0",
"license": "ISC",
"dependencies": {
"@tursodatabase/database-wasm": "^0.2.0"
},
"devDependencies": {
"vite": "^7.1.9"
}
},
"examples/sync-node": {
"version": "1.0.0",
"license": "ISC",
"dependencies": {
"@tursodatabase/sync": "^0.2.0"
}
},
"examples/sync-wasm-vite": {
"version": "1.0.0",
"license": "ISC",
"dependencies": {
"@tursodatabase/sync-wasm": "^0.2.0"
},
"devDependencies": {
"vite": "^7.1.9"
}
},
"node_modules/@babel/code-frame": {
"version": "7.27.1",
"resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-7.27.1.tgz",
@@ -1656,6 +1694,14 @@
"node": ">= 12"
}
},
"node_modules/database-node": {
"resolved": "examples/database-node",
"link": true
},
"node_modules/database-wasm-vite": {
"resolved": "examples/database-wasm-vite",
"link": true
},
"node_modules/debug": {
"version": "4.4.1",
"resolved": "https://registry.npmjs.org/debug/-/debug-4.4.1.tgz",
@@ -3048,6 +3094,14 @@
"url": "https://github.com/sponsors/antfu"
}
},
"node_modules/sync-node": {
"resolved": "examples/sync-node",
"link": true
},
"node_modules/sync-wasm-vite": {
"resolved": "examples/sync-wasm-vite",
"link": true
},
"node_modules/tar-fs": {
"version": "2.1.4",
"resolved": "https://registry.npmjs.org/tar-fs/-/tar-fs-2.1.4.tgz",
@@ -3248,9 +3302,9 @@
"license": "MIT"
},
"node_modules/vite": {
"version": "7.1.5",
"resolved": "https://registry.npmjs.org/vite/-/vite-7.1.5.tgz",
"integrity": "sha512-4cKBO9wR75r0BeIWWWId9XK9Lj6La5X846Zw9dFfzMRw38IlTk2iCcUt6hsyiDRcPidc55ZParFYDXi0nXOeLQ==",
"version": "7.1.9",
"resolved": "https://registry.npmjs.org/vite/-/vite-7.1.9.tgz",
"integrity": "sha512-4nVGliEpxmhCL8DslSAUdxlB6+SMrhB0a1v5ijlh1xB1nEPuy1mxaHxysVucLHuWryAxLWg6a5ei+U4TLn/rFg==",
"dev": true,
"license": "MIT",
"dependencies": {

View File

@@ -12,7 +12,11 @@
"packages/wasm",
"sync/packages/common",
"sync/packages/native",
"sync/packages/wasm"
"sync/packages/wasm",
"examples/database-node",
"examples/database-wasm-vite",
"examples/sync-node",
"examples/sync-wasm-vite"
],
"version": "0.2.0"
}

View File

@@ -18,6 +18,10 @@ function timeoutMs(ms: number): Promise<void> {
return new Promise(resolve => setTimeout(resolve, ms))
}
function normalizeUrl(url: string): string {
return url.replace(/^libsql:\/\//, 'https://');
}
async function process(opts: RunOpts, io: ProtocolIo, request: any) {
const requestType = request.request();
const completion = request.completion();
@@ -32,6 +36,7 @@ async function process(opts: RunOpts, io: ProtocolIo, request: any) {
completion.poison(`url is empty - sync is paused`);
return;
}
url = normalizeUrl(url);
try {
let headers = typeof opts.headers === "function" ? await opts.headers() : opts.headers;
if (requestType.headers != null && requestType.headers.length > 0) {

View File

@@ -1593,7 +1593,7 @@ __metadata:
languageName: unknown
linkType: soft
"@tursodatabase/database-wasm@workspace:packages/wasm":
"@tursodatabase/database-wasm@npm:^0.2.0, @tursodatabase/database-wasm@workspace:packages/wasm":
version: 0.0.0-use.local
resolution: "@tursodatabase/database-wasm@workspace:packages/wasm"
dependencies:
@@ -1608,7 +1608,7 @@ __metadata:
languageName: unknown
linkType: soft
"@tursodatabase/database@workspace:packages/native":
"@tursodatabase/database@npm:^0.2.0, @tursodatabase/database@workspace:packages/native":
version: 0.0.0-use.local
resolution: "@tursodatabase/database@workspace:packages/native"
dependencies:
@@ -1632,7 +1632,7 @@ __metadata:
languageName: unknown
linkType: soft
"@tursodatabase/sync-wasm@workspace:sync/packages/wasm":
"@tursodatabase/sync-wasm@npm:^0.2.0, @tursodatabase/sync-wasm@workspace:sync/packages/wasm":
version: 0.0.0-use.local
resolution: "@tursodatabase/sync-wasm@workspace:sync/packages/wasm"
dependencies:
@@ -1648,7 +1648,7 @@ __metadata:
languageName: unknown
linkType: soft
"@tursodatabase/sync@workspace:sync/packages/native":
"@tursodatabase/sync@npm:^0.2.0, @tursodatabase/sync@workspace:sync/packages/native":
version: 0.0.0-use.local
resolution: "@tursodatabase/sync@workspace:sync/packages/native"
dependencies:
@@ -2100,6 +2100,23 @@ __metadata:
languageName: node
linkType: hard
"database-node@workspace:examples/database-node":
version: 0.0.0-use.local
resolution: "database-node@workspace:examples/database-node"
dependencies:
"@tursodatabase/database": "npm:^0.2.0"
languageName: unknown
linkType: soft
"database-wasm-vite@workspace:examples/database-wasm-vite":
version: 0.0.0-use.local
resolution: "database-wasm-vite@workspace:examples/database-wasm-vite"
dependencies:
"@tursodatabase/database-wasm": "npm:^0.2.0"
vite: "npm:^7.1.9"
languageName: unknown
linkType: soft
"debug@npm:4":
version: 4.4.3
resolution: "debug@npm:4.4.3"
@@ -3655,6 +3672,23 @@ __metadata:
languageName: node
linkType: hard
"sync-node@workspace:examples/sync-node":
version: 0.0.0-use.local
resolution: "sync-node@workspace:examples/sync-node"
dependencies:
"@tursodatabase/sync": "npm:^0.2.0"
languageName: unknown
linkType: soft
"sync-wasm-vite@workspace:examples/sync-wasm-vite":
version: 0.0.0-use.local
resolution: "sync-wasm-vite@workspace:examples/sync-wasm-vite"
dependencies:
"@tursodatabase/sync-wasm": "npm:^0.2.0"
vite: "npm:^7.1.9"
languageName: unknown
linkType: soft
"tar-fs@npm:^2.0.0":
version: 2.1.4
resolution: "tar-fs@npm:2.1.4"
@@ -3865,9 +3899,9 @@ __metadata:
languageName: node
linkType: hard
"vite@npm:^5.0.0 || ^6.0.0 || ^7.0.0-0, vite@npm:^7.1.5":
version: 7.1.5
resolution: "vite@npm:7.1.5"
"vite@npm:^5.0.0 || ^6.0.0 || ^7.0.0-0, vite@npm:^7.1.5, vite@npm:^7.1.9":
version: 7.1.9
resolution: "vite@npm:7.1.9"
dependencies:
esbuild: "npm:^0.25.0"
fdir: "npm:^6.5.0"
@@ -3916,7 +3950,7 @@ __metadata:
optional: true
bin:
vite: bin/vite.js
checksum: 10c0/782d2f20c25541b26d1fb39bef5f194149caff39dc25b7836e25f049ca919f2e2ce186bddb21f3f20f6195354b3579ec637a8ca08d65b117f8b6f81e3e730a9c
checksum: 10c0/f628f903a137c1410232558bde99c223ea00a090bda6af77752c61f912955f0050aac12d3cfe024d08a0f150ff6fab61b3d0be75d634a59b94d49f525392e1f7
languageName: node
linkType: hard