API Reference
Modules

@coasys/ad4m / Exports

@coasys/ad4m

Table of contents

Enumerations

Classes

Interfaces

Type Aliases

Variables

Decorators Functions

Other Functions

Type Aliases

Ad4mSignalCB

Ƭ Ad4mSignalCB: (signal: any) => void

Type declaration

▸ (signal): void

Parameters
NameType
signalany
Returns

void

Defined in

language/LanguageContext.ts:37 (opens in a new tab)


Address

Ƭ Address: string

Defined in

Address.ts:1 (opens in a new tab)


AgentAppsUpdatedCallback

Ƭ AgentAppsUpdatedCallback: () => null

Type declaration

▸ (): null

Returns

null

Defined in

agent/AgentClient.ts:84 (opens in a new tab)


AgentStatusChangedCallback

Ƭ AgentStatusChangedCallback: (agent: Agent) => null

Type declaration

▸ (agent): null

Parameters
NameType
agentAgent
Returns

null

Defined in

agent/AgentClient.ts:83 (opens in a new tab)


AgentUpdatedCallback

Ƭ AgentUpdatedCallback: (agent: Agent) => null

Type declaration

▸ (agent): null

Parameters
NameType
agentAgent
Returns

null

Defined in

agent/AgentClient.ts:82 (opens in a new tab)


AllInstancesResult

Ƭ AllInstancesResult: Object

Type declaration

NameType
AllInstancesAd4mModel[]
TotalCount?number
isInit?boolean

Defined in

model/types.ts:103 (opens in a new tab)


ConformanceFilterFn

Ƭ ConformanceFilterFn: (relationPredicate: string, targetClass: Ad4mModelLike) => { conformanceConditions: ConformanceCondition[] ; getter: string } | undefined

Type declaration

▸ (relationPredicate, targetClass): { conformanceConditions: ConformanceCondition[] ; getter: string } | undefined

Signature for the conformance-filter builder injected by the caller.

Parameters
NameType
relationPredicatestring
targetClassAd4mModelLike
Returns

{ conformanceConditions: ConformanceCondition[] ; getter: string } | undefined

Defined in

model/shacl-gen.ts:17 (opens in a new tab)


DID

Ƭ DID: string

Defined in

DID.ts:1 (opens in a new tab)


FlowableCondition

Ƭ FlowableCondition: "any" | LinkPattern

Flowable condition - determines which expressions can enter this flow "any" means all expressions can start this flow Otherwise, a link pattern to check

Defined in

shacl/SHACLFlow.ts:54 (opens in a new tab)


GetOptions

Ƭ GetOptions: Pick<Query, "include" | "properties">

Options accepted by the instance get() method.

A subset of Query — only hydration controls apply to a single known instance.

Defined in

model/types.ts:97 (opens in a new tab)


HasManyMethods

Ƭ HasManyMethods<Keys>: { [K in Keys as `add${Capitalize<K>}`]: Function } & { [K in Keys as `remove${Capitalize<K>}`]: Function } & { [K in Keys as `set${Capitalize<K>}`]: Function }

Utility type that describes the auto-generated helper methods for a HasMany relation. For a property named comments on a class Post, the following methods will be available on instances:

post.addComment(value) post.removeComment(value) post.setComment(values)

Type parameters

NameType
Keysextends string

Defined in

model/decorators.ts:711 (opens in a new tab)


HostingUserInfoChangedCallback

Ƭ HostingUserInfoChangedCallback: (info: HostingUserInfo) => void

Type declaration

▸ (info): void

Parameters
NameType
infoHostingUserInfo
Returns

void

Defined in

agent/AgentClient.ts:85 (opens in a new tab)


LinkStatus

Ƭ LinkStatus: "shared" | "local"

Defined in

perspectives/PerspectiveProxy.ts:324 (opens in a new tab)


MessageCallback

Ƭ MessageCallback: (message: PerspectiveExpression) => void

Type declaration

▸ (message): void

Parameters
NameType
messagePerspectiveExpression
Returns

void

Defined in

language/Language.ts:204 (opens in a new tab)


Order

Ƭ Order: Object

Index signature

▪ [propertyName: string]: "ASC" | "DESC"

Defined in

model/types.ts:29 (opens in a new tab)


PaginationResult

Ƭ PaginationResult<T>: Object

Type parameters

Name
T

Type declaration

NameType
pageNumbernumber
pageSizenumber
resultsT[]
totalCount?number

Defined in

model/types.ts:105 (opens in a new tab)


ParentScope

Ƭ ParentScope: { field?: string ; id: string ; model: typeof Ad4mModel } | { id: string ; predicate: string }

Discriminated union for parent-scoped queries.

Model form (preferred) — predicate auto-resolved from the parent model's relation metadata. Use field to disambiguate when the parent has multiple relations targeting the same child class.

Raw form — explicit predicate string, no metadata lookup.

Defined in

model/types.ts:40 (opens in a new tab)


PerspectiveDiffObserver

Ƭ PerspectiveDiffObserver: (diff: PerspectiveDiff) => void

Type declaration

▸ (diff): void

Parameters
NameType
diffPerspectiveDiff
Returns

void

Defined in

language/Language.ts:151 (opens in a new tab)


Query

Ƭ Query: Object

Type declaration

NameTypeDescription
count?boolean-
include?IncludeMap-
limit?number-
offset?number-
order?Order-
parent?ParentScopeFilter to instances that are the target of a link from a given parent.
properties?string[]-
where?Where-

Defined in

model/types.ts:67 (opens in a new tab)


RelationSubQuery

Ƭ RelationSubQuery: Omit<Query, "parent" | "count">

Sub-query options for a specific relation inside an IncludeMap.

Equivalent to Query without top-level scoping (parent) or count, since the result set is already constrained to the linked relation.

Example

await post.get({ include: { comments: { order: { createdAt: 'DESC' }, limit: 5 } } });

Defined in

model/types.ts:90 (opens in a new tab)


ResultsWithTotalCount

Ƭ ResultsWithTotalCount<T>: Object

Type parameters

Name
T

Type declaration

NameType
resultsT[]
totalCount?number

Defined in

model/types.ts:104 (opens in a new tab)


StatusCallback

Ƭ StatusCallback: (caller: DID) => Perspective

Type declaration

▸ (caller): Perspective

Parameters
NameType
callerDID
Returns

Perspective

Defined in

language/Language.ts:205 (opens in a new tab)


SyncStateChangeObserver

Ƭ SyncStateChangeObserver: (state: PerspectiveState) => void

Type declaration

▸ (state): void

Parameters
NameType
statePerspectiveState
Returns

void

Defined in

language/Language.ts:152 (opens in a new tab)


TelepresenceSignalCallback

Ƭ TelepresenceSignalCallback: (payload: PerspectiveExpression, recipientDid?: string) => void

Type declaration

▸ (payload, recipientDid?): void

Parameters
NameType
payloadPerspectiveExpression
recipientDid?string
Returns

void

Defined in

language/Language.ts:270 (opens in a new tab)


ValueTuple

Ƭ ValueTuple: [name: string, value: any, resolve?: boolean]

Defined in

model/types.ts:111 (opens in a new tab)


Where

Ƭ Where: Object

Index signature

▪ [propertyName: string]: WhereCondition

Defined in

model/types.ts:28 (opens in a new tab)


WhereCondition

Ƭ WhereCondition: string | number | boolean | string[] | number[] | { [K in keyof WhereOps]?: WhereOps[K] }

Defined in

model/types.ts:27 (opens in a new tab)


WhereOps

Ƭ WhereOps: Object

Type declaration

NameType
between[number, number]
containsstring | number
gtnumber
gtenumber
ltnumber
ltenumber
notstring | number | boolean | string[] | number[]

Defined in

model/types.ts:18 (opens in a new tab)

Variables

SMART_LITERAL_CONTENT_PREDICATE

Const SMART_LITERAL_CONTENT_PREDICATE: "smart_literal://content"

Defined in

SmartLiteral.ts:6 (opens in a new tab)


typeDefsString

Const typeDefsString: ""

Defined in

typeDefs.ts:6 (opens in a new tab)

Decorators Functions

BelongsToMany

BelongsToMany(opts): PropertyDecorator

Decorator for defining the inverse side of a many-to-many relation.

Parameters

NameType
optsRelationOptions

Returns

PropertyDecorator

Description

Declares the non-owning (inverse) side of a many-to-many relationship. The property is a read-only relation since the owning side manages links.

Supports two calling conventions:

@BelongsToMany({ through: "post://tag", target: () => Post })
@BelongsToMany(() => Post, { through: "post://tag" })

Example

@Model({ name: "Tag" })
class Tag extends Ad4mModel {
  @BelongsToMany(() => Post, { through: "post://tag" })
  posts: string[] = [];
}

Defined in

model/decorators.ts:998 (opens in a new tab)

BelongsToMany(target, opts?): PropertyDecorator

Parameters

NameType
target() => Ad4mModelLike
opts?Omit<RelationOptions, "target">

Returns

PropertyDecorator

Defined in

model/decorators.ts:999 (opens in a new tab)


BelongsToOne

BelongsToOne(opts): PropertyDecorator

Decorator for defining the inverse side of a one-to-one relation.

Parameters

NameType
optsRelationOptions

Returns

PropertyDecorator

Description

Declares the non-owning (inverse) side of a one-to-one relationship. The property is read-only since the owning side manages the link.

Supports two calling conventions:

@BelongsToOne({ through: "post://author", target: () => Post })
@BelongsToOne(() => Post, { through: "post://author" })

Example

@Model({ name: "Author" })
class Author extends Ad4mModel {
  @BelongsToOne(() => Post, { through: "post://author" })
  post: string = "";
}

Defined in

model/decorators.ts:940 (opens in a new tab)

BelongsToOne(target, opts?): PropertyDecorator

Parameters

NameType
target() => Ad4mModelLike
opts?Omit<RelationOptions, "target">

Returns

PropertyDecorator

Defined in

model/decorators.ts:941 (opens in a new tab)


Flag

Flag(opts): <T>(target: T, key: keyof T) => void

Decorator for defining flags on model classes.

Parameters

NameTypeDescription
optsFlagOptionsFlag configuration

Returns

fn

▸ <T>(target, key): void

Type parameters
Name
T
Parameters
NameType
targetT
keykeyof T
Returns

void

Description

A specialized property decorator for defining immutable type flags or markers on model instances. Flags are always required properties with a fixed value that cannot be changed after creation.

Common uses for flags:

  • Type discrimination between different kinds of models
  • Marking models with specific capabilities or features
  • Versioning or compatibility markers

Note: Use of Flag is discouraged unless you specifically need type-based filtering or discrimination between different kinds of models. For most cases, regular properties with

Property

or

Optional

are more appropriate.

Example

class Message extends Ad4mModel {
  // Type flag to identify message models
  @Flag({
    through: "ad4m://type",
    value: "ad4m://message"
  })
  type: string = "";
 
  // Version flag for compatibility
  @Flag({
    through: "ad4m://version",
    value: "1.0.0"
  })
  version: string = "";
 
  // Feature flag
  @Flag({
    through: "message://feature",
    value: "message://encrypted"
  })
  feature: string = "";
}
 
// Later you can query for specific types:
const messages = await Message.query(perspective)
  .where({ type: "ad4m://message" })
  .run();

Defined in

model/decorators.ts:382 (opens in a new tab)


HasMany

HasMany(opts): PropertyDecorator

Decorator for defining a one-to-many relation.

Parameters

NameType
optsRelationOptions

Returns

PropertyDecorator

Description

Declares that the decorated property is an array of related model instances. Under the hood it registers the relation in the relation registry and also creates the corresponding relation entry so that the SDNA / SHACL generators continue to emit the correct subject-class code.

Supports two calling conventions:

// Options-object style
@HasMany({ through: "post://comment", target: () => Comment })
 
// Target-first shorthand
@HasMany(() => Comment, { through: "post://comment" })

Example

@Model({ name: "Post" })
class Post extends Ad4mModel {
  @HasMany(() => Comment, { through: "post://comment" })
  comments: string[] = [];
}

Defined in

model/decorators.ts:806 (opens in a new tab)

HasMany(target, opts?): PropertyDecorator

Parameters

NameType
target() => Ad4mModelLike
opts?Omit<RelationOptions, "target">

Returns

PropertyDecorator

Defined in

model/decorators.ts:807 (opens in a new tab)


HasOne

HasOne(opts): PropertyDecorator

Decorator for defining a one-to-one relation (owning side).

Parameters

NameType
optsRelationOptions

Returns

PropertyDecorator

Description

Declares that the decorated property holds a single related model instance. The owning side manages the link.

Supports two calling conventions:

@HasOne({ through: "post://author", target: () => Author })
@HasOne(() => Author, { through: "post://author" })

Example

@Model({ name: "Post" })
class Post extends Ad4mModel {
  @HasOne(() => Author, { through: "post://author" })
  author: string = "";
}

Defined in

model/decorators.ts:870 (opens in a new tab)

HasOne(target, opts?): PropertyDecorator

Parameters

NameType
target() => Ad4mModelLike
opts?Omit<RelationOptions, "target">

Returns

PropertyDecorator

Defined in

model/decorators.ts:871 (opens in a new tab)


Model

Model(opts): (target: any) => void

Decorator for defining model classes in AD4M.

Parameters

NameTypeDescription
optsModelConfigModel configuration

Returns

fn

▸ (target): void

Parameters
NameType
targetany
Returns

void

Description

The root decorator that must be applied to any class that represents a model in AD4M. It registers the class as a Social DNA (SDNA) subject class and provides the infrastructure for storing and retrieving instances.

This decorator:

  • Registers the class with a unique name in the AD4M system
  • Generates the necessary SDNA code for the model's properties and relations
  • Enables the use of other model decorators (@Property, @HasMany, etc.)
  • Provides static query methods through the Ad4mModel base class

Example

@Model({ name: "Recipe" })
class Recipe extends Ad4mModel {
  @Property({
    through: "recipe://name",
    resolveLanguage: "literal"
  })
  name: string = "";
 
  @HasMany({ through: "recipe://ingredient" })
  ingredients: string[] = [];
 
  // Static query methods from Ad4mModel:
  static async findByName(perspective: PerspectiveProxy, name: string) {
    return Recipe.query(perspective)
      .where({ name })
      .run();
  }
}
 
// Using the model:
const recipe = new Recipe(perspective);
recipe.name = "Chocolate Cake";
await recipe.save();
 
// Querying instances:
const recipes = await Recipe.query(perspective)
  .where({ name: "Chocolate Cake" })
  .run();
 
// Using with PerspectiveProxy:
await perspective.ensureSDNASubjectClass(Recipe);

Defined in

model/decorators.ts:480 (opens in a new tab)


Optional

Optional(opts): <T>(target: T, key: keyof T) => void

Convenience decorator for defining optional (not required) properties.

Parameters

NameTypeDescription
optsPropertyOptionsProperty configuration (same options as @Property)

Returns

fn

▸ <T>(target, key): void

Type parameters
Name
T
Parameters
NameType
targetT
keykeyof T
Returns

void

Description

Equivalent to @Property but defaults required to false and does not apply resolveLanguage or initial defaults. Use this when a property may or may not have a value, and you want full control over its configuration.

Example

class Recipe extends Ad4mModel {
  @Optional({ through: "recipe://description" })
  description?: string;
}

Defined in

model/decorators.ts:309 (opens in a new tab)


Property

Property(opts): <T>(target: T, key: keyof T) => void

The primary property decorator for AD4M model classes.

Parameters

NameTypeDescription
optsPropertyOptionsProperty configuration

Returns

fn

▸ <T>(target, key): void

Type parameters
Name
T
Parameters
NameType
targetT
keykeyof T
Returns

void

Description

The core property decorator with smart defaults. All other property decorators (@Optional, @ReadOnly) are thin wrappers that adjust these defaults.

Smart defaults (all overridable):

  • requiredfalse
  • readOnlyfalse
  • resolveLanguage"literal"
  • initialundefined (no link created until a value is explicitly set)

Properties are optional by default. When a model instance is created without providing a value for an optional property, no link is added to the graph. Set required: true explicitly when a property must always be present (this also adds a "literal://string:uninitialized" sentinel as the initial value so that the SDNA constructor creates a placeholder link).

Example

class User extends Ad4mModel {
  // Optional property (default) — no link created until a value is set
  @Property({
    through: "user://name"
  })
  name: string = "";
 
  // Explicitly required property with sentinel initial value
  @Property({
    through: "user://status",
    required: true
  })
  status: string = "";
 
  // Required property with custom initial value
  @Property({
    through: "user://role",
    required: true,
    initial: "user://member"
  })
  role: string = "";
 
  // Optional property with literal resolution
  @Property({
    through: "user://bio",
    resolveLanguage: "literal"
  })
  bio: string = "";
}

Defined in

model/decorators.ts:571 (opens in a new tab)


ReadOnly

ReadOnly(opts): <T>(target: T, key: keyof T) => void

Decorator for defining read-only properties on model classes.

Parameters

NameTypeDescription
optsPropertyOptionsProperty configuration

Returns

fn

▸ <T>(target, key): void

Type parameters
Name
T
Parameters
NameType
targetT
keykeyof T
Returns

void

Description

A convenience decorator that defines a read-only property. Equivalent to @Property with readOnly: true.

Read-only properties are ideal for:

  • Computed or derived values
  • Properties that should never change after creation
  • Properties that are set by the system
  • Properties that represent immutable data

Example

class Post extends Ad4mModel {
  // Read-only property with custom getter for computed value
  @ReadOnly({
    through: "post://likes",
    getter: `findall(User, triple(Base, "post://liked_by", User), Users), length(Users, Value)`
  })
  likeCount: number = 0;
 
  // Read-only property for creation timestamp
  @ReadOnly({
    through: "post://created_at",
    initial: new Date().toISOString()
  })
  createdAt: string = "";
 
  // Read-only property that resolves to a Literal
  @ReadOnly({
    through: "post://author",
    resolveLanguage: "literal"
  })
  author: string = "";
 
  // Read-only property for system-managed data
  @ReadOnly({
    through: "post://version",
    initial: "1.0.0"
  })
  version: string = "";
}

Defined in

model/decorators.ts:637 (opens in a new tab)


Other Functions

ExpressionGeneric

ExpressionGeneric<DataType>(DataTypeClass): any

Type parameters

Name
DataType

Parameters

NameType
DataTypeClassClassType<DataType>

Returns

any

Defined in

expression/Expression.ts:42 (opens in a new tab)


ExpressionGenericInput

ExpressionGenericInput<DataType>(DataTypeClass): any

Type parameters

Name
DataType

Parameters

NameType
DataTypeClassClassType<DataType>

Returns

any

Defined in

expression/Expression.ts:67 (opens in a new tab)


assignValuesToInstance

assignValuesToInstance(perspective, instance, values): Promise<void>

Assigns decoded Prolog property values to an instance.

Handles UTF-8 byte sequence reconstruction, expression resolution, transform functions, and read-only property filtering.

Parameters

NameType
perspectivePerspectiveProxy
instanceany
valuesValueTuple[]

Returns

Promise<void>

Defined in

model/hydration.ts:339 (opens in a new tab)


buildAuthorAndTimestampQuery

buildAuthorAndTimestampQuery(): string

Returns

string

Defined in

model/query-prolog.ts:21 (opens in a new tab)


buildConformanceFilter

buildConformanceFilter(relationPredicate, targetClass): { conformanceConditions: ConformanceCondition[] ; getter: string } | undefined

Build a conformance filter for a relation whose target model is known.

Inspects the target class's property metadata to derive:

  • conformanceConditions: Structured, DB-agnostic conditions (flag & required checks)
  • getter: Pre-computed SurrealQL expression that traverses outgoing links and filters target nodes to only those conforming to the target shape.

Parameters

NameTypeDescription
relationPredicatestringThe relation's predicate URI (e.g. "flux://entry_type")
targetClassAd4mModelLikeThe target model class (resolved from the target() thunk)

Returns

{ conformanceConditions: ConformanceCondition[] ; getter: string } | undefined

{ getter, conformanceConditions } or undefined if no conditions could be derived

Defined in

model/decorators.ts:147 (opens in a new tab)


buildConformanceGetter

buildConformanceGetter(relationPredicate, targetClass): string | undefined

Builds a SurrealQL conformance getter for a relation whose target model is known but no explicit getter string was supplied.

The generated getter traverses outgoing links matching the relation's predicate and then filters the target nodes to only those that conform to the target model's shape (required properties / flags).

Delegates to the shared buildConformanceFilter() utility in decorators.ts so the same logic is used at shape-definition time and at query time.

Parameters

NameTypeDescription
relationPredicatestringThe relation's predicate URI (e.g. "flux://entry_type")
targetClassanyThe target model class (result of calling the target() thunk)

Returns

string | undefined

A SurrealQL expression string, or undefined if no conformance conditions could be derived from the target model.

Defined in

model/hydration.ts:435 (opens in a new tab)


buildCountQuery

buildCountQuery(count?): string

Parameters

NameType
count?boolean

Returns

string

Defined in

model/query-prolog.ts:116 (opens in a new tab)


buildGraphTraversalWhereClause

buildGraphTraversalWhereClause(metadata, allRelationsMetadata, where?): string

Builds WHERE clause filters using SurrealDB graph traversal syntax.

Translates where conditions into ->link[WHERE ...] / <-link[WHERE ...] filters that SurrealDB can optimize via graph indexes.

Parameters

NameTypeDescription
metadataModelMetadataModel metadata from getModelMetadata()
allRelationsMetadataRecord<string, RelationMetadataEntry>Full relation metadata (needed for belongs-to direction detection)
where?WhereUser-supplied where conditions

Returns

string

Combined AND-joined condition string, or empty string

Defined in

model/query-surreal.ts:37 (opens in a new tab)


buildLimitQuery

buildLimitQuery(limit?): string

Parameters

NameType
limit?number

Returns

string

Defined in

model/query-prolog.ts:145 (opens in a new tab)


buildModelFromJSONSchema

buildModelFromJSONSchema(BaseClass, schema, options): typeof Ad4mModel

Core implementation of Ad4mModel.fromJSONSchema().

Creates a dynamic Ad4mModel subclass from a JSON Schema definition, wiring up property / relation metadata, setters, and the @Model decorator.

Parameters

NameTypeDescription
BaseClasstypeof Ad4mModelThe Ad4mModel class (or subclass) to extend
schemaJSONSchemaJSON Schema definition
optionsJSONSchemaToModelOptionsConfiguration options

Returns

typeof Ad4mModel

Generated Ad4mModel subclass

Defined in

model/json-schema.ts:263 (opens in a new tab)


buildOffsetQuery

buildOffsetQuery(offset?): string

Parameters

NameType
offset?number

Returns

string

Defined in

model/query-prolog.ts:140 (opens in a new tab)


buildOrderQuery

buildOrderQuery(order?): string

Parameters

NameType
order?Order

Returns

string

Defined in

model/query-prolog.ts:120 (opens in a new tab)


buildParentQuery

buildParentQuery(parent, resolvedPredicate?): string

Parameters

NameType
parentParentScope
resolvedPredicate?string

Returns

string

Defined in

model/query-prolog.ts:13 (opens in a new tab)


buildPropertiesQuery

buildPropertiesQuery(properties?): string

Parameters

NameType
properties?string[]

Returns

string

Defined in

model/query-prolog.ts:34 (opens in a new tab)


buildSDNA

buildSDNA(subjectName, obj, properties, allRelationsMeta): Object

Build SDNA (Social DNA) Prolog code for a model class.

Parameters

NameTypeDescription
subjectNamestringThe model's registered name (from @Model({ name }))
objanytarget.prototype — used to inspect prototype methods (e.g. setter stubs, subjectConstructor, isSubjectInstance)
propertiesRecord<string, PropertyMetadataEntry>Merged property metadata (from getPropertiesMetadata)
allRelationsMetaRecord<string, RelationMetadataEntry>Merged relation metadata (from getRelationsMetadata)

Returns

Object

NameType
namestring
sdnastring

Defined in

model/sdna.ts:21 (opens in a new tab)


buildSHACL

buildSHACL(subjectName, target, properties, allRelationsMeta, conformanceFilterFn): Object

Build a SHACL shape for a model class.

Parameters

NameTypeDescription
subjectNamestringThe model's registered name (from @Model({ name }))
targetanyThe class constructor (used for prototype access, inheritance chain, and relation target resolution)
propertiesRecord<string, PropertyMetadataEntry>Merged property metadata (from getPropertiesMetadata)
allRelationsMetaRecord<string, RelationMetadataEntry>Merged relation metadata (from getRelationsMetadata)
conformanceFilterFnConformanceFilterFnInjected conformance-filter builder (avoids circular dependency back into decorators.ts)

Returns

Object

NameType
namestring
shapeSHACLShape

Defined in

model/shacl-gen.ts:33 (opens in a new tab)


buildSurrealQLQuery

buildSurrealQLQuery(metadata, allRelationsMetadata, query, modelClass): string

Builds a complete SurrealQL query from a Query object and model metadata.

This is the core implementation behind Ad4mModel.queryToSurrealQL(). It produces a graph-traversal query that:

  1. Filters nodes by required predicates (conformance check)
  2. Applies user WHERE conditions
  3. Fetches all outgoing links for hydration

Parameters

NameTypeDescription
metadataModelMetadataModel metadata from getModelMetadata()
allRelationsMetadataRecord<string, RelationMetadataEntry>Full relation registry (for belongs-to detection)
queryQueryQuery parameters
modelClassanyThe model class (for resolveParentPredicate)

Returns

string

Complete SurrealQL query string

Defined in

model/query-surreal.ts:184 (opens in a new tab)


buildWhereQuery

buildWhereQuery(where?): string

Parameters

NameType
whereWhere

Returns

string

Defined in

model/query-prolog.ts:48 (opens in a new tab)


capSentence

capSentence(cap): string

Parameters

NameType
capany

Returns

string

Defined in

utils.ts:15 (opens in a new tab)


determineNamespace

determineNamespace(schema, options): string

Determines the namespace for predicates using cascading precedence:

  1. Explicit namespace in options
  2. x-ad4m metadata in schema
  3. Infer from schema title
  4. Try to extract from $id
  5. Error if nothing works

Parameters

NameType
schemaJSONSchema
optionsJSONSchemaToModelOptions

Returns

string

Defined in

model/json-schema.ts:108 (opens in a new tab)


determinePredicate

determinePredicate(schema, propertyName, propertySchema, namespace, options): string

Determines the predicate for a specific property using cascading precedence:

  1. Explicit property mapping
  2. x-ad4m metadata in property schema
  3. Predicate template
  4. Custom predicate generator
  5. Default: namespace + property name

Parameters

NameType
schemaJSONSchema
propertyNamestring
propertySchemaJSONSchemaProperty
namespacestring
optionsJSONSchemaToModelOptions

Returns

string

Defined in

model/json-schema.ts:157 (opens in a new tab)


escapeSurrealString

escapeSurrealString(value): string

Escapes a string value for safe use in SurrealQL queries.

Parameters

NameTypeDescription
valuestringThe string value to escape

Returns

string

The escaped string safe for SurrealQL interpolation (without surrounding quotes)

Description

Prevents SQL injection by properly escaping special characters in string values that will be interpolated into SurrealQL queries. This handles the most common special characters that could break SQL queries or enable injection attacks.

Single quotes, backslashes, and other special characters are escaped using backslash notation, which is the standard escaping mechanism for SurrealQL.

Example

const userInput = "user's input with 'quotes'";
const escaped = escapeSurrealString(userInput);
const query = `SELECT * FROM link WHERE uri = '${escaped}'`;
// Results in: SELECT * FROM link WHERE uri = 'user\'s input with \'quotes\''

Defined in

utils.ts:49 (opens in a new tab)


evaluateCustomGettersForInstance

evaluateCustomGettersForInstance(instance, perspective, metadata, options?): Promise<void>

Evaluates custom SurrealQL getters for properties and relations on a specific instance.

For relations that declare a target but no explicit getter, a conformance getter is auto-generated from the target model's metadata (unless filter: false).

Parameters

NameType
instanceany
perspectivePerspectiveProxy
metadataModelMetadata
options?Object
options.include?Record<string, any>
options.requestedProperties?string[]

Returns

Promise<void>

Defined in

model/hydration.ts:454 (opens in a new tab)


exprRef2String

exprRef2String(ref): string

Parameters

NameType
refExpressionRef

Returns

string

Defined in

expression/ExpressionRef.ts:22 (opens in a new tab)


formatList

formatList(list): any

Parameters

NameType
listany

Returns

any

Defined in

utils.ts:1 (opens in a new tab)


generatePrologFacts

generatePrologFacts(ModelClass): string

Generate Prolog predicate facts from a model class's decorator metadata.

Given a model class decorated with @Model (and its @Flag, @Property, @HasMany, @BelongsToMany decorators), this function emits a string of Prolog clauses that can be prepended to any perspective.infer() call.

The generated predicates are:

  • Instance recognizermodelName(X) — matches instances of the model
  • Property gettersmodelName_propName(X, Value) — one per property
  • Relation gettersmodelName_relName(X, Values) — one per relation

Parameters

NameTypeDescription
ModelClasstypeof Ad4mModelA class decorated with @Model that extends Ad4mModel

Returns

string

A multi-line Prolog string ready for use with perspective.infer()

Example

import { generatePrologFacts } from '@coasys/ad4m';
 
const facts = generatePrologFacts(Poll);
const result = await perspective.infer(\`
  \${facts}
  recent_popular_poll(X) :-
    poll(X),
    poll_vote_count(X, N), N > 10.
\`);

Defined in

model/prolog-facts.ts:109 (opens in a new tab)


getDefaultValueForType

getDefaultValueForType(type?): any

Gets default value for a JSON Schema type.

Parameters

NameType
type?string

Returns

any

Defined in

model/json-schema.ts:238 (opens in a new tab)


getPropertiesMetadata

getPropertiesMetadata(ctor): Record<string, PropertyMetadataEntry>

Retrieve property metadata for a given class constructor. Walks the prototype chain so subclass decorators compose with parent decorators.

Parameters

NameType
ctorFunction

Returns

Record<string, PropertyMetadataEntry>

Defined in

model/decorators.ts:64 (opens in a new tab)


getPropertyOption

getPropertyOption(propertyName, propertySchema, options, optionName, defaultValue?): any

Gets property-specific options using cascading precedence:

  1. Property-specific options
  2. x-ad4m metadata in property
  3. Global option
  4. Default value

Parameters

NameType
propertyNamestring
propertySchemaJSONSchemaProperty
optionsJSONSchemaToModelOptions
optionNamekeyof PropertyOptions
defaultValue?any

Returns

any

Defined in

model/json-schema.ts:209 (opens in a new tab)


getRelationsMetadata

getRelationsMetadata(ctor): Record<string, RelationMetadataEntry>

Retrieve relation metadata for a given class constructor. Walks the prototype chain so subclass decorators compose with parent decorators.

Parameters

NameType
ctorFunction

Returns

Record<string, RelationMetadataEntry>

Defined in

model/decorators.ts:83 (opens in a new tab)


hydrateFromLinks

hydrateFromLinks(instance, links, metadata, perspective, requestedProperties?): Promise<void>

Hydrates an instance from an array of raw links.

Processes properties (latest-wins semantics), relations (chronological accumulation), and timestamps/author in a single pass over the links array.

Parameters

NameTypeDescription
instanceanyThe blank model instance to populate
links{ author?: string ; predicate: string ; target: string ; timestamp?: string | number }[]Array of link objects (predicate, target, author?, timestamp?)
metadataModelMetadataModel metadata from getModelMetadata()
perspectivePerspectiveProxyThe perspective for expression resolution
requestedProperties?string[]Optional sparse fieldset; when provided, only these property names are hydrated (relations are unaffected). Omit or pass undefined to hydrate all properties.

Returns

Promise<void>

Defined in

model/hydration.ts:188 (opens in a new tab)


hydratePropertyValue

hydratePropertyValue(target, propMeta, perspective, expectedType?): Promise<any>

Resolves a single property value from a raw link target string.

Handles expression resolution, literal URI parsing, primitive type coercion, and optional transform functions.

Parameters

NameTypeDescription
targetstringThe raw target string from the link
propMetaPropertyMetadataProperty metadata from the decorator registry
perspectivePerspectiveProxyThe perspective for expression resolution
expectedType?stringOptional JS typeof hint for coercion (e.g. 'number')

Returns

Promise<any>

The resolved value

Defined in

model/hydration.ts:120 (opens in a new tab)


hydrateRelations

hydrateRelations<T>(modelClass, instances, perspective, includeMap): Promise<void>

Hydrates relation fields on instances according to the provided IncludeMap.

For each relation listed in includeMap, the raw expression-URI strings stored on the instance are replaced with fully-hydrated model instances (fetched via the relation's target() class). Nested IncludeMaps are supported for multi-level eager loading.

Type parameters

Name
T

Parameters

NameTypeDescription
modelClassanyThe model class whose relation metadata to read
instancesT[]The instances whose relations should be hydrated
perspectivePerspectiveProxyThe perspective to fetch related instances from
includeMapIncludeMapDescribes which relations to hydrate

Returns

Promise<void>

Defined in

model/hydration.ts:564 (opens in a new tab)


isArrayType

isArrayType(schema): boolean

Parameters

NameType
schemaJSONSchemaProperty

Returns

boolean

Defined in

model/json-schema.ts:85 (opens in a new tab)


isExpression

isExpression(e): boolean

Parameters

NameType
eany

Returns

boolean

Defined in

expression/Expression.ts:97 (opens in a new tab)


isLink

isLink(l): boolean

Parameters

NameType
lany

Returns

boolean

Defined in

links/Links.ts:91 (opens in a new tab)


isNumericType

isNumericType(schema): boolean

Parameters

NameType
schemaJSONSchemaProperty

Returns

boolean

Defined in

model/json-schema.ts:93 (opens in a new tab)


isObjectType

isObjectType(schema): boolean

Parameters

NameType
schemaJSONSchemaProperty

Returns

boolean

Defined in

model/json-schema.ts:89 (opens in a new tab)


isSchemaType

isSchemaType(schema, expectedType): boolean

Parameters

NameType
schemaJSONSchemaProperty
expectedTypestring

Returns

boolean

Defined in

model/json-schema.ts:81 (opens in a new tab)


linkEqual

linkEqual(l1, l2): boolean

Parameters

NameType
l1LinkExpression
l2LinkExpression

Returns

boolean

Defined in

links/Links.ts:83 (opens in a new tab)


matchesCondition

matchesCondition(value, condition): boolean

Checks if a value matches a where-condition (for post-query filtering).

Parameters

NameType
valueany
conditionWhereCondition

Returns

boolean

Defined in

model/hydration.ts:43 (opens in a new tab)


normalizeNamespaceString

normalizeNamespaceString(namespace): string

Parameters

NameType
namespacestring

Returns

string

Defined in

model/json-schema.ts:60 (opens in a new tab)


normalizeSchemaType

normalizeSchemaType(type?): string | undefined

Parameters

NameType
type?string | string[]

Returns

string | undefined

Defined in

model/json-schema.ts:71 (opens in a new tab)


normalizeValue

normalizeValue(value): any

Normalize a value for snapshot storage. Arrays of model instances are reduced to their .id strings so that dirty-tracking compares stable identifiers instead of object references.

Parameters

NameType
valueany

Returns

any

Defined in

model/hydration.ts:31 (opens in a new tab)


parseExprUrl

parseExprUrl(url): ExpressionRef

Parameters

NameType
urlstring

Returns

ExpressionRef

Defined in

expression/ExpressionRef.ts:29 (opens in a new tab)


resolveParentPredicate

resolveParentPredicate(parent, childCtor): string

Resolves the predicate for a parent query.

Uses TS discriminated union narrowing:

  • Raw form ({ id, predicate }) → predicate used as-is
  • Model form ({ model, id, field? }) → lookup from relation metadata
    • With field: direct key lookup
    • Without field: scan for a relation whose target() matches childCtor

Parameters

NameType
parentParentScope
childCtorFunction

Returns

string

Defined in

model/query-common.ts:17 (opens in a new tab)


setPropertyRegistryEntry

setPropertyRegistryEntry(ctor, propName, meta): void

Programmatically register property metadata for a given constructor. Used by fromJSONSchema() and other dynamic model builders.

Parameters

NameType
ctorFunction
propNamestring
metaPropertyMetadataEntry & { writable?: boolean }

Returns

void

Defined in

model/decorators.ts:103 (opens in a new tab)


setRelationRegistryEntry

setRelationRegistryEntry(ctor, relName, meta): void

Programmatically register relation metadata for a given constructor. Used by fromJSONSchema() and other dynamic model builders.

Parameters

NameType
ctorFunction
relNamestring
metaRelationMetadataEntry

Returns

void

Defined in

model/decorators.ts:116 (opens in a new tab)