TypeScript / Node generated SDK¶
The Node package supplies connection and native runtime primitives. Application models, values, managers, and query tokens come from the TypeScript package generated by the canonical Split-YAML workspace.
Install and generate¶
npm install @type-bridge/node
type-bridge --manifest typebridge.yaml schema check
type-bridge --manifest typebridge.yaml schema generate
Configure the generated target in typebridge.yaml:
Compile the generated package with its emitted TypeScript configuration. Do not
edit its sources or construct models with @type-bridge/node factories. The
package privately embeds the verified authority used by its managers and query
sessions; an ordinary Node application does not configure or read an external
JSON authority.
Connect¶
import { RustDatabase } from "@type-bridge/node";
const db = RustDatabase.connect("localhost:1729", "application", {
username: "admin",
password: "password",
httpPort: 8000,
});
Database lifecycle and credentials remain application-owned. Schema mutation is performed by explicit workspace migration commands, not model import.
Construct generated values¶
import {
Age,
Employment,
Person,
PersonId,
} from "./generated/typescript/dist/index.js";
const ada = Person.create({
personId: PersonId.create("ada"),
age: Age.create(36n),
});
Generated values are immutable. Integer attributes use JavaScript bigint so
the TypeDB integer domain is not silently truncated. Decimal and duration values
use their lossless generated boundary representations.
Schema fields and roles that collide with generated runtime members receive a
trailing underscore in the canonical projection: a key physically named name
is accessed as name_, and a role named reference becomes reference_.
Use these same names in construction, references, field/role tokens, and hydrated
values. Physical schema labels and key identity stay unchanged; existing
non-colliding projected names stay unchanged.
Unbounded role and list cardinalities accept any count at or above their declared minimum. Finite maxima and optional zero cardinality remain enforced.
After upgrading the generator and compatible runtime, regenerate the complete package. Projection and package fingerprints are recomputed from the corrected names and runtime resources; semantic schema fingerprints remain unchanged.
Managers¶
const manager = Person.manager(db);
const stored = manager.put(ada);
const people = manager.filter({ age__gte: Age.create(18n) }).all();
if (stored.iid !== null) {
const replacement = Person.create({
personId: PersonId.create("ada"),
age: Age.create(37n),
});
manager.update(stored.iid, replacement);
}
Generated entity and relation managers expose insert, insertMany, put,
putMany, immutable replacement update, delete, getByIid, filter,
all, first, count, and exists.
Packages whose schema uses ordered collections select the successor manager and
also expose atomic updateMany and deleteMany. Updates are readonly
[iid, replacement] tuples; deletes accept canonical IID strings. Insert, put,
and update batches return frozen values in input order, while delete returns no
affected-row count:
if (stored.iid !== null) {
const replacements = [
[stored.iid, Person.create({
personId: PersonId.create("ada"),
age: Age.create(38n),
})],
] as const;
const updated = manager.updateMany(replacements);
manager.deleteMany(replacements.map(([iid]) => iid));
}
Legacy unordered packages retain their existing manager surface and runtime resource exactly; regenerate from an ordered schema to use the successor batch methods.
The successor manager also exposes immutable, token-branded canonical filters:
const threshold = Person.manager(db)
.where(Person.fields.age, "gte", Age.create(18n));
const adults = threshold.all();
const ada = Person.manager(db)
.where(Person.fields.personId, "eq", PersonId.create("ada"))
.first();
Each where returns a reusable sibling. Canonical filters accept only generated
field tokens, exact generated values, and eq, ne, lt, lte, gt, or
gte; Boolean ordering rejects before I/O. Their first requires equality for
every effective reference-key field and proves optional singularity. The
object-based filter(...) API remains available for compatibility lookups and
keeps its existing arbitrary-first behavior.
Filter keys use generated TypeScript field names plus optional __eq, __ne,
__gt, __gte, __lt, or __lte suffixes. Use a trailing __eq when a
generated field name itself collides with a lookup suffix.
Relations¶
const employment = Employment.create({
employee: stored,
employer: acme,
});
Employment.manager(db).insert(employment);
The constructor admits only generated player types allowed by the canonical
plays facts. Generated reference values can supply an existing IID/key without
hydrating a complete player.
Queries¶
import { QuerySession } from "./generated/typescript/dist/index.js";
const session = new QuerySession(db);
const person = session.exact(Person);
const employmentVar = session.exact(Employment);
const adult = person.field(Person.age).gte(Age.create(18n));
const employee = employmentVar.role(Employment.employee).connects(person);
const rows = await session
.query(person, employmentVar)
.where(adult, employee)
.rows({ limit: 100n });
QuerySession(connection, { resources, cancellation, queryLimits }) runs on a
direct RustDatabase or transaction, or on a proxy connection (see
Proxy queries). Composition is synchronous and performs no
I/O. Every terminal (one, first, rows, pageBy, countBy, existsBy,
aggregate, grouped aggregate) returns a Promise on every connection;
direct terminals run off the JavaScript thread, so they do not block the event
loop.
The generated query facade supports exact/subtype bindings, owner-aware fields and roles, comparison/string/Boolean predicates, explicit cross joins, bounded reachability, positional/named/collected shapes, ordering, windows, pages, counts, existence, and direct reducers/grouping.
const left = session.exact(Person);
const right = session.exact(Person);
const pairs = await session
.query(left, right)
.allowCrossJoin(left, right)
.rows({ limit: 10n });
Transactions¶
const transaction = db.transaction("write");
try {
const person = Person.manager(transaction).put(ada);
Employment.manager(transaction).insert(
Employment.create({ employee: person, employer: acme }),
);
transaction.commit();
} catch (error) {
transaction.rollback();
throw error;
}
A successful rollback() keeps the transaction usable. You can execute more
work and commit it; call close() to end it without committing.
Generated managers never commit a caller-owned transaction. Close read transactions after their final query terminal.
Staged transactions and plans¶
A plan is one typed query-plan/v3 pipeline: a match with comparisons and
let values, then updates, inserts, puts and deletes. A staged transaction
queues plans and runs them all at commit, in order, as one TypeDB
transaction. Nothing opens before commit, and a plan that matches no row
writes nothing, so one plan is a complete conditional write. Which writes
make it race-safe is in Concurrency and conditional writes.
The one-query purchase checks the stock and the balance, takes the item and the price, and records the purchase:
import { Plan, type RustDatabase } from "@type-bridge/node";
import {
Account,
Item,
Purchase,
schemaAuthority,
} from "./generated/typescript/dist/index.js";
function purchase(order: string, itemId: string, accountId: string): Plan {
const plan = Plan.builder();
const item = plan.exact(Item);
const buyer = plan.exact(Account);
const orderInput = plan.input("order_id", "string");
const itemInput = plan.input("item_id", "string");
const accountInput = plan.input("account_id", "string");
const itemKey = plan.field(item, Item.itemId);
const buyerKey = plan.field(buyer, Account.accountId);
const stock = plan.field(item, Item.stock);
const price = plan.field(item, Item.price);
const balance = plan.field(buyer, Account.balance);
plan
.where(itemKey.eq(itemInput))
.where(buyerKey.eq(accountInput))
.where(stock.gt(0n))
.where(balance.ge(price));
const nextStock = plan.let("next_stock", stock.sub(1n));
const nextBalance = plan.let("next_balance", balance.sub(price));
plan.update(item, Item.stock, nextStock).update(buyer, Account.balance, nextBalance);
plan
.insert(Purchase)
.field(Purchase.orderId, orderInput)
.player(Purchase.buyer, buyer)
.player(Purchase.item, item);
plan.row([orderInput.value(order), itemInput.value(itemId), accountInput.value(accountId)]);
return plan.build(schemaAuthority());
}
async function buy(db: RustDatabase): Promise<boolean> {
await using tx = db.stagedTransaction();
const bought = tx.stage(purchase("O1", "I1", "A1"));
await tx.commit();
// `{ kind: "matched", value: 0 }`: out of stock or short of funds; nothing was written.
const answer = bought.get();
return answer.kind === "matched" && answer.value === 1;
}
The builder takes the generated model, field and role tokens, so a field of
another model does not type-check. schemaAuthority() is the generated
package's embedded authority; a QueryV2Authority over declared-schema bytes
works too. Builder calls never throw on content: build throws the first
invalid call (an invalid literal, a reused name, a field the thing does not
own, a key update) as a QueryV2Error. Nothing is checked against TypeDB
until commit. Literals are string, bigint (long) and boolean values,
or the typed helpers (double(1.5), decimal("1.25"), date(...)); a
plain number is not a literal.
- Reads. A plan without writes answers
{ kind: "rows" }of the columns passed toreturning, orcount()/exists(). - Writes. A write plan answers
{ kind: "matched", value }, the number of rows its pipeline wrote, or withreturning([...])the rows from the same pipeline. - Batches. Each
rowbinds the inputs once; many rows run the one plan over all of them. - Expressions.
lettakesadd,sub,mul,divandmodover values, inputs and literals, andPlanExpr.pow,abs,ceil,floor,round,min,maxandlength. - Answers. Each
stagereturns aPendingPlanAnswer;get()resolves after a successful commit. A failed commit stores nothing and rejects with aQueryV2Errorwhosecodeandfailurename the typed outcome; every answer of that commit throws the same failure. - Kinds.
db.stagedTransaction("read" | "write" | "schema")fixes the kind; without one, a staged write makes itwrite.readrefuses write plans andschemarefuses every plan. - Reuse.
rollback()discards the queued plans and keeps the transaction;close()ends it. TypeScript never commits implicitly:await usingcloses the transaction at scope exit without committing (Node 18.18 or newer, and TypeScript 5.2 or newer or@types/nodefor theusingdeclaration).
RustDatabase.transaction(kind) keeps its released meaning, the eager
RustTransactionContext the generated managers and query sessions run on;
the staged transaction is stagedTransaction(kind). Generated managers do
not stage plans yet.
Building is deterministic and shared with the Rust, Python and C builders:
handles are numbered in creation order, match terms keep their call order,
consecutive writes of one kind share a stage, and names come from labels
(item, item_stock). The same program has the same canonical plan bytes
(plan.canonicalBytes()) in every language.
Proxy queries¶
A proxy connection runs the same program against a TypeBridge server. Only the connection changes:
import {
ExchangeConnection,
Person,
QueryExecutionResourceLimits,
QuerySession,
connectProxy,
} from "./generated/typescript/dist/index.js";
// The built-in HTTP route to the server's /v2/capabilities and /v2/query.
const proxy = await connectProxy("https://typebridge.example", {
headers: [["Authorization", `Bearer ${token}`]],
});
const session = new QuerySession(proxy);
// Or a host-owned transport that routes and authenticates itself.
const hosted = new QuerySession(
new ExchangeConnection(advertisementBytes, exchange),
{ resources: new QueryExecutionResourceLimits({ items: 100n }) },
);
const person = session.exact(Person);
const rows = await session.query(person).rows({ limit: 50n });
Both connections use the package's privately embedded, verified Query V2
authority; no authority file or QueryV2Authority is passed. connectProxy
fetches the server advertisement over the configured TLS mode (tls,
tlsRootCa), or takes a pinned advertisement; headers carries caller
authentication. It follows no redirects. ExchangeConnection takes
advertisement bytes that came from the intended server over authenticated TLS
or were pinned out of band, and an exchange(request, signal?) function that
performs one request and resolves to the exact reply bytes; the host owns the
HTTP client, credentials, and retry policy. Either takes answerLimits, the
ceiling every session on the connection runs under.
Each terminal performs one exchange and hydrates the same generated classes and scalar groups as direct execution.
Writes cross the proxy as staged transactions.
await ProxyConnection.transaction(kind) returns a StagedTransaction, the
class RustDatabase.stagedTransaction(kind) returns for direct staging
(see Staged transactions and plans).
tx.stage(plan) queues a built plan (tx.stagePlan(bytes, declaredSchema)
queues canonical plan bytes), and
await tx.commit() sends the staged stack as one
typebridge.query-remote-request/v3 envelope to POST /v3/staged. The reply
is signed and verified before any answer resolves; answers and typed failures
match direct execution, and commit_outcome_unknown stays unknown. The proxy
keeps no replies: a dropped or unverifiable reply rejects with
commit_outcome_unknown, the writes may have applied, and the caller reads the
database to find out. Every other signed refusal keeps its code and applied
nothing. The /v3/capabilities advertisement must name the same
executor and reply key as the connection's advertisement
(query_remote_v3_advertisement_mismatch otherwise); pin it with the
stagedAdvertisement connect option. Writes need a caller the server's
interceptor vouches for, or a server that allows unauthenticated staged writes;
otherwise the commit fails with staged_write_not_authorized. See the
staged remote envelope.
Runtime boundary¶
@type-bridge/node no longer serves as a model factory, schema parser, or
programmatic generator. The generated package installs canonical projection
bytes into the native runtime and native class identity checks reject
structural lookalikes or values from another generated package.
Packaging note¶
Generated TypeScript packages require @type-bridge/node 2.1 or newer within
the 2.x line. The npm package publishes native modules for Linux glibc
(x64/arm64), macOS (x64/arm64), and Windows (x64/arm64); other
targets build from source and must satisfy the repository toolchain.
Provider query and commit errors expose readonly error.failure data on
QueryV2Error: phase, reason, lock_kind, annotation, op_index,
retry_safe and the TypeDB code. Rust classifies these fields; TypeScript
only forwards them. A safe retry reruns the complete transaction on a new
snapshot. An unknown commit outcome requires reconciliation before retry.