@coasys/ad4m 0.12.0-rc1-dev.1 → 0.12.0-rc1-dev.3

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 (124) hide show
  1. package/jest.config.js +8 -1
  2. package/lib/index.cjs +13793 -12854
  3. package/lib/index.js +13782 -12851
  4. package/lib/src/Ad4mClient.test.d.ts +1 -0
  5. package/lib/src/Ad4mClient.test.js +1204 -0
  6. package/lib/src/Literal.test.d.ts +1 -0
  7. package/lib/src/Literal.test.js +41 -0
  8. package/lib/src/model/Ad4mModel.d.ts +528 -101
  9. package/lib/src/model/Ad4mModel.js +1670 -748
  10. package/lib/src/model/Ad4mModel.test.js +140 -156
  11. package/lib/src/model/Subject.d.ts +3 -3
  12. package/lib/src/model/Subject.js +25 -25
  13. package/lib/src/model/decorators.d.ts +259 -247
  14. package/lib/src/model/decorators.js +379 -422
  15. package/lib/src/model/mutation.d.ts +81 -0
  16. package/lib/src/model/mutation.js +317 -0
  17. package/lib/src/model/parentUtils.d.ts +32 -0
  18. package/lib/src/model/parentUtils.js +64 -0
  19. package/lib/src/model/prolog/generatePrologFacts.d.ts +36 -0
  20. package/lib/src/model/prolog/generatePrologFacts.js +139 -0
  21. package/lib/src/model/prolog/index.d.ts +1 -0
  22. package/lib/src/model/prolog/index.js +1 -0
  23. package/lib/src/model/query/ModelQueryBuilder.d.ts +82 -0
  24. package/lib/src/model/query/ModelQueryBuilder.js +115 -0
  25. package/lib/src/model/query/QueryBuilder.d.ts +101 -0
  26. package/lib/src/model/query/QueryBuilder.js +193 -0
  27. package/lib/src/model/query/SurrealQueryBuilder.d.ts +48 -0
  28. package/lib/src/model/query/SurrealQueryBuilder.js +371 -0
  29. package/lib/src/model/query/fetchInstance.d.ts +24 -0
  30. package/lib/src/model/query/fetchInstance.js +144 -0
  31. package/lib/src/model/query/hydration.d.ts +54 -0
  32. package/lib/src/model/query/hydration.js +214 -0
  33. package/lib/src/model/query/operations.d.ts +59 -0
  34. package/lib/src/model/query/operations.js +384 -0
  35. package/lib/src/model/query/snapshot.d.ts +59 -0
  36. package/lib/src/model/query/snapshot.js +106 -0
  37. package/lib/src/model/query/surrealCompiler.d.ts +42 -0
  38. package/lib/src/model/query/surrealCompiler.js +304 -0
  39. package/lib/src/model/schema/fromJSONSchema.d.ts +67 -0
  40. package/lib/src/model/schema/fromJSONSchema.js +264 -0
  41. package/lib/src/model/schema/metadata.d.ts +15 -0
  42. package/lib/src/model/schema/metadata.js +112 -0
  43. package/lib/src/model/subscription.d.ts +47 -0
  44. package/lib/src/model/subscription.js +231 -0
  45. package/lib/src/model/transaction.d.ts +27 -0
  46. package/lib/src/model/transaction.js +32 -0
  47. package/lib/src/model/types.d.ts +195 -0
  48. package/lib/src/model/types.js +8 -0
  49. package/lib/src/model/util.d.ts +6 -6
  50. package/lib/src/model/util.js +22 -22
  51. package/lib/src/neighbourhood/NeighbourhoodClient.js +31 -12
  52. package/lib/src/perspectives/PerspectiveProxy.d.ts +9 -9
  53. package/lib/src/perspectives/PerspectiveProxy.js +63 -51
  54. package/lib/src/shacl/SHACLShape.d.ts +9 -0
  55. package/lib/src/shacl/SHACLShape.js +28 -4
  56. package/lib/src/shims/reflect-metadata.d.ts +0 -0
  57. package/lib/src/shims/type-graphql.d.ts +32 -0
  58. package/lib/src/src/Ad4mClient.d.ts +28 -0
  59. package/lib/src/src/Address.d.ts +1 -0
  60. package/lib/src/src/DID.d.ts +1 -0
  61. package/lib/src/src/Exception.d.ts +7 -0
  62. package/lib/src/src/Literal.d.ts +7 -0
  63. package/lib/src/src/PubSub.d.ts +17 -0
  64. package/lib/src/src/SmartLiteral.d.ts +12 -0
  65. package/lib/src/src/agent/Agent.d.ts +110 -0
  66. package/lib/src/src/agent/AgentClient.d.ts +62 -0
  67. package/lib/src/src/agent/AgentResolver.d.ts +30 -0
  68. package/lib/src/src/agent/AgentStatus.d.ts +8 -0
  69. package/lib/src/src/ai/AIClient.d.ts +32 -0
  70. package/lib/src/src/ai/AIResolver.d.ts +75 -0
  71. package/lib/src/src/ai/Tasks.d.ts +37 -0
  72. package/lib/src/src/buildSchema.d.ts +1 -0
  73. package/lib/src/src/expression/Expression.d.ts +28 -0
  74. package/lib/src/src/expression/ExpressionClient.d.ts +13 -0
  75. package/lib/src/src/expression/ExpressionRef.d.ts +9 -0
  76. package/lib/src/src/expression/ExpressionResolver.d.ts +10 -0
  77. package/lib/src/src/index.d.ts +35 -0
  78. package/lib/src/src/jestSetup.d.ts +1 -0
  79. package/lib/src/src/language/Icon.d.ts +4 -0
  80. package/lib/src/src/language/Language.d.ts +206 -0
  81. package/lib/src/src/language/LanguageClient.d.ts +17 -0
  82. package/lib/src/src/language/LanguageContext.d.ts +37 -0
  83. package/lib/src/src/language/LanguageHandle.d.ts +9 -0
  84. package/lib/src/src/language/LanguageMeta.d.ts +35 -0
  85. package/lib/src/src/language/LanguageRef.d.ts +6 -0
  86. package/lib/src/src/language/LanguageResolver.d.ts +19 -0
  87. package/lib/src/src/links/Links.d.ts +39 -0
  88. package/lib/src/src/links/Links.test.d.ts +1 -0
  89. package/lib/src/src/model/Ad4mModel.d.ts +1438 -0
  90. package/lib/src/src/model/Ad4mModel.test.d.ts +1 -0
  91. package/lib/src/src/model/Subject.d.ts +25 -0
  92. package/lib/src/src/model/decorators.d.ts +545 -0
  93. package/lib/src/src/model/util.d.ts +12 -0
  94. package/lib/src/src/neighbourhood/Neighbourhood.d.ts +10 -0
  95. package/lib/src/src/neighbourhood/NeighbourhoodClient.d.ts +25 -0
  96. package/lib/src/src/neighbourhood/NeighbourhoodProxy.d.ts +19 -0
  97. package/lib/src/src/neighbourhood/NeighbourhoodProxy.test.d.ts +1 -0
  98. package/lib/src/src/neighbourhood/NeighbourhoodResolver.d.ts +24 -0
  99. package/lib/src/src/perspectives/LinkQuery.d.ts +11 -0
  100. package/lib/src/src/perspectives/Perspective.d.ts +38 -0
  101. package/lib/src/src/perspectives/Perspective.test.d.ts +1 -0
  102. package/lib/src/src/perspectives/PerspectiveClient.d.ts +97 -0
  103. package/lib/src/src/perspectives/PerspectiveDiff.d.ts +9 -0
  104. package/lib/src/src/perspectives/PerspectiveHandle.d.ts +18 -0
  105. package/lib/src/src/perspectives/PerspectiveProxy.d.ts +865 -0
  106. package/lib/src/src/perspectives/PerspectiveResolver.d.ts +57 -0
  107. package/lib/src/src/runtime/RuntimeClient.d.ts +56 -0
  108. package/lib/src/src/runtime/RuntimeResolver.d.ts +132 -0
  109. package/lib/src/src/shacl/SHACLFlow.d.ts +171 -0
  110. package/lib/src/src/shacl/SHACLFlow.test.d.ts +1 -0
  111. package/lib/src/src/shacl/SHACLShape.d.ts +117 -0
  112. package/lib/src/src/shacl/SHACLShape.test.d.ts +1 -0
  113. package/lib/src/src/typeDefs.d.ts +1 -0
  114. package/lib/src/src/unwrapApolloResult.d.ts +2 -0
  115. package/lib/src/src/utils.d.ts +25 -0
  116. package/package.json +20 -24
  117. package/src/model/Ad4mModel.test.ts +132 -149
  118. package/src/model/Ad4mModel.ts +1930 -784
  119. package/src/model/Subject.ts +24 -24
  120. package/src/model/decorators.ts +626 -482
  121. package/src/model/util.ts +22 -22
  122. package/src/neighbourhood/NeighbourhoodClient.ts +32 -16
  123. package/src/perspectives/PerspectiveProxy.ts +69 -55
  124. package/src/shacl/SHACLShape.ts +33 -4
@@ -1,28 +1,48 @@
1
- var __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {
2
- if (kind === "m") throw new TypeError("Private method is not writable");
3
- if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
4
- if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
5
- return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
6
- };
7
- var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) {
8
- if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
9
- if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
10
- return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
11
- };
12
- var _Ad4mModel_baseExpression, _Ad4mModel_subjectClassName, _Ad4mModel_source, _Ad4mModel_perspective;
13
1
  import { Literal } from "../Literal";
14
2
  import { Link } from "../links/Links";
15
- import { makeRandomPrologAtom, ModelOptions } from "./decorators";
3
+ import { LinkQuery } from "../perspectives/LinkQuery";
4
+ import { makeRandomId, Model, getPropertiesMetadata, getRelationsMetadata, setPropertyRegistryEntry, setRelationRegistryEntry } from "./decorators";
16
5
  import { propertyNameToSetterName } from "./util";
17
6
  import { escapeSurrealString } from "../utils";
18
7
  function capitalize(word) {
19
8
  return word.charAt(0).toUpperCase() + word.slice(1);
20
9
  }
21
- function buildSourceQuery(source) {
22
- // Constrains the query to instances that have the provided source
23
- if (!source)
24
- return "";
25
- return `triple("${source}", "ad4m://has_child", Base)`;
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)`;
26
46
  }
27
47
  // todo: only return Timestamp & Author from query (Base, AllLinks, and SortLinks not required)
28
48
  function buildAuthorAndTimestampQuery() {
@@ -50,31 +70,19 @@ function buildPropertiesQuery(properties) {
50
70
  ), Properties)
51
71
  `;
52
72
  }
53
- function buildCollectionsQuery(collections) {
54
- // Gets the name and array of values for all (or some) collections on a Ad4mModel instance
55
- // If no collections are provided, all are included
56
- return `
57
- findall([CollectionName, CollectionValues], (
58
- % Constrain to specified collections if provided
59
- ${collections ? `member(CollectionName, [${collections.map((name) => `"${name}"`).join(", ")}]),` : ""}
60
-
61
- collection(SubjectClass, CollectionName),
62
- collection_getter(SubjectClass, Base, CollectionName, CollectionValues)
63
- ), Collections)
64
- `;
65
- }
66
73
  function buildWhereQuery(where = {}) {
67
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).
68
76
  function formatValue(value) {
69
77
  // Wrap strings in quotes
70
78
  return typeof value === "string" ? `"${value}"` : value;
71
79
  }
72
80
  return Object.entries(where)
73
81
  .map(([key, value]) => {
74
- const isSpecial = ["base", "author", "timestamp"].includes(key);
82
+ const isSpecial = ["id", "author", "timestamp"].includes(key);
75
83
  const getter = `resolve_property(SubjectClass, Base, "${key}", Value${key}, _)`;
76
- // const getter = `property_getter(SubjectClass, Base, "${key}", URI), literal_from_url(URI, V, _)`;
77
- const field = capitalize(key);
84
+ // For 'id' the Prolog variable is always 'Base'
85
+ const field = key === "id" ? "Base" : capitalize(key);
78
86
  // Handle direct array values (for IN conditions)
79
87
  if (Array.isArray(value)) {
80
88
  const formattedValues = value.map((v) => formatValue(v)).join(", ");
@@ -137,8 +145,22 @@ function buildCountQuery(count) {
137
145
  function buildOrderQuery(order) {
138
146
  if (!order)
139
147
  return "SortedInstances = UnsortedInstances";
140
- const [propertyName, direction] = Object.entries(order)[0];
141
- return `sort_instances(UnsortedInstances, "${propertyName}", "${direction}", SortedInstances)`;
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 ");
142
164
  }
143
165
  function buildOffsetQuery(offset) {
144
166
  if (!offset || offset < 0)
@@ -191,21 +213,21 @@ function isNumericType(schema) {
191
213
  *
192
214
  * @description
193
215
  * Ad4mModel provides the foundation for creating data models that are stored in AD4M perspectives.
194
- * Each model instance is represented as a subgraph in the perspective, with properties and collections
216
+ * Each model instance is represented as a subgraph in the perspective, with properties and relations
195
217
  * mapped to links in that graph. The class uses Prolog-based queries to efficiently search and filter
196
218
  * instances based on their properties and relationships.
197
219
  *
198
220
  * Key concepts:
199
221
  * - Each model instance has a unique base expression that serves as its identifier
200
222
  * - Properties are stored as links with predicates defined by the `through` option
201
- * - Collections represent one-to-many relationships as sets of links
223
+ * - Relations represent one-to-many relationships as sets of links
202
224
  * - Queries are translated to Prolog for efficient graph pattern matching
203
225
  * - Changes are tracked through the perspective's subscription system
204
226
  *
205
227
  * @example
206
228
  * ```typescript
207
229
  * // Define a recipe model
208
- * @ModelOptions({ name: "Recipe" })
230
+ * @Model({ name: "Recipe" })
209
231
  * class Recipe extends Ad4mModel {
210
232
  * // Required property with literal value
211
233
  * @Property({
@@ -233,15 +255,12 @@ function isNumericType(schema) {
233
255
  * })
234
256
  * averageRating: number = 0;
235
257
  *
236
- * // Collection of ingredients
237
- * @Collection({ through: "recipe://ingredient" })
238
- * ingredients: string[] = [];
258
+ * // Relation of ingredients
259
+ * @HasMany({ through: "recipe://ingredient" })
260
+ * ingredients: string[] = [];
239
261
  *
240
- * // Collection of comments that are instances of another model
241
- * @Collection({
242
- * through: "recipe://comment",
243
- * where: { isInstance: Comment }
244
- * })
262
+ * // Relation of comments linked to another model
263
+ * @HasMany(() => Comment, { through: "recipe://comment" })
245
264
  * comments: Comment[] = [];
246
265
  * }
247
266
  *
@@ -286,6 +305,23 @@ function isNumericType(schema) {
286
305
  * ```
287
306
  */
288
307
  export class Ad4mModel {
308
+ /**
309
+ * Generates the SDNA (Subject DNA) Prolog rules for this model class.
310
+ * Injected at class-definition time by the `@Model` decorator.
311
+ * Returns a default value on un-decorated base classes.
312
+ */
313
+ static generateSDNA() {
314
+ return { sdna: '', name: '' };
315
+ }
316
+ /**
317
+ * Generates the SHACL shape graph for this model class.
318
+ * Injected at class-definition time by the `@Model` decorator.
319
+ * Returns `{ shape: null, name: '' }` on un-decorated base classes —
320
+ * the decorator's `parentSHACL?.shape?.nodeShapeUri` check handles this.
321
+ */
322
+ static generateSHACL() {
323
+ return { shape: null, name: '' };
324
+ }
289
325
  static async getClassName(perspective) {
290
326
  // Check if this is the Ad4mModel class itself or a subclass
291
327
  const isBaseClass = this === Ad4mModel;
@@ -317,60 +353,60 @@ export class Ad4mModel {
317
353
  * Extracts metadata from decorators for query building.
318
354
  *
319
355
  * @description
320
- * This method reads the metadata stored by decorators (@Property, @Collection, etc.)
356
+ * This method reads the metadata stored by decorators (@Property, @HasMany, etc.)
321
357
  * and returns it in a structured format that's easier to work with for query builders
322
358
  * and other systems that need to introspect model structure.
323
359
  *
324
360
  * The metadata includes:
325
- * - Class name from @ModelOptions
361
+ * - Class name from @Model
326
362
  * - Property metadata (predicates, types, constraints, etc.)
327
- * - Collection metadata (predicates, filters, etc.)
363
+ * - Relation metadata (predicates, filters, etc.)
328
364
  *
329
365
  * For models created via `fromJSONSchema()`, this method will derive metadata from
330
- * the stored `__properties` and `__collections` structures that were populated during
331
- * the dynamic class creation. If these structures are empty but a JSON schema was
332
- * attached to the class, it can fall back to deriving metadata from that schema.
366
+ * the WeakMap registries that were populated during the dynamic class creation.
367
+ * If these structures are empty but a JSON schema was attached to the class,
368
+ * it can fall back to deriving metadata from that schema.
333
369
  *
334
- * @returns Structured metadata object containing className, properties, and collections
335
- * @throws Error if the class doesn't have @ModelOptions decorator
370
+ * @returns Structured metadata object containing className, properties, and relations
371
+ * @throws Error if the class doesn't have @Model decorator
336
372
  *
337
373
  * @example
338
374
  * ```typescript
339
- * @ModelOptions({ name: "Recipe" })
375
+ * @Model({ name: "Recipe" })
340
376
  * class Recipe extends Ad4mModel {
341
377
  * @Property({ through: "recipe://name", resolveLanguage: "literal" })
342
378
  * name: string = "";
343
379
  *
344
- * @Collection({ through: "recipe://ingredient" })
380
+ * @HasMany({ through: "recipe://ingredient" })
345
381
  * ingredients: string[] = [];
346
382
  * }
347
383
  *
348
384
  * const metadata = Recipe.getModelMetadata();
349
385
  * console.log(metadata.className); // "Recipe"
350
386
  * console.log(metadata.properties.name.predicate); // "recipe://name"
351
- * console.log(metadata.collections.ingredients.predicate); // "recipe://ingredient"
387
+ * console.log(metadata.relations.ingredients.predicate); // "recipe://ingredient"
352
388
  * ```
353
389
  */
354
390
  static getModelMetadata() {
355
391
  // Access the prototype with any type to access decorator-added properties
356
392
  const prototype = this.prototype;
357
- // Validate that the class has @ModelOptions decorator
393
+ // Validate that the class has @Model decorator
358
394
  // The decorator sets prototype.className, so we check for its existence
359
395
  if (!prototype.className || prototype.className === 'Ad4mModel') {
360
- throw new Error("Model class must be decorated with @ModelOptions");
396
+ throw new Error("Model class must be decorated with @Model");
361
397
  }
362
398
  // Extract className
363
399
  const className = prototype.className;
364
- // Extract properties from prototype.__properties
400
+ // Extract properties from WeakMap registry
365
401
  const propertiesMetadata = {};
366
- const prototypeProperties = prototype.__properties || {};
402
+ const prototypeProperties = getPropertiesMetadata(this);
367
403
  for (const [propertyName, opts] of Object.entries(prototypeProperties)) {
368
404
  const options = opts;
369
405
  propertiesMetadata[propertyName] = {
370
406
  name: propertyName,
371
407
  predicate: options.through || "",
372
408
  required: options.required || false,
373
- writable: options.writable || false,
409
+ readOnly: !(options.writable ?? false),
374
410
  ...(options.initial !== undefined && { initial: options.initial }),
375
411
  ...(options.resolveLanguage !== undefined && { resolveLanguage: options.resolveLanguage }),
376
412
  ...(options.prologGetter !== undefined && { prologGetter: options.prologGetter }),
@@ -381,24 +417,25 @@ export class Ad4mModel {
381
417
  ...(options.flag !== undefined && { flag: options.flag })
382
418
  };
383
419
  }
384
- // Extract collections from prototype.__collections
385
- const collectionsMetadata = {};
386
- const prototypeCollections = prototype.__collections || {};
387
- for (const [collectionName, opts] of Object.entries(prototypeCollections)) {
420
+ // Extract relations (relations) from WeakMap registry
421
+ const relationsMetadata = {};
422
+ const allRelationsMeta = getRelationsMetadata(this);
423
+ const prototypeRelations = Object.fromEntries(Object.entries(allRelationsMeta).filter(([, r]) => r.kind === 'hasMany' || r.kind === 'belongsToMany'));
424
+ for (const [relationName, opts] of Object.entries(prototypeRelations)) {
388
425
  const options = opts;
389
- collectionsMetadata[collectionName] = {
390
- name: collectionName,
391
- predicate: options.through || "",
392
- ...(options.where !== undefined && { where: options.where }),
426
+ relationsMetadata[relationName] = {
427
+ name: relationName,
428
+ predicate: options.predicate || "",
393
429
  ...(options.local !== undefined && { local: options.local }),
394
- ...(options.getter !== undefined && { getter: options.getter })
430
+ ...(options.getter !== undefined && { getter: options.getter }),
431
+ direction: (options.kind === 'belongsToMany' || options.kind === 'belongsToOne') ? 'reverse' : 'forward',
395
432
  };
396
433
  }
397
434
  // Fallback: If both structures are empty but a JSON schema is attached, derive from it
398
435
  // This handles edge cases where fromJSONSchema() was called but metadata wasn't properly populated
399
436
  const hasProperties = Object.keys(propertiesMetadata).length > 0;
400
- const hasCollections = Object.keys(collectionsMetadata).length > 0;
401
- const hasMetadata = hasProperties || hasCollections;
437
+ const hasRelations = Object.keys(relationsMetadata).length > 0;
438
+ const hasMetadata = hasProperties || hasRelations;
402
439
  if (!hasMetadata && prototype.__jsonSchema) {
403
440
  // Derive metadata from the attached JSON schema
404
441
  const schema = prototype.__jsonSchema;
@@ -408,7 +445,7 @@ export class Ad4mModel {
408
445
  const isArray = isArrayType(propertySchema);
409
446
  const predicate = this.determinePredicate(schema, propertyName, propertySchema, this.determineNamespace(schema, options), options);
410
447
  if (isArray) {
411
- collectionsMetadata[propertyName] = {
448
+ relationsMetadata[propertyName] = {
412
449
  name: propertyName,
413
450
  predicate: predicate,
414
451
  ...(propertySchema["x-ad4m"]?.local !== undefined && { local: propertySchema["x-ad4m"].local })
@@ -420,7 +457,7 @@ export class Ad4mModel {
420
457
  name: propertyName,
421
458
  predicate: predicate,
422
459
  required: isRequired,
423
- writable: propertySchema["x-ad4m"]?.writable !== false,
460
+ readOnly: propertySchema["x-ad4m"]?.writable === false,
424
461
  ...(propertySchema["x-ad4m"]?.resolveLanguage && { resolveLanguage: propertySchema["x-ad4m"].resolveLanguage }),
425
462
  ...(propertySchema["x-ad4m"]?.initial && { initial: propertySchema["x-ad4m"].initial }),
426
463
  ...(propertySchema["x-ad4m"]?.local !== undefined && { local: propertySchema["x-ad4m"].local })
@@ -432,14 +469,15 @@ export class Ad4mModel {
432
469
  return {
433
470
  className,
434
471
  properties: propertiesMetadata,
435
- collections: collectionsMetadata
472
+ relations: relationsMetadata,
436
473
  };
437
474
  }
438
475
  /**
439
476
  * Constructs a new model instance.
440
477
  *
441
478
  * @param perspective - The perspective where this model will be stored
442
- * @param baseExpression - Optional unique identifier for this instance
479
+ * @param baseExpression - Optional expression URI for this instance.
480
+ * If omitted, a random Literal URL is generated.
443
481
  * @param source - Optional source expression this instance is linked to
444
482
  *
445
483
  * @example
@@ -448,49 +486,50 @@ export class Ad4mModel {
448
486
  * const recipe = new Recipe(perspective);
449
487
  *
450
488
  * // Create with specific base expression
451
- * const recipe = new Recipe(perspective, "recipe://chocolate-cake");
452
- *
453
- * // Create with source link
454
- * const recipe = new Recipe(perspective, undefined, "cookbook://desserts");
489
+ * const recipe = new Recipe(perspective, "literal://...");
455
490
  * ```
456
491
  */
457
- constructor(perspective, baseExpression, source) {
458
- _Ad4mModel_baseExpression.set(this, void 0);
459
- _Ad4mModel_subjectClassName.set(this, void 0);
460
- _Ad4mModel_source.set(this, void 0);
461
- _Ad4mModel_perspective.set(this, void 0);
462
- __classPrivateFieldSet(this, _Ad4mModel_baseExpression, baseExpression ? baseExpression : Literal.from(makeRandomPrologAtom(24)).toUrl(), "f");
463
- __classPrivateFieldSet(this, _Ad4mModel_perspective, perspective, "f");
464
- __classPrivateFieldSet(this, _Ad4mModel_source, source || "ad4m://self", "f");
492
+ constructor(perspective, baseExpression) {
493
+ this._snapshot = null;
494
+ this._baseExpression = baseExpression ? baseExpression : Literal.from(makeRandomId(24)).toUrl();
495
+ this._perspective = perspective;
465
496
  }
466
497
  /**
467
- * Gets the base expression of the subject.
498
+ * The unique identifier (expression URI) of this model instance.
499
+ */
500
+ get id() {
501
+ return this._baseExpression;
502
+ }
503
+ /**
504
+ * @deprecated Use `.id` instead. Will be removed in a future version.
468
505
  */
469
506
  get baseExpression() {
470
- return __classPrivateFieldGet(this, _Ad4mModel_baseExpression, "f");
507
+ return this._baseExpression;
471
508
  }
472
509
  /**
473
510
  * Protected getter for the perspective.
474
511
  * Allows subclasses to access the perspective while keeping it private from external code.
475
512
  */
476
513
  get perspective() {
477
- return __classPrivateFieldGet(this, _Ad4mModel_perspective, "f");
514
+ return this._perspective;
478
515
  }
479
516
  /**
480
517
  * Get property metadata from decorator (Phase 1: Prolog-free refactor)
481
518
  * @private
482
519
  */
483
520
  getPropertyMetadata(key) {
484
- const proto = Object.getPrototypeOf(this);
485
- return proto.__properties?.[key];
521
+ const ctor = this.constructor;
522
+ const props = getPropertiesMetadata(ctor);
523
+ return props[key];
486
524
  }
487
525
  /**
488
- * Get collection metadata from decorator (Phase 1: Prolog-free refactor)
526
+ * Get relation options from decorator
489
527
  * @private
490
528
  */
491
- getCollectionMetadata(key) {
492
- const proto = Object.getPrototypeOf(this);
493
- return proto.__collections?.[key];
529
+ getRelationOptions(key) {
530
+ const ctor = this.constructor;
531
+ const rels = getRelationsMetadata(ctor);
532
+ return rels[key];
494
533
  }
495
534
  /**
496
535
  * Generate property setter action from metadata (Phase 1: Prolog-free refactor)
@@ -498,8 +537,13 @@ export class Ad4mModel {
498
537
  * @private
499
538
  */
500
539
  generatePropertySetterAction(key, metadata) {
540
+ // Flags are always immutable — throw a clear error
541
+ if (metadata.flag) {
542
+ throw new Error(`Property "${key}" is a @Flag and cannot be written. ` +
543
+ `Flags are immutable type markers set at creation time.`);
544
+ }
501
545
  // Check if property is read-only
502
- if (metadata.writable === false) {
546
+ if (metadata.readOnly) {
503
547
  throw new Error(`Property "${key}" is read-only and cannot be written`);
504
548
  }
505
549
  if (metadata.prologSetter) {
@@ -519,17 +563,17 @@ export class Ad4mModel {
519
563
  }];
520
564
  }
521
565
  /**
522
- * Generate collection action from metadata (Phase 1: Prolog-free refactor)
566
+ * Generate relation action from metadata (Phase 1: Prolog-free refactor)
523
567
  * Replaces Prolog queries: collection_adder, collection_remover, collection_setter
524
568
  * @private
525
569
  */
526
- generateCollectionAction(key, actionType) {
527
- const metadata = this.getCollectionMetadata(key);
570
+ generateRelationAction(key, actionType) {
571
+ const metadata = this.getRelationOptions(key);
528
572
  if (!metadata) {
529
- throw new Error(`Collection "${key}" has no metadata defined`);
573
+ throw new Error(`Relation "${key}" has no metadata defined`);
530
574
  }
531
- if (!metadata.through) {
532
- throw new Error(`Collection "${key}" has no 'through' predicate defined`);
575
+ if (!metadata.predicate) {
576
+ throw new Error(`Relation "${key}" has no predicate defined`);
533
577
  }
534
578
  const actionMap = {
535
579
  adder: "addLink",
@@ -539,11 +583,196 @@ export class Ad4mModel {
539
583
  return [{
540
584
  action: actionMap[actionType],
541
585
  source: "this",
542
- predicate: metadata.through,
586
+ predicate: metadata.predicate,
543
587
  target: "value",
544
588
  ...(metadata.local && { local: true })
545
589
  }];
546
590
  }
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
+ /**
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
674
+ */
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
+ }
547
776
  static async assignValuesToInstance(perspective, instance, values) {
548
777
  // Map properties to object
549
778
  const propsObject = Object.fromEntries(await Promise.all(values.map(async ([name, value, resolve]) => {
@@ -583,7 +812,8 @@ export class Ad4mModel {
583
812
  }
584
813
  }
585
814
  // Apply transform function if it exists
586
- const transform = instance["__properties"]?.[name]?.transform;
815
+ const propsMeta = getPropertiesMetadata(instance.constructor);
816
+ const transform = propsMeta[name]?.transform;
587
817
  if (transform && typeof transform === "function") {
588
818
  finalValue = transform(finalValue);
589
819
  }
@@ -610,189 +840,206 @@ export class Ad4mModel {
610
840
  // Assign properties to instance
611
841
  Object.assign(instance, writableProps);
612
842
  }
613
- async getData() {
614
- // Builds an object with the author, timestamp, all properties, & all collections on the Ad4mModel and saves it to the instance
843
+ // ──────────────────────────────────────────────────────────
844
+ // Snapshot / dirty tracking
845
+ // ──────────────────────────────────────────────────────────
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
+ /**
865
+ * @param includedRelations Controls which relation fields are recorded
866
+ * in the snapshot for dirty-tracking:
867
+ * • `undefined` (default) — snapshot ALL relations (used by `.get()`,
868
+ * `.create()`, `.save()` etc. where full hydration has occurred).
869
+ * • `IncludeMap` object (e.g. `{ views: true }`) — only snapshot the
870
+ * relations named in the map. Fields not listed are omitted from
871
+ * the snapshot so that `changedFields()` ignores them.
872
+ * • `null` / empty object — skip ALL relations (used by bare
873
+ * subscriptions that don't eagerly load relations).
874
+ */
875
+ takeSnapshot(includedRelations) {
876
+ const ctor = this.constructor;
877
+ const metadata = ctor.getModelMetadata();
878
+ const snap = {};
879
+ // Always snapshot properties
880
+ for (const propName of Object.keys(metadata.properties)) {
881
+ const val = this[propName];
882
+ snap[propName] = Ad4mModel.normalizeValue(Array.isArray(val) ? [...val] : val);
883
+ }
884
+ // Snapshot relations only when appropriate:
885
+ // undefined → all relations (backward compat)
886
+ // IncludeMap → only the keys present in the map
887
+ // null / {} → none
888
+ if (includedRelations === undefined) {
889
+ // Full snapshot — e.g. after getData() / create()
890
+ for (const relName of Object.keys(metadata.relations)) {
891
+ const val = this[relName];
892
+ snap[relName] = Ad4mModel.normalizeValue(Array.isArray(val) ? [...val] : val);
893
+ }
894
+ }
895
+ else if (includedRelations && Object.keys(includedRelations).length > 0) {
896
+ // Partial snapshot — only the explicitly included relations
897
+ for (const relName of Object.keys(includedRelations)) {
898
+ if (relName in metadata.relations) {
899
+ const val = this[relName];
900
+ snap[relName] = Ad4mModel.normalizeValue(Array.isArray(val) ? [...val] : val);
901
+ }
902
+ }
903
+ }
904
+ // else: null or empty object → skip all relations
905
+ this._snapshot = snap;
906
+ }
907
+ /**
908
+ * Returns `true` if any tracked property or relation has changed
909
+ * since the last hydration (or since `takeSnapshot()` was last called).
910
+ *
911
+ * Always returns `true` if no snapshot exists (e.g. a freshly
912
+ * constructed instance that hasn't been fetched yet).
913
+ *
914
+ * @example
915
+ * ```typescript
916
+ * const recipe = await Recipe.create(perspective, { name: "Pasta" });
917
+ * recipe.isDirty(); // false — just hydrated
918
+ * recipe.name = "Risotto";
919
+ * recipe.isDirty(); // true
920
+ * ```
921
+ */
922
+ isDirty() {
923
+ if (!this._snapshot)
924
+ return true;
925
+ return this.changedFields().length > 0;
926
+ }
927
+ /**
928
+ * Returns the names of properties/relations that differ from the
929
+ * snapshot taken at the last hydration.
930
+ *
931
+ * Returns **all** field names if no snapshot exists.
932
+ *
933
+ * @example
934
+ * ```typescript
935
+ * recipe.name = "New Name";
936
+ * recipe.changedFields(); // ["name"]
937
+ * ```
938
+ */
939
+ changedFields() {
940
+ const ctor = this.constructor;
941
+ const metadata = ctor.getModelMetadata();
942
+ if (!this._snapshot) {
943
+ return [
944
+ ...Object.keys(metadata.properties),
945
+ ...Object.keys(metadata.relations),
946
+ ];
947
+ }
948
+ const changed = [];
949
+ const allFields = [
950
+ ...Object.keys(metadata.properties),
951
+ ...Object.keys(metadata.relations),
952
+ ];
953
+ for (const field of allFields) {
954
+ // Skip fields that were not recorded in the snapshot (e.g. relation
955
+ // fields omitted because the originating query had no `include`).
956
+ // Without this guard, a relation populated by hydrateFromLinks with
957
+ // raw string IDs would appear "dirty" against a missing snapshot
958
+ // entry and trigger an unnecessary (and potentially destructive)
959
+ // setRelationValues call during innerUpdate.
960
+ if (!(field in this._snapshot))
961
+ continue;
962
+ const current = Ad4mModel.normalizeValue(this[field]);
963
+ const original = this._snapshot[field];
964
+ if (Array.isArray(current) || Array.isArray(original)) {
965
+ // Order-insensitive comparison (sorted) so reordering alone
966
+ // doesn't mark a relation as dirty.
967
+ const a = Array.isArray(current) ? [...current].sort() : [];
968
+ const b = Array.isArray(original) ? [...original].sort() : [];
969
+ if (a.length !== b.length || a.some((v, i) => v !== b[i])) {
970
+ changed.push(field);
971
+ }
972
+ }
973
+ else if (current !== original) {
974
+ changed.push(field);
975
+ }
976
+ }
977
+ return changed;
978
+ }
979
+ async getData(opts) {
980
+ // Builds an object with the author, timestamp, all properties, & all relations on the Ad4mModel and saves it to the instance
615
981
  // Use SurrealDB for data queries
616
982
  try {
617
983
  const ctor = this.constructor;
618
984
  const metadata = ctor.getModelMetadata();
619
985
  // Query for all links from this specific node (base expression)
620
- // Using formatSurrealValue to prevent SQL injection by properly escaping the value
621
- const safeBaseExpression = ctor.formatSurrealValue(__classPrivateFieldGet(this, _Ad4mModel_baseExpression, "f"));
622
- // Note: We use ORDER BY timestamp ASC because:
623
- // - For collections: we want chronological order (oldest to newest)
624
- // - For properties: we select the LAST element to get "latest wins" semantics
986
+ const safeBaseExpression = ctor.formatSurrealValue(this._baseExpression);
625
987
  const linksQuery = `
626
988
  SELECT id, predicate, out.uri AS target, author, timestamp
627
989
  FROM link
628
990
  WHERE in.uri = ${safeBaseExpression}
629
991
  ORDER BY timestamp ASC
630
992
  `;
631
- const links = await __classPrivateFieldGet(this, _Ad4mModel_perspective, "f").querySurrealDB(linksQuery);
993
+ const links = await this._perspective.querySurrealDB(linksQuery);
632
994
  if (links && links.length > 0) {
633
- let minTimestamp = null;
634
- let maxTimestamp = null;
635
- let latestAuthor = null;
636
- let originalAuthor = null;
637
- // Process properties (skip those with custom getter)
638
- for (const [propName, propMeta] of Object.entries(metadata.properties)) {
639
- if (propMeta.getter)
640
- continue; // Handle via custom getter evaluation
641
- const matching = links.filter((l) => l.predicate === propMeta.predicate);
642
- if (matching.length > 0) {
643
- // "Latest wins" semantics: select the last element since links are ordered ASC.
644
- // The last element has the most recent timestamp and represents the current property value.
645
- const link = matching[matching.length - 1];
646
- let value = link.target;
647
- // Track timestamps/authors for createdAt and updatedAt
648
- if (link.timestamp) {
649
- if (!minTimestamp || link.timestamp < minTimestamp) {
650
- minTimestamp = link.timestamp;
651
- originalAuthor = link.author;
652
- }
653
- if (!maxTimestamp || link.timestamp > maxTimestamp) {
654
- maxTimestamp = link.timestamp;
655
- latestAuthor = link.author;
656
- }
657
- }
658
- // Handle resolveLanguage
659
- if (propMeta.resolveLanguage && propMeta.resolveLanguage !== 'literal') {
660
- try {
661
- const expression = await __classPrivateFieldGet(this, _Ad4mModel_perspective, "f").getExpression(value);
662
- if (expression) {
663
- try {
664
- value = JSON.parse(expression.data);
665
- }
666
- catch {
667
- value = expression.data;
668
- }
669
- }
670
- }
671
- catch (e) {
672
- console.warn(`Failed to resolve expression for ${propName}:`, e);
673
- }
674
- }
675
- else if (propMeta.resolveLanguage === 'literal' && typeof value === 'string' && value.startsWith('literal://')) {
676
- // Only parse literal URIs when resolveLanguage is explicitly 'literal'.
677
- // Without this guard, properties pointing to baseExpressions of other models
678
- // (which may be literal:// strings) would get unwrapped, breaking link URI validation.
679
- try {
680
- const parsed = Literal.fromUrl(value).get();
681
- value = parsed.data !== undefined ? parsed.data : parsed;
682
- }
683
- catch (e) {
684
- // Keep original value
685
- }
686
- }
687
- // Apply transform if exists
688
- if (propMeta.transform && typeof propMeta.transform === 'function') {
689
- value = propMeta.transform(value);
690
- }
691
- this[propName] = value;
692
- }
693
- }
694
- // Process collections (skip those with custom getter)
695
- for (const [collName, collMeta] of Object.entries(metadata.collections)) {
696
- if (collMeta.getter)
697
- continue; // Handle via custom getter evaluation
698
- const matching = links.filter((l) => l.predicate === collMeta.predicate);
699
- // Collections preserve chronological order: links are sorted ASC by timestamp,
700
- // so the collection reflects the order in which items were added (oldest to newest).
701
- let values = matching.map((l) => l.target);
702
- // Apply where.condition filtering if present
703
- if (collMeta.where?.condition && values.length > 0) {
704
- try {
705
- // Filter values by evaluating condition for each value
706
- const filteredValues = [];
707
- for (const value of values) {
708
- let condition = collMeta.where.condition
709
- .replace(/\$perspective/g, `'${__classPrivateFieldGet(this, _Ad4mModel_perspective, "f").uuid}'`)
710
- .replace(/\$base/g, `'${__classPrivateFieldGet(this, _Ad4mModel_baseExpression, "f")}'`)
711
- .replace(/Target/g, `'${value.replace(/'/g, "\\'")}'`);
712
- // If condition starts with WHERE, wrap it in array length check pattern
713
- // Using array::len() to properly count matching links
714
- if (condition.trim().startsWith('WHERE')) {
715
- condition = `array::len(SELECT * FROM link ${condition}) > 0`;
716
- }
717
- const filterQuery = `RETURN ${condition}`;
718
- const result = await __classPrivateFieldGet(this, _Ad4mModel_perspective, "f").querySurrealDB(filterQuery);
719
- // RETURN can return the value directly or in an array
720
- const isTrue = result === true || (Array.isArray(result) && result.length > 0 && result[0] === true);
721
- if (isTrue) {
722
- filteredValues.push(value);
723
- }
724
- }
725
- values = filteredValues;
726
- }
727
- catch (error) {
728
- console.warn(`Failed to apply condition filter for ${collName}:`, error);
729
- // Keep unfiltered values on error
730
- }
731
- }
732
- // Apply where.isInstance filtering if present
733
- if (collMeta.where?.isInstance && values.length > 0) {
734
- try {
735
- const className = typeof collMeta.where.isInstance === 'string'
736
- ? collMeta.where.isInstance
737
- : collMeta.where.isInstance.name;
738
- const filterMetadata = await __classPrivateFieldGet(this, _Ad4mModel_perspective, "f").getSubjectClassMetadataFromSDNA(className);
739
- if (filterMetadata) {
740
- values = await __classPrivateFieldGet(this, _Ad4mModel_perspective, "f").batchCheckSubjectInstances(values, filterMetadata);
741
- }
742
- }
743
- catch (error) {
744
- // Keep unfiltered values on error
745
- }
746
- }
747
- this[collName] = values;
748
- }
749
- // Set author and timestamps
750
- if (originalAuthor) {
751
- this.author = originalAuthor;
752
- }
753
- if (minTimestamp) {
754
- this.createdAt = minTimestamp;
995
+ // Core hydration: properties (latest-wins), relations, timestamps/author
996
+ const requestedProperties = opts?.properties && opts.properties.length > 0 ? opts.properties : undefined;
997
+ await ctor.hydrateFromLinks(this, links, metadata, this._perspective, requestedProperties);
998
+ }
999
+ // Populate reverse relation fields (belongsToOne / belongsToMany) as string IDs.
1000
+ const allRelsMeta = getRelationsMetadata(ctor);
1001
+ const requestedProps = opts?.properties && opts.properties.length > 0 ? new Set(opts.properties) : null;
1002
+ for (const [relName, relMeta] of Object.entries(allRelsMeta)) {
1003
+ if (relMeta.kind !== 'belongsToOne' && relMeta.kind !== 'belongsToMany')
1004
+ continue;
1005
+ if (requestedProps && !requestedProps.has(relName))
1006
+ continue;
1007
+ const reverseLinks = await this._perspective.get(new LinkQuery({ predicate: relMeta.predicate, target: this._baseExpression }));
1008
+ const sourceIds = reverseLinks
1009
+ .filter((l) => l.data.target === this._baseExpression)
1010
+ .map((l) => l.data.source);
1011
+ if (relMeta.kind === 'belongsToOne') {
1012
+ this[relName] = sourceIds.length > 0 ? sourceIds[sourceIds.length - 1] : null;
755
1013
  }
756
- if (maxTimestamp) {
757
- this.updatedAt = maxTimestamp;
1014
+ else {
1015
+ this[relName] = sourceIds;
758
1016
  }
759
1017
  }
760
1018
  // Evaluate SurrealQL getters
761
- await ctor.evaluateCustomGettersForInstance(this, __classPrivateFieldGet(this, _Ad4mModel_perspective, "f"), metadata);
762
- // Apply where.isInstance filtering to getter collections
763
- // (non-getter collections were already filtered above)
764
- for (const [collName, collMeta] of Object.entries(metadata.collections)) {
765
- if (collMeta.getter && collMeta.where?.isInstance && this[collName]?.length > 0) {
766
- try {
767
- const className = typeof collMeta.where.isInstance === 'string'
768
- ? collMeta.where.isInstance
769
- : collMeta.where.isInstance.name;
770
- const filterMetadata = await __classPrivateFieldGet(this, _Ad4mModel_perspective, "f").getSubjectClassMetadataFromSDNA(className);
771
- if (filterMetadata) {
772
- const filtered = await __classPrivateFieldGet(this, _Ad4mModel_perspective, "f").batchCheckSubjectInstances(this[collName], filterMetadata);
773
- this[collName] = filtered;
774
- }
775
- }
776
- catch (error) {
777
- // Keep unfiltered values on error
778
- }
779
- }
1019
+ await ctor.evaluateCustomGettersForInstance(this, this._perspective, metadata);
1020
+ // Eager-load relations if requested
1021
+ if (opts?.include) {
1022
+ await ctor.hydrateRelations([this], this._perspective, opts.include);
780
1023
  }
781
1024
  }
782
1025
  catch (e) {
783
- console.error(`SurrealDB getData also failed for ${__classPrivateFieldGet(this, _Ad4mModel_baseExpression, "f")}:`, e);
1026
+ console.error(`SurrealDB getData also failed for ${this._baseExpression}:`, e);
784
1027
  }
1028
+ this.takeSnapshot();
785
1029
  return this;
786
1030
  }
787
1031
  // Todo: Only return AllInstances (InstancesWithOffset, SortedInstances, & UnsortedInstances not required)
788
1032
  static async queryToProlog(perspective, query, modelClassName) {
789
- const { source, properties, collections, where, order, offset, limit, count } = query;
1033
+ const { properties, where, order, offset, limit, count } = query;
790
1034
  const className = modelClassName || (await this.getClassName(perspective));
1035
+ // Resolve parent predicate from model metadata if needed
1036
+ const resolvedParentPredicate = query.parent
1037
+ ? resolveParentPredicate(query.parent, this)
1038
+ : undefined;
791
1039
  const instanceQueries = [
792
1040
  buildAuthorAndTimestampQuery(),
793
- buildSourceQuery(source),
1041
+ buildParentQuery(query.parent, resolvedParentPredicate),
794
1042
  buildPropertiesQuery(properties),
795
- buildCollectionsQuery(collections),
796
1043
  buildWhereQuery(where),
797
1044
  ];
798
1045
  const resultSetQueries = [buildCountQuery(count), buildOrderQuery(order), buildOffsetQuery(offset), buildLimitQuery(limit)];
@@ -807,11 +1054,11 @@ export class Ad4mModel {
807
1054
  return fullQuery;
808
1055
  }
809
1056
  /**
810
- * Evaluates custom SurrealQL getters for properties and collections on a specific instance.
1057
+ * Evaluates custom SurrealQL getters for properties and relations on a specific instance.
811
1058
  * @private
812
1059
  */
813
1060
  static async evaluateCustomGettersForInstance(instance, perspective, metadata) {
814
- const safeBaseExpression = this.formatSurrealValue(instance.baseExpression);
1061
+ const safeBaseExpression = this.formatSurrealValue(instance.id);
815
1062
  // Evaluate property getters
816
1063
  for (const [propName, propMeta] of Object.entries(metadata.properties)) {
817
1064
  if (propMeta.getter) {
@@ -829,28 +1076,258 @@ export class Ad4mModel {
829
1076
  }
830
1077
  }
831
1078
  }
832
- // Evaluate collection getters
833
- for (const [collName, collMeta] of Object.entries(metadata.collections)) {
834
- if (collMeta.getter) {
1079
+ // Evaluate relation getters
1080
+ for (const [relName, relMeta] of Object.entries(metadata.relations)) {
1081
+ if (relMeta.getter) {
835
1082
  try {
836
1083
  // Replace 'Base' placeholder with actual base expression
837
- const query = collMeta.getter.replace(/Base/g, safeBaseExpression);
1084
+ const query = relMeta.getter.replace(/Base/g, safeBaseExpression);
838
1085
  // Query from node table to have graph traversal context
839
1086
  const result = await perspective.querySurrealDB(`SELECT (${query}) AS value FROM node WHERE uri = ${safeBaseExpression}`);
840
1087
  if (result && result.length > 0 && result[0].value !== undefined && result[0].value !== null) {
841
- // Filter out 'None' from collection results
1088
+ // Filter out 'None' from relation results
842
1089
  const value = result[0].value;
843
- instance[collName] = Array.isArray(value)
1090
+ instance[relName] = Array.isArray(value)
844
1091
  ? value.filter((v) => v !== undefined && v !== null && v !== '' && v !== 'None')
845
1092
  : value;
846
1093
  }
847
1094
  }
848
1095
  catch (error) {
849
- console.warn(`Failed to evaluate getter for ${collName}:`, error);
1096
+ console.warn(`Failed to evaluate getter for ${relName}:`, error);
850
1097
  }
851
1098
  }
852
1099
  }
853
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
+ }
854
1331
  /**
855
1332
  * Generates a SurrealQL query from a Query object.
856
1333
  *
@@ -862,18 +1339,18 @@ export class Ad4mModel {
862
1339
  *
863
1340
  * The generated query uses a CTE (Common Table Expression) pattern:
864
1341
  * 1. First, identify candidate base expressions by filtering links based on where conditions
865
- * 2. Then, for each candidate base, resolve properties and collections via subqueries
1342
+ * 2. Then, for each candidate base, resolve properties and relations via subqueries
866
1343
  * 3. Finally, apply ordering, pagination (LIMIT/START) at the SQL level
867
1344
  *
868
1345
  * Key architectural notes:
869
1346
  * - SurrealDB stores only raw links (source, predicate, target, author, timestamp)
870
1347
  * - No SDNA knowledge at the database level
871
1348
  * - Properties are resolved via subqueries that look for links with specific predicates
872
- * - Collections are similar but return multiple values instead of one
1349
+ * - Relations are similar but return multiple values instead of one
873
1350
  * - Special fields (base, author, timestamp) are accessed directly, not via subqueries
874
1351
  *
875
1352
  * @param perspective - The perspective to query (used for metadata extraction)
876
- * @param query - Query parameters (where, order, limit, offset, properties, collections)
1353
+ * @param query - Query parameters (where, order, limit, offset, properties, relations)
877
1354
  * @returns Complete SurrealQL query string ready for execution
878
1355
  *
879
1356
  * @example
@@ -889,43 +1366,68 @@ export class Ad4mModel {
889
1366
  */
890
1367
  static async queryToSurrealQL(perspective, query) {
891
1368
  const metadata = this.getModelMetadata();
892
- const { source, where, order, offset, limit } = query;
1369
+ const { where, order, offset, limit } = query;
893
1370
  // Build list of graph traversal filters for required predicates
894
1371
  const graphTraversalFilters = [];
895
- // Add source filter if specified (filter to nodes that are children of this source)
896
- // Source filter means: find targets of 'ad4m://has_child' links from the specified source
897
- if (source) {
898
- // Use graph traversal: node must be target of has_child link from source
899
- graphTraversalFilters.push(`count(<-link[WHERE perspective = $perspective AND in.uri = ${this.formatSurrealValue(source)} AND predicate = 'ad4m://has_child']) > 0`);
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`);
900
1376
  }
901
1377
  // Add filters for required properties
902
1378
  for (const [propName, propMeta] of Object.entries(metadata.properties)) {
903
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;
904
1385
  // For flag properties, also filter by the target value
905
1386
  if (propMeta.flag && propMeta.initial) {
906
- graphTraversalFilters.push(`count(->link[WHERE perspective = $perspective AND predicate = '${escapeSurrealString(propMeta.predicate)}' AND out.uri = '${escapeSurrealString(propMeta.initial)}']) > 0`);
1387
+ graphTraversalFilters.push(`count(->link[WHERE predicate = '${escapeSurrealString(propMeta.predicate)}' AND out.uri = '${escapeSurrealString(propMeta.initial)}']) > 0`);
907
1388
  }
908
1389
  else {
909
- graphTraversalFilters.push(`count(->link[WHERE perspective = $perspective AND predicate = '${escapeSurrealString(propMeta.predicate)}']) > 0`);
1390
+ graphTraversalFilters.push(`count(->link[WHERE predicate = '${escapeSurrealString(propMeta.predicate)}']) > 0`);
910
1391
  }
911
1392
  }
912
1393
  }
913
- // If no required properties, we need at least one property to define the model
914
- // Use any property with an initial value as the defining characteristic
1394
+ // If no required properties produced filters, try properties with initial
1395
+ // values (e.g. @Flag or @Property with an explicit initial).
915
1396
  if (graphTraversalFilters.length === 0) {
916
1397
  for (const [propName, propMeta] of Object.entries(metadata.properties)) {
917
1398
  if (propMeta.initial) {
918
- // For flag properties, also filter by the target value
919
1399
  if (propMeta.flag) {
920
- graphTraversalFilters.push(`count(->link[WHERE perspective = $perspective AND predicate = '${escapeSurrealString(propMeta.predicate)}' AND out.uri = '${escapeSurrealString(propMeta.initial)}']) > 0`);
1400
+ graphTraversalFilters.push(`count(->link[WHERE predicate = '${escapeSurrealString(propMeta.predicate)}' AND out.uri = '${escapeSurrealString(propMeta.initial)}']) > 0`);
921
1401
  }
922
1402
  else {
923
- graphTraversalFilters.push(`count(->link[WHERE perspective = $perspective AND predicate = '${escapeSurrealString(propMeta.predicate)}']) > 0`);
1403
+ graphTraversalFilters.push(`count(->link[WHERE predicate = '${escapeSurrealString(propMeta.predicate)}']) > 0`);
924
1404
  }
925
- break; // Just need one defining property
1405
+ break;
926
1406
  }
927
1407
  }
928
1408
  }
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
+ }
1430
+ }
929
1431
  // Build user WHERE clause filters using graph traversal
930
1432
  const userWhereClause = this.buildGraphTraversalWhereClause(metadata, where);
931
1433
  // Build complete WHERE clause using graph traversal filters
@@ -936,17 +1438,20 @@ export class Ad4mModel {
936
1438
  if (userWhereClause) {
937
1439
  whereConditions.push(userWhereClause);
938
1440
  }
939
- // Always ensure node has at least one link in this perspective
940
- whereConditions.push(`count(->link[WHERE perspective = $perspective]) > 0`);
1441
+ // Always ensure node has at least one link (each perspective has its own isolated DB)
1442
+ whereConditions.push(`count(->link) > 0`);
941
1443
  // Build the query FROM node using direct graph traversal in WHERE
942
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")
943
1447
  const fullQuery = `
944
1448
  SELECT
945
1449
  id AS source,
946
1450
  uri AS source_uri,
947
- ->link[WHERE perspective = $perspective] AS links
1451
+ ->link AS links
948
1452
  FROM node
949
1453
  WHERE ${whereConditions.join(' AND ')}
1454
+ FETCH links
950
1455
  `.trim();
951
1456
  return fullQuery;
952
1457
  }
@@ -975,16 +1480,16 @@ WHERE ${whereConditions.join(' AND ')}
975
1480
  return '';
976
1481
  const conditions = [];
977
1482
  for (const [propertyName, condition] of Object.entries(where)) {
978
- // Check if this is a special field (base, author, timestamp)
1483
+ // Check if this is a special field (id, author, timestamp)
979
1484
  // Note: author and timestamp filtering is done in JavaScript after query
980
- const isSpecial = ['base', 'author', 'timestamp'].includes(propertyName);
1485
+ const isSpecial = ['id', 'author', 'timestamp'].includes(propertyName);
981
1486
  if (isSpecial) {
982
1487
  // Skip author and timestamp - they'll be filtered in JavaScript
983
- // Only handle 'base' (which maps to 'uri') here
1488
+ // Only handle 'id' (which maps to 'uri') here
984
1489
  if (propertyName === 'author' || propertyName === 'timestamp') {
985
1490
  continue; // Skip - will be filtered post-query
986
1491
  }
987
- const columnName = 'uri'; // base maps to uri in node table
1492
+ const columnName = 'uri'; // id maps to uri in node table
988
1493
  // Handle base/uri field directly
989
1494
  if (Array.isArray(condition)) {
990
1495
  // Array values (IN clause)
@@ -1028,7 +1533,58 @@ WHERE ${whereConditions.join(' AND ')}
1028
1533
  }
1029
1534
  }
1030
1535
  else {
1031
- // Handle regular properties via graph traversal
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
+ }
1032
1588
  const propMeta = metadata.properties[propertyName];
1033
1589
  if (!propMeta)
1034
1590
  continue; // Skip if property not found in metadata
@@ -1038,7 +1594,7 @@ WHERE ${whereConditions.join(' AND ')}
1038
1594
  if (Array.isArray(condition)) {
1039
1595
  // Array values (IN clause)
1040
1596
  const formattedValues = condition.map(v => this.formatSurrealValue(v)).join(', ');
1041
- conditions.push(`count(->link[WHERE perspective = $perspective AND predicate = '${predicate}' AND ${targetField} IN [${formattedValues}]]) > 0`);
1597
+ conditions.push(`count(->link[WHERE predicate = '${predicate}' AND ${targetField} IN [${formattedValues}]]) > 0`);
1042
1598
  }
1043
1599
  else if (typeof condition === 'object' && condition !== null) {
1044
1600
  // Operator object
@@ -1047,11 +1603,11 @@ WHERE ${whereConditions.join(' AND ')}
1047
1603
  if (Array.isArray(ops.not)) {
1048
1604
  // For NOT IN with array: must NOT have a link with value in the array
1049
1605
  const formattedValues = ops.not.map(v => this.formatSurrealValue(v)).join(', ');
1050
- conditions.push(`count(->link[WHERE perspective = $perspective AND predicate = '${predicate}' AND ${targetField} IN [${formattedValues}]]) = 0`);
1606
+ conditions.push(`count(->link[WHERE predicate = '${predicate}' AND ${targetField} IN [${formattedValues}]]) = 0`);
1051
1607
  }
1052
1608
  else {
1053
1609
  // For NOT with single value: must NOT have this value
1054
- conditions.push(`count(->link[WHERE perspective = $perspective AND predicate = '${predicate}' AND ${targetField} = ${this.formatSurrealValue(ops.not)}]) = 0`);
1610
+ conditions.push(`count(->link[WHERE predicate = '${predicate}' AND ${targetField} = ${this.formatSurrealValue(ops.not)}]) = 0`);
1055
1611
  }
1056
1612
  }
1057
1613
  // Note: gt, gte, lt, lte, between, contains operators are filtered in JavaScript
@@ -1064,12 +1620,12 @@ WHERE ${whereConditions.join(' AND ')}
1064
1620
  ops.between !== undefined || ops.contains !== undefined;
1065
1621
  if (hasComparisonOps) {
1066
1622
  // Ensure we only get nodes that have this property
1067
- conditions.push(`count(->link[WHERE perspective = $perspective AND predicate = '${predicate}']) > 0`);
1623
+ conditions.push(`count(->link[WHERE predicate = '${predicate}']) > 0`);
1068
1624
  }
1069
1625
  }
1070
1626
  else {
1071
1627
  // Simple equality
1072
- conditions.push(`count(->link[WHERE perspective = $perspective AND predicate = '${predicate}' AND ${targetField} = ${this.formatSurrealValue(condition)}]) > 0`);
1628
+ conditions.push(`count(->link[WHERE predicate = '${predicate}' AND ${targetField} = ${this.formatSurrealValue(condition)}]) > 0`);
1073
1629
  }
1074
1630
  }
1075
1631
  }
@@ -1106,17 +1662,17 @@ WHERE ${whereConditions.join(' AND ')}
1106
1662
  return '';
1107
1663
  const conditions = [];
1108
1664
  for (const [propertyName, condition] of Object.entries(where)) {
1109
- // Check if this is a special field (base, author, timestamp)
1665
+ // Check if this is a special field (id, author, timestamp)
1110
1666
  // Note: author and timestamp filtering is done in JavaScript after GROUP BY
1111
1667
  // because they need to be computed from the grouped links first
1112
- const isSpecial = ['base', 'author', 'timestamp'].includes(propertyName);
1668
+ const isSpecial = ['id', 'author', 'timestamp'].includes(propertyName);
1113
1669
  if (isSpecial) {
1114
1670
  // Skip author and timestamp - they'll be filtered in JavaScript
1115
- // Only handle 'base' (which maps to 'source') here
1671
+ // Only handle 'id' (which maps to 'source') here
1116
1672
  if (propertyName === 'author' || propertyName === 'timestamp') {
1117
1673
  continue; // Skip - will be filtered post-query
1118
1674
  }
1119
- const columnName = 'source'; // base maps to source
1675
+ const columnName = 'source'; // id maps to source
1120
1676
  // Handle base/source field directly
1121
1677
  if (Array.isArray(condition)) {
1122
1678
  // Array values (IN clause)
@@ -1211,26 +1767,26 @@ WHERE ${whereConditions.join(' AND ')}
1211
1767
  * Builds the SELECT fields for SurrealQL queries.
1212
1768
  *
1213
1769
  * @description
1214
- * Generates the field list for the SELECT clause, resolving properties and collections
1770
+ * Generates the field list for the SELECT clause, resolving properties and relations
1215
1771
  * via subqueries. Each property is fetched with a subquery that finds the link with the
1216
- * appropriate predicate and returns its target. Collections are similar but don't use LIMIT 1.
1772
+ * appropriate predicate and returns its target. Relations are similar but don't use LIMIT 1.
1217
1773
  *
1218
1774
  * Field types:
1219
1775
  * - Properties: `(SELECT VALUE target FROM link WHERE source = $parent.base AND predicate = 'X' LIMIT 1) AS propName`
1220
- * - Collections: `(SELECT VALUE target FROM link WHERE source = $parent.base AND predicate = 'X') AS collName`
1776
+ * - Relations: `(SELECT VALUE target FROM link WHERE source = $parent.base AND predicate = 'X') AS relName`
1221
1777
  * - Author/Timestamp: Always included to provide metadata about each instance
1222
1778
  *
1223
- * If properties or collections arrays are provided, only those fields are included.
1224
- * Otherwise, all properties/collections from metadata are included.
1779
+ * If properties or relations arrays are provided, only those fields are included.
1780
+ * Otherwise, all properties/relations from metadata are included.
1225
1781
  *
1226
- * @param metadata - Model metadata containing property and collection predicates
1782
+ * @param metadata - Model metadata containing property and relation predicates
1227
1783
  * @param properties - Optional array of property names to include (default: all)
1228
- * @param collections - Optional array of collection names to include (default: all)
1784
+ * @param relations - Optional array of relation names to include (default: all)
1229
1785
  * @returns Comma-separated SELECT field list
1230
1786
  *
1231
1787
  * @private
1232
1788
  */
1233
- static buildSurrealSelectFields(metadata, properties, collections) {
1789
+ static buildSurrealSelectFields(metadata, properties, relations) {
1234
1790
  const fields = [];
1235
1791
  // Determine properties to fetch
1236
1792
  const propsToFetch = properties || Object.keys(metadata.properties);
@@ -1242,15 +1798,15 @@ WHERE ${whereConditions.join(' AND ')}
1242
1798
  const escapedPredicate = escapeSurrealString(propMeta.predicate);
1243
1799
  fields.push(`(SELECT VALUE target FROM link WHERE source = source AND predicate = '${escapedPredicate}' LIMIT 1) AS ${propName}`);
1244
1800
  }
1245
- // Determine collections to fetch
1246
- const collsToFetch = collections || Object.keys(metadata.collections);
1247
- for (const collName of collsToFetch) {
1248
- const collMeta = metadata.collections[collName];
1249
- if (!collMeta)
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)
1250
1806
  continue; // Skip if not found
1251
1807
  // Reference source directly since we're selecting from link table
1252
- const escapedPredicate = escapeSurrealString(collMeta.predicate);
1253
- fields.push(`(SELECT VALUE target FROM link WHERE source = source AND predicate = '${escapedPredicate}') AS ${collName}`);
1808
+ const escapedPredicate = escapeSurrealString(relMeta.predicate);
1809
+ fields.push(`(SELECT VALUE target FROM link WHERE source = source AND predicate = '${escapedPredicate}') AS ${relName}`);
1254
1810
  }
1255
1811
  // Always add author and timestamp fields
1256
1812
  fields.push(`(SELECT VALUE author FROM link WHERE source = source ORDER BY timestamp ASC LIMIT 1) AS author`);
@@ -1264,7 +1820,7 @@ WHERE ${whereConditions.join(' AND ')}
1264
1820
  *
1265
1821
  * @private
1266
1822
  */
1267
- static buildSurrealSelectFieldsWithAggregation(metadata, properties, collections) {
1823
+ static buildSurrealSelectFieldsWithAggregation(metadata, properties, relations) {
1268
1824
  const fields = [];
1269
1825
  // Determine properties to fetch
1270
1826
  const propsToFetch = properties || Object.keys(metadata.properties);
@@ -1276,15 +1832,15 @@ WHERE ${whereConditions.join(' AND ')}
1276
1832
  const escapedPredicate = escapeSurrealString(propMeta.predicate);
1277
1833
  fields.push(`array::first(target[WHERE predicate = '${escapedPredicate}']) AS ${propName}`);
1278
1834
  }
1279
- // Determine collections to fetch
1280
- const collsToFetch = collections || Object.keys(metadata.collections);
1281
- for (const collName of collsToFetch) {
1282
- const collMeta = metadata.collections[collName];
1283
- if (!collMeta)
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)
1284
1840
  continue; // Skip if not found
1285
1841
  // Use array filtering to get all target values for this predicate
1286
- const escapedPredicate = escapeSurrealString(collMeta.predicate);
1287
- fields.push(`target[WHERE predicate = '${escapedPredicate}'] AS ${collName}`);
1842
+ const escapedPredicate = escapeSurrealString(relMeta.predicate);
1843
+ fields.push(`target[WHERE predicate = '${escapedPredicate}'] AS ${relName}`);
1288
1844
  }
1289
1845
  // Always add author and timestamp fields
1290
1846
  fields.push(`array::first(author) AS author`);
@@ -1332,14 +1888,14 @@ WHERE ${whereConditions.join(' AND ')}
1332
1888
  if (!result?.[0]?.AllInstances)
1333
1889
  return { results: [], totalCount: 0 };
1334
1890
  // Map results to instances
1335
- const requestedAttribtes = [...(query?.properties || []), ...(query?.collections || [])];
1891
+ const requestedProperties = query?.properties || [];
1336
1892
  const allInstances = await Promise.all(result[0].AllInstances.map(async ([Base, Properties, Collections, Timestamp, Author]) => {
1337
1893
  try {
1338
1894
  const instance = new this(perspective, Base);
1339
1895
  // Remove unrequested attributes from instance
1340
- if (requestedAttribtes.length) {
1896
+ if (requestedProperties.length) {
1341
1897
  Object.keys(instance).forEach((key) => {
1342
- if (!requestedAttribtes.includes(key))
1898
+ if (!requestedProperties.includes(key) && key !== 'createdAt' && key !== 'updatedAt' && key !== 'author' && key !== 'id' && key !== 'baseExpression')
1343
1899
  delete instance[key];
1344
1900
  });
1345
1901
  }
@@ -1354,7 +1910,21 @@ WHERE ${whereConditions.join(' AND ')}
1354
1910
  return null;
1355
1911
  }
1356
1912
  }));
1357
- return { results: allInstances.filter((instance) => instance !== null), totalCount: result[0].TotalCount };
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 };
1358
1928
  }
1359
1929
  /**
1360
1930
  * Converts SurrealDB query results to Ad4mModel instances.
@@ -1371,7 +1941,6 @@ WHERE ${whereConditions.join(' AND ')}
1371
1941
  return { results: [], totalCount: 0 };
1372
1942
  const metadata = this.getModelMetadata();
1373
1943
  const requestedProperties = query?.properties || [];
1374
- const requestedCollections = query?.collections || [];
1375
1944
  // The query used GROUP BY with graph traversal, so each row has:
1376
1945
  // - source: the node ID (e.g., "node:abc123")
1377
1946
  // - source_uri: the actual URI (the base expression)
@@ -1388,248 +1957,61 @@ WHERE ${whereConditions.join(' AND ')}
1388
1957
  }
1389
1958
  const links = row.links || [];
1390
1959
  const instance = new this(perspective, base);
1391
- // Track both earliest (createdAt) and most recent (updatedAt) timestamps
1392
- let minTimestamp = null;
1393
- let maxTimestamp = null;
1394
- let originalAuthor = null;
1395
- let latestAuthor = null;
1396
- // Process each link (track index for collection ordering)
1397
- for (let linkIndex = 0; linkIndex < links.length; linkIndex++) {
1398
- const link = links[linkIndex];
1399
- const predicate = link.predicate;
1400
- const target = link.target;
1401
- // Skip 'None' values
1402
- if (target === 'None')
1403
- continue;
1404
- // Track both earliest (createdAt) and latest (updatedAt) timestamps with their authors
1405
- if (link.timestamp) {
1406
- if (!minTimestamp || link.timestamp < minTimestamp) {
1407
- minTimestamp = link.timestamp;
1408
- originalAuthor = link.author;
1409
- }
1410
- if (!maxTimestamp || link.timestamp > maxTimestamp) {
1411
- maxTimestamp = link.timestamp;
1412
- latestAuthor = link.author;
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];
1413
1969
  }
1414
1970
  }
1415
- // Find matching property (skip those with getter)
1416
- let foundProperty = false;
1417
- for (const [propName, propMeta] of Object.entries(metadata.properties)) {
1418
- if (propMeta.getter)
1419
- continue; // Handle via getter evaluation
1420
- if (propMeta.predicate === predicate) {
1421
- // For properties, take the first value (or we could use timestamp to get latest)
1422
- // Note: Empty objects {} are truthy, so we need to check for them explicitly
1423
- const currentValue = instance[propName];
1424
- const isEmptyObject = typeof currentValue === 'object' && currentValue !== null && !Array.isArray(currentValue) && Object.keys(currentValue).length === 0;
1425
- if (!currentValue || currentValue === "" || currentValue === 0 || isEmptyObject) {
1426
- let convertedValue = target;
1427
- // Only process if target has a value
1428
- if (target !== undefined && target !== null && target !== '') {
1429
- // Check if we need to resolve a non-literal language expression.
1430
- // resolveLanguage must be defined and not 'literal' to trigger expression resolution.
1431
- // Also skip if the target itself is a literal:// URI — those are handled by the
1432
- // literal-parsing branch below (avoids calling getExpression on empty literals like
1433
- // "literal://string:" which would cause a deserialization error).
1434
- if (propMeta.resolveLanguage != undefined && propMeta.resolveLanguage !== 'literal' && typeof target === 'string' && !target.startsWith('literal://')) {
1435
- // For non-literal languages, resolve the expression via perspective.getExpression()
1436
- // Note: Literals are already parsed by SurrealDB's fn::parse_literal()
1437
- try {
1438
- const expression = await perspective.getExpression(target);
1439
- if (expression) {
1440
- // Parse the expression data if it's a JSON string
1441
- try {
1442
- convertedValue = JSON.parse(expression.data);
1443
- }
1444
- catch {
1445
- // If parsing fails, use the data as-is
1446
- convertedValue = expression.data;
1447
- }
1448
- }
1449
- }
1450
- catch (e) {
1451
- console.warn(`Failed to resolve expression for ${propName} with target "${target}":`, e);
1452
- console.warn("Falling back to raw value");
1453
- convertedValue = target; // Fall back to raw value
1454
- }
1455
- }
1456
- else if (propMeta.resolveLanguage === 'literal' && typeof target === 'string' && target.startsWith('literal://')) {
1457
- // Only parse literal URIs when resolveLanguage is explicitly set to 'literal'.
1458
- // Without this check, properties pointing to baseExpressions of other models
1459
- // (which may be literal:// strings) would get unwrapped, breaking link URI validation.
1460
- try {
1461
- const parsed = Literal.fromUrl(target).get();
1462
- if (parsed.data !== undefined) {
1463
- convertedValue = parsed.data;
1464
- }
1465
- else {
1466
- convertedValue = parsed;
1467
- }
1468
- }
1469
- catch (e) {
1470
- // If literal parsing fails, just use the value as-is (don't bail)
1471
- convertedValue = target;
1472
- }
1473
- }
1474
- else if (typeof target === 'string') {
1475
- // Type conversion: check the instance property's current type
1476
- const expectedType = typeof instance[propName];
1477
- if (expectedType === 'number') {
1478
- convertedValue = Number(target);
1479
- }
1480
- else if (expectedType === 'boolean') {
1481
- convertedValue = target === 'true' || target === '1';
1482
- }
1483
- }
1484
- }
1485
- // Apply transform function if it exists
1486
- if (propMeta.transform && typeof propMeta.transform === 'function') {
1487
- convertedValue = propMeta.transform(convertedValue);
1488
- }
1489
- instance[propName] = convertedValue;
1490
- }
1491
- foundProperty = true;
1492
- break;
1971
+ for (const relName of Object.keys(metadata.relations)) {
1972
+ if (!requested.has(relName) && !(query.include && relName in query.include)) {
1973
+ delete instance[relName];
1493
1974
  }
1494
1975
  }
1495
- // If not a property, check if it's a collection (skip those with getter)
1496
- if (!foundProperty) {
1497
- for (const [collName, collMeta] of Object.entries(metadata.collections)) {
1498
- if (collMeta.getter)
1499
- continue; // Handle via getter evaluation
1500
- if (collMeta.predicate === predicate) {
1501
- // For collections, accumulate all values with their timestamps and indices for sorting
1502
- if (!instance[collName]) {
1503
- instance[collName] = [];
1504
- }
1505
- // Initialize timestamp tracking array if not already done
1506
- const timestampsKey = `__${collName}_timestamps`;
1507
- const indicesKey = `__${collName}_indices`;
1508
- if (!instance[timestampsKey]) {
1509
- instance[timestampsKey] = [];
1510
- }
1511
- if (!instance[indicesKey]) {
1512
- instance[indicesKey] = [];
1513
- }
1514
- if (!instance[collName].includes(target)) {
1515
- instance[collName].push(target);
1516
- instance[timestampsKey].push(link.timestamp || '');
1517
- // Track original position in the links array for stable sorting
1518
- instance[indicesKey].push(linkIndex);
1519
- }
1520
- break;
1521
- }
1976
+ // Also strip metadata fields unless explicitly requested
1977
+ for (const metaField of ['author', 'createdAt', 'updatedAt']) {
1978
+ if (!requested.has(metaField)) {
1979
+ delete instance[metaField];
1522
1980
  }
1523
1981
  }
1524
1982
  }
1525
- // Set author and timestamps
1526
- if (originalAuthor) {
1527
- instance.author = originalAuthor;
1528
- }
1529
- // Set createdAt from earliest timestamp
1530
- if (minTimestamp) {
1531
- if (typeof minTimestamp === 'string' && minTimestamp.includes('T')) {
1532
- instance.createdAt = new Date(minTimestamp).getTime();
1533
- }
1534
- else if (typeof minTimestamp === 'string') {
1535
- const parsed = parseInt(minTimestamp, 10);
1536
- instance.createdAt = isNaN(parsed) ? minTimestamp : parsed;
1537
- }
1538
- else {
1539
- instance.createdAt = minTimestamp;
1540
- }
1541
- }
1542
- // Set updatedAt from most recent timestamp
1543
- if (maxTimestamp) {
1544
- if (typeof maxTimestamp === 'string' && maxTimestamp.includes('T')) {
1545
- instance.updatedAt = new Date(maxTimestamp).getTime();
1546
- }
1547
- else if (typeof maxTimestamp === 'string') {
1548
- const parsed = parseInt(maxTimestamp, 10);
1549
- instance.updatedAt = isNaN(parsed) ? maxTimestamp : parsed;
1550
- }
1551
- else {
1552
- instance.updatedAt = maxTimestamp;
1553
- }
1554
- }
1555
- // Sort collections by timestamp to maintain insertion order
1556
- for (const [collName, collMeta] of Object.entries(metadata.collections)) {
1557
- const timestampsKey = `__${collName}_timestamps`;
1558
- const indicesKey = `__${collName}_indices`;
1559
- if (instance[collName] && instance[timestampsKey]) {
1560
- // Create array of [value, timestamp, index] tuples
1561
- const pairs = instance[collName].map((value, index) => ({
1562
- value,
1563
- timestamp: instance[timestampsKey][index] || '',
1564
- originalIndex: instance[indicesKey]?.[index] ?? index
1565
- }));
1566
- // Sort by timestamp first, then by original index for stable sorting
1567
- pairs.sort((a, b) => {
1568
- const tsA = String(a.timestamp || '');
1569
- const tsB = String(b.timestamp || '');
1570
- const tsCompare = tsA.localeCompare(tsB);
1571
- if (tsCompare !== 0)
1572
- return tsCompare;
1573
- // Use original index as tiebreaker for stable sorting
1574
- return a.originalIndex - b.originalIndex;
1575
- });
1576
- // Replace collection with sorted values, filtering out empty strings and None
1577
- instance[collName] = pairs
1578
- .map(p => p.value)
1579
- .filter((v) => v !== undefined && v !== null && v !== '' && v !== 'None');
1580
- // Clean up temporary arrays
1581
- delete instance[timestampsKey];
1582
- delete instance[indicesKey];
1583
- }
1584
- }
1585
- // Filter by requested attributes if specified
1586
- if (requestedProperties.length > 0 || requestedCollections.length > 0) {
1587
- const requestedAttributes = [...requestedProperties, ...requestedCollections];
1588
- Object.keys(instance).forEach((key) => {
1589
- // Keep only requested attributes, plus always keep createdAt, updatedAt, author, and baseExpression
1590
- // Note: timestamp is a getter alias for createdAt, so we preserve createdAt instead
1591
- if (!requestedAttributes.includes(key) && key !== 'createdAt' && key !== 'updatedAt' && key !== 'author' && key !== 'baseExpression') {
1592
- delete instance[key];
1593
- }
1594
- });
1595
- }
1596
1983
  instances.push(instance);
1597
1984
  }
1598
1985
  catch (error) {
1599
1986
  console.error(`Failed to process SurrealDB instance ${base}:`, error);
1600
1987
  }
1601
1988
  }
1602
- // Evaluate custom getters for all instances (single pass)
1603
- // This populates collection values needed for where.isInstance filtering
1604
- for (const instance of instances) {
1605
- await this.evaluateCustomGettersForInstance(instance, perspective, metadata);
1606
- }
1607
- // Filter collections by where.isInstance if specified
1608
- // Do this after initial evaluation so collection values exist for filtering
1609
- for (const instance of instances) {
1610
- for (const [collName, collMeta] of Object.entries(metadata.collections)) {
1611
- if (collMeta.where?.isInstance && instance[collName]?.length > 0) {
1612
- try {
1613
- const targetClass = collMeta.where.isInstance;
1614
- const subjects = instance[collName];
1615
- // Get the class metadata from SDNA to pass to batchCheckSubjectInstances
1616
- const targetClassName = typeof targetClass === 'string'
1617
- ? targetClass
1618
- : targetClass.prototype?.className || targetClass.name;
1619
- const classMetadata = await perspective.getSubjectClassMetadataFromSDNA(targetClassName);
1620
- if (!classMetadata) {
1621
- continue;
1622
- }
1623
- // Check which subjects are instances of the target class
1624
- const validSubjects = await perspective.batchCheckSubjectInstances(subjects, classMetadata);
1625
- // Update the collection with filtered instances
1626
- instance[collName] = validSubjects;
1989
+ // Populate reverse relation fields (belongsToOne / belongsToMany) as string IDs.
1990
+ // These relations point FROM other nodes TO this instance, so they cannot be resolved
1991
+ // from the node's own outgoing links fetched above. We do a reverse-link lookup here
1992
+ // so that these fields are populated as IDs even without an explicit include.
1993
+ const allRelsMeta = getRelationsMetadata(this);
1994
+ const reverseRelEntries = Object.entries(allRelsMeta).filter(([relName, meta]) => (meta.kind === 'belongsToOne' || meta.kind === 'belongsToMany') &&
1995
+ (requestedProperties.length === 0 || requestedProperties.includes(relName)));
1996
+ if (reverseRelEntries.length > 0 && instances.length > 0) {
1997
+ await Promise.all(instances.map(async (inst) => {
1998
+ for (const [relName, relMeta] of reverseRelEntries) {
1999
+ const reverseLinks = await perspective.get(new LinkQuery({ predicate: relMeta.predicate, target: inst.id }));
2000
+ const sourceIds = reverseLinks
2001
+ .filter((l) => l.data.target === inst.id)
2002
+ .map((l) => l.data.source);
2003
+ if (relMeta.kind === 'belongsToOne') {
2004
+ inst[relName] = sourceIds.length > 0 ? sourceIds[sourceIds.length - 1] : null;
1627
2005
  }
1628
- catch (error) {
1629
- // On error, leave the collection unfiltered rather than breaking everything
2006
+ else {
2007
+ inst[relName] = sourceIds;
1630
2008
  }
1631
2009
  }
1632
- }
2010
+ }));
2011
+ }
2012
+ // Evaluate custom getters for all instances (single pass)
2013
+ for (const instance of instances) {
2014
+ await this.evaluateCustomGettersForInstance(instance, perspective, metadata);
1633
2015
  }
1634
2016
  // Filter by where conditions that couldn't be filtered in SQL
1635
2017
  // This includes:
@@ -1674,31 +2056,35 @@ WHERE ${whereConditions.join(' AND ')}
1674
2056
  const effectiveOrder = query.order ||
1675
2057
  (query.limit !== undefined || query.offset !== undefined ? { timestamp: 'ASC' } : null);
1676
2058
  if (effectiveOrder) {
1677
- const orderPropName = Object.keys(effectiveOrder)[0];
1678
- const orderDirection = Object.values(effectiveOrder)[0];
2059
+ const orderEntries = Object.entries(effectiveOrder);
1679
2060
  filteredInstances.sort((a, b) => {
1680
- let aVal = a[orderPropName];
1681
- let bVal = b[orderPropName];
1682
- // Handle undefined values - push them to the end
1683
- if (aVal === undefined && bVal === undefined)
1684
- return 0;
1685
- if (aVal === undefined)
1686
- return orderDirection === 'ASC' ? 1 : -1;
1687
- if (bVal === undefined)
1688
- return orderDirection === 'ASC' ? -1 : 1;
1689
- // Compare values
1690
- let comparison = 0;
1691
- if (typeof aVal === 'number' && typeof bVal === 'number') {
1692
- comparison = aVal - bVal;
1693
- }
1694
- else if (typeof aVal === 'string' && typeof bVal === 'string') {
1695
- comparison = aVal.localeCompare(bVal);
1696
- }
1697
- else {
1698
- // Convert to strings for comparison
1699
- comparison = String(aVal).localeCompare(String(bVal));
2061
+ for (const [orderPropName, orderDirection] of orderEntries) {
2062
+ let aVal = a[orderPropName];
2063
+ let bVal = b[orderPropName];
2064
+ // Handle undefined values - push them to the end
2065
+ if (aVal === undefined && bVal === undefined)
2066
+ continue;
2067
+ if (aVal === undefined)
2068
+ return orderDirection === 'ASC' ? 1 : -1;
2069
+ if (bVal === undefined)
2070
+ return orderDirection === 'ASC' ? -1 : 1;
2071
+ // Compare values
2072
+ let comparison = 0;
2073
+ if (typeof aVal === 'number' && typeof bVal === 'number') {
2074
+ comparison = aVal - bVal;
2075
+ }
2076
+ else if (typeof aVal === 'string' && typeof bVal === 'string') {
2077
+ comparison = aVal.localeCompare(bVal);
2078
+ }
2079
+ else {
2080
+ comparison = String(aVal).localeCompare(String(bVal));
2081
+ }
2082
+ if (comparison !== 0) {
2083
+ return orderDirection === 'DESC' ? -comparison : comparison;
2084
+ }
2085
+ // comparison === 0: continue to next sort field
1700
2086
  }
1701
- return orderDirection === 'DESC' ? -comparison : comparison;
2087
+ return 0;
1702
2088
  });
1703
2089
  }
1704
2090
  // Calculate totalCount BEFORE applying limit/offset
@@ -1710,6 +2096,20 @@ WHERE ${whereConditions.join(' AND ')}
1710
2096
  const end = query.limit ? start + query.limit : undefined;
1711
2097
  paginatedInstances = filteredInstances.slice(start, end);
1712
2098
  }
2099
+ // Eager-load relations if requested (BEFORE snapshot so dirty tracking is accurate)
2100
+ if (query.include && paginatedInstances.length > 0) {
2101
+ await this.hydrateRelations(paginatedInstances, perspective, query.include);
2102
+ }
2103
+ // Take snapshots for dirty tracking after ALL hydration is complete
2104
+ // (including eager-loaded relations).
2105
+ // When `include` is specified, only snapshot those relations.
2106
+ // Otherwise snapshot ALL fields (properties + relations) since
2107
+ // hydrateFromLinks populates relations with stable raw IDs —
2108
+ // this ensures push-to-array + save() correctly detects dirty relations.
2109
+ const snapshotRelations = query.include;
2110
+ for (const inst of paginatedInstances) {
2111
+ inst.takeSnapshot(snapshotRelations);
2112
+ }
1713
2113
  return {
1714
2114
  results: paginatedInstances,
1715
2115
  totalCount
@@ -1799,6 +2199,9 @@ WHERE ${whereConditions.join(' AND ')}
1799
2199
  * ```
1800
2200
  */
1801
2201
  static async findAll(perspective, query = {}, useSurrealDB = true) {
2202
+ if (query.properties && query.properties.length === 0) {
2203
+ throw new Error("properties[] must not be empty — omit the field to return all properties, or specify at least one field name");
2204
+ }
1802
2205
  if (useSurrealDB) {
1803
2206
  const surrealQuery = await this.queryToSurrealQL(perspective, query);
1804
2207
  const result = await perspective.querySurrealDB(surrealQuery);
@@ -1812,6 +2215,31 @@ WHERE ${whereConditions.join(' AND ')}
1812
2215
  return results;
1813
2216
  }
1814
2217
  }
2218
+ /**
2219
+ * Finds the first instance matching the query, or `null` if none exists.
2220
+ *
2221
+ * Equivalent to `findAll` with `limit: 1` — only one instance is hydrated.
2222
+ *
2223
+ * @param perspective - The perspective to search in
2224
+ * @param query - Optional query parameters to filter results
2225
+ * @param useSurrealDB - Whether to use SurrealDB (default: true) or Prolog (legacy)
2226
+ * @returns The first matching instance, or `null`
2227
+ *
2228
+ * @example
2229
+ * ```typescript
2230
+ * const recipe = await Recipe.findOne(perspective, {
2231
+ * where: { name: "Pasta" }
2232
+ * });
2233
+ * if (recipe) {
2234
+ * console.log(recipe.name);
2235
+ * }
2236
+ * ```
2237
+ */
2238
+ static async findOne(perspective, query = {}, useSurrealDB = true) {
2239
+ const limitedQuery = { ...query, limit: 1 };
2240
+ const results = await this.findAll(perspective, limitedQuery, useSurrealDB);
2241
+ return results[0] ?? null;
2242
+ }
1815
2243
  /**
1816
2244
  * Gets all instances with count of total matches without offset & limit applied.
1817
2245
  *
@@ -1881,9 +2309,12 @@ WHERE ${whereConditions.join(' AND ')}
1881
2309
  }
1882
2310
  }
1883
2311
  static async countQueryToProlog(perspective, query = {}, modelClassName) {
1884
- const { source, where } = query;
2312
+ const { where } = query;
1885
2313
  const className = modelClassName || (await this.getClassName(perspective));
1886
- const instanceQueries = [buildAuthorAndTimestampQuery(), buildSourceQuery(source), buildWhereQuery(where)];
2314
+ const resolvedParentPredicate = query.parent
2315
+ ? resolveParentPredicate(query.parent, this)
2316
+ : undefined;
2317
+ const instanceQueries = [buildAuthorAndTimestampQuery(), buildParentQuery(query.parent, resolvedParentPredicate), buildWhereQuery(where)];
1887
2318
  const resultSetQueries = [buildCountQuery(true), buildOrderQuery(), buildOffsetQuery(), buildLimitQuery()];
1888
2319
  const fullQuery = `
1889
2320
  findall([Base, Properties, Collections, Timestamp, Author], (
@@ -1962,119 +2393,172 @@ WHERE ${whereConditions.join(' AND ')}
1962
2393
  return;
1963
2394
  }
1964
2395
  if (resolveLanguage) {
1965
- value = await __classPrivateFieldGet(this, _Ad4mModel_perspective, "f").createExpression(value, resolveLanguage);
2396
+ value = await this._perspective.createExpression(value, resolveLanguage);
1966
2397
  }
1967
- await __classPrivateFieldGet(this, _Ad4mModel_perspective, "f").executeAction(actions, __classPrivateFieldGet(this, _Ad4mModel_baseExpression, "f"), [{ name: "value", value }], batchId);
2398
+ await this._perspective.executeAction(actions, this._baseExpression, [{ name: "value", value }], batchId);
2399
+ }
2400
+ /** Resolve a relation argument to a plain string ID. Accepts either a raw
2401
+ * string ID or an Ad4mModel instance (in which case `.id` is used). */
2402
+ resolveRelationId(value) {
2403
+ if (typeof value === 'string')
2404
+ return value;
2405
+ if (value && typeof value === 'object' && typeof value.id === 'string')
2406
+ return value.id;
2407
+ return String(value);
1968
2408
  }
1969
- async setCollectionSetter(key, value, batchId) {
2409
+ async setRelationValues(key, value, batchId) {
1970
2410
  // Phase 1: Use metadata instead of Prolog queries
1971
- const metadata = this.getCollectionMetadata(key);
2411
+ const metadata = this.getRelationOptions(key);
1972
2412
  if (!metadata) {
1973
- console.warn(`Collection "${key}" has no metadata, skipping`);
2413
+ console.warn(`Relation "${key}" has no metadata, skipping`);
1974
2414
  return;
1975
2415
  }
1976
2416
  // Generate actions from metadata (replaces Prolog query)
1977
- const actions = this.generateCollectionAction(key, 'setter');
2417
+ const actions = this.generateRelationAction(key, 'setter');
1978
2418
  if (value != null) {
1979
2419
  if (Array.isArray(value)) {
1980
- await __classPrivateFieldGet(this, _Ad4mModel_perspective, "f").executeAction(actions, __classPrivateFieldGet(this, _Ad4mModel_baseExpression, "f"), value.map((v) => ({ name: "value", value: v })), batchId);
2420
+ await this._perspective.executeAction(actions, this._baseExpression, value.map((v) => ({ name: "value", value: this.resolveRelationId(v) })), batchId);
1981
2421
  }
1982
2422
  else {
1983
- await __classPrivateFieldGet(this, _Ad4mModel_perspective, "f").executeAction(actions, __classPrivateFieldGet(this, _Ad4mModel_baseExpression, "f"), [{ name: "value", value }], batchId);
2423
+ await this._perspective.executeAction(actions, this._baseExpression, [{ name: "value", value: this.resolveRelationId(value) }], batchId);
1984
2424
  }
1985
2425
  }
1986
2426
  }
1987
- async setCollectionAdder(key, value, batchId) {
2427
+ async addRelationValue(key, value, batchId) {
1988
2428
  // Phase 1: Use metadata instead of Prolog queries
1989
- const metadata = this.getCollectionMetadata(key);
2429
+ const metadata = this.getRelationOptions(key);
1990
2430
  if (!metadata) {
1991
- console.warn(`Collection "${key}" has no metadata, skipping`);
2431
+ console.warn(`Relation "${key}" has no metadata, skipping`);
1992
2432
  return;
1993
2433
  }
1994
2434
  // Generate actions from metadata (replaces Prolog query)
1995
- const actions = this.generateCollectionAction(key, 'adder');
2435
+ const actions = this.generateRelationAction(key, 'adder');
1996
2436
  if (value != null) {
1997
2437
  if (Array.isArray(value)) {
1998
- await Promise.all(value.map((v) => __classPrivateFieldGet(this, _Ad4mModel_perspective, "f").executeAction(actions, __classPrivateFieldGet(this, _Ad4mModel_baseExpression, "f"), [{ name: "value", value: v }], batchId)));
2438
+ await Promise.all(value.map((v) => this._perspective.executeAction(actions, this._baseExpression, [{ name: "value", value: this.resolveRelationId(v) }], batchId)));
1999
2439
  }
2000
2440
  else {
2001
- await __classPrivateFieldGet(this, _Ad4mModel_perspective, "f").executeAction(actions, __classPrivateFieldGet(this, _Ad4mModel_baseExpression, "f"), [{ name: "value", value }], batchId);
2441
+ await this._perspective.executeAction(actions, this._baseExpression, [{ name: "value", value: this.resolveRelationId(value) }], batchId);
2002
2442
  }
2003
2443
  }
2004
2444
  }
2005
- async setCollectionRemover(key, value, batchId) {
2445
+ async removeRelationValue(key, value, batchId) {
2006
2446
  // Phase 1: Use metadata instead of Prolog queries
2007
- const metadata = this.getCollectionMetadata(key);
2447
+ const metadata = this.getRelationOptions(key);
2008
2448
  if (!metadata) {
2009
- console.warn(`Collection "${key}" has no metadata, skipping`);
2449
+ console.warn(`Relation "${key}" has no metadata, skipping`);
2010
2450
  return;
2011
2451
  }
2012
2452
  // Generate actions from metadata (replaces Prolog query)
2013
- const actions = this.generateCollectionAction(key, 'remover');
2453
+ const actions = this.generateRelationAction(key, 'remover');
2014
2454
  if (value != null) {
2015
2455
  if (Array.isArray(value)) {
2016
- await Promise.all(value.map((v) => __classPrivateFieldGet(this, _Ad4mModel_perspective, "f").executeAction(actions, __classPrivateFieldGet(this, _Ad4mModel_baseExpression, "f"), [{ name: "value", value: v }], batchId)));
2456
+ await Promise.all(value.map((v) => this._perspective.executeAction(actions, this._baseExpression, [{ name: "value", value: this.resolveRelationId(v) }], batchId)));
2017
2457
  }
2018
2458
  else {
2019
- await __classPrivateFieldGet(this, _Ad4mModel_perspective, "f").executeAction(actions, __classPrivateFieldGet(this, _Ad4mModel_baseExpression, "f"), [{ name: "value", value }], batchId);
2459
+ await this._perspective.executeAction(actions, this._baseExpression, [{ name: "value", value: this.resolveRelationId(value) }], batchId);
2020
2460
  }
2021
2461
  }
2022
2462
  }
2023
2463
  /**
2024
2464
  * Saves the model instance to the perspective.
2025
- * Creates a new instance with the base expression and links it to the source.
2465
+ *
2466
+ * **New instances** (no snapshot yet): creates the subject via
2467
+ * `createSubject` with initial scalar values, then sets relations
2468
+ * via `innerUpdate`.
2469
+ *
2470
+ * **Existing instances** (snapshot present, i.e. fetched via `get()`
2471
+ * or a query): updates only dirty fields via `innerUpdate`, then
2472
+ * refreshes from the perspective.
2026
2473
  *
2027
2474
  * @param batchId - Optional batch ID for batch operations
2028
2475
  * @throws Will throw if instance creation, linking, or updating fails
2029
2476
  *
2030
2477
  * @example
2031
2478
  * ```typescript
2479
+ * // Create
2032
2480
  * const recipe = new Recipe(perspective);
2033
2481
  * recipe.name = "Spaghetti";
2034
- * recipe.ingredients = ["pasta", "tomato sauce"];
2035
2482
  * await recipe.save();
2036
2483
  *
2037
- * // Or with batch operations:
2038
- * const batchId = await perspective.createBatch();
2039
- * await recipe.save(batchId);
2040
- * await perspective.commitBatch(batchId);
2484
+ * // Update
2485
+ * recipe.rating = 10;
2486
+ * await recipe.save();
2041
2487
  * ```
2042
2488
  */
2043
2489
  async save(batchId) {
2044
- // We use createSubject's initialValues to set properties (but not collections)
2045
- // We then later use innerUpdate to set collections
2490
+ // Existing instance → update path (has been fetched / hydrated before)
2491
+ if (this._snapshot) {
2492
+ await this.innerUpdate(true, batchId);
2493
+ if (batchId) {
2494
+ // Batch hasn't been committed yet — getData() would fetch stale data
2495
+ // and overwrite in-memory values. Just refresh the snapshot so further
2496
+ // saves within the same batch diff correctly.
2497
+ this.takeSnapshot();
2498
+ }
2499
+ else {
2500
+ await this.getData();
2501
+ }
2502
+ return;
2503
+ }
2504
+ // New instance → create path
2046
2505
  let batchCreatedHere = false;
2047
2506
  if (!batchId) {
2048
2507
  batchId = await this.perspective.createBatch();
2049
2508
  batchCreatedHere = true;
2050
2509
  }
2051
- // First filter out the properties that are not collections (arrays)
2052
- const initialValues = {};
2053
- for (const [key, value] of Object.entries(this)) {
2054
- if (value !== undefined && value !== null && !(Array.isArray(value) && value.length > 0) && !value?.action) {
2055
- initialValues[key] = value;
2056
- }
2057
- }
2058
- // Get the class name instead of passing the instance to avoid Prolog query generation
2059
- const className = await this.perspective.stringOrTemplateObjectToSubjectClassName(this);
2060
- // Create the subject with the initial values
2061
- await this.perspective.createSubject(className, __classPrivateFieldGet(this, _Ad4mModel_baseExpression, "f"), initialValues, batchId);
2062
- // Link the subject to the source
2063
- await __classPrivateFieldGet(this, _Ad4mModel_perspective, "f").add(new Link({ source: __classPrivateFieldGet(this, _Ad4mModel_source, "f"), predicate: "ad4m://has_child", target: this.baseExpression }), 'shared', batchId);
2064
- // Set collections
2065
- await this.innerUpdate(false, batchId);
2510
+ // Check if the model has any constructor actions (required properties,
2511
+ // flags, or properties with initial values). Models whose properties are
2512
+ // all optional, have no @Flag, and have no initial values produce an empty
2513
+ // SHACL constructor, so calling createSubject would fail on the Rust side
2514
+ // ("No SHACL constructor found"). In that case we skip createSubject
2515
+ // entirely and let innerUpdate write the links directly.
2516
+ const metadata = this.constructor.getModelMetadata();
2517
+ const hasConstructor = Object.values(metadata.properties).some((p) => p.required || p.flag || p.initial !== undefined);
2518
+ if (hasConstructor) {
2519
+ // First filter out the properties that are not relations (arrays)
2520
+ const initialValues = {};
2521
+ for (const [key, value] of Object.entries(this)) {
2522
+ if (value !== undefined && value !== null && !(Array.isArray(value) && value.length > 0) && !value?.action) {
2523
+ initialValues[key] = value;
2524
+ }
2525
+ }
2526
+ // Get the class name instead of passing the instance to avoid Prolog query generation
2527
+ const className = await this.perspective.stringOrTemplateObjectToSubjectClassName(this);
2528
+ // Create the subject with the initial values
2529
+ await this.perspective.createSubject(className, this._baseExpression, initialValues, batchId);
2530
+ }
2531
+ // Set properties and relations via innerUpdate.
2532
+ // When createSubject was skipped (no constructor actions), we must enable
2533
+ // property writing so that scalar values are persisted as links.
2534
+ await this.innerUpdate(!hasConstructor, batchId);
2066
2535
  // If we got a batchId passed in, we let the caller decide when to commit.
2067
- // But then we can call getData() since the instance won't exist in the perspective
2068
- // until the bacht is committedl
2536
+ // We can't call getData() since the instance won't exist in the perspective
2537
+ // until the batch is committed.
2069
2538
  if (batchCreatedHere) {
2070
2539
  await this.perspective.commitBatch(batchId);
2071
2540
  await this.getData();
2072
2541
  }
2542
+ else {
2543
+ // Take a snapshot so that a subsequent save() within the same batch
2544
+ // routes through the UPDATE path instead of CREATE, avoiding duplicate
2545
+ // links (e.g. two competing "title" values).
2546
+ this.takeSnapshot();
2547
+ }
2073
2548
  }
2074
2549
  cleanCopy() {
2550
+ const ctor = this.constructor;
2551
+ const metadata = ctor.getModelMetadata();
2075
2552
  const cleanCopy = {};
2076
- const props = Object.entries(this);
2077
- for (const [key, value] of props) {
2553
+ // Only include schema-declared fields (properties + relations),
2554
+ // preserving internal ORM machinery (_id, _perspective, generated
2555
+ // addX/removeX/setX methods, _snapshot, etc.)
2556
+ const schemaFields = new Set([
2557
+ ...Object.keys(metadata.properties),
2558
+ ...Object.keys(metadata.relations),
2559
+ ]);
2560
+ for (const key of schemaFields) {
2561
+ const value = this[key];
2078
2562
  if (value !== undefined && value !== null && key !== "author" && key !== "timestamp") {
2079
2563
  cleanCopy[key] = value;
2080
2564
  }
@@ -2082,36 +2566,56 @@ WHERE ${whereConditions.join(' AND ')}
2082
2566
  return cleanCopy;
2083
2567
  }
2084
2568
  async innerUpdate(setProperties = true, batchId) {
2085
- __classPrivateFieldSet(this, _Ad4mModel_subjectClassName, await __classPrivateFieldGet(this, _Ad4mModel_perspective, "f").stringOrTemplateObjectToSubjectClassName(this.cleanCopy()), "f");
2569
+ const ctor = this.constructor;
2570
+ this._subjectClassName = await this._perspective.stringOrTemplateObjectToSubjectClassName(this.cleanCopy());
2571
+ // Determine which fields actually changed (skip unchanged when snapshot exists)
2572
+ const dirty = this._snapshot ? new Set(this.changedFields()) : null;
2573
+ // Only iterate schema-declared fields, not internal ORM properties
2574
+ const metadata = ctor.getModelMetadata();
2575
+ const schemaFields = new Set([
2576
+ ...Object.keys(metadata.properties),
2577
+ ...Object.keys(metadata.relations),
2578
+ ]);
2086
2579
  const entries = Object.entries(this);
2087
2580
  for (const [key, value] of entries) {
2581
+ // Only process schema-declared fields
2582
+ if (!schemaFields.has(key))
2583
+ continue;
2584
+ // Skip unchanged fields when a snapshot is available
2585
+ if (dirty && !dirty.has(key))
2586
+ continue;
2088
2587
  if (value !== undefined && value !== null) {
2089
2588
  if (value?.action) {
2090
2589
  switch (value.action) {
2091
2590
  case "setter":
2092
- await this.setCollectionSetter(key, value.value, batchId);
2591
+ await this.setRelationValues(key, value.value, batchId);
2093
2592
  break;
2094
2593
  case "adder":
2095
- await this.setCollectionAdder(key, value.value, batchId);
2594
+ await this.addRelationValue(key, value.value, batchId);
2096
2595
  break;
2097
2596
  case "remover":
2098
- await this.setCollectionRemover(key, value.value, batchId);
2597
+ await this.removeRelationValue(key, value.value, batchId);
2099
2598
  break;
2100
2599
  default:
2101
- await this.setCollectionSetter(key, value.value, batchId);
2600
+ await this.setRelationValues(key, value.value, batchId);
2102
2601
  break;
2103
2602
  }
2104
2603
  }
2105
2604
  else if (Array.isArray(value)) {
2106
- // Handle all arrays as collections, including empty ones (which clears the collection)
2107
- await this.setCollectionSetter(key, value, batchId);
2605
+ // Handle all arrays as relations, including empty ones (which clears the relation)
2606
+ await this.setRelationValues(key, value, batchId);
2108
2607
  }
2109
2608
  else if (value !== undefined && value !== null && value !== "") {
2110
2609
  if (setProperties) {
2111
- // Check if this is a collection property (has collection metadata)
2112
- const collMetadata = this.getCollectionMetadata(key);
2113
- if (collMetadata) {
2114
- // Skip - it's a collection, not a regular property
2610
+ // Check if this is a relation property (has relation metadata)
2611
+ const relationMeta = this.getRelationOptions(key);
2612
+ if (relationMeta) {
2613
+ // Skip - it's a relation, not a regular property
2614
+ continue;
2615
+ }
2616
+ // Skip flag properties — they are immutable after creation
2617
+ const propMeta = this.getPropertyMetadata(key);
2618
+ if (propMeta?.flag) {
2115
2619
  continue;
2116
2620
  }
2117
2621
  await this.setProperty(key, value, batchId);
@@ -2121,31 +2625,11 @@ WHERE ${whereConditions.join(' AND ')}
2121
2625
  }
2122
2626
  }
2123
2627
  /**
2124
- * Updates the model instance's properties and collections.
2125
- *
2126
- * @param batchId - Optional batch ID for batch operations
2127
- * @throws Will throw if property setting or collection updates fail
2128
- *
2129
- * @example
2130
- * ```typescript
2131
- * const recipe = await Recipe.findAll(perspective)[0];
2132
- * recipe.rating = 5;
2133
- * recipe.ingredients.push("garlic");
2134
- * await recipe.update();
2135
- *
2136
- * // Or with batch operations:
2137
- * const batchId = await perspective.createBatch();
2138
- * await recipe.update(batchId);
2139
- * await perspective.commitBatch(batchId);
2140
- * ```
2141
- */
2142
- async update(batchId) {
2143
- await this.innerUpdate(true, batchId);
2144
- await this.getData();
2145
- }
2146
- /**
2147
- * Gets the model instance with all properties and collections populated.
2628
+ * Gets the model instance with all properties and relations populated.
2148
2629
  *
2630
+ * @param optsOrInclude - Optional hydration options. Accepts two forms:
2631
+ * - `GetOptions` wrapper: `{ include: { comments: true }, properties: ['title'] }`
2632
+ * - `IncludeMap` shorthand: `{ comments: true }` (equivalent to `{ include: { comments: true } }`)
2149
2633
  * @returns The populated model instance
2150
2634
  * @throws Will throw if data retrieval fails
2151
2635
  *
@@ -2154,11 +2638,29 @@ WHERE ${whereConditions.join(' AND ')}
2154
2638
  * const recipe = new Recipe(perspective, existingId);
2155
2639
  * await recipe.get();
2156
2640
  * console.log(recipe.name, recipe.ingredients);
2641
+ *
2642
+ * // Shorthand — pass IncludeMap directly:
2643
+ * await recipe.get({ ingredients: true });
2644
+ *
2645
+ * // Full options — includes sparse fieldset:
2646
+ * await recipe.get({ include: { ingredients: true }, properties: ['name'] });
2157
2647
  * ```
2158
2648
  */
2159
- async get() {
2160
- __classPrivateFieldSet(this, _Ad4mModel_subjectClassName, await __classPrivateFieldGet(this, _Ad4mModel_perspective, "f").stringOrTemplateObjectToSubjectClassName(this.cleanCopy()), "f");
2161
- return await this.getData();
2649
+ async get(optsOrInclude) {
2650
+ // Normalise: if the caller passed a plain IncludeMap shorthand (no `include`
2651
+ // or `properties` key at the top level) wrap it in GetOptions automatically.
2652
+ let opts;
2653
+ if (!optsOrInclude) {
2654
+ opts = undefined;
2655
+ }
2656
+ else if ('include' in optsOrInclude || 'properties' in optsOrInclude) {
2657
+ opts = optsOrInclude;
2658
+ }
2659
+ else {
2660
+ opts = { include: optsOrInclude };
2661
+ }
2662
+ this._subjectClassName = await this._perspective.stringOrTemplateObjectToSubjectClassName(this.cleanCopy());
2663
+ return await this.getData(opts);
2162
2664
  }
2163
2665
  /**
2164
2666
  * Deletes the model instance from the perspective.
@@ -2178,7 +2680,218 @@ WHERE ${whereConditions.join(' AND ')}
2178
2680
  * ```
2179
2681
  */
2180
2682
  async delete(batchId) {
2181
- await __classPrivateFieldGet(this, _Ad4mModel_perspective, "f").removeSubject(this, __classPrivateFieldGet(this, _Ad4mModel_baseExpression, "f"), batchId);
2683
+ // Check if the model has a destructor (required properties, flags, or
2684
+ // properties with initial values). Models whose properties are all
2685
+ // optional, have no @Flag, and have no initial values produce an empty
2686
+ // SHACL destructor, so calling removeSubject would fail. In that case
2687
+ // we skip the destructor and just remove all outgoing links directly.
2688
+ const metadata = this.constructor.getModelMetadata();
2689
+ const hasDestructor = Object.values(metadata.properties).some((p) => p.required || p.flag || p.initial !== undefined);
2690
+ if (hasDestructor) {
2691
+ // Remove the subject itself (destructor actions)
2692
+ await this._perspective.removeSubject(this, this._baseExpression, batchId);
2693
+ }
2694
+ else {
2695
+ // No destructor — manually remove all outgoing links from this node
2696
+ try {
2697
+ const outgoingLinks = await this._perspective.get(new LinkQuery({ source: this._baseExpression }));
2698
+ if (outgoingLinks.length > 0) {
2699
+ await this._perspective.removeLinks(outgoingLinks, batchId);
2700
+ }
2701
+ }
2702
+ catch (e) {
2703
+ console.warn(`delete(): failed to remove outgoing links for ${this._baseExpression}:`, e);
2704
+ }
2705
+ }
2706
+ // Clean up incoming links — remove any links that point **to** this instance
2707
+ try {
2708
+ const incomingLinks = await this._perspective.get(new LinkQuery({ target: this._baseExpression }));
2709
+ if (incomingLinks.length > 0) {
2710
+ await this._perspective.removeLinks(incomingLinks, batchId);
2711
+ }
2712
+ }
2713
+ catch (e) {
2714
+ // Non-fatal: the subject was already deleted; incoming link cleanup is best-effort
2715
+ console.warn(`delete(): failed to clean up incoming links for ${this._baseExpression}:`, e);
2716
+ }
2717
+ }
2718
+ /**
2719
+ * Creates and saves a new model instance in one step.
2720
+ *
2721
+ * @param perspective - The perspective to create the instance in
2722
+ * @param data - Property values to assign before saving
2723
+ * @param options - Optional settings:
2724
+ * - `parent` — a `ParentScope` (model form or raw form) whose `id` will
2725
+ * be used to create an incoming link from the parent to the new instance.
2726
+ * - `batchId` — an existing batch id; when provided the link write and
2727
+ * `save()` are added to the batch instead of committed immediately.
2728
+ * @returns The saved model instance
2729
+ *
2730
+ * @example
2731
+ * ```typescript
2732
+ * // Simple create
2733
+ * const recipe = await Recipe.create(perspective, {
2734
+ * name: "Spaghetti",
2735
+ * rating: 5,
2736
+ * });
2737
+ *
2738
+ * // Create under a parent (link auto-created)
2739
+ * const comment = await Comment.create(perspective, { text: "Great!" }, {
2740
+ * parent: { model: Post, id: postId },
2741
+ * });
2742
+ *
2743
+ * // Create inside a transaction
2744
+ * await Ad4mModel.transaction(perspective, async (tx) => {
2745
+ * await Recipe.create(perspective, { name: "Pasta" }, { batchId: tx.batchId });
2746
+ * });
2747
+ * ```
2748
+ */
2749
+ static async create(perspective, data = {}, options) {
2750
+ const instance = new this(perspective);
2751
+ Object.assign(instance, data);
2752
+ // When a parent scope is provided without a caller-supplied batch, open a
2753
+ // new batch ourselves so that the instance creation and the parent→child
2754
+ // link are committed atomically. If either step throws, commitBatch is
2755
+ // never reached and the batch is implicitly abandoned (rollback).
2756
+ if (options?.parent && !options?.batchId) {
2757
+ const batchId = await perspective.createBatch();
2758
+ await instance.save(batchId);
2759
+ const predicate = resolveParentPredicate(options.parent, this);
2760
+ const link = new Link({
2761
+ source: options.parent.id,
2762
+ predicate,
2763
+ target: instance.id,
2764
+ });
2765
+ await perspective.add(link, 'shared', batchId);
2766
+ await perspective.commitBatch(batchId);
2767
+ // Hydrate the instance now that the batch has been committed (mirrors the
2768
+ // behaviour of save() when it manages its own batch).
2769
+ await instance.get();
2770
+ return instance;
2771
+ }
2772
+ await instance.save(options?.batchId);
2773
+ // Create parent → child link if a parent scope was provided
2774
+ if (options?.parent) {
2775
+ const predicate = resolveParentPredicate(options.parent, this);
2776
+ const link = new Link({
2777
+ source: options.parent.id,
2778
+ predicate,
2779
+ target: instance.id,
2780
+ });
2781
+ await perspective.add(link, 'shared', options?.batchId);
2782
+ }
2783
+ return instance;
2784
+ }
2785
+ /**
2786
+ * Updates an existing model instance identified by `id`.
2787
+ *
2788
+ * Fetches the instance, applies the provided changes, calls `save()`,
2789
+ * and returns the refreshed instance.
2790
+ *
2791
+ * @param perspective - The perspective containing the instance
2792
+ * @param id - The expression URI of the instance to update
2793
+ * @param data - Property values to merge before saving
2794
+ * @returns The updated model instance
2795
+ *
2796
+ * @example
2797
+ * ```typescript
2798
+ * const recipe = await Recipe.update(perspective, recipeId, {
2799
+ * rating: 10,
2800
+ * });
2801
+ * ```
2802
+ */
2803
+ static async update(perspective, id, data) {
2804
+ const instance = new this(perspective, id);
2805
+ await instance.get();
2806
+ Object.assign(instance, data);
2807
+ await instance.save();
2808
+ return instance;
2809
+ }
2810
+ /**
2811
+ * Deletes an existing model instance identified by `id`.
2812
+ *
2813
+ * Also cleans up any incoming links that point to this instance.
2814
+ *
2815
+ * @param perspective - The perspective containing the instance
2816
+ * @param id - The expression URI of the instance to delete
2817
+ *
2818
+ * @example
2819
+ * ```typescript
2820
+ * await Recipe.delete(perspective, recipeId);
2821
+ * ```
2822
+ *
2823
+ * @deprecated Use the name `delete` — `remove` is preserved as an alias.
2824
+ */
2825
+ static async remove(perspective, id) {
2826
+ return this.delete(perspective, id);
2827
+ }
2828
+ /**
2829
+ * Deletes an existing model instance identified by `id`.
2830
+ *
2831
+ * Also cleans up any incoming links that point to this instance.
2832
+ *
2833
+ * @param perspective - The perspective containing the instance
2834
+ * @param id - The expression URI of the instance to delete
2835
+ *
2836
+ * @example
2837
+ * ```typescript
2838
+ * await Recipe.delete(perspective, recipeId);
2839
+ * ```
2840
+ */
2841
+ static async delete(perspective, id) {
2842
+ const instance = new this(perspective, id);
2843
+ await instance.delete();
2844
+ }
2845
+ /**
2846
+ * Registers this model's SHACL schema on the given perspective.
2847
+ *
2848
+ * This ensures the perspective knows about the model's shape
2849
+ * (properties, relations, constraints) so instances can be
2850
+ * created, queried, and validated.
2851
+ *
2852
+ * @param perspective - The perspective to register the model on
2853
+ *
2854
+ * @example
2855
+ * ```typescript
2856
+ * await Recipe.register(perspective);
2857
+ * // Now you can create / query Recipe instances on this perspective
2858
+ * ```
2859
+ */
2860
+ static async register(perspective) {
2861
+ await perspective.ensureSDNASubjectClass(this);
2862
+ }
2863
+ /**
2864
+ * Executes a set of model operations inside a single batch (transaction).
2865
+ *
2866
+ * All `save`, `update`, and `delete` calls made via the provided `batchId`
2867
+ * are buffered and flushed atomically when the callback completes.
2868
+ * If the callback throws, the batch is **not** committed, preventing
2869
+ * partial writes.
2870
+ *
2871
+ * @param perspective - The perspective to operate on
2872
+ * @param fn - Async callback that receives a `TransactionContext` object.
2873
+ * Pass `tx.batchId` to `save(tx.batchId)`, `update(tx.batchId)`,
2874
+ * `delete(tx.batchId)`, etc.
2875
+ * @returns The value returned by `fn`
2876
+ *
2877
+ * @example
2878
+ * ```typescript
2879
+ * await Ad4mModel.transaction(perspective, async (tx) => {
2880
+ * const recipe = new Recipe(perspective);
2881
+ * recipe.name = "Spaghetti";
2882
+ * await recipe.save(tx.batchId);
2883
+ *
2884
+ * const old = await Recipe.query(perspective).where({ name: "Stale" }).run();
2885
+ * for (const r of old) await r.delete(tx.batchId);
2886
+ * });
2887
+ * // All changes committed atomically here
2888
+ * ```
2889
+ */
2890
+ static async transaction(perspective, fn) {
2891
+ const batchId = await perspective.createBatch();
2892
+ const result = await fn({ batchId });
2893
+ await perspective.commitBatch(batchId);
2894
+ return result;
2182
2895
  }
2183
2896
  /**
2184
2897
  * Creates a query builder for fluent query construction.
@@ -2273,9 +2986,9 @@ WHERE ${whereConditions.join(' AND ')}
2273
2986
  }
2274
2987
  DynamicModelClass.className = options.name;
2275
2988
  DynamicModelClass.prototype.className = options.name;
2276
- // Generate properties and collections metadata
2989
+ // Generate properties and relations metadata
2277
2990
  const properties = {};
2278
- const collections = {};
2991
+ const relations = {};
2279
2992
  if (schema.properties) {
2280
2993
  for (const [propertyName, propertySchema] of Object.entries(schema.properties)) {
2281
2994
  const predicate = this.determinePredicate(schema, propertyName, propertySchema, namespace, options);
@@ -2283,9 +2996,9 @@ WHERE ${whereConditions.join(' AND ')}
2283
2996
  const propertyType = normalizeSchemaType(propertySchema.type);
2284
2997
  const isArray = isArrayType(propertySchema);
2285
2998
  if (isArray) {
2286
- // Handle arrays as collections
2287
- // Store the singular form as the collection key since SDNA generation expects singular
2288
- collections[propertyName] = {
2999
+ // Handle arrays as relations
3000
+ // Store the singular form as the relation key since SDNA generation expects singular
3001
+ relations[propertyName] = {
2289
3002
  through: predicate,
2290
3003
  local: this.getPropertyOption(propertyName, propertySchema, options, 'local')
2291
3004
  };
@@ -2295,10 +3008,10 @@ WHERE ${whereConditions.join(' AND ')}
2295
3008
  writable: true,
2296
3009
  value: []
2297
3010
  });
2298
- // Add collection methods
3011
+ // Add relation methods
2299
3012
  const adderName = `add${capitalize(propertyName)}`;
2300
3013
  const removerName = `remove${capitalize(propertyName)}`;
2301
- const setterName = `setCollection${capitalize(propertyName)}`;
3014
+ const setterName = `set${capitalize(propertyName)}`;
2302
3015
  DynamicModelClass.prototype[adderName] = function () {
2303
3016
  // Placeholder function for SDNA generation
2304
3017
  };
@@ -2317,7 +3030,13 @@ WHERE ${whereConditions.join(' AND ')}
2317
3030
  resolveLanguage = options.resolveLanguage;
2318
3031
  }
2319
3032
  const local = this.getPropertyOption(propertyName, propertySchema, options, 'local');
2320
- const writable = this.getPropertyOption(propertyName, propertySchema, options, 'writable', true);
3033
+ // Determine readOnly: check PropertyOptions first, then x-ad4m.writable (inverted) for JSON Schema wire format
3034
+ let readOnly = this.getPropertyOption(propertyName, propertySchema, options, 'readOnly');
3035
+ if (readOnly === undefined) {
3036
+ const xWritable = propertySchema["x-ad4m"]?.writable;
3037
+ readOnly = xWritable !== undefined ? !xWritable : false;
3038
+ }
3039
+ const writable = !readOnly;
2321
3040
  let initial = this.getPropertyOption(propertyName, propertySchema, options, 'initial');
2322
3041
  // Handle nested objects by serializing to JSON
2323
3042
  if (isObjectType(propertySchema) && !resolveLanguage) {
@@ -2328,6 +3047,12 @@ WHERE ${whereConditions.join(' AND ')}
2328
3047
  if ((resolveLanguage === undefined || resolveLanguage === null) && isNumericType(propertySchema)) {
2329
3048
  resolveLanguage = 'literal';
2330
3049
  }
3050
+ // Default resolveLanguage to 'literal' for all remaining property types,
3051
+ // matching the @Property decorator behaviour. Without this, string values
3052
+ // stored as literal:// URLs are returned unparsed.
3053
+ if (resolveLanguage === undefined || resolveLanguage === null) {
3054
+ resolveLanguage = 'literal';
3055
+ }
2331
3056
  // If property is required, ensure it has an initial value
2332
3057
  if (isRequired && !initial) {
2333
3058
  if (isObjectType(propertySchema)) {
@@ -2362,51 +3087,27 @@ WHERE ${whereConditions.join(' AND ')}
2362
3087
  }
2363
3088
  }
2364
3089
  }
2365
- // Validate that at least one property has an initial value (needed for valid SDNA constructor)
2366
- // Collections don't create constructor actions, only properties with initial values do
2367
- const hasPropertyWithInitial = Object.values(properties).some((prop) => prop.initial);
2368
- if (!hasPropertyWithInitial) {
2369
- // If no properties have initial values, add a type identifier automatically
2370
- const typeProperty = `ad4m://type`;
2371
- let typeValue;
2372
- if (namespace.includes('://')) {
2373
- const [scheme, rest] = namespace.split('://');
2374
- const path = (rest || '').replace(/\/+$/, '');
2375
- if (path) {
2376
- typeValue = `${scheme}://${path}/instance`;
2377
- }
2378
- else {
2379
- typeValue = `${scheme}://instance`;
2380
- }
2381
- }
2382
- else {
2383
- const path = namespace.replace(/\/+$/, '');
2384
- typeValue = `${path}/instance`;
2385
- }
2386
- properties['__ad4m_type'] = {
2387
- through: typeProperty,
2388
- required: true,
2389
- writable: false,
2390
- initial: typeValue,
2391
- flag: true
2392
- };
2393
- // Add the type property to the prototype
2394
- Object.defineProperty(DynamicModelClass.prototype, '__ad4m_type', {
2395
- configurable: true,
2396
- writable: false,
2397
- value: typeValue
3090
+ // No auto-flag generation — models with all-optional properties use
3091
+ // open-world structural matching. Consumers who need type discrimination
3092
+ // should add an explicit @Flag to their model definition.
3093
+ // Attach metadata to WeakMap registries
3094
+ for (const [propName, propMeta] of Object.entries(properties)) {
3095
+ setPropertyRegistryEntry(DynamicModelClass, propName, propMeta);
3096
+ }
3097
+ for (const [relName, relMeta] of Object.entries(relations)) {
3098
+ setRelationRegistryEntry(DynamicModelClass, relName, {
3099
+ predicate: relMeta.through || "",
3100
+ kind: 'hasMany',
3101
+ ...(relMeta.getter !== undefined && { getter: relMeta.getter }),
3102
+ ...(relMeta.local !== undefined && { local: relMeta.local }),
2398
3103
  });
2399
- console.warn(`No properties with initial values found. Added automatic type flag: ${typeProperty} = ${typeValue}`);
2400
3104
  }
2401
- // Attach metadata to prototype
2402
- DynamicModelClass.prototype.__properties = properties;
2403
- DynamicModelClass.prototype.__collections = collections;
2404
3105
  // Store the JSON schema and options on the prototype for potential fallback use by getModelMetadata()
2405
3106
  DynamicModelClass.prototype.__jsonSchema = schema;
2406
3107
  DynamicModelClass.prototype.__jsonSchemaOptions = options;
2407
- // Apply the ModelOptions decorator to set up the generateSDNA method
2408
- const ModelOptionsDecorator = ModelOptions({ name: options.name });
2409
- ModelOptionsDecorator(DynamicModelClass);
3108
+ // Apply the Model decorator to set up the generateSDNA method
3109
+ const ModelDecorator = Model({ name: options.name });
3110
+ ModelDecorator(DynamicModelClass);
2410
3111
  return DynamicModelClass;
2411
3112
  }
2412
3113
  /**
@@ -2519,7 +3220,6 @@ WHERE ${whereConditions.join(' AND ')}
2519
3220
  }
2520
3221
  }
2521
3222
  }
2522
- _Ad4mModel_baseExpression = new WeakMap(), _Ad4mModel_subjectClassName = new WeakMap(), _Ad4mModel_source = new WeakMap(), _Ad4mModel_perspective = new WeakMap();
2523
3223
  Ad4mModel.classNamesByClass = new WeakMap();
2524
3224
  /** Query builder for Ad4mModel queries.
2525
3225
  * Allows building queries with a fluent interface and either running them once
@@ -2635,18 +3335,72 @@ export class ModelQueryBuilder {
2635
3335
  return this;
2636
3336
  }
2637
3337
  /**
2638
- * Sets the source filter for the query.
2639
- *
2640
- * @param source - The source to filter by
3338
+ * Scopes the query to instances linked from a parent.
3339
+ *
3340
+ * The predicate is resolved in order of precedence:
3341
+ * 1. **Instance only** — the parent's constructor is used as the model
3342
+ * class; its relation metadata is scanned for a relation whose
3343
+ * `target()` matches the queried model class.
3344
+ * 2. **Instance + options with `field`** — direct field-name lookup on
3345
+ * the parent model's relation metadata (disambiguates when a parent
3346
+ * has multiple relations targeting the same child class).
3347
+ * 3. **String id + model class** — same metadata scan (or field lookup if
3348
+ * options include `field`).
3349
+ * 4. **String id + string predicate** — raw escape hatch, no metadata lookup.
3350
+ *
3351
+ * Passing a plain string id with no second argument throws because the
3352
+ * predicate cannot be resolved without a model class.
3353
+ *
3354
+ * @param idOrInstance - The parent's expression URI **or** an Ad4mModel instance
3355
+ * @param modelOrPredicate - A model class (predicate auto-resolved) **or** a raw predicate string
3356
+ * @param options - Optional settings: `field` for direct relation-name lookup
2641
3357
  * @returns The query builder for chaining
2642
3358
  *
2643
3359
  * @example
2644
3360
  * ```typescript
2645
- * .source("ad4m://self")
3361
+ * // Instance — predicate auto-resolved from Cookbook's @HasMany(() => Recipe)
3362
+ * Recipe.query(perspective).parent(cookbook).get();
3363
+ *
3364
+ * // Instance + field — disambiguate when parent has multiple relations to same child
3365
+ * Recipe.query(perspective).parent(cookbook, { field: "recipes" }).get();
3366
+ *
3367
+ * // String id + model class
3368
+ * Recipe.query(perspective).parent(cookbookId, Cookbook).get();
3369
+ *
3370
+ * // String id + model class + field
3371
+ * Recipe.query(perspective).parent(cookbookId, Cookbook, { field: "recipes" }).get();
3372
+ *
3373
+ * // String id + raw predicate (escape hatch)
3374
+ * Recipe.query(perspective).parent(cookbookId, "cookbook://recipe").get();
2646
3375
  * ```
2647
3376
  */
2648
- source(source) {
2649
- this.queryParams.source = source;
3377
+ parent(idOrInstance, modelOrPredicate, options) {
3378
+ const id = typeof idOrInstance === 'string' ? idOrInstance : idOrInstance.id;
3379
+ // Handle options-object as second arg: parent(instance, { field: "recipes" })
3380
+ if (typeof modelOrPredicate === 'object' && modelOrPredicate !== null && !('prototype' in modelOrPredicate)) {
3381
+ if (typeof idOrInstance === 'string') {
3382
+ throw new Error('parent() called with a string id and options object requires a model class as second argument');
3383
+ }
3384
+ const model = idOrInstance.constructor;
3385
+ this.queryParams.parent = { id, model, field: modelOrPredicate.field };
3386
+ return this;
3387
+ }
3388
+ const field = options?.field;
3389
+ if (typeof modelOrPredicate === 'string') {
3390
+ // Raw predicate string → raw form of ParentScope
3391
+ this.queryParams.parent = { id, predicate: modelOrPredicate };
3392
+ }
3393
+ else if (typeof modelOrPredicate === 'function') {
3394
+ // Model class → model form of ParentScope
3395
+ this.queryParams.parent = { id, model: modelOrPredicate, ...(field && { field }) };
3396
+ }
3397
+ else if (typeof idOrInstance !== 'string') {
3398
+ // Ad4mModel instance — derive model class from constructor
3399
+ this.queryParams.parent = { id, model: idOrInstance.constructor, ...(field && { field }) };
3400
+ }
3401
+ else {
3402
+ throw new Error('parent() called with a string id requires a second argument: either a model class or a predicate string');
3403
+ }
2650
3404
  return this;
2651
3405
  }
2652
3406
  /**
@@ -2665,18 +3419,33 @@ export class ModelQueryBuilder {
2665
3419
  return this;
2666
3420
  }
2667
3421
  /**
2668
- * Specifies which collections to include in the results.
3422
+ * Specifies which relations to eager-load (hydrate into model instances).
3423
+ *
3424
+ * Without `include`, relation fields contain raw expression URIs (strings).
3425
+ * With `include`, the URIs are resolved into fully-hydrated model instances
3426
+ * using the `target` class declared in the relation decorator.
2669
3427
  *
2670
- * @param collections - Array of collection names to include
3428
+ * Supports nested includes for multi-level eager loading.
3429
+ *
3430
+ * @param map - An IncludeMap describing which relations to hydrate
2671
3431
  * @returns The query builder for chaining
2672
3432
  *
2673
3433
  * @example
2674
3434
  * ```typescript
2675
- * .collections(["ingredients", "steps"])
3435
+ * // Hydrate comments one level deep
3436
+ * const recipes = await Recipe.query(perspective)
3437
+ * .include({ comments: true })
3438
+ * .run();
3439
+ * // recipe.comments is now Comment[] (model instances), not string[]
3440
+ *
3441
+ * // Nested: hydrate comments AND each comment's author
3442
+ * const recipes = await Recipe.query(perspective)
3443
+ * .include({ comments: { author: true } })
3444
+ * .run();
2676
3445
  * ```
2677
3446
  */
2678
- collections(collections) {
2679
- this.queryParams.collections = collections;
3447
+ include(map) {
3448
+ this.queryParams.include = map;
2680
3449
  return this;
2681
3450
  }
2682
3451
  overrideModelClassName(className) {
@@ -2725,18 +3494,37 @@ export class ModelQueryBuilder {
2725
3494
  * ```
2726
3495
  */
2727
3496
  async get() {
3497
+ let results;
2728
3498
  if (this.useSurrealDBFlag) {
2729
3499
  const surrealQuery = await this.ctor.queryToSurrealQL(this.perspective, this.queryParams);
2730
3500
  const result = await this.perspective.querySurrealDB(surrealQuery);
2731
- const { results } = await this.ctor.instancesFromSurrealResult(this.perspective, this.queryParams, result);
2732
- return results;
3501
+ ({ results } = await this.ctor.instancesFromSurrealResult(this.perspective, this.queryParams, result));
2733
3502
  }
2734
3503
  else {
2735
3504
  const query = await this.ctor.queryToProlog(this.perspective, this.queryParams, this.modelClassName);
2736
3505
  const result = await this.perspective.infer(query);
2737
- const { results } = await this.ctor.instancesFromPrologResult(this.perspective, this.queryParams, result);
2738
- return results;
3506
+ ({ results } = await this.ctor.instancesFromPrologResult(this.perspective, this.queryParams, result));
2739
3507
  }
3508
+ return results;
3509
+ }
3510
+ /**
3511
+ * Returns the first matching instance, or `null` if none match.
3512
+ *
3513
+ * Internally sets `limit: 1` and delegates to `get()`.
3514
+ *
3515
+ * @returns The first matching instance, or `null`
3516
+ *
3517
+ * @example
3518
+ * ```typescript
3519
+ * const recipe = await Recipe.query(perspective)
3520
+ * .where({ name: "Pasta" })
3521
+ * .first();
3522
+ * ```
3523
+ */
3524
+ async first() {
3525
+ this.queryParams.limit = 1;
3526
+ const results = await this.get();
3527
+ return results[0] ?? null;
2740
3528
  }
2741
3529
  /**
2742
3530
  * Subscribes to the query and receives updates when results change.
@@ -2772,31 +3560,32 @@ export class ModelQueryBuilder {
2772
3560
  async subscribe(callback) {
2773
3561
  // Clean up any existing subscription
2774
3562
  this.dispose();
3563
+ const ctor = this.ctor;
2775
3564
  if (this.useSurrealDBFlag) {
2776
- const surrealQuery = await this.ctor.queryToSurrealQL(this.perspective, this.queryParams);
3565
+ const surrealQuery = await ctor.queryToSurrealQL(this.perspective, this.queryParams);
2777
3566
  this.currentSubscription = await this.perspective.subscribeSurrealDB(surrealQuery);
2778
3567
  const processResults = async (result) => {
2779
- // The result from live query subscription update (handled in PerspectiveInstance listener)
2780
- // is the new full set of results (because we re-query in Rust).
2781
- // So we just need to map it to instances.
2782
- const { results } = await this.ctor.instancesFromSurrealResult(this.perspective, this.queryParams, result);
3568
+ const { results } = await ctor.instancesFromSurrealResult(this.perspective, this.queryParams, result);
2783
3569
  callback(results);
2784
3570
  };
2785
3571
  this.currentSubscription.onResult(processResults);
2786
3572
  // Process initial result
2787
- const { results } = await this.ctor.instancesFromSurrealResult(this.perspective, this.queryParams, this.currentSubscription.result);
3573
+ const { results } = await ctor.instancesFromSurrealResult(this.perspective, this.queryParams, this.currentSubscription.result);
3574
+ // Also invoke callback with initial results so subscribers see them
3575
+ callback(results);
2788
3576
  return results;
2789
3577
  }
2790
3578
  else {
2791
- // Note: Subscriptions currently only work with Prolog
2792
- const query = await this.ctor.queryToProlog(this.perspective, this.queryParams, this.modelClassName);
3579
+ const query = await ctor.queryToProlog(this.perspective, this.queryParams, this.modelClassName);
2793
3580
  this.currentSubscription = await this.perspective.subscribeInfer(query);
2794
3581
  const processResults = async (result) => {
2795
- const { results } = await this.ctor.instancesFromPrologResult(this.perspective, this.queryParams, result);
3582
+ const { results } = await ctor.instancesFromPrologResult(this.perspective, this.queryParams, result);
2796
3583
  callback(results);
2797
3584
  };
2798
3585
  this.currentSubscription.onResult(processResults);
2799
- const { results } = await this.ctor.instancesFromPrologResult(this.perspective, this.queryParams, this.currentSubscription.result);
3586
+ const { results } = await ctor.instancesFromPrologResult(this.perspective, this.queryParams, this.currentSubscription.result);
3587
+ // Also invoke callback with initial results so subscribers see them
3588
+ callback(results);
2800
3589
  return results;
2801
3590
  }
2802
3591
  }
@@ -2871,6 +3660,7 @@ export class ModelQueryBuilder {
2871
3660
  };
2872
3661
  this.currentSubscription.onResult(processResults);
2873
3662
  const { totalCount } = await this.ctor.instancesFromSurrealResult(this.perspective, this.queryParams, this.currentSubscription.result);
3663
+ callback(totalCount);
2874
3664
  return totalCount;
2875
3665
  }
2876
3666
  else {
@@ -2881,7 +3671,9 @@ export class ModelQueryBuilder {
2881
3671
  callback(newCount);
2882
3672
  };
2883
3673
  this.currentSubscription.onResult(processResults);
2884
- return this.currentSubscription.result?.[0]?.TotalCount || 0;
3674
+ const initialCount = this.currentSubscription.result?.[0]?.TotalCount || 0;
3675
+ callback(initialCount);
3676
+ return initialCount;
2885
3677
  }
2886
3678
  }
2887
3679
  /**
@@ -2960,7 +3752,9 @@ export class ModelQueryBuilder {
2960
3752
  };
2961
3753
  this.currentSubscription.onResult(processResults);
2962
3754
  const { results, totalCount } = (await this.ctor.instancesFromSurrealResult(this.perspective, paginationQuery, this.currentSubscription.result));
2963
- return { results, totalCount, pageSize, pageNumber };
3755
+ const initialPage = { results, totalCount, pageSize, pageNumber };
3756
+ callback(initialPage);
3757
+ return initialPage;
2964
3758
  }
2965
3759
  else {
2966
3760
  const prologQuery = await this.ctor.queryToProlog(this.perspective, paginationQuery, this.modelClassName);
@@ -2971,7 +3765,135 @@ export class ModelQueryBuilder {
2971
3765
  };
2972
3766
  this.currentSubscription.onResult(processResults);
2973
3767
  const { results, totalCount } = (await this.ctor.instancesFromPrologResult(this.perspective, paginationQuery, this.currentSubscription.result));
2974
- return { results, totalCount, pageSize, pageNumber };
3768
+ const initialPrologPage = { results, totalCount, pageSize, pageNumber };
3769
+ callback(initialPrologPage);
3770
+ return initialPrologPage;
2975
3771
  }
2976
3772
  }
2977
3773
  }
3774
+ // ── Standalone Prolog fact generator ──────────────────────────────────────────
3775
+ /**
3776
+ * Convert a camelCase or PascalCase identifier to snake_case.
3777
+ * Examples: "TestPost" -> "test_post", "createdAt" -> "created_at"
3778
+ */
3779
+ function toSnakeCase(str) {
3780
+ return str
3781
+ .replace(/([A-Z])/g, "_$1")
3782
+ .toLowerCase()
3783
+ .replace(/^_/, "");
3784
+ }
3785
+ function buildInstanceClause(predicateName, metadata) {
3786
+ const props = metadata.properties;
3787
+ // Collect flags first — these are the strongest recognizers
3788
+ const flags = Object.values(props).filter((p) => p.flag && p.predicate && p.initial);
3789
+ if (flags.length > 0) {
3790
+ const conditions = flags
3791
+ .map((p) => `triple(X, '${p.predicate}', '${p.initial}')`)
3792
+ .join(",\n ");
3793
+ return `${predicateName}(X) :-\n ${conditions}.`;
3794
+ }
3795
+ // Fallback: required non-flag properties
3796
+ const required = Object.values(props).filter((p) => p.required && p.predicate && !p.flag);
3797
+ if (required.length > 0) {
3798
+ const conditions = required
3799
+ .map((p) => `triple(X, '${p.predicate}', _)`)
3800
+ .join(",\n ");
3801
+ return `${predicateName}(X) :-\n ${conditions}.`;
3802
+ }
3803
+ // Open-world structural fallback: match nodes that have at least one of the
3804
+ // model's declared property predicates. Uses disjunction (;) so any single
3805
+ // predicate is enough.
3806
+ const allPredicates = Object.values(props)
3807
+ .filter((p) => p.predicate)
3808
+ .map((p) => p.predicate);
3809
+ if (metadata.relations) {
3810
+ for (const rel of Object.values(metadata.relations)) {
3811
+ if (rel.predicate)
3812
+ allPredicates.push(rel.predicate);
3813
+ }
3814
+ }
3815
+ if (allPredicates.length > 0) {
3816
+ const disjunction = allPredicates
3817
+ .map((pred) => `triple(X, '${pred}', _)`)
3818
+ .join(" ;\n ");
3819
+ return `${predicateName}(X) :-\n (${disjunction}).`;
3820
+ }
3821
+ return null;
3822
+ }
3823
+ function buildPropertyClause(modelPredicateName, prop) {
3824
+ if (prop.flag)
3825
+ return null;
3826
+ if (!prop.predicate)
3827
+ return null;
3828
+ const clauseName = `${modelPredicateName}_${toSnakeCase(prop.name)}`;
3829
+ return `${clauseName}(X, Value) :- triple(X, '${prop.predicate}', Value).`;
3830
+ }
3831
+ function buildRelationClause(modelPredicateName, relation) {
3832
+ if (!relation.predicate)
3833
+ return null;
3834
+ const clauseName = `${modelPredicateName}_${toSnakeCase(relation.name)}`;
3835
+ if (relation.direction === "reverse") {
3836
+ return `${clauseName}(X, Values) :- findall(V, triple(V, '${relation.predicate}', X), Values).`;
3837
+ }
3838
+ return `${clauseName}(X, Values) :- findall(V, triple(X, '${relation.predicate}', V), Values).`;
3839
+ }
3840
+ /**
3841
+ * Generate Prolog predicate facts from a model class's decorator metadata.
3842
+ *
3843
+ * Given a model class decorated with `@Model` (and its `@Flag`, `@Property`,
3844
+ * `@HasMany`, `@BelongsToMany` decorators), this function emits a string of
3845
+ * Prolog clauses that can be prepended to any `perspective.infer()` call.
3846
+ *
3847
+ * The generated predicates are:
3848
+ * - **Instance recognizer** — `modelName(X)` — matches instances of the model
3849
+ * - **Property getters** — `modelName_propName(X, Value)` — one per property
3850
+ * - **Relation getters** — `modelName_relName(X, Values)` — one per relation
3851
+ *
3852
+ * @example
3853
+ * ```typescript
3854
+ * import { generatePrologFacts } from '@coasys/ad4m';
3855
+ *
3856
+ * const facts = generatePrologFacts(Poll);
3857
+ * const result = await perspective.infer(\`
3858
+ * \${facts}
3859
+ * recent_popular_poll(X) :-
3860
+ * poll(X),
3861
+ * poll_vote_count(X, N), N > 10.
3862
+ * \`);
3863
+ * ```
3864
+ *
3865
+ * @param ModelClass - A class decorated with `@Model` that extends `Ad4mModel`
3866
+ * @returns A multi-line Prolog string ready for use with `perspective.infer()`
3867
+ */
3868
+ export function generatePrologFacts(ModelClass) {
3869
+ const metadata = ModelClass.getModelMetadata();
3870
+ const predicateName = toSnakeCase(metadata.className);
3871
+ const lines = [];
3872
+ lines.push(`% ${metadata.className} — generated Prolog facts`);
3873
+ // Instance recognizer
3874
+ const instanceClause = buildInstanceClause(predicateName, metadata);
3875
+ if (instanceClause) {
3876
+ lines.push("");
3877
+ lines.push(`% Instance recognizer`);
3878
+ lines.push(instanceClause);
3879
+ }
3880
+ // Property getters
3881
+ const propClauses = Object.values(metadata.properties)
3882
+ .map((p) => buildPropertyClause(predicateName, p))
3883
+ .filter((c) => c !== null);
3884
+ if (propClauses.length > 0) {
3885
+ lines.push("");
3886
+ lines.push(`% Field getters`);
3887
+ lines.push(...propClauses);
3888
+ }
3889
+ // Relation getters
3890
+ const relClauses = Object.values(metadata.relations)
3891
+ .map((c) => buildRelationClause(predicateName, c))
3892
+ .filter((c) => c !== null);
3893
+ if (relClauses.length > 0) {
3894
+ lines.push("");
3895
+ lines.push(`% Relation getters`);
3896
+ lines.push(...relClauses);
3897
+ }
3898
+ return lines.join("\n");
3899
+ }