Skip to main content
Declare a view with view from @bijectionhq/library-views. Its identity determines its keys and existence. Place the view in the app tree to register its generated queries and mutations.

Compose a Customer

A Customer exists while its CRM account is active. A billing fact gives its legal name, and the CRM name is the fallback. The edit marker creates a typed, erasable write home for a correction. Warehouse orders contribute landed totals and a link to Order objects. Start with accounts as the key and name: c.name as the only view field. That is enough for a local lookup({ key }). The full example adds Snowflake orders and a local correction. The order rows bind to crmId on the local account. Callers still use the account key for Customer.
customers.ts
count reads a selection’s cardinality. sum uses a declared total. A derive is pure and receives its listed fields. In prefer, an entry after an unwrapped derive, an identity field, a count, a sum or a list field can never be reached, and check refuses it with ViewField. nonNull(term) lets a present null fall through for that operand and removes null from its type, so prefer(nonNull(s.crm.phone), c.phone) is a string. Use nonNull(derive(…)) to put a derive before other entries. nonNull over a term that is never null, such as a count, a list field or a column declared without t.maybe, is a type error, and check refuses it with ViewField. open(term) opens a sealed field when the audience clears it. An ordered first(1) source contributes one row. An ordered first(n) with a larger bound contributes a list in that order. A local atMost(n) contributes a complete list and requires a unique slot constraint on the carrier. Inline lists accept up to 64 entries. Use a link to page larger collections. On a protected order, use a bounded atMost(n) list and derive the result, use a structural order, or use a unique point. A source-owned carrier can contribute a top-n list, a count, or a link. The second argument to a sources builder names contributors in that declaration. For example, office: offices(reached.billing.office) follows the office key stored in a billing fact reached by the Customer’s key. A chain can follow up to three contributor routes. A referenced contributor must resolve to a single fact. Use selectView to bind a view to one SDK client and construct a selection without making a call. read, watch, and explain are passive. Requesting the selection at head admits only its required warehouse work.
For a warehouse observation on the Customer card, use observed on a reviewed aggregate in the view’s define(account) builder. The result carries the measures in one record with one source witness. A virtual selection’s aggregate(measures) and page() resolve the matching reviewed read using its filters, measures or order. The same builder can return fields, links and actions: (self) => ({ ... }) so they can share a warehouse binding as an ordinary local variable. To follow contributors, return sources: (reached) => ({ ... }) and read their typed fields in fields: (sources) => ({ ... }). Pass a View to link(Order, route). Use a function for an edge whose target is declared later. For exact warehouse membership, set snapshot: true on a named PostgreSQL page read. Its reviewed max bounds the complete result and can be at most 64 rows. Request the first page with page({ size: 20 }).request(). The receiver reads the whole binding once. Pass the returned cursor to the selection’s .after(cursor).read() to serve the next page from the same observation. Acquisition checks that every member is retained. Each page checks that coverage still holds and opens only the member rows it returns. Erasing any captured member invalidates the entire traversal. explain() returns the source cut and the view’s read version. The authenticated cursor binds its position, caller, selection, projection, size, and both read bases. A changed or expired observation requires a new first page. Target fields use the first page’s Bijection version with current admission and source retention. Use browse({ size: 20 }) for independently acquired pages. Advance either selection with .after(cursor) to retain its size and projection. For larger exact populations, link to the indexed rows of a complete typed snapshot copy and read the local selection at a pinned Bijection version. The SDK offers page() on links with a declared exact route. Exact and browse cursors have separate types. The CLI uses the same coordinates.
Use the returned cursor with the same mode, size and projection. Explain reports the serving route and its basis. For a filtered page, it also reports how many candidates the view evaluated and whether it checked range coverage. MCP tools from tools(Customer) read landed answers by default. Set refresh: "stale" to acquire the selected observation and optionally wait. When a selected field needs a key from a pending SQL lookup in the same label, that lookup’s landing can resume the admitted request after the client disconnects. The continuation checks the requester’s standing before asking the next source. Other routes may retry within a bounded window. Read and explain calls use the facts that have already landed. pick narrows field evaluation, its dependencies, and the typed result. A literal selection gives the named fields and the key. A variable array makes fields that may be omitted optional. pick: [] reads only identity and applicable provenance. A read defaults to its served pick when one is declared, or to all view fields. Links return target objects or a page of objects for a many link. A link’s roles are the intersection of the source and target roles. The declaration requires a shared role for an exposed link and checks that the target label flows to the source label. A local many link can declare { max: n }. Bijection installs a guard on the carrier that counts matching rows at commit. For where({ account }) with { max: 2 }, the guard checks the number of rows for that account after all the transaction’s writes. The guard must be able to read the whole group. Omit max to page through a link without a declared cardinality limit. An association can project a target’s typed key with .pick("customer"). A tagged union link takes the full { kind, key } domain. For an external page link, the same arguments select an observation and request its refresh. With no size, both use 20 or the address bound, whichever is smaller. Request the first page with no cursor. After it lands, pass its next cursor with the same key, link and size to request and read the next page. Refresh admission is separate from the page. A continuation can land at a newer warehouse observation and carries that page’s own observed time. Point-in-time lookups continue to read the observations held at their version.

Read plans and objectives

Each generated lookup, find, search, total, and link query has a plan in bijection.lock. A local read uses RTDB facts. Pushdown uses one reviewed receiver statement and can fuse point routes. A key-route plan evaluates bounded joins over landed answers. A landed non-aggregate warehouse point can supply a projected field as the key for another non-aggregate point at a different receiver. A Trino statement that crosses forwards has snapshot coherence only when it uses a dated cut and every crossed forward declares travel. A mixed plan can combine source instants. Query a published dataset explicitly through its own handle. Generated view reads bind keys into the reviewed routes. To change a route, update the declaration and review the new lock before deploying it. Declare objectives on a view or on a serve entry. fresh is the maximum age of a landed observation, volume bounds the population, coherence selects snapshot or mixed, and history is the required retained duration. Use exact: true to require ready answers. Reads use landed answers at their Bijection version. Branch deploy stages the reviewed plans with the candidate Program, and branch review compares them with the installed Program. Landing promotes the candidate and the branch’s writes. Refresh requests staged on the branch run after landing.

Serve a view

serve maintains read-shaped entries in RTDB as identity and contributor facts change. A lookup, find, search, or total entry can declare a pick and objectives. A find entry adds an ordered by list, a search entry adds a text field, and a total entry adds its group and optional sum. The plan covers the entries of its generated read.
A total sums an owned decimal or int contribution. Decimal sums take the contributor’s declared scale. where fixes a group prefix, so { region } and {} both read a [region, segment] group. A declared find shape also answers a count. An undeclared shape refuses TotalMissing, and a sum over a shared contribution refuses NonAdditive. Find, search and total return basis.serve with through and behind for the Bijection version, observed for the oldest observation the read evaluated, and unready for objects still waiting for a landing. populationReady reports whether a complete census has landed. An unavailable filter value counts when the object could match. A direct head query can read the maintained order, rank or count. Pass behind: false for exact coverage. An exact read that encounters an unready object refuses SourceUnready. Mutations and branch or versioned reads use exact coverage. Corpus-relative scores in exact mode need current coverage. Exact find, search and total over landed SQL sources page the current census. They check readiness only for objects and fields that could affect the requested result, within the host’s read and transaction limits. A served population comes from a local identity or a bounded copy of an external identity whose virtual table declares copy: true. A keyed lookup can read landed external answers without creating a population. volume bounds a copy. Above the source’s reviewed page bound, declare travel so every page uses one source cut. The copy becomes visible when all pages have landed, and every source page counts toward the budget. ServePopulation names the route or bound that is missing. When the population uses external fields, the planner derives standing requests from its volume and fresh. It reviews their rate against the warehouse receiver’s budget: { statements: { perHour } }. A virtual table can declare a smaller share with the same shape. To resolve FreshnessInfeasible, increase the interval or budget, narrow the population, or fuse routes. SQL charges the receiving place. Each private member place has its own budget account. Lower-priority requests leave capacity for interactive asks. An exhausted account returns Limit with BudgetExhausted in the message. Member-scoped contributors materialize at their member’s label. Keep each served object within one member. Erasing a contributor or closing its lifetime or lease also closes dependent serving rows. When the selected derivative returns DerivativeBuilding after a closure, exact reads that need it refuse SourceUnready. Other served queries filter closed rows and include observed omissions in basis.serve.unready. If the derivative cannot supply its rows, the query reads a bounded set of visible survivors and reports populationReady: false.

Publish a relational view

Customer.relation({ pick: ["name", "region"], cut: { coherence: "snapshot" } }) gives a typed relation a pipeline can publish as a dataset. Bind each local table to its mirror and each warehouse source to its installed bulk export target, export dataset and reviewed statement digests. Choose coherence: "mixed" explicitly for a source that cannot travel. The pipeline’s target supplies the engine. Publish a view relation Use a relational derive when a computed field must run in that engine.
Relational derive supports literals, fields, arithmetic, comparison, boolean operations, coalesce, and case. A TypeScript callback, a cross-app object point, or logic depending on External state refuses when the relation is used as a pipeline input. A second audience can use Customer.under(label, { allow, sources?, fields? }). Inherited fields share the original write homes. A correction made through the base view also appears in the further audience’s lookup. A field redeclared there keeps its edit, and its terms must admit the stored value type. A tagged union uses view.union({ customer: Customer, supplier: Supplier }, { title }) and keys shaped as { kind, key }. Members over one table require disjoint equality selections. A Customer key is retired while its redirects fact is present: a merge writes that fact and nothing else. A retired key answers null in lookup and leaves the serving population. Its successor leaf follows the declared redirects to a live Customer key, up to 16 hops. It refuses a repeated key. Links leave retired targets absent. The client can call successor separately. The first request for a field can depend on an external binding that has not landed yet. Bijection can resume that admitted request within a bounded task window. Fusion serves eligible same-receiver point routes in one statement.

Reviewed effects

A view action can require one observed aggregate using require: { openExposure: { snapshot: "source", within: { minutes: 5 } } }. The handler receives the plain typed aggregate and its evidence separately. Use reviewedMutation when a caller must confirm a plan before it commits. Build the plan with reviewed.insert, reviewed.replace, reviewed.patch, reviewed.delete, or reviewed.submit. Place the private receipt table alongside the application’s tables. One review call returns the ordered proposed writes and tasks and records their receipt. Call review.rehearse() to exercise commit guards in a discarded world before confirmation. Commit evaluates its guards in the deciding transaction.
The CLI returns the same proposal and receipt.
An MCP server can explicitly publish the same review and commit with actionTools(Customer.actions.approveExposure, { review, commit }). The two tools take the action’s business arguments. The commit tool also takes the review receipt. Commit checks the receipt’s caller, subject, evidence, expiry, and plan in the same transaction that writes the rows, submits tasks and consumes the receipt. A changed row targeted by a replacement, patch or deletion requires a new review. Target delivery settles separately. A lost commit reply can be retried through the same receipt. An evidence request only acquires evidence. Submit a new review after it lands.

Edit and restore

Actions are mutations. They take { key, …args } and pass the handler the key, any declared reads, and fields promised by its evidence. The action lists the fields it edits or retracts in edits. Its commit label must admit its reads and flow to those write homes. An action that writes to a lower home lists the applicable release in releases. The home admits just the actions whose edits name that field. An invariant lowers to one write guard per local table it reads, and every write guard is judged at commit on the state the transaction leaves. An invariant can read fields from another table, a separate edit home or another row of the identity table: a transaction that breaks it across them refuses Forbidden with its message, and one that changes several of its rows and keeps it commits. Invariants refuse InvariantOverSource over external fields, source-owned tables, another app’s object point or a selection other than the identity.
actions.ts
app.ts
The published view mounts its named actions together. The catalog describes actions the caller may attempt, including the argument schema, declared refusals, field edits, and evidence. Invocation checks current authorization and the key. A representative can correct the local name while the amount is still unasked.
An edit of null is present and wins over a fallback. With yields: true, the edit wins while the current fallback matches the value recorded when the edit was made. The fallback must be ready to record that value. A later unknown fallback supplies its unknown state, and sealed content above the audience cannot be used for yield. Customer.edit removes the earlier edit and writes a fresh one. Customer.retract removes the edit so the source can decide again. The removal is blind: it retracts the earlier row at its unique point without reading it, so each edit carries only its own decision’s units, and erasing an earlier edit’s inputs leaves the current one standing. A removal is a closable tombstone that never refuses, so it names no survival. An action above a lower home lists one release to that home, which the fresh row and the removal both name. The roles in erase.allow can invoke the generated Customer.erase({ key }) mutation. It closes the erasable identity, including a present retired identity, and its owned contributions. It closes successor facts and walks up to 256 predecessor keys through the successor table’s indexed target field in the same transaction. A large owned selection is erased in pages: rows past the first page are erased by follow-up tasks whose generated mutation declares its survival (survives:), so each page outlives what the eraser read. Because Customer declares erase, a direct ctx.erase of an account, member erasure or expiry also erases its owned contributions. A view without erase deletes nothing of its own. An ordinary entry guard can protect the eraser, and an authored mutation can call it with ctx.call. A shared contribution can outlive the object. An owned virtual-table route can close its warehouse dataset bucket in the same transaction. Forwarding the erase to the warehouse is designed, not implemented. changes pages the versions at which the object’s fields changed, as the diff of successive lookups. It reads the logs of the object’s points, the carrier selections behind its counts, sums and lists, its edit homes and the history of its external sources. External field values carry the landed observation. Each catalog field gives changes.depth, the shortest contributing history, and the view gives the minimum together with changes.excludes, the fields history cannot follow. Past that depth the call refuses Expired with SourceRetention.

Read and refresh warehouse fields

External values are External<V>. A ready value carries observed. In prefer, an absent row falls through. A present row with a null field supplies the value. The other states are unasked, pending, refused and withheld. Order.lookup answers External<ObjectOf<typeof Order> | null>. A derive that uses an external field uses the first applicable state in the order withheld, refused, unasked, pending. A pending result carries the earliest pending since. Its ready result carries the oldest observation it uses. basis carries each source’s scope, observation time, position, freshness and refusal. A ready coherence: "mixed" object carries the identity’s observed time. An individual input’s cut stays on its own basis entry or field answer. Two independently fresh observations can straddle a transfer from balances (100, 0) to (0, 100) and report (100, 100). Use consistent: "source" for a virtual identity and one fused point chain on the same PostgreSQL receiver. The inputs must be direct, schema-qualified local heap tables using the receiver’s app credential. Lookup returns coherence: "source" and one opaque cut when every reachable point, including an answered absence, shares the receiver-attested snapshot. A missing or different witness refuses with CommonCutMissing even when the picked fields omit that point. Refresh takes the receiver’s current snapshot in this mode. A travelling table can instead refresh a source instant with at. Its receiver must declare skew. The default source instant is the frame entry instant minus that skew. For a timeline source, over selects a window of valid time to land. Reads at a Bijection version continue to see what had landed there. Pass the same selection to useLive from @bijectionhq/library-views/react to watch it and renew demand at head. The hook returns the current result, the admission state in request, and a retry function. When request.state is reported, the report uses the same admission outcomes as calling selection.request() directly. Unmounting releases future demand. On a cold read, show the local name and the amount’s unasked state. Request the selected dependencies, then watch the lookup for the landed value. An accepted request can still be pending. Zero is a ready answer. A ready null means that the source answered without a value for the field. A withheld observation supplies no value. Explain without requesting work at head or at a pinned version. The source explanation also lists the row bound and digest from committed named-read statements when present.
An action can require count and amount from one qualified PostgreSQL aggregate. On a PostgreSQL-backed Customer view, declare the evidence once and give the action that declaration. The Snowflake view above can display landed totals and has no qualified aggregate snapshot witness for this action.
The handler receives ready values. The mutation checks the shared witness and the freshness deadline before the local write. An answer can be fresh enough for display and too old to approve. Handle SourceStale, CommonCutMissing, ObjectUnready, and ObjectUnavailable by code. A permitted recovery names request and its selected fields, age limit, and whether it needs a new cut. The caller can wait for the fresh answer before submitting again. For fresh evidence from a single observation, see ready(ctx, value, { within }) from @bijectionhq/library-sources. ontology(views, { allow }) exposes the catalog to admitted roles. bijection describe ontology reads the ontology catalog at its default path. Pass a different path if the catalog is mounted elsewhere. Focus on an object, field, link or action. The live catalog filters the result under the selected caller. A link description shows how to follow it and an action description shows how to trial and submit it.
--source shows the source-derived view, field, link, action, serve and erase records reviewed in bijection.lock. Focused source JSON includes named records and an explicit origin. explain object --link reads one landed page using the same size and cursor as the link query. Its refresh example appears when the selected caller can request the page at the live head. bijection trial shows proposed writes, queued tasks and the validity deadline. If the action refuses and supplies a recovery, the terminal shows the refresh and watch commands. Requesting evidence and submitting the action are explicit calls. The submission checks the current evidence and authority. Pass { allow, sets: { customerOrders } } to publish an object-set description too. Read it with bijection describe ontology --set customerOrders. tools(customers) derives MCP descriptions for generated view leaves. The inspect tool reads the landed state passively. Publish write tools through an explicit named tool group. The external lookup tool accepts refresh: "stale" | "never" and wait as a duration string. It can hold a public streamed call for up to 20 seconds by default and returns the observation states available when it answers. In a branch the lookup answers without an automatic refresh or wait. A retired key that redirects answers { object: null, successor }. To expose the eraser, add tools({ eraseCustomer: Customer.erase }, { eraseCustomer: "Erase a customer." }) as a named tool group. Its descriptor carries destructiveHint: true.