API reference ¶
The authoritative API contract lives in specs/. This page lists the public surface with one-line descriptions and pointers into the per-symbol spec for the details. For end-to-end usage walkthroughs, see the recipes.
Module surface ¶
All public symbols are imported from the package root:
import {
// factories
openRepo, openStore,
// primary classes
Repository, Sheet, Transaction, PushDaemon, Template,
// error classes
GitsheetsError, ConfigError, ValidationError, TransactionError,
IndexError, RefError, PathTemplateError, NotFoundError, ContractError,
AggregationError,
// utilities
mergePatch, validateRecord, canonicalContractHash,
parseToml, parseConfigToml, stringifyRecord,
getFormat, hasFormat, registerFormat, resolveFormatConfig,
// record annotation symbols
RECORD_SHEET_KEY, RECORD_PATH_KEY,
} from 'gitsheets';
Type-only exports (selected highlights):
import type {
OpenRepoOptions, OpenSheetOptions, OpenSheetsOptions,
TransactionOptions, TransactionResult, TransactionHandler, Author,
SheetConfig, SheetFieldConfig, SortRule, UpsertResult, UpsertOptions, WillChangeResult,
SheetConstructorOptions, IndexKeyFn, DefineIndexOptions, QueryFilter, RangeFilter, QueryOptions,
DiffStatus, DiffOptions, DiffChange,
AggregateSpec, AggregatesSpec, AggregateModifiers, AggregateOptions,
AttachmentBlobHandle, AttachmentEntry,
Format, FormatConfig,
OpenStoreOptions, Store, StoreTx, StoreTransactFn, ValidatorMap, InferRecord,
PushDaemonOptions, PushDaemonStatus, PushFailureReason, BackoffConfig,
JSONSchema, StandardSchemaV1, ValidationIssue, StandardSchemaResult,
RecordLike, PathTemplateBlob, PathTemplateTree, PathTemplateQueryResult,
OpenSheetContractOptions, ContractVerificationMode, ConformanceReport,
ContractDocumentFormat, CanonicalContractHashOptions,
} from 'gitsheets';
No deep imports (gitsheets/lib/Sheet) — the implementation can rearrange packages/gitsheets/src/ freely without notice. The package-root surface is the only stable API.
Factories ¶
openRepo(opts?) → Promise<Repository> ¶
Open a Repository against a git directory. Discovers from cwd upward when gitDir is omitted. Fresh-but-initialized repositories (no commits yet) are supported.
const repo = await openRepo(); // discovered
const repo = await openRepo({ gitDir: '/.git' }); // explicit
const repo = await openRepo({ branch: 'data' }); // branch mode: records live on `data`
const repo = await openRepo({ submodule: 'data' }); // submodule mode: records live in the `data` submodule
Default branch. Every repository is bound to one default branch: the branch live sheets read, transactions commit to when given no parent, and refresh / sync / fetch / the push daemon / merge target when given no ref. It resolves once, at open, from the first of opts.branch → GITSHEETS_BRANCH → the gitsheets.branch git config of the opened repository → the branch HEAD points at. repo.branch reports it ('data'), or null when the repository is bound to a detached HEAD (every default then follows HEAD, as before). A tag, commit, or malformed name throws ConfigError (config_invalid). The branch may not exist yet: it reads as empty and the first committing transaction creates it with a root commit. Explicit refs — readBlob('HEAD', …), openSheet(name, { ref: 'HEAD' }), transact({ parent: 'main' }) — keep meaning exactly what they name. See Headless data.
Submodule mode. opts.submodule (else GITSHEETS_SUBMODULE, else the superproject’s gitsheets.submodule git config) opens the git submodule at that path instead — <path>/.git, else .git/modules/<name>; neither throws ConfigError (config_missing) naming git sheet submodule init <path>. The submodule’s HEAD is the superproject’s pointer to a data snapshot: the default branch is HEAD’s branch, or HEAD itself when detached (a commit then advances HEAD directly, compare-and-swap; sync / fetch / the push daemon need a branch). opts.branch / GITSHEETS_BRANCH / gitsheets.branch resolve inside the submodule; a branch HEAD is not on is written without moving the pointer. After a commit the superproject’s git status reports modified: data (new commits) — commit the pointer with your code; opts.stagePointer: true also updates the superproject’s index gitlink after each commit, merge, or sync that moves the pointer (never commits); if that fails after the commit landed, TransactionError (pointer_stage_failed) carries err.commitHash — run git add <path>, don’t retry. A path with no .gitmodules entry is ConfigError (config_invalid); a linked worktree uses its own modules/ dir. The binding is resolved at open, so reopen after git submodule update changes what HEAD is. opts.at (a superproject commit-ish) pins every sheet read-only at the data commit it points at: writes, sync, fetch, merge, tag, and the push daemon throw TransactionError (transaction_required); no pointer at that commit throws RefError (ref_not_found). repo.submodule reports the path (null in branch mode).
const repo = await openRepo({ submodule: 'data', stagePointer: true });
const shipped = await openRepo({ submodule: 'data', at: 'v1.2.0' }); // read-only: the data v1.2.0 shipped with
openStore(repo, opts?) → Promise<Store<V>> ¶
Typed wrapper over Repository.openSheets() that binds per-sheet Standard Schema validators. store.<sheet> is Sheet<InferRecord<V[sheet]>> for every sheet in opts.validators.
const store = await openStore(repo, {
validators: { users: UserSchema, projects: ProjectSchema },
// ref: 'published', // optional: a read-only store pinned at a ref; store.refresh() re-resolves it
});
Repository ¶
| Method | Purpose |
|---|---|
repo.openSheet<T>(name, opts?) |
Sheet handle; opts.validator (Standard Schema), opts.root, opts.prefix, opts.ref (pin reads to a branch/tag/commit — read-only, excluded from auto-refresh; sheet.refresh() re-resolves the ref), opts.contract (verify against a contract before returning — result on sheet.contractVerification) |
repo.openSheets(opts?) |
All sheets keyed by name; opts.root, opts.prefix, opts.ref |
repo.transact(opts, handler) |
Run a handler in a single-commit transaction |
repo.withLock(fn) |
Run fn holding the write lock transact uses — coordinate non-transact git ops. Not reentrant (lock_held) |
repo.requireExplicitTransactions() |
Switch to strict mode (one-way) |
repo.startPushDaemon(opts) |
Start async push to a configured remote |
repo.resolveRef(ref) |
Resolve a ref or commit hash; returns string \| null |
repo.sync(opts?) |
Bring a branch up to date with a remote other writers push to: fetch, then fast-forward / replay local commits / preserve-on-conflict under the write lock; rebinds live sheets; hands new tips to the push daemon. Outcomes in-sync · fast-forwarded · ahead · rebased · conflict · conflict-escaped · fetch-failed |
repo.fetch(opts?) |
The fetch step of sync on its own, outside any lock: { ok, remoteRef, remoteCommit \| error } — failure is a value |
repo.isAncestor(a, b) |
Promise<boolean> — is commit a reachable from b |
repo.tag(name, target?, { force? }) |
Lightweight tag (default target: the default branch’s tip, HEAD when bound to a detached HEAD); refuses an existing tag unless force — git tag -f without the spawn |
repo.listTree(ref, path?) |
Direct entries { name, type, mode, hash } of the tree at <ref>:<path>, or null — git ls-tree without the spawn |
repo.merge({ theirs, ours?, prefer?, commit? }) |
Sheet-aware merge: record files changed on both sides are field-merged and written canonically; conflicts follow prefer (fail · ours · theirs) or are reported in the result, never thrown. Outcomes up-to-date · fast-forward · merged · conflict · dry-run |
repo.refresh() |
Rebind every live Sheet to the default branch’s current tree — for out-of-band ref movement (a successful transact and repo.sync() auto-refresh) |
repo.branch |
The default branch’s short name, or null when bound to a detached HEAD |
repo.submodule |
Submodule mode: the submodule’s path ('data'), or null |
repo.readBlob(ref, path) |
Promise<BlobHandle> — the blob at <ref>:<path>, resolved at call time: hash, size (from the object header), read(), stream(). Throws RefError / NotFoundError |
repo.readBlobStream(ref, path) |
Promise<Readable> — readBlob(…).stream(): in-core up to 1 MiB, piped from git cat-file blob above that |
opts.prefix scopes records to a sub-tree under each sheet’s configured root — useful for multi-tenant deployments where one git repo holds many tenants under <root>/<tenant>/.... Mirrors the CLI --prefix flag (env GITSHEETS_PREFIX). The sheet’s .gitsheets/<name>.toml config file is unaffected — only the record data tree is scoped.
Sheet ¶
Sheet<T extends RecordLike = RecordLike> — generic on the record type. With a validator (via openSheet({ validator }) or openStore), T flows through every method signature.
Reading ¶
| Method | Returns |
|---|---|
sheet.query(filter?, opts?) |
AsyncGenerator<T> — iterator; filter entries are equality, a predicate, a nested object, or a { $gt, $gte, $lt, $lte } range (see path templates); opts.signal for AbortSignal cancellation; opts.withBody for content-typed body loading |
sheet.queryFirst(filter?, opts?) |
Promise<T \| undefined> — honors opts.signal, opts.withBody |
sheet.queryAll(filter?, opts?) |
Promise<T[]> — honors opts.signal, opts.withBody |
sheet.get(path, opts?) |
Promise<T \| undefined> — one record by its rendered path (one blob read, no scan); opts.withBody; on a tx-bound sheet reads the private tree |
sheet.loadBody(record) |
Promise<T> — hydrate a body-less record (content-typed sheets) |
sheet.refresh() |
Rebind this sheet’s read snapshot to the default branch’s current tree (out-of-band movement; own commits auto-refresh) |
sheet.pathForRecord(record) |
Promise<string> — rendered path, no write |
sheet.normalizeRecord(record) |
Promise<T> — canonical form, no write: the core’s normalization of the marshalled record (array order and key order exactly as a write commits them; null keys dropped; unrepresentable values throw ValidationError) |
Writing ¶
| Method | Purpose |
|---|---|
sheet.upsert(record, opts?) |
Insert or replace; returns { blob, path }. A record loaded from the sheet whose rendered path changes is renamed: the old file is deleted and its attachment directory moves with it. opts.allowMissingBody for content-typed sheets (an explicit null body needs no opt-in; absent/undefined throws) |
sheet.delete(recordOrPath) |
Remove a record + cascade attachments |
sheet.patch(query, partial) |
RFC 7396 merge patch over an existing record. For content-typed sheets with [gitsheet.format].title configured (v1.3): a title-only patch rewrites the body’s H1; a body-only patch re-derives the title |
sheet.willChange(record, opts?) |
Pre-flight idempotency check — returns { changed, path, currentBlobHash?, nextText } without mutating the tree (v1.3) |
sheet.clear() |
Remove every record from the sheet’s tree |
sheet.clone() |
Clone the Sheet for staging tentative state |
All write methods route through a transaction — permissive mode auto-opens one; strict mode requires repo.transact.
willChange runs upsert’s full validation + normalization + serialization pipeline and compares the resulting bytes to the existing blob at the rendered path. Useful for consumers that want commit-skipping idempotency semantics — “only commit if something actually changed.” Throws the same errors upsert would on the same input (ValidationError, IndexError, PathTemplateError).
Attachments ¶
| Method | Purpose |
|---|---|
sheet.getAttachment(record, name) |
One attachment’s BlobHandle (hash, size, read(), stream()) or null |
sheet.getAttachments(record) |
Map of name → BlobHandle |
sheet.getAttachmentStream(recordOrPath, name) |
Promise<Readable \| null> — stream an attachment’s bytes without materializing the record |
sheet.setAttachment(record, name, content) |
Add or replace — content may be raw bytes (Buffer/Uint8Array), a UTF-8 string, or a BlobHandle |
sheet.setAttachments(record, map) |
Bulk variant; values accept the same types, mixed freely |
sheet.deleteAttachment(record, name) |
Remove a single attachment; throws NotFoundError if missing |
sheet.deleteAttachments(record) |
Remove all attachments; idempotent no-op when no attachment dir |
sheet.attachments(record) |
AsyncGenerator<AttachmentEntry> yielding {name, mimeType, blob} with .read() / .stream() |
Diff ¶
| Method | Returns |
|---|---|
sheet.diffFrom(srcCommitHash?, opts?) |
AsyncGenerator<DiffChange<T>> — per-record changes since srcCommitHash (defaults to the empty tree). opts.blobs / opts.records / opts.patches attach hologit blob handles, parsed src/dst records, and RFC 6902 JSON Patches respectively. Throws RefError if srcCommitHash doesn’t resolve. |
Indexing ¶
| Method | Purpose |
|---|---|
sheet.defineIndex(name, keyFn) |
Lazy index (build on first lookup) |
sheet.defineIndex(name, { unique, eager }, keyFn) |
With opts; eager: true returns Promise<void> |
sheet.findByIndex(name, key) |
Promise<T \| T[] \| undefined> |
→ specs/api/sheet.md · indexing recipe
Aggregation ¶
| Method | Returns |
|---|---|
sheet.aggregate(filter, aggregates, opts?) |
Promise<Record<string, unknown>> — one value per named aggregate over the records matching filter (pass undefined or {} for all). Computed in the core: pruned like query, read body-less, folded in canonical path order. opts.signal for cancellation; works on a tx-bound sheet |
const r = await sheet.aggregate(
{ postedAt: { $gte: '2026-01-01' } },
{
count: { count: true },
total: { sum: 'amountCents' },
byStatus: { count: true, groupBy: 'status' },
latest: { max: 'postedAt' },
ids: { reduce: 'acc.push(record.id); return acc;', initial: [] },
},
);
// → { count: 1402, total: 98231100, byStatus: { posted: 1390, pending: 12 }, latest: Date, ids: [...] }
Forms: { count: true }, { sum: 'f' }, { avg: 'f' }, { min: 'f' }, { max: 'f' }, { distinct: 'f' }, and the { reduce, initial, finalize? } escape hatch, whose bodies run in the core’s embedded JS engine (never in Node) so every binding gets the same answer. Each form takes where (an equality/range filter, no functions) and groupBy (a field; the result becomes a table keyed by its string form).
sumis an integer when every contributing value is, else the float fold in path order;avgis a float.min/maxorder numbers, strings, and datetimes;distinctreturns the sorted unique scalars. Mixing kinds in one field throwsAggregationError.- An aggregate with nothing to fold is left out of the result, except
countandsum(0). A grouped aggregate is always a table ({}when empty). filtermay carry function predicates as onquery; they run host-side to pick the records, then the core folds over exactly those.distinctholds every unique value in memory — fine at gitsheets’ scale, but don’t point it at a high-cardinality field you don’t need.reduce/finalizemust be pure, and the core enforces it:Math.random(),Date.now(), and an argument-lessnew Date()/Date()throw (anAggregationError);new Date(ms),new Date(isoString),Date.UTC, andDate.parsestill work, and aDate’s local-time methods read UTC on every host. Eachreducegroup runs in a fresh engine realm under loop / recursion / stack limits, so a runaway snippet is anAggregationError, not a hang. That determinism is what lets rollup sheets commitreduceresults.- Numbers coming out of a
reducefollow the engine’s one rule: an exact integer within ±(2^53 − 1) is an integer, anything else a float. On Node, an integral float result (4.0, e.g. fromavg) is indistinguishable from4anyway — JS has one number type (a pre-existing binding projection, not specific to aggregation). - Grouped results are plain objects, so JS orders integer-like keys numerically first (
"9"before"10", both before"a"); the core and the TOML output sort keys by byte order. A group literally named__proto__is an ordinary own key. - Throws
TypeErrorfor a malformed spec or a body-field reference on a content-typed sheet;AggregationError(aggregation_failed, withsheetandaggregate) when the data can’t be aggregated, or areducethrows or returns something TOML can’t hold.
→ specs/behaviors/aggregation.md
Rollup sheets ¶
A sheet whose config has a [gitsheet.rollup] table is a rollup sheet: one record per partition of a source sheet, holding aggregates in the grammar above, committed by gitsheets in the same commit as the record changes and stamped with the source partition’s git tree id (sourceTree) and the .gitsheets/ directory’s (configTree). See the rollups recipe.
# .gitsheets/transactions-monthly.toml
[gitsheet]
root = 'transactions-monthly'
path = '${{ postedAt: YYYY/MM }}' # a proper prefix of the source's path
[gitsheet.rollup]
from = 'transactions'
[gitsheet.rollup.aggregates]
count = { count = true }
total = { sum = 'amountCents' }
| Member | Behavior |
|---|---|
query / queryFirst / queryAll / get / count / aggregate / findByIndex |
Read through the source: a stored record whose stamps match its partition and the configs is served; a stale or missing one is recomputed transiently (nothing is written); a record whose partition is gone is not yielded. Key-field filters (including bucket ranges) prune like on the source |
opts.stale (on query, queryFirst, queryAll, get) |
'recompute' (default) or 'serve' — the stored records exactly as committed |
sheet.materialize() |
Promise<{ recomputed: string[], deleted: string[] }> — recompute every stale or missing rollup record and delete orphans, in one commit (into the current transaction on a tx-bound sheet); no commit when everything is fresh. TypeError on a non-rollup sheet |
upsert / delete / patch / clear / attachment writers |
Throw TransactionError (sheet_derived) |
- Every commit gitsheets produces —
repo.transact, a permissive write,repo.merge, eachrepo.syncreplay — regenerates the rollups of the partitions it touched. A config change regenerates them all. - An
AggregationErrorin that pass (withsheet,aggregate, andpartition) aborts the commit; so does aValidationErroragainst a declared rollup[gitsheet.schema]. - A plain
git mergeor an outside writer leaves stale stamps: reads stay correct, andmaterialize()/git sheet rolluppersists the repair. - Prefixed (multi-tenant) sources get per-prefix rollups under
<rollup root>/<prefix>/…; every gitsheets commit, merge, and sync replay maintains all of them. - Equality on a date key field accepts
'2026-03-01'or a midnight-UTCDate(any local-date field does).
Transaction ¶
| Member | Purpose |
|---|---|
tx.sheet<T>(name, opts?) |
Sheet bound to the tx’s tree; opts.validator, opts.prefix |
tx.parentCommitHash |
Commit hash the tx parents on (may be null for fresh repos) |
tx.parentRef / tx.branchRef |
Refs being read from / advanced |
tx.writeFile(path, content) |
Stage a raw file (repo-root-relative; string as UTF-8 or Buffer/Uint8Array) in the same commit as record changes — sheet configs, contracts, fixtures. Returns a BlobHandle. Not validated or normalized |
tx.deleteFile(path) |
Remove a raw file; returns whether it existed (a miss leaves the tx unmutated) |
repo.transact options: parent (ref or hash; default HEAD; null for an orphan root commit — empty start, no parents, always commits, branch created and must not exist), branch (ref to advance; created if absent), author, committer, message, trailers.
Consumers don’t construct Transaction directly — it comes from repo.transact’s handler. tx.sheet(name) may be called any number of times; writes are atomic within the handler.
→ specs/api/transaction.md · specs/behaviors/transactions.md · request-bound recipe
TransactionResult ¶
interface TransactionResult<T> {
readonly value: T; // handler return value
readonly commitHash: string | null; // null when no mutations occurred
readonly treeHash: string | null;
readonly ref: string | null;
readonly parentCommitHash: string | null;
}
Store ¶
type Store<V extends ValidatorMap> = {
readonly [K in keyof V]: Sheet<InferRecord<V[K]>>;
} & {
readonly transact: StoreTransactFn<V>;
readonly refresh: () => Promise<void>;
};
store.<sheet> for each sheet declared in validators. store.transact(opts, async tx => ...) mirrors repo.transact with tx.<sheet> aliases that thread validators through. store.refresh() rebinds every sheet to the default branch’s current tree (delegates to repo.refresh()).
Reads through store.<sheet> follow the freshness model: a successful store.transact / repo.transact auto-refreshes, so post-commit reads reflect the committed state — see specs/behaviors/freshness.md.
Sheets not in validators are accessible via repo.openSheet(name) for one-off un-typed access.
PushDaemon ¶
Returned from repo.startPushDaemon(opts). EventEmitter with:
| Event | Payload |
|---|---|
push |
{ commit, durationMs } |
retry |
{ commit, attempt, nextDelayMs, reason } |
error |
{ commit, err, attempt, reason } — reason: 'non-fast-forward' \| 'unknown'. NFF is terminal (no retry). |
stopped |
(none) |
| Method | Purpose |
|---|---|
daemon.status() |
Snapshot: running, lastPushAt, lastError (with reason), pendingCommits, currentBackoffMs, currentAttempt |
daemon.stop({ timeoutMs }) |
Drain in-flight retries (graceful) |
On startPushDaemon the daemon also runs a one-shot startup-backlog check (fetch + rev-list --count <remote>/<branch>..<branch>) and queues any commits ahead of the remote; this is how a restarted daemon catches up.
→ specs/behaviors/push-sync.md · production recipe
Errors ¶
All gitsheets exceptions extend GitsheetsError:
class GitsheetsError extends Error {
readonly code: string; // stable identifier
readonly status: number; // HTTP-style hint
override readonly cause?: unknown;
}
Subclasses:
| Class | Common codes |
|---|---|
ConfigError |
config_missing, config_invalid |
ValidationError |
validation_failed (carries issues: ValidationIssue[]) |
TransactionError |
transaction_in_progress, transaction_required, parent_moved, commit_failed, push_daemon_running, transaction_closed, lock_held |
IndexError |
index_unique_conflict, index_not_defined (carries conflictingPaths) |
RefError |
ref_not_found, not_an_ancestor |
PathTemplateError |
path_render_failed, path_invalid_chars |
NotFoundError |
record_not_found |
ContractError |
contract_missing, contract_invalid, contract_unsatisfied (carries contract and, on contract_unsatisfied, the conformance report in issues) |
AggregationError |
aggregation_failed (carries sheet, aggregate, and partition for a persisted rollup) |
Consumers switch on instanceof or err.code — never on err.message.
→ specs/api/errors.md — full code table
Path Template ¶
Template.fromString(s) — parse + cache. Most consumers don’t construct Template directly; it’s exposed for advanced use cases (path template diagnostics, custom queryTree integrations). getFieldNames() lists every field the template may read (expression identifiers included, best-effort); getStaticFieldNames() lists only the plain / recursive references and date-bucket base fields — the set the open-time template check requires the schema to list.
render(record) and queryTree(tree, query) run in the core — the same renderer a write uses, expression components included — so Template.render, sheet.pathForRecord, and the path an upsert commits always agree. Each compiled template holds its own engine; the fromString cache is per thread (a worker thread compiles its own).
→ path templates doc · specs/behaviors/path-templates.md
Utility ¶
mergePatch(target, patch) ¶
RFC 7396 JSON Merge Patch as a pure function. Useful when you want the patch semantic without going through Sheet.patch. See specs/behaviors/patch-semantics.md.
validateRecord({ record, schema, validator? }) ¶
Run the same validation pipeline Sheet.upsert uses without going through a Sheet. Useful for pre-flight (UI form submission, CSV ingest, audit passes against legacy records). Returns the possibly-transformed record on success, throws ValidationError on failure. See specs/behaviors/validation.md.
canonicalContractHash(input, options?) ¶
The contract identity primitive: canonicalize a contract document — parsed data, or JSON/TOML text with { format } — through the canonical TOML encoder and return the SHA-256 hex of the resulting bytes. Two parties holding the same logical document compute the same hash regardless of serialization.
TOML round-tripping ¶
| Symbol | Use |
|---|---|
parseToml(text) |
Parse TOML to a plain object; preserves @iarna/toml date types |
parseConfigToml(text, sourcePath) |
Same parse with config-aware error messages — for .gitsheets/<sheet>.toml |
stringifyRecord(record) |
Serialize an object to canonical TOML (deep-sorted keys) |
Used by the AXI tool’s config-scaffolding commands; available to consumers that need raw config-text round-tripping.
Format dispatch ¶
| Symbol | Use |
|---|---|
getFormat(type) |
Resolve a format implementation by name ('toml', 'markdown', 'mdx') |
hasFormat(type) |
Probe whether a format is registered |
registerFormat(type, impl) |
Register a custom format implementation |
resolveFormatConfig(raw) |
Validate and normalize a [gitsheet.format] block |
Available for consumers who want to render records through a sheet’s configured format without going through a Sheet instance.
Conventions ¶
Read specs/api/conventions.md for the cross-cutting rules: TypeScript posture, async patterns, options-object pattern, default refs/paths.
Stability ¶
Everything documented in specs/ (and re-exported from gitsheets) is stable from v1.0 onward. Additions in minor versions are additive (new methods, new options). Internal modules under dist/ that aren’t re-exported are implementation details and may change in minor releases.