TypeScript / JavaScript

TypeScript API

Common JavaScript and TypeScript API for native Node and WebAssembly.

This documentation covers the @maelys-dev/datalog npm package at v0.27.0 (published release), including its native Node and WebAssembly entry points and TypeScript declarations. Install the package.

Reference by topic

Each detailed method card sits with its owning class. These topic pages show how the operations work together.

Detailed API

engine reference

NameSummary
Engine class (1 field)The root owner of independent rulesets and their descendants. Create it with Engine.create(); close releases its full resource tree.
EngineOptions interface (3 fields)Select the size profile and optionally locate a matching WASM factory and binary.
ManifestOptions interface (2 fields)Explicit permissions for test-only policies and undeclared source atoms; hashes remain verified.
ManifestInput aliasLoad a filesystem path in native Node, or a manifest and source bundle in either runtime.
Engine.limits propertyBuild limits for this engine profile.
Engine.create() methodInitialize a fresh engine for the selected runtime and profile.
engine.registerDomain() methodCopy predicate declarations and allowed source atoms into the engine registry.
engine.loadInlineRuleset() methodCompile one source policy against an already registered domain.
engine.loadManifest() methodValidate and load enabled policies from a manifest, including source hashes and permissions.
engine.close() methodRelease this resource and its owned descendants. Closing is idempotent.
using engine protocolLeave the scope to close this Engine, all of its rulesets and their sessions, results and input buffers.
EngineOptions.profile? propertySMALL by default; LARGE has independently compiled bounds.
EngineOptions.wasmFactory? propertyOptional factory from the same artifact set as the selected binary.
EngineOptions.wasmUrl? propertyOptional URL for the matching WASM binary.
ManifestOptions.allowTestOnly? propertyPermit policies marked test_only; disabled by default.
ManifestOptions.allowUndeclaredPolicyAtoms? propertyPermit undeclared source atoms; disabled by default.

Guides: Stable quickstart · Manifest loading · Full program

wasm-integration reference

NameSummary
WasmModule interface (1 field)The factory module contract used by the WASM transport. Application code normally lets Engine.create load it.
WasmModule.HEAPU8 propertyCurrent byte view of WASM memory; reacquire it after memory growth.
module.ccall() methodInvoke a named C export through the Emscripten module.
module._malloc() methodReserve a buffer in the module linear memory.
module._free() methodRelease a buffer previously reserved in this module.

Guides: Runtime selection and installation · Full program

predicate reference

NameSummary
Predicate class (3 fields)A predicate name, arity and flag set. Creating this value does not register a domain.
Predicate.name propertyDeclared predicate name.
Predicate.arity propertyNumber of ordered terms (zero through four).
Predicate.flags propertyBitwise combination of predicate flags.
Predicate.edb() methodCreate a runtime-input predicate declaration.
Predicate.edbQuery() methodCreate a queryable runtime-input predicate declaration.
Predicate.idb() methodCreate a derived predicate declaration.
Predicate.idbQuery() methodCreate a queryable derived predicate declaration.
Predicate.policyFact() methodCreate a source-fact predicate declaration.
Predicate.policyFactQuery() methodCreate a queryable source-fact predicate declaration.
new Predicate() constructorDescribe a predicate using an explicit combination of flags.
PRED_EDB constantPredicate flag for application-supplied runtime facts.
PRED_IDB constantPredicate flag for derived facts.
PRED_QUERY constantPredicate flag permitting public ground queries and enumeration.
PRED_POLICY_FACT constantPredicate flag for facts written in policy source.

Guides: Registries and Predicates · Declare the document-access vocabulary · Registry scope

rulesets reference

NameSummary
Ruleset class (2 fields)An immutable loaded policy set that owns its EDBs, sessions and results.
ProgramCounts interface (3 fields)Immutable counts of one compiled policy, independent of request facts and session quotas.
Ruleset.policyCount propertyNumber of loaded policies.
Ruleset.fingerprint propertySemantic fingerprint of the policy selection.
ruleset.programCounts() methodRead the predicate, policy-fact and normalized-rule counts of a selected policy without preparing a session.
ruleset.edb() methodReserve a reusable bounded input buffer owned by this ruleset.
ruleset.prepare() methodReserve reusable execution storage for the selected policy before request processing.
ruleset.solve() methodEvaluate an EDB using a private session owned by the returned result.
ruleset.close() methodRelease this resource and its owned descendants. Closing is idempotent.
using ruleset protocolLeave the scope to close this Ruleset and its sessions, results and input buffers.
ProgramCounts.predicates propertyCompiled predicate declarations, including unused registry declarations.
ProgramCounts.facts propertyFacts compiled from policy source, excluding request EDB facts.
ProgramCounts.rules propertyNormalized compiled rules, including expanded OR alternatives.
ruleset.readsPredicate() methodChecks whether the selected compiled policy reads a named predicate in its rule body, without preparing a session.

Guides: Ruleset usage guide · Compile once, keep ownership explicit · Objects created from a ruleset

Edb reference

NameSummary
Edb class (2 fields)Reusable bounded runtime input belonging to one ruleset.
Fact interface (2 fields)One predicate and its ordered input terms, staged atomically with its batch.
EdbOptions interface (2 fields)Fixed input fact and text bounds, independent of the prepared session quotas.
EdbUsage interface (3 fields)Current input occupancy and its reserved text capacity.
InputValue aliasA runtime input symbol, exact signed 64-bit integer, or boolean. Unsafe numeric inputs are rejected.
Value aliasA resolved output value; integers always use bigint.
Edb.count propertyNumber of raw facts stored in this EDB.
Edb.usage propertyCurrent input fact and text occupancy.
edb.addFact() methodAppend one typed fact to mutable input.
edb.addFacts() methodStage a whole batch and append it atomically; rejection preserves existing input.
edb.clear() methodEmpty mutable input while retaining its storage.
edb.reset() methodEmpty and unfreeze input for a new request; existing results retain their snapshots.
edb.close() methodRelease this resource and its owned descendants. Closing is idempotent.
using edb protocolLeave the scope to close this input buffer; its Ruleset remains open.
Fact.predicate propertyPredicate name for this input fact.
Fact.terms propertyOrdered input values; integer numbers must be safe integers.
EdbOptions.factCapacity? propertyMaximum raw facts stored in the EDB, including repeated facts.
EdbOptions.textCapacity? propertyReserved bytes for interned input text including terminators.
EdbUsage.facts propertyNumber of raw facts currently stored.
EdbUsage.textBytes propertyUsed text bytes, or the explicit session text quota in capacity options.
EdbUsage.textCapacity propertyReserved bytes for interned input text including terminators.

Guides: EDB and input facts guide · Give each request an explicit input buffer · Clear, reset and result snapshots

Session reference

NameSummary
SessionCapacities class (4 fields)Validated portable quotas between zero and UINT32_MAX; omitted fields retain engine defaults.
Session class (3 fields)A prepared execution context with fixed capacities and at most one live result.
CapacityOptions interface (4 fields)Fixed per-session quotas. An omitted quota uses the profile default; zero is an explicit request.
SessionOptions interface (5 fields)Select a policy and the capabilities, work budget, capacities and explanation storage required before solving.
Capability object (12 fields)Backend feature requirements. These bits are separate from explanation workspace kinds.
ExplanationKind object (2 fields)Optional explanation workspace kinds, combined with bitwise OR.
SessionCapacities.inputFacts? propertyMaximum session input facts.
SessionCapacities.derivedFacts? propertyMaximum session derived facts.
SessionCapacities.symbols? propertyMaximum session symbols.
SessionCapacities.textBytes? propertyUsed text bytes, or the explicit session text quota in capacity options.
new SessionCapacities() constructorValidate explicit fixed session quotas.
Session.capacities propertyEffective fixed capacities, or requested optional quotas when preparing a session.
Session.fingerprint propertySemantic fingerprint of the policy selection.
Session.executionFingerprint propertyFingerprint incorporating execution configuration.
session.inputs() methodAttach retained dynamic input before this session's first successful solve. The binding allocates its storage; ordinary solve is unavailable while it remains attached.
session.solve() methodEvaluate an EDB from the same ruleset using this prepared session. Ordinary solve is unavailable while retained input is attached.
session.close() methodRelease this resource and its owned descendants. Closing is idempotent.
using session protocolLeave the scope to close this Session and its active result.
CapacityOptions.inputFacts? propertyMaximum session input facts.
CapacityOptions.derivedFacts? propertyMaximum session derived facts.
CapacityOptions.symbols? propertyMaximum session symbols.
CapacityOptions.textBytes? propertyUsed text bytes, or the explicit session text quota in capacity options.
SessionOptions.policyIndex? propertyZero-based policy selection; defaults to zero.
SessionOptions.requiredCapabilities? propertyRequired backend capability bits; unsupported requests fail preparation.
SessionOptions.workLimit? propertyRequested work budget; a backend without this capability rejects a nonzero limit.
SessionOptions.explanations? propertyOptional TRUE/FALSE workspace mask; zero reserves no workspace.
SessionOptions.capacities? propertyEffective fixed capacities, or requested optional quotas when preparing a session.
Capability.POSITIVE propertyPositive rule evaluation capability bit.
Capability.NEGATION propertyStratified negation capability bit.
Capability.COMPARISONS propertyTyped comparisons capability bit.
Capability.ARITHMETIC propertyArithmetic capability bit.
Capability.FILTERS propertyFilters capability bit.
Capability.EXPLAIN_TRUE propertyWhy-true explanations capability bit.
Capability.WORK_LIMIT propertyBounded work admission capability bit.
Capability.EXPLAIN_FALSE propertyWhy-false explanations capability bit.
Capability.AGGREGATES propertyAggregate support capability bit.
Capability.MIN propertyMinimum aggregates capability bit.
Capability.MAX propertyMaximum aggregates capability bit.
Capability.SUM propertySum aggregates capability bit.
ExplanationKind.TRUE propertyReserve Why-true workspace.
ExplanationKind.FALSE propertyReserve Why-false workspace.

Guides: Session and solving guide · Prepare storage and reuse it across requests · Preparation options

Session inputs reference

NameSummary
InputBase class (2 fields)An exact unsigned 64-bit incarnation and generation token for retained input.
InputOptions interface (4 fields)Optional fixed capacities and additional vocabulary for retained input storage, independent of session quotas.
SessionInputs class (1 field)Retained dynamic input attached to a prepared session; compiled policy facts remain separate.
InputBase.incarnation propertyIdentifies this retained-input attachment.
InputBase.generation propertyIdentifies its current committed input generation.
new InputBase() constructorConstruct an exact retained-input base token from its two unsigned 64-bit components.
InputOptions.factCapacity? propertyMaximum retained input facts; defaults to the session input-fact quota.
InputOptions.additionCapacity? propertyMaximum raw additions per apply call; defaults to factCapacity.
InputOptions.removalCapacity? propertyMaximum raw removals per apply call; defaults to factCapacity.
InputOptions.symbols? propertyAdditional strings admitted to the immutable program vocabulary.
SessionInputs.base propertyCurrent committed retained-input base token.
retained.replace() methodReplace all retained input and return its solved snapshot.
retained.apply() methodApply retained-input changes and return their solved snapshot.
retained.close() methodRelease retained input after closing its live result.
using retained protocolLeave the scope to close retained input after its live result has been closed.

Guides: Session preparation

querying reference

NameSummary
ResultTerm class (2 fields)A result-bound term whose symbol identity can only be resolved while its owner is alive.
SolveResult class (2 fields)A leased result snapshot supporting queries, enumeration and canonical explanations.
ResultTerm.kind propertyWhether the term is a symbol, integer, or boolean.
ResultTerm.value propertyA symbol ID local to its result, or a typed integer/boolean value.
term.resolve() methodCopy the typed value from this result-bound term.
SolveResult.fingerprint propertySemantic fingerprint of the policy selection.
SolveResult.executionFingerprint propertyFingerprint incorporating execution configuration.
result.containsFact() methodCheck membership of a ground fact exposed by the domain query flags.
result.derivedFactCount() methodCount all derived facts in the retained result.
result.enumeratePredicateFacts() methodCopy resolved values for one queryable predicate and arity.
result.enumerateRaw() methodRead immutable terms whose symbol identities remain bound to this result.
result.resolveTerm() methodResolve a term owned by this same live result into a copied value.
result.explainTrue() methodProduce the canonical Why-true document for a ground fact.
result.explainFalse() methodProduce the canonical Why-false document for a ground fact.
result.close() methodRelease the result lease and its private convenience session, if any. Closing is idempotent.
using result protocolLeave the scope to close this result; externally owned sessions, rulesets and input buffers remain open.

Guides: Querying guide · Membership and enumeration · Copied values and result-bound terms · Explain a decision explicitly

errors reference

NameSummary
MaelysDatalogError exception (3 fields)An operation failure with its status and an immutable copied diagnostic.
Limits interface (14 fields)Build-time engine bounds for the selected SMALL or LARGE profile.
Diagnostic interface (18 fields)An immutable copied diagnostic. Optional fields appear only when the engine supplies their presence bits.
Status object (15 fields)Stable operation status values. A false query answer is successful and is not an error status.
MaelysDatalogError.code propertyAlias of the operation status on MaelysDatalogError; diagnostic.code is the separate engine diagnostic code.
MaelysDatalogError.status propertyStable numeric operation status.
MaelysDatalogError.diagnostic propertyImmutable copied structured diagnostic.
new MaelysDatalogError() constructorConstruct an error carrying the failed operation, status and diagnostic.
Limits.maxSymbols propertyMaximum interned symbols.
Limits.stringPoolBytes propertyBytes in the engine string pool.
Limits.maxPredicates propertyMaximum registered predicates.
Limits.maxRules propertyMaximum compiled rules.
Limits.maxArity propertyMaximum predicate arity.
Limits.maxBodyLiterals propertyMaximum literals in one rule body.
Limits.maxDepth propertyMaximum supported engine depth.
Limits.maxEdbFacts propertyMaximum runtime input facts.
Limits.maxIdbFacts propertyMaximum derived facts.
Limits.maxFactsPerPred propertyMaximum facts per predicate.
Limits.maxStringBytes propertyMaximum bytes in one string.
Limits.inputEdbTextBytes propertyDefault text capacity of the input buffer.
Limits.maxPolicyAtoms propertyMaximum declared policy-source atoms.
Limits.maxPolicyAtomBytes propertyMaximum UTF-8 bytes across policy atoms, excluding NUL terminators.
Diagnostic.status propertyStable numeric operation status.
Diagnostic.source propertyNumeric diagnostic source.
Diagnostic.code propertyNative diagnostic code; distinct from the operation status.
Diagnostic.present propertyPresence-bit mask describing available structured fields.
Diagnostic.phase propertyPhase during which the operation failed.
Diagnostic.message propertyHuman-readable diagnostic detail copied from the engine.
Diagnostic.hint propertySuggested corrective action when supplied.
Diagnostic.codeName propertyStable diagnostic code name.
Diagnostic.statusName propertyStable operation status name.
Diagnostic.location? propertyOptional source file, line and column.
Diagnostic.predicate? propertyOptional predicate name and arity.
Diagnostic.capacity? propertyOptional attempted value and applicable bound, with its numeric budget kind and, when supplied, its public budget name.
Diagnostic.depth? propertyOptional observed depth and bound.
Diagnostic.comparison? propertyOptional operand kinds and comparison outcome.
Diagnostic.arity? propertyOptional expected and observed arity and term index.
Diagnostic.rule? propertyOptional rule identifier.
Diagnostic.aggregate? propertyOptional aggregate operation, exact textual operand and bound.
Diagnostic.context? propertyOptional token, field and domain context.
Status.OK propertyOperation succeeded.
Status.INVALID_ARGUMENT propertyMalformed argument.
Status.INVALID_FIELD propertyInvalid field or typed value.
Status.NOT_FOUND propertyRequested item or explanation symbol not found.
Status.NOT_IMPLEMENTED propertyOperation not implemented.
Status.UNSUPPORTED propertyUnsupported capability or operation.
Status.TIMEOUT propertyOperation timed out.
Status.IO propertyInput/output failure.
Status.INTERNAL propertyInternal operation failure.
Status.UNAUTHORIZED propertyAuthentication required.
Status.FORBIDDEN propertyPermission or manifest policy rejects the operation.
Status.RATE_LIMITED propertyRate limit reached.
Status.PAYLOAD_TOO_LARGE propertyContent exceeds an engine bound.
Status.INVALID_STATE propertyResource is closed or its current lease prevents the operation.
Status.STORAGE_TOO_SMALL propertySupplied storage is insufficient.

Guides: Errors guide · Separate answers from failures · Correct the cause before retrying The Python alignment concerns capabilities and ownership: independent rulesets, bounded inputs, prepared sessions, result lifetimes, manifests, diagnostics and canonical explanations. JavaScript names use camelCase, returned integers use bigint, and initialization is asynchronous. Filesystem manifest loading is available in the native entry point; both runtimes accept an in-memory bundle. The common API does not expose custom native backends or window adapters.

Interfaces

Interfaces describe object shapes accepted or returned by the API. Follow each link to its detailed definition on the corresponding topic page.

Interfaces and implementations

The published declaration records explicit implements clauses. TypeScript also accepts objects by structure, so this list cannot enumerate every object or external class that satisfies an interface.

Engine class

The Engine class and all its method fiches are together on one page.

Usage and examples

One API, two runtimes

The package is a distribution unit. WASM and a native Node addon are execution choices within that package. Both expose the same Engine, Ruleset, Edb, Session and SolveResult classes, types and lifecycle from the first version of this new API.

Entry pointExecutionTypical use
@maelys-dev/datalog/nodeNative Node-API addon with the engine compiled inNode applications and Node worker threads
@maelys-dev/datalog/wasmWebAssemblyBrowser applications, module workers, or Node
@maelys-dev/datalogConditional export: native in Node, WASM for the browser conditionApplications whose bundler resolves the intended environment

Native artifacts support Linux x64 and ARM64 with glibc 2.34 or newer, and macOS ARM64 13.5 or newer. Node 22, 24 and 26 are tested. Windows, musl/Alpine and macOS x64 require the explicit WASM entry point. Both runtimes offer the SMALL and LARGE profiles. JavaScript and TypeScript use the same implementation; TypeScript adds compile-time declarations, not another engine. The native addon carries its engine and does not require an application to locate a separately installed shared library.

Install the published package

The package is published in GitHub Packages. Configure the scope and a token with package read access in your npm configuration:

CODE
@maelys-dev:registry=https://npm.pkg.github.com
//npm.pkg.github.com/:_authToken=${GITHUB_TOKEN}

Install the package version matching this site's engine:

CODE
npm install @maelys-dev/datalog@0.27.0

Choose one import for the application:

CODE
// Native Node, ESM:
import { Engine, Predicate } from '@maelys-dev/datalog/node'

// Browser/module worker, or an explicit WASM choice in Node:
// import { Engine, Predicate } from '@maelys-dev/datalog/wasm'

const engine = await Engine.create({ profile: 'small' })
try {
  console.log(engine.limits.maxEdbFacts)
} finally {
  engine.close()
}

CommonJS applications use require('@maelys-dev/datalog/node') and await Engine.create() inside an async function. After initialization, engine calls are synchronous. In a browser without a bundler, import the package's src/wasm.mjs by URL and serve its src and wasm directories together. wasmUrl can select the matching binary's URL; it does not replace the required JavaScript module. Keep the factory, binary and declarations from one build. Custom factory integrations can consult the WASM module contract.

Use a module worker for expensive browser evaluations. Create and close the Engine inside that worker; send application data and copied answers across the message boundary. Native calls are serialized across Node workers that load the same addon, so moving work off an event loop is not a promise of parallel solves.

Moving from the retired wrapper

Retired wrapperPublished shared API
One active MaelysPlayground policy/session/resultExplicit Ruleset, Edb, Session and SolveResult objects
pg.loadPolicy(domain, id, source)engine.loadInlineRuleset(domain, id, source) returns a ruleset
pg.addFacts(facts)input.addFacts(facts) on an EDB owned by that ruleset
pg.solve()session.solve(input) returns a result
pg.query(...), pg.enumerate(...)result.containsFact(...), result.enumeratePredicateFacts(...)
pg.freeResult()result.close()
Clear the wrapper's inputinput.reset() starts a fresh request, including after a successful solve
pg.buildLimits()engine.limits

These are changes in ownership as well as naming. Closing a ruleset closes its inputs, sessions and results. Keep it alive while those objects are used, and keep result objects local to the session that created them.