@coasys/ad4m 0.13.0-test-4 → 0.13.0-test-6

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 (72) hide show
  1. package/lib/index.cjs +1507 -1372
  2. package/lib/index.js +1505 -1370
  3. package/lib/src/Ad4mClient.d.ts +1 -1
  4. package/lib/src/Ad4mClient.js +12 -1
  5. package/lib/src/agent/AgentClient.d.ts +16 -0
  6. package/lib/src/agent/AgentClient.js +74 -4
  7. package/lib/src/cache/PersistentCache.d.ts +40 -0
  8. package/lib/src/cache/PersistentCache.js +139 -0
  9. package/lib/src/expression/ExpressionClient.d.ts +8 -0
  10. package/lib/src/expression/ExpressionClient.js +113 -5
  11. package/lib/src/index.d.ts +1 -0
  12. package/lib/src/index.js +1 -0
  13. package/lib/src/model/Ad4mModel.d.ts +20 -7
  14. package/lib/src/model/Ad4mModel.js +102 -108
  15. package/lib/src/model/Ad4mModel.test.js +688 -1434
  16. package/lib/src/model/ModelQueryBuilder.d.ts +6 -6
  17. package/lib/src/model/ModelQueryBuilder.js +29 -20
  18. package/lib/src/model/Subject.js +6 -6
  19. package/lib/src/model/hydration.d.ts +2 -39
  20. package/lib/src/model/hydration.js +2 -260
  21. package/lib/src/model/query-surreal.d.ts +44 -0
  22. package/lib/src/model/query-surreal.js +249 -0
  23. package/lib/src/model/query-utils.d.ts +1 -0
  24. package/lib/src/model/query-utils.js +46 -1
  25. package/lib/src/model/relation-filtering.test.js +15 -15
  26. package/lib/src/model/surreal-utils.d.ts +42 -0
  27. package/lib/src/model/surreal-utils.js +128 -0
  28. package/lib/src/model/types.d.ts +4 -6
  29. package/lib/src/perspectives/PerspectiveClient.d.ts +1 -1
  30. package/lib/src/perspectives/PerspectiveClient.js +15 -13
  31. package/lib/src/perspectives/PerspectiveProxy.d.ts +14 -0
  32. package/lib/src/perspectives/PerspectiveProxy.js +16 -3
  33. package/lib/src/perspectives/PerspectiveResolver.d.ts +1 -0
  34. package/lib/src/perspectives/PerspectiveResolver.js +11 -0
  35. package/lib/src/runtime/RuntimeResolver.d.ts +1 -28
  36. package/lib/src/runtime/RuntimeResolver.js +4 -197
  37. package/lib/src/schema.gql +1 -27
  38. package/lib/src/shacl/SHACLShape.test.js +0 -82
  39. package/package.json +11 -8
  40. package/src/Ad4mClient.test.ts +14 -4
  41. package/src/Ad4mClient.ts +12 -1
  42. package/src/agent/AgentClient.ts +84 -2
  43. package/src/cache/PersistentCache.ts +145 -0
  44. package/src/cache/cache.test.ts +713 -0
  45. package/src/expression/ExpressionClient.ts +137 -3
  46. package/src/index.ts +1 -0
  47. package/src/model/Ad4mModel.test.ts +59 -358
  48. package/src/model/Ad4mModel.ts +112 -108
  49. package/src/model/ModelQueryBuilder.ts +29 -17
  50. package/src/model/hydration.ts +2 -279
  51. package/src/model/query-utils.ts +47 -2
  52. package/src/model/types.ts +5 -6
  53. package/src/perspectives/PerspectiveClient.ts +26 -17
  54. package/src/perspectives/PerspectiveProxy.ts +24 -3
  55. package/lib/src/model/hydration-batch.d.ts +0 -34
  56. package/lib/src/model/hydration-batch.js +0 -147
  57. package/lib/src/model/hydration-batching.test.d.ts +0 -7
  58. package/lib/src/model/hydration-batching.test.js +0 -456
  59. package/lib/src/model/model-manifest.d.ts +0 -41
  60. package/lib/src/model/model-manifest.js +0 -11
  61. package/lib/src/model/query-cache.test.d.ts +0 -1
  62. package/lib/src/model/query-cache.test.js +0 -43
  63. package/lib/src/model/query-sparql-batch.d.ts +0 -17
  64. package/lib/src/model/query-sparql-batch.js +0 -260
  65. package/lib/src/model/query-sparql.test.d.ts +0 -1
  66. package/lib/src/model/query-sparql.test.js +0 -312
  67. package/lib/src/model/subscription-delta.test.d.ts +0 -24
  68. package/lib/src/model/subscription-delta.test.js +0 -180
  69. package/lib/src/model/subscription-pool.d.ts +0 -39
  70. package/lib/src/model/subscription-pool.js +0 -165
  71. package/lib/src/perspectives/PerspectiveClient.test.d.ts +0 -1
  72. package/lib/src/perspectives/PerspectiveClient.test.js +0 -224
@@ -1,23 +1,11 @@
1
1
  /**
2
2
  * hydration.ts — Instance hydration helpers extracted from Ad4mModel.
3
3
  *
4
- * After the Rust model_query pipeline migration (Phases 1-13), most hydration
5
- * logic moved to Rust. This file retains:
4
+ * After the Rust model_query pipeline migration, most hydration logic moved
5
+ * to Rust. This file retains:
6
6
  * - normalizeValue() — snapshot dirty-tracking
7
- * - matchesCondition() — JS-side post-filter (used by evaluateCustomGettersForInstance)
8
- * - evaluateCustomGettersForInstance() — lazy getter evaluation (Ad4mModel.evaluateGetters)
9
- * - buildConformanceGetter() — conformance SPARQL generation for relation getters
10
7
  */
11
8
 
12
- import type { PerspectiveProxy } from "../perspectives/PerspectiveProxy";
13
- import { buildConformanceFilter } from "./decorators";
14
- import { compileWhereClause } from "./query-utils";
15
- import { escapeQueryString } from "../utils";
16
- import type {
17
- RelationMetadata, ModelMetadata,
18
- WhereCondition,
19
- } from "./types";
20
-
21
9
  // ──────────────────────────────────────────────────────────
22
10
  // Pure helpers
23
11
  // ──────────────────────────────────────────────────────────
@@ -36,269 +24,4 @@ export function normalizeValue(value: any): any {
36
24
  return value;
37
25
  }
38
26
 
39
- /**
40
- * Checks if a value matches a where-condition (for post-query filtering).
41
- */
42
- export function matchesCondition(value: any, condition: WhereCondition): boolean {
43
- // Handle array values (IN clause)
44
- if (Array.isArray(condition)) {
45
- return (condition as any[]).includes(value);
46
- }
47
-
48
- // Handle operator object
49
- if (typeof condition === 'object' && condition !== null) {
50
- const ops = condition as any;
51
-
52
- // Special case: 'not' operator (exclusive with other operators)
53
- if (ops.not !== undefined) {
54
- if (Array.isArray(ops.not)) {
55
- return !(ops.not as any[]).includes(value);
56
- } else {
57
- return value !== ops.not;
58
- }
59
- }
60
-
61
- // Special case: 'between' operator (inclusive range, exclusive with gt/gte/lt/lte)
62
- if (ops.between !== undefined && Array.isArray(ops.between) && ops.between.length === 2) {
63
- return value >= ops.between[0] && value <= ops.between[1];
64
- }
65
-
66
- // For all other operators (gt, gte, lt, lte, contains), we need to check ALL of them
67
- // and return true only if ALL conditions are satisfied
68
- let allConditionsMet = true;
69
-
70
- if (ops.gt !== undefined) {
71
- allConditionsMet = allConditionsMet && (value > ops.gt);
72
- }
73
-
74
- if (ops.gte !== undefined) {
75
- allConditionsMet = allConditionsMet && (value >= ops.gte);
76
- }
77
-
78
- if (ops.lt !== undefined) {
79
- allConditionsMet = allConditionsMet && (value < ops.lt);
80
- }
81
-
82
- if (ops.lte !== undefined) {
83
- allConditionsMet = allConditionsMet && (value <= ops.lte);
84
- }
85
-
86
- if (ops.contains !== undefined) {
87
- if (typeof value === 'string') {
88
- allConditionsMet = allConditionsMet && value.includes(String(ops.contains));
89
- } else if (Array.isArray(value)) {
90
- allConditionsMet = allConditionsMet && value.includes(ops.contains);
91
- } else {
92
- allConditionsMet = false;
93
- }
94
- }
95
-
96
- return allConditionsMet;
97
- }
98
-
99
- // Simple equality
100
- return value === condition;
101
- }
102
-
103
- // ──────────────────────────────────────────────────────────
104
- // SPARQL custom getter evaluation
105
- // ──────────────────────────────────────────────────────────
106
-
107
- /**
108
- * Builds a SPARQL conformance getter for a relation whose `target` model
109
- * is known but no explicit `getter` string was supplied.
110
- *
111
- * The generated getter traverses outgoing links matching the relation's
112
- * predicate and then filters the target nodes to only those that conform to
113
- * the target model's shape (required properties / flags).
114
- *
115
- * Delegates to the shared `buildConformanceFilter()` utility in decorators.ts
116
- * so the same logic is used at shape-definition time and at query time.
117
- *
118
- * @param relationPredicate - The relation's predicate URI (e.g. "flux://entry_type")
119
- * @param targetClass - The target model class (result of calling the `target()` thunk)
120
- * @returns A SPARQL expression string, or `undefined` if no conformance
121
- * conditions could be derived from the target model.
122
- */
123
- export function buildConformanceGetter(
124
- relationPredicate: string,
125
- targetClass: any
126
- ): string | undefined {
127
- const filter = buildConformanceFilter(relationPredicate, targetClass);
128
- if (!filter) {
129
- const targetName = targetClass?.prototype?.className || targetClass?.name || 'unknown';
130
- console.warn(`[Ad4mModel] buildConformanceGetter: no conditions found for target "${targetName}".`);
131
- return undefined;
132
- }
133
- return filter.getter;
134
- }
135
-
136
- /**
137
- * Evaluates custom SurrealQL getters for properties and relations on a specific instance.
138
- *
139
- * For relations that declare a `target` but no explicit `getter`, a conformance
140
- * getter is auto-generated from the target model's metadata (unless `filter: false`).
141
- */
142
-
143
- export async function evaluateCustomGettersForInstance(
144
- instance: any,
145
- perspective: PerspectiveProxy,
146
- metadata: ModelMetadata,
147
- options?: { requestedProperties?: string[]; include?: Record<string, any>; skipPropertyGetters?: boolean }
148
- ): Promise<void> {
149
- const safeBaseExpression = `<${instance.id}>`;
150
-
151
- // Build projection filter — when requestedProperties is active, only
152
- // evaluate getters for fields that are requested (or included).
153
- const projectionActive = options?.requestedProperties && options.requestedProperties.length > 0;
154
- const projectionSet = projectionActive ? new Set(options!.requestedProperties) : null;
155
-
156
- // Evaluate property getters (skip when caller only wants relation type-filtering)
157
- if (!options?.skipPropertyGetters) {
158
- for (const [propName, propMeta] of Object.entries(metadata.properties)) {
159
- if (projectionSet && !projectionSet.has(propName)) continue;
160
- if ((propMeta as any).getter) {
161
- try {
162
- const rawGetter = (propMeta as any).getter;
163
- const getterWithBase = rawGetter.replace(/\?source\b/g, `<${instance.id}>`).replace(/<Base>/g, `<${instance.id}>`).replace(/Base/g, `<${instance.id}>`);
164
-
165
- // If the getter is already SPARQL (starts with SELECT/ASK/CONSTRUCT), execute directly
166
- const trimmed = getterWithBase.trim().toUpperCase();
167
- if (trimmed.startsWith('SELECT') || trimmed.startsWith('ASK') || trimmed.startsWith('CONSTRUCT')) {
168
- const result = await perspective.querySparql(getterWithBase);
169
- if (trimmed.startsWith('ASK')) {
170
- instance[propName] = result === true || result === 'true';
171
- } else if (result && result.length > 0) {
172
- // Get first binding's first value
173
- const firstRow = result[0];
174
- const firstKey = Object.keys(firstRow)[0];
175
- const val = firstRow[firstKey]?.value ?? firstRow[firstKey];
176
- if (val !== undefined && val !== null && val !== 'None' && val !== '') {
177
- instance[propName] = val;
178
- }
179
- }
180
- } else {
181
- // Legacy SurrealDB-style getter — safety guard for getters that don't match
182
- // SPARQL patterns (SELECT/ASK). Logs a warning but does not crash.
183
- console.warn(`Unsupported legacy getter syntax for property ${propName} — use native SPARQL (SELECT/ASK): ${rawGetter.slice(0, 100)}`);
184
- }
185
- } catch (error) {
186
- console.warn(`Failed to evaluate getter for ${propName}:`, error);
187
- }
188
- }
189
- }
190
- } // end skipPropertyGetters guard
191
-
192
- // Evaluate relation getters (explicit or auto-generated from target)
193
- for (const [relName, relMeta] of Object.entries(metadata.relations)) {
194
- // Skip relations excluded by property projection (unless in include map)
195
- if (projectionSet && !projectionSet.has(relName) && !(options?.include && relName in options.include)) continue;
196
- const meta = relMeta as RelationMetadata;
197
-
198
- // Determine the getter to execute:
199
- // 1. Explicit `getter` always wins
200
- // 2. If `target` is set and `filter !== false`, auto-generate conformance getter
201
- // BUT skip auto-generation for reverse relations (belongsToMany / belongsToOne)
202
- // because buildConformanceGetter traverses outgoing links which is wrong for
203
- // reverse relations. Their values are already populated by the reverse link
204
- // lookup in instancesFromQueryResult / getData.
205
- let getter = meta.getter;
206
- if (!getter && meta.where && meta.direction !== 'reverse') {
207
- try {
208
- const TargetClass = meta.target?.();
209
- const targetMetadata = TargetClass
210
- ? (TargetClass as any).getModelMetadata?.() ?? null
211
- : null;
212
-
213
- // Check if all where conditions can be SPARQL-filtered.
214
- // literal-resolved properties store signed expressions (literal:json:{…}),
215
- // not raw literal:string: IRIs, so SPARQL exact-match fails for them.
216
- let allSparqlFilterable = true;
217
- if (targetMetadata) {
218
- for (const propName of Object.keys(meta.where)) {
219
- if (['id', 'author', 'timestamp'].includes(propName)) continue;
220
- const propMeta = targetMetadata.properties[propName];
221
- if (propMeta && (!propMeta.resolveLanguage || propMeta.resolveLanguage === 'literal')) {
222
- allSparqlFilterable = false;
223
- break;
224
- }
225
- }
226
- } else {
227
- allSparqlFilterable = false;
228
- }
229
27
 
230
- if (allSparqlFilterable) {
231
- const conditions = compileWhereClause(meta.where, targetMetadata);
232
- if (conditions.length > 0) {
233
- const escapedPredicate = escapeQueryString(meta.predicate);
234
- getter = `SELECT ?target WHERE { <Base> <${escapedPredicate}> ?target . ${conditions.join(' ')} }`;
235
- }
236
- }
237
- // If not filterable, fall through to buildConformanceGetter + JS post-filter below
238
- } catch (e) {
239
- console.warn(`[Ad4mModel] where-clause compilation failed for relation "${relName}":`, e);
240
- }
241
- }
242
- if (!getter && meta.target && meta.filter !== false && meta.direction !== 'reverse') {
243
- try {
244
- const TargetClass = meta.target();
245
- getter = buildConformanceGetter(meta.predicate, TargetClass);
246
- if (!getter) {
247
- console.warn(`[Ad4mModel] buildConformanceGetter returned undefined for relation "${relName}" (predicate: "${meta.predicate}")`);
248
- }
249
- } catch (e) {
250
- console.warn(`[Ad4mModel] auto-generation failed for relation "${relName}":`, e);
251
- }
252
- }
253
-
254
- if (getter) {
255
- try {
256
- const getterWithBase = getter.replace(/\?source\b/g, `<${instance.id}>`).replace(/<Base>/g, `<${instance.id}>`).replace(/\bBase\b/g, `<${instance.id}>`);
257
- const trimmed = getterWithBase.trim().toUpperCase();
258
-
259
- if (trimmed.startsWith('SELECT') || trimmed.startsWith('ASK') || trimmed.startsWith('CONSTRUCT')) {
260
- // Native SPARQL getter — execute directly
261
- const result = await perspective.querySparql(getterWithBase);
262
- if (result && result.length > 0) {
263
- const values = result.map((r: any) => {
264
- const firstKey = Object.keys(r)[0];
265
- return r[firstKey]?.value ?? r[firstKey];
266
- }).filter((v: any) => v !== undefined && v !== null && v !== '' && v !== 'None');
267
- instance[relName] = values;
268
- }
269
- } else {
270
- // Legacy SurrealDB-style getter — safety guard for relation getters that don't
271
- // match SPARQL patterns (SELECT/ASK). Logs a warning but does not crash.
272
- console.warn(`Unsupported legacy getter syntax for relation ${relName} — use native SPARQL (SELECT/ASK): ${getter.slice(0, 100)}`);
273
- }
274
- } catch (error) {
275
- console.warn(`Failed to evaluate getter for ${relName}:`, error);
276
- }
277
- }
278
-
279
- // JS post-filter for where conditions that couldn't be SPARQL-filtered
280
- // (e.g. literal-resolved properties storing signed expressions)
281
- const currentValues = instance[relName];
282
- if (meta.where && Array.isArray(currentValues) && currentValues.length > 0) {
283
- const TargetClass = meta.target?.();
284
- if (TargetClass) {
285
- const filtered: string[] = [];
286
- for (const targetId of currentValues) {
287
- try {
288
- const inst = new (TargetClass as any)(perspective, targetId);
289
- await inst.get();
290
- let matches = true;
291
- for (const [prop, expected] of Object.entries(meta.where)) {
292
- if ((inst as any)[prop] !== expected) { matches = false; break; }
293
- }
294
- if (matches) filtered.push(targetId);
295
- } catch {
296
- // If we can't hydrate, keep the value (conservative)
297
- filtered.push(targetId);
298
- }
299
- }
300
- instance[relName] = filtered;
301
- }
302
- }
303
- }
304
- }
@@ -53,7 +53,7 @@ export function formatQueryValue(value: any): string {
53
53
  export function buildWhereCondition(
54
54
  predicate: string,
55
55
  condition: WhereCondition,
56
- opts?: { resolveLanguage?: string },
56
+ opts?: { resolveLanguage?: string; varIndex?: number },
57
57
  ): string {
58
58
  const escapedPredicate = escapeQueryString(predicate);
59
59
  // For literal-resolved properties, we match against the raw IRI (which is a literal: URI)
@@ -62,6 +62,8 @@ export function buildWhereCondition(
62
62
  // For language-resolved properties, values are plain URIs
63
63
  const isLiteral = !opts?.resolveLanguage || opts.resolveLanguage === 'literal';
64
64
 
65
+ const varSuffix = opts?.varIndex ?? 0;
66
+
65
67
  function formatValue(v: any): string {
66
68
  if (typeof v === 'string') {
67
69
  return isLiteral
@@ -72,8 +74,45 @@ export function buildWhereCondition(
72
74
  return `<literal:string:${v}>`;
73
75
  }
74
76
 
77
+ /**
78
+ * For literal properties, generate a FILTER-based match that handles both
79
+ * the raw value and the literal-encoded value. This mirrors the Rust
80
+ * `build_projection_where_patterns` approach which uses:
81
+ * FILTER(STR(?var) = "value" || STR(?var) = "literal:string:encodedValue")
82
+ * This is more robust than exact IRI matching because it handles edge cases
83
+ * where the stored format might vary.
84
+ */
85
+ function formatLiteralFilter(varName: string, v: any): string {
86
+ const raw = escapeQueryString(String(v));
87
+ const encoded = encodeURIComponent(String(v))
88
+ .replace(/!/g, '%21')
89
+ .replace(/'/g, '%27')
90
+ .replace(/\(/g, '%28')
91
+ .replace(/\)/g, '%29')
92
+ .replace(/\*/g, '%2A');
93
+ if (typeof v === 'string') {
94
+ return `FILTER(STR(${varName}) = "${raw}" || STR(${varName}) = "literal:string:${encoded}")`;
95
+ } else if (typeof v === 'number') {
96
+ return `FILTER(STR(${varName}) = "${v}" || STR(${varName}) = "literal:number:${v}")`;
97
+ } else if (typeof v === 'boolean') {
98
+ return `FILTER(STR(${varName}) = "${v}" || STR(${varName}) = "literal:boolean:${v}")`;
99
+ }
100
+ return `FILTER(STR(${varName}) = "${raw}")`;
101
+ }
102
+
75
103
  if (Array.isArray(condition)) {
76
104
  // Array values → FILTER IN
105
+ if (isLiteral) {
106
+ const varName = `?_wc${varSuffix}`;
107
+ const inValues = (condition as any[]).flatMap(v => {
108
+ const raw = escapeQueryString(String(v));
109
+ const encoded = encodeURIComponent(String(v))
110
+ .replace(/!/g, '%21').replace(/'/g, '%27')
111
+ .replace(/\(/g, '%28').replace(/\)/g, '%29').replace(/\*/g, '%2A');
112
+ return [`"${raw}"`, `"literal:string:${encoded}"`];
113
+ }).join(', ');
114
+ return `?target <${escapedPredicate}> ${varName} . FILTER(STR(${varName}) IN (${inValues}))`;
115
+ }
77
116
  const formattedValues = (condition as any[]).map(formatValue).join(', ');
78
117
  return `FILTER EXISTS { ?target <${escapedPredicate}> ?_val . FILTER(?_val IN (${formattedValues})) }`;
79
118
  } else if (typeof condition === 'object' && condition !== null) {
@@ -112,6 +151,12 @@ export function buildWhereCondition(
112
151
  return parts.join(' ');
113
152
  } else {
114
153
  // Simple equality
154
+ if (isLiteral) {
155
+ // Use FILTER matching (mirrors Rust build_projection_where_patterns)
156
+ // to handle both raw values and literal-encoded IRIs robustly.
157
+ const varName = `?_wc${varSuffix}`;
158
+ return `?target <${escapedPredicate}> ${varName} . ${formatLiteralFilter(varName, condition)}`;
159
+ }
115
160
  return `?target <${escapedPredicate}> ${formatValue(condition)} .`;
116
161
  }
117
162
  }
@@ -154,7 +199,7 @@ export function compileWhereClause(
154
199
  predicate = propertyName;
155
200
  }
156
201
 
157
- const cond = buildWhereCondition(predicate, condition, { resolveLanguage });
202
+ const cond = buildWhereCondition(predicate, condition, { resolveLanguage, varIndex: conditions.length });
158
203
  if (cond) {
159
204
  conditions.push(cond);
160
205
  }
@@ -127,12 +127,11 @@ export type Query = {
127
127
  count?: boolean;
128
128
  /**
129
129
  * When true, SPARQL property getters (@Property with `getter`) ARE evaluated
130
- * during collection hydration. By default, collection queries skip getter
131
- * evaluation for performance — getters run only on single-instance get().
130
+ * during collection hydration. Defaults to true — getters run post-pagination
131
+ * via batched VALUES queries so the cost is O(getters), not O(instances × getters).
132
132
  *
133
- * Use this when you need getter-backed properties (e.g. `replyingTo`,
134
- * `isPopular`) in a list query. For most list/feed UIs, leave this off
135
- * and use `Ad4mModel.evaluateGetters()` on visible items only.
133
+ * Set to false to explicitly skip getter evaluation for performance-sensitive
134
+ * queries where getter-backed properties are not needed.
136
135
  */
137
136
  deepQuery?: boolean;
138
137
  };
@@ -161,7 +160,7 @@ export type GetOptions = Pick<Query, 'include' | 'properties'>;
161
160
  // Result types
162
161
  // ---------------------------------------------------------------------------
163
162
 
164
- export type AllInstancesResult = { AllInstances: Ad4mModel[]; TotalCount?: number; isInit?: boolean };
163
+ export type AllInstancesResult = { AllInstances: Ad4mModel[]; TotalCount?: number };
165
164
  export type ResultsWithTotalCount<T> = { results: T[]; totalCount?: number };
166
165
  export type PaginationResult<T> = { results: T[]; totalCount?: number; pageSize: number; pageNumber: number };
167
166
 
@@ -16,14 +16,8 @@ export type UuidCallback = (uuid: string) => null
16
16
  export type LinkCallback = (link: LinkExpression) => null
17
17
  export type SyncStateChangeCallback = (state: PerspectiveState) => null
18
18
 
19
- function normalizeQueryResult(raw: unknown, errorContext: string): { result: AllInstancesResult; isInit: boolean } {
19
+ function normalizeQueryResult(raw: unknown, errorContext: string): AllInstancesResult {
20
20
  let finalResult: unknown = raw
21
- let isInit = false
22
-
23
- if (typeof finalResult === 'string' && finalResult.startsWith('#init#')) {
24
- finalResult = finalResult.substring(6)
25
- isInit = true
26
- }
27
21
 
28
22
  if (typeof finalResult === 'string') {
29
23
  try {
@@ -33,11 +27,7 @@ function normalizeQueryResult(raw: unknown, errorContext: string): { result: All
33
27
  }
34
28
  }
35
29
 
36
- if (isInit && typeof finalResult === 'object' && finalResult !== null) {
37
- (finalResult as Record<string, unknown>).isInit = true
38
- }
39
-
40
- return { result: finalResult as AllInstancesResult, isInit }
30
+ return finalResult as AllInstancesResult
41
31
  }
42
32
 
43
33
  export class PerspectiveClient {
@@ -131,13 +121,13 @@ export class PerspectiveClient {
131
121
  return JSON.parse(result)
132
122
  }
133
123
 
134
- async subscribeQuery(uuid: string, query: string): Promise<{ subscriptionId: string, result: AllInstancesResult, isInit?: boolean }> {
124
+ async subscribeQuery(uuid: string, query: string): Promise<{ subscriptionId: string, result: AllInstancesResult }> {
135
125
  const response = await this.#apiClient.call<{ subscriptionId: string, result: unknown }>(
136
126
  'perspective.subscribeQuery', { uuid, query }
137
127
  )
138
128
  const { subscriptionId, result } = response
139
- const normalized = normalizeQueryResult(result, 'Error parsing subscribeQuery result:')
140
- return { subscriptionId, result: normalized.result, isInit: normalized.isInit }
129
+ const parsed = normalizeQueryResult(result, 'Error parsing subscribeQuery result:')
130
+ return { subscriptionId, result: parsed }
141
131
  }
142
132
 
143
133
  async perspectiveKeepAliveQuery(uuid: string, subscriptionId: string): Promise<boolean> {
@@ -161,8 +151,8 @@ export class PerspectiveClient {
161
151
  const eventSubscriptionId = event.subscriptionId || event.subscription_id
162
152
  if (eventSubscriptionId !== subscriptionId) return
163
153
 
164
- const normalized = normalizeQueryResult(event.result, 'Error parsing query subscription:')
165
- onData(normalized.result)
154
+ const parsed = normalizeQueryResult(event.result, 'Error parsing query subscription:')
155
+ onData(parsed)
166
156
  }
167
157
  )
168
158
  this.#querySubscriptionUnsubscribers.set(subscriptionId, unsub)
@@ -193,6 +183,25 @@ export class PerspectiveClient {
193
183
  return JSON.parse(resultJson)
194
184
  }
195
185
 
186
+ async evaluateGetters(
187
+ uuid: string,
188
+ className: string,
189
+ instanceIds: string[],
190
+ shapeJson: string,
191
+ propertyNames?: string[],
192
+ ): Promise<Record<string, Record<string, any>>> {
193
+ const resultJson = await this.#apiClient.call<string>(
194
+ 'perspective.evaluateGetters', {
195
+ uuid,
196
+ class_name: className,
197
+ instance_ids: instanceIds,
198
+ shape_json: shapeJson,
199
+ ...(propertyNames && { property_names: propertyNames }),
200
+ }
201
+ )
202
+ return JSON.parse(resultJson)
203
+ }
204
+
196
205
  async modelSubscribe(uuid: string, className: string, queryJson: string, shapeJson?: string): Promise<{ subscriptionId: string, result: any }> {
197
206
  const response = await this.#apiClient.call<{ subscription_id: string, result: string }>(
198
207
  'perspective.modelSubscribe', { uuid, class_name: className, query_json: queryJson, shape_json: shapeJson }
@@ -171,9 +171,6 @@ export class QuerySubscriptionProxy {
171
171
  this.#initReject = undefined;
172
172
  }
173
173
 
174
- // Skip duplicate init messages
175
- if (updateResult.isInit && this.#latestResult) return;
176
-
177
174
  this.#latestResult = updateResult;
178
175
  this.#notifyCallbacks(updateResult);
179
176
  }
@@ -612,6 +609,30 @@ export class PerspectiveProxy {
612
609
  return await this.#client.modelQuery(this.#handle.uuid, className, queryJson, shapeJson);
613
610
  }
614
611
 
612
+ /**
613
+ * Evaluate property getters for a batch of instances in a single RPC call.
614
+ * Returns a map of `{ instanceId: { prop: value, ... } }`.
615
+ *
616
+ * Use this instead of `Ad4mModel.evaluateGetters()` for lazy-loading
617
+ * getter-backed properties on visible items (e.g. `replyingTo` on messages).
618
+ *
619
+ * @param className - The model class name (e.g. "Message")
620
+ * @param instanceIds - Array of instance base expression URIs
621
+ * @param shapeJson - Shape metadata JSON from the model class
622
+ * @param propertyNames - Optional subset of property names to evaluate
623
+ * @returns Map of instance ID → evaluated property values
624
+ */
625
+ async evaluateGetters(
626
+ className: string,
627
+ instanceIds: string[],
628
+ shapeJson: string,
629
+ propertyNames?: string[],
630
+ ): Promise<Record<string, Record<string, any>>> {
631
+ return await this.#client.evaluateGetters(
632
+ this.#handle.uuid, className, instanceIds, shapeJson, propertyNames,
633
+ );
634
+ }
635
+
615
636
  /**
616
637
  * Subscribe to model query changes. Builds trigger SPARQL from the model shape
617
638
  * internally in Rust, registers a subscription, runs the initial query, and
@@ -1,34 +0,0 @@
1
- /**
2
- * Batch hydration for SPARQL batch query results.
3
- *
4
- * Takes the flat rows returned by `buildBatchSPARQLQuery()` (each tagged
5
- * with ?depth, ?parentBase, ?relationName) and reconstructs a tree of
6
- * model instances.
7
- *
8
- * @module
9
- */
10
- import type { IncludeMap } from "./types";
11
- /**
12
- * A row returned by the batch SPARQL query.
13
- */
14
- interface BatchRow {
15
- depth: string;
16
- parentBase: string;
17
- relationName: string;
18
- source: string;
19
- predicate: string;
20
- target: string;
21
- author: string;
22
- timestamp: string;
23
- }
24
- /**
25
- * Hydrate batch SPARQL results into a tree of model instances.
26
- *
27
- * @param rows - Flat rows from the batch SPARQL query
28
- * @param rootClass - The root model class (extends Ad4mModel)
29
- * @param includeMap - The include specification from the query
30
- * @param perspective - The PerspectiveProxy for creating instances
31
- * @returns Array of hydrated root instances with relations populated
32
- */
33
- export declare function hydrateBatchResult<T>(rows: BatchRow[], rootClass: any, includeMap: IncludeMap, perspective: any): Promise<T[]>;
34
- export {};