@coasys/ad4m / Exports
@coasys/ad4m
Table of contents
Enumerations
Classes
- AIClient
- AIModelLoadingStatus
- AIPromptExamples
- AIPromptExamplesInput
- AITask
- AITaskInput
- Ad4mClient
- Ad4mModel
- Agent
- AgentClient
- AgentExpression
- AgentSignature
- AgentStatus
- Apps
- AuthInfo
- AuthInfoInput
- Capability
- CapabilityInput
- Dna
- EntanglementProof
- EntanglementProofInput
- ExceptionInfo
- Expression
- ExpressionProof
- ExpressionProofInput
- ExpressionRef
- ExpressionRendered
- HostingUserInfo
- Icon
- ImportResult
- ImportStats
- InteractionCall
- InteractionMeta
- InteractionParameter
- LanguageExpression
- LanguageHandle
- LanguageLanguageInput
- LanguageMeta
- LanguageMetaInput
- LanguageMetaInternal
- LanguageRef
- Link
- LinkExpression
- LinkExpressionInput
- LinkExpressionMutations
- LinkExpressionUpdated
- LinkInput
- LinkMutations
- LinkQuery
- Literal
- ModelQueryBuilder
- Neighbourhood
- NeighbourhoodExpression
- NeighbourhoodProxy
- Notification
- NotificationInput
- OnlineAgent
- PaymentRequestResult
- Perspective
- PerspectiveDiff
- PerspectiveDiffExpression
- PerspectiveExpression
- PerspectiveHandle
- PerspectiveInput
- PerspectiveProxy
- PerspectiveUnsignedInput
- QuerySubscriptionProxy
- Resource
- ResourceInput
- RuntimeInfo
- SHACLFlow
- SHACLShape
- SentMessage
- SmartLiteral
- Subject
- TriggeredNotification
- UserCreationResult
- UserStatistics
- VerificationRequestResult
- WakerSubscriptionManager
Interfaces
- AD4MAction
- Ad4mModelLike
- AgentService
- ConformanceCondition
- DirectMessageAdapter
- ExpressionAdapter
- ExpressionUI
- FlagOptions
- FlowState
- FlowTransition
- GetAllAdapter
- GetByAuthorAdapter
- HolochainLanguageDelegate
- IncludeMap
- InitializeArgs
- Interaction
- JSONSchema
- JSONSchemaProperty
- JSONSchemaToModelOptions
- Language
- LanguageAdapter
- LanguageContext
- LinkPattern
- LinkSyncAdapter
- MentionMessage
- ModelConfig
- ModelMetadata
- PropertyMetadata
- PropertyMetadataEntry
- PropertyOptions
- PublicSharing
- ReadOnlyLanguage
- RelationMetadata
- RelationMetadataEntry
- RelationOptions
- SHACLPropertyShape
- SettingsUI
- SignaturesService
- TelepresenceAdapter
- WakerLogger
- WakerSubscription
- WakerSubscriptionManagerOptions
Type Aliases
- Ad4mSignalCB
- Address
- AgentAppsUpdatedCallback
- AgentStatusChangedCallback
- AgentUpdatedCallback
- AllInstancesResult
- ConformanceFilterFn
- DID
- FlowableCondition
- GetOptions
- HasManyMethods
- HostingUserInfoChangedCallback
- LinkStatus
- MessageCallback
- Order
- PaginationResult
- ParentScope
- PerspectiveDiffObserver
- Query
- RelationSubQuery
- ResultsWithTotalCount
- StatusCallback
- SyncStateChangeObserver
- TelepresenceSignalCallback
- ValueTuple
- Where
- WhereCondition
- WhereOps
Variables
Decorators Functions
Other Functions
- ExpressionGeneric
- ExpressionGenericInput
- assignValuesToInstance
- buildAuthorAndTimestampQuery
- buildConformanceFilter
- buildConformanceGetter
- buildCountQuery
- buildGraphTraversalWhereClause
- buildLimitQuery
- buildModelFromJSONSchema
- buildOffsetQuery
- buildOrderQuery
- buildParentQuery
- buildPropertiesQuery
- buildSDNA
- buildSHACL
- buildSurrealQLQuery
- buildWhereQuery
- capSentence
- determineNamespace
- determinePredicate
- escapeSurrealString
- evaluateCustomGettersForInstance
- exprRef2String
- formatList
- generatePrologFacts
- getDefaultValueForType
- getPropertiesMetadata
- getPropertyOption
- getRelationsMetadata
- hydrateFromLinks
- hydratePropertyValue
- hydrateRelations
- isArrayType
- isExpression
- isLink
- isNumericType
- isObjectType
- isSchemaType
- linkEqual
- matchesCondition
- normalizeNamespaceString
- normalizeSchemaType
- normalizeValue
- parseExprUrl
- resolveParentPredicate
- setPropertyRegistryEntry
- setRelationRegistryEntry
Type Aliases
Ad4mSignalCB
Ƭ Ad4mSignalCB: (signal: any) => void
Type declaration
▸ (signal): void
Parameters
| Name | Type |
|---|---|
signal | any |
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
| Name | Type |
|---|---|
agent | Agent |
Returns
null
Defined in
agent/AgentClient.ts:83 (opens in a new tab)
AgentUpdatedCallback
Ƭ AgentUpdatedCallback: (agent: Agent) => null
Type declaration
▸ (agent): null
Parameters
| Name | Type |
|---|---|
agent | Agent |
Returns
null
Defined in
agent/AgentClient.ts:82 (opens in a new tab)
AllInstancesResult
Ƭ AllInstancesResult: Object
Type declaration
| Name | Type |
|---|---|
AllInstances | Ad4mModel[] |
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
| Name | Type |
|---|---|
relationPredicate | string |
targetClass | Ad4mModelLike |
Returns
{ conformanceConditions: ConformanceCondition[] ; getter: string } | undefined
Defined in
model/shacl-gen.ts:17 (opens in a new tab)
DID
Ƭ DID: string
Defined in
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
| Name | Type |
|---|---|
Keys | extends string |
Defined in
model/decorators.ts:711 (opens in a new tab)
HostingUserInfoChangedCallback
Ƭ HostingUserInfoChangedCallback: (info: HostingUserInfo) => void
Type declaration
▸ (info): void
Parameters
| Name | Type |
|---|---|
info | HostingUserInfo |
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
| Name | Type |
|---|---|
message | PerspectiveExpression |
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
| Name | Type |
|---|---|
pageNumber | number |
pageSize | number |
results | T[] |
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
| Name | Type |
|---|---|
diff | PerspectiveDiff |
Returns
void
Defined in
language/Language.ts:151 (opens in a new tab)
Query
Ƭ Query: Object
Type declaration
| Name | Type | Description |
|---|---|---|
count? | boolean | - |
include? | IncludeMap | - |
limit? | number | - |
offset? | number | - |
order? | Order | - |
parent? | ParentScope | Filter 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
| Name | Type |
|---|---|
results | T[] |
totalCount? | number |
Defined in
model/types.ts:104 (opens in a new tab)
StatusCallback
Ƭ StatusCallback: (caller: DID) => Perspective
Type declaration
▸ (caller): Perspective
Parameters
| Name | Type |
|---|---|
caller | DID |
Returns
Defined in
language/Language.ts:205 (opens in a new tab)
SyncStateChangeObserver
Ƭ SyncStateChangeObserver: (state: PerspectiveState) => void
Type declaration
▸ (state): void
Parameters
| Name | Type |
|---|---|
state | PerspectiveState |
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
| Name | Type |
|---|---|
payload | PerspectiveExpression |
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
| Name | Type |
|---|---|
between | [number, number] |
contains | string | number |
gt | number |
gte | number |
lt | number |
lte | number |
not | string | 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
| Name | Type |
|---|---|
opts | RelationOptions |
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
| Name | Type |
|---|---|
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
| Name | Type |
|---|---|
opts | RelationOptions |
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
| Name | Type |
|---|---|
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
| Name | Type | Description |
|---|---|---|
opts | FlagOptions | Flag configuration |
Returns
fn
▸ <T>(target, key): void
Type parameters
| Name |
|---|
T |
Parameters
| Name | Type |
|---|---|
target | T |
key | keyof 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
| Name | Type |
|---|---|
opts | RelationOptions |
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
| Name | Type |
|---|---|
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
| Name | Type |
|---|---|
opts | RelationOptions |
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
| Name | Type |
|---|---|
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
| Name | Type | Description |
|---|---|---|
opts | ModelConfig | Model configuration |
Returns
fn
▸ (target): void
Parameters
| Name | Type |
|---|---|
target | any |
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
| Name | Type | Description |
|---|---|---|
opts | PropertyOptions | Property configuration (same options as @Property) |
Returns
fn
▸ <T>(target, key): void
Type parameters
| Name |
|---|
T |
Parameters
| Name | Type |
|---|---|
target | T |
key | keyof 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
| Name | Type | Description |
|---|---|---|
opts | PropertyOptions | Property configuration |
Returns
fn
▸ <T>(target, key): void
Type parameters
| Name |
|---|
T |
Parameters
| Name | Type |
|---|---|
target | T |
key | keyof 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):
required→falsereadOnly→falseresolveLanguage→"literal"initial→undefined(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
| Name | Type | Description |
|---|---|---|
opts | PropertyOptions | Property configuration |
Returns
fn
▸ <T>(target, key): void
Type parameters
| Name |
|---|
T |
Parameters
| Name | Type |
|---|---|
target | T |
key | keyof 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
| Name | Type |
|---|---|
DataTypeClass | ClassType<DataType> |
Returns
any
Defined in
expression/Expression.ts:42 (opens in a new tab)
ExpressionGenericInput
▸ ExpressionGenericInput<DataType>(DataTypeClass): any
Type parameters
| Name |
|---|
DataType |
Parameters
| Name | Type |
|---|---|
DataTypeClass | ClassType<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
| Name | Type |
|---|---|
perspective | PerspectiveProxy |
instance | any |
values | ValueTuple[] |
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
| Name | Type | Description |
|---|---|---|
relationPredicate | string | The relation's predicate URI (e.g. "flux://entry_type") |
targetClass | Ad4mModelLike | The 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
| Name | Type | Description |
|---|---|---|
relationPredicate | string | The relation's predicate URI (e.g. "flux://entry_type") |
targetClass | any | The 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
| Name | Type |
|---|---|
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
| Name | Type | Description |
|---|---|---|
metadata | ModelMetadata | Model metadata from getModelMetadata() |
allRelationsMetadata | Record<string, RelationMetadataEntry> | Full relation metadata (needed for belongs-to direction detection) |
where? | Where | User-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
| Name | Type |
|---|---|
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
| Name | Type | Description |
|---|---|---|
BaseClass | typeof Ad4mModel | The Ad4mModel class (or subclass) to extend |
schema | JSONSchema | JSON Schema definition |
options | JSONSchemaToModelOptions | Configuration options |
Returns
typeof Ad4mModel
Generated Ad4mModel subclass
Defined in
model/json-schema.ts:263 (opens in a new tab)
buildOffsetQuery
▸ buildOffsetQuery(offset?): string
Parameters
| Name | Type |
|---|---|
offset? | number |
Returns
string
Defined in
model/query-prolog.ts:140 (opens in a new tab)
buildOrderQuery
▸ buildOrderQuery(order?): string
Parameters
| Name | Type |
|---|---|
order? | Order |
Returns
string
Defined in
model/query-prolog.ts:120 (opens in a new tab)
buildParentQuery
▸ buildParentQuery(parent, resolvedPredicate?): string
Parameters
| Name | Type |
|---|---|
parent | ParentScope |
resolvedPredicate? | string |
Returns
string
Defined in
model/query-prolog.ts:13 (opens in a new tab)
buildPropertiesQuery
▸ buildPropertiesQuery(properties?): string
Parameters
| Name | Type |
|---|---|
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
| Name | Type | Description |
|---|---|---|
subjectName | string | The model's registered name (from @Model({ name })) |
obj | any | target.prototype — used to inspect prototype methods (e.g. setter stubs, subjectConstructor, isSubjectInstance) |
properties | Record<string, PropertyMetadataEntry> | Merged property metadata (from getPropertiesMetadata) |
allRelationsMeta | Record<string, RelationMetadataEntry> | Merged relation metadata (from getRelationsMetadata) |
Returns
Object
| Name | Type |
|---|---|
name | string |
sdna | string |
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
| Name | Type | Description |
|---|---|---|
subjectName | string | The model's registered name (from @Model({ name })) |
target | any | The class constructor (used for prototype access, inheritance chain, and relation target resolution) |
properties | Record<string, PropertyMetadataEntry> | Merged property metadata (from getPropertiesMetadata) |
allRelationsMeta | Record<string, RelationMetadataEntry> | Merged relation metadata (from getRelationsMetadata) |
conformanceFilterFn | ConformanceFilterFn | Injected conformance-filter builder (avoids circular dependency back into decorators.ts) |
Returns
Object
| Name | Type |
|---|---|
name | string |
shape | SHACLShape |
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:
- Filters nodes by required predicates (conformance check)
- Applies user WHERE conditions
- Fetches all outgoing links for hydration
Parameters
| Name | Type | Description |
|---|---|---|
metadata | ModelMetadata | Model metadata from getModelMetadata() |
allRelationsMetadata | Record<string, RelationMetadataEntry> | Full relation registry (for belongs-to detection) |
query | Query | Query parameters |
modelClass | any | The 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
| Name | Type |
|---|---|
where | Where |
Returns
string
Defined in
model/query-prolog.ts:48 (opens in a new tab)
capSentence
▸ capSentence(cap): string
Parameters
| Name | Type |
|---|---|
cap | any |
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:
- Explicit namespace in options
- x-ad4m metadata in schema
- Infer from schema title
- Try to extract from $id
- Error if nothing works
Parameters
| Name | Type |
|---|---|
schema | JSONSchema |
options | JSONSchemaToModelOptions |
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:
- Explicit property mapping
- x-ad4m metadata in property schema
- Predicate template
- Custom predicate generator
- Default: namespace + property name
Parameters
| Name | Type |
|---|---|
schema | JSONSchema |
propertyName | string |
propertySchema | JSONSchemaProperty |
namespace | string |
options | JSONSchemaToModelOptions |
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
| Name | Type | Description |
|---|---|---|
value | string | The 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
| Name | Type |
|---|---|
instance | any |
perspective | PerspectiveProxy |
metadata | ModelMetadata |
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
| Name | Type |
|---|---|
ref | ExpressionRef |
Returns
string
Defined in
expression/ExpressionRef.ts:22 (opens in a new tab)
formatList
▸ formatList(list): any
Parameters
| Name | Type |
|---|---|
list | any |
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 recognizer —
modelName(X)— matches instances of the model - Property getters —
modelName_propName(X, Value)— one per property - Relation getters —
modelName_relName(X, Values)— one per relation
Parameters
| Name | Type | Description |
|---|---|---|
ModelClass | typeof Ad4mModel | A 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
| Name | Type |
|---|---|
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
| Name | Type |
|---|---|
ctor | Function |
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:
- Property-specific options
- x-ad4m metadata in property
- Global option
- Default value
Parameters
| Name | Type |
|---|---|
propertyName | string |
propertySchema | JSONSchemaProperty |
options | JSONSchemaToModelOptions |
optionName | keyof 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
| Name | Type |
|---|---|
ctor | Function |
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
| Name | Type | Description |
|---|---|---|
instance | any | The blank model instance to populate |
links | { author?: string ; predicate: string ; target: string ; timestamp?: string | number }[] | Array of link objects (predicate, target, author?, timestamp?) |
metadata | ModelMetadata | Model metadata from getModelMetadata() |
perspective | PerspectiveProxy | The 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
| Name | Type | Description |
|---|---|---|
target | string | The raw target string from the link |
propMeta | PropertyMetadata | Property metadata from the decorator registry |
perspective | PerspectiveProxy | The perspective for expression resolution |
expectedType? | string | Optional 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
| Name | Type | Description |
|---|---|---|
modelClass | any | The model class whose relation metadata to read |
instances | T[] | The instances whose relations should be hydrated |
perspective | PerspectiveProxy | The perspective to fetch related instances from |
includeMap | IncludeMap | Describes which relations to hydrate |
Returns
Promise<void>
Defined in
model/hydration.ts:564 (opens in a new tab)
isArrayType
▸ isArrayType(schema): boolean
Parameters
| Name | Type |
|---|---|
schema | JSONSchemaProperty |
Returns
boolean
Defined in
model/json-schema.ts:85 (opens in a new tab)
isExpression
▸ isExpression(e): boolean
Parameters
| Name | Type |
|---|---|
e | any |
Returns
boolean
Defined in
expression/Expression.ts:97 (opens in a new tab)
isLink
▸ isLink(l): boolean
Parameters
| Name | Type |
|---|---|
l | any |
Returns
boolean
Defined in
links/Links.ts:91 (opens in a new tab)
isNumericType
▸ isNumericType(schema): boolean
Parameters
| Name | Type |
|---|---|
schema | JSONSchemaProperty |
Returns
boolean
Defined in
model/json-schema.ts:93 (opens in a new tab)
isObjectType
▸ isObjectType(schema): boolean
Parameters
| Name | Type |
|---|---|
schema | JSONSchemaProperty |
Returns
boolean
Defined in
model/json-schema.ts:89 (opens in a new tab)
isSchemaType
▸ isSchemaType(schema, expectedType): boolean
Parameters
| Name | Type |
|---|---|
schema | JSONSchemaProperty |
expectedType | string |
Returns
boolean
Defined in
model/json-schema.ts:81 (opens in a new tab)
linkEqual
▸ linkEqual(l1, l2): boolean
Parameters
| Name | Type |
|---|---|
l1 | LinkExpression |
l2 | LinkExpression |
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
| Name | Type |
|---|---|
value | any |
condition | WhereCondition |
Returns
boolean
Defined in
model/hydration.ts:43 (opens in a new tab)
normalizeNamespaceString
▸ normalizeNamespaceString(namespace): string
Parameters
| Name | Type |
|---|---|
namespace | string |
Returns
string
Defined in
model/json-schema.ts:60 (opens in a new tab)
normalizeSchemaType
▸ normalizeSchemaType(type?): string | undefined
Parameters
| Name | Type |
|---|---|
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
| Name | Type |
|---|---|
value | any |
Returns
any
Defined in
model/hydration.ts:31 (opens in a new tab)
parseExprUrl
▸ parseExprUrl(url): ExpressionRef
Parameters
| Name | Type |
|---|---|
url | string |
Returns
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 whosetarget()matcheschildCtor
- With
Parameters
| Name | Type |
|---|---|
parent | ParentScope |
childCtor | Function |
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
| Name | Type |
|---|---|
ctor | Function |
propName | string |
meta | PropertyMetadataEntry & { 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
| Name | Type |
|---|---|
ctor | Function |
relName | string |
meta | RelationMetadataEntry |
Returns
void