@coasys/ad4m 0.13.0-postmessage-ws-proxy.0 → 0.13.0-postmessage-ws-proxy.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 (33) hide show
  1. package/lib/index.cjs +564 -461
  2. package/lib/index.js +561 -462
  3. package/lib/src/index.d.ts +1 -0
  4. package/lib/src/index.js +1 -0
  5. package/lib/src/model/Ad4mModel.d.ts +9 -17
  6. package/lib/src/model/Ad4mModel.js +34 -148
  7. package/lib/src/model/ModelQueryBuilder.d.ts +5 -10
  8. package/lib/src/model/ModelQueryBuilder.js +8 -14
  9. package/lib/src/model/shacl-gen.js +115 -46
  10. package/lib/src/model/types.d.ts +138 -3
  11. package/lib/src/perspectives/PerspectiveClient.d.ts +4 -4
  12. package/lib/src/perspectives/PerspectiveClient.js +5 -6
  13. package/lib/src/perspectives/PerspectiveProxy.d.ts +8 -7
  14. package/lib/src/perspectives/PerspectiveProxy.js +10 -9
  15. package/lib/src/perspectives/SparqlBindings.d.ts +47 -0
  16. package/lib/src/perspectives/SparqlBindings.js +65 -0
  17. package/lib/src/shacl/SHACLShape.d.ts +18 -0
  18. package/lib/src/shacl/SHACLShape.js +83 -0
  19. package/package.json +8 -11
  20. package/src/index.ts +1 -0
  21. package/src/model/Ad4mModel.test.ts +23 -64
  22. package/src/model/Ad4mModel.ts +52 -159
  23. package/src/model/ModelQueryBuilder.ts +17 -23
  24. package/src/model/relation-filtering.test.ts +46 -39
  25. package/src/model/shacl-gen.ts +122 -53
  26. package/src/model/shacl-roundtrip.test.ts +197 -0
  27. package/src/model/types-typed-query.test.ts +360 -0
  28. package/src/model/types.ts +194 -3
  29. package/src/perspectives/PerspectiveClient.ts +6 -8
  30. package/src/perspectives/PerspectiveProxy.ts +13 -13
  31. package/src/perspectives/SparqlBindings.ts +79 -0
  32. package/src/shacl/SHACLShape.test.ts +110 -0
  33. package/src/shacl/SHACLShape.ts +125 -0
@@ -3,7 +3,7 @@ import { Link } from "../links/Links";
3
3
  import { LinkQuery } from "../perspectives/LinkQuery";
4
4
  import { PerspectiveProxy } from "../perspectives/PerspectiveProxy";
5
5
  import { makeRandomId } from "./util";
6
- import { getPropertiesMetadata, getRelationsMetadata, buildConformanceFilter, setPropertyRegistryEntry, setRelationRegistryEntry, Model } from "./decorators";
6
+ import { getPropertiesMetadata, getRelationsMetadata, setPropertyRegistryEntry, setRelationRegistryEntry, Model } from "./decorators";
7
7
  import type { PropertyOptions, PropertyMetadataEntry, RelationMetadataEntry } from "./decorators";
8
8
  import { formatQueryValue, compileWhereClause } from "./query-utils";
9
9
  import { resolveParentPredicate } from "./query-common";
@@ -21,6 +21,7 @@ import type {
21
21
  GetOptions, AllInstancesResult, ResultsWithTotalCount,
22
22
  PaginationResult, PropertyMetadata, RelationMetadata, ModelMetadata,
23
23
  IncludeProjection,
24
+ TypedQuery, IncludeExtras, IncludeOf,
24
25
  } from "./types";
25
26
 
26
27
 
@@ -68,54 +69,6 @@ function defaultFileDecode(resolved: unknown): unknown {
68
69
  // Helpers for Rust-side include resolution
69
70
  // ---------------------------------------------------------------------------
70
71
 
71
- /**
72
- * Recursively enrich relation metadata in the shape with target class shapes
73
- * so the Rust endpoint can resolve includes in-process (no extra GraphQL
74
- * round-trips per relation).
75
- */
76
- function enrichShapeForIncludes(
77
- metadata: ModelMetadata,
78
- include: IncludeMap,
79
- allRelMeta: Record<string, RelationMetadataEntry>,
80
- ): void {
81
- for (const [relName, includeVal] of Object.entries(include)) {
82
- if (!includeVal) continue;
83
- const meta = allRelMeta[relName];
84
- if (!meta?.target) continue;
85
-
86
- const TargetClass = meta.target() as typeof Ad4mModel;
87
- // Deep-copy so we don't mutate the cached metadata
88
- const targetMeta = JSON.parse(JSON.stringify(TargetClass.getModelMetadata()));
89
-
90
- // Ensure the relation is in metadata.relations (fallback for edge cases)
91
- if (!metadata.relations[relName]) {
92
- metadata.relations[relName] = {
93
- name: relName,
94
- predicate: meta.predicate,
95
- direction:
96
- meta.kind === 'belongsToMany' || meta.kind === 'belongsToOne'
97
- ? 'reverse'
98
- : 'forward',
99
- };
100
- }
101
- const rel = metadata.relations[relName] as any;
102
- rel.kind = meta.kind;
103
- rel.maxCount = meta.maxCount;
104
- rel.targetShape = targetMeta;
105
- rel.targetClassName = targetMeta.className;
106
-
107
- // Recurse for nested includes
108
- const nested =
109
- typeof includeVal === 'object' && includeVal !== null
110
- ? (includeVal as any).include
111
- : undefined;
112
- if (nested) {
113
- const targetRelMeta = getRelationsMetadata(TargetClass as any);
114
- enrichShapeForIncludes(targetMeta, nested, targetRelMeta);
115
- }
116
- }
117
- }
118
-
119
72
  /**
120
73
  * Construct a model class instance from a plain JSON object returned by the
121
74
  * Rust endpoint. Recursively converts included relation values (which come
@@ -867,13 +820,14 @@ export class Ad4mModel {
867
820
 
868
821
  /**
869
822
  * Build the JSON parameters needed for a model query/subscription endpoint.
870
- * Returns the className, queryJson, and shapeJson that the Rust executor expects.
823
+ * Returns the className and queryJson that the Rust executor expects.
824
+ * Shape resolution happens server-side from the perspective's SHACL triples.
871
825
  * @internal
872
826
  */
873
827
  static prepareModelQueryParams(
874
828
  query: Query = {},
875
829
  classNameOverride?: string | null,
876
- ): { className: string; queryJson: string; shapeJson: string; metadata: ModelMetadata } {
830
+ ): { className: string; queryJson: string; metadata: ModelMetadata } {
877
831
  const metadata = this.getModelMetadata();
878
832
  const className = classNameOverride || metadata.className;
879
833
 
@@ -909,16 +863,18 @@ export class Ad4mModel {
909
863
  }
910
864
  if (Object.keys(normalIncludes).length > 0) queryInput.include = normalIncludes;
911
865
  if (Object.keys(projections).length > 0) {
912
- // Enrich projections with target shapes so Rust can apply where clause filtering
866
+ // Tag each projection with its target class name so the executor can
867
+ // resolve the target shape through its in-memory cache when applying
868
+ // projection where-clause filters.
913
869
  const allRelMeta = getRelationsMetadata(this as any);
914
870
  for (const [, proj] of Object.entries(projections)) {
915
871
  const relMeta = allRelMeta[proj.from];
916
- if (!proj.targetShape && relMeta?.target) {
872
+ if (!proj.targetClassName && relMeta?.target) {
917
873
  try {
918
874
  const TargetClass = relMeta.target();
919
875
  const targetMeta = (TargetClass as any).getModelMetadata?.();
920
- if (targetMeta) {
921
- proj.targetShape = targetMeta;
876
+ if (targetMeta?.className) {
877
+ proj.targetClassName = targetMeta.className;
922
878
  }
923
879
  } catch (e) { console.debug(`prepareModelQueryParams: target class unavailable for projection:`, e); }
924
880
  }
@@ -935,59 +891,13 @@ export class Ad4mModel {
935
891
  if (query.count !== undefined) queryInput.count = query.count;
936
892
  queryInput.deepQuery = query.deepQuery ?? true;
937
893
 
938
- if (queryInput.include) {
939
- const allRelMeta = getRelationsMetadata(this as any);
940
- enrichShapeForIncludes(metadata, queryInput.include, allRelMeta);
941
- }
942
-
943
- // Pre-compute conformance getters for Rust-side evaluation.
944
- // Where clauses are NOT compiled into getter SPARQL because stored
945
- // property values are signed expression envelopes (literal:json:...),
946
- // not simple literal:string:X values. Instead, where clauses are
947
- // attached as metadata for Rust-side post-evaluation filtering.
948
- {
949
- const allRelMeta = getRelationsMetadata(this as any);
950
- for (const [relName, relMeta] of Object.entries(metadata.relations)) {
951
- const rel = relMeta as any;
952
- if (rel.getter || rel.direction === 'reverse' || rel.filter === false) continue;
953
- const meta = allRelMeta[relName];
954
- if (!meta?.target) continue;
955
- try {
956
- const TargetClass = meta.target();
957
- const filter = buildConformanceFilter(meta.predicate, TargetClass);
958
-
959
- if (filter) {
960
- rel.getter = filter.getter;
961
- }
962
-
963
- // Attach where-clause metadata for Rust-side post-getter filtering
964
- if (rel.where) {
965
- try {
966
- const targetMetadata = (TargetClass as any).getModelMetadata?.() ?? null;
967
- if (targetMetadata) {
968
- const predicates: Record<string, string> = {};
969
- for (const propName of Object.keys(rel.where)) {
970
- if (['id', 'author', 'timestamp'].includes(propName)) continue;
971
- const propMeta = targetMetadata.properties[propName];
972
- if (propMeta?.predicate) {
973
- predicates[propName] = propMeta.predicate;
974
- }
975
- }
976
- if (Object.keys(predicates).length > 0) {
977
- rel.whereFilter = rel.where;
978
- rel.wherePredicates = predicates;
979
- }
980
- }
981
- } catch (e) { console.debug(`prepareModelQueryParams: target metadata unavailable for relation '${relName}':`, e); }
982
- }
983
- } catch (e) { console.debug(`prepareModelQueryParams: target class unavailable for relation '${relName}':`, e); }
984
- }
985
- }
894
+ // Conformance getters, where filters, and target shapes for includes
895
+ // are all resolved by the executor from the perspective's SHACL triples
896
+ // — no client-side pre-computation is needed any more.
986
897
 
987
898
  return {
988
899
  className,
989
900
  queryJson: JSON.stringify(queryInput),
990
- shapeJson: JSON.stringify(metadata),
991
901
  metadata,
992
902
  };
993
903
  }
@@ -1080,13 +990,13 @@ export class Ad4mModel {
1080
990
  query: Query = {},
1081
991
  classNameOverride?: string | null,
1082
992
  ): Promise<ResultsWithTotalCount<T>> {
1083
- // Delegate all query input building, shape enrichment, and getter
1084
- // pre-computation to the shared prepareModelQueryParams helper.
1085
- const { className, queryJson, shapeJson } = this.prepareModelQueryParams(
993
+ // Delegate query input building to the shared prepareModelQueryParams
994
+ // helper. The executor resolves the shape from SHACL server-side.
995
+ const { className, queryJson } = this.prepareModelQueryParams(
1086
996
  query, classNameOverride,
1087
997
  );
1088
998
 
1089
- const result = await perspective.modelQuery(className, queryJson, shapeJson);
999
+ const result = await perspective.modelQuery(className, queryJson);
1090
1000
 
1091
1001
  // Convert JSON instances to model class instances, recursively constructing
1092
1002
  // class instances for any included relations resolved by Rust.
@@ -1139,19 +1049,18 @@ export class Ad4mModel {
1139
1049
  * });
1140
1050
  * ```
1141
1051
  */
1142
- static async findAll<T extends Ad4mModel>(
1052
+ static async findAll<T extends Ad4mModel, Q extends TypedQuery<T> = {}>(
1143
1053
  this: typeof Ad4mModel & (new (...args: any[]) => T),
1144
1054
  perspective: PerspectiveProxy,
1145
- query: Query = {},
1146
- /** @deprecated Ignored — Prolog engine has been removed. */
1147
- _engine?: 'sparql' | 'prolog' | boolean
1148
- ): Promise<T[]> {
1149
- if (query.properties && query.properties.length === 0) {
1055
+ query?: Q,
1056
+ ): Promise<(T & IncludeExtras<T, IncludeOf<Q>>)[]> {
1057
+ const q = (query ?? {}) as Query;
1058
+ if (q.properties && q.properties.length === 0) {
1150
1059
  throw new Error("properties[] must not be empty — omit the field to return all properties, or specify at least one field name");
1151
1060
  }
1152
1061
 
1153
- const { results } = await this.executeModelQuery(perspective, query);
1154
- return results;
1062
+ const { results } = await this.executeModelQuery(perspective, q);
1063
+ return results as (T & IncludeExtras<T, IncludeOf<Q>>)[];
1155
1064
  }
1156
1065
 
1157
1066
  /**
@@ -1174,15 +1083,13 @@ export class Ad4mModel {
1174
1083
  * }
1175
1084
  * ```
1176
1085
  */
1177
- static async findOne<T extends Ad4mModel>(
1086
+ static async findOne<T extends Ad4mModel, Q extends TypedQuery<T> = {}>(
1178
1087
  this: typeof Ad4mModel & (new (...args: any[]) => T),
1179
1088
  perspective: PerspectiveProxy,
1180
- query: Query = {},
1181
- /** @deprecated Ignored — Prolog engine has been removed. */
1182
- _engine?: 'sparql' | 'prolog' | boolean,
1183
- ): Promise<T | null> {
1184
- const limitedQuery = { ...query, limit: 1 };
1185
- const results = await this.findAll(perspective, limitedQuery);
1089
+ query?: Q,
1090
+ ): Promise<(T & IncludeExtras<T, IncludeOf<Q>>) | null> {
1091
+ const limitedQuery = { ...((query ?? {}) as Query), limit: 1 } as Q;
1092
+ const results = await this.findAll<T, Q>(perspective, limitedQuery);
1186
1093
  return results[0] ?? null;
1187
1094
  }
1188
1095
 
@@ -1203,14 +1110,13 @@ export class Ad4mModel {
1203
1110
  * console.log(`Showing 10 of ${totalCount} dessert recipes`);
1204
1111
  * ```
1205
1112
  */
1206
- static async findAllAndCount<T extends Ad4mModel>(
1113
+ static async findAllAndCount<T extends Ad4mModel, Q extends TypedQuery<T> = {}>(
1207
1114
  this: typeof Ad4mModel & (new (...args: any[]) => T),
1208
1115
  perspective: PerspectiveProxy,
1209
- query: Query = {},
1210
- /** @deprecated Ignored — Prolog engine has been removed. */
1211
- _engine?: 'sparql' | 'prolog' | boolean
1212
- ): Promise<ResultsWithTotalCount<T>> {
1213
- return await this.executeModelQuery(perspective, query);
1116
+ query?: Q,
1117
+ ): Promise<ResultsWithTotalCount<T & IncludeExtras<T, IncludeOf<Q>>>> {
1118
+ const out = await this.executeModelQuery(perspective, (query ?? {}) as Query);
1119
+ return out as ResultsWithTotalCount<T & IncludeExtras<T, IncludeOf<Q>>>;
1214
1120
  }
1215
1121
 
1216
1122
  /**
@@ -1230,18 +1136,16 @@ export class Ad4mModel {
1230
1136
  * console.log(`Page ${page.pageNumber} of recipes, ${page.results.length} items`);
1231
1137
  * ```
1232
1138
  */
1233
- static async paginate<T extends Ad4mModel>(
1139
+ static async paginate<T extends Ad4mModel, Q extends TypedQuery<T> = {}>(
1234
1140
  this: typeof Ad4mModel & (new (...args: any[]) => T),
1235
1141
  perspective: PerspectiveProxy,
1236
1142
  pageSize: number,
1237
1143
  pageNumber: number,
1238
- query?: Query,
1239
- /** @deprecated Ignored — Prolog engine has been removed. */
1240
- _engine?: 'sparql' | 'prolog' | boolean
1241
- ): Promise<PaginationResult<T>> {
1242
- const paginationQuery = { ...(query || {}), limit: pageSize, offset: pageSize * (pageNumber - 1), count: true };
1144
+ query?: Q,
1145
+ ): Promise<PaginationResult<T & IncludeExtras<T, IncludeOf<Q>>>> {
1146
+ const paginationQuery = { ...((query ?? {}) as Query), limit: pageSize, offset: pageSize * (pageNumber - 1), count: true };
1243
1147
  const { results, totalCount } = await this.executeModelQuery(perspective, paginationQuery);
1244
- return { results, totalCount, pageSize, pageNumber };
1148
+ return { results: results as (T & IncludeExtras<T, IncludeOf<Q>>)[], totalCount, pageSize, pageNumber };
1245
1149
  }
1246
1150
 
1247
1151
  /**
@@ -1270,8 +1174,12 @@ export class Ad4mModel {
1270
1174
  * });
1271
1175
  * ```
1272
1176
  */
1273
- static async count(perspective: PerspectiveProxy, query: Query = {}): Promise<number> {
1274
- const { totalCount } = await this.executeModelQuery(perspective, { ...query, limit: 0 });
1177
+ static async count<T extends Ad4mModel>(
1178
+ this: typeof Ad4mModel & (new (...args: any[]) => T),
1179
+ perspective: PerspectiveProxy,
1180
+ query?: TypedQuery<T>,
1181
+ ): Promise<number> {
1182
+ const { totalCount } = await this.executeModelQuery(perspective, { ...((query ?? {}) as Query), limit: 0 });
1275
1183
  return totalCount;
1276
1184
  }
1277
1185
 
@@ -1635,28 +1543,13 @@ export class Ad4mModel {
1635
1543
  if (instances.length === 0) return;
1636
1544
  const metadata = this.getModelMetadata();
1637
1545
 
1638
- // Pre-compute conformance getters so the shape sent to Rust includes them
1639
- const allRelMeta = getRelationsMetadata(this as any);
1640
- for (const [relName, relMeta] of Object.entries(metadata.relations)) {
1641
- const rel = relMeta as any;
1642
- if (rel.getter || rel.direction === 'reverse' || rel.filter === false) continue;
1643
- const meta = allRelMeta[relName];
1644
- if (!meta?.target) continue;
1645
- try {
1646
- const TargetClass = meta.target();
1647
- const filter = buildConformanceFilter(meta.predicate, TargetClass);
1648
- if (filter) rel.getter = filter.getter;
1649
- } catch (e) { console.debug(`evaluateGetters: target class unavailable for relation '${relName}':`, e); }
1650
- }
1651
-
1652
- const shapeJson = JSON.stringify(metadata);
1653
1546
  const instanceIds = instances.map(inst => inst.id || (inst as any)._baseExpression);
1654
1547
 
1655
- // Single RPC call evaluates all getters in-process on the executor
1548
+ // The executor reads getter SPARQL from the perspective's SHACL triples
1549
+ // (written by `addSdna`), so no shape JSON is shipped with the call.
1656
1550
  const result = await perspective.evaluateGetters(
1657
1551
  metadata.className,
1658
1552
  instanceIds,
1659
- shapeJson,
1660
1553
  propertyNames,
1661
1554
  );
1662
1555
 
@@ -2067,11 +1960,11 @@ export class Ad4mModel {
2067
1960
  * ```
2068
1961
  */
2069
1962
  static query<T extends Ad4mModel>(
2070
- this: typeof Ad4mModel & (new (...args: any[]) => T),
2071
- perspective: PerspectiveProxy,
2072
- query?: Query
1963
+ this: typeof Ad4mModel & (new (...args: any[]) => T),
1964
+ perspective: PerspectiveProxy,
1965
+ query?: TypedQuery<T>,
2073
1966
  ): ModelQueryBuilder<T> {
2074
- return new ModelQueryBuilder<T>(perspective, this as any, query);
1967
+ return new ModelQueryBuilder<T>(perspective, this as any, (query ?? {}) as Query);
2075
1968
  }
2076
1969
 
2077
1970
  /**
@@ -10,6 +10,7 @@ import type { PerspectiveProxy } from "../perspectives/PerspectiveProxy";
10
10
  import type {
11
11
  Where, Order, IncludeMap, Query,
12
12
  ResultsWithTotalCount, PaginationResult,
13
+ TypedWhere, TypedOrder, TypedIncludeMap, PropertyKeysOf,
13
14
  } from "./types";
14
15
 
15
16
  /** Query builder for Ad4mModel queries.
@@ -80,8 +81,8 @@ export class ModelQueryBuilder<T extends Ad4mModel> {
80
81
  * })
81
82
  * ```
82
83
  */
83
- where(conditions: Where): ModelQueryBuilder<T> {
84
- this.queryParams.where = conditions;
84
+ where(conditions: TypedWhere<T>): ModelQueryBuilder<T> {
85
+ this.queryParams.where = conditions as Where;
85
86
  return this;
86
87
  }
87
88
 
@@ -96,8 +97,8 @@ export class ModelQueryBuilder<T extends Ad4mModel> {
96
97
  * .order({ createdAt: "DESC" })
97
98
  * ```
98
99
  */
99
- order(orderBy: Order): ModelQueryBuilder<T> {
100
- this.queryParams.order = orderBy;
100
+ order(orderBy: TypedOrder<T>): ModelQueryBuilder<T> {
101
+ this.queryParams.order = orderBy as Order;
101
102
  return this;
102
103
  }
103
104
 
@@ -218,8 +219,8 @@ export class ModelQueryBuilder<T extends Ad4mModel> {
218
219
  * .properties(["name", "description", "rating"])
219
220
  * ```
220
221
  */
221
- properties(properties: string[]): ModelQueryBuilder<T> {
222
- this.queryParams.properties = properties;
222
+ properties(properties: PropertyKeysOf<T>[] | string[]): ModelQueryBuilder<T> {
223
+ this.queryParams.properties = properties as string[];
223
224
  return this;
224
225
  }
225
226
 
@@ -272,8 +273,8 @@ export class ModelQueryBuilder<T extends Ad4mModel> {
272
273
  * .run();
273
274
  * ```
274
275
  */
275
- include(map: IncludeMap): ModelQueryBuilder<T> {
276
- this.queryParams.include = map;
276
+ include(map: TypedIncludeMap<T>): ModelQueryBuilder<T> {
277
+ this.queryParams.include = map as IncludeMap;
277
278
  return this;
278
279
  }
279
280
 
@@ -282,14 +283,6 @@ export class ModelQueryBuilder<T extends Ad4mModel> {
282
283
  return this;
283
284
  }
284
285
 
285
- /**
286
- * Sets the query engine to use.
287
- * @deprecated Prolog engine has been removed. All queries use SPARQL/Rust.
288
- */
289
- engine(_eng: 'sparql' | 'prolog'): ModelQueryBuilder<T> {
290
- return this;
291
- }
292
-
293
286
  /**
294
287
  * Executes the query once and returns the results.
295
288
  *
@@ -377,15 +370,16 @@ export class ModelQueryBuilder<T extends Ad4mModel> {
377
370
 
378
371
  const ctor = this.ctor;
379
372
 
380
- // Build the model query params (className, queryJson, shapeJson)
381
- const { className, queryJson, shapeJson } = (ctor as any).prepareModelQueryParams(
373
+ // Build the model query params (className, queryJson). The executor
374
+ // resolves the shape from the perspective's SHACL triples.
375
+ const { className, queryJson } = (ctor as any).prepareModelQueryParams(
382
376
  this.queryParams, this.modelClassName
383
377
  );
384
378
 
385
379
  // Register model subscription via Rust — this builds trigger SPARQL internally,
386
380
  // registers the subscription, and runs the initial query in one call.
387
381
  const { subscriptionId, result: initialModelResult } = await this.perspective.modelSubscribe(
388
- className, queryJson, shapeJson
382
+ className, queryJson
389
383
  );
390
384
 
391
385
  // Convert JSON instances to model class instances
@@ -558,12 +552,12 @@ export class ModelQueryBuilder<T extends Ad4mModel> {
558
552
  this.dispose();
559
553
 
560
554
  const countParams = { ...this.queryParams, limit: 0 };
561
- const { className, queryJson, shapeJson } = (this.ctor as any).prepareModelQueryParams(
555
+ const { className, queryJson } = (this.ctor as any).prepareModelQueryParams(
562
556
  countParams, this.modelClassName
563
557
  );
564
558
 
565
559
  const { subscriptionId, result: initialModelResult } = await this.perspective.modelSubscribe(
566
- className, queryJson, shapeJson
560
+ className, queryJson
567
561
  );
568
562
 
569
563
  const parseCount = (raw: any): number => {
@@ -712,12 +706,12 @@ export class ModelQueryBuilder<T extends Ad4mModel> {
712
706
  const subscriptionParams = { ...(this.queryParams || {}) };
713
707
  delete subscriptionParams.limit;
714
708
  delete subscriptionParams.offset;
715
- const { className, queryJson, shapeJson } = (ctor as any).prepareModelQueryParams(
709
+ const { className, queryJson } = (ctor as any).prepareModelQueryParams(
716
710
  subscriptionParams, this.modelClassName
717
711
  );
718
712
 
719
713
  const { subscriptionId } = await this.perspective.modelSubscribe(
720
- className, queryJson, shapeJson
714
+ className, queryJson
721
715
  );
722
716
 
723
717
  // Build the paginated query for Rust endpoint (count: true fetches both results and totalCount in one call)
@@ -270,11 +270,18 @@ describe("generateSHACL() relation getter population", () => {
270
270
  it("should use explicit getter when provided (ignoring auto-generation)", () => {
271
271
  const { shape } = (ParentWithRelations as any).generateSHACL();
272
272
 
273
- // Getter-only relations have no predicate and are excluded from SHACL shapes
273
+ // Getter-only relations have no `through` predicate but must still
274
+ // appear in the SHACL shape so the executor can find the getter; the
275
+ // writer synthesises a deterministic IRI for `sh:path`.
274
276
  const customProp = shape.properties.find(
275
277
  (p: SHACLPropertyShape) => p.name === "customItems"
276
278
  );
277
- expect(customProp).toBeUndefined();
279
+ expect(customProp).toBeDefined();
280
+ expect(customProp!.getter).toBe(
281
+ "SELECT ?target WHERE { ?target <test://custom> ?source . }"
282
+ );
283
+ expect(customProp!.path).toBeDefined();
284
+ expect(customProp!.path).toContain("ad4m://getter/");
278
285
  });
279
286
 
280
287
  it("should survive full round-trip: generateSHACL → toLinks → fromLinks", () => {
@@ -299,11 +306,15 @@ describe("generateSHACL() relation getter population", () => {
299
306
  expect(flaggedProp!.conformanceConditions).toBeDefined();
300
307
  expect(flaggedProp!.conformanceConditions!.length).toBeGreaterThan(0);
301
308
 
302
- // The custom getter-only relation should NOT be in the SHACL shape
309
+ // Getter-only relations now round-trip too — the synthesised path
310
+ // lets the SHACL graph carry the entry through links/fromLinks.
303
311
  const customProp = reconstructed.properties.find(
304
312
  (p: SHACLPropertyShape) => p.name === "customItems"
305
313
  );
306
- expect(customProp).toBeUndefined();
314
+ expect(customProp).toBeDefined();
315
+ expect(customProp!.getter).toBe(
316
+ "SELECT ?target WHERE { ?target <test://custom> ?source . }"
317
+ );
307
318
  });
308
319
  });
309
320
 
@@ -574,7 +585,13 @@ describe("where clause validation", () => {
574
585
  });
575
586
 
576
587
  describe("where clause compilation", () => {
577
- it("should compile where clause to SPARQL getter", () => {
588
+ // Under the source-of-truth refactor the SHACL writer no longer inlines
589
+ // `where` conditions into the relation's SPARQL getter. Instead it emits
590
+ // `ad4m://whereFilter` + `ad4m://wherePredicates` triples that the
591
+ // Rust executor evaluates as a post-getter pass at query time. These
592
+ // tests assert that contract on the writer side.
593
+
594
+ it("should emit whereFilter and wherePredicates on the relation shape", () => {
578
595
  @Model({ name: "WhereTarget" })
579
596
  class WhereTarget extends Ad4mModel {
580
597
  @Property({ through: "test://status", required: true })
@@ -595,13 +612,11 @@ describe("where clause compilation", () => {
595
612
  (p: SHACLPropertyShape) => p.name === "items"
596
613
  );
597
614
  expect(itemsProp).toBeDefined();
598
- expect(itemsProp!.getter).toBeDefined();
599
- expect(itemsProp!.getter).toContain("test://has_item");
600
- expect(itemsProp!.getter).toContain("test://status");
601
- expect(itemsProp!.getter).toContain("active");
615
+ expect(itemsProp!.whereFilter).toEqual({ status: "active" });
616
+ expect(itemsProp!.wherePredicates).toEqual({ status: "test://status" });
602
617
  });
603
618
 
604
- it("should use where clause instead of auto-derived conformance when both target and where are set", () => {
619
+ it("should set whereFilter alongside an auto-derived conformance getter when target is provided", () => {
605
620
  @Model({ name: "WhereOverrideParent" })
606
621
  class WhereOverrideParent extends Ad4mModel {
607
622
  @HasMany(() => FlaggedTarget, {
@@ -616,16 +631,15 @@ describe("where clause compilation", () => {
616
631
  (p: SHACLPropertyShape) => p.name === "flaggedItems"
617
632
  );
618
633
  expect(prop).toBeDefined();
634
+ // whereFilter / wherePredicates carry the post-getter filter; type
635
+ // filtering stays on the auto-derived conformance getter.
636
+ expect(prop!.whereFilter).toEqual({ name: "specific" });
637
+ expect(prop!.wherePredicates).toEqual({ name: "test://name" });
619
638
  expect(prop!.getter).toBeDefined();
620
- // Should contain the where condition (name = specific)
621
- expect(prop!.getter).toContain("test://name");
622
- expect(prop!.getter).toContain("specific");
623
- // Should NOT contain the auto-derived flag condition
624
- // (where overrides auto-conformance)
625
- expect(prop!.getter).not.toContain("test://flagged_type");
639
+ expect(prop!.getter).toContain("test://flagged_type");
626
640
  });
627
641
 
628
- it("should compile where clause with not operator", () => {
642
+ it("should emit whereFilter with a not operator unchanged", () => {
629
643
  @Model({ name: "WhereNotTarget" })
630
644
  class WhereNotTarget extends Ad4mModel {
631
645
  @Property({ through: "test://status" })
@@ -646,13 +660,11 @@ describe("where clause compilation", () => {
646
660
  (p: SHACLPropertyShape) => p.name === "items"
647
661
  );
648
662
  expect(prop).toBeDefined();
649
- expect(prop!.getter).toBeDefined();
650
- // Should contain a negation condition
651
- expect(prop!.getter).toContain("test://status");
652
- expect(prop!.getter).toContain("archived");
663
+ expect(prop!.whereFilter).toEqual({ status: { not: "archived" } });
664
+ expect(prop!.wherePredicates).toEqual({ status: "test://status" });
653
665
  });
654
666
 
655
- it("should compile where clause with array values (IN)", () => {
667
+ it("should emit whereFilter with array (IN) values unchanged", () => {
656
668
  @Model({ name: "WhereArrayTarget" })
657
669
  class WhereArrayTarget extends Ad4mModel {
658
670
  @Property({ through: "test://category" })
@@ -673,13 +685,11 @@ describe("where clause compilation", () => {
673
685
  (p: SHACLPropertyShape) => p.name === "items"
674
686
  );
675
687
  expect(prop).toBeDefined();
676
- expect(prop!.getter).toBeDefined();
677
- expect(prop!.getter).toContain("test://category");
678
- expect(prop!.getter).toContain("food");
679
- expect(prop!.getter).toContain("drink");
688
+ expect(prop!.whereFilter).toEqual({ category: ["food", "drink"] });
689
+ expect(prop!.wherePredicates).toEqual({ category: "test://category" });
680
690
  });
681
691
 
682
- it("should compile where clause without target using raw predicate URIs", () => {
692
+ it("should emit whereFilter without wherePredicates when target metadata is absent", () => {
683
693
  @Model({ name: "WhereNoTargetParent" })
684
694
  class WhereNoTargetParent extends Ad4mModel {
685
695
  @HasMany({
@@ -694,12 +704,13 @@ describe("where clause compilation", () => {
694
704
  (p: SHACLPropertyShape) => p.name === "items"
695
705
  );
696
706
  expect(prop).toBeDefined();
697
- expect(prop!.getter).toBeDefined();
698
- expect(prop!.getter).toContain("test://status");
699
- expect(prop!.getter).toContain("active");
707
+ expect(prop!.whereFilter).toEqual({ "test://status": "active" });
708
+ // Without target metadata the writer cannot resolve property→predicate;
709
+ // the executor falls back to interpreting keys as raw IRIs.
710
+ expect(prop!.wherePredicates).toBeUndefined();
700
711
  });
701
712
 
702
- it("should set both where-compiled getter and sh:class when target is present", () => {
713
+ it("should set both whereFilter and sh:class when target is present", () => {
703
714
  @Model({ name: "WherePlusClassParent" })
704
715
  class WherePlusClassParent extends Ad4mModel {
705
716
  @HasMany(() => FlaggedTarget, {
@@ -714,15 +725,12 @@ describe("where clause compilation", () => {
714
725
  (p: SHACLPropertyShape) => p.name === "flaggedItems"
715
726
  );
716
727
  expect(prop).toBeDefined();
717
- // where-compiled getter
718
- expect(prop!.getter).toBeDefined();
719
- expect(prop!.getter).toContain("specific");
720
- // sh:class still set (target is present)
728
+ expect(prop!.whereFilter).toEqual({ name: "specific" });
721
729
  expect(prop!.class).toBeDefined();
722
730
  expect(prop!.class).toContain("FlaggedTarget");
723
731
  });
724
732
 
725
- it("should round-trip where-compiled getter through toLinks/fromLinks", () => {
733
+ it("should round-trip whereFilter and wherePredicates through toLinks/fromLinks", () => {
726
734
  @Model({ name: "WhereRoundTripTarget" })
727
735
  class WhereRoundTripTarget extends Ad4mModel {
728
736
  @Property({ through: "test://status", required: true })
@@ -749,9 +757,8 @@ describe("where clause compilation", () => {
749
757
  (p: SHACLPropertyShape) => p.name === "items"
750
758
  );
751
759
  expect(prop).toBeDefined();
752
- expect(prop!.getter).toBeDefined();
753
- expect(prop!.getter).toContain("test://status");
754
- expect(prop!.getter).toContain("active");
760
+ expect(prop!.whereFilter).toEqual({ status: "active" });
761
+ expect(prop!.wherePredicates).toEqual({ status: "test://status" });
755
762
  });
756
763
  });
757
764