@coasys/ad4m 0.12.0-rc1-dev.4 → 0.12.0-rc2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (166) hide show
  1. package/lib/index.cjs +5052 -4446
  2. package/lib/index.js +5019 -4442
  3. package/lib/src/agent/AgentClient.d.ts +4 -0
  4. package/lib/src/agent/AgentClient.js +34 -0
  5. package/lib/src/index.d.ts +2 -3
  6. package/lib/src/index.js +2 -3
  7. package/lib/src/model/Ad4mModel.d.ts +8 -782
  8. package/lib/src/model/Ad4mModel.js +160 -2354
  9. package/lib/src/model/ModelQueryBuilder.d.ts +370 -0
  10. package/lib/src/model/ModelQueryBuilder.js +556 -0
  11. package/lib/src/model/decorators.d.ts +71 -23
  12. package/lib/src/model/decorators.js +133 -384
  13. package/lib/src/model/hydration.d.ts +102 -0
  14. package/lib/src/model/hydration.js +709 -0
  15. package/lib/src/model/index.d.ts +20 -0
  16. package/lib/src/model/index.js +20 -0
  17. package/lib/src/model/{schema/fromJSONSchema.d.ts → json-schema.d.ts} +45 -12
  18. package/lib/src/model/json-schema.js +326 -0
  19. package/lib/src/model/prolog-facts.d.ts +37 -0
  20. package/lib/src/model/{prolog/generatePrologFacts.js → prolog-facts.js} +47 -52
  21. package/lib/src/model/query-common.d.ts +14 -0
  22. package/lib/src/model/query-common.js +36 -0
  23. package/lib/src/model/query-prolog.d.ts +15 -0
  24. package/lib/src/model/query-prolog.js +140 -0
  25. package/lib/src/model/query-surreal.d.ts +44 -0
  26. package/lib/src/model/query-surreal.js +249 -0
  27. package/lib/src/model/relation-filtering.test.js +838 -0
  28. package/lib/src/model/sdna.d.ts +14 -0
  29. package/lib/src/model/sdna.js +141 -0
  30. package/lib/src/model/shacl-gen.d.ts +31 -0
  31. package/lib/src/model/shacl-gen.js +246 -0
  32. package/lib/src/model/surreal-utils.d.ts +42 -0
  33. package/lib/src/model/surreal-utils.js +128 -0
  34. package/lib/src/model/types.d.ts +75 -96
  35. package/lib/src/model/types.js +4 -4
  36. package/lib/src/model/util.d.ts +4 -5
  37. package/lib/src/model/util.js +12 -32
  38. package/lib/src/perspectives/PerspectiveClient.d.ts +1 -1
  39. package/lib/src/perspectives/PerspectiveProxy.d.ts +1 -1
  40. package/lib/src/perspectives/WakerSubscriptionManager.d.ts +79 -0
  41. package/lib/src/perspectives/WakerSubscriptionManager.js +196 -0
  42. package/lib/src/runtime/RuntimeResolver.d.ts +14 -0
  43. package/lib/src/runtime/RuntimeResolver.js +73 -0
  44. package/lib/src/schema.gql +14 -0
  45. package/lib/src/shacl/SHACLShape.d.ts +23 -0
  46. package/lib/src/shacl/SHACLShape.js +45 -0
  47. package/lib/src/typeDefs.js +14 -0
  48. package/package.json +13 -8
  49. package/src/agent/AgentClient.ts +45 -0
  50. package/src/index.ts +2 -3
  51. package/src/model/Ad4mModel.ts +1089 -3686
  52. package/src/model/ModelQueryBuilder.ts +617 -0
  53. package/src/model/Subject.ts +1 -1
  54. package/src/model/decorators.ts +218 -453
  55. package/src/model/hydration.ts +796 -0
  56. package/src/model/index.ts +21 -0
  57. package/src/model/json-schema.ts +424 -0
  58. package/src/model/prolog-facts.ts +145 -0
  59. package/src/model/query-common.ts +48 -0
  60. package/src/model/query-prolog.ts +148 -0
  61. package/src/model/query-surreal.ts +280 -0
  62. package/src/model/relation-filtering.test.ts +803 -0
  63. package/src/model/sdna.ts +170 -0
  64. package/src/model/shacl-gen.ts +292 -0
  65. package/src/model/surreal-utils.ts +147 -0
  66. package/src/model/types.ts +182 -0
  67. package/src/model/util.ts +13 -36
  68. package/src/perspectives/PerspectiveClient.ts +1 -1
  69. package/src/perspectives/PerspectiveProxy.ts +1 -1
  70. package/src/perspectives/WakerSubscriptionManager.ts +292 -0
  71. package/src/runtime/RuntimeResolver.ts +53 -0
  72. package/src/shacl/SHACLShape.ts +83 -0
  73. package/lib/src/Ad4mClient.test.js +0 -1204
  74. package/lib/src/Literal.test.d.ts +0 -1
  75. package/lib/src/Literal.test.js +0 -41
  76. package/lib/src/model/mutation.d.ts +0 -81
  77. package/lib/src/model/mutation.js +0 -317
  78. package/lib/src/model/parentUtils.d.ts +0 -32
  79. package/lib/src/model/parentUtils.js +0 -64
  80. package/lib/src/model/prolog/generatePrologFacts.d.ts +0 -36
  81. package/lib/src/model/prolog/index.d.ts +0 -1
  82. package/lib/src/model/prolog/index.js +0 -1
  83. package/lib/src/model/query/ModelQueryBuilder.d.ts +0 -82
  84. package/lib/src/model/query/ModelQueryBuilder.js +0 -115
  85. package/lib/src/model/query/QueryBuilder.d.ts +0 -101
  86. package/lib/src/model/query/QueryBuilder.js +0 -193
  87. package/lib/src/model/query/SurrealQueryBuilder.d.ts +0 -48
  88. package/lib/src/model/query/SurrealQueryBuilder.js +0 -371
  89. package/lib/src/model/query/fetchInstance.d.ts +0 -24
  90. package/lib/src/model/query/fetchInstance.js +0 -144
  91. package/lib/src/model/query/hydration.d.ts +0 -54
  92. package/lib/src/model/query/hydration.js +0 -214
  93. package/lib/src/model/query/operations.d.ts +0 -59
  94. package/lib/src/model/query/operations.js +0 -384
  95. package/lib/src/model/query/snapshot.d.ts +0 -59
  96. package/lib/src/model/query/snapshot.js +0 -106
  97. package/lib/src/model/query/surrealCompiler.d.ts +0 -42
  98. package/lib/src/model/query/surrealCompiler.js +0 -304
  99. package/lib/src/model/schema/fromJSONSchema.js +0 -264
  100. package/lib/src/model/schema/metadata.d.ts +0 -15
  101. package/lib/src/model/schema/metadata.js +0 -112
  102. package/lib/src/model/subscription.d.ts +0 -47
  103. package/lib/src/model/subscription.js +0 -231
  104. package/lib/src/model/transaction.d.ts +0 -27
  105. package/lib/src/model/transaction.js +0 -32
  106. package/lib/src/shims/reflect-metadata.d.ts +0 -0
  107. package/lib/src/shims/type-graphql.d.ts +0 -32
  108. package/lib/src/src/Ad4mClient.d.ts +0 -28
  109. package/lib/src/src/Address.d.ts +0 -1
  110. package/lib/src/src/DID.d.ts +0 -1
  111. package/lib/src/src/Exception.d.ts +0 -7
  112. package/lib/src/src/Literal.d.ts +0 -7
  113. package/lib/src/src/PubSub.d.ts +0 -17
  114. package/lib/src/src/SmartLiteral.d.ts +0 -12
  115. package/lib/src/src/agent/Agent.d.ts +0 -110
  116. package/lib/src/src/agent/AgentClient.d.ts +0 -62
  117. package/lib/src/src/agent/AgentResolver.d.ts +0 -30
  118. package/lib/src/src/agent/AgentStatus.d.ts +0 -8
  119. package/lib/src/src/ai/AIClient.d.ts +0 -32
  120. package/lib/src/src/ai/AIResolver.d.ts +0 -75
  121. package/lib/src/src/ai/Tasks.d.ts +0 -37
  122. package/lib/src/src/buildSchema.d.ts +0 -1
  123. package/lib/src/src/expression/Expression.d.ts +0 -28
  124. package/lib/src/src/expression/ExpressionClient.d.ts +0 -13
  125. package/lib/src/src/expression/ExpressionRef.d.ts +0 -9
  126. package/lib/src/src/expression/ExpressionResolver.d.ts +0 -10
  127. package/lib/src/src/index.d.ts +0 -35
  128. package/lib/src/src/jestSetup.d.ts +0 -1
  129. package/lib/src/src/language/Icon.d.ts +0 -4
  130. package/lib/src/src/language/Language.d.ts +0 -206
  131. package/lib/src/src/language/LanguageClient.d.ts +0 -17
  132. package/lib/src/src/language/LanguageContext.d.ts +0 -37
  133. package/lib/src/src/language/LanguageHandle.d.ts +0 -9
  134. package/lib/src/src/language/LanguageMeta.d.ts +0 -35
  135. package/lib/src/src/language/LanguageRef.d.ts +0 -6
  136. package/lib/src/src/language/LanguageResolver.d.ts +0 -19
  137. package/lib/src/src/links/Links.d.ts +0 -39
  138. package/lib/src/src/links/Links.test.d.ts +0 -1
  139. package/lib/src/src/model/Ad4mModel.d.ts +0 -1438
  140. package/lib/src/src/model/Ad4mModel.test.d.ts +0 -1
  141. package/lib/src/src/model/Subject.d.ts +0 -25
  142. package/lib/src/src/model/decorators.d.ts +0 -545
  143. package/lib/src/src/model/util.d.ts +0 -12
  144. package/lib/src/src/neighbourhood/Neighbourhood.d.ts +0 -10
  145. package/lib/src/src/neighbourhood/NeighbourhoodClient.d.ts +0 -25
  146. package/lib/src/src/neighbourhood/NeighbourhoodProxy.d.ts +0 -19
  147. package/lib/src/src/neighbourhood/NeighbourhoodProxy.test.d.ts +0 -1
  148. package/lib/src/src/neighbourhood/NeighbourhoodResolver.d.ts +0 -24
  149. package/lib/src/src/perspectives/LinkQuery.d.ts +0 -11
  150. package/lib/src/src/perspectives/Perspective.d.ts +0 -38
  151. package/lib/src/src/perspectives/Perspective.test.d.ts +0 -1
  152. package/lib/src/src/perspectives/PerspectiveClient.d.ts +0 -97
  153. package/lib/src/src/perspectives/PerspectiveDiff.d.ts +0 -9
  154. package/lib/src/src/perspectives/PerspectiveHandle.d.ts +0 -18
  155. package/lib/src/src/perspectives/PerspectiveProxy.d.ts +0 -865
  156. package/lib/src/src/perspectives/PerspectiveResolver.d.ts +0 -57
  157. package/lib/src/src/runtime/RuntimeClient.d.ts +0 -56
  158. package/lib/src/src/runtime/RuntimeResolver.d.ts +0 -132
  159. package/lib/src/src/shacl/SHACLFlow.d.ts +0 -171
  160. package/lib/src/src/shacl/SHACLFlow.test.d.ts +0 -1
  161. package/lib/src/src/shacl/SHACLShape.d.ts +0 -117
  162. package/lib/src/src/shacl/SHACLShape.test.d.ts +0 -1
  163. package/lib/src/src/typeDefs.d.ts +0 -1
  164. package/lib/src/src/unwrapApolloResult.d.ts +0 -2
  165. package/lib/src/src/utils.d.ts +0 -25
  166. /package/lib/src/{Ad4mClient.test.d.ts → model/relation-filtering.test.d.ts} +0 -0
@@ -1,213 +1,15 @@
1
1
  import { Literal } from "../Literal";
2
2
  import { Link } from "../links/Links";
3
3
  import { LinkQuery } from "../perspectives/LinkQuery";
4
- import { makeRandomId, Model, getPropertiesMetadata, getRelationsMetadata, setPropertyRegistryEntry, setRelationRegistryEntry } from "./decorators";
5
- import { propertyNameToSetterName } from "./util";
6
- import { escapeSurrealString } from "../utils";
7
- function capitalize(word) {
8
- return word.charAt(0).toUpperCase() + word.slice(1);
9
- }
10
- /**
11
- * Resolves the predicate for a parent query.
12
- *
13
- * Uses TS discriminated union narrowing:
14
- * - Raw form (`{ id, predicate }`) → predicate used as-is
15
- * - Model form (`{ model, id, field? }`) → lookup from relation metadata
16
- * - With `field`: direct key lookup
17
- * - Without `field`: scan for a relation whose `target()` matches `childCtor`
18
- */
19
- function resolveParentPredicate(parent, childCtor) {
20
- // Raw form — explicit predicate
21
- if ('predicate' in parent)
22
- return parent.predicate;
23
- // Model form — resolve from relation metadata
24
- const { model } = parent;
25
- const relMeta = getRelationsMetadata(model);
26
- // Direct lookup by field name when provided
27
- if (parent.field) {
28
- const entry = relMeta[parent.field];
29
- if (!entry) {
30
- throw new Error(`parent(): field "${parent.field}" is not a registered relation on ${model.name}`);
31
- }
32
- return entry.predicate;
33
- }
34
- // Fallback: scan for a relation whose target matches the child class
35
- for (const [, entry] of Object.entries(relMeta)) {
36
- if (entry.target && entry.target() === childCtor) {
37
- return entry.predicate;
38
- }
39
- }
40
- throw new Error(`parent(): could not resolve predicate — no relation on ${model.name} targets ${childCtor.name || 'the queried class'}`);
41
- }
42
- function buildParentQuery(parent, resolvedPredicate) {
43
- if (!parent || !resolvedPredicate)
44
- return '';
45
- return `triple("${parent.id}", "${resolvedPredicate}", Base)`;
46
- }
47
- // todo: only return Timestamp & Author from query (Base, AllLinks, and SortLinks not required)
48
- function buildAuthorAndTimestampQuery() {
49
- // Gets the author and timestamp of a Ad4mModel instance (based on the first link mentioning the base)
50
- return `
51
- findall(
52
- [T, A],
53
- link(Base, _, _, T, A),
54
- AllLinks
55
- ),
56
- sort(AllLinks, SortedLinks),
57
- SortedLinks = [[Timestamp, Author]|_]
58
- `;
59
- }
60
- function buildPropertiesQuery(properties) {
61
- // Gets the name, value, and resolve boolean for all (or some) properties on a Ad4mModel instance
62
- // Resolves literals (if property_resolve/2 is true) to their value - either the data field if it is
63
- // an Expression in JSON literal, or the direct literal value if it is a simple literal
64
- // If no properties are provided, all are included
65
- return `
66
- findall([PropertyName, PropertyValue, Resolve], (
67
- % Constrain to specified properties if provided
68
- ${properties ? `member(PropertyName, [${properties.map((name) => `"${name}"`).join(", ")}]),` : ""}
69
- resolve_property(SubjectClass, Base, PropertyName, PropertyValue, Resolve)
70
- ), Properties)
71
- `;
72
- }
73
- function buildWhereQuery(where = {}) {
74
- // Constrains the query to instances that match the provided where conditions
75
- // 'id' maps to the Prolog 'Base' variable (the base expression of the instance).
76
- function formatValue(value) {
77
- // Wrap strings in quotes
78
- return typeof value === "string" ? `"${value}"` : value;
79
- }
80
- return Object.entries(where)
81
- .map(([key, value]) => {
82
- const isSpecial = ["id", "author", "timestamp"].includes(key);
83
- const getter = `resolve_property(SubjectClass, Base, "${key}", Value${key}, _)`;
84
- // For 'id' the Prolog variable is always 'Base'
85
- const field = key === "id" ? "Base" : capitalize(key);
86
- // Handle direct array values (for IN conditions)
87
- if (Array.isArray(value)) {
88
- const formattedValues = value.map((v) => formatValue(v)).join(", ");
89
- if (isSpecial)
90
- return `member(${field}, [${formattedValues}])`;
91
- else
92
- return `${getter}, member(Value${key}, [${formattedValues}])`;
93
- }
94
- // Handle operation object
95
- if (typeof value === "object" && value !== null) {
96
- const { not, between, lt, lte, gt, gte } = value;
97
- // Handle NOT operation
98
- if (not !== undefined) {
99
- if (Array.isArray(not)) {
100
- // NOT IN array
101
- const formattedValues = not.map((v) => formatValue(v)).join(", ");
102
- if (isSpecial)
103
- return `\\+ member(${field}, [${formattedValues}])`;
104
- else
105
- return `${getter}, \\+ member(Value${key}, [${formattedValues}])`;
106
- }
107
- else {
108
- // NOT EQUAL
109
- if (isSpecial)
110
- return `${field} \\= ${formatValue(not)}`;
111
- else
112
- return `${getter}, Value${key} \\= ${formatValue(not)}`;
113
- }
114
- }
115
- // Handle BETWEEN
116
- if (between !== undefined && Array.isArray(between) && between.length === 2) {
117
- if (isSpecial)
118
- return `${field} >= ${between[0]}, ${field} =< ${between[1]}`;
119
- else
120
- return `${getter}, Value${key} >= ${between[0]}, Value${key} =< ${between[1]}`;
121
- }
122
- // Handle lt, lte, gt, & gte operations
123
- const operators = [
124
- { value: lt, symbol: "<" },
125
- { value: lte, symbol: "=<" },
126
- { value: gt, symbol: ">" },
127
- { value: gte, symbol: ">=" }, // GREATER THAN OR EQUAL TO
128
- ];
129
- for (const { value, symbol } of operators) {
130
- if (value !== undefined)
131
- return isSpecial ? `${field} ${symbol} ${value}` : `${getter}, Value${key} ${symbol} ${value}`;
132
- }
133
- }
134
- // Default to direct equality
135
- if (isSpecial)
136
- return `${field} = ${formatValue(value)}`;
137
- else
138
- return `${getter}, Value${key} = ${formatValue(value)}`;
139
- })
140
- .join(", ");
141
- }
142
- function buildCountQuery(count) {
143
- return count ? "length(UnsortedInstances, TotalCount)" : "";
144
- }
145
- function buildOrderQuery(order) {
146
- if (!order)
147
- return "SortedInstances = UnsortedInstances";
148
- const entries = Object.entries(order);
149
- if (entries.length === 1) {
150
- const [propertyName, direction] = entries[0];
151
- return `sort_instances(UnsortedInstances, "${propertyName}", "${direction}", SortedInstances)`;
152
- }
153
- // Multi-field sort: sort from least-significant to most-significant key
154
- // so that the final (primary) sort preserves secondary-key ordering for equal values.
155
- // The merge_sort implementation is stable (equal elements keep original order).
156
- const clauses = [];
157
- for (let i = entries.length - 1; i >= 0; i--) {
158
- const [propertyName, direction] = entries[i];
159
- const inputVar = i === entries.length - 1 ? "UnsortedInstances" : `MultiSortIntermediate${i + 1}`;
160
- const outputVar = i === 0 ? "SortedInstances" : `MultiSortIntermediate${i}`;
161
- clauses.push(`sort_instances(${inputVar}, "${propertyName}", "${direction}", ${outputVar})`);
162
- }
163
- return clauses.join(",\n ");
164
- }
165
- function buildOffsetQuery(offset) {
166
- if (!offset || offset < 0)
167
- return "InstancesWithOffset = SortedInstances";
168
- return `skipN(SortedInstances, ${offset}, InstancesWithOffset)`;
169
- }
170
- function buildLimitQuery(limit) {
171
- if (!limit || limit < 0)
172
- return "AllInstances = InstancesWithOffset";
173
- return `takeN(InstancesWithOffset, ${limit}, AllInstances)`;
174
- }
175
- function normalizeNamespaceString(namespace) {
176
- if (!namespace)
177
- return '';
178
- if (namespace.includes('://')) {
179
- const [scheme, rest] = namespace.split('://');
180
- const path = (rest || '').replace(/\/+$/, '');
181
- return `${scheme}://${path}`;
182
- }
183
- else {
184
- return namespace.replace(/\/+$/, '');
185
- }
186
- }
187
- function normalizeSchemaType(type) {
188
- if (!type)
189
- return undefined;
190
- if (typeof type === "string")
191
- return type;
192
- if (Array.isArray(type) && type.length > 0) {
193
- const nonNull = type.find((t) => t !== "null");
194
- return nonNull || type[0];
195
- }
196
- return undefined;
197
- }
198
- function isSchemaType(schema, expectedType) {
199
- return normalizeSchemaType(schema.type) === expectedType;
200
- }
201
- function isArrayType(schema) {
202
- return isSchemaType(schema, "array");
203
- }
204
- function isObjectType(schema) {
205
- return isSchemaType(schema, "object");
206
- }
207
- function isNumericType(schema) {
208
- const normalized = normalizeSchemaType(schema.type);
209
- return normalized === "number" || normalized === "integer";
210
- }
4
+ import { makeRandomId } from "./util";
5
+ import { getPropertiesMetadata, getRelationsMetadata } from "./decorators";
6
+ import { formatSurrealValue } from "./surreal-utils";
7
+ import { resolveParentPredicate } from "./query-common";
8
+ import { buildParentQuery, buildAuthorAndTimestampQuery, buildPropertiesQuery, buildWhereQuery, buildCountQuery, buildOrderQuery, buildOffsetQuery, buildLimitQuery } from "./query-prolog";
9
+ import { isArrayType, determinePredicate, determineNamespace, buildModelFromJSONSchema } from "./json-schema";
10
+ import { buildSurrealQLQuery } from "./query-surreal";
11
+ import { ModelQueryBuilder } from "./ModelQueryBuilder";
12
+ import { normalizeValue, matchesCondition, hydrateFromLinks, assignValuesToInstance as _assignValuesToInstance, evaluateCustomGettersForInstance, hydrateRelations, } from "./hydration";
211
13
  /**
212
14
  * Base class for defining data models in AD4M.
213
15
  *
@@ -429,6 +231,9 @@ export class Ad4mModel {
429
231
  ...(options.local !== undefined && { local: options.local }),
430
232
  ...(options.getter !== undefined && { getter: options.getter }),
431
233
  direction: (options.kind === 'belongsToMany' || options.kind === 'belongsToOne') ? 'reverse' : 'forward',
234
+ ...(options.target !== undefined && { target: options.target }),
235
+ ...(options.filter !== undefined && { filter: options.filter }),
236
+ ...(options.where !== undefined && { where: options.where }),
432
237
  };
433
238
  }
434
239
  // Fallback: If both structures are empty but a JSON schema is attached, derive from it
@@ -443,7 +248,7 @@ export class Ad4mModel {
443
248
  if (schema.properties) {
444
249
  for (const [propertyName, propertySchema] of Object.entries(schema.properties)) {
445
250
  const isArray = isArrayType(propertySchema);
446
- const predicate = this.determinePredicate(schema, propertyName, propertySchema, this.determineNamespace(schema, options), options);
251
+ const predicate = determinePredicate(schema, propertyName, propertySchema, determineNamespace(schema, options), options);
447
252
  if (isArray) {
448
253
  relationsMetadata[propertyName] = {
449
254
  name: propertyName,
@@ -514,7 +319,7 @@ export class Ad4mModel {
514
319
  return this._perspective;
515
320
  }
516
321
  /**
517
- * Get property metadata from decorator (Phase 1: Prolog-free refactor)
322
+ * Get property metadata from decorator.
518
323
  * @private
519
324
  */
520
325
  getPropertyMetadata(key) {
@@ -532,8 +337,7 @@ export class Ad4mModel {
532
337
  return rels[key];
533
338
  }
534
339
  /**
535
- * Generate property setter action from metadata (Phase 1: Prolog-free refactor)
536
- * Replaces Prolog query: property_setter(C, key, Setter)
340
+ * Generate property setter action from metadata.
537
341
  * @private
538
342
  */
539
343
  generatePropertySetterAction(key, metadata) {
@@ -563,8 +367,7 @@ export class Ad4mModel {
563
367
  }];
564
368
  }
565
369
  /**
566
- * Generate relation action from metadata (Phase 1: Prolog-free refactor)
567
- * Replaces Prolog queries: collection_adder, collection_remover, collection_setter
370
+ * Generate relation action from metadata.
568
371
  * @private
569
372
  */
570
373
  generateRelationAction(key, actionType) {
@@ -588,279 +391,16 @@ export class Ad4mModel {
588
391
  ...(metadata.local && { local: true })
589
392
  }];
590
393
  }
591
- // ──────────────────────────────────────────────────────────
592
- // Unified hydration helpers
593
- // ──────────────────────────────────────────────────────────
594
- /**
595
- * Resolves a raw link target value into a hydrated property value.
596
- *
597
- * Handles, in order:
598
- * 1. Non-literal expression resolution (`perspective.getExpression`)
599
- * 2. Literal URI parsing (`Literal.fromUrl(…).get()`)
600
- * 3. Primitive type coercion (string → number / boolean)
601
- * 4. Transform function application
602
- *
603
- * @param target - The raw target string from the link
604
- * @param propMeta - Property metadata from the decorator registry
605
- * @param perspective - The perspective for expression resolution
606
- * @param expectedType - Optional JS typeof hint for coercion (e.g. 'number')
607
- * @returns The resolved value
608
- * @private
609
- */
610
- static async hydratePropertyValue(target, propMeta, perspective, expectedType) {
611
- let value = target;
612
- if (target !== undefined && target !== null && target !== '') {
613
- // Non-literal expression resolution
614
- if (propMeta.resolveLanguage != null &&
615
- propMeta.resolveLanguage !== 'literal' &&
616
- typeof target === 'string' &&
617
- !target.startsWith('literal://')) {
618
- try {
619
- const expression = await perspective.getExpression(target);
620
- if (expression) {
621
- try {
622
- value = JSON.parse(expression.data);
623
- }
624
- catch {
625
- value = expression.data;
626
- }
627
- }
628
- }
629
- catch (e) {
630
- console.warn(`hydratePropertyValue: failed to resolve expression for "${propMeta.name}":`, e);
631
- }
632
- }
633
- // Literal URI parsing
634
- else if (propMeta.resolveLanguage === 'literal' &&
635
- typeof target === 'string' &&
636
- target.startsWith('literal://')) {
637
- try {
638
- const parsed = Literal.fromUrl(target).get();
639
- value = parsed.data !== undefined ? parsed.data : parsed;
640
- }
641
- catch {
642
- // Keep raw value
643
- }
644
- }
645
- // Primitive type coercion
646
- else if (typeof target === 'string' && expectedType) {
647
- if (expectedType === 'number')
648
- value = Number(target);
649
- else if (expectedType === 'boolean')
650
- value = target === 'true' || target === '1';
651
- }
652
- }
653
- // Transform function
654
- if (propMeta.transform && typeof propMeta.transform === 'function') {
655
- value = propMeta.transform(value);
656
- }
657
- return value;
658
- }
659
394
  /**
660
- * Hydrates an instance from an array of raw links.
661
- *
662
- * Processes properties (latest-wins semantics), relations
663
- * (chronological accumulation), and timestamps/author in a single
664
- * pass over the links array.
665
- *
666
- * @param instance - The blank model instance to populate
667
- * @param links - Array of link objects (predicate, target, author?, timestamp?)
668
- * @param metadata - Model metadata from `getModelMetadata()`
669
- * @param perspective - The perspective for expression resolution
670
- * @param requestedProperties - Optional sparse fieldset; when provided, only these
671
- * property names are hydrated (relations are unaffected).
672
- * Omit or pass `undefined` to hydrate all properties.
673
- * @private
395
+ * Assigns decoded Prolog property values to an instance.
396
+ * Delegates to the standalone function in hydration.ts.
674
397
  */
675
- static async hydrateFromLinks(instance, links, metadata, perspective, requestedProperties) {
676
- if (!links || links.length === 0)
677
- return;
678
- let minTimestamp = null;
679
- let maxTimestamp = null;
680
- let originalAuthor = null;
681
- let latestAuthor = null;
682
- // Build predicate→propName and predicate→relName lookup maps for O(1) matching
683
- // When requestedProperties is provided, only include those properties in the map
684
- const propFilter = requestedProperties && requestedProperties.length > 0
685
- ? new Set(requestedProperties)
686
- : null;
687
- const predToProperty = new Map();
688
- for (const [propName, propMeta] of Object.entries(metadata.properties)) {
689
- if (propMeta.getter)
690
- continue; // Handled via custom getter evaluation
691
- if (propFilter && !propFilter.has(propName))
692
- continue; // Skip unrequested properties
693
- predToProperty.set(propMeta.predicate, [propName, propMeta]);
694
- }
695
- const predToRelation = new Map();
696
- for (const [relName, relMeta] of Object.entries(metadata.relations)) {
697
- if (relMeta.getter)
698
- continue;
699
- predToRelation.set(relMeta.predicate, [relName, relMeta]);
700
- }
701
- // Per-property accumulator: track all matching targets so we can pick the last (latest-wins)
702
- const propertyLatest = new Map();
703
- // Per-relation accumulator: ordered targets with metadata for sorting
704
- const relationAccum = new Map();
705
- // Single pass over all links
706
- for (let i = 0; i < links.length; i++) {
707
- const link = links[i];
708
- const { predicate, target, author, timestamp } = link;
709
- if (target === 'None' || target === undefined || target === null)
710
- continue;
711
- // Track timestamps/authors
712
- if (timestamp != null) {
713
- if (minTimestamp == null || timestamp < minTimestamp) {
714
- minTimestamp = timestamp;
715
- originalAuthor = author ?? null;
716
- }
717
- if (maxTimestamp == null || timestamp > maxTimestamp) {
718
- maxTimestamp = timestamp;
719
- latestAuthor = author ?? null;
720
- }
721
- }
722
- // Property match — accumulate for latest-wins
723
- const propEntry = predToProperty.get(predicate);
724
- if (propEntry) {
725
- const existing = propertyLatest.get(propEntry[0]);
726
- // Latest-wins: always overwrite (links are ordered ASC so last = latest)
727
- propertyLatest.set(propEntry[0], { target, timestamp });
728
- continue;
729
- }
730
- // Relation match — accumulate all
731
- const relEntry = predToRelation.get(predicate);
732
- if (relEntry) {
733
- const [relName] = relEntry;
734
- let arr = relationAccum.get(relName);
735
- if (!arr) {
736
- arr = [];
737
- relationAccum.set(relName, arr);
738
- }
739
- arr.push({ target, timestamp: timestamp ?? '', index: i });
740
- }
741
- }
742
- // Resolve properties
743
- for (const [propName, { target }] of propertyLatest) {
744
- const [, propMeta] = predToProperty.get(metadata.properties[propName].predicate);
745
- const expectedType = typeof instance[propName];
746
- instance[propName] = await this.hydratePropertyValue(target, propMeta, perspective, expectedType !== 'undefined' ? expectedType : undefined);
747
- }
748
- // Resolve relations: sort by timestamp (stable via index tiebreaker), filter empties
749
- for (const [relName, items] of relationAccum) {
750
- items.sort((a, b) => {
751
- const cmp = String(a.timestamp).localeCompare(String(b.timestamp));
752
- return cmp !== 0 ? cmp : a.index - b.index;
753
- });
754
- instance[relName] = items
755
- .map(i => i.target)
756
- .filter((v) => v !== undefined && v !== null && v !== '' && v !== 'None');
757
- }
758
- // Assign author / timestamps
759
- if (originalAuthor)
760
- instance.author = originalAuthor;
761
- if (minTimestamp != null) {
762
- instance.createdAt = typeof minTimestamp === 'string' && minTimestamp.includes('T')
763
- ? new Date(minTimestamp).getTime()
764
- : typeof minTimestamp === 'string'
765
- ? (isNaN(parseInt(minTimestamp, 10)) ? minTimestamp : parseInt(minTimestamp, 10))
766
- : minTimestamp;
767
- }
768
- if (maxTimestamp != null) {
769
- instance.updatedAt = typeof maxTimestamp === 'string' && maxTimestamp.includes('T')
770
- ? new Date(maxTimestamp).getTime()
771
- : typeof maxTimestamp === 'string'
772
- ? (isNaN(parseInt(maxTimestamp, 10)) ? maxTimestamp : parseInt(maxTimestamp, 10))
773
- : maxTimestamp;
774
- }
775
- }
776
398
  static async assignValuesToInstance(perspective, instance, values) {
777
- // Map properties to object
778
- const propsObject = Object.fromEntries(await Promise.all(values.map(async ([name, value, resolve]) => {
779
- let finalValue = value;
780
- // Handle UTF-8 byte sequences from Prolog URL decoding
781
- if (!resolve && typeof value === 'string') {
782
- // Only attempt reconstruction if the string looks like a byte string (all code points <= 0xFF)
783
- // and contains at least one high byte (>= 0x80). This avoids mangling valid Unicode.
784
- const codePoints = Array.from(value, ch => ch.codePointAt(0));
785
- const looksByteString = codePoints.every(cp => cp <= 0xFF);
786
- const hasHighByte = codePoints.some(cp => cp >= 0x80);
787
- if (looksByteString && hasHighByte) {
788
- try {
789
- const bytes = Uint8Array.from(codePoints);
790
- const decoded = new TextDecoder('utf-8', { fatal: true }).decode(bytes);
791
- if (decoded !== value)
792
- finalValue = decoded;
793
- }
794
- catch (error) {
795
- // If UTF-8 conversion fails, keep the original value
796
- console.warn(`UTF-8 byte reconstruction failed for property "${name}"`, { value, error });
797
- }
798
- }
799
- }
800
- // Resolve the value if necessary
801
- if (resolve) {
802
- let resolvedExpression = await perspective.getExpression(value);
803
- if (resolvedExpression) {
804
- try {
805
- // Attempt to parse the data as JSON
806
- finalValue = JSON.parse(resolvedExpression.data);
807
- }
808
- catch (error) {
809
- // If parsing fails, keep the original data
810
- finalValue = resolvedExpression.data;
811
- }
812
- }
813
- }
814
- // Apply transform function if it exists
815
- const propsMeta = getPropertiesMetadata(instance.constructor);
816
- const transform = propsMeta[name]?.transform;
817
- if (transform && typeof transform === "function") {
818
- finalValue = transform(finalValue);
819
- }
820
- return [name, finalValue];
821
- })));
822
- // Filter out properties that are read-only (getters without setters)
823
- const writableProps = Object.fromEntries(Object.entries(propsObject).filter(([key]) => {
824
- const descriptor = Object.getOwnPropertyDescriptor(Object.getPrototypeOf(instance), key);
825
- if (!descriptor) {
826
- // No descriptor means it's a regular property on the instance, allow it
827
- return true;
828
- }
829
- // Check if it's an accessor descriptor (has get/set) vs data descriptor (has value/writable)
830
- const isAccessor = descriptor.get !== undefined || descriptor.set !== undefined;
831
- if (isAccessor) {
832
- // Accessor descriptor: only allow if it has a setter
833
- return descriptor.set !== undefined;
834
- }
835
- else {
836
- // Data descriptor: only allow if writable is not explicitly false
837
- return descriptor.writable !== false;
838
- }
839
- }));
840
- // Assign properties to instance
841
- Object.assign(instance, writableProps);
399
+ return _assignValuesToInstance(perspective, instance, values);
842
400
  }
843
401
  // ──────────────────────────────────────────────────────────
844
402
  // Snapshot / dirty tracking
845
403
  // ──────────────────────────────────────────────────────────
846
- /**
847
- * Captures a shallow snapshot of the instance's current property and
848
- * relation values. Called automatically after hydration (`get()`,
849
- * query results). The snapshot is used by `isDirty()`,
850
- * `changedFields()`, and by `update()` to skip unchanged fields.
851
- * @private
852
- */
853
- /**
854
- * Normalize a value for snapshot storage.
855
- * Arrays of model instances are reduced to their `.id` strings so that
856
- * dirty-tracking compares stable identifiers instead of object references.
857
- */
858
- static normalizeValue(value) {
859
- if (Array.isArray(value)) {
860
- return value.map((v) => v && typeof v === 'object' && typeof v.id === 'string' ? v.id : v);
861
- }
862
- return value;
863
- }
864
404
  /**
865
405
  * @param includedRelations Controls which relation fields are recorded
866
406
  * in the snapshot for dirty-tracking:
@@ -879,7 +419,7 @@ export class Ad4mModel {
879
419
  // Always snapshot properties
880
420
  for (const propName of Object.keys(metadata.properties)) {
881
421
  const val = this[propName];
882
- snap[propName] = Ad4mModel.normalizeValue(Array.isArray(val) ? [...val] : val);
422
+ snap[propName] = normalizeValue(Array.isArray(val) ? [...val] : val);
883
423
  }
884
424
  // Snapshot relations only when appropriate:
885
425
  // undefined → all relations (backward compat)
@@ -889,7 +429,7 @@ export class Ad4mModel {
889
429
  // Full snapshot — e.g. after getData() / create()
890
430
  for (const relName of Object.keys(metadata.relations)) {
891
431
  const val = this[relName];
892
- snap[relName] = Ad4mModel.normalizeValue(Array.isArray(val) ? [...val] : val);
432
+ snap[relName] = normalizeValue(Array.isArray(val) ? [...val] : val);
893
433
  }
894
434
  }
895
435
  else if (includedRelations && Object.keys(includedRelations).length > 0) {
@@ -897,7 +437,7 @@ export class Ad4mModel {
897
437
  for (const relName of Object.keys(includedRelations)) {
898
438
  if (relName in metadata.relations) {
899
439
  const val = this[relName];
900
- snap[relName] = Ad4mModel.normalizeValue(Array.isArray(val) ? [...val] : val);
440
+ snap[relName] = normalizeValue(Array.isArray(val) ? [...val] : val);
901
441
  }
902
442
  }
903
443
  }
@@ -959,7 +499,7 @@ export class Ad4mModel {
959
499
  // setRelationValues call during innerUpdate.
960
500
  if (!(field in this._snapshot))
961
501
  continue;
962
- const current = Ad4mModel.normalizeValue(this[field]);
502
+ const current = normalizeValue(this[field]);
963
503
  const original = this._snapshot[field];
964
504
  if (Array.isArray(current) || Array.isArray(original)) {
965
505
  // Order-insensitive comparison (sorted) so reordering alone
@@ -983,7 +523,7 @@ export class Ad4mModel {
983
523
  const ctor = this.constructor;
984
524
  const metadata = ctor.getModelMetadata();
985
525
  // Query for all links from this specific node (base expression)
986
- const safeBaseExpression = ctor.formatSurrealValue(this._baseExpression);
526
+ const safeBaseExpression = formatSurrealValue(this._baseExpression);
987
527
  const linksQuery = `
988
528
  SELECT id, predicate, out.uri AS target, author, timestamp
989
529
  FROM link
@@ -994,7 +534,7 @@ export class Ad4mModel {
994
534
  if (links && links.length > 0) {
995
535
  // Core hydration: properties (latest-wins), relations, timestamps/author
996
536
  const requestedProperties = opts?.properties && opts.properties.length > 0 ? opts.properties : undefined;
997
- await ctor.hydrateFromLinks(this, links, metadata, this._perspective, requestedProperties);
537
+ await hydrateFromLinks(this, links, metadata, this._perspective, requestedProperties);
998
538
  }
999
539
  // Populate reverse relation fields (belongsToOne / belongsToMany) as string IDs.
1000
540
  const allRelsMeta = getRelationsMetadata(ctor);
@@ -1016,10 +556,13 @@ export class Ad4mModel {
1016
556
  }
1017
557
  }
1018
558
  // Evaluate SurrealQL getters
1019
- await ctor.evaluateCustomGettersForInstance(this, this._perspective, metadata);
559
+ const getterOpts = opts?.properties || opts?.include
560
+ ? { requestedProperties: opts?.properties, include: opts?.include }
561
+ : undefined;
562
+ await evaluateCustomGettersForInstance(this, this._perspective, metadata, getterOpts);
1020
563
  // Eager-load relations if requested
1021
564
  if (opts?.include) {
1022
- await ctor.hydrateRelations([this], this._perspective, opts.include);
565
+ await hydrateRelations(ctor, [this], this._perspective, opts.include);
1023
566
  }
1024
567
  }
1025
568
  catch (e) {
@@ -1028,7 +571,6 @@ export class Ad4mModel {
1028
571
  this.takeSnapshot();
1029
572
  return this;
1030
573
  }
1031
- // Todo: Only return AllInstances (InstancesWithOffset, SortedInstances, & UnsortedInstances not required)
1032
574
  static async queryToProlog(perspective, query, modelClassName) {
1033
575
  const { properties, where, order, offset, limit, count } = query;
1034
576
  const className = modelClassName || (await this.getClassName(perspective));
@@ -1053,281 +595,6 @@ export class Ad4mModel {
1053
595
  `;
1054
596
  return fullQuery;
1055
597
  }
1056
- /**
1057
- * Evaluates custom SurrealQL getters for properties and relations on a specific instance.
1058
- * @private
1059
- */
1060
- static async evaluateCustomGettersForInstance(instance, perspective, metadata) {
1061
- const safeBaseExpression = this.formatSurrealValue(instance.id);
1062
- // Evaluate property getters
1063
- for (const [propName, propMeta] of Object.entries(metadata.properties)) {
1064
- if (propMeta.getter) {
1065
- try {
1066
- // Replace 'Base' placeholder with actual base expression
1067
- const query = propMeta.getter.replace(/Base/g, safeBaseExpression);
1068
- // Query from node table to have graph traversal context
1069
- const result = await perspective.querySurrealDB(`SELECT (${query}) AS value FROM node WHERE uri = ${safeBaseExpression}`);
1070
- if (result && result.length > 0 && result[0].value !== undefined && result[0].value !== null && result[0].value !== 'None' && result[0].value !== '') {
1071
- instance[propName] = result[0].value;
1072
- }
1073
- }
1074
- catch (error) {
1075
- console.warn(`Failed to evaluate getter for ${propName}:`, error);
1076
- }
1077
- }
1078
- }
1079
- // Evaluate relation getters
1080
- for (const [relName, relMeta] of Object.entries(metadata.relations)) {
1081
- if (relMeta.getter) {
1082
- try {
1083
- // Replace 'Base' placeholder with actual base expression
1084
- const query = relMeta.getter.replace(/Base/g, safeBaseExpression);
1085
- // Query from node table to have graph traversal context
1086
- const result = await perspective.querySurrealDB(`SELECT (${query}) AS value FROM node WHERE uri = ${safeBaseExpression}`);
1087
- if (result && result.length > 0 && result[0].value !== undefined && result[0].value !== null) {
1088
- // Filter out 'None' from relation results
1089
- const value = result[0].value;
1090
- instance[relName] = Array.isArray(value)
1091
- ? value.filter((v) => v !== undefined && v !== null && v !== '' && v !== 'None')
1092
- : value;
1093
- }
1094
- }
1095
- catch (error) {
1096
- console.warn(`Failed to evaluate getter for ${relName}:`, error);
1097
- }
1098
- }
1099
- }
1100
- }
1101
- /**
1102
- * Hydrates relation fields on instances according to the provided IncludeMap.
1103
- *
1104
- * For each relation listed in `includeMap`, the raw expression-URI strings
1105
- * stored on the instance are replaced with fully-hydrated model instances
1106
- * (fetched via the relation's `target()` class). Nested IncludeMaps are
1107
- * supported for multi-level eager loading.
1108
- *
1109
- * @param instances - The instances whose relations should be hydrated
1110
- * @param perspective - The perspective to fetch related instances from
1111
- * @param includeMap - Describes which relations to hydrate
1112
- * @private
1113
- */
1114
- static async hydrateRelations(instances, perspective, includeMap) {
1115
- if (!includeMap || Object.keys(includeMap).length === 0)
1116
- return;
1117
- const relMeta = getRelationsMetadata(this);
1118
- for (const [relName, includeValue] of Object.entries(includeMap)) {
1119
- const meta = relMeta[relName];
1120
- if (!meta) {
1121
- console.warn(`include: relation "${relName}" not found in metadata, skipping`);
1122
- continue;
1123
- }
1124
- const TargetClass = meta.target();
1125
- // Determine if a RelationSubQuery was supplied (object) vs a plain `true`
1126
- const subQuery = typeof includeValue === 'object' && includeValue !== null
1127
- ? includeValue
1128
- : undefined;
1129
- const nestedInclude = subQuery?.include;
1130
- // ── Reverse relations (belongsToOne / belongsToMany) ──────────────────
1131
- // The link goes target→instance, so we query backwards:
1132
- // predicate = meta.predicate, target = inst.id → source is the related id
1133
- if (meta.kind === 'belongsToOne' || meta.kind === 'belongsToMany') {
1134
- // Per-instance reverse lookup (can't batch easily across instances)
1135
- for (const inst of instances) {
1136
- const reverseLinks = await perspective.get(new LinkQuery({ predicate: meta.predicate, target: inst.id }));
1137
- // Defensive filter: perspective.get may return extra results; ensure
1138
- // we only use links that genuinely point to this instance.
1139
- const sourceIds = reverseLinks
1140
- .filter(l => l.data.target === inst.id)
1141
- .map(l => l.data.source);
1142
- if (meta.kind === 'belongsToOne') {
1143
- if (sourceIds.length === 0) {
1144
- inst[relName] = null;
1145
- continue;
1146
- }
1147
- const sourceId = sourceIds[sourceIds.length - 1]; // latest-wins
1148
- try {
1149
- const related = new TargetClass(perspective, sourceId);
1150
- await related.get();
1151
- inst[relName] = related;
1152
- }
1153
- catch {
1154
- inst[relName] = null;
1155
- }
1156
- }
1157
- else {
1158
- // belongsToMany — return array of hydrated instances
1159
- let hydrated = [];
1160
- // If there's a where/order sub-query, delegate to findAll for filtering
1161
- if (subQuery && (subQuery.where || subQuery.order || subQuery.properties)) {
1162
- const whereWithIds = {
1163
- id: sourceIds,
1164
- ...(subQuery.where ?? {}),
1165
- };
1166
- hydrated = await TargetClass.findAll(perspective, {
1167
- where: whereWithIds,
1168
- ...(subQuery.order && { order: subQuery.order }),
1169
- ...(subQuery.properties && { properties: subQuery.properties }),
1170
- });
1171
- }
1172
- else {
1173
- await Promise.all(sourceIds.map(async (sid) => {
1174
- try {
1175
- const related = new TargetClass(perspective, sid);
1176
- await related.get(subQuery?.properties ? { properties: subQuery.properties } : undefined);
1177
- hydrated.push(related);
1178
- }
1179
- catch { /* skip */ }
1180
- }));
1181
- }
1182
- // Apply order (client-side, if not already handled by findAll above)
1183
- if (subQuery?.order && !(subQuery.where || subQuery.properties)) {
1184
- const orderEntries = Object.entries(subQuery.order);
1185
- hydrated = hydrated.sort((a, b) => {
1186
- for (const [field, dir] of orderEntries) {
1187
- const av = String(a[field] ?? '');
1188
- const bv = String(b[field] ?? '');
1189
- const diff = av.localeCompare(bv);
1190
- if (diff !== 0)
1191
- return dir === 'DESC' ? -diff : diff;
1192
- }
1193
- return 0;
1194
- });
1195
- }
1196
- // Apply offset and limit
1197
- if (subQuery?.offset != null || subQuery?.limit != null) {
1198
- const start = subQuery.offset ?? 0;
1199
- const end = subQuery.limit != null ? start + subQuery.limit : undefined;
1200
- hydrated = hydrated.slice(start, end);
1201
- }
1202
- inst[relName] = hydrated;
1203
- // Recurse for nested includes
1204
- if (nestedInclude && hydrated.length > 0) {
1205
- await TargetClass.hydrateRelations(hydrated, perspective, nestedInclude);
1206
- }
1207
- }
1208
- }
1209
- continue; // skip the forward-relation path below
1210
- }
1211
- // ── Forward relations (hasMany / hasOne) ──────────────────────────────
1212
- // Collect all unique URIs across all instances for batch-friendly lookup.
1213
- // IMPORTANT: We cache each instance's raw value NOW (before the async
1214
- // findAll) so that concurrent getData() calls on the same instance can't
1215
- // overwrite the relation field between the uriSet relation and the
1216
- // post-await assignment loop. Without this cache, a concurrent call
1217
- // can replace the raw URI strings with hydrated model objects, causing
1218
- // the `typeof v === 'string'` check to fail and the array to end up empty.
1219
- const uriSet = new Set();
1220
- const rawCache = new Map();
1221
- for (const inst of instances) {
1222
- const raw = inst[relName];
1223
- rawCache.set(inst, Array.isArray(raw) ? [...raw] : raw);
1224
- if (raw == null)
1225
- continue;
1226
- if (Array.isArray(raw)) {
1227
- for (const v of raw) {
1228
- if (typeof v === 'string')
1229
- uriSet.add(v);
1230
- // Handle already-hydrated instances (from a concurrent call)
1231
- else if (v && typeof v === 'object' && typeof v.id === 'string')
1232
- uriSet.add(v.id);
1233
- }
1234
- }
1235
- else if (typeof raw === 'string') {
1236
- uriSet.add(raw);
1237
- }
1238
- else if (raw && typeof raw === 'object' && typeof raw.id === 'string') {
1239
- uriSet.add(raw.id);
1240
- }
1241
- }
1242
- if (uriSet.size === 0)
1243
- continue;
1244
- // Hydrate related instances using findAll to ensure conformance checking.
1245
- // findAll validates model membership via graph traversal (required predicates / flags),
1246
- // so non-conforming linked URIs are silently dropped — matching the documented behaviour.
1247
- const hydrated = new Map();
1248
- const whereWithIds = {
1249
- id: Array.from(uriSet),
1250
- ...(subQuery?.where ?? {}),
1251
- };
1252
- const fetchQuery = {
1253
- where: whereWithIds,
1254
- ...(subQuery?.order && { order: subQuery.order }),
1255
- ...(subQuery?.properties && { properties: subQuery.properties }),
1256
- };
1257
- const results = await TargetClass.findAll(perspective, fetchQuery);
1258
- for (const result of results) {
1259
- hydrated.set(result.id, result);
1260
- }
1261
- // Replace raw URIs with hydrated instances on each parent instance.
1262
- // Use the cached raw values captured BEFORE the async findAll to avoid
1263
- // the race condition where a concurrent getData() already replaced the
1264
- // strings with hydrated objects.
1265
- for (const inst of instances) {
1266
- const raw = rawCache.get(inst);
1267
- if (raw == null)
1268
- continue;
1269
- if (Array.isArray(raw)) {
1270
- // Map URIs → instances; handle both raw strings and already-hydrated objects
1271
- let resolved = raw
1272
- .map((v) => {
1273
- if (typeof v === 'string') {
1274
- return hydrated.has(v) ? hydrated.get(v) : null;
1275
- }
1276
- // Already a hydrated model instance (from a concurrent call)
1277
- if (v && typeof v === 'object' && typeof v.id === 'string') {
1278
- return hydrated.has(v.id) ? hydrated.get(v.id) : v;
1279
- }
1280
- return null;
1281
- })
1282
- .filter((v) => v !== null);
1283
- // Per-instance sort (client-side, after filtering)
1284
- if (subQuery?.order) {
1285
- const orderEntries = Object.entries(subQuery.order);
1286
- resolved = resolved.sort((a, b) => {
1287
- for (const [field, dir] of orderEntries) {
1288
- const av = String(a[field] ?? '');
1289
- const bv = String(b[field] ?? '');
1290
- const diff = av.localeCompare(bv);
1291
- if (diff !== 0)
1292
- return dir === 'DESC' ? -diff : diff;
1293
- }
1294
- return 0;
1295
- });
1296
- }
1297
- // Per-instance limit / offset
1298
- if (subQuery?.offset != null || subQuery?.limit != null) {
1299
- const start = subQuery.offset ?? 0;
1300
- const end = subQuery.limit != null ? start + subQuery.limit : undefined;
1301
- resolved = resolved.slice(start, end);
1302
- }
1303
- // Enforce maxCount guard — single-valued relations keep only the last item
1304
- if (meta.maxCount === 1) {
1305
- if (resolved.length > 1) {
1306
- console.warn(`include: relation "${relName}" has maxCount 1 but ${resolved.length} values found; keeping the last`);
1307
- }
1308
- inst[relName] = resolved.length > 0
1309
- ? resolved[resolved.length - 1]
1310
- : null;
1311
- }
1312
- else {
1313
- inst[relName] = resolved;
1314
- }
1315
- }
1316
- else if (typeof raw === 'string' && hydrated.has(raw)) {
1317
- inst[relName] = hydrated.get(raw);
1318
- }
1319
- else if (raw && typeof raw === 'object' && typeof raw.id === 'string') {
1320
- // Already-hydrated object — look up refreshed version or keep as-is
1321
- inst[relName] = hydrated.has(raw.id) ? hydrated.get(raw.id) : raw;
1322
- }
1323
- }
1324
- // Recurse for nested includes
1325
- if (nestedInclude) {
1326
- const hydratedInstances = Array.from(hydrated.values());
1327
- await TargetClass.hydrateRelations(hydratedInstances, perspective, nestedInclude);
1328
- }
1329
- }
1330
- }
1331
598
  /**
1332
599
  * Generates a SurrealQL query from a Query object.
1333
600
  *
@@ -1366,612 +633,97 @@ export class Ad4mModel {
1366
633
  */
1367
634
  static async queryToSurrealQL(perspective, query) {
1368
635
  const metadata = this.getModelMetadata();
1369
- const { where, order, offset, limit } = query;
1370
- // Build list of graph traversal filters for required predicates
1371
- const graphTraversalFilters = [];
1372
- // Add parent filter if specified (filter to nodes linked from a parent via a specific predicate)
1373
- if (query.parent) {
1374
- const parentPredicate = resolveParentPredicate(query.parent, this);
1375
- graphTraversalFilters.push(`count(<-link[WHERE in.uri = ${this.formatSurrealValue(query.parent.id)} AND predicate = '${escapeSurrealString(parentPredicate)}']) > 0`);
1376
- }
1377
- // Add filters for required properties
1378
- for (const [propName, propMeta] of Object.entries(metadata.properties)) {
1379
- if (propMeta.required) {
1380
- // Skip properties with a getter — they are computed dynamically
1381
- // and may not have a stored link with their predicate, so requiring their
1382
- // presence would wrongly exclude valid model instances.
1383
- if (propMeta.getter)
1384
- continue;
1385
- // For flag properties, also filter by the target value
1386
- if (propMeta.flag && propMeta.initial) {
1387
- graphTraversalFilters.push(`count(->link[WHERE predicate = '${escapeSurrealString(propMeta.predicate)}' AND out.uri = '${escapeSurrealString(propMeta.initial)}']) > 0`);
1388
- }
1389
- else {
1390
- graphTraversalFilters.push(`count(->link[WHERE predicate = '${escapeSurrealString(propMeta.predicate)}']) > 0`);
636
+ const allRelMeta = getRelationsMetadata(this);
637
+ return buildSurrealQLQuery(metadata, allRelMeta, query, this);
638
+ }
639
+ static async instancesFromPrologResult(perspective, query, result) {
640
+ if (!result?.[0]?.AllInstances)
641
+ return { results: [], totalCount: 0 };
642
+ // Map results to instances
643
+ const requestedProperties = query?.properties || [];
644
+ const allInstances = await Promise.all(result[0].AllInstances.map(async ([Base, Properties, Collections, Timestamp, Author]) => {
645
+ try {
646
+ const instance = new this(perspective, Base);
647
+ // Remove unrequested attributes from instance
648
+ if (requestedProperties.length) {
649
+ Object.keys(instance).forEach((key) => {
650
+ if (!requestedProperties.includes(key) && key !== 'createdAt' && key !== 'updatedAt' && key !== 'author' && key !== 'id' && key !== 'baseExpression')
651
+ delete instance[key];
652
+ });
1391
653
  }
654
+ // Collect values to assign to instance
655
+ const values = [...Properties, ...Collections, ["createdAt", Timestamp], ["author", Author]];
656
+ await Ad4mModel.assignValuesToInstance(perspective, instance, values);
657
+ return instance;
1392
658
  }
1393
- }
1394
- // If no required properties produced filters, try properties with initial
1395
- // values (e.g. @Flag or @Property with an explicit initial).
1396
- if (graphTraversalFilters.length === 0) {
1397
- for (const [propName, propMeta] of Object.entries(metadata.properties)) {
1398
- if (propMeta.initial) {
1399
- if (propMeta.flag) {
1400
- graphTraversalFilters.push(`count(->link[WHERE predicate = '${escapeSurrealString(propMeta.predicate)}' AND out.uri = '${escapeSurrealString(propMeta.initial)}']) > 0`);
1401
- }
1402
- else {
1403
- graphTraversalFilters.push(`count(->link[WHERE predicate = '${escapeSurrealString(propMeta.predicate)}']) > 0`);
1404
- }
1405
- break;
1406
- }
659
+ catch (error) {
660
+ console.error(`Failed to process instance ${Base}:`, error);
661
+ // Return null for failed instances - we'll filter these out below
662
+ return null;
1407
663
  }
664
+ }));
665
+ const instances = allInstances.filter((instance) => instance !== null);
666
+ // Eager-load relations if requested (BEFORE snapshot so dirty tracking is accurate)
667
+ if (query.include && instances.length > 0) {
668
+ await hydrateRelations(this, instances, perspective, query.include);
1408
669
  }
1409
- // Still no filters → open-world structural matching.
1410
- // Require the node to have at least one link whose predicate is declared
1411
- // by this model (property OR relation). This prevents the query from
1412
- // matching every node in the perspective.
1413
- if (graphTraversalFilters.length === 0) {
1414
- const structuralPredicates = [];
1415
- for (const [, propMeta] of Object.entries(metadata.properties)) {
1416
- if (propMeta.predicate) {
1417
- structuralPredicates.push(`predicate = '${escapeSurrealString(propMeta.predicate)}'`);
1418
- }
1419
- }
1420
- if (metadata.relations) {
1421
- for (const [, relMeta] of Object.entries(metadata.relations)) {
1422
- if (relMeta.predicate) {
1423
- structuralPredicates.push(`predicate = '${escapeSurrealString(relMeta.predicate)}'`);
1424
- }
1425
- }
1426
- }
1427
- if (structuralPredicates.length > 0) {
1428
- graphTraversalFilters.push(`count(->link[WHERE (${structuralPredicates.join(' OR ')})]) > 0`);
1429
- }
670
+ // Take snapshots for dirty tracking after ALL hydration is complete
671
+ // (including eager-loaded relations).
672
+ // When `include` is specified, only snapshot those relations.
673
+ // Otherwise snapshot ALL fields (properties + relations) since
674
+ // hydrateFromLinks populates relations with stable raw IDs.
675
+ const snapshotRelations = query.include;
676
+ for (const inst of instances) {
677
+ inst.takeSnapshot(snapshotRelations);
1430
678
  }
1431
- // Build user WHERE clause filters using graph traversal
1432
- const userWhereClause = this.buildGraphTraversalWhereClause(metadata, where);
1433
- // Build complete WHERE clause using graph traversal filters
1434
- const whereConditions = [];
1435
- // Add all graph traversal filters for required properties
1436
- whereConditions.push(...graphTraversalFilters);
1437
- // Add user where conditions if any
1438
- if (userWhereClause) {
1439
- whereConditions.push(userWhereClause);
1440
- }
1441
- // Always ensure node has at least one link (each perspective has its own isolated DB)
1442
- whereConditions.push(`count(->link) > 0`);
1443
- // Build the query FROM node using direct graph traversal in WHERE
1444
- // This avoids slow subqueries and uses graph indexes for fast traversal
1445
- // FETCH links expands the link record IDs into full record objects
1446
- // (without FETCH, ->link returns only IDs like "link:abc123")
1447
- const fullQuery = `
1448
- SELECT
1449
- id AS source,
1450
- uri AS source_uri,
1451
- ->link AS links
1452
- FROM node
1453
- WHERE ${whereConditions.join(' AND ')}
1454
- FETCH links
1455
- `.trim();
1456
- return fullQuery;
679
+ return { results: instances, totalCount: result[0].TotalCount };
1457
680
  }
1458
681
  /**
1459
- * Builds the WHERE clause for SurrealQL queries using graph traversal syntax.
1460
- *
1461
- * @description
1462
- * Translates where conditions into graph traversal filters: `->link[WHERE ...]`
1463
- * This is more efficient than nested SELECTs because SurrealDB can optimize graph traversals.
1464
- *
1465
- * Handles several condition types:
1466
- * - Simple equality: `{ name: "Pasta" }` → `->link[WHERE predicate = 'X' AND out.uri = 'Pasta']`
1467
- * - Arrays (IN clause): `{ name: ["Pasta", "Pizza"] }` → `->link[WHERE predicate = 'X' AND out.uri IN [...]]`
1468
- * - NOT operators: Use `NOT` prefix
1469
- * - Comparison operators (gt, gte, lt, lte, etc.): Handled in post-query JavaScript filtering
1470
- * - Special fields: base uses `uri` directly, author/timestamp handled post-query
682
+ * Converts SurrealDB query results to Ad4mModel instances.
1471
683
  *
1472
- * @param metadata - Model metadata containing property predicates
1473
- * @param where - Where conditions from the query
1474
- * @returns Graph traversal WHERE clause filters, or empty string if no conditions
684
+ * @param perspective - The perspective context
685
+ * @param query - The query parameters used
686
+ * @param result - Array of result objects from SurrealDB
687
+ * @returns Promise resolving to results with total count
1475
688
  *
1476
- * @private
689
+ * @internal
1477
690
  */
1478
- static buildGraphTraversalWhereClause(metadata, where) {
1479
- if (!where)
1480
- return '';
1481
- const conditions = [];
1482
- for (const [propertyName, condition] of Object.entries(where)) {
1483
- // Check if this is a special field (id, author, timestamp)
1484
- // Note: author and timestamp filtering is done in JavaScript after query
1485
- const isSpecial = ['id', 'author', 'timestamp'].includes(propertyName);
1486
- if (isSpecial) {
1487
- // Skip author and timestamp - they'll be filtered in JavaScript
1488
- // Only handle 'id' (which maps to 'uri') here
1489
- if (propertyName === 'author' || propertyName === 'timestamp') {
1490
- continue; // Skip - will be filtered post-query
1491
- }
1492
- const columnName = 'uri'; // id maps to uri in node table
1493
- // Handle base/uri field directly
1494
- if (Array.isArray(condition)) {
1495
- // Array values (IN clause)
1496
- const formattedValues = condition.map(v => this.formatSurrealValue(v)).join(', ');
1497
- conditions.push(`${columnName} IN [${formattedValues}]`);
691
+ static async instancesFromSurrealResult(perspective, query, result) {
692
+ if (!result || result.length === 0)
693
+ return { results: [], totalCount: 0 };
694
+ const metadata = this.getModelMetadata();
695
+ const requestedProperties = query?.properties || [];
696
+ // The query used GROUP BY with graph traversal, so each row has:
697
+ // - source: the node ID (e.g., "node:abc123")
698
+ // - source_uri: the actual URI (the base expression)
699
+ // - links: array of link objects with {predicate, target, author, timestamp}
700
+ const instances = [];
701
+ for (const row of result) {
702
+ let base;
703
+ try {
704
+ // Use source_uri as the base (the actual URI), not the node ID
705
+ base = row.source_uri;
706
+ // Skip rows without a source_uri field
707
+ if (!base) {
708
+ continue;
1498
709
  }
1499
- else if (typeof condition === 'object' && condition !== null) {
1500
- // Operator object
1501
- const ops = condition;
1502
- if (ops.not !== undefined) {
1503
- if (Array.isArray(ops.not)) {
1504
- const formattedValues = ops.not.map(v => this.formatSurrealValue(v)).join(', ');
1505
- conditions.push(`${columnName} NOT IN [${formattedValues}]`);
1506
- }
1507
- else {
1508
- conditions.push(`${columnName} != ${this.formatSurrealValue(ops.not)}`);
710
+ const links = row.links || [];
711
+ const instance = new this(perspective, base);
712
+ // Core hydration via unified helper (pass requestedProperties for sparse fieldset)
713
+ await hydrateFromLinks(instance, links, metadata, perspective, requestedProperties.length > 0 ? requestedProperties : undefined);
714
+ // When specific properties are requested, delete unrequested properties
715
+ // so they return undefined instead of their constructor defaults (e.g. 0, [])
716
+ if (requestedProperties.length > 0) {
717
+ const requested = new Set(requestedProperties);
718
+ for (const propName of Object.keys(metadata.properties)) {
719
+ if (!requested.has(propName)) {
720
+ delete instance[propName];
1509
721
  }
1510
722
  }
1511
- if (ops.between !== undefined && Array.isArray(ops.between) && ops.between.length === 2) {
1512
- conditions.push(`${columnName} >= ${this.formatSurrealValue(ops.between[0])} AND ${columnName} <= ${this.formatSurrealValue(ops.between[1])}`);
1513
- }
1514
- if (ops.gt !== undefined) {
1515
- conditions.push(`${columnName} > ${this.formatSurrealValue(ops.gt)}`);
1516
- }
1517
- if (ops.gte !== undefined) {
1518
- conditions.push(`${columnName} >= ${this.formatSurrealValue(ops.gte)}`);
1519
- }
1520
- if (ops.lt !== undefined) {
1521
- conditions.push(`${columnName} < ${this.formatSurrealValue(ops.lt)}`);
1522
- }
1523
- if (ops.lte !== undefined) {
1524
- conditions.push(`${columnName} <= ${this.formatSurrealValue(ops.lte)}`);
1525
- }
1526
- if (ops.contains !== undefined) {
1527
- conditions.push(`${columnName} CONTAINS ${this.formatSurrealValue(ops.contains)}`);
1528
- }
1529
- }
1530
- else {
1531
- // Simple equality
1532
- conditions.push(`${columnName} = ${this.formatSurrealValue(condition)}`);
1533
- }
1534
- }
1535
- else {
1536
- // Handle regular properties via graph traversal.
1537
- // IMPORTANT: Check relation metadata first — @BelongsToOne / @BelongsToMany
1538
- // also write into propertyRegistry, but the link direction is inverted.
1539
- // If we matched the property path they would get a forward ->link filter
1540
- // which is wrong for belongs-to relations.
1541
- const allRelations = getRelationsMetadata(this);
1542
- const relMeta = allRelations[propertyName];
1543
- const isBelongs = relMeta?.kind === 'belongsToOne' || relMeta?.kind === 'belongsToMany';
1544
- if (relMeta) {
1545
- const predicate = escapeSurrealString(relMeta.predicate);
1546
- if (Array.isArray(condition)) {
1547
- const formattedValues = condition.map(v => this.formatSurrealValue(v)).join(', ');
1548
- if (isBelongs) {
1549
- conditions.push(`count(<-link[WHERE predicate = '${predicate}' AND in.uri IN [${formattedValues}]]) > 0`);
1550
- }
1551
- else {
1552
- conditions.push(`count(->link[WHERE predicate = '${predicate}' AND out.uri IN [${formattedValues}]]) > 0`);
1553
- }
1554
- }
1555
- else if (typeof condition === 'object' && condition !== null) {
1556
- const ops = condition;
1557
- if (ops.not !== undefined) {
1558
- if (Array.isArray(ops.not)) {
1559
- const formattedValues = ops.not.map(v => this.formatSurrealValue(v)).join(', ');
1560
- if (isBelongs) {
1561
- conditions.push(`count(<-link[WHERE predicate = '${predicate}' AND in.uri IN [${formattedValues}]]) = 0`);
1562
- }
1563
- else {
1564
- conditions.push(`count(->link[WHERE predicate = '${predicate}' AND out.uri IN [${formattedValues}]]) = 0`);
1565
- }
1566
- }
1567
- else {
1568
- if (isBelongs) {
1569
- conditions.push(`count(<-link[WHERE predicate = '${predicate}' AND in.uri = ${this.formatSurrealValue(ops.not)}]) = 0`);
1570
- }
1571
- else {
1572
- conditions.push(`count(->link[WHERE predicate = '${predicate}' AND out.uri = ${this.formatSurrealValue(ops.not)}]) = 0`);
1573
- }
1574
- }
1575
- }
1576
- }
1577
- else {
1578
- // Simple equality
1579
- if (isBelongs) {
1580
- conditions.push(`count(<-link[WHERE predicate = '${predicate}' AND in.uri = ${this.formatSurrealValue(condition)}]) > 0`);
1581
- }
1582
- else {
1583
- conditions.push(`count(->link[WHERE predicate = '${predicate}' AND out.uri = ${this.formatSurrealValue(condition)}]) > 0`);
1584
- }
1585
- }
1586
- continue;
1587
- }
1588
- const propMeta = metadata.properties[propertyName];
1589
- if (!propMeta)
1590
- continue; // Skip if property not found in metadata
1591
- const predicate = escapeSurrealString(propMeta.predicate);
1592
- // Use fn::parse_literal() for properties with resolveLanguage
1593
- const targetField = propMeta.resolveLanguage === 'literal' ? 'fn::parse_literal(out.uri)' : 'out.uri';
1594
- if (Array.isArray(condition)) {
1595
- // Array values (IN clause)
1596
- const formattedValues = condition.map(v => this.formatSurrealValue(v)).join(', ');
1597
- conditions.push(`count(->link[WHERE predicate = '${predicate}' AND ${targetField} IN [${formattedValues}]]) > 0`);
1598
- }
1599
- else if (typeof condition === 'object' && condition !== null) {
1600
- // Operator object
1601
- const ops = condition;
1602
- if (ops.not !== undefined) {
1603
- if (Array.isArray(ops.not)) {
1604
- // For NOT IN with array: must NOT have a link with value in the array
1605
- const formattedValues = ops.not.map(v => this.formatSurrealValue(v)).join(', ');
1606
- conditions.push(`count(->link[WHERE predicate = '${predicate}' AND ${targetField} IN [${formattedValues}]]) = 0`);
1607
- }
1608
- else {
1609
- // For NOT with single value: must NOT have this value
1610
- conditions.push(`count(->link[WHERE predicate = '${predicate}' AND ${targetField} = ${this.formatSurrealValue(ops.not)}]) = 0`);
1611
- }
1612
- }
1613
- // Note: gt, gte, lt, lte, between, contains operators are filtered in JavaScript
1614
- // post-query because fn::parse_literal() comparisons in SurrealDB
1615
- // don't work reliably with numeric comparisons.
1616
- // These are handled in instancesFromSurrealResult along with author/timestamp filtering.
1617
- // However, we still need to ensure the property exists
1618
- const hasComparisonOps = ops.gt !== undefined || ops.gte !== undefined ||
1619
- ops.lt !== undefined || ops.lte !== undefined ||
1620
- ops.between !== undefined || ops.contains !== undefined;
1621
- if (hasComparisonOps) {
1622
- // Ensure we only get nodes that have this property
1623
- conditions.push(`count(->link[WHERE predicate = '${predicate}']) > 0`);
1624
- }
1625
- }
1626
- else {
1627
- // Simple equality
1628
- conditions.push(`count(->link[WHERE predicate = '${predicate}' AND ${targetField} = ${this.formatSurrealValue(condition)}]) > 0`);
1629
- }
1630
- }
1631
- }
1632
- return conditions.join(' AND ');
1633
- }
1634
- /**
1635
- * Builds the WHERE clause for SurrealQL queries.
1636
- *
1637
- * @description
1638
- * Translates the where conditions from the Query object into SurrealQL WHERE clause fragments.
1639
- * For each property filter, generates a subquery that checks for links with the appropriate
1640
- * predicate and target value.
1641
- *
1642
- * Handles several condition types:
1643
- * - Simple equality: `{ name: "Pasta" }` → subquery checking for predicate and target match
1644
- * - Arrays (IN clause): `{ name: ["Pasta", "Pizza"] }` → target IN [...]
1645
- * - Operators: `{ rating: { gt: 4 } }` → target > '4'
1646
- * - gt, gte, lt, lte: comparison operators
1647
- * - not: negation (single value or array)
1648
- * - between: range check
1649
- * - contains: substring/element check (uses SurrealQL CONTAINS)
1650
- * - Special fields: base, author, timestamp are accessed directly, not via subqueries
1651
- *
1652
- * All conditions are joined with AND.
1653
- *
1654
- * @param metadata - Model metadata containing property predicates
1655
- * @param where - Where conditions from the query
1656
- * @returns WHERE clause string (without the "WHERE" keyword), or empty string if no conditions
1657
- *
1658
- * @private
1659
- */
1660
- static buildSurrealWhereClause(metadata, where) {
1661
- if (!where)
1662
- return '';
1663
- const conditions = [];
1664
- for (const [propertyName, condition] of Object.entries(where)) {
1665
- // Check if this is a special field (id, author, timestamp)
1666
- // Note: author and timestamp filtering is done in JavaScript after GROUP BY
1667
- // because they need to be computed from the grouped links first
1668
- const isSpecial = ['id', 'author', 'timestamp'].includes(propertyName);
1669
- if (isSpecial) {
1670
- // Skip author and timestamp - they'll be filtered in JavaScript
1671
- // Only handle 'id' (which maps to 'source') here
1672
- if (propertyName === 'author' || propertyName === 'timestamp') {
1673
- continue; // Skip - will be filtered post-query
1674
- }
1675
- const columnName = 'source'; // id maps to source
1676
- // Handle base/source field directly
1677
- if (Array.isArray(condition)) {
1678
- // Array values (IN clause)
1679
- const formattedValues = condition.map(v => this.formatSurrealValue(v)).join(', ');
1680
- conditions.push(`${columnName} IN [${formattedValues}]`);
1681
- }
1682
- else if (typeof condition === 'object' && condition !== null) {
1683
- // Operator object
1684
- const ops = condition;
1685
- if (ops.not !== undefined) {
1686
- if (Array.isArray(ops.not)) {
1687
- const formattedValues = ops.not.map(v => this.formatSurrealValue(v)).join(', ');
1688
- conditions.push(`${columnName} NOT IN [${formattedValues}]`);
1689
- }
1690
- else {
1691
- conditions.push(`${columnName} != ${this.formatSurrealValue(ops.not)}`);
1692
- }
1693
- }
1694
- if (ops.between !== undefined && Array.isArray(ops.between) && ops.between.length === 2) {
1695
- conditions.push(`${columnName} >= ${this.formatSurrealValue(ops.between[0])} AND ${columnName} <= ${this.formatSurrealValue(ops.between[1])}`);
1696
- }
1697
- if (ops.gt !== undefined) {
1698
- conditions.push(`${columnName} > ${this.formatSurrealValue(ops.gt)}`);
1699
- }
1700
- if (ops.gte !== undefined) {
1701
- conditions.push(`${columnName} >= ${this.formatSurrealValue(ops.gte)}`);
1702
- }
1703
- if (ops.lt !== undefined) {
1704
- conditions.push(`${columnName} < ${this.formatSurrealValue(ops.lt)}`);
1705
- }
1706
- if (ops.lte !== undefined) {
1707
- conditions.push(`${columnName} <= ${this.formatSurrealValue(ops.lte)}`);
1708
- }
1709
- if (ops.contains !== undefined) {
1710
- conditions.push(`${columnName} CONTAINS ${this.formatSurrealValue(ops.contains)}`);
1711
- }
1712
- }
1713
- else {
1714
- // Simple equality
1715
- conditions.push(`${columnName} = ${this.formatSurrealValue(condition)}`);
1716
- }
1717
- }
1718
- else {
1719
- // Handle regular properties via subqueries
1720
- const propMeta = metadata.properties[propertyName];
1721
- if (!propMeta)
1722
- continue; // Skip if property not found in metadata
1723
- const predicate = escapeSurrealString(propMeta.predicate);
1724
- // Use fn::parse_literal() for properties with resolveLanguage
1725
- const targetField = propMeta.resolveLanguage === 'literal' ? 'fn::parse_literal(target)' : 'target';
1726
- if (Array.isArray(condition)) {
1727
- // Array values (IN clause)
1728
- const formattedValues = condition.map(v => this.formatSurrealValue(v)).join(', ');
1729
- conditions.push(`source IN (SELECT VALUE source FROM link WHERE predicate = '${predicate}' AND ${targetField} IN [${formattedValues}])`);
1730
- }
1731
- else if (typeof condition === 'object' && condition !== null) {
1732
- // Operator object
1733
- const ops = condition;
1734
- if (ops.not !== undefined) {
1735
- if (Array.isArray(ops.not)) {
1736
- // For NOT IN with array: exclude sources that HAVE a value in the array
1737
- const formattedValues = ops.not.map(v => this.formatSurrealValue(v)).join(', ');
1738
- conditions.push(`source NOT IN (SELECT VALUE source FROM link WHERE predicate = '${predicate}' AND ${targetField} IN [${formattedValues}])`);
1739
- }
1740
- else {
1741
- // For NOT with single value: exclude sources that HAVE this value
1742
- conditions.push(`source NOT IN (SELECT VALUE source FROM link WHERE predicate = '${predicate}' AND ${targetField} = ${this.formatSurrealValue(ops.not)})`);
1743
- }
1744
- }
1745
- // Note: gt, gte, lt, lte, between, contains operators are filtered in JavaScript
1746
- // post-query because fn::parse_literal() comparisons in SurrealDB subqueries
1747
- // don't work reliably with numeric comparisons.
1748
- // These are handled in instancesFromSurrealResult along with author/timestamp filtering.
1749
- // However, we still need to ensure the property exists by filtering on the predicate
1750
- const hasComparisonOps = ops.gt !== undefined || ops.gte !== undefined ||
1751
- ops.lt !== undefined || ops.lte !== undefined ||
1752
- ops.between !== undefined || ops.contains !== undefined;
1753
- if (hasComparisonOps) {
1754
- // Ensure we only get instances that have this property
1755
- conditions.push(`source IN (SELECT VALUE source FROM link WHERE predicate = '${predicate}')`);
1756
- }
1757
- }
1758
- else {
1759
- // Simple equality
1760
- conditions.push(`source IN (SELECT VALUE source FROM link WHERE predicate = '${predicate}' AND ${targetField} = ${this.formatSurrealValue(condition)})`);
1761
- }
1762
- }
1763
- }
1764
- return conditions.join(' AND ');
1765
- }
1766
- /**
1767
- * Builds the SELECT fields for SurrealQL queries.
1768
- *
1769
- * @description
1770
- * Generates the field list for the SELECT clause, resolving properties and relations
1771
- * via subqueries. Each property is fetched with a subquery that finds the link with the
1772
- * appropriate predicate and returns its target. Relations are similar but don't use LIMIT 1.
1773
- *
1774
- * Field types:
1775
- * - Properties: `(SELECT VALUE target FROM link WHERE source = $parent.base AND predicate = 'X' LIMIT 1) AS propName`
1776
- * - Relations: `(SELECT VALUE target FROM link WHERE source = $parent.base AND predicate = 'X') AS relName`
1777
- * - Author/Timestamp: Always included to provide metadata about each instance
1778
- *
1779
- * If properties or relations arrays are provided, only those fields are included.
1780
- * Otherwise, all properties/relations from metadata are included.
1781
- *
1782
- * @param metadata - Model metadata containing property and relation predicates
1783
- * @param properties - Optional array of property names to include (default: all)
1784
- * @param relations - Optional array of relation names to include (default: all)
1785
- * @returns Comma-separated SELECT field list
1786
- *
1787
- * @private
1788
- */
1789
- static buildSurrealSelectFields(metadata, properties, relations) {
1790
- const fields = [];
1791
- // Determine properties to fetch
1792
- const propsToFetch = properties || Object.keys(metadata.properties);
1793
- for (const propName of propsToFetch) {
1794
- const propMeta = metadata.properties[propName];
1795
- if (!propMeta)
1796
- continue; // Skip if not found
1797
- // Reference source directly since we're selecting from link table
1798
- const escapedPredicate = escapeSurrealString(propMeta.predicate);
1799
- fields.push(`(SELECT VALUE target FROM link WHERE source = source AND predicate = '${escapedPredicate}' LIMIT 1) AS ${propName}`);
1800
- }
1801
- // Determine relations to fetch
1802
- const relsToFetch = relations || Object.keys(metadata.relations);
1803
- for (const relName of relsToFetch) {
1804
- const relMeta = metadata.relations[relName];
1805
- if (!relMeta)
1806
- continue; // Skip if not found
1807
- // Reference source directly since we're selecting from link table
1808
- const escapedPredicate = escapeSurrealString(relMeta.predicate);
1809
- fields.push(`(SELECT VALUE target FROM link WHERE source = source AND predicate = '${escapedPredicate}') AS ${relName}`);
1810
- }
1811
- // Always add author and timestamp fields
1812
- fields.push(`(SELECT VALUE author FROM link WHERE source = source ORDER BY timestamp ASC LIMIT 1) AS author`);
1813
- fields.push(`(SELECT VALUE timestamp FROM link WHERE source = source ORDER BY timestamp ASC LIMIT 1) AS createdAt`);
1814
- fields.push(`(SELECT VALUE timestamp FROM link WHERE source = source ORDER BY timestamp DESC LIMIT 1) AS updatedAt`);
1815
- return fields.join(',\n ');
1816
- }
1817
- /**
1818
- * Builds the SELECT fields for SurrealQL queries using aggregation functions.
1819
- * Compatible with GROUP BY source queries.
1820
- *
1821
- * @private
1822
- */
1823
- static buildSurrealSelectFieldsWithAggregation(metadata, properties, relations) {
1824
- const fields = [];
1825
- // Determine properties to fetch
1826
- const propsToFetch = properties || Object.keys(metadata.properties);
1827
- for (const propName of propsToFetch) {
1828
- const propMeta = metadata.properties[propName];
1829
- if (!propMeta)
1830
- continue; // Skip if not found
1831
- // Use array::first to get the first target value for this predicate
1832
- const escapedPredicate = escapeSurrealString(propMeta.predicate);
1833
- fields.push(`array::first(target[WHERE predicate = '${escapedPredicate}']) AS ${propName}`);
1834
- }
1835
- // Determine relations to fetch
1836
- const relsToFetch = relations || Object.keys(metadata.relations);
1837
- for (const relName of relsToFetch) {
1838
- const relMeta = metadata.relations[relName];
1839
- if (!relMeta)
1840
- continue; // Skip if not found
1841
- // Use array filtering to get all target values for this predicate
1842
- const escapedPredicate = escapeSurrealString(relMeta.predicate);
1843
- fields.push(`target[WHERE predicate = '${escapedPredicate}'] AS ${relName}`);
1844
- }
1845
- // Always add author and timestamp fields
1846
- fields.push(`array::first(author) AS author`);
1847
- fields.push(`array::first(timestamp) AS createdAt`);
1848
- fields.push(`array::last(timestamp) AS updatedAt`);
1849
- return fields.join(',\n ');
1850
- }
1851
- /**
1852
- * Formats a value for use in SurrealQL queries.
1853
- *
1854
- * @description
1855
- * Handles different value types:
1856
- * - Strings: Wrapped in single quotes with backslash-escaped special characters
1857
- * - Numbers/booleans: Converted to string
1858
- * - Arrays: Recursively formatted and wrapped in brackets
1859
- *
1860
- * @param value - The value to format
1861
- * @returns Formatted value string ready for SurrealQL
1862
- *
1863
- * @private
1864
- */
1865
- static formatSurrealValue(value) {
1866
- if (typeof value === 'string') {
1867
- // Escape backslashes first, then single quotes and other special characters
1868
- const escaped = value
1869
- .replace(/\\/g, '\\\\') // Backslash -> \\
1870
- .replace(/'/g, "\\'") // Single quote -> \'
1871
- .replace(/"/g, '\\"') // Double quote -> \"
1872
- .replace(/\n/g, '\\n') // Newline -> \n
1873
- .replace(/\r/g, '\\r') // Carriage return -> \r
1874
- .replace(/\t/g, '\\t'); // Tab -> \t
1875
- return `'${escaped}'`;
1876
- }
1877
- else if (typeof value === 'number' || typeof value === 'boolean') {
1878
- return String(value);
1879
- }
1880
- else if (Array.isArray(value)) {
1881
- return `[${value.map(v => this.formatSurrealValue(v)).join(', ')}]`;
1882
- }
1883
- else {
1884
- return String(value);
1885
- }
1886
- }
1887
- static async instancesFromPrologResult(perspective, query, result) {
1888
- if (!result?.[0]?.AllInstances)
1889
- return { results: [], totalCount: 0 };
1890
- // Map results to instances
1891
- const requestedProperties = query?.properties || [];
1892
- const allInstances = await Promise.all(result[0].AllInstances.map(async ([Base, Properties, Collections, Timestamp, Author]) => {
1893
- try {
1894
- const instance = new this(perspective, Base);
1895
- // Remove unrequested attributes from instance
1896
- if (requestedProperties.length) {
1897
- Object.keys(instance).forEach((key) => {
1898
- if (!requestedProperties.includes(key) && key !== 'createdAt' && key !== 'updatedAt' && key !== 'author' && key !== 'id' && key !== 'baseExpression')
1899
- delete instance[key];
1900
- });
1901
- }
1902
- // Collect values to assign to instance
1903
- const values = [...Properties, ...Collections, ["createdAt", Timestamp], ["author", Author]];
1904
- await Ad4mModel.assignValuesToInstance(perspective, instance, values);
1905
- return instance;
1906
- }
1907
- catch (error) {
1908
- console.error(`Failed to process instance ${Base}:`, error);
1909
- // Return null for failed instances - we'll filter these out below
1910
- return null;
1911
- }
1912
- }));
1913
- const instances = allInstances.filter((instance) => instance !== null);
1914
- // Eager-load relations if requested (BEFORE snapshot so dirty tracking is accurate)
1915
- if (query.include && instances.length > 0) {
1916
- await this.hydrateRelations(instances, perspective, query.include);
1917
- }
1918
- // Take snapshots for dirty tracking after ALL hydration is complete
1919
- // (including eager-loaded relations).
1920
- // When `include` is specified, only snapshot those relations.
1921
- // Otherwise snapshot ALL fields (properties + relations) since
1922
- // hydrateFromLinks populates relations with stable raw IDs.
1923
- const snapshotRelations = query.include;
1924
- for (const inst of instances) {
1925
- inst.takeSnapshot(snapshotRelations);
1926
- }
1927
- return { results: instances, totalCount: result[0].TotalCount };
1928
- }
1929
- /**
1930
- * Converts SurrealDB query results to Ad4mModel instances.
1931
- *
1932
- * @param perspective - The perspective context
1933
- * @param query - The query parameters used
1934
- * @param result - Array of result objects from SurrealDB
1935
- * @returns Promise resolving to results with total count
1936
- *
1937
- * @internal
1938
- */
1939
- static async instancesFromSurrealResult(perspective, query, result) {
1940
- if (!result || result.length === 0)
1941
- return { results: [], totalCount: 0 };
1942
- const metadata = this.getModelMetadata();
1943
- const requestedProperties = query?.properties || [];
1944
- // The query used GROUP BY with graph traversal, so each row has:
1945
- // - source: the node ID (e.g., "node:abc123")
1946
- // - source_uri: the actual URI (the base expression)
1947
- // - links: array of link objects with {predicate, target, author, timestamp}
1948
- const instances = [];
1949
- for (const row of result) {
1950
- let base;
1951
- try {
1952
- // Use source_uri as the base (the actual URI), not the node ID
1953
- base = row.source_uri;
1954
- // Skip rows without a source_uri field
1955
- if (!base) {
1956
- continue;
1957
- }
1958
- const links = row.links || [];
1959
- const instance = new this(perspective, base);
1960
- // Core hydration via unified helper (pass requestedProperties for sparse fieldset)
1961
- await this.hydrateFromLinks(instance, links, metadata, perspective, requestedProperties.length > 0 ? requestedProperties : undefined);
1962
- // When specific properties are requested, delete unrequested properties
1963
- // so they return undefined instead of their constructor defaults (e.g. 0, [])
1964
- if (requestedProperties.length > 0) {
1965
- const requested = new Set(requestedProperties);
1966
- for (const propName of Object.keys(metadata.properties)) {
1967
- if (!requested.has(propName)) {
1968
- delete instance[propName];
1969
- }
1970
- }
1971
- for (const relName of Object.keys(metadata.relations)) {
1972
- if (!requested.has(relName) && !(query.include && relName in query.include)) {
1973
- delete instance[relName];
1974
- }
723
+ for (const relName of Object.keys(metadata.relations)) {
724
+ if (!requested.has(relName) && !(query.include && relName in query.include)) {
725
+ delete instance[relName];
726
+ }
1975
727
  }
1976
728
  // Also strip metadata fields unless explicitly requested
1977
729
  for (const metaField of ['author', 'createdAt', 'updatedAt']) {
@@ -2010,8 +762,11 @@ FETCH links
2010
762
  }));
2011
763
  }
2012
764
  // Evaluate custom getters for all instances (single pass)
765
+ const getterOpts = requestedProperties.length > 0 || query.include
766
+ ? { requestedProperties, include: query.include }
767
+ : undefined;
2013
768
  for (const instance of instances) {
2014
- await this.evaluateCustomGettersForInstance(instance, perspective, metadata);
769
+ await evaluateCustomGettersForInstance(instance, perspective, metadata, getterOpts);
2015
770
  }
2016
771
  // Filter by where conditions that couldn't be filtered in SQL
2017
772
  // This includes:
@@ -2027,7 +782,7 @@ FETCH links
2027
782
  continue;
2028
783
  // For author and timestamp, always filter in JS
2029
784
  if (propertyName === 'author' || propertyName === 'timestamp') {
2030
- if (!this.matchesCondition(instance[propertyName], condition)) {
785
+ if (!matchesCondition(instance[propertyName], condition)) {
2031
786
  return false;
2032
787
  }
2033
788
  continue;
@@ -2041,7 +796,7 @@ FETCH links
2041
796
  ops.lt !== undefined || ops.lte !== undefined ||
2042
797
  ops.between !== undefined || ops.contains !== undefined;
2043
798
  if (hasComparisonOps) {
2044
- if (!this.matchesCondition(instance[propertyName], condition)) {
799
+ if (!matchesCondition(instance[propertyName], condition)) {
2045
800
  return false;
2046
801
  }
2047
802
  }
@@ -2098,7 +853,7 @@ FETCH links
2098
853
  }
2099
854
  // Eager-load relations if requested (BEFORE snapshot so dirty tracking is accurate)
2100
855
  if (query.include && paginatedInstances.length > 0) {
2101
- await this.hydrateRelations(paginatedInstances, perspective, query.include);
856
+ await hydrateRelations(this, paginatedInstances, perspective, query.include);
2102
857
  }
2103
858
  // Take snapshots for dirty tracking after ALL hydration is complete
2104
859
  // (including eager-loaded relations).
@@ -2115,62 +870,6 @@ FETCH links
2115
870
  totalCount
2116
871
  };
2117
872
  }
2118
- /**
2119
- * Checks if a value matches a condition (for post-query filtering).
2120
- * @private
2121
- */
2122
- static matchesCondition(value, condition) {
2123
- // Handle array values (IN clause)
2124
- if (Array.isArray(condition)) {
2125
- return condition.includes(value);
2126
- }
2127
- // Handle operator object
2128
- if (typeof condition === 'object' && condition !== null) {
2129
- const ops = condition;
2130
- // Special case: 'not' operator (exclusive with other operators)
2131
- if (ops.not !== undefined) {
2132
- if (Array.isArray(ops.not)) {
2133
- return !ops.not.includes(value);
2134
- }
2135
- else {
2136
- return value !== ops.not;
2137
- }
2138
- }
2139
- // Special case: 'between' operator (inclusive range, exclusive with gt/gte/lt/lte)
2140
- if (ops.between !== undefined && Array.isArray(ops.between) && ops.between.length === 2) {
2141
- return value >= ops.between[0] && value <= ops.between[1];
2142
- }
2143
- // For all other operators (gt, gte, lt, lte, contains), we need to check ALL of them
2144
- // and return true only if ALL conditions are satisfied
2145
- let allConditionsMet = true;
2146
- if (ops.gt !== undefined) {
2147
- allConditionsMet = allConditionsMet && (value > ops.gt);
2148
- }
2149
- if (ops.gte !== undefined) {
2150
- allConditionsMet = allConditionsMet && (value >= ops.gte);
2151
- }
2152
- if (ops.lt !== undefined) {
2153
- allConditionsMet = allConditionsMet && (value < ops.lt);
2154
- }
2155
- if (ops.lte !== undefined) {
2156
- allConditionsMet = allConditionsMet && (value <= ops.lte);
2157
- }
2158
- if (ops.contains !== undefined) {
2159
- if (typeof value === 'string') {
2160
- allConditionsMet = allConditionsMet && value.includes(String(ops.contains));
2161
- }
2162
- else if (Array.isArray(value)) {
2163
- allConditionsMet = allConditionsMet && value.includes(ops.contains);
2164
- }
2165
- else {
2166
- allConditionsMet = false;
2167
- }
2168
- }
2169
- return allConditionsMet;
2170
- }
2171
- // Simple equality
2172
- return value === condition;
2173
- }
2174
873
  /**
2175
874
  * Gets all instances of the model in the perspective that match the query params.
2176
875
  *
@@ -2378,7 +1077,6 @@ FETCH links
2378
1077
  }
2379
1078
  }
2380
1079
  async setProperty(key, value, batchId) {
2381
- // Phase 1: Use metadata instead of Prolog queries
2382
1080
  const metadata = this.getPropertyMetadata(key);
2383
1081
  if (!metadata) {
2384
1082
  console.warn(`Property "${key}" has no metadata, skipping`);
@@ -2407,7 +1105,6 @@ FETCH links
2407
1105
  return String(value);
2408
1106
  }
2409
1107
  async setRelationValues(key, value, batchId) {
2410
- // Phase 1: Use metadata instead of Prolog queries
2411
1108
  const metadata = this.getRelationOptions(key);
2412
1109
  if (!metadata) {
2413
1110
  console.warn(`Relation "${key}" has no metadata, skipping`);
@@ -2425,7 +1122,6 @@ FETCH links
2425
1122
  }
2426
1123
  }
2427
1124
  async addRelationValue(key, value, batchId) {
2428
- // Phase 1: Use metadata instead of Prolog queries
2429
1125
  const metadata = this.getRelationOptions(key);
2430
1126
  if (!metadata) {
2431
1127
  console.warn(`Relation "${key}" has no metadata, skipping`);
@@ -2443,7 +1139,6 @@ FETCH links
2443
1139
  }
2444
1140
  }
2445
1141
  async removeRelationValue(key, value, batchId) {
2446
- // Phase 1: Use metadata instead of Prolog queries
2447
1142
  const metadata = this.getRelationOptions(key);
2448
1143
  if (!metadata) {
2449
1144
  console.warn(`Relation "${key}" has no metadata, skipping`);
@@ -2590,7 +1285,6 @@ FETCH links
2590
1285
  }
2591
1286
  async innerUpdate(setProperties = true, batchId) {
2592
1287
  const ctor = this.constructor;
2593
- this._subjectClassName = await this._perspective.stringOrTemplateObjectToSubjectClassName(this.cleanCopy());
2594
1288
  // Determine which fields actually changed (skip unchanged when snapshot exists)
2595
1289
  const dirty = this._snapshot ? new Set(this.changedFields()) : null;
2596
1290
  // Only iterate schema-declared fields, not internal ORM properties
@@ -2607,6 +1301,22 @@ FETCH links
2607
1301
  // Skip unchanged fields when a snapshot is available
2608
1302
  if (dirty && !dirty.has(key))
2609
1303
  continue;
1304
+ // Skip read-only computed relations — explicit getters never write links.
1305
+ // For target+filter relations, skip only when another relation on this
1306
+ // model claims the same predicate (i.e., this is a filtered *view* of a
1307
+ // base relation and writing would collide).
1308
+ const relMeta = metadata.relations[key];
1309
+ if (relMeta) {
1310
+ if (relMeta.getter)
1311
+ continue;
1312
+ if (relMeta.target && relMeta.filter !== false) {
1313
+ // Check for predicate collision with a sibling relation
1314
+ const hasCollision = Object.entries(metadata.relations).some(([otherName, otherMeta]) => otherName !== key &&
1315
+ otherMeta.predicate === relMeta.predicate);
1316
+ if (hasCollision)
1317
+ continue;
1318
+ }
1319
+ }
2610
1320
  if (value !== undefined && value !== null) {
2611
1321
  if (value?.action) {
2612
1322
  switch (value.action) {
@@ -2682,7 +1392,6 @@ FETCH links
2682
1392
  else {
2683
1393
  opts = { include: optsOrInclude };
2684
1394
  }
2685
- this._subjectClassName = await this._perspective.stringOrTemplateObjectToSubjectClassName(this.cleanCopy());
2686
1395
  return await this.getData(opts);
2687
1396
  }
2688
1397
  /**
@@ -2703,11 +1412,6 @@ FETCH links
2703
1412
  * ```
2704
1413
  */
2705
1414
  async delete(batchId) {
2706
- // Check if the model has a destructor (required properties, flags, or
2707
- // properties with initial values). Models whose properties are all
2708
- // optional, have no @Flag, and have no initial values produce an empty
2709
- // SHACL destructor, so calling removeSubject would fail. In that case
2710
- // we skip the destructor and just remove all outgoing links directly.
2711
1415
  const metadata = this.constructor.getModelMetadata();
2712
1416
  const hasDestructor = Object.values(metadata.properties).some((p) => p.required || p.flag || p.initial !== undefined);
2713
1417
  if (hasDestructor) {
@@ -2715,18 +1419,39 @@ FETCH links
2715
1419
  await this._perspective.removeSubject(this, this._baseExpression, batchId);
2716
1420
  }
2717
1421
  else {
2718
- // No destructor — manually remove all outgoing links from this node
1422
+ // No destructor (all-optional model).
1423
+ // SAFETY: We must NOT remove all outgoing links because another model
1424
+ // class may be instantiated on the same base expression. Removing
1425
+ // everything would silently destroy that other instance's data — and
1426
+ // if that instance has a destructor, it can no longer be called
1427
+ // cleanly, leaving link debris.
1428
+ //
1429
+ // Instead we only remove outgoing links whose predicate is declared
1430
+ // by THIS model's schema (properties + relations).
2719
1431
  try {
1432
+ const knownPredicates = new Set();
1433
+ for (const p of Object.values(metadata.properties)) {
1434
+ if (p.predicate)
1435
+ knownPredicates.add(p.predicate);
1436
+ }
1437
+ for (const r of Object.values(metadata.relations)) {
1438
+ if (r.predicate)
1439
+ knownPredicates.add(r.predicate);
1440
+ }
2720
1441
  const outgoingLinks = await this._perspective.get(new LinkQuery({ source: this._baseExpression }));
2721
- if (outgoingLinks.length > 0) {
2722
- await this._perspective.removeLinks(outgoingLinks, batchId);
1442
+ const ownLinks = outgoingLinks.filter((link) => link.data.predicate && knownPredicates.has(link.data.predicate));
1443
+ if (ownLinks.length > 0) {
1444
+ await this._perspective.removeLinks(ownLinks, batchId);
2723
1445
  }
2724
1446
  }
2725
1447
  catch (e) {
2726
1448
  console.warn(`delete(): failed to remove outgoing links for ${this._baseExpression}:`, e);
2727
1449
  }
2728
1450
  }
2729
- // Clean up incoming links — remove any links that point **to** this instance
1451
+ // Clean up incoming links — remove any links that point **to** this instance.
1452
+ // Unlike outgoing links (scoped above), incoming links originate from OTHER
1453
+ // nodes. Removing them doesn't damage sibling models on this node; it
1454
+ // prevents dangling references elsewhere (e.g. a parent's has_child link).
2730
1455
  try {
2731
1456
  const incomingLinks = await this._perspective.get(new LinkQuery({ target: this._baseExpression }));
2732
1457
  if (incomingLinks.length > 0) {
@@ -2738,6 +1463,9 @@ FETCH links
2738
1463
  console.warn(`delete(): failed to clean up incoming links for ${this._baseExpression}:`, e);
2739
1464
  }
2740
1465
  }
1466
+ // ──────────────────────────────────────────────────────────
1467
+ // Static convenience methods
1468
+ // ──────────────────────────────────────────────────────────
2741
1469
  /**
2742
1470
  * Creates and saves a new model instance in one step.
2743
1471
  *
@@ -2994,929 +1722,7 @@ FETCH links
2994
1722
  * @throws Error when namespace cannot be inferred
2995
1723
  */
2996
1724
  static fromJSONSchema(schema, options) {
2997
- // Disallow top-level "author" property since Ad4mModel provides it implicitly via link authorship
2998
- if (schema?.properties && Object.prototype.hasOwnProperty.call(schema.properties, "author")) {
2999
- throw new Error('JSON Schema must not define a top-level "author" property because Ad4mModel already exposes it. Please rename the property (e.g., "writer").');
3000
- }
3001
- // Determine namespace with cascading precedence
3002
- const namespace = this.determineNamespace(schema, options);
3003
- // Create the dynamic class
3004
- const DynamicModelClass = class extends Ad4mModel {
3005
- };
3006
- // Set up class metadata
3007
- if (!options.name || options.name.trim() === '') {
3008
- throw new Error("options.name is required and cannot be empty");
3009
- }
3010
- DynamicModelClass.className = options.name;
3011
- DynamicModelClass.prototype.className = options.name;
3012
- // Generate properties and relations metadata
3013
- const properties = {};
3014
- const relations = {};
3015
- if (schema.properties) {
3016
- for (const [propertyName, propertySchema] of Object.entries(schema.properties)) {
3017
- const predicate = this.determinePredicate(schema, propertyName, propertySchema, namespace, options);
3018
- const isRequired = schema.required?.includes(propertyName) || false;
3019
- const propertyType = normalizeSchemaType(propertySchema.type);
3020
- const isArray = isArrayType(propertySchema);
3021
- if (isArray) {
3022
- // Handle arrays as relations
3023
- // Store the singular form as the relation key since SDNA generation expects singular
3024
- relations[propertyName] = {
3025
- through: predicate,
3026
- local: this.getPropertyOption(propertyName, propertySchema, options, 'local')
3027
- };
3028
- // Define the property on prototype
3029
- Object.defineProperty(DynamicModelClass.prototype, propertyName, {
3030
- configurable: true,
3031
- writable: true,
3032
- value: []
3033
- });
3034
- // Add relation methods
3035
- const adderName = `add${capitalize(propertyName)}`;
3036
- const removerName = `remove${capitalize(propertyName)}`;
3037
- const setterName = `set${capitalize(propertyName)}`;
3038
- DynamicModelClass.prototype[adderName] = function () {
3039
- // Placeholder function for SDNA generation
3040
- };
3041
- DynamicModelClass.prototype[removerName] = function () {
3042
- // Placeholder function for SDNA generation
3043
- };
3044
- DynamicModelClass.prototype[setterName] = function () {
3045
- // Placeholder function for SDNA generation
3046
- };
3047
- }
3048
- else {
3049
- // Handle regular properties
3050
- let resolveLanguage = this.getPropertyOption(propertyName, propertySchema, options, 'resolveLanguage');
3051
- // If no specific resolveLanguage for this property, use the global one
3052
- if (!resolveLanguage && options.resolveLanguage) {
3053
- resolveLanguage = options.resolveLanguage;
3054
- }
3055
- const local = this.getPropertyOption(propertyName, propertySchema, options, 'local');
3056
- // Determine readOnly: check PropertyOptions first, then x-ad4m.writable (inverted) for JSON Schema wire format
3057
- let readOnly = this.getPropertyOption(propertyName, propertySchema, options, 'readOnly');
3058
- if (readOnly === undefined) {
3059
- const xWritable = propertySchema["x-ad4m"]?.writable;
3060
- readOnly = xWritable !== undefined ? !xWritable : false;
3061
- }
3062
- const writable = !readOnly;
3063
- let initial = this.getPropertyOption(propertyName, propertySchema, options, 'initial');
3064
- // Handle nested objects by serializing to JSON
3065
- if (isObjectType(propertySchema) && !resolveLanguage) {
3066
- resolveLanguage = 'literal';
3067
- console.warn(`Property "${propertyName}" is an object type. It will be stored as JSON. Consider flattening complex objects for better semantic querying.`);
3068
- }
3069
- // Ensure numeric properties use literal language for correct typing
3070
- if ((resolveLanguage === undefined || resolveLanguage === null) && isNumericType(propertySchema)) {
3071
- resolveLanguage = 'literal';
3072
- }
3073
- // Default resolveLanguage to 'literal' for all remaining property types,
3074
- // matching the @Property decorator behaviour. Without this, string values
3075
- // stored as literal:// URLs are returned unparsed.
3076
- if (resolveLanguage === undefined || resolveLanguage === null) {
3077
- resolveLanguage = 'literal';
3078
- }
3079
- // If property is required, ensure it has an initial value
3080
- if (isRequired && !initial) {
3081
- if (isObjectType(propertySchema)) {
3082
- initial = 'literal://json:{}';
3083
- }
3084
- else {
3085
- initial = "ad4m://undefined";
3086
- }
3087
- }
3088
- properties[propertyName] = {
3089
- through: predicate,
3090
- required: isRequired,
3091
- writable: writable,
3092
- ...(resolveLanguage && { resolveLanguage }),
3093
- ...(local !== undefined && { local }),
3094
- ...(initial && { initial })
3095
- };
3096
- // Define the property on prototype
3097
- Object.defineProperty(DynamicModelClass.prototype, propertyName, {
3098
- configurable: true,
3099
- writable: true,
3100
- value: this.getDefaultValueForType(propertyType)
3101
- });
3102
- // Add setter function if writable
3103
- if (writable) {
3104
- const setterName = propertyNameToSetterName(propertyName);
3105
- DynamicModelClass.prototype[setterName] = function () {
3106
- // This is a placeholder function that the SDNA generation looks for
3107
- // The actual setter logic is handled by the Ad4mModel base class
3108
- };
3109
- }
3110
- }
3111
- }
3112
- }
3113
- // No auto-flag generation — models with all-optional properties use
3114
- // open-world structural matching. Consumers who need type discrimination
3115
- // should add an explicit @Flag to their model definition.
3116
- // Attach metadata to WeakMap registries
3117
- for (const [propName, propMeta] of Object.entries(properties)) {
3118
- setPropertyRegistryEntry(DynamicModelClass, propName, propMeta);
3119
- }
3120
- for (const [relName, relMeta] of Object.entries(relations)) {
3121
- setRelationRegistryEntry(DynamicModelClass, relName, {
3122
- predicate: relMeta.through || "",
3123
- kind: 'hasMany',
3124
- ...(relMeta.getter !== undefined && { getter: relMeta.getter }),
3125
- ...(relMeta.local !== undefined && { local: relMeta.local }),
3126
- });
3127
- }
3128
- // Store the JSON schema and options on the prototype for potential fallback use by getModelMetadata()
3129
- DynamicModelClass.prototype.__jsonSchema = schema;
3130
- DynamicModelClass.prototype.__jsonSchemaOptions = options;
3131
- // Apply the Model decorator to set up the generateSDNA method
3132
- const ModelDecorator = Model({ name: options.name });
3133
- ModelDecorator(DynamicModelClass);
3134
- return DynamicModelClass;
3135
- }
3136
- /**
3137
- * Determines the namespace for predicates using cascading precedence
3138
- */
3139
- static determineNamespace(schema, options) {
3140
- // 1. Explicit namespace in options (highest precedence)
3141
- if (options.namespace) {
3142
- return options.namespace;
3143
- }
3144
- // 2. x-ad4m metadata in schema
3145
- if (schema["x-ad4m"]?.namespace) {
3146
- return schema["x-ad4m"].namespace;
3147
- }
3148
- // 3. Infer from schema title
3149
- if (schema.title) {
3150
- return `${schema.title.toLowerCase()}://`;
3151
- }
3152
- // 4. Try to extract from $id if it's a URL
3153
- if (schema.$id) {
3154
- try {
3155
- const url = new URL(schema.$id);
3156
- const pathParts = url.pathname.split('/').filter(p => p);
3157
- if (pathParts.length > 0) {
3158
- const lastPart = pathParts[pathParts.length - 1];
3159
- const baseName = lastPart.replace(/\.schema\.json$/, '').replace(/\.json$/, '');
3160
- return `${baseName.toLowerCase()}://`;
3161
- }
3162
- }
3163
- catch {
3164
- // If $id is not a valid URL, continue to error
3165
- }
3166
- }
3167
- // 5. Error if no namespace can be determined
3168
- throw new Error(`Cannot infer namespace for JSON Schema. Please provide one of:
3169
- - options.namespace
3170
- - schema["x-ad4m"].namespace
3171
- - schema.title
3172
- - valid schema.$id`);
3173
- }
3174
- /**
3175
- * Determines the predicate for a specific property using cascading precedence
3176
- */
3177
- static determinePredicate(schema, propertyName, propertySchema, namespace, options) {
3178
- // 1. Explicit property mapping (highest precedence)
3179
- if (options.propertyMapping?.[propertyName]) {
3180
- return options.propertyMapping[propertyName];
3181
- }
3182
- // 2. x-ad4m metadata in property schema
3183
- if (propertySchema["x-ad4m"]?.through) {
3184
- return propertySchema["x-ad4m"].through;
3185
- }
3186
- // 3. Generate from namespace + property name
3187
- if (options.predicateTemplate) {
3188
- const normalizedNs = normalizeNamespaceString(namespace);
3189
- const [scheme, rest] = normalizedNs.includes('://') ? normalizedNs.split('://') : ['', normalizedNs];
3190
- const nsNoScheme = rest || '';
3191
- return options.predicateTemplate
3192
- .replace('${namespace}', nsNoScheme)
3193
- .replace('${scheme}', scheme)
3194
- .replace('${ns}', nsNoScheme)
3195
- .replace('${title}', schema.title || '')
3196
- .replace('${property}', propertyName);
3197
- }
3198
- // 4. Custom predicate generator
3199
- if (options.predicateGenerator) {
3200
- return options.predicateGenerator(schema.title || '', propertyName);
3201
- }
3202
- // 5. Default: namespace + property name
3203
- const normalizedNs = normalizeNamespaceString(namespace);
3204
- if (normalizedNs.includes('://')) {
3205
- // For namespaces like "product://", append property directly
3206
- return `${normalizedNs}${propertyName}`;
3207
- }
3208
- else {
3209
- return `${normalizedNs}://${propertyName}`;
3210
- }
3211
- }
3212
- /**
3213
- * Gets property-specific options using cascading precedence
3214
- */
3215
- static getPropertyOption(propertyName, propertySchema, options, optionName, defaultValue) {
3216
- // 1. Property-specific options
3217
- if (options.propertyOptions?.[propertyName]?.[optionName] !== undefined) {
3218
- return options.propertyOptions[propertyName][optionName];
3219
- }
3220
- // 2. x-ad4m metadata in property
3221
- if (propertySchema["x-ad4m"]?.[optionName] !== undefined) {
3222
- return propertySchema["x-ad4m"][optionName];
3223
- }
3224
- // 3. Global option
3225
- if (options[optionName] !== undefined) {
3226
- return options[optionName];
3227
- }
3228
- // 4. Default value
3229
- return defaultValue;
3230
- }
3231
- /**
3232
- * Gets default value for a JSON Schema type
3233
- */
3234
- static getDefaultValueForType(type) {
3235
- switch (type) {
3236
- case 'string': return '';
3237
- case 'number': return 0;
3238
- case 'integer': return 0;
3239
- case 'boolean': return false;
3240
- case 'array': return [];
3241
- case 'object': return {};
3242
- default: return '';
3243
- }
1725
+ return buildModelFromJSONSchema(this, schema, options);
3244
1726
  }
3245
1727
  }
3246
1728
  Ad4mModel.classNamesByClass = new WeakMap();
3247
- /** Query builder for Ad4mModel queries.
3248
- * Allows building queries with a fluent interface and either running them once
3249
- * or subscribing to updates.
3250
- *
3251
- * @example
3252
- * ```typescript
3253
- * const builder = Recipe.query(perspective)
3254
- * .where({ category: "Dessert" })
3255
- * .order({ rating: "DESC" })
3256
- * .limit(10);
3257
- *
3258
- * // Run once
3259
- * const recipes = await builder.run();
3260
- *
3261
- * // Or subscribe to updates
3262
- * await builder.subscribe(recipes => {
3263
- * console.log("Updated recipes:", recipes);
3264
- * });
3265
- * ```
3266
- */
3267
- export class ModelQueryBuilder {
3268
- constructor(perspective, ctor, query) {
3269
- this.queryParams = {};
3270
- this.modelClassName = null;
3271
- this.useSurrealDBFlag = true;
3272
- this.perspective = perspective;
3273
- this.ctor = ctor;
3274
- if (query)
3275
- this.queryParams = query;
3276
- }
3277
- /**
3278
- * Disposes of the current subscription if one exists.
3279
- *
3280
- * This method:
3281
- * 1. Stops the keepalive signals to the subscription
3282
- * 2. Unsubscribes from GraphQL subscription updates
3283
- * 3. Notifies the backend to clean up subscription resources
3284
- * 4. Clears the subscription reference
3285
- *
3286
- * You should call this method when you're done with a subscription
3287
- * to prevent memory leaks and ensure proper cleanup.
3288
- */
3289
- dispose() {
3290
- if (this.currentSubscription) {
3291
- this.currentSubscription.dispose();
3292
- this.currentSubscription = undefined;
3293
- }
3294
- }
3295
- /**
3296
- * Adds where conditions to the query.
3297
- *
3298
- * @param conditions - The conditions to filter by
3299
- * @returns The query builder for chaining
3300
- *
3301
- * @example
3302
- * ```typescript
3303
- * .where({
3304
- * category: "Dessert",
3305
- * rating: { gt: 4 },
3306
- * tags: ["vegan", "quick"],
3307
- * published: true
3308
- * })
3309
- * ```
3310
- */
3311
- where(conditions) {
3312
- this.queryParams.where = conditions;
3313
- return this;
3314
- }
3315
- /**
3316
- * Sets the order for the query results.
3317
- *
3318
- * @param orderBy - The ordering criteria
3319
- * @returns The query builder for chaining
3320
- *
3321
- * @example
3322
- * ```typescript
3323
- * .order({ createdAt: "DESC" })
3324
- * ```
3325
- */
3326
- order(orderBy) {
3327
- this.queryParams.order = orderBy;
3328
- return this;
3329
- }
3330
- /**
3331
- * Sets the maximum number of results to return.
3332
- *
3333
- * @param limit - Maximum number of results
3334
- * @returns The query builder for chaining
3335
- *
3336
- * @example
3337
- * ```typescript
3338
- * .limit(10)
3339
- * ```
3340
- */
3341
- limit(limit) {
3342
- this.queryParams.limit = limit;
3343
- return this;
3344
- }
3345
- /**
3346
- * Sets the number of results to skip.
3347
- *
3348
- * @param offset - Number of results to skip
3349
- * @returns The query builder for chaining
3350
- *
3351
- * @example
3352
- * ```typescript
3353
- * .offset(20) // Skip first 20 results
3354
- * ```
3355
- */
3356
- offset(offset) {
3357
- this.queryParams.offset = offset;
3358
- return this;
3359
- }
3360
- /**
3361
- * Scopes the query to instances linked from a parent.
3362
- *
3363
- * The predicate is resolved in order of precedence:
3364
- * 1. **Instance only** — the parent's constructor is used as the model
3365
- * class; its relation metadata is scanned for a relation whose
3366
- * `target()` matches the queried model class.
3367
- * 2. **Instance + options with `field`** — direct field-name lookup on
3368
- * the parent model's relation metadata (disambiguates when a parent
3369
- * has multiple relations targeting the same child class).
3370
- * 3. **String id + model class** — same metadata scan (or field lookup if
3371
- * options include `field`).
3372
- * 4. **String id + string predicate** — raw escape hatch, no metadata lookup.
3373
- *
3374
- * Passing a plain string id with no second argument throws because the
3375
- * predicate cannot be resolved without a model class.
3376
- *
3377
- * @param idOrInstance - The parent's expression URI **or** an Ad4mModel instance
3378
- * @param modelOrPredicate - A model class (predicate auto-resolved) **or** a raw predicate string
3379
- * @param options - Optional settings: `field` for direct relation-name lookup
3380
- * @returns The query builder for chaining
3381
- *
3382
- * @example
3383
- * ```typescript
3384
- * // Instance — predicate auto-resolved from Cookbook's @HasMany(() => Recipe)
3385
- * Recipe.query(perspective).parent(cookbook).get();
3386
- *
3387
- * // Instance + field — disambiguate when parent has multiple relations to same child
3388
- * Recipe.query(perspective).parent(cookbook, { field: "recipes" }).get();
3389
- *
3390
- * // String id + model class
3391
- * Recipe.query(perspective).parent(cookbookId, Cookbook).get();
3392
- *
3393
- * // String id + model class + field
3394
- * Recipe.query(perspective).parent(cookbookId, Cookbook, { field: "recipes" }).get();
3395
- *
3396
- * // String id + raw predicate (escape hatch)
3397
- * Recipe.query(perspective).parent(cookbookId, "cookbook://recipe").get();
3398
- * ```
3399
- */
3400
- parent(idOrInstance, modelOrPredicate, options) {
3401
- const id = typeof idOrInstance === 'string' ? idOrInstance : idOrInstance.id;
3402
- // Handle options-object as second arg: parent(instance, { field: "recipes" })
3403
- if (typeof modelOrPredicate === 'object' && modelOrPredicate !== null && !('prototype' in modelOrPredicate)) {
3404
- if (typeof idOrInstance === 'string') {
3405
- throw new Error('parent() called with a string id and options object requires a model class as second argument');
3406
- }
3407
- const model = idOrInstance.constructor;
3408
- this.queryParams.parent = { id, model, field: modelOrPredicate.field };
3409
- return this;
3410
- }
3411
- const field = options?.field;
3412
- if (typeof modelOrPredicate === 'string') {
3413
- // Raw predicate string → raw form of ParentScope
3414
- this.queryParams.parent = { id, predicate: modelOrPredicate };
3415
- }
3416
- else if (typeof modelOrPredicate === 'function') {
3417
- // Model class → model form of ParentScope
3418
- this.queryParams.parent = { id, model: modelOrPredicate, ...(field && { field }) };
3419
- }
3420
- else if (typeof idOrInstance !== 'string') {
3421
- // Ad4mModel instance — derive model class from constructor
3422
- this.queryParams.parent = { id, model: idOrInstance.constructor, ...(field && { field }) };
3423
- }
3424
- else {
3425
- throw new Error('parent() called with a string id requires a second argument: either a model class or a predicate string');
3426
- }
3427
- return this;
3428
- }
3429
- /**
3430
- * Specifies which properties to include in the results.
3431
- *
3432
- * @param properties - Array of property names to include
3433
- * @returns The query builder for chaining
3434
- *
3435
- * @example
3436
- * ```typescript
3437
- * .properties(["name", "description", "rating"])
3438
- * ```
3439
- */
3440
- properties(properties) {
3441
- this.queryParams.properties = properties;
3442
- return this;
3443
- }
3444
- /**
3445
- * Specifies which relations to eager-load (hydrate into model instances).
3446
- *
3447
- * Without `include`, relation fields contain raw expression URIs (strings).
3448
- * With `include`, the URIs are resolved into fully-hydrated model instances
3449
- * using the `target` class declared in the relation decorator.
3450
- *
3451
- * Supports nested includes for multi-level eager loading.
3452
- *
3453
- * @param map - An IncludeMap describing which relations to hydrate
3454
- * @returns The query builder for chaining
3455
- *
3456
- * @example
3457
- * ```typescript
3458
- * // Hydrate comments one level deep
3459
- * const recipes = await Recipe.query(perspective)
3460
- * .include({ comments: true })
3461
- * .run();
3462
- * // recipe.comments is now Comment[] (model instances), not string[]
3463
- *
3464
- * // Nested: hydrate comments AND each comment's author
3465
- * const recipes = await Recipe.query(perspective)
3466
- * .include({ comments: { author: true } })
3467
- * .run();
3468
- * ```
3469
- */
3470
- include(map) {
3471
- this.queryParams.include = map;
3472
- return this;
3473
- }
3474
- overrideModelClassName(className) {
3475
- this.modelClassName = className;
3476
- return this;
3477
- }
3478
- /**
3479
- * Enables or disables SurrealDB query path.
3480
- *
3481
- * @param enabled - Whether to use SurrealDB (default: true, 10-100x faster) or Prolog (legacy)
3482
- * @returns The query builder for chaining
3483
- *
3484
- * @example
3485
- * ```typescript
3486
- * // Use SurrealDB (default)
3487
- * const recipes = await Recipe.query(perspective)
3488
- * .where({ category: "Dessert" })
3489
- * .useSurrealDB(true)
3490
- * .get();
3491
- *
3492
- * // Use Prolog (legacy)
3493
- * const recipesProlog = await Recipe.query(perspective)
3494
- * .where({ category: "Dessert" })
3495
- * .useSurrealDB(false)
3496
- * .get();
3497
- * ```
3498
- *
3499
- * @remarks
3500
- * Note: Subscriptions (subscribe(), countSubscribe(), paginateSubscribe()) default to SurrealDB live queries
3501
- * if useSurrealDB(true) is set (default).
3502
- */
3503
- useSurrealDB(enabled = true) {
3504
- this.useSurrealDBFlag = enabled;
3505
- return this;
3506
- }
3507
- /**
3508
- * Executes the query once and returns the results.
3509
- *
3510
- * @returns Array of matching entities
3511
- *
3512
- * @example
3513
- * ```typescript
3514
- * const recipes = await Recipe.query(perspective)
3515
- * .where({ category: "Dessert" })
3516
- * .get();
3517
- * ```
3518
- */
3519
- async get() {
3520
- let results;
3521
- if (this.useSurrealDBFlag) {
3522
- const surrealQuery = await this.ctor.queryToSurrealQL(this.perspective, this.queryParams);
3523
- const result = await this.perspective.querySurrealDB(surrealQuery);
3524
- ({ results } = await this.ctor.instancesFromSurrealResult(this.perspective, this.queryParams, result));
3525
- }
3526
- else {
3527
- const query = await this.ctor.queryToProlog(this.perspective, this.queryParams, this.modelClassName);
3528
- const result = await this.perspective.infer(query);
3529
- ({ results } = await this.ctor.instancesFromPrologResult(this.perspective, this.queryParams, result));
3530
- }
3531
- return results;
3532
- }
3533
- /**
3534
- * Returns the first matching instance, or `null` if none match.
3535
- *
3536
- * Internally sets `limit: 1` and delegates to `get()`.
3537
- *
3538
- * @returns The first matching instance, or `null`
3539
- *
3540
- * @example
3541
- * ```typescript
3542
- * const recipe = await Recipe.query(perspective)
3543
- * .where({ name: "Pasta" })
3544
- * .first();
3545
- * ```
3546
- */
3547
- async first() {
3548
- this.queryParams.limit = 1;
3549
- const results = await this.get();
3550
- return results[0] ?? null;
3551
- }
3552
- /**
3553
- * Subscribes to the query and receives updates when results change.
3554
- *
3555
- * This method:
3556
- * 1. Creates and initializes a SurrealDB live query subscription (default)
3557
- * 2. Sets up the callback to process future updates
3558
- * 3. Returns the initial results immediately
3559
- *
3560
- * Remember to call dispose() when you're done with the subscription
3561
- * to clean up resources.
3562
- *
3563
- * @param callback - Function to call with updated results
3564
- * @returns Initial results array
3565
- *
3566
- * @example
3567
- * ```typescript
3568
- * const builder = Recipe.query(perspective)
3569
- * .where({ status: "cooking" });
3570
- *
3571
- * const initialRecipes = await builder.subscribe(recipes => {
3572
- * console.log("Updated recipes:", recipes);
3573
- * });
3574
- *
3575
- * // When done with subscription:
3576
- * builder.dispose();
3577
- * ```
3578
- *
3579
- * @remarks
3580
- * By default, this uses SurrealDB live queries for real-time updates.
3581
- * Prolog subscriptions remain available via `.useSurrealDB(false)`.
3582
- */
3583
- async subscribe(callback) {
3584
- // Clean up any existing subscription
3585
- this.dispose();
3586
- const ctor = this.ctor;
3587
- if (this.useSurrealDBFlag) {
3588
- const surrealQuery = await ctor.queryToSurrealQL(this.perspective, this.queryParams);
3589
- this.currentSubscription = await this.perspective.subscribeSurrealDB(surrealQuery);
3590
- const processResults = async (result) => {
3591
- const { results } = await ctor.instancesFromSurrealResult(this.perspective, this.queryParams, result);
3592
- callback(results);
3593
- };
3594
- this.currentSubscription.onResult(processResults);
3595
- // Process initial result
3596
- const { results } = await ctor.instancesFromSurrealResult(this.perspective, this.queryParams, this.currentSubscription.result);
3597
- // Also invoke callback with initial results so subscribers see them
3598
- callback(results);
3599
- return results;
3600
- }
3601
- else {
3602
- const query = await ctor.queryToProlog(this.perspective, this.queryParams, this.modelClassName);
3603
- this.currentSubscription = await this.perspective.subscribeInfer(query);
3604
- const processResults = async (result) => {
3605
- const { results } = await ctor.instancesFromPrologResult(this.perspective, this.queryParams, result);
3606
- callback(results);
3607
- };
3608
- this.currentSubscription.onResult(processResults);
3609
- const { results } = await ctor.instancesFromPrologResult(this.perspective, this.queryParams, this.currentSubscription.result);
3610
- // Also invoke callback with initial results so subscribers see them
3611
- callback(results);
3612
- return results;
3613
- }
3614
- }
3615
- /**
3616
- * Gets the total count of matching entities.
3617
- *
3618
- * @returns Total count
3619
- *
3620
- * @example
3621
- * ```typescript
3622
- * const totalDesserts = await Recipe.query(perspective)
3623
- * .where({ category: "Dessert" })
3624
- * .count();
3625
- * ```
3626
- */
3627
- async count() {
3628
- if (this.useSurrealDBFlag) {
3629
- const surrealQuery = await this.ctor.queryToSurrealQL(this.perspective, this.queryParams);
3630
- const result = await this.perspective.querySurrealDB(surrealQuery);
3631
- // Use instancesFromSurrealResult to apply JS-level filtering for advanced where conditions
3632
- // (e.g., gt, gte, lt, lte, between, contains on properties and author/timestamp)
3633
- // This ensures count() returns the same number as get().length
3634
- const { totalCount } = await this.ctor.instancesFromSurrealResult(this.perspective, this.queryParams, result);
3635
- return totalCount;
3636
- }
3637
- else {
3638
- const query = await this.ctor.countQueryToProlog(this.perspective, this.queryParams, this.modelClassName);
3639
- const result = await this.perspective.infer(query);
3640
- return result?.[0]?.TotalCount || 0;
3641
- }
3642
- }
3643
- /**
3644
- * Subscribes to count updates for matching entities.
3645
- *
3646
- * This method:
3647
- * 1. Creates and initializes a SurrealDB live query subscription for the count (default)
3648
- * 2. Sets up the callback to process future count updates
3649
- * 3. Returns the initial count immediately
3650
- *
3651
- * Remember to call dispose() when you're done with the subscription
3652
- * to clean up resources.
3653
- *
3654
- * @param callback - Function to call with updated count
3655
- * @returns Initial count
3656
- *
3657
- * @example
3658
- * ```typescript
3659
- * const builder = Recipe.query(perspective)
3660
- * .where({ status: "active" });
3661
- *
3662
- * const initialCount = await builder.countSubscribe(count => {
3663
- * console.log("Active items:", count);
3664
- * });
3665
- *
3666
- * // When done with subscription:
3667
- * builder.dispose();
3668
- * ```
3669
- *
3670
- * @remarks
3671
- * By default, this uses SurrealDB live queries for real-time updates.
3672
- * Prolog subscriptions remain available via `.useSurrealDB(false)`.
3673
- */
3674
- async countSubscribe(callback) {
3675
- // Clean up any existing subscription
3676
- this.dispose();
3677
- if (this.useSurrealDBFlag) {
3678
- const surrealQuery = await this.ctor.queryToSurrealQL(this.perspective, this.queryParams);
3679
- this.currentSubscription = await this.perspective.subscribeSurrealDB(surrealQuery);
3680
- const processResults = async (result) => {
3681
- const { totalCount } = await this.ctor.instancesFromSurrealResult(this.perspective, this.queryParams, result);
3682
- callback(totalCount);
3683
- };
3684
- this.currentSubscription.onResult(processResults);
3685
- const { totalCount } = await this.ctor.instancesFromSurrealResult(this.perspective, this.queryParams, this.currentSubscription.result);
3686
- callback(totalCount);
3687
- return totalCount;
3688
- }
3689
- else {
3690
- const query = await this.ctor.countQueryToProlog(this.perspective, this.queryParams, this.modelClassName);
3691
- this.currentSubscription = await this.perspective.subscribeInfer(query);
3692
- const processResults = async (result) => {
3693
- const newCount = result?.[0]?.TotalCount || 0;
3694
- callback(newCount);
3695
- };
3696
- this.currentSubscription.onResult(processResults);
3697
- const initialCount = this.currentSubscription.result?.[0]?.TotalCount || 0;
3698
- callback(initialCount);
3699
- return initialCount;
3700
- }
3701
- }
3702
- /**
3703
- * Gets a page of results with pagination metadata.
3704
- *
3705
- * @param pageSize - Number of items per page
3706
- * @param pageNumber - Which page to retrieve (1-based)
3707
- * @returns Paginated results with metadata
3708
- *
3709
- * @example
3710
- * ```typescript
3711
- * const page = await Recipe.query(perspective)
3712
- * .where({ category: "Main" })
3713
- * .paginate(10, 1);
3714
- * console.log(`Page ${page.pageNumber}, ${page.results.length} of ${page.totalCount}`);
3715
- * ```
3716
- */
3717
- async paginate(pageSize, pageNumber) {
3718
- const paginationQuery = { ...(this.queryParams || {}), limit: pageSize, offset: pageSize * (pageNumber - 1), count: true };
3719
- if (this.useSurrealDBFlag) {
3720
- const surrealQuery = await this.ctor.queryToSurrealQL(this.perspective, paginationQuery);
3721
- const result = await this.perspective.querySurrealDB(surrealQuery);
3722
- const { results, totalCount } = (await this.ctor.instancesFromSurrealResult(this.perspective, paginationQuery, result));
3723
- return { results, totalCount, pageSize, pageNumber };
3724
- }
3725
- else {
3726
- const prologQuery = await this.ctor.queryToProlog(this.perspective, paginationQuery, this.modelClassName);
3727
- const result = await this.perspective.infer(prologQuery);
3728
- const { results, totalCount } = (await this.ctor.instancesFromPrologResult(this.perspective, paginationQuery, result));
3729
- return { results, totalCount, pageSize, pageNumber };
3730
- }
3731
- }
3732
- /**
3733
- * Subscribes to paginated results updates.
3734
- *
3735
- * This method:
3736
- * 1. Creates and initializes a SurrealDB live query subscription for the paginated results (default)
3737
- * 2. Sets up the callback to process future page updates
3738
- * 3. Returns the initial page immediately
3739
- *
3740
- * Remember to call dispose() when you're done with the subscription
3741
- * to clean up resources.
3742
- *
3743
- * @param pageSize - Number of items per page
3744
- * @param pageNumber - Which page to retrieve (1-based)
3745
- * @param callback - Function to call with updated pagination results
3746
- * @returns Initial pagination results
3747
- *
3748
- * @example
3749
- * ```typescript
3750
- * const builder = Recipe.query(perspective)
3751
- * .where({ category: "Main" });
3752
- *
3753
- * const initialPage = await builder.paginateSubscribe(10, 1, page => {
3754
- * console.log("Updated page:", page.results);
3755
- * });
3756
- *
3757
- * // When done with subscription:
3758
- * builder.dispose();
3759
- * ```
3760
- *
3761
- * @remarks
3762
- * By default, this uses SurrealDB live queries for real-time updates.
3763
- * Prolog subscriptions remain available via `.useSurrealDB(false)`.
3764
- */
3765
- async paginateSubscribe(pageSize, pageNumber, callback) {
3766
- // Clean up any existing subscription
3767
- this.dispose();
3768
- const paginationQuery = { ...(this.queryParams || {}), limit: pageSize, offset: pageSize * (pageNumber - 1), count: true };
3769
- if (this.useSurrealDBFlag) {
3770
- const surrealQuery = await this.ctor.queryToSurrealQL(this.perspective, paginationQuery);
3771
- this.currentSubscription = await this.perspective.subscribeSurrealDB(surrealQuery);
3772
- const processResults = async (result) => {
3773
- const { results, totalCount } = (await this.ctor.instancesFromSurrealResult(this.perspective, paginationQuery, result));
3774
- callback({ results, totalCount, pageSize, pageNumber });
3775
- };
3776
- this.currentSubscription.onResult(processResults);
3777
- const { results, totalCount } = (await this.ctor.instancesFromSurrealResult(this.perspective, paginationQuery, this.currentSubscription.result));
3778
- const initialPage = { results, totalCount, pageSize, pageNumber };
3779
- callback(initialPage);
3780
- return initialPage;
3781
- }
3782
- else {
3783
- const prologQuery = await this.ctor.queryToProlog(this.perspective, paginationQuery, this.modelClassName);
3784
- this.currentSubscription = await this.perspective.subscribeInfer(prologQuery);
3785
- const processResults = async (r) => {
3786
- const { results, totalCount } = (await this.ctor.instancesFromPrologResult(this.perspective, this.queryParams, r));
3787
- callback({ results, totalCount, pageSize, pageNumber });
3788
- };
3789
- this.currentSubscription.onResult(processResults);
3790
- const { results, totalCount } = (await this.ctor.instancesFromPrologResult(this.perspective, paginationQuery, this.currentSubscription.result));
3791
- const initialPrologPage = { results, totalCount, pageSize, pageNumber };
3792
- callback(initialPrologPage);
3793
- return initialPrologPage;
3794
- }
3795
- }
3796
- }
3797
- // ── Standalone Prolog fact generator ──────────────────────────────────────────
3798
- /**
3799
- * Convert a camelCase or PascalCase identifier to snake_case.
3800
- * Examples: "TestPost" -> "test_post", "createdAt" -> "created_at"
3801
- */
3802
- function toSnakeCase(str) {
3803
- return str
3804
- .replace(/([A-Z])/g, "_$1")
3805
- .toLowerCase()
3806
- .replace(/^_/, "");
3807
- }
3808
- function buildInstanceClause(predicateName, metadata) {
3809
- const props = metadata.properties;
3810
- // Collect flags first — these are the strongest recognizers
3811
- const flags = Object.values(props).filter((p) => p.flag && p.predicate && p.initial);
3812
- if (flags.length > 0) {
3813
- const conditions = flags
3814
- .map((p) => `triple(X, '${p.predicate}', '${p.initial}')`)
3815
- .join(",\n ");
3816
- return `${predicateName}(X) :-\n ${conditions}.`;
3817
- }
3818
- // Fallback: required non-flag properties
3819
- const required = Object.values(props).filter((p) => p.required && p.predicate && !p.flag);
3820
- if (required.length > 0) {
3821
- const conditions = required
3822
- .map((p) => `triple(X, '${p.predicate}', _)`)
3823
- .join(",\n ");
3824
- return `${predicateName}(X) :-\n ${conditions}.`;
3825
- }
3826
- // Open-world structural fallback: match nodes that have at least one of the
3827
- // model's declared property predicates. Uses disjunction (;) so any single
3828
- // predicate is enough.
3829
- const allPredicates = Object.values(props)
3830
- .filter((p) => p.predicate)
3831
- .map((p) => p.predicate);
3832
- if (metadata.relations) {
3833
- for (const rel of Object.values(metadata.relations)) {
3834
- if (rel.predicate)
3835
- allPredicates.push(rel.predicate);
3836
- }
3837
- }
3838
- if (allPredicates.length > 0) {
3839
- const disjunction = allPredicates
3840
- .map((pred) => `triple(X, '${pred}', _)`)
3841
- .join(" ;\n ");
3842
- return `${predicateName}(X) :-\n (${disjunction}).`;
3843
- }
3844
- return null;
3845
- }
3846
- function buildPropertyClause(modelPredicateName, prop) {
3847
- if (prop.flag)
3848
- return null;
3849
- if (!prop.predicate)
3850
- return null;
3851
- const clauseName = `${modelPredicateName}_${toSnakeCase(prop.name)}`;
3852
- return `${clauseName}(X, Value) :- triple(X, '${prop.predicate}', Value).`;
3853
- }
3854
- function buildRelationClause(modelPredicateName, relation) {
3855
- if (!relation.predicate)
3856
- return null;
3857
- const clauseName = `${modelPredicateName}_${toSnakeCase(relation.name)}`;
3858
- if (relation.direction === "reverse") {
3859
- return `${clauseName}(X, Values) :- findall(V, triple(V, '${relation.predicate}', X), Values).`;
3860
- }
3861
- return `${clauseName}(X, Values) :- findall(V, triple(X, '${relation.predicate}', V), Values).`;
3862
- }
3863
- /**
3864
- * Generate Prolog predicate facts from a model class's decorator metadata.
3865
- *
3866
- * Given a model class decorated with `@Model` (and its `@Flag`, `@Property`,
3867
- * `@HasMany`, `@BelongsToMany` decorators), this function emits a string of
3868
- * Prolog clauses that can be prepended to any `perspective.infer()` call.
3869
- *
3870
- * The generated predicates are:
3871
- * - **Instance recognizer** — `modelName(X)` — matches instances of the model
3872
- * - **Property getters** — `modelName_propName(X, Value)` — one per property
3873
- * - **Relation getters** — `modelName_relName(X, Values)` — one per relation
3874
- *
3875
- * @example
3876
- * ```typescript
3877
- * import { generatePrologFacts } from '@coasys/ad4m';
3878
- *
3879
- * const facts = generatePrologFacts(Poll);
3880
- * const result = await perspective.infer(\`
3881
- * \${facts}
3882
- * recent_popular_poll(X) :-
3883
- * poll(X),
3884
- * poll_vote_count(X, N), N > 10.
3885
- * \`);
3886
- * ```
3887
- *
3888
- * @param ModelClass - A class decorated with `@Model` that extends `Ad4mModel`
3889
- * @returns A multi-line Prolog string ready for use with `perspective.infer()`
3890
- */
3891
- export function generatePrologFacts(ModelClass) {
3892
- const metadata = ModelClass.getModelMetadata();
3893
- const predicateName = toSnakeCase(metadata.className);
3894
- const lines = [];
3895
- lines.push(`% ${metadata.className} — generated Prolog facts`);
3896
- // Instance recognizer
3897
- const instanceClause = buildInstanceClause(predicateName, metadata);
3898
- if (instanceClause) {
3899
- lines.push("");
3900
- lines.push(`% Instance recognizer`);
3901
- lines.push(instanceClause);
3902
- }
3903
- // Property getters
3904
- const propClauses = Object.values(metadata.properties)
3905
- .map((p) => buildPropertyClause(predicateName, p))
3906
- .filter((c) => c !== null);
3907
- if (propClauses.length > 0) {
3908
- lines.push("");
3909
- lines.push(`% Field getters`);
3910
- lines.push(...propClauses);
3911
- }
3912
- // Relation getters
3913
- const relClauses = Object.values(metadata.relations)
3914
- .map((c) => buildRelationClause(predicateName, c))
3915
- .filter((c) => c !== null);
3916
- if (relClauses.length > 0) {
3917
- lines.push("");
3918
- lines.push(`% Relation getters`);
3919
- lines.push(...relClauses);
3920
- }
3921
- return lines.join("\n");
3922
- }