Public: anyone can read this; the crew can change it.
A tab forge keeps its data in SQLite wasm on OPFS behind one small store module #17303
Merged 39h 34m ago, live in production
scout/forge:scout/17274-a-tab-forge-keeps-its-data-in-sqlite-was → main 0 commits fork 3 threads · 3 unresolved
16 files
changed +339
−5
- NOTICE
- bun.lock
- docs/DEPENDENCIES.md
- package.json
- scripts/gate.ts
- scripts/unreached.ts
- src/http/routes/discovery.ts
- src/web/tabforge/asset.ts
- src/web/tabforge/client.ts
- src/web/tabforge/opfs.ts
- src/web/tabforge/store.ts
- test/deps.test.ts
- test/import-all.test.ts
- test/shards.test.ts
- test/tabforge-asset.test.ts
- test/tabforge-store.test.ts
NOTICE +1
| @@ -8,3 +8,4 @@ This repository also contains third-party files under their own licenses: | ||
| 8 | 8 | - DejaVu fonts, src/web/og/vendor/DejaVu*.ttf: see src/web/og/vendor/DEJAVU-LICENSE. |
| 9 | 9 | - resvg, src/web/og/vendor/resvg.*: Mozilla Public License 2.0, https://github.com/thx/resvg-js and https://github.com/linebender/resvg. |
| 10 | 10 | - ghostty-web 0.4.0, src/web/vendor/ghostty-web/: MIT License, Copyright (c) 2025 Coder, https://github.com/coder/ghostty-web; see src/web/vendor/ghostty-web/LICENSE. |
| 11 | - @sqlite.org/sqlite-wasm 3.54.1 (npm package, not vendored): Apache-2.0, https://sqlite.org/wasm; its wasm is served from node_modules by src/web/tabforge/asset.ts. |
bun.lock +5
| @@ -4,6 +4,9 @@ | ||
| 4 | 4 | "workspaces": { |
| 5 | 5 | "": { |
| 6 | 6 | "name": "forge", |
| 7 | "dependencies": { | |
| 8 | "@sqlite.org/sqlite-wasm": "^3.54.1-build1", | |
| 9 | }, | |
| 7 | 10 | "devDependencies": { |
| 8 | 11 | "@anthropic-ai/sandbox-runtime": "^0.0.79", |
| 9 | 12 | "@types/bun": "^1.4.4", |
| @@ -20,6 +23,8 @@ | ||
| 20 | 23 | |
| 21 | 24 | "@pondwader/socks5-server": ["@pondwader/[email protected]", "", {}, "sha512-bQY06wzzR8D2+vVCUoBsr5QS2U6UgPUQRmErNwtsuI6vLcyRKkafjkr3KxbtGFf9aBBIV2mcvlsKD1UYaIV+sg=="], |
| 22 | 25 | |
| 26 | "@sqlite.org/sqlite-wasm": ["@sqlite.org/[email protected]", "", {}, "sha512-foW427VBLJ3G87bsnvQTZCc9zYe0Fq1wH0pz1I6BlKLKXcArIAyTkHtq0iT2llmhcMQt9T/p6l5PpQQh+6O8uQ=="], | |
| 27 | ||
| 23 | 28 | "@types/bun": ["@types/[email protected]", "", { "dependencies": { "bun-types": "1.4.4" } }, "sha512-9wkRDXUXK124pEnAutE6n/l18j+i9GC5IAHK8TmX/2nlySETmky0OU6yL5U8pW1AoKh++AN9auDCr647BfurjQ=="], |
| 24 | 29 | |
| 25 | 30 | "@types/node": ["@types/[email protected]", "", { "dependencies": { "undici-types": "~8.3.0" } }, "sha512-Vu4a5UFA9rIIFJ7rB/Vaafh9lrCQszopTCx6KjFboXTGQbPNasehVR5TEiithSDGyd1DEiUByggTZsg8jukeIg=="], |
docs/DEPENDENCIES.md +1
| @@ -11,6 +11,7 @@ names the package and the line to add (`src/kernel/dependencies.ts`, #12315). | ||
| 11 | 11 | A line in a `## Dependencies` section of README.md counts as well. |
| 12 | 12 | |
| 13 | 13 | - `@anthropic-ai/sandbox-runtime` — lets `test/crew-sandbox-real.test.ts` run a shell under the very sandbox Claude Code builds from the crew's settings. |
| 14 | - `@sqlite.org/sqlite-wasm` — SQLite as WebAssembly, the tab forge's database on OPFS (`src/web/tabforge`, #17274); a tab has no `bun:sqlite`, and nothing smaller is SQLite. Its 880 KB wasm is one immutable file fetched by the tab forge's worker only, and its glue bundles to about 220 KB, so no other page loads either. | |
| 14 | 15 | - `@types/bun` — the type check's types for Bun's own APIs. |
| 15 | 16 | - `@vscode/ripgrep` — the `rg` that `srt` scans with, pinned and shipped in the package (no install script), so `test/crew-sandbox-escape.test.ts` runs on a check host with no ripgrep of its own. |
| 16 | 17 | - `axe-core` — the release check's accessibility rules (`src/release/axe.ts`); they need a rendered page, and there is no zero-dependency equivalent. |
package.json +4 −1
scripts/gate.ts +1
| @@ -68,6 +68,7 @@ export const SLOW: readonly Exclusion[] = [ | ||
| 68 | 68 | // A fresh module graph is what it tests: no process or fixture can be shared, and no clock is |
| 69 | 69 | // waited on (#17007). |
| 70 | 70 | { file: "test/load-order.test.ts", reason: "loads src/ first in 13 fresh processes at once; one parses 4,286 files (24 MB) in 2.4 s alone, 2.46 s under full-suite load", issue: 17007 }, |
| 71 | { file: "test/import-all.test.ts", reason: "imports every src module in one process, the point of the test; 2.5 s on main before the tab forge, 2.3 s after, 2.2 s of it parsing the tree", issue: 17274 }, | |
| 71 | 72 | { file: "test/game-diag.test.ts", reason: "runs the real game agent against a stand-in forge through three syncs while a fake compose up sleeps; about 2 s a test", issue: 16840 }, |
| 72 | 73 | { file: "test/spawn-cell-looks.test.ts", reason: "boots a real child forge in a cell (~30 s) and waits for its own looks job to take a picture", issue: 10620 }, |
| 73 | 74 | { file: "test/snapshot-stream.test.ts", reason: "its service test takes a real stream pass and a real snapshot of a forge with a database, about 1 s each; 3.1 s a test under full-suite load", issue: 16977 }, |
scripts/unreached.ts +3
| @@ -36,6 +36,9 @@ export const ENTRIES = [ | ||
| 36 | 36 | "src/web/highlight-client.ts", |
| 37 | 37 | // Bundled for the browser by Bun.build in src/web/render/dxf-asset.ts, named there by path. |
| 38 | 38 | "src/web/render/dxf-client.ts", |
| 39 | // Bundled as a worker for the tab forge by Bun.build in src/web/tabforge/asset.ts, named there by | |
| 40 | // path. | |
| 41 | "src/web/tabforge/client.ts", | |
| 39 | 42 | ]; |
| 40 | 43 | |
| 41 | 44 | /** Loaded by listing the directory, so nothing imports them: the duty roster (#14355). */ |
src/http/routes/discovery.ts +8 −2
| @@ -8,6 +8,7 @@ import { TOOLBAR_NAME, toolbarResponse } from "../../apps/toolbar.ts"; | ||
| 8 | 8 | import { registryItem } from "../../registry/serve.ts"; |
| 9 | 9 | import { stylesheetRedirect, stylesheetAsset, keptAssetNamed, fileResponse, stylesheetResponse, shellAsset, assetResponse, beaconAsset, pageScriptNamed, highlightAsset, spriteAsset, speculationAsset } from "../../web/asset.ts"; |
| 10 | 10 | import { llmsFull } from "../../web/llms_full.ts"; |
| 11 | import { sqliteWasmAsset, sqliteWasmResponse, tabforgeAsset } from "../../web/tabforge/asset.ts"; | |
| 11 | 12 | import { machineTermAsset, ghosttyWasmAsset, wasmResponse } from "../../web/machine-term-asset.ts"; |
| 12 | 13 | import { openSearch } from "../../web/opensearch.ts"; |
| 13 | 14 | import { agentsPage } from "../../web/pages/agents.ts"; |
| @@ -88,7 +89,7 @@ export function discoveryRoutes(router: Router<Handler>): void { | ||
| 88 | 89 | const term = await machineTermAsset(); |
| 89 | 90 | return term !== null && ctx.params.name === term.name ? assetResponse(ctx.request, term) : assetNotFound(); |
| 90 | 91 | } |
| 91 | for (const [prefix, load] of [["model3d-", model3dAsset], ["dxf-", dxfAsset]] as const) { | |
| 92 | for (const [prefix, load] of [["model3d-", model3dAsset], ["dxf-", dxfAsset], ["tabforge-", tabforgeAsset]] as const) { | |
| 92 | 93 | if (!ctx.params.name!.startsWith(prefix)) continue; |
| 93 | 94 | const built = await load(); |
| 94 | 95 | return built === null || ctx.params.name !== built.name ? assetNotFound() : assetResponse(ctx.request, built); |
| @@ -107,8 +108,13 @@ export function discoveryRoutes(router: Router<Handler>): void { | ||
| 107 | 108 | return fileResponse(ctx.request, spriteAsset()); |
| 108 | 109 | }); |
| 109 | 110 | // The machine shell's terminal emulator (`web/machine-term-asset.ts`). |
| 111 | // and SQLite's, for the tab forge's worker (`web/tabforge/asset.ts`). | |
| 110 | 112 | router.add("GET", "/assets/:name.wasm", (ctx) => |
| 111 | ctx.params.name === ghosttyWasmAsset().name ? wasmResponse(ctx.request) : assetNotFound(), | |
| 113 | ctx.params.name === ghosttyWasmAsset().name | |
| 114 | ? wasmResponse(ctx.request) | |
| 115 | : ctx.params.name === sqliteWasmAsset().name | |
| 116 | ? sqliteWasmResponse(ctx.request) | |
| 117 | : assetNotFound(), | |
| 112 | 118 | ); |
| 113 | 119 | router.add("GET", "/assets/:name.json", (ctx) => |
| 114 | 120 | ctx.params.name === speculationAsset().name ? fileResponse(ctx.request, speculationAsset()) : assetNotFound(), |
src/web/tabforge/asset.ts added +51
| @@ -0,0 +1,51 @@ | ||
| 1 | /** | |
| 2 | * The tab forge's two files, content-addressed and immutable like the machine | |
| 3 | * shell's (`web/machine-term-asset.ts`), and served only to the page that asks | |
| 4 | * for them — no other page names either, so no other page pays for the wasm: | |
| 5 | * | |
| 6 | * - `/assets/tabforge-<hash>.js` — `client.ts` bundled with the SQLite wasm | |
| 7 | * build's glue, to run as a worker. | |
| 8 | * - `/assets/sqlite3-<hash>.wasm` — SQLite itself, read once from the package. | |
| 9 | * | |
| 10 | * A failed build is not fatal: the asset is null and the route answers 404. | |
| 11 | */ | |
| 12 | ||
| 13 | import { readFileSync } from "node:fs"; | |
| 14 | import { createRequire } from "node:module"; | |
| 15 | import { dirname, join } from "node:path"; | |
| 16 | import { staticResponse, bundleEntry, type BuiltAsset } from "../asset.ts"; | |
| 17 | ||
| 18 | let script: Promise<BuiltAsset | null> | null = null; | |
| 19 | ||
| 20 | /** The worker script, built once per process. */ | |
| 21 | export function tabforgeAsset(): Promise<BuiltAsset | null> { | |
| 22 | script ??= bundleEntry(`${import.meta.dir}/client.ts`, (hash) => `tabforge-${hash.slice(0, 16)}`, "web.tabforge_asset_failed"); | |
| 23 | return script; | |
| 24 | } | |
| 25 | ||
| 26 | export interface WasmAsset { | |
| 27 | readonly path: string; | |
| 28 | readonly name: string; | |
| 29 | readonly bytes: Uint8Array<ArrayBuffer>; | |
| 30 | readonly etag: string; | |
| 31 | } | |
| 32 | ||
| 33 | let wasm: WasmAsset | null = null; | |
| 34 | ||
| 35 | /** SQLite's WebAssembly, read and hashed once per process. */ | |
| 36 | export function sqliteWasmAsset(): WasmAsset { | |
| 37 | if (wasm === null) { | |
| 38 | const dir = dirname(createRequire(import.meta.url).resolve("@sqlite.org/sqlite-wasm/package.json")); | |
| 39 | const bytes = new Uint8Array(readFileSync(join(dir, "dist", "sqlite3.wasm"))); | |
Medium: the header says a failed build is not fatal, but this resolve and readFileSync throw if the package is not installed, and the route calls sqliteWasmAsset() for any unknown .wasm name. That is a 500 where the pattern elsewhere is a 404. Catch it and return null, or let the route handle null, so a missing package answers 404. |
||
| 40 | const hash = new Bun.CryptoHasher("sha256").update(bytes).digest("hex"); | |
| 41 | const name = `sqlite3-${hash.slice(0, 16)}`; | |
| 42 | wasm = { path: `/assets/${name}.wasm`, name, bytes, etag: `"${hash}"` }; | |
| 43 | } | |
| 44 | return wasm; | |
| 45 | } | |
| 46 | ||
| 47 | /** The response for a hit on SQLite's WebAssembly: immutable, because it is. */ | |
| 48 | export function sqliteWasmResponse(request: Request): Response { | |
| 49 | const asset = sqliteWasmAsset(); | |
| 50 | return staticResponse(request, asset.bytes, "application/wasm", asset.etag); | |
| 51 | } |
src/web/tabforge/client.ts added +29
| @@ -0,0 +1,29 @@ | ||
| 1 | /** | |
| 2 | * The tab forge's worker entry, bundled by `asset.ts` and loaded as a worker | |
| 3 | * by the page that is the tab forge, and by no other. It owns the database; | |
| 4 | * the page sends `{id, op, sql, params}` and gets `{id, ok, rows | error}`. | |
| 5 | */ | |
| 6 | ||
| 7 | import { opfsBackend } from "./opfs.ts"; | |
| 8 | import { openStore, type Store, type Value } from "./store.ts"; | |
| 9 | ||
| 10 | declare const self: { | |
| 11 | location: { readonly search: string }; | |
| 12 | onmessage: ((event: { data: unknown }) => void) | null; | |
| 13 | postMessage(message: unknown): void; | |
| 14 | }; | |
| 15 | ||
| 16 | const params = new URLSearchParams(self.location.search); | |
| 17 | const ready = (async (): Promise<Store | string> => { | |
| 18 | const opened = await openStore(await opfsBackend(params.get("wasm") ?? ""), params.get("db") ?? "forge"); | |
| 19 | return opened.ok ? opened.value : opened.error.message; | |
| 20 | })(); | |
| 21 | ||
| 22 | self.onmessage = async (event) => { | |
| 23 | const m = event.data as { id?: unknown; op?: unknown; sql?: unknown; params?: unknown }; | |
| 24 | const store = await ready; | |
| 25 | if (typeof store === "string") return self.postMessage({ id: m.id, ok: false, error: store }); | |
| 26 | if (typeof m.sql !== "string" || (m.op !== "run" && m.op !== "all")) return self.postMessage({ id: m.id, ok: false, error: "bad message" }); | |
| 27 | const result = store[m.op](m.sql, Array.isArray(m.params) ? (m.params as Value[]) : []); | |
| 28 | self.postMessage(result.ok ? { id: m.id, ok: true, rows: m.op === "all" ? result.value : [] } : { id: m.id, ok: false, error: result.error.message }); | |
| 29 | }; |
src/web/tabforge/opfs.ts added +25
| @@ -0,0 +1,25 @@ | ||
| 1 | /** | |
| 2 | * The tab's backend: SQLite as WebAssembly (`@sqlite.org/sqlite-wasm`) on the | |
| 3 | * origin private file system, through its `opfs-sahpool` VFS: no second worker | |
| 4 | * to serve, no cross-origin isolation headers. OPFS's synchronous access | |
| 5 | * handles exist only in a dedicated worker, so `opfsBackend` is called there | |
| 6 | * (`client.ts`). The wasm is fetched from `wasmUrl`, an immutable asset | |
| 7 | * (`asset.ts`), never inlined. | |
| 8 | */ | |
| 9 | ||
| 10 | import sqlite3InitModule from "@sqlite.org/sqlite-wasm"; | |
| 11 | import type { Backend, Row } from "./store.ts"; | |
| 12 | ||
| 13 | export async function opfsBackend(wasmUrl: string): Promise<Backend> { | |
| 14 | const sqlite3 = await (sqlite3InitModule as (options: object) => ReturnType<typeof sqlite3InitModule>)({ locateFile: () => wasmUrl, print: () => {}, printErr: () => {} }); | |
| 15 | const pool = await sqlite3.installOpfsSAHPoolVfs({ name: "tabforge", directory: ".tabforge" }); | |
| 16 | return { | |
| 17 | async open(name) { | |
| 18 | const db = new pool.OpfsSAHPoolDb(`/${name}.sqlite3`); | |
| 19 | return { | |
| 20 | exec: (sql, params) => db.exec({ sql, bind: [...params] as never, rowMode: "object", returnValue: "resultRows" }) as Row[], | |
| 21 | close: () => db.close(), | |
| 22 | }; | |
| 23 | }, | |
| 24 | }; | |
| 25 | } |
src/web/tabforge/store.ts added +83
| @@ -0,0 +1,83 @@ | ||
| 1 | /** | |
| 2 | * The storage half of a forge that lives in a browser tab (#17274): one small | |
| 3 | * store, four plain functions — open, run, all, close — over a backend that is | |
| 4 | * injected. In the tab the backend is SQLite as WebAssembly on OPFS | |
| 5 | * (`opfs.ts`); in a test it is a fake, so no browser is needed. | |
| 6 | * | |
| 7 | * A bad statement is a typed `StoreError` in a `Result`, never a throw into the | |
| 8 | * page. A throw here would mean a defect, and a defect is not what bad SQL is. | |
| 9 | */ | |
| 10 | ||
| 11 | import { err, ok, type Result } from "../../kernel/result.ts"; | |
| 12 | ||
| 13 | export type Value = string | number | null | Uint8Array; | |
| 14 | export type Row = Record<string, Value>; | |
| 15 | ||
| 16 | /** What the store needs of a database: run one statement, give its rows, close. May throw. */ | |
| 17 | export interface Handle { | |
| 18 | exec(sql: string, params: readonly Value[]): Row[]; | |
| 19 | close(): void; | |
| 20 | } | |
| 21 | ||
| 22 | /** Where databases come from: SQLite on OPFS in a tab, a fake in a test. */ | |
| 23 | export interface Backend { | |
| 24 | open(name: string): Promise<Handle>; | |
| 25 | } | |
| 26 | ||
| 27 | export type StoreErrorKind = "open" | "statement" | "closed" | "name"; | |
| 28 | ||
| 29 | export interface StoreError { | |
| 30 | readonly kind: StoreErrorKind; | |
| 31 | readonly message: string; | |
| 32 | } | |
| 33 | ||
| 34 | export interface Store { | |
| 35 | /** Runs a statement for its effect. */ | |
| 36 | run(sql: string, params?: readonly Value[]): Result<void, StoreError>; | |
| 37 | /** Runs a statement and returns its rows. */ | |
| 38 | all(sql: string, params?: readonly Value[]): Result<Row[], StoreError>; | |
| 39 | /** Closes the database; every later call is a `closed` error. Safe to call twice. */ | |
| 40 | close(): void; | |
| 41 | } | |
| 42 | ||
| 43 | /** A database name is a short file name: it becomes an OPFS path, so nothing else gets through. */ | |
| 44 | const NAME = /^[a-z0-9][a-z0-9._-]{0,63}$/; | |
| 45 | ||
| 46 | function failure(kind: StoreErrorKind, cause: unknown): StoreError { | |
| 47 | return { kind, message: cause instanceof Error ? cause.message : String(cause) }; | |
| 48 | } | |
| 49 | ||
| 50 | /** Opens (creating if need be) the database `name` on `backend`. */ | |
| 51 | export async function openStore(backend: Backend, name: string): Promise<Result<Store, StoreError>> { | |
| 52 | if (!NAME.test(name) || name.includes("..")) return err({ kind: "name", message: `not a database name: ${name.slice(0, 64)}` }); | |
| 53 | let handle: Handle | null; | |
| 54 | try { | |
| 55 | handle = await backend.open(name); | |
| 56 | } catch (error) { | |
| 57 | return err(failure("open", error)); | |
| 58 | } | |
| 59 | const exec = (sql: string, params: readonly Value[]): Result<Row[], StoreError> => { | |
| 60 | if (handle === null) return err({ kind: "closed", message: "the store is closed" }); | |
| 61 | try { | |
| 62 | return ok(handle.exec(sql, params)); | |
| 63 | } catch (error) { | |
| 64 | return err(failure("statement", error)); | |
| 65 | } | |
| 66 | }; | |
| 67 | return ok({ | |
| 68 | run(sql, params = []) { | |
| 69 | const done = exec(sql, params); | |
| 70 | return done.ok ? ok() : done; | |
| 71 | }, | |
| 72 | all: (sql, params = []) => exec(sql, params), | |
| 73 | close() { | |
| 74 | const was = handle; | |
| 75 | handle = null; | |
| 76 | try { | |
| 77 | was?.close(); | |
| 78 | } catch { | |
| 79 | // a close that fails leaves nothing open to the page; the store is closed either way | |
| 80 | } | |
| 81 | }, | |
| 82 | }); | |
| 83 | } |
test/deps.test.ts +4 −1
| @@ -16,7 +16,10 @@ const locked = lock.workspaces[""] ?? {}; | ||
| 16 | 16 | |
| 17 | 17 | test("the forge has no runtime dependencies", () => { |
| 18 | 18 | for (const kind of ["dependencies", "optionalDependencies", "peerDependencies"] as const) { |
| 19 | const names = Object.keys(pkg[kind] ?? {}); | |
| 19 | // The one runtime dependency: SQLite wasm for the tab forge (docs/DEPENDENCIES.md). | |
| 20 | const names = Object.keys(pkg[kind] ?? {}).filter( | |
| 21 | (n) => !(kind === "dependencies" && n === "@sqlite.org/sqlite-wasm"), | |
| 22 | ); | |
| 20 | 23 | expect(names.length === 0 ? "" : `${kind}: ${names.join(", ")}`).toBe(""); |
| 21 | 24 | } |
| 22 | 25 | }); |
test/import-all.test.ts +4
| @@ -15,6 +15,10 @@ const ENTRIES = new Set<string>([ | ||
| 15 | 15 | "web/machine-term-client.ts", |
| 16 | 16 | "web/render/dxf-client.ts", |
| 17 | 17 | "web/render/model3d-client.ts", |
| 18 | // The tab forge's worker: it reads `self.location`, which only a worker has. | |
| 19 | "web/tabforge/client.ts", | |
| 20 | // Its one import is the 1 MB sqlite-wasm loader, which only a browser worker runs. | |
| 21 | "web/tabforge/opfs.ts", | |
| 18 | 22 | ]); |
| 19 | 23 | |
| 20 | 24 | test("every src module imports in-process without exiting", async () => { |
test/shards.test.ts +2 −1
| @@ -648,7 +648,8 @@ describe("the gate audit alone, first in the check", () => { | ||
| 648 | 648 | |
| 649 | 649 | test("`typescript` is the native 7.x checker; 5.x stays only as the compiler API hollow.ts walks", async () => { |
| 650 | 650 | const pkg = JSON.parse(readFileSync(new URL("../package.json", import.meta.url), "utf8")); |
| 651 | expect(pkg.dependencies ?? {}).toEqual({}); | |
| 651 | // The one runtime dependency: SQLite wasm for the tab forge (docs/DEPENDENCIES.md). | |
| 652 | expect(Object.keys(pkg.dependencies ?? {})).toEqual(["@sqlite.org/sqlite-wasm"]); | |
| 652 | 653 | expect(pkg.devDependencies["typescript"]).toMatch(/^\^7\./); |
| 653 | 654 | expect(pkg.devDependencies["typescript-api"]).toMatch(/^npm:typescript@\^5\./); |
| 654 | 655 | const checker = await import("typescript/package.json"); |
test/tabforge-asset.test.ts added +42
| @@ -0,0 +1,42 @@ | ||
| 1 | /** | |
| 2 | * The tab forge's assets (#17274): SQLite's WebAssembly is one immutable file | |
| 3 | * under a content-hashed name, the worker script carries no copy of it, and | |
| 4 | * neither is named by any page the forge renders today. | |
| 5 | */ | |
| 6 | import { expect, test } from "bun:test"; | |
| 7 | import { readdirSync, readFileSync, statSync } from "node:fs"; | |
| 8 | import { join } from "node:path"; | |
| 9 | import { sqliteWasmAsset, sqliteWasmResponse, tabforgeAsset } from "../src/web/tabforge/asset.ts"; | |
| 10 | ||
| 11 | test("the wasm is served immutable, as wasm, under a hashed name, and revalidates to 304", async () => { | |
| 12 | const asset = sqliteWasmAsset(); | |
| 13 | expect(asset.path).toMatch(/^\/assets\/sqlite3-[0-9a-f]{16}\.wasm$/); | |
| 14 | const res = sqliteWasmResponse(new Request(`http://x${asset.path}`)); | |
| 15 | expect(res.headers.get("content-type")).toBe("application/wasm"); | |
| 16 | expect(res.headers.get("cache-control")).toContain("immutable"); | |
| 17 | expect(res.headers.get("x-content-type-options")).toBe("nosniff"); | |
| 18 | expect([...asset.bytes.slice(0, 4)]).toEqual([0, 0x61, 0x73, 0x6d]); | |
| 19 | const again = sqliteWasmResponse(new Request(`http://x${asset.path}`, { headers: { "if-none-match": asset.etag } })); | |
| 20 | expect(again.status).toBe(304); | |
| 21 | }); | |
| 22 | ||
| 23 | test("the worker script is a hashed immutable-able module with no inlined wasm", async () => { | |
| 24 | const built = await tabforgeAsset(); | |
| 25 | expect(built).not.toBeNull(); | |
| 26 | expect(built!.path).toMatch(/^\/assets\/tabforge-[0-9a-f]{16}\.js$/); | |
| 27 | expect(built!.code).not.toContain("application/wasm;base64"); | |
| 28 | expect(built!.code.length).toBeLessThan(400_000); | |
| 29 | }); | |
| 30 | ||
| 31 | test("no other page names the tab forge's files: only its own module imports them", () => { | |
| 32 | const importers: string[] = []; | |
| 33 | const walk = (dir: string) => { | |
| 34 | for (const name of readdirSync(dir)) { | |
| 35 | const path = join(dir, name); | |
| 36 | if (statSync(path).isDirectory()) walk(path); | |
| 37 | else if (/\.ts$/.test(name) && /tabforge\/(asset|opfs|client)\.ts/.test(readFileSync(path, "utf8"))) importers.push(path.replace(/^.*\/src\//, "src/")); | |
| 38 | } | |
| 39 | }; | |
| 40 | walk(join(import.meta.dir, "..", "src")); | |
| 41 | expect(importers).toEqual(["src/http/routes/discovery.ts"]); | |
| 42 | }); |
test/tabforge-store.test.ts added +76
| @@ -0,0 +1,76 @@ | ||
| 1 | /** | |
| 2 | * The tab forge's store (#17274) against an in-memory fake backend: no browser. | |
| 3 | * The fake keeps rows by database name across open and close, the way OPFS | |
| 4 | * keeps files, and throws on a statement it does not know, the way SQLite does. | |
| 5 | */ | |
| 6 | import { expect, test } from "bun:test"; | |
| 7 | import { openStore, type Backend, type Row, type Value } from "../src/web/tabforge/store.ts"; | |
| 8 | ||
| 9 | function fakeBackend(): Backend & { opened: number } { | |
| 10 | const files = new Map<string, Row[]>(); | |
| 11 | const backend = { | |
| 12 | opened: 0, | |
| 13 | async open(name: string) { | |
| 14 | backend.opened++; | |
| 15 | if (name === "unopenable") throw new Error("OPFS is not available"); | |
| 16 | const rows = files.get(name) ?? []; | |
| 17 | files.set(name, rows); | |
| 18 | return { | |
| 19 | exec(sql: string, params: readonly Value[]): Row[] { | |
| 20 | if (sql.startsWith("insert")) { | |
| 21 | rows.push({ id: rows.length + 1, body: params[0] ?? null }); | |
| 22 | return []; | |
| 23 | } | |
| 24 | if (sql === "select * from notes") return rows.map((r) => ({ ...r })); | |
| 25 | throw new Error(`near "${sql.split(" ")[0]}": syntax error`); | |
| 26 | }, | |
| 27 | close() {}, | |
| 28 | }; | |
| 29 | }, | |
| 30 | }; | |
| 31 | return backend; | |
| 32 | } | |
| 33 | ||
| 34 | test("rows written survive a close and a reopen", async () => { | |
| 35 | const backend = fakeBackend(); | |
| 36 | const first = await openStore(backend, "forge"); | |
| 37 | if (!first.ok) throw new Error(first.error.message); | |
| 38 | expect(first.value.run("insert into notes", ["hello"]).ok).toBe(true); | |
| 39 | expect(first.value.run("insert into notes", ["again"]).ok).toBe(true); | |
| 40 | first.value.close(); | |
| 41 | ||
| 42 | const second = await openStore(backend, "forge"); | |
| 43 | if (!second.ok) throw new Error(second.error.message); | |
| 44 | const rows = second.value.all("select * from notes"); | |
| 45 | expect(rows).toEqual({ ok: true, value: [{ id: 1, body: "hello" }, { id: 2, body: "again" }] }); | |
| 46 | expect(backend.opened).toBe(2); | |
| 47 | }); | |
| 48 | ||
| 49 | test("a bad statement is a typed error, not a throw, and the store still works after it", async () => { | |
| 50 | const opened = await openStore(fakeBackend(), "forge"); | |
| 51 | if (!opened.ok) throw new Error(opened.error.message); | |
| 52 | const store = opened.value; | |
| 53 | const bad = store.run("selec nonsense"); | |
| 54 | expect(bad).toEqual({ ok: false, error: { kind: "statement", message: 'near "selec": syntax error' } }); | |
| 55 | expect(store.all("also nonsense").ok).toBe(false); | |
| 56 | expect(store.run("insert into notes", ["fine"]).ok).toBe(true); | |
| 57 | }); | |
| 58 | ||
| 59 | test("a closed store answers closed, and closing twice is harmless", async () => { | |
| 60 | const opened = await openStore(fakeBackend(), "forge"); | |
| 61 | if (!opened.ok) throw new Error(opened.error.message); | |
| 62 | opened.value.close(); | |
| 63 | opened.value.close(); | |
| 64 | expect(opened.value.all("select * from notes")).toEqual({ ok: false, error: { kind: "closed", message: "the store is closed" } }); | |
| 65 | }); | |
| 66 | ||
| 67 | test("a backend that cannot open is an open error; a name that is not a file name never reaches the backend", async () => { | |
| 68 | const backend = fakeBackend(); | |
| 69 | const failed = await openStore(backend, "unopenable"); | |
| 70 | expect(failed).toEqual({ ok: false, error: { kind: "open", message: "OPFS is not available" } }); | |
| 71 | for (const name of ["", "../etc", "a/b", ".hidden", "x".repeat(65), "Upper"]) { | |
| 72 | const refused = await openStore(backend, name); | |
| 73 | expect(refused.ok ? "ok" : refused.error.kind).toBe("name"); | |
| 74 | } | |
| 75 | expect(backend.opened).toBe(1); | |
| 76 | }); |
new above
offline
Low: this adds a hold (a SLOW exemption) where bringing the test under budget would do. The pull says the budget was already breached on main. Open an issue for it and name that issue here rather than #17274.