This documentation is available as Markdown for AI agents and LLMs. See the full Markdown index at /llms.txt, or add .md to any page's URL.

Writing the data module

The view asks; app.ts answers. The README's todo list keeps its data in memory. This app keeps a reading list in SQLite, so it survives a restart, and shows a quote fetched from the network. It was made with exact new, and its test passes on the web host, macOS and the iOS Simulator.
contract
shape Book
id: string
title: string
shape Saved
ok: bool
message: string
shape Quote
text: string
component ReadingList
state draft = ""
state notice = ""
resource books = books() as shape Book[]
resource quote = quote() as shape Quote else empty(text="…")
mutation saved as shape Saved refreshes books then afterSave
derive quoteError = match failure(quote) { case some(f) => f.code == "offline" ? "Check your connection to reload the quote." : "Couldn't reload the quote.", case none => "" }
derive saveError = match failure(saved) { case some(_) => "Couldn't save this book. Try again.", case none => "" }
action reloadQuote
refresh quote
action edit(value: string)
draft = value
action add
if draft.trim() != "" and not pending(saved)
notice = ""
send saved = addBook(draft.trim())
action afterSave
match saved
case some(result)
notice = result.message
if result.ok
draft = ""
case none
notice = ""
view
column padding=24 gap=12
text "Reading list" role="heading" aria-level=1
text quote.text color="-exact-secondary-label" testId="quote"
if quoteError != ""
row gap=8
text quoteError color="-exact-secondary-label" flex=1 testId="quote-error"
button press=reloadQuote testId="retry-quote"
text "Try again"
row gap=8
input value=draft input=edit submit=add placeholder="A book" aria-label="New book" disabled=pending(saved) testId="title" flex=1
button press=add disabled=(draft.trim() == "" or pending(saved)) testId="add"
text "Add"
if saveError != ""
text saveError color="-exact-system-red" testId="save-error"
text notice testId="notice"
for book in books key=book.id
text book.title testId=`book-${book.id}`
Generate the types app.ts imports, and regenerate them whenever a source's arguments or declared shape change:
Terminal
bun exact.mjs contract types app.contract -o app.contract.d.ts
ts
import type { Answer, Database, Result, Sources, Storage } from './app.contract.d.ts';
export const appId = 'com.example.reading-list';
// One capability per line: what this module may reach. Nothing else is allowed.
export const grants = [
'sqlite.open app:/data/books.db',
'net.fetch https://api.quotable.kurokeita.dev',
].join('\n');
// An open database locks its file, so a read and a write that overlap (a
// mutation and the refresh it triggers) would refuse each other as busy.
// One queue, one open at a time.
let queue: Promise<unknown> = Promise.resolve();
function withBooks<T>(storage: Storage, work: (db: Database) => Promise<T>): Promise<T> {
const run = queue.then(async () => {
const db = await storage.sqlite.open('app:/data/books.db');
try {
await db.execute('CREATE TABLE IF NOT EXISTS books (id INTEGER PRIMARY KEY, title TEXT NOT NULL)');
return await work(db);
} finally { await db.close(); }
});
queue = run.catch(() => {});
return run;
}
const sources: Sources = {
// A read: SQLite rows to the declared `Book[]`. Integers arrive as
// bigint, so convert them. At build (bake) time there is no storage: the
// refusal's code is 'bake', and an empty list is the first frame's value.
// The app asks again when it runs.
books: (_args, _store, storage): Promise<Result<'books'>> =>
withBooks(storage, async (db) => {
const { rows } = await db.query('SELECT id, title FROM books ORDER BY id');
return rows.map(([id, title]) => ({ id: String(id), title: String(title) }));
}).catch((error) => {
if ((error as { code?: string }).code === 'bake') return [];
throw error;
}),
// A write, sent by the `saved` mutation; `refreshes books` reads the list again.
addBook: ([title], _store, storage): Promise<Result<'addBook'>> =>
withBooks(storage, async (db) => {
await db.execute('INSERT INTO books (title) VALUES (?)', [title]);
return { ok: true, message: `Added ${title}.` };
}),
// A failed read must not replace the last quote with an empty one.
quote: async (): Promise<Result<'quote'>> => {
const response = await fetch('https://api.quotable.kurokeita.dev/api/quotes/random');
if (!response.ok) throw new Error('The quote request failed.');
const body: unknown = await response.json();
if (body === null || typeof body !== 'object' || !('quote' in body) || body.quote === null || typeof body.quote !== 'object' || !('content' in body.quote) || typeof body.quote.content !== 'string') {
throw new Error('The quote response is invalid.');
}
return { text: body.quote.content };
},
};
export const answer: Answer = (source, args, store, storage, native) =>
sources[source](args, store, storage, native);
Each name the Contract calls (books(), addBook(…), quote()) is a key of sources. A source receives its arguments as an array, then the store (secrets), storage (files and SQLite), and the native module, if any. It returns the declared shape, or a promise of it. A resource and a mutation are answered the same way; the difference is only who asks and when.
Grants. grants lists, one per line, everything the module may reach. A call outside them fails. The capabilities are:
Grant
Allows
net.fetch https://api.example.com
fetch to that origin (https://*.example.com for its subdomains; https: or http: for every origin of the scheme, as a CSP scheme source). Native checks each redirect before contact. Web checks the final response URL. On render-server pages, connect-src uses app grants: a hop outside the page origin and app grants is blocked before contact (Network); a hop the app grants but this source does not can receive a 307 POST body and return to a source-granted final URL, succeeding on web while native refuses. Static and dev pages have no such CSP, so even an app-ungranted hop can be contacted and a return chain can succeed. Without CSP, an ungranted final URL fails after contact, naming where it led: outside the app's grants (net.fetch): redirected to https://other.example
net.websocket wss://api.example.com
a WebSocket to that origin (wss: or ws: for every origin of the scheme)
sqlite.open app:/data/name.db
storage.sqlite.open on that path
fs.read app:/data/dir, fs.write app:/data/dir
storage.fs under that prefix (app:/data, app:/cache, app:/tmp)
secret.keep name
store.keepKey(name, pair) and store.key(name): a P-256 key pair kept by the platform
storage.kv scope, env.read NAME
a host's key–value scope and environment variable (grants/src/lib.rs); a data module has no API for them yet: its storage is fs and sqlite, so keep key–value data in a file or a table
What catches people.
•
A source cannot repeat a timer, and ambient clocks skip bake. setInterval, requestAnimationFrame and requestIdleCallback are refused at build time and on every executor; use a Contract task to repeat work. Date.now(), new Date() without a value, performance.now() and Math.random() work against the host's deterministic clock and seeded substream (CSPRNG in production), alongside crypto.getRandomValues and crypto.randomUUID, but a resource that calls them is excluded from launch bake and SSR caching and logs [ambient-clock]. Pass exactTime() or performanceNow() from Contract when the value should bake, cache or stay reactive (the data-module reference has the full rules). An answer may wait with setTimeout or AbortSignal.timeout: the timer is due on the app's clock, the agent's clock +N fires it, and it is cleared when its answer gives its value.
•
There is no storage or network at build time. The build bakes each resource's first value into the plan, and a storage or native.call then is refused with code: 'bake'. An uncaught refusal leaves the resource unbaked; its placeholder (or the type's zero) shows until the app asks again at launch. Catching that code can also supply a first-frame value, as books does. Other source errors still fail the build. A source used as an else placeholder must answer at bake without storage. A fetch also stays unbaked; an else placeholder supplies something better than the type's zero, as quote does.
•
An open database locks its file. A mutation and the refresh it triggers overlap, and the second open fails as busy. Queue every open, as withBooks does.
•
A save need not be awaited. An editor answers from memory and saves in the answer, unawaited; the answer is there at once and the write finishes behind it, in the order the edits were made, on every host:
ts
edit(store, args) {
song = apply(song, args);
storage.fs.atomicWriteFile(PATH, new TextEncoder().encode(JSON.stringify(song))).catch(note); // started now, not awaited
return song;
}
Call storage in the answer rather than chaining it on a promise, keep a failure (note) to say in the next answer, and put writes that must stay together in one transaction.
•
SQLite integers are bigint. Convert them (String(id), Number(n)) before returning; a Contract number is not a bigint.
•
A domain refusal from a write is data. A write source may return ok: false with a message so the view can explain the refusal. A thrown error produces no new mutation reply: the mutation keeps its previous value and runs no then. A failed read should fail its resource so Exact retains its last valid answer.
•
app.ts imports local files and pure-JavaScript packages. The bake bundles a package's code (ESM or CommonJS, its browser build first), as Excord's fflate is. One that needs Node (fs, Buffer), the DOM or a native addon is refused by name. An import type (or a name used only as a type) may reach any package's declarations, such as the rows snapback4 types writes to snapback/generated/api.ts, and every build checks against them.
Testing with storage. Each authored test gets an empty store of its own, apart from the app's real data. An ad hoc agent drive has none unless it names a scratch store with --storage:
contract-test
test "a book is added and kept"
clock settle
type "title" "Middlemarch"
tap "add"
clock settle
expect text "notice" == "Added Middlemarch."
expect text "book-1" == "Middlemarch"
Terminal
bun exact.mjs test web # each test starts with an empty store
bun exact.mjs agent web --storage demo "type title Dune" "tap add" "clock settle" tree
A native scratch store is kept between drives (--reset-storage empties it), so a second agent ios --storage demo opens the list the first one saved. On the web the store is Chrome's profile for that name, served at one origin, and starts empty each drive: the second drive passes --keep-storage to open the saved list (Firefox and WebKit drives always start fresh). A test's reload restarts the app on its store within one drive, including a data module's secret.keep.
Rust instead. A data module can be a Rust crate rather than app.ts: bun exact.mjs contract rust app.contract -o shapes.rs generates the shapes as structs with their conversions, and Caltrain's data crate answers its sources that way. The Exact developer reference covers placement on a worker, live replacement, and the platform limits.
Is this helpful
Last updated November 30, 2026
Exact Docs