Skip to content

Repository ​

A Repository holds an app's events. It applies NIP-09 deletes, NIP-40 expiration and replaceable-event semantics, answers nostr filters asynchronously, and emits a diff whenever its contents change. An App owns one as app.repository, and the derivations build live stores from it.

Two implementations share these semantics. MemoryRepository keeps everything in memory. SqliteRepository keeps events in SQLite in a worker, so nothing is copied into memory at startup.

Repository ​

Properties:

  • tracker - The Tracker recording which relays each event was seen on

Events:

  • "update" - Emitted with a RepositoryUpdate whenever a write changes what a query returns
  • "clear" - Emitted by clear()

Methods:

  • query(filters, {includeDeleted, includeExpired, relay, signal}) - Resolves to the events matching any filter, newest first. relay keeps only events the tracker has seen on that relay, before any limit counts. Each filter's limit applies to that filter, and a limit of 0 returns nothing stored, as a relay would. A query whose signal aborts before the repository answers rejects with the signal's reason
  • count(filters, options) - Resolves to the number of distinct events query would return
  • countTags(name, {signal}) - Resolves to a Map from each value of the single-letter tag name to how many events query would return that carry it
  • getEvent(idOrAddress) - Resolves to the event with that id, or the current version at an address (kind:pubkey:d)
  • isDeleted(event) - Whether a delete hides the event. It is synchronous because request calls it on every incoming event
  • publish(event) - Stores an event and resolves to whether a query would now return it. An event already held unchanged, whatever the order of its keys, or one older than the stored version at its address, changes nothing. One stored already deleted, expired or superseded resolves false. An event under a stored id with different content, such as an unsigned event gaining its signature, replaces the stored copy
  • removeEvent(idOrAddress) - Removes an event, restores the version it replaced, and withdraws any deletes it asserted
  • pendingWrites() - A promise that settles once every write made so far has been reported as an "update", or undefined when none is outstanding. MemoryRepository reports each write as it is made, so it always returns undefined
  • clear() - Removes every event and every tracked relay
  • observe({filters, onUpdate, onLoad, onError, includeDeleted, relay}) - Reads the stored events matching filters, then calls onUpdate with each change to them, and returns a function that stops it. onLoad receives everything the read found, reconciled with the changes reported while it was in flight, and nothing once the repository is cleared; without it, the read reaches onUpdate as the events it adds. A failed read goes to onError, or is logged without it. The derivations are built on it

Deletes and replaceables ​

A kind 5 event deletes the ids and addresses in its e and a tags. The delete hides only events by its own author, and an address delete hides only versions older than the delete. Only a replaceable event has an address. A store records a delete whether or not it holds the target, so a target that arrives later is still hidden. Deleted events stay stored, and query skips them unless includeDeleted is set.

A newer event at an address replaces the stored one, which the repository treats as deleted by its successor and reaches only by id. Removing the newer event restores the older one. Expired events stay stored and are skipped unless includeExpired is set.

An "update" lists an event that arrives already deleted, expired or superseded in removed, along with anything it supersedes or deletes.

RepositoryUpdate ​

typescript
type RepositoryUpdate = {
  added: TrustedEvent[]
  removed: Set<string>
}

mergeRepositoryUpdates(updates) folds several updates into one, where a later update wins for an id that appears in both lists.

MemoryRepository ​

MemoryRepository indexes events by id, by address (replaceables only), by author, by kind, by day of created_at, and by each single-letter tag's first value. A filter with ids, authors or a single-letter tag narrows through the first of those indexes, in that order. Otherwise a filter with both a limit and an until is answered from the day index, walked from until back towards since, so the window bounds the work rather than the size of the repository. Any other filter narrows through kinds, then since/until, and scans every event when neither applies.

Besides the async interface it has synchronous versions (querySync, getEventSync, publishSync, removeEventSync), isExpired(event), dump() for every stored event, and load(events), which adds a batch and emits a single "update".

SqliteRepository ​

SqliteRepository is a client for a SqliteEngine reached through a SqliteConnection, and connectSqlite({name, createWorker}) opens one in a browser. The worker, @welshman/store/sqlite-worker, opens the database in OPFS through a sqlite-wasm SAH pool of its own, which needs no cross-origin isolation but holds the database exclusively. Tabs sharing a database therefore elect a leader with a web lock. The leader runs the worker, and the other tabs send it their calls. Each answer goes to the tab that asked, and the leader tells every tab where it falls in the order the worker committed it, so each tab hears the changes the others commit in that order, and reports them as "update"s of its own. When the leader closes, the next tab opens the database and answers the calls left pending. A write the old leader committed but never answered runs again there and reports nothing new. A worker that fails to load answers every call with its failure.

typescript
import {SqliteRepository, connectSqlite} from "@welshman/store"
import SqliteWorker from "@welshman/store/sqlite-worker?worker"

const repository = await SqliteRepository.open({
  connection: connectSqlite({name: `events-${pubkey}`, createWorker: () => new SqliteWorker()}),
  batchDelay: 10,
})

// On logout or account switch: send what's waiting, then let the database go to another tab
await repository.close()

The ?worker import is Vite's; other bundlers construct the worker their own way.

  • Write batching. Writes collect for batchDelay milliseconds (10 by default) and commit as one transaction. A read sends any waiting writes first, so it sees them, while pendingWrites() waits for the batch to go out when it is due.
  • Synchronous state. Relays recorded on the tracker are written to the database. Every query result, and every write that reports an event, adds that event's stored relays to the tracker without emitting "add", since nothing new was seen. Another tab's relay records reach the tracker as "add" and "remove". isDeleted answers from a copy of the delete table that SqliteRepository.open loads before it resolves, updated by each write, this tab's or another's.
  • Retention. The repository keeps one superseded version per address. Opening it drops expired events and relay records whose event is gone, and every open tab hears what that changed. An expired current version takes the version it kept back with it.
  • Signatures. An event read back is marked verified only if the copy stored had already been verified, as everything appPolicyIngest stores has.
  • Memory. The repository holds only what it's reading, but a derivation holds everything its filters match while it's subscribed, and @welshman/app's collections stay subscribed for the life of the app.

Beyond Repository it has evict(filters), which drops every matching event outright, with nothing restored in its place (a current version takes the version it kept back with it), and close(), which sends the writes still waiting and then closes the connection.

SqliteEngine runs over any synchronous SqliteDatabase (exec, run, all, and define for a SQL function). wasmDatabase(db) adapts a sqlite-wasm database, and node:sqlite fits the same interface in tests. A search filter matches content containing its first term, ignoring case in any script, as matchFilter does.

App tables ​

An app keeps its own tables in the same database by serving its own worker. serveSqlite(extend), from @welshman/store/sqlite-serve, runs the engine's migrations and then calls extend(db, engine), which creates the app's schema and returns its methods. The worker serves those alongside the engine's, and an app method with an engine method's name is ignored. Methods run synchronously in the worker, and their arguments and results must survive a structured clone.

typescript
// summaries.worker.ts
import {serveSqlite} from "@welshman/store/sqlite-serve"
import type {SqliteDatabase} from "@welshman/store"

export const extend = (db: SqliteDatabase) => {
  db.exec(`
    CREATE TABLE IF NOT EXISTS summaries (event_id TEXT PRIMARY KEY, text TEXT NOT NULL);
    CREATE TRIGGER IF NOT EXISTS summaries_events AFTER DELETE ON events
      BEGIN DELETE FROM summaries WHERE event_id = old.id; END;
  `)

  return {
    putSummary: (id: string, text: string) =>
      db.run("INSERT OR REPLACE INTO summaries (event_id, text) VALUES (?, ?)", [id, text]),
  }
}

serveSqlite(extend)
typescript
import {SqliteRepository, connectSqlite} from "@welshman/store"
import SummariesWorker from "./summaries.worker?worker"
import type {extend} from "./summaries.worker"

const repository = await SqliteRepository.open({
  connection: connectSqlite<ReturnType<typeof extend>>({name, createWorker: () => new SummariesWorker()}),
})

await repository.call("putSummary", event.id, "a note")

repository.call(method, ...args) sends any waiting writes first, so an app method sees every event published before it. The engine removes a stored event by deleting its row from events, so a trigger on that table keeps rows keyed by events.id in step. extend also receives the engine, whose query answers with only the events a repository query would return.

LOCAL_RELAY_URL ​

LOCAL_RELAY_URL ("local://welshman.relay/") names the repository as a relay. With a repository in the context, getAdapter answers that url with a LocalAdapter, so request, publish and count read and write the repository through the same path as a remote relay. An open subscription receives matching events as the repository reports them.

Example ​

typescript
import {on} from "@welshman/lib"
import {MemoryRepository} from "@welshman/store"
import {LOCAL_RELAY_URL, request} from "@welshman/net"

const repository = new MemoryRepository()

on(repository, "update", ({added, removed}) => {
  console.log(`${added.length} added, ${removed.size} removed`)
})

await repository.publish(event)

const notes = await repository.query([{kinds: [1], authors: [pubkey], limit: 20}])

request({
  relays: [LOCAL_RELAY_URL],
  filters: [{kinds: [1]}],
  context: {repository},
  onEvent: event => console.log("stored", event.id),
})