@coasys/ad4m 0.12.0-rc1-dev.5 → 0.12.0

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 (161) hide show
  1. package/lib/index.cjs +4968 -4805
  2. package/lib/index.js +4936 -4801
  3. package/lib/src/agent/AgentClient.d.ts +4 -0
  4. package/lib/src/agent/AgentClient.js +34 -0
  5. package/lib/src/index.d.ts +2 -3
  6. package/lib/src/index.js +2 -3
  7. package/lib/src/model/Ad4mModel.d.ts +8 -812
  8. package/lib/src/model/Ad4mModel.js +78 -2390
  9. package/lib/src/model/ModelQueryBuilder.d.ts +370 -0
  10. package/lib/src/model/ModelQueryBuilder.js +556 -0
  11. package/lib/src/model/decorators.d.ts +2 -20
  12. package/lib/src/model/decorators.js +5 -410
  13. package/lib/src/model/hydration.d.ts +102 -0
  14. package/lib/src/model/hydration.js +709 -0
  15. package/lib/src/model/index.d.ts +20 -0
  16. package/lib/src/model/index.js +20 -0
  17. package/lib/src/model/{schema/fromJSONSchema.d.ts → json-schema.d.ts} +45 -12
  18. package/lib/src/model/json-schema.js +326 -0
  19. package/lib/src/model/prolog-facts.d.ts +37 -0
  20. package/lib/src/model/{prolog/generatePrologFacts.js → prolog-facts.js} +47 -52
  21. package/lib/src/model/query-common.d.ts +14 -0
  22. package/lib/src/model/query-common.js +36 -0
  23. package/lib/src/model/query-prolog.d.ts +15 -0
  24. package/lib/src/model/query-prolog.js +140 -0
  25. package/lib/src/model/query-surreal.d.ts +44 -0
  26. package/lib/src/model/query-surreal.js +249 -0
  27. package/lib/src/model/sdna.d.ts +14 -0
  28. package/lib/src/model/sdna.js +141 -0
  29. package/lib/src/model/shacl-gen.d.ts +31 -0
  30. package/lib/src/model/shacl-gen.js +246 -0
  31. package/lib/src/model/surreal-utils.d.ts +1 -1
  32. package/lib/src/model/types.d.ts +75 -96
  33. package/lib/src/model/types.js +4 -4
  34. package/lib/src/model/util.d.ts +4 -5
  35. package/lib/src/model/util.js +12 -32
  36. package/lib/src/perspectives/PerspectiveClient.d.ts +1 -1
  37. package/lib/src/perspectives/PerspectiveProxy.d.ts +1 -1
  38. package/lib/src/perspectives/WakerSubscriptionManager.d.ts +79 -0
  39. package/lib/src/perspectives/WakerSubscriptionManager.js +196 -0
  40. package/lib/src/runtime/RuntimeResolver.d.ts +14 -0
  41. package/lib/src/runtime/RuntimeResolver.js +73 -0
  42. package/lib/src/schema.gql +14 -0
  43. package/lib/src/typeDefs.js +14 -0
  44. package/package.json +13 -8
  45. package/src/agent/AgentClient.ts +45 -0
  46. package/src/index.ts +2 -3
  47. package/src/model/Ad4mModel.ts +1084 -3818
  48. package/src/model/ModelQueryBuilder.ts +617 -0
  49. package/src/model/Subject.ts +1 -1
  50. package/src/model/decorators.ts +17 -475
  51. package/src/model/hydration.ts +796 -0
  52. package/src/model/index.ts +21 -0
  53. package/src/model/json-schema.ts +424 -0
  54. package/src/model/prolog-facts.ts +145 -0
  55. package/src/model/query-common.ts +48 -0
  56. package/src/model/query-prolog.ts +148 -0
  57. package/src/model/query-surreal.ts +280 -0
  58. package/src/model/relation-filtering.test.ts +0 -1
  59. package/src/model/sdna.ts +170 -0
  60. package/src/model/shacl-gen.ts +292 -0
  61. package/src/model/surreal-utils.ts +1 -1
  62. package/src/model/types.ts +182 -0
  63. package/src/model/util.ts +13 -36
  64. package/src/perspectives/PerspectiveClient.ts +1 -1
  65. package/src/perspectives/PerspectiveProxy.ts +1 -1
  66. package/src/perspectives/WakerSubscriptionManager.ts +292 -0
  67. package/src/runtime/RuntimeResolver.ts +53 -0
  68. package/lib/src/Ad4mClient.test.d.ts +0 -1
  69. package/lib/src/Ad4mClient.test.js +0 -1204
  70. package/lib/src/Literal.test.d.ts +0 -1
  71. package/lib/src/Literal.test.js +0 -41
  72. package/lib/src/model/mutation.d.ts +0 -81
  73. package/lib/src/model/mutation.js +0 -317
  74. package/lib/src/model/parentUtils.d.ts +0 -32
  75. package/lib/src/model/parentUtils.js +0 -64
  76. package/lib/src/model/prolog/generatePrologFacts.d.ts +0 -36
  77. package/lib/src/model/prolog/index.d.ts +0 -1
  78. package/lib/src/model/prolog/index.js +0 -1
  79. package/lib/src/model/query/ModelQueryBuilder.d.ts +0 -82
  80. package/lib/src/model/query/ModelQueryBuilder.js +0 -115
  81. package/lib/src/model/query/QueryBuilder.d.ts +0 -101
  82. package/lib/src/model/query/QueryBuilder.js +0 -193
  83. package/lib/src/model/query/SurrealQueryBuilder.d.ts +0 -48
  84. package/lib/src/model/query/SurrealQueryBuilder.js +0 -371
  85. package/lib/src/model/query/fetchInstance.d.ts +0 -24
  86. package/lib/src/model/query/fetchInstance.js +0 -144
  87. package/lib/src/model/query/hydration.d.ts +0 -54
  88. package/lib/src/model/query/hydration.js +0 -214
  89. package/lib/src/model/query/operations.d.ts +0 -59
  90. package/lib/src/model/query/operations.js +0 -384
  91. package/lib/src/model/query/snapshot.d.ts +0 -59
  92. package/lib/src/model/query/snapshot.js +0 -106
  93. package/lib/src/model/query/surrealCompiler.d.ts +0 -42
  94. package/lib/src/model/query/surrealCompiler.js +0 -304
  95. package/lib/src/model/schema/fromJSONSchema.js +0 -264
  96. package/lib/src/model/schema/metadata.d.ts +0 -15
  97. package/lib/src/model/schema/metadata.js +0 -112
  98. package/lib/src/model/subscription.d.ts +0 -47
  99. package/lib/src/model/subscription.js +0 -231
  100. package/lib/src/model/transaction.d.ts +0 -27
  101. package/lib/src/model/transaction.js +0 -32
  102. package/lib/src/shims/reflect-metadata.d.ts +0 -0
  103. package/lib/src/shims/type-graphql.d.ts +0 -32
  104. package/lib/src/src/Ad4mClient.d.ts +0 -28
  105. package/lib/src/src/Address.d.ts +0 -1
  106. package/lib/src/src/DID.d.ts +0 -1
  107. package/lib/src/src/Exception.d.ts +0 -7
  108. package/lib/src/src/Literal.d.ts +0 -7
  109. package/lib/src/src/PubSub.d.ts +0 -17
  110. package/lib/src/src/SmartLiteral.d.ts +0 -12
  111. package/lib/src/src/agent/Agent.d.ts +0 -110
  112. package/lib/src/src/agent/AgentClient.d.ts +0 -62
  113. package/lib/src/src/agent/AgentResolver.d.ts +0 -30
  114. package/lib/src/src/agent/AgentStatus.d.ts +0 -8
  115. package/lib/src/src/ai/AIClient.d.ts +0 -32
  116. package/lib/src/src/ai/AIResolver.d.ts +0 -75
  117. package/lib/src/src/ai/Tasks.d.ts +0 -37
  118. package/lib/src/src/buildSchema.d.ts +0 -1
  119. package/lib/src/src/expression/Expression.d.ts +0 -28
  120. package/lib/src/src/expression/ExpressionClient.d.ts +0 -13
  121. package/lib/src/src/expression/ExpressionRef.d.ts +0 -9
  122. package/lib/src/src/expression/ExpressionResolver.d.ts +0 -10
  123. package/lib/src/src/index.d.ts +0 -35
  124. package/lib/src/src/jestSetup.d.ts +0 -1
  125. package/lib/src/src/language/Icon.d.ts +0 -4
  126. package/lib/src/src/language/Language.d.ts +0 -206
  127. package/lib/src/src/language/LanguageClient.d.ts +0 -17
  128. package/lib/src/src/language/LanguageContext.d.ts +0 -37
  129. package/lib/src/src/language/LanguageHandle.d.ts +0 -9
  130. package/lib/src/src/language/LanguageMeta.d.ts +0 -35
  131. package/lib/src/src/language/LanguageRef.d.ts +0 -6
  132. package/lib/src/src/language/LanguageResolver.d.ts +0 -19
  133. package/lib/src/src/links/Links.d.ts +0 -39
  134. package/lib/src/src/links/Links.test.d.ts +0 -1
  135. package/lib/src/src/model/Ad4mModel.d.ts +0 -1438
  136. package/lib/src/src/model/Ad4mModel.test.d.ts +0 -1
  137. package/lib/src/src/model/Subject.d.ts +0 -25
  138. package/lib/src/src/model/decorators.d.ts +0 -545
  139. package/lib/src/src/model/util.d.ts +0 -12
  140. package/lib/src/src/neighbourhood/Neighbourhood.d.ts +0 -10
  141. package/lib/src/src/neighbourhood/NeighbourhoodClient.d.ts +0 -25
  142. package/lib/src/src/neighbourhood/NeighbourhoodProxy.d.ts +0 -19
  143. package/lib/src/src/neighbourhood/NeighbourhoodProxy.test.d.ts +0 -1
  144. package/lib/src/src/neighbourhood/NeighbourhoodResolver.d.ts +0 -24
  145. package/lib/src/src/perspectives/LinkQuery.d.ts +0 -11
  146. package/lib/src/src/perspectives/Perspective.d.ts +0 -38
  147. package/lib/src/src/perspectives/Perspective.test.d.ts +0 -1
  148. package/lib/src/src/perspectives/PerspectiveClient.d.ts +0 -97
  149. package/lib/src/src/perspectives/PerspectiveDiff.d.ts +0 -9
  150. package/lib/src/src/perspectives/PerspectiveHandle.d.ts +0 -18
  151. package/lib/src/src/perspectives/PerspectiveProxy.d.ts +0 -865
  152. package/lib/src/src/perspectives/PerspectiveResolver.d.ts +0 -57
  153. package/lib/src/src/runtime/RuntimeClient.d.ts +0 -56
  154. package/lib/src/src/runtime/RuntimeResolver.d.ts +0 -132
  155. package/lib/src/src/shacl/SHACLFlow.d.ts +0 -171
  156. package/lib/src/src/shacl/SHACLFlow.test.d.ts +0 -1
  157. package/lib/src/src/shacl/SHACLShape.d.ts +0 -117
  158. package/lib/src/src/shacl/SHACLShape.test.d.ts +0 -1
  159. package/lib/src/src/typeDefs.d.ts +0 -1
  160. package/lib/src/src/unwrapApolloResult.d.ts +0 -2
  161. package/lib/src/src/utils.d.ts +0 -25
@@ -0,0 +1,796 @@
1
+ /**
2
+ * hydration.ts — Instance hydration helpers extracted from Ad4mModel.
3
+ *
4
+ * Pure / stateless functions that populate Ad4mModel instances from
5
+ * raw link arrays, Prolog tuples, or SurrealDB rows. None of these
6
+ * functions depend on the `Ad4mModel` class at runtime — they accept
7
+ * the instance, metadata, or perspective as explicit parameters.
8
+ */
9
+
10
+ import { Literal } from "../Literal";
11
+ import { LinkQuery } from "../perspectives/LinkQuery";
12
+ import type { PerspectiveProxy } from "../perspectives/PerspectiveProxy";
13
+ import { getPropertiesMetadata, getRelationsMetadata, buildConformanceFilter } from "./decorators";
14
+ import type { RelationMetadataEntry } from "./decorators";
15
+ import { escapeSurrealString } from "../utils";
16
+ import { formatSurrealValue, compileWhereClause } from "./surreal-utils";
17
+ import type {
18
+ PropertyMetadata, RelationMetadata, ModelMetadata,
19
+ ValueTuple, WhereCondition, IncludeMap, RelationSubQuery,
20
+ } from "./types";
21
+
22
+ // ──────────────────────────────────────────────────────────
23
+ // Pure helpers
24
+ // ──────────────────────────────────────────────────────────
25
+
26
+ /**
27
+ * Normalize a value for snapshot storage.
28
+ * Arrays of model instances are reduced to their `.id` strings so that
29
+ * dirty-tracking compares stable identifiers instead of object references.
30
+ */
31
+ export function normalizeValue(value: any): any {
32
+ if (Array.isArray(value)) {
33
+ return value.map((v: any) =>
34
+ v && typeof v === 'object' && typeof v.id === 'string' ? v.id : v,
35
+ );
36
+ }
37
+ return value;
38
+ }
39
+
40
+ /**
41
+ * Checks if a value matches a where-condition (for post-query filtering).
42
+ */
43
+ export function matchesCondition(value: any, condition: WhereCondition): boolean {
44
+ // Handle array values (IN clause)
45
+ if (Array.isArray(condition)) {
46
+ return (condition as any[]).includes(value);
47
+ }
48
+
49
+ // Handle operator object
50
+ if (typeof condition === 'object' && condition !== null) {
51
+ const ops = condition as any;
52
+
53
+ // Special case: 'not' operator (exclusive with other operators)
54
+ if (ops.not !== undefined) {
55
+ if (Array.isArray(ops.not)) {
56
+ return !(ops.not as any[]).includes(value);
57
+ } else {
58
+ return value !== ops.not;
59
+ }
60
+ }
61
+
62
+ // Special case: 'between' operator (inclusive range, exclusive with gt/gte/lt/lte)
63
+ if (ops.between !== undefined && Array.isArray(ops.between) && ops.between.length === 2) {
64
+ return value >= ops.between[0] && value <= ops.between[1];
65
+ }
66
+
67
+ // For all other operators (gt, gte, lt, lte, contains), we need to check ALL of them
68
+ // and return true only if ALL conditions are satisfied
69
+ let allConditionsMet = true;
70
+
71
+ if (ops.gt !== undefined) {
72
+ allConditionsMet = allConditionsMet && (value > ops.gt);
73
+ }
74
+
75
+ if (ops.gte !== undefined) {
76
+ allConditionsMet = allConditionsMet && (value >= ops.gte);
77
+ }
78
+
79
+ if (ops.lt !== undefined) {
80
+ allConditionsMet = allConditionsMet && (value < ops.lt);
81
+ }
82
+
83
+ if (ops.lte !== undefined) {
84
+ allConditionsMet = allConditionsMet && (value <= ops.lte);
85
+ }
86
+
87
+ if (ops.contains !== undefined) {
88
+ if (typeof value === 'string') {
89
+ allConditionsMet = allConditionsMet && value.includes(String(ops.contains));
90
+ } else if (Array.isArray(value)) {
91
+ allConditionsMet = allConditionsMet && value.includes(ops.contains);
92
+ } else {
93
+ allConditionsMet = false;
94
+ }
95
+ }
96
+
97
+ return allConditionsMet;
98
+ }
99
+
100
+ // Simple equality
101
+ return value === condition;
102
+ }
103
+
104
+ // ──────────────────────────────────────────────────────────
105
+ // Property / link hydration
106
+ // ──────────────────────────────────────────────────────────
107
+
108
+ /**
109
+ * Resolves a single property value from a raw link target string.
110
+ *
111
+ * Handles expression resolution, literal URI parsing, primitive
112
+ * type coercion, and optional transform functions.
113
+ *
114
+ * @param target - The raw target string from the link
115
+ * @param propMeta - Property metadata from the decorator registry
116
+ * @param perspective - The perspective for expression resolution
117
+ * @param expectedType - Optional JS typeof hint for coercion (e.g. 'number')
118
+ * @returns The resolved value
119
+ */
120
+ export async function hydratePropertyValue(
121
+ target: string,
122
+ propMeta: PropertyMetadata,
123
+ perspective: PerspectiveProxy,
124
+ expectedType?: string,
125
+ ): Promise<any> {
126
+ let value: any = target;
127
+
128
+ if (target !== undefined && target !== null && target !== '') {
129
+ // Non-literal expression resolution
130
+ if (
131
+ propMeta.resolveLanguage != null &&
132
+ propMeta.resolveLanguage !== 'literal' &&
133
+ typeof target === 'string' &&
134
+ !target.startsWith('literal://')
135
+ ) {
136
+ try {
137
+ const expression = await perspective.getExpression(target);
138
+ if (expression) {
139
+ try { value = JSON.parse(expression.data); } catch { value = expression.data; }
140
+ }
141
+ } catch (e) {
142
+ console.warn(`hydratePropertyValue: failed to resolve expression for "${propMeta.name}":`, e);
143
+ }
144
+ }
145
+ // Literal URI parsing
146
+ else if (
147
+ propMeta.resolveLanguage === 'literal' &&
148
+ typeof target === 'string' &&
149
+ target.startsWith('literal://')
150
+ ) {
151
+ try {
152
+ const parsed = Literal.fromUrl(target).get();
153
+ value = parsed.data !== undefined ? parsed.data : parsed;
154
+ } catch {
155
+ // Keep raw value
156
+ }
157
+ }
158
+ // Primitive type coercion
159
+ else if (typeof target === 'string' && expectedType) {
160
+ if (expectedType === 'number') value = Number(target);
161
+ else if (expectedType === 'boolean') value = target === 'true' || target === '1';
162
+ }
163
+ }
164
+
165
+ // Transform function
166
+ if (propMeta.transform && typeof propMeta.transform === 'function') {
167
+ value = propMeta.transform(value);
168
+ }
169
+
170
+ return value;
171
+ }
172
+
173
+ /**
174
+ * Hydrates an instance from an array of raw links.
175
+ *
176
+ * Processes properties (latest-wins semantics), relations
177
+ * (chronological accumulation), and timestamps/author in a single
178
+ * pass over the links array.
179
+ *
180
+ * @param instance - The blank model instance to populate
181
+ * @param links - Array of link objects (predicate, target, author?, timestamp?)
182
+ * @param metadata - Model metadata from `getModelMetadata()`
183
+ * @param perspective - The perspective for expression resolution
184
+ * @param requestedProperties - Optional sparse fieldset; when provided, only these
185
+ * property names are hydrated (relations are unaffected).
186
+ * Omit or pass `undefined` to hydrate all properties.
187
+ */
188
+ export async function hydrateFromLinks(
189
+ instance: any,
190
+ links: Array<{ predicate: string; target: string; author?: string; timestamp?: string | number }>,
191
+ metadata: ModelMetadata,
192
+ perspective: PerspectiveProxy,
193
+ requestedProperties?: string[],
194
+ ): Promise<void> {
195
+ if (!links || links.length === 0) return;
196
+
197
+ let minTimestamp: string | number | null = null;
198
+ let maxTimestamp: string | number | null = null;
199
+ let originalAuthor: string | null = null;
200
+ let latestAuthor: string | null = null;
201
+
202
+ // Build predicate→propName and predicate→relName lookup maps for O(1) matching
203
+ // When requestedProperties is provided, only include those properties in the map
204
+ const propFilter = requestedProperties && requestedProperties.length > 0
205
+ ? new Set(requestedProperties)
206
+ : null;
207
+
208
+ const predToProperty = new Map<string, [string, PropertyMetadata]>();
209
+ for (const [propName, propMeta] of Object.entries(metadata.properties)) {
210
+ if (propMeta.getter) continue; // Handled via custom getter evaluation
211
+ if (propFilter && !propFilter.has(propName)) continue; // Skip unrequested properties
212
+ predToProperty.set(propMeta.predicate, [propName, propMeta]);
213
+ }
214
+
215
+ const predToRelation = new Map<string, [string, RelationMetadata]>();
216
+
217
+ // Two-pass approach: first add all non-getter, non-target-filtered relations,
218
+ // then try to add target+filter relations only if their predicate isn't
219
+ // already claimed. This prevents predicate collisions (e.g. entries +
220
+ // messages sharing the same predicate) while still populating unique-
221
+ // predicate relations normally via link hydration.
222
+ const deferredTargetRelations: [string, RelationMetadata][] = [];
223
+ for (const [relName, relMeta] of Object.entries(metadata.relations)) {
224
+ if (relMeta.getter) continue; // Handled via explicit custom getter evaluation
225
+ if (relMeta.target && relMeta.filter !== false) {
226
+ deferredTargetRelations.push([relName, relMeta]);
227
+ continue;
228
+ }
229
+ predToRelation.set(relMeta.predicate, [relName, relMeta]);
230
+ }
231
+ // Second pass: add deferred target+filter relations only if their predicate
232
+ // is not already claimed by a base relation. When a collision exists, the
233
+ // conformance getter will handle the filtered view instead.
234
+ for (const [relName, relMeta] of deferredTargetRelations) {
235
+ if (!predToRelation.has(relMeta.predicate)) {
236
+ predToRelation.set(relMeta.predicate, [relName, relMeta]);
237
+ }
238
+ }
239
+
240
+ // Per-property accumulator: track all matching targets so we can pick the last (latest-wins)
241
+ const propertyLatest = new Map<string, { target: string; timestamp?: string | number }>();
242
+
243
+ // Per-relation accumulator: ordered targets with metadata for sorting
244
+ const relationAccum = new Map<string, Array<{ target: string; timestamp: string | number; index: number }>>();
245
+
246
+ // Single pass over all links
247
+ for (let i = 0; i < links.length; i++) {
248
+ const link = links[i];
249
+ const { predicate, target, author, timestamp } = link;
250
+ if (target === 'None' || target === undefined || target === null) continue;
251
+
252
+ // Track timestamps/authors
253
+ if (timestamp != null) {
254
+ if (minTimestamp == null || timestamp < minTimestamp) {
255
+ minTimestamp = timestamp;
256
+ originalAuthor = author ?? null;
257
+ }
258
+ if (maxTimestamp == null || timestamp > maxTimestamp) {
259
+ maxTimestamp = timestamp;
260
+ latestAuthor = author ?? null;
261
+ }
262
+ }
263
+
264
+ // Property match — accumulate for latest-wins
265
+ const propEntry = predToProperty.get(predicate);
266
+ if (propEntry) {
267
+ const existing = propertyLatest.get(propEntry[0]);
268
+ // Latest-wins: always overwrite (links are ordered ASC so last = latest)
269
+ propertyLatest.set(propEntry[0], { target, timestamp });
270
+ continue;
271
+ }
272
+
273
+ // Relation match — accumulate all
274
+ const relEntry = predToRelation.get(predicate);
275
+ if (relEntry) {
276
+ const [relName] = relEntry;
277
+ let arr = relationAccum.get(relName);
278
+ if (!arr) {
279
+ arr = [];
280
+ relationAccum.set(relName, arr);
281
+ }
282
+ arr.push({ target, timestamp: timestamp ?? '', index: i });
283
+ }
284
+ }
285
+
286
+ // Resolve properties
287
+ for (const [propName, { target }] of propertyLatest) {
288
+ const [, propMeta] = predToProperty.get(
289
+ metadata.properties[propName].predicate
290
+ )!;
291
+ const expectedType = typeof instance[propName];
292
+ instance[propName] = await hydratePropertyValue(
293
+ target,
294
+ propMeta,
295
+ perspective,
296
+ expectedType !== 'undefined' ? expectedType : undefined,
297
+ );
298
+ }
299
+
300
+ // Resolve relations: sort by timestamp (stable via index tiebreaker), filter empties
301
+ for (const [relName, items] of relationAccum) {
302
+ items.sort((a, b) => {
303
+ const cmp = String(a.timestamp).localeCompare(String(b.timestamp));
304
+ return cmp !== 0 ? cmp : a.index - b.index;
305
+ });
306
+ instance[relName] = items
307
+ .map(i => i.target)
308
+ .filter((v: any) => v !== undefined && v !== null && v !== '' && v !== 'None');
309
+ }
310
+
311
+ // Assign author / timestamps
312
+ if (originalAuthor) instance.author = originalAuthor;
313
+ if (minTimestamp != null) {
314
+ instance.createdAt = typeof minTimestamp === 'string' && minTimestamp.includes('T')
315
+ ? new Date(minTimestamp).getTime()
316
+ : typeof minTimestamp === 'string'
317
+ ? (isNaN(parseInt(minTimestamp, 10)) ? minTimestamp : parseInt(minTimestamp, 10))
318
+ : minTimestamp;
319
+ }
320
+ if (maxTimestamp != null) {
321
+ instance.updatedAt = typeof maxTimestamp === 'string' && maxTimestamp.includes('T')
322
+ ? new Date(maxTimestamp).getTime()
323
+ : typeof maxTimestamp === 'string'
324
+ ? (isNaN(parseInt(maxTimestamp, 10)) ? maxTimestamp : parseInt(maxTimestamp, 10))
325
+ : maxTimestamp;
326
+ }
327
+ }
328
+
329
+ // ──────────────────────────────────────────────────────────
330
+ // Prolog result hydration (assignValuesToInstance)
331
+ // ──────────────────────────────────────────────────────────
332
+
333
+ /**
334
+ * Assigns decoded Prolog property values to an instance.
335
+ *
336
+ * Handles UTF-8 byte sequence reconstruction, expression resolution,
337
+ * transform functions, and read-only property filtering.
338
+ */
339
+ export async function assignValuesToInstance(
340
+ perspective: PerspectiveProxy,
341
+ instance: any,
342
+ values: ValueTuple[],
343
+ ): Promise<void> {
344
+ // Map properties to object
345
+ const propsObject = Object.fromEntries(
346
+ await Promise.all(
347
+ values.map(async ([name, value, resolve]) => {
348
+ let finalValue = value;
349
+
350
+ // Handle UTF-8 byte sequences from Prolog URL decoding
351
+ if (!resolve && typeof value === 'string') {
352
+ // Only attempt reconstruction if the string looks like a byte string (all code points <= 0xFF)
353
+ // and contains at least one high byte (>= 0x80). This avoids mangling valid Unicode.
354
+ const codePoints = Array.from(value, ch => ch.codePointAt(0)!);
355
+ const looksByteString = codePoints.every(cp => cp <= 0xFF);
356
+ const hasHighByte = codePoints.some(cp => cp >= 0x80);
357
+ if (looksByteString && hasHighByte) {
358
+ try {
359
+ const bytes = Uint8Array.from(codePoints);
360
+ const decoded = new TextDecoder('utf-8', { fatal: true }).decode(bytes);
361
+ if (decoded !== value) finalValue = decoded;
362
+ } catch (error) {
363
+ // If UTF-8 conversion fails, keep the original value
364
+ console.warn(`UTF-8 byte reconstruction failed for property "${name}"`, { value, error });
365
+ }
366
+ }
367
+ }
368
+
369
+ // Resolve the value if necessary
370
+ if (resolve) {
371
+ let resolvedExpression = await perspective.getExpression(value);
372
+ if (resolvedExpression) {
373
+ try {
374
+ // Attempt to parse the data as JSON
375
+ finalValue = JSON.parse(resolvedExpression.data);
376
+ } catch (error) {
377
+ // If parsing fails, keep the original data
378
+ finalValue = resolvedExpression.data;
379
+ }
380
+ }
381
+ }
382
+ // Apply transform function if it exists
383
+ const propsMeta = getPropertiesMetadata(instance.constructor);
384
+ const transform = propsMeta[name]?.transform;
385
+ if (transform && typeof transform === "function") {
386
+ finalValue = transform(finalValue);
387
+ }
388
+ return [name, finalValue];
389
+ })
390
+ )
391
+ );
392
+ // Filter out properties that are read-only (getters without setters)
393
+ const writableProps = Object.fromEntries(
394
+ Object.entries(propsObject).filter(([key]) => {
395
+ const descriptor = Object.getOwnPropertyDescriptor(Object.getPrototypeOf(instance), key);
396
+ if (!descriptor) {
397
+ // No descriptor means it's a regular property on the instance, allow it
398
+ return true;
399
+ }
400
+ // Check if it's an accessor descriptor (has get/set) vs data descriptor (has value/writable)
401
+ const isAccessor = descriptor.get !== undefined || descriptor.set !== undefined;
402
+ if (isAccessor) {
403
+ // Accessor descriptor: only allow if it has a setter
404
+ return descriptor.set !== undefined;
405
+ } else {
406
+ // Data descriptor: only allow if writable is not explicitly false
407
+ return descriptor.writable !== false;
408
+ }
409
+ })
410
+ );
411
+ // Assign properties to instance
412
+ Object.assign(instance, writableProps);
413
+ }
414
+
415
+ // ──────────────────────────────────────────────────────────
416
+ // SurrealQL custom getter evaluation
417
+ // ──────────────────────────────────────────────────────────
418
+
419
+ /**
420
+ * Builds a SurrealQL conformance getter for a relation whose `target` model
421
+ * is known but no explicit `getter` string was supplied.
422
+ *
423
+ * The generated getter traverses outgoing links matching the relation's
424
+ * predicate and then filters the target nodes to only those that conform to
425
+ * the target model's shape (required properties / flags).
426
+ *
427
+ * Delegates to the shared `buildConformanceFilter()` utility in decorators.ts
428
+ * so the same logic is used at shape-definition time and at query time.
429
+ *
430
+ * @param relationPredicate - The relation's predicate URI (e.g. "flux://entry_type")
431
+ * @param targetClass - The target model class (result of calling the `target()` thunk)
432
+ * @returns A SurrealQL expression string, or `undefined` if no conformance
433
+ * conditions could be derived from the target model.
434
+ */
435
+ export function buildConformanceGetter(
436
+ relationPredicate: string,
437
+ targetClass: any
438
+ ): string | undefined {
439
+ const filter = buildConformanceFilter(relationPredicate, targetClass);
440
+ if (!filter) {
441
+ const targetName = targetClass?.prototype?.className || targetClass?.name || 'unknown';
442
+ console.warn(`[Ad4mModel] buildConformanceGetter: no conditions found for target "${targetName}".`);
443
+ return undefined;
444
+ }
445
+ return filter.getter;
446
+ }
447
+
448
+ /**
449
+ * Evaluates custom SurrealQL getters for properties and relations on a specific instance.
450
+ *
451
+ * For relations that declare a `target` but no explicit `getter`, a conformance
452
+ * getter is auto-generated from the target model's metadata (unless `filter: false`).
453
+ */
454
+ export async function evaluateCustomGettersForInstance(
455
+ instance: any,
456
+ perspective: PerspectiveProxy,
457
+ metadata: ModelMetadata,
458
+ options?: { requestedProperties?: string[]; include?: Record<string, any> }
459
+ ): Promise<void> {
460
+ const safeBaseExpression = formatSurrealValue(instance.id);
461
+
462
+ // Build projection filter — when requestedProperties is active, only
463
+ // evaluate getters for fields that are requested (or included).
464
+ const projectionActive = options?.requestedProperties && options.requestedProperties.length > 0;
465
+ const projectionSet = projectionActive ? new Set(options!.requestedProperties) : null;
466
+
467
+ // Evaluate property getters
468
+ for (const [propName, propMeta] of Object.entries(metadata.properties)) {
469
+ if (projectionSet && !projectionSet.has(propName)) continue;
470
+ if ((propMeta as any).getter) {
471
+ try {
472
+ // Replace 'Base' placeholder with actual base expression
473
+ const query = (propMeta as any).getter.replace(/Base/g, safeBaseExpression);
474
+ // Query from node table to have graph traversal context
475
+ const result = await perspective.querySurrealDB(
476
+ `SELECT (${query}) AS value FROM node WHERE uri = ${safeBaseExpression}`
477
+ );
478
+ if (result && result.length > 0 && result[0].value !== undefined && result[0].value !== null && result[0].value !== 'None' && result[0].value !== '') {
479
+ instance[propName] = result[0].value;
480
+ }
481
+ } catch (error) {
482
+ console.warn(`Failed to evaluate getter for ${propName}:`, error);
483
+ }
484
+ }
485
+ }
486
+
487
+ // Evaluate relation getters (explicit or auto-generated from target)
488
+ for (const [relName, relMeta] of Object.entries(metadata.relations)) {
489
+ // Skip relations excluded by property projection (unless in include map)
490
+ if (projectionSet && !projectionSet.has(relName) && !(options?.include && relName in options.include)) continue;
491
+ const meta = relMeta as RelationMetadata;
492
+
493
+ // Determine the getter to execute:
494
+ // 1. Explicit `getter` always wins
495
+ // 2. `where` clause → compile DSL to SurrealQL getter
496
+ // 3. If `target` is set and `filter !== false`, auto-generate from target metadata
497
+ // BUT skip auto-generation for reverse relations (belongsToMany / belongsToOne)
498
+ // because buildConformanceGetter traverses outgoing links (->link) which is
499
+ // wrong for reverse relations. Their values are already populated by the
500
+ // reverse link lookup in instancesFromSurrealResult / getData.
501
+ let getter = meta.getter;
502
+ if (!getter && meta.where && meta.direction !== 'reverse') {
503
+ try {
504
+ const TargetClass = meta.target?.();
505
+ const targetMetadata = TargetClass
506
+ ? (TargetClass as any).getModelMetadata?.() ?? null
507
+ : null;
508
+ const conditions = compileWhereClause(meta.where, targetMetadata);
509
+ if (conditions.length > 0) {
510
+ const escapedPred = escapeSurrealString(meta.predicate);
511
+ getter = `(->link[WHERE predicate = '${escapedPred}'].out[WHERE ${conditions.join(' AND ')}].uri)`;
512
+ }
513
+ } catch (e) {
514
+ // Target metadata may not be available yet
515
+ }
516
+ }
517
+ if (!getter && meta.target && meta.filter !== false && meta.direction !== 'reverse') {
518
+ try {
519
+ const TargetClass = meta.target();
520
+ getter = buildConformanceGetter(meta.predicate, TargetClass);
521
+ if (!getter) {
522
+ console.warn(`[Ad4mModel] buildConformanceGetter returned undefined for relation "${relName}" (predicate: "${meta.predicate}")`);
523
+ }
524
+ } catch (e) {
525
+ console.warn(`[Ad4mModel] auto-generation failed for relation "${relName}":`, e);
526
+ }
527
+ }
528
+
529
+ if (getter) {
530
+ try {
531
+ // Replace 'Base' placeholder with actual base expression
532
+ const query = getter.replace(/Base/g, safeBaseExpression);
533
+ const fullQuery = `SELECT (${query}) AS value FROM node WHERE uri = ${safeBaseExpression}`;
534
+ // Query from node table to have graph traversal context
535
+ const result = await perspective.querySurrealDB(fullQuery);
536
+
537
+ if (result && result.length > 0 && result[0].value !== undefined && result[0].value !== null) {
538
+ // Filter out 'None' from relation results
539
+ const value = result[0].value;
540
+ instance[relName] = Array.isArray(value)
541
+ ? value.filter((v: any) => v !== undefined && v !== null && v !== '' && v !== 'None')
542
+ : value;
543
+ }
544
+ } catch (error) {
545
+ console.warn(`Failed to evaluate getter for ${relName}:`, error);
546
+ }
547
+ }
548
+ }
549
+ }
550
+
551
+ /**
552
+ * Hydrates relation fields on instances according to the provided IncludeMap.
553
+ *
554
+ * For each relation listed in `includeMap`, the raw expression-URI strings
555
+ * stored on the instance are replaced with fully-hydrated model instances
556
+ * (fetched via the relation's `target()` class). Nested IncludeMaps are
557
+ * supported for multi-level eager loading.
558
+ *
559
+ * @param modelClass - The model class whose relation metadata to read
560
+ * @param instances - The instances whose relations should be hydrated
561
+ * @param perspective - The perspective to fetch related instances from
562
+ * @param includeMap - Describes which relations to hydrate
563
+ */
564
+ export async function hydrateRelations<T>(
565
+ modelClass: any,
566
+ instances: T[],
567
+ perspective: PerspectiveProxy,
568
+ includeMap: IncludeMap | undefined,
569
+ ): Promise<void> {
570
+ if (!includeMap || Object.keys(includeMap).length === 0) return;
571
+
572
+ const relMeta = getRelationsMetadata(modelClass);
573
+
574
+ for (const [relName, includeValue] of Object.entries(includeMap)) {
575
+ const meta: RelationMetadataEntry | undefined = relMeta[relName];
576
+ if (!meta) {
577
+ console.warn(`include: relation "${relName}" not found in metadata, skipping`);
578
+ continue;
579
+ }
580
+
581
+ const TargetClass = meta.target() as any;
582
+
583
+ // Determine if a RelationSubQuery was supplied (object) vs a plain `true`
584
+ const subQuery: RelationSubQuery | undefined =
585
+ typeof includeValue === 'object' && includeValue !== null
586
+ ? (includeValue as RelationSubQuery)
587
+ : undefined;
588
+ const nestedInclude: IncludeMap | undefined = subQuery?.include;
589
+
590
+ // ── Reverse relations (belongsToOne / belongsToMany) ──────────────────
591
+ // The link goes target→instance, so we query backwards:
592
+ // predicate = meta.predicate, target = inst.id → source is the related id
593
+ if (meta.kind === 'belongsToOne' || meta.kind === 'belongsToMany') {
594
+ // Per-instance reverse lookup (can't batch easily across instances)
595
+ for (const inst of instances) {
596
+ const reverseLinks = await perspective.get(
597
+ new LinkQuery({ predicate: meta.predicate, target: (inst as any).id })
598
+ );
599
+ // Defensive filter: perspective.get may return extra results; ensure
600
+ // we only use links that genuinely point to this instance.
601
+ const sourceIds = reverseLinks
602
+ .filter(l => l.data.target === (inst as any).id)
603
+ .map(l => l.data.source);
604
+
605
+ if (meta.kind === 'belongsToOne') {
606
+ if (sourceIds.length === 0) {
607
+ (inst as any)[relName] = null;
608
+ continue;
609
+ }
610
+ const sourceId = sourceIds[sourceIds.length - 1]; // latest-wins
611
+ try {
612
+ const related = new TargetClass(perspective, sourceId);
613
+ await related.get();
614
+ (inst as any)[relName] = related;
615
+ } catch {
616
+ (inst as any)[relName] = null;
617
+ }
618
+ } else {
619
+ // belongsToMany — return array of hydrated instances
620
+ let hydrated: any[] = [];
621
+
622
+ // If there's a where/order sub-query, delegate to findAll for filtering
623
+ if (subQuery && (subQuery.where || subQuery.order || subQuery.properties)) {
624
+ const whereWithIds: Record<string, any> = {
625
+ id: sourceIds,
626
+ ...(subQuery.where ?? {}),
627
+ };
628
+ hydrated = await TargetClass.findAll(perspective, {
629
+ where: whereWithIds as any,
630
+ ...(subQuery.order && { order: subQuery.order as any }),
631
+ ...(subQuery.properties && { properties: subQuery.properties }),
632
+ });
633
+ } else {
634
+ await Promise.all(sourceIds.map(async (sid: string) => {
635
+ try {
636
+ const related = new TargetClass(perspective, sid);
637
+ await related.get(
638
+ subQuery?.properties ? { properties: subQuery.properties } : undefined
639
+ );
640
+ hydrated.push(related);
641
+ } catch { /* skip */ }
642
+ }));
643
+ }
644
+
645
+ // Apply order (client-side, if not already handled by findAll above)
646
+ if (subQuery?.order && !(subQuery.where || subQuery.properties)) {
647
+ const orderEntries = Object.entries(subQuery.order);
648
+ hydrated = hydrated.sort((a: any, b: any) => {
649
+ for (const [field, dir] of orderEntries) {
650
+ const av = String(a[field] ?? '');
651
+ const bv = String(b[field] ?? '');
652
+ const diff = av.localeCompare(bv);
653
+ if (diff !== 0) return dir === 'DESC' ? -diff : diff;
654
+ }
655
+ return 0;
656
+ });
657
+ }
658
+
659
+ // Apply offset and limit
660
+ if (subQuery?.offset != null || subQuery?.limit != null) {
661
+ const start = subQuery.offset ?? 0;
662
+ const end = subQuery.limit != null ? start + subQuery.limit : undefined;
663
+ hydrated = hydrated.slice(start, end);
664
+ }
665
+
666
+ (inst as any)[relName] = hydrated;
667
+
668
+ // Recurse for nested includes
669
+ if (nestedInclude && hydrated.length > 0) {
670
+ await hydrateRelations(TargetClass, hydrated, perspective, nestedInclude);
671
+ }
672
+ }
673
+ }
674
+ continue; // skip the forward-relation path below
675
+ }
676
+
677
+ // ── Forward relations (hasMany / hasOne) ──────────────────────────────
678
+ // Collect all unique URIs across all instances for batch-friendly lookup.
679
+ // IMPORTANT: We cache each instance's raw value NOW (before the async
680
+ // findAll) so that concurrent getData() calls on the same instance can't
681
+ // overwrite the relation field between the uriSet relation and the
682
+ // post-await assignment loop. Without this cache, a concurrent call
683
+ // can replace the raw URI strings with hydrated model objects, causing
684
+ // the `typeof v === 'string'` check to fail and the array to end up empty.
685
+ const uriSet = new Set<string>();
686
+ const rawCache = new Map<T, any>();
687
+ for (const inst of instances) {
688
+ const raw = (inst as any)[relName];
689
+ rawCache.set(inst, Array.isArray(raw) ? [...raw] : raw);
690
+ if (raw == null) continue;
691
+ if (Array.isArray(raw)) {
692
+ for (const v of raw) {
693
+ if (typeof v === 'string') uriSet.add(v);
694
+ // Handle already-hydrated instances (from a concurrent call)
695
+ else if (v && typeof v === 'object' && typeof v.id === 'string') uriSet.add(v.id);
696
+ }
697
+ } else if (typeof raw === 'string') {
698
+ uriSet.add(raw);
699
+ } else if (raw && typeof raw === 'object' && typeof raw.id === 'string') {
700
+ uriSet.add(raw.id);
701
+ }
702
+ }
703
+
704
+ if (uriSet.size === 0) continue;
705
+
706
+ // Hydrate related instances using findAll to ensure conformance checking.
707
+ // findAll validates model membership via graph traversal (required predicates / flags),
708
+ // so non-conforming linked URIs are silently dropped — matching the documented behaviour.
709
+ const hydrated = new Map<string, any>();
710
+
711
+ const whereWithIds: Record<string, any> = {
712
+ id: Array.from(uriSet),
713
+ ...(subQuery?.where ?? {}),
714
+ };
715
+ const fetchQuery: any = {
716
+ where: whereWithIds,
717
+ ...(subQuery?.order && { order: subQuery.order }),
718
+ ...(subQuery?.properties && { properties: subQuery.properties }),
719
+ };
720
+ const results = await TargetClass.findAll(perspective, fetchQuery);
721
+ for (const result of results) {
722
+ hydrated.set(result.id, result);
723
+ }
724
+
725
+ // Replace raw URIs with hydrated instances on each parent instance.
726
+ // Use the cached raw values captured BEFORE the async findAll to avoid
727
+ // the race condition where a concurrent getData() already replaced the
728
+ // strings with hydrated objects.
729
+ for (const inst of instances) {
730
+ const raw = rawCache.get(inst);
731
+ if (raw == null) continue;
732
+ if (Array.isArray(raw)) {
733
+ // Map URIs → instances; handle both raw strings and already-hydrated objects
734
+ let resolved: any[] = raw
735
+ .map((v: any) => {
736
+ if (typeof v === 'string') {
737
+ return hydrated.has(v) ? hydrated.get(v)! : null;
738
+ }
739
+ // Already a hydrated model instance (from a concurrent call)
740
+ if (v && typeof v === 'object' && typeof v.id === 'string') {
741
+ return hydrated.has(v.id) ? hydrated.get(v.id)! : v;
742
+ }
743
+ return null;
744
+ })
745
+ .filter((v: any): v is any => v !== null);
746
+
747
+ // Per-instance sort (client-side, after filtering)
748
+ if (subQuery?.order) {
749
+ const orderEntries = Object.entries(subQuery.order);
750
+ resolved = resolved.sort((a: any, b: any) => {
751
+ for (const [field, dir] of orderEntries) {
752
+ const av = String(a[field] ?? '');
753
+ const bv = String(b[field] ?? '');
754
+ const diff = av.localeCompare(bv);
755
+ if (diff !== 0) return dir === 'DESC' ? -diff : diff;
756
+ }
757
+ return 0;
758
+ });
759
+ }
760
+
761
+ // Per-instance limit / offset
762
+ if (subQuery?.offset != null || subQuery?.limit != null) {
763
+ const start = subQuery.offset ?? 0;
764
+ const end =
765
+ subQuery.limit != null ? start + subQuery.limit : undefined;
766
+ resolved = resolved.slice(start, end);
767
+ }
768
+
769
+ // Enforce maxCount guard — single-valued relations keep only the last item
770
+ if (meta.maxCount === 1) {
771
+ if (resolved.length > 1) {
772
+ console.warn(
773
+ `include: relation "${relName}" has maxCount 1 but ${resolved.length} values found; keeping the last`,
774
+ );
775
+ }
776
+ (inst as any)[relName] = resolved.length > 0
777
+ ? resolved[resolved.length - 1]
778
+ : null;
779
+ } else {
780
+ (inst as any)[relName] = resolved;
781
+ }
782
+ } else if (typeof raw === 'string' && hydrated.has(raw)) {
783
+ (inst as any)[relName] = hydrated.get(raw);
784
+ } else if (raw && typeof raw === 'object' && typeof raw.id === 'string') {
785
+ // Already-hydrated object — look up refreshed version or keep as-is
786
+ (inst as any)[relName] = hydrated.has(raw.id) ? hydrated.get(raw.id) : raw;
787
+ }
788
+ }
789
+
790
+ // Recurse for nested includes
791
+ if (nestedInclude) {
792
+ const hydratedInstances = Array.from(hydrated.values());
793
+ await hydrateRelations(TargetClass, hydratedInstances, perspective, nestedInclude);
794
+ }
795
+ }
796
+ }