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
| Name | Summary |
|---|---|
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 alias | Load a filesystem path in native Node, or a manifest and source bundle in either runtime. |
Engine.limits property | Build limits for this engine profile. |
Engine.create() method | Initialize a fresh engine for the selected runtime and profile. |
engine.registerDomain() method | Copy predicate declarations and allowed source atoms into the engine registry. |
engine.loadInlineRuleset() method | Compile one source policy against an already registered domain. |
engine.loadManifest() method | Validate and load enabled policies from a manifest, including source hashes and permissions. |
engine.close() method | Release this resource and its owned descendants. Closing is idempotent. |
using engine protocol | Leave the scope to close this Engine, all of its rulesets and their sessions, results and input buffers. |
EngineOptions.profile? property | SMALL by default; LARGE has independently compiled bounds. |
EngineOptions.wasmFactory? property | Optional factory from the same artifact set as the selected binary. |
EngineOptions.wasmUrl? property | Optional URL for the matching WASM binary. |
ManifestOptions.allowTestOnly? property | Permit policies marked test_only; disabled by default. |
ManifestOptions.allowUndeclaredPolicyAtoms? property | Permit undeclared source atoms; disabled by default. |
Guides: Stable quickstart · Manifest loading · Full program
wasm-integration reference
| Name | Summary |
|---|---|
WasmModule interface (1 field) | The factory module contract used by the WASM transport. Application code normally lets Engine.create load it. |
WasmModule.HEAPU8 property | Current byte view of WASM memory; reacquire it after memory growth. |
module.ccall() method | Invoke a named C export through the Emscripten module. |
module._malloc() method | Reserve a buffer in the module linear memory. |
module._free() method | Release a buffer previously reserved in this module. |
Guides: Runtime selection and installation · Full program
predicate reference
| Name | Summary |
|---|---|
Predicate class (3 fields) | A predicate name, arity and flag set. Creating this value does not register a domain. |
Predicate.name property | Declared predicate name. |
Predicate.arity property | Number of ordered terms (zero through four). |
Predicate.flags property | Bitwise combination of predicate flags. |
Predicate.edb() method | Create a runtime-input predicate declaration. |
Predicate.edbQuery() method | Create a queryable runtime-input predicate declaration. |
Predicate.idb() method | Create a derived predicate declaration. |
Predicate.idbQuery() method | Create a queryable derived predicate declaration. |
Predicate.policyFact() method | Create a source-fact predicate declaration. |
Predicate.policyFactQuery() method | Create a queryable source-fact predicate declaration. |
new Predicate() constructor | Describe a predicate using an explicit combination of flags. |
PRED_EDB constant | Predicate flag for application-supplied runtime facts. |
PRED_IDB constant | Predicate flag for derived facts. |
PRED_QUERY constant | Predicate flag permitting public ground queries and enumeration. |
PRED_POLICY_FACT constant | Predicate flag for facts written in policy source. |
Guides: Registries and Predicates · Declare the document-access vocabulary · Registry scope
rulesets reference
| Name | Summary |
|---|---|
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 property | Number of loaded policies. |
Ruleset.fingerprint property | Semantic fingerprint of the policy selection. |
ruleset.programCounts() method | Read the predicate, policy-fact and normalized-rule counts of a selected policy without preparing a session. |
ruleset.edb() method | Reserve a reusable bounded input buffer owned by this ruleset. |
ruleset.prepare() method | Reserve reusable execution storage for the selected policy before request processing. |
ruleset.solve() method | Evaluate an EDB using a private session owned by the returned result. |
ruleset.close() method | Release this resource and its owned descendants. Closing is idempotent. |
using ruleset protocol | Leave the scope to close this Ruleset and its sessions, results and input buffers. |
ProgramCounts.predicates property | Compiled predicate declarations, including unused registry declarations. |
ProgramCounts.facts property | Facts compiled from policy source, excluding request EDB facts. |
ProgramCounts.rules property | Normalized compiled rules, including expanded OR alternatives. |
ruleset.readsPredicate() method | Checks 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
| Name | Summary |
|---|---|
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 alias | A runtime input symbol, exact signed 64-bit integer, or boolean. Unsafe numeric inputs are rejected. |
Value alias | A resolved output value; integers always use bigint. |
Edb.count property | Number of raw facts stored in this EDB. |
Edb.usage property | Current input fact and text occupancy. |
edb.addFact() method | Append one typed fact to mutable input. |
edb.addFacts() method | Stage a whole batch and append it atomically; rejection preserves existing input. |
edb.clear() method | Empty mutable input while retaining its storage. |
edb.reset() method | Empty and unfreeze input for a new request; existing results retain their snapshots. |
edb.close() method | Release this resource and its owned descendants. Closing is idempotent. |
using edb protocol | Leave the scope to close this input buffer; its Ruleset remains open. |
Fact.predicate property | Predicate name for this input fact. |
Fact.terms property | Ordered input values; integer numbers must be safe integers. |
EdbOptions.factCapacity? property | Maximum raw facts stored in the EDB, including repeated facts. |
EdbOptions.textCapacity? property | Reserved bytes for interned input text including terminators. |
EdbUsage.facts property | Number of raw facts currently stored. |
EdbUsage.textBytes property | Used text bytes, or the explicit session text quota in capacity options. |
EdbUsage.textCapacity property | Reserved 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
| Name | Summary |
|---|---|
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? property | Maximum session input facts. |
SessionCapacities.derivedFacts? property | Maximum session derived facts. |
SessionCapacities.symbols? property | Maximum session symbols. |
SessionCapacities.textBytes? property | Used text bytes, or the explicit session text quota in capacity options. |
new SessionCapacities() constructor | Validate explicit fixed session quotas. |
Session.capacities property | Effective fixed capacities, or requested optional quotas when preparing a session. |
Session.fingerprint property | Semantic fingerprint of the policy selection. |
Session.executionFingerprint property | Fingerprint incorporating execution configuration. |
session.inputs() method | Attach 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() method | Evaluate an EDB from the same ruleset using this prepared session. Ordinary solve is unavailable while retained input is attached. |
session.close() method | Release this resource and its owned descendants. Closing is idempotent. |
using session protocol | Leave the scope to close this Session and its active result. |
CapacityOptions.inputFacts? property | Maximum session input facts. |
CapacityOptions.derivedFacts? property | Maximum session derived facts. |
CapacityOptions.symbols? property | Maximum session symbols. |
CapacityOptions.textBytes? property | Used text bytes, or the explicit session text quota in capacity options. |
SessionOptions.policyIndex? property | Zero-based policy selection; defaults to zero. |
SessionOptions.requiredCapabilities? property | Required backend capability bits; unsupported requests fail preparation. |
SessionOptions.workLimit? property | Requested work budget; a backend without this capability rejects a nonzero limit. |
SessionOptions.explanations? property | Optional TRUE/FALSE workspace mask; zero reserves no workspace. |
SessionOptions.capacities? property | Effective fixed capacities, or requested optional quotas when preparing a session. |
Capability.POSITIVE property | Positive rule evaluation capability bit. |
Capability.NEGATION property | Stratified negation capability bit. |
Capability.COMPARISONS property | Typed comparisons capability bit. |
Capability.ARITHMETIC property | Arithmetic capability bit. |
Capability.FILTERS property | Filters capability bit. |
Capability.EXPLAIN_TRUE property | Why-true explanations capability bit. |
Capability.WORK_LIMIT property | Bounded work admission capability bit. |
Capability.EXPLAIN_FALSE property | Why-false explanations capability bit. |
Capability.AGGREGATES property | Aggregate support capability bit. |
Capability.MIN property | Minimum aggregates capability bit. |
Capability.MAX property | Maximum aggregates capability bit. |
Capability.SUM property | Sum aggregates capability bit. |
ExplanationKind.TRUE property | Reserve Why-true workspace. |
ExplanationKind.FALSE property | Reserve Why-false workspace. |
Guides: Session and solving guide · Prepare storage and reuse it across requests · Preparation options
Session inputs reference
| Name | Summary |
|---|---|
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 property | Identifies this retained-input attachment. |
InputBase.generation property | Identifies its current committed input generation. |
new InputBase() constructor | Construct an exact retained-input base token from its two unsigned 64-bit components. |
InputOptions.factCapacity? property | Maximum retained input facts; defaults to the session input-fact quota. |
InputOptions.additionCapacity? property | Maximum raw additions per apply call; defaults to factCapacity. |
InputOptions.removalCapacity? property | Maximum raw removals per apply call; defaults to factCapacity. |
InputOptions.symbols? property | Additional strings admitted to the immutable program vocabulary. |
SessionInputs.base property | Current committed retained-input base token. |
retained.replace() method | Replace all retained input and return its solved snapshot. |
retained.apply() method | Apply retained-input changes and return their solved snapshot. |
retained.close() method | Release retained input after closing its live result. |
using retained protocol | Leave the scope to close retained input after its live result has been closed. |
Guides: Session preparation
querying reference
| Name | Summary |
|---|---|
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 property | Whether the term is a symbol, integer, or boolean. |
ResultTerm.value property | A symbol ID local to its result, or a typed integer/boolean value. |
term.resolve() method | Copy the typed value from this result-bound term. |
SolveResult.fingerprint property | Semantic fingerprint of the policy selection. |
SolveResult.executionFingerprint property | Fingerprint incorporating execution configuration. |
result.containsFact() method | Check membership of a ground fact exposed by the domain query flags. |
result.derivedFactCount() method | Count all derived facts in the retained result. |
result.enumeratePredicateFacts() method | Copy resolved values for one queryable predicate and arity. |
result.enumerateRaw() method | Read immutable terms whose symbol identities remain bound to this result. |
result.resolveTerm() method | Resolve a term owned by this same live result into a copied value. |
result.explainTrue() method | Produce the canonical Why-true document for a ground fact. |
result.explainFalse() method | Produce the canonical Why-false document for a ground fact. |
result.close() method | Release the result lease and its private convenience session, if any. Closing is idempotent. |
using result protocol | Leave 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
| Name | Summary |
|---|---|
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 property | Alias of the operation status on MaelysDatalogError; diagnostic.code is the separate engine diagnostic code. |
MaelysDatalogError.status property | Stable numeric operation status. |
MaelysDatalogError.diagnostic property | Immutable copied structured diagnostic. |
new MaelysDatalogError() constructor | Construct an error carrying the failed operation, status and diagnostic. |
Limits.maxSymbols property | Maximum interned symbols. |
Limits.stringPoolBytes property | Bytes in the engine string pool. |
Limits.maxPredicates property | Maximum registered predicates. |
Limits.maxRules property | Maximum compiled rules. |
Limits.maxArity property | Maximum predicate arity. |
Limits.maxBodyLiterals property | Maximum literals in one rule body. |
Limits.maxDepth property | Maximum supported engine depth. |
Limits.maxEdbFacts property | Maximum runtime input facts. |
Limits.maxIdbFacts property | Maximum derived facts. |
Limits.maxFactsPerPred property | Maximum facts per predicate. |
Limits.maxStringBytes property | Maximum bytes in one string. |
Limits.inputEdbTextBytes property | Default text capacity of the input buffer. |
Limits.maxPolicyAtoms property | Maximum declared policy-source atoms. |
Limits.maxPolicyAtomBytes property | Maximum UTF-8 bytes across policy atoms, excluding NUL terminators. |
Diagnostic.status property | Stable numeric operation status. |
Diagnostic.source property | Numeric diagnostic source. |
Diagnostic.code property | Native diagnostic code; distinct from the operation status. |
Diagnostic.present property | Presence-bit mask describing available structured fields. |
Diagnostic.phase property | Phase during which the operation failed. |
Diagnostic.message property | Human-readable diagnostic detail copied from the engine. |
Diagnostic.hint property | Suggested corrective action when supplied. |
Diagnostic.codeName property | Stable diagnostic code name. |
Diagnostic.statusName property | Stable operation status name. |
Diagnostic.location? property | Optional source file, line and column. |
Diagnostic.predicate? property | Optional predicate name and arity. |
Diagnostic.capacity? property | Optional attempted value and applicable bound, with its numeric budget kind and, when supplied, its public budget name. |
Diagnostic.depth? property | Optional observed depth and bound. |
Diagnostic.comparison? property | Optional operand kinds and comparison outcome. |
Diagnostic.arity? property | Optional expected and observed arity and term index. |
Diagnostic.rule? property | Optional rule identifier. |
Diagnostic.aggregate? property | Optional aggregate operation, exact textual operand and bound. |
Diagnostic.context? property | Optional token, field and domain context. |
Status.OK property | Operation succeeded. |
Status.INVALID_ARGUMENT property | Malformed argument. |
Status.INVALID_FIELD property | Invalid field or typed value. |
Status.NOT_FOUND property | Requested item or explanation symbol not found. |
Status.NOT_IMPLEMENTED property | Operation not implemented. |
Status.UNSUPPORTED property | Unsupported capability or operation. |
Status.TIMEOUT property | Operation timed out. |
Status.IO property | Input/output failure. |
Status.INTERNAL property | Internal operation failure. |
Status.UNAUTHORIZED property | Authentication required. |
Status.FORBIDDEN property | Permission or manifest policy rejects the operation. |
Status.RATE_LIMITED property | Rate limit reached. |
Status.PAYLOAD_TOO_LARGE property | Content exceeds an engine bound. |
Status.INVALID_STATE property | Resource is closed or its current lease prevents the operation. |
Status.STORAGE_TOO_SMALL property | Supplied 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 point | Execution | Typical use |
|---|---|---|
@maelys-dev/datalog/node | Native Node-API addon with the engine compiled in | Node applications and Node worker threads |
@maelys-dev/datalog/wasm | WebAssembly | Browser applications, module workers, or Node |
@maelys-dev/datalog | Conditional export: native in Node, WASM for the browser condition | Applications 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:
@maelys-dev:registry=https://npm.pkg.github.com
//npm.pkg.github.com/:_authToken=${GITHUB_TOKEN}Install the package version matching this site's engine:
npm install @maelys-dev/datalog@0.27.0Choose one import for the application:
// 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 wrapper | Published shared API |
|---|---|
One active MaelysPlayground policy/session/result | Explicit 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 input | input.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.