@coasys/ad4m 0.13.0-postmessage-ws-proxy.0 → 0.13.0-postmessage-ws-proxy.5

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 (52) hide show
  1. package/lib/index.cjs +825 -653
  2. package/lib/index.js +812 -654
  3. package/lib/src/Ad4mClient.d.ts +1 -0
  4. package/lib/src/Ad4mClient.js +1 -1
  5. package/lib/src/ai/AIClient.js +1 -1
  6. package/lib/src/apiClient.d.ts +4 -1
  7. package/lib/src/apiClient.js +6 -1
  8. package/lib/src/index.d.ts +4 -0
  9. package/lib/src/index.js +4 -0
  10. package/lib/src/model/Ad4mModel.d.ts +9 -32
  11. package/lib/src/model/Ad4mModel.js +36 -266
  12. package/lib/src/model/ModelQueryBuilder.d.ts +5 -10
  13. package/lib/src/model/ModelQueryBuilder.js +20 -36
  14. package/lib/src/model/decorators.d.ts +7 -4
  15. package/lib/src/model/shacl-gen.js +120 -47
  16. package/lib/src/model/types.d.ts +140 -4
  17. package/lib/src/perspectives/PerspectiveClient.d.ts +4 -4
  18. package/lib/src/perspectives/PerspectiveClient.js +5 -6
  19. package/lib/src/perspectives/PerspectiveProxy.d.ts +8 -7
  20. package/lib/src/perspectives/PerspectiveProxy.js +10 -9
  21. package/lib/src/perspectives/SparqlBindings.d.ts +47 -0
  22. package/lib/src/perspectives/SparqlBindings.js +65 -0
  23. package/lib/src/shacl/NodeExpression.d.ts +44 -0
  24. package/lib/src/shacl/NodeExpression.js +39 -0
  25. package/lib/src/shacl/SHACLShape.d.ts +23 -0
  26. package/lib/src/shacl/SHACLShape.js +115 -1
  27. package/lib/src/shacl/builders.d.ts +58 -0
  28. package/lib/src/shacl/builders.js +76 -0
  29. package/lib/src/shacl/index.d.ts +36 -0
  30. package/lib/src/shacl/index.js +33 -0
  31. package/package.json +8 -11
  32. package/src/Ad4mClient.ts +2 -2
  33. package/src/ai/AIClient.ts +1 -1
  34. package/src/apiClient.ts +8 -1
  35. package/src/index.ts +4 -0
  36. package/src/model/Ad4mModel.test.ts +33 -74
  37. package/src/model/Ad4mModel.ts +54 -272
  38. package/src/model/ModelQueryBuilder.ts +29 -46
  39. package/src/model/decorators.ts +7 -4
  40. package/src/model/relation-filtering.test.ts +46 -39
  41. package/src/model/shacl-gen.ts +128 -54
  42. package/src/model/shacl-roundtrip.test.ts +197 -0
  43. package/src/model/types-typed-query.test.ts +360 -0
  44. package/src/model/types.ts +196 -4
  45. package/src/perspectives/PerspectiveClient.ts +6 -8
  46. package/src/perspectives/PerspectiveProxy.ts +13 -13
  47. package/src/perspectives/SparqlBindings.ts +79 -0
  48. package/src/shacl/NodeExpression.ts +54 -0
  49. package/src/shacl/SHACLShape.test.ts +172 -0
  50. package/src/shacl/SHACLShape.ts +173 -1
  51. package/src/shacl/builders.ts +86 -0
  52. package/src/shacl/index.ts +72 -0
@@ -6,7 +6,7 @@
6
6
  */
7
7
  import type { Ad4mModel } from "./Ad4mModel";
8
8
  import type { PerspectiveProxy } from "../perspectives/PerspectiveProxy";
9
- import type { Where, Order, IncludeMap, Query, PaginationResult } from "./types";
9
+ import type { Query, PaginationResult, TypedWhere, TypedOrder, TypedIncludeMap, PropertyKeysOf } from "./types";
10
10
  /** Query builder for Ad4mModel queries.
11
11
  * Allows building queries with a fluent interface and either running them once
12
12
  * or subscribing to updates.
@@ -63,7 +63,7 @@ export declare class ModelQueryBuilder<T extends Ad4mModel> {
63
63
  * })
64
64
  * ```
65
65
  */
66
- where(conditions: Where): ModelQueryBuilder<T>;
66
+ where(conditions: TypedWhere<T>): ModelQueryBuilder<T>;
67
67
  /**
68
68
  * Sets the order for the query results.
69
69
  *
@@ -75,7 +75,7 @@ export declare class ModelQueryBuilder<T extends Ad4mModel> {
75
75
  * .order({ createdAt: "DESC" })
76
76
  * ```
77
77
  */
78
- order(orderBy: Order): ModelQueryBuilder<T>;
78
+ order(orderBy: TypedOrder<T>): ModelQueryBuilder<T>;
79
79
  /**
80
80
  * Sets the maximum number of results to return.
81
81
  *
@@ -156,7 +156,7 @@ export declare class ModelQueryBuilder<T extends Ad4mModel> {
156
156
  * .properties(["name", "description", "rating"])
157
157
  * ```
158
158
  */
159
- properties(properties: string[]): ModelQueryBuilder<T>;
159
+ properties(properties: PropertyKeysOf<T>[] | string[]): ModelQueryBuilder<T>;
160
160
  /**
161
161
  * Controls whether SPARQL property getters are evaluated during hydration.
162
162
  *
@@ -202,13 +202,8 @@ export declare class ModelQueryBuilder<T extends Ad4mModel> {
202
202
  * .run();
203
203
  * ```
204
204
  */
205
- include(map: IncludeMap): ModelQueryBuilder<T>;
205
+ include(map: TypedIncludeMap<T>): ModelQueryBuilder<T>;
206
206
  overrideModelClassName(className: string): ModelQueryBuilder<T>;
207
- /**
208
- * Sets the query engine to use.
209
- * @deprecated Prolog engine has been removed. All queries use SPARQL/Rust.
210
- */
211
- engine(_eng: 'sparql' | 'prolog'): ModelQueryBuilder<T>;
212
207
  /**
213
208
  * Executes the query once and returns the results.
214
209
  *
@@ -256,13 +256,6 @@ export class ModelQueryBuilder {
256
256
  this.modelClassName = className;
257
257
  return this;
258
258
  }
259
- /**
260
- * Sets the query engine to use.
261
- * @deprecated Prolog engine has been removed. All queries use SPARQL/Rust.
262
- */
263
- engine(_eng) {
264
- return this;
265
- }
266
259
  /**
267
260
  * Executes the query once and returns the results.
268
261
  *
@@ -344,23 +337,18 @@ export class ModelQueryBuilder {
344
337
  // Clean up any existing subscription
345
338
  this.dispose();
346
339
  const ctor = this.ctor;
347
- // Build the model query params (className, queryJson, shapeJson)
348
- const { className, queryJson, shapeJson } = ctor.prepareModelQueryParams(this.queryParams, this.modelClassName);
340
+ // Build the model query params (className, queryJson). The executor
341
+ // resolves the shape from the perspective's SHACL triples.
342
+ const { className, queryJson } = ctor.prepareModelQueryParams(this.queryParams, this.modelClassName);
349
343
  // Register model subscription via Rust — this builds trigger SPARQL internally,
350
344
  // registers the subscription, and runs the initial query in one call.
351
- const { subscriptionId, result: initialModelResult } = await this.perspective.modelSubscribe(className, queryJson, shapeJson);
345
+ const { subscriptionId, result: initialModelResult } = await this.perspective.modelSubscribe(className, queryJson);
352
346
  // Convert JSON instances to model class instances
353
347
  const parseResults = (raw) => {
354
348
  return ctor.parseModelResult(this.perspective, raw, this.queryParams.include, this.queryParams.properties);
355
349
  };
356
- // Resolve non-literal (file-language) properties — handles both raw URI strings
357
- // and already-resolved FileData objects returned by the Rust executor.
358
- const resolveAndReturn = async (instances) => {
359
- await ctor.resolveNonLiteralProps(this.perspective, instances);
360
- return instances;
361
- };
362
- // Parse initial results (with non-literal resolution)
363
- const initialResults = await resolveAndReturn(parseResults(initialModelResult));
350
+ // Transforms are now applied by the Rust executor during hydration
351
+ const initialResults = parseResults(initialModelResult);
364
352
  // Track last emitted result fingerprint to suppress duplicate callbacks
365
353
  let lastResultFingerprint = null;
366
354
  const buildFingerprint = (results) => {
@@ -373,20 +361,16 @@ export class ModelQueryBuilder {
373
361
  // When Rust re-runs the model query and finds changed results, it pushes them.
374
362
  const unsubscribe = this.perspective.client.subscribeToQueryUpdates(subscriptionId, (rawResult) => {
375
363
  try {
376
- const parsed = parseResults(rawResult);
377
- console.debug(`[ModelQueryBuilder.subscribe] Update received for ${subscriptionId}: ${parsed.length} instances`);
378
- resolveAndReturn(parsed).then((results) => {
379
- const fp = buildFingerprint(results);
380
- if (fp === lastResultFingerprint) {
381
- console.debug(`[ModelQueryBuilder.subscribe] Fingerprint unchanged, skipping callback`);
382
- return;
383
- }
384
- console.debug(`[ModelQueryBuilder.subscribe] Fingerprint changed, calling callback with ${results.length} results`);
385
- lastResultFingerprint = fp;
386
- callback(results);
387
- }).catch((e) => {
388
- console.error('Model subscription update resolve error:', e);
389
- });
364
+ const results = parseResults(rawResult);
365
+ console.debug(`[ModelQueryBuilder.subscribe] Update received for ${subscriptionId}: ${results.length} instances`);
366
+ const fp = buildFingerprint(results);
367
+ if (fp === lastResultFingerprint) {
368
+ console.debug(`[ModelQueryBuilder.subscribe] Fingerprint unchanged, skipping callback`);
369
+ return;
370
+ }
371
+ console.debug(`[ModelQueryBuilder.subscribe] Fingerprint changed, calling callback with ${results.length} results`);
372
+ lastResultFingerprint = fp;
373
+ callback(results);
390
374
  }
391
375
  catch (e) {
392
376
  console.error('Model subscription update parse error:', e);
@@ -508,8 +492,8 @@ export class ModelQueryBuilder {
508
492
  // Clean up any existing subscription
509
493
  this.dispose();
510
494
  const countParams = { ...this.queryParams, limit: 0 };
511
- const { className, queryJson, shapeJson } = this.ctor.prepareModelQueryParams(countParams, this.modelClassName);
512
- const { subscriptionId, result: initialModelResult } = await this.perspective.modelSubscribe(className, queryJson, shapeJson);
495
+ const { className, queryJson } = this.ctor.prepareModelQueryParams(countParams, this.modelClassName);
496
+ const { subscriptionId, result: initialModelResult } = await this.perspective.modelSubscribe(className, queryJson);
513
497
  const parseCount = (raw) => {
514
498
  const data = typeof raw === 'string' ? JSON.parse(raw) : raw;
515
499
  return data.totalCount ?? 0;
@@ -644,8 +628,8 @@ export class ModelQueryBuilder {
644
628
  const subscriptionParams = { ...(this.queryParams || {}) };
645
629
  delete subscriptionParams.limit;
646
630
  delete subscriptionParams.offset;
647
- const { className, queryJson, shapeJson } = ctor.prepareModelQueryParams(subscriptionParams, this.modelClassName);
648
- const { subscriptionId } = await this.perspective.modelSubscribe(className, queryJson, shapeJson);
631
+ const { className, queryJson } = ctor.prepareModelQueryParams(subscriptionParams, this.modelClassName);
632
+ const { subscriptionId } = await this.perspective.modelSubscribe(className, queryJson);
649
633
  // Build the paginated query for Rust endpoint (count: true fetches both results and totalCount in one call)
650
634
  const paginatedQuery = {
651
635
  ...(this.queryParams || {}),
@@ -130,11 +130,14 @@ export interface PropertyOptions {
130
130
  */
131
131
  local?: boolean;
132
132
  /**
133
- * Optional transform function to modify the property value after it is retrieved.
134
- * This is useful for transforming raw data into a more usable format.
135
- * The function takes the raw value as input and returns the transformed value.
133
+ * Optional transform expression to modify the property value.
134
+ * This is a SHACL-AF Node Expression that runs in the Rust model query engine.
135
+ * Examples: `fileToDataUri`, `concat(literal('prefix_'), focus())`, etc.
136
+ * Builders (`focus`, `literal`, `path`, `exists`, `ifExpr`, `concat`,
137
+ * `coalesce`, `fn`) and the `fileToDataUri` built-in are exported from
138
+ * the package root: `import { concat, literal, focus } from '@coasys/ad4m'`.
136
139
  */
137
- transform?: (value: any) => any;
140
+ transform?: import('../shacl/NodeExpression').NodeExpression;
138
141
  /**
139
142
  * Allowed values for this property (enum constraint).
140
143
  * Maps to SHACL `sh:in`. Each entry has a `value` (the stored RDF term)
@@ -7,8 +7,6 @@
7
7
  * decorators.ts stays focused on decorator registration logic.
8
8
  */
9
9
  import { SHACLShape } from "../shacl/SHACLShape";
10
- import { escapeQueryString } from "../utils";
11
- import { compileWhereClause } from "./query-utils";
12
10
  import { propertyNameToSetterName } from "./util";
13
11
  /**
14
12
  * Build a SHACL shape for a model class.
@@ -25,7 +23,6 @@ export function buildSHACL(subjectName, target, properties, allRelationsMeta, co
25
23
  const obj = target.prototype;
26
24
  // ── Determine namespace from first property or relation ─────────────
27
25
  let namespace = "ad4m://";
28
- const relations = Object.fromEntries(Object.entries(allRelationsMeta).filter(([, r]) => r.kind === 'hasMany' || r.kind === 'belongsToMany'));
29
26
  // Try properties first
30
27
  if (Object.keys(properties).length > 0) {
31
28
  const firstProp = properties[Object.keys(properties)[0]];
@@ -37,8 +34,8 @@ export function buildSHACL(subjectName, target, properties, allRelationsMeta, co
37
34
  }
38
35
  }
39
36
  // Fall back to relations if no properties
40
- else if (Object.keys(relations).length > 0) {
41
- const firstRel = relations[Object.keys(relations)[0]];
37
+ else if (Object.keys(allRelationsMeta).length > 0) {
38
+ const firstRel = allRelationsMeta[Object.keys(allRelationsMeta)[0]];
42
39
  if (firstRel.predicate) {
43
40
  const match = firstRel.predicate.match(/^([^:]+:\/\/)/);
44
41
  if (match) {
@@ -112,9 +109,19 @@ export function buildSHACL(subjectName, target, properties, allRelationsMeta, co
112
109
  if (propMeta.writable !== undefined) {
113
110
  propShape.writable = propMeta.writable;
114
111
  }
115
- if (propMeta.resolveLanguage) {
112
+ if (propMeta.resolveLanguage != null) {
116
113
  propShape.resolveLanguage = propMeta.resolveLanguage;
117
114
  }
115
+ // Explicit getter SPARQL — the executor evaluates this when
116
+ // hydrating the property, in addition to (or instead of)
117
+ // reading raw links via `propMeta.through`.
118
+ if (propMeta.getter) {
119
+ propShape.getter = propMeta.getter;
120
+ }
121
+ // Serializable transform expression (SHACL-AF Node Expression)
122
+ if (propMeta.transform) {
123
+ propShape.transform = propMeta.transform;
124
+ }
118
125
  // ── Setter actions ──────────────────────────────────────────────
119
126
  if (propMeta.prologSetter) {
120
127
  console.warn(`[SHACL Generation] Custom Prolog setter for property '${propName}' in class '${subjectName}' is not yet supported. ` +
@@ -153,63 +160,82 @@ export function buildSHACL(subjectName, target, properties, allRelationsMeta, co
153
160
  shape.addProperty(propShape);
154
161
  }
155
162
  // ── Convert relations to SHACL property shapes ─────────────────────
156
- for (const relName in relations) {
157
- const relMeta = relations[relName];
158
- if (!relMeta.predicate)
163
+ for (const relName in allRelationsMeta) {
164
+ const relMeta = allRelationsMeta[relName];
165
+ // Getter-only relations (no `through`) have no real link predicate
166
+ // but still need a SHACL property entry so the executor can find
167
+ // the getter expression. Synthesize a deterministic IRI so the
168
+ // SHACL graph is well-formed; the predicate is never used to match
169
+ // links because the getter is the sole source of values. Use
170
+ // slash separators so the result is a valid IRI (colons in the
171
+ // authority confuse strict SPARQL IRI parsers).
172
+ if (!relMeta.predicate && !relMeta.getter)
159
173
  continue;
174
+ const synthesizedPath = relMeta.predicate
175
+ || `ad4m://getter/${subjectName}/${relName}`;
160
176
  const relShape = {
161
177
  name: relName,
162
- path: relMeta.predicate,
178
+ path: synthesizedPath,
163
179
  };
164
180
  // Relations typically contain IRIs
165
181
  relShape.nodeKind = 'IRI';
182
+ // Encode relation kind so the executor can derive direction and
183
+ // scalar-vs-collection rendering without consulting the JS class.
184
+ relShape.relationKind = relMeta.kind;
185
+ // Scalar relations cap at 1.
186
+ if (relMeta.kind === 'hasOne' || relMeta.kind === 'belongsToOne') {
187
+ relShape.maxCount = 1;
188
+ }
189
+ else if (relMeta.maxCount !== undefined) {
190
+ relShape.maxCount = relMeta.maxCount;
191
+ }
192
+ // Encode opt-out of type filtering (default true; only emit when false).
193
+ if (relMeta.filter === false) {
194
+ relShape.filter = false;
195
+ }
166
196
  // AD4M-specific metadata
167
197
  if (relMeta.local !== undefined) {
168
198
  relShape.local = relMeta.local;
169
199
  }
170
- // Adder action
171
- relShape.adder = [{
172
- action: "addLink",
173
- source: "this",
174
- predicate: relMeta.predicate,
175
- target: "value",
176
- ...(relMeta.local && { local: true })
177
- }];
178
- // Remover action
179
- relShape.remover = [{
180
- action: "removeLink",
181
- source: "this",
182
- predicate: relMeta.predicate,
183
- target: "value",
184
- ...(relMeta.local && { local: true })
185
- }];
200
+ // Adder / Remover actions — only meaningful for relations backed
201
+ // by a real link predicate. Getter-only relations are read-only.
202
+ if (relMeta.predicate) {
203
+ relShape.adder = [{
204
+ action: "addLink",
205
+ source: "this",
206
+ predicate: relMeta.predicate,
207
+ target: "value",
208
+ ...(relMeta.local && { local: true })
209
+ }];
210
+ relShape.remover = [{
211
+ action: "removeLink",
212
+ source: "this",
213
+ predicate: relMeta.predicate,
214
+ target: "value",
215
+ ...(relMeta.local && { local: true })
216
+ }];
217
+ }
186
218
  // ── Build Getter (conformance filter) ───────────────────────────
187
219
  // Priority chain:
188
220
  // 1. Explicit getter string → use verbatim
189
- // 2. `where` clause → compile DSL to SPARQL getter
190
- // 3. target + filter !== false → auto-derive from shape
221
+ // 2. target + filter !== false → auto-derive conformance getter
222
+ // from the shape. Where-clause filtering is applied as a
223
+ // post-getter pass via `whereFilter` / `wherePredicates`, which
224
+ // use `parse_literal_value` and so transparently handle
225
+ // `literal:json:` envelopes that simple FILTER(STR(?x) = ...)
226
+ // comparisons can't.
191
227
  if (relMeta.getter) {
192
228
  relShape.getter = relMeta.getter;
193
229
  }
194
- else if (relMeta.where) {
195
- try {
196
- const TargetClass = relMeta.target?.();
197
- const targetMetadata = TargetClass
198
- ? TargetClass.getModelMetadata?.() ?? null
199
- : null;
200
- const conditions = compileWhereClause(relMeta.where, targetMetadata);
201
- if (conditions.length > 0) {
202
- const escapedPredicate = escapeQueryString(relMeta.predicate);
203
- relShape.getter = `SELECT ?target WHERE { <Base> <${escapedPredicate}> ?target . ${conditions.join(' ')} }`;
204
- }
205
- }
206
- catch (e) {
207
- // Target metadata may not be available yet
208
- }
209
- }
210
- else if (relMeta.target && relMeta.filter !== false) {
230
+ else if (relMeta.target
231
+ && relMeta.filter !== false
232
+ && relMeta.kind !== 'belongsToOne'
233
+ && relMeta.kind !== 'belongsToMany') {
211
234
  // Lazy conformance filter: store deferred reference,
212
- // resolve on first access via a getter on relShape
235
+ // resolve on first access via a getter on relShape.
236
+ // Skipped for reverse relations (belongsTo*) because the
237
+ // auto-derived getter assumes forward direction; the executor's
238
+ // `resolve_reverse_relations` already populates these correctly.
213
239
  const targetThunk = relMeta.target;
214
240
  const predicate = relMeta.predicate;
215
241
  let resolved = false;
@@ -246,6 +272,8 @@ export function buildSHACL(subjectName, target, properties, allRelationsMeta, co
246
272
  });
247
273
  }
248
274
  // ── sh:class — target shape reference ───────────────────────────
275
+ // Also emit ad4m:targetClassName so the executor can look up the
276
+ // target class shape through its in-memory cache by bare name.
249
277
  if (relMeta.target) {
250
278
  try {
251
279
  const TargetClass = relMeta.target();
@@ -253,9 +281,54 @@ export function buildSHACL(subjectName, target, properties, allRelationsMeta, co
253
281
  if (targetSHACL?.shape?.nodeShapeUri) {
254
282
  relShape.class = targetSHACL.shape.nodeShapeUri;
255
283
  }
284
+ if (targetSHACL?.name) {
285
+ relShape.targetClassName = targetSHACL.name;
286
+ }
287
+ else {
288
+ const targetProto = TargetClass.prototype;
289
+ if (targetProto?.className) {
290
+ relShape.targetClassName = targetProto.className;
291
+ }
292
+ }
293
+ }
294
+ catch (e) {
295
+ // Target class resolution failed (typically a circular
296
+ // decorator dependency). Since the executor no longer
297
+ // receives target metadata over the wire, dropping the
298
+ // reference here would turn a transient build-time issue
299
+ // into a permanent broken-include at query time. Log
300
+ // loudly so the failure is discoverable.
301
+ console.warn(`[shacl-gen] Failed to resolve target class for relation `
302
+ + `"${subjectName}.${relName}": ${e instanceof Error ? e.message : String(e)}`);
303
+ }
304
+ }
305
+ // ── Where-clause metadata for post-getter filtering ─────────────
306
+ // The executor uses these to apply where conditions against the
307
+ // target class without needing the target's ModelMetadata at query time.
308
+ if (relMeta.where) {
309
+ relShape.whereFilter = relMeta.where;
310
+ try {
311
+ const TargetClass = relMeta.target?.();
312
+ const targetMetadata = TargetClass
313
+ ? TargetClass.getModelMetadata?.() ?? null
314
+ : null;
315
+ if (targetMetadata?.properties) {
316
+ const predicates = {};
317
+ for (const propName of Object.keys(relMeta.where)) {
318
+ if (['id', 'author', 'timestamp'].includes(propName))
319
+ continue;
320
+ const propMeta = targetMetadata.properties[propName];
321
+ if (propMeta?.predicate) {
322
+ predicates[propName] = propMeta.predicate;
323
+ }
324
+ }
325
+ if (Object.keys(predicates).length > 0) {
326
+ relShape.wherePredicates = predicates;
327
+ }
328
+ }
256
329
  }
257
330
  catch (e) {
258
- // Target class may not be available yet
331
+ // Target metadata may not be available yet
259
332
  }
260
333
  }
261
334
  shape.addProperty(relShape);
@@ -6,6 +6,7 @@
6
6
  * creating circular runtime dependencies on `Ad4mModel.ts`.
7
7
  */
8
8
  import type { Ad4mModel } from "./Ad4mModel";
9
+ import type { NodeExpression } from "../shacl/NodeExpression";
9
10
  export type WhereOps = {
10
11
  not: string | number | boolean | string[] | number[];
11
12
  between: [number, number];
@@ -89,11 +90,12 @@ export interface IncludeProjection {
89
90
  /** When true, attaches an integer count instead of a list. */
90
91
  count?: true;
91
92
  /**
92
- * Serialised target class shape. Set automatically by `executeModelQuery`
93
- * when a `where` clause is present and the target class is resolvable.
93
+ * Bare class name of the projection target. Set automatically by
94
+ * `prepareModelQueryParams`; the executor resolves the target's shape
95
+ * through its in-memory cache when applying projection where filters.
94
96
  * @internal
95
97
  */
96
- targetShape?: ModelMetadata;
98
+ targetClassName?: string;
97
99
  /** Post-hydration where clause applied to the target instances. */
98
100
  where?: Where;
99
101
  /** Limit results (when 1, the attached value is unwrapped to a scalar). */
@@ -142,6 +144,139 @@ export type Query = {
142
144
  * ```
143
145
  */
144
146
  export type RelationSubQuery = Omit<Query, 'parent' | 'count'>;
147
+ /** Keys of T that are user-declared (not methods, not inherited from Ad4mModel). */
148
+ export type ModelDataKeys<T extends Ad4mModel> = {
149
+ [K in keyof T]: K extends keyof Ad4mModel ? never : T[K] extends (...args: any[]) => any ? never : K;
150
+ }[keyof T];
151
+ /** Keys of T that can appear in a `where` clause — scalars and scalar arrays.
152
+ * Excludes typed Ad4mModel references (single or array); `string[]`/`number[]`
153
+ * remain included because they're often filterable even when also used as
154
+ * link targets.
155
+ *
156
+ * Iterates over `keyof T` directly (not `ModelDataKeys<T>`) to preserve the
157
+ * key constraint — mapped types over computed type aliases sometimes widen
158
+ * to `string | undefined` in the key position, which then breaks indexing. */
159
+ export type PropertyKeysOf<T extends Ad4mModel> = {
160
+ [K in keyof T]: K extends ModelDataKeys<T> ? NonNullable<T[K]> extends Ad4mModel ? never : NonNullable<T[K]> extends Ad4mModel[] ? never : K : never;
161
+ }[keyof T];
162
+ /** Keys of T that can appear in `include` — typed Ad4mModel references AND
163
+ * `string[]` link-target arrays (the `@HasMany` + `string[]` pattern that
164
+ * AD4M uses for relations without a target class thunk). Handles both
165
+ * `?: Foo` (optional → `Foo | undefined`) and `Foo | null` field shapes, and
166
+ * optional/nullable array variants (`?: Foo[]`, `Foo[] | null`). */
167
+ export type RelationKeysOf<T extends Ad4mModel> = {
168
+ [K in keyof T]: K extends ModelDataKeys<T> ? NonNullable<T[K]> extends Ad4mModel ? K : NonNullable<T[K]> extends Ad4mModel[] ? K : NonNullable<T[K]> extends string[] ? K : never : never;
169
+ }[keyof T];
170
+ /** The model type referenced by a relation field K on T.
171
+ * Falls back to `Ad4mModel` (loose) for the `string[]` relation pattern,
172
+ * since no target class is available at the type level. */
173
+ export type RelatedModel<T extends Ad4mModel, K extends RelationKeysOf<T>> = NonNullable<T[K]> extends (infer U)[] ? (U extends Ad4mModel ? U : Ad4mModel) : NonNullable<T[K]> extends Ad4mModel ? NonNullable<T[K]> : Ad4mModel;
174
+ /** True when T has no statically-declared data fields (e.g. fromSHACL classes). */
175
+ type HasNoTypedFields<T extends Ad4mModel> = [
176
+ PropertyKeysOf<T> | RelationKeysOf<T>
177
+ ] extends [never] ? true : false;
178
+ export type StringWhereOps = {
179
+ not?: string | string[];
180
+ contains?: string;
181
+ };
182
+ export type NumericWhereOps = {
183
+ not?: number | number[];
184
+ lt?: number;
185
+ lte?: number;
186
+ gt?: number;
187
+ gte?: number;
188
+ between?: [number, number];
189
+ };
190
+ export type TypedWhereCondition<V> = V extends string ? string | string[] | StringWhereOps : V extends number ? number | number[] | NumericWhereOps : V extends boolean ? boolean : V extends Array<infer U> ? U extends string ? string | string[] | StringWhereOps : U extends number ? number | number[] | NumericWhereOps : WhereCondition : WhereCondition;
191
+ /** Strict Where: keys constrained to T's properties, plus the well-known
192
+ * link-metadata fields (`id`/`author`/`timestamp`). */
193
+ type StrictTypedWhere<T extends Ad4mModel> = {
194
+ [K in PropertyKeysOf<T>]?: TypedWhereCondition<T[K]>;
195
+ } & {
196
+ base?: string | string[];
197
+ id?: string | string[];
198
+ author?: WhereCondition;
199
+ timestamp?: WhereCondition;
200
+ };
201
+ /** Public typed `where` for a model class. Falls back to the loose `Where`
202
+ * shape when T has no declared fields (e.g. fromSHACL-derived classes). */
203
+ export type TypedWhere<T extends Ad4mModel> = HasNoTypedFields<T> extends true ? Where : StrictTypedWhere<T>;
204
+ type StrictTypedOrder<T extends Ad4mModel> = {
205
+ [K in PropertyKeysOf<T> | 'timestamp' | 'author' | 'createdAt' | 'updatedAt']?: 'ASC' | 'DESC';
206
+ };
207
+ export type TypedOrder<T extends Ad4mModel> = HasNoTypedFields<T> extends true ? Order : StrictTypedOrder<T>;
208
+ /** Sub-query for an eager-loaded relation — inherits the target model's constraints. */
209
+ export type TypedRelationSubQuery<U extends Ad4mModel> = {
210
+ where?: TypedWhere<U>;
211
+ order?: TypedOrder<U>;
212
+ include?: TypedIncludeMap<U>;
213
+ limit?: number;
214
+ offset?: number;
215
+ };
216
+ /** Projection — `from` must be a real relation on T; `where`/`order` constrained to that target.
217
+ * Modelled as a discriminated union so the literal `count: true` and `limit: 1`
218
+ * variants narrow inference into `IncludeExtras` (count → number, limit-1 → scalar). */
219
+ export type TypedIncludeProjection<T extends Ad4mModel> = {
220
+ [K in RelationKeysOf<T>]: {
221
+ from: K;
222
+ count: true;
223
+ } | {
224
+ from: K;
225
+ limit: 1;
226
+ where?: TypedWhere<RelatedModel<T, K>>;
227
+ order?: TypedOrder<RelatedModel<T, K>>;
228
+ } | {
229
+ from: K;
230
+ limit?: number;
231
+ where?: TypedWhere<RelatedModel<T, K>>;
232
+ order?: TypedOrder<RelatedModel<T, K>>;
233
+ };
234
+ }[RelationKeysOf<T>];
235
+ type StrictTypedIncludeMap<T extends Ad4mModel> = {
236
+ [K in RelationKeysOf<T>]?: boolean | TypedRelationSubQuery<RelatedModel<T, K>>;
237
+ } & {
238
+ [K in `$${string}`]?: TypedIncludeProjection<T>;
239
+ };
240
+ export type TypedIncludeMap<T extends Ad4mModel> = HasNoTypedFields<T> extends true ? IncludeMap : StrictTypedIncludeMap<T>;
241
+ /**
242
+ * Given a model T and an `include` literal I, compute the extra fields
243
+ * contributed by `$`-prefixed projection keys.
244
+ *
245
+ * - `{ count: true }` → `number`
246
+ * - `{ from: R, limit: 1 }` → `RelatedModel<T,R> | null`
247
+ * - `{ from: R }` (no limit/1) → `RelatedModel<T,R>[]`
248
+ *
249
+ * Returns `unknown` (intersection-neutral) when `I` has no `$`-keys, so that
250
+ * `T & IncludeExtras<T, I>` collapses back to `T` and downstream type
251
+ * predicates (`(x): x is T => ...`) keep working unchanged.
252
+ */
253
+ export type IncludeExtras<T extends Ad4mModel, I> = I extends Record<string, any> ? Extract<keyof I, `$${string}`> extends never ? unknown : {
254
+ [K in Extract<keyof I, `$${string}`>]: I[K] extends {
255
+ count: true;
256
+ } ? number : I[K] extends {
257
+ from: infer R;
258
+ limit: 1;
259
+ } ? (R extends RelationKeysOf<T> ? RelatedModel<T, R> | null : never) : I[K] extends {
260
+ from: infer R;
261
+ } ? (R extends RelationKeysOf<T> ? RelatedModel<T, R>[] : never) : unknown;
262
+ } : unknown;
263
+ type StrictTypedQuery<T extends Ad4mModel> = {
264
+ parent?: ParentScope;
265
+ properties?: PropertyKeysOf<T>[];
266
+ include?: TypedIncludeMap<T>;
267
+ includeAll?: boolean;
268
+ where?: TypedWhere<T>;
269
+ order?: TypedOrder<T>;
270
+ offset?: number;
271
+ limit?: number;
272
+ count?: boolean;
273
+ deepQuery?: boolean;
274
+ };
275
+ export type TypedQuery<T extends Ad4mModel> = HasNoTypedFields<T> extends true ? Query : StrictTypedQuery<T>;
276
+ /** Helper that extracts the `include` literal from a TypedQuery for use with IncludeExtras. */
277
+ export type IncludeOf<Q> = Q extends {
278
+ include?: infer I;
279
+ } ? I : undefined;
145
280
  /**
146
281
  * Options accepted by the instance `get()` method.
147
282
  *
@@ -188,7 +323,7 @@ export interface PropertyMetadata {
188
323
  /** Whether stored locally only */
189
324
  local?: boolean;
190
325
  /** Transform function */
191
- transform?: (value: any) => any;
326
+ transform?: NodeExpression;
192
327
  /** Whether this is a flag property */
193
328
  flag?: boolean;
194
329
  }
@@ -227,3 +362,4 @@ export interface ModelMetadata {
227
362
  /** Map of relation name to metadata */
228
363
  relations: Record<string, RelationMetadata>;
229
364
  }
365
+ export {};
@@ -27,7 +27,7 @@ export declare class PerspectiveClient {
27
27
  publishSnapshotByUUID(uuid: string): Promise<string | null>;
28
28
  queryLinks(uuid: string, query: LinkQuery): Promise<LinkExpression[]>;
29
29
  queryProlog(uuid: string, query: string): Promise<unknown>;
30
- querySparql(uuid: string, query: string): Promise<unknown>;
30
+ querySparql<T = any>(uuid: string, query: string): Promise<T>;
31
31
  subscribeQuery(uuid: string, query: string): Promise<{
32
32
  subscriptionId: string;
33
33
  result: AllInstancesResult;
@@ -37,9 +37,9 @@ export declare class PerspectiveClient {
37
37
  subscribeToQueryUpdates(subscriptionId: string, onData: (result: AllInstancesResult) => void): () => void;
38
38
  keepAliveQuery(uuid: string, subscriptionId: string): Promise<boolean>;
39
39
  disposeQuerySubscription(uuid: string, subscriptionId: string): Promise<boolean>;
40
- modelQuery(uuid: string, className: string, queryJson: string, shapeJson?: string): Promise<any>;
41
- evaluateGetters(uuid: string, className: string, instanceIds: string[], shapeJson: string, propertyNames?: string[]): Promise<Record<string, Record<string, any>>>;
42
- modelSubscribe(uuid: string, className: string, queryJson: string, shapeJson?: string): Promise<{
40
+ modelQuery(uuid: string, className: string, queryJson: string): Promise<any>;
41
+ evaluateGetters(uuid: string, className: string, instanceIds: string[], propertyNames?: string[]): Promise<Record<string, Record<string, any>>>;
42
+ modelSubscribe(uuid: string, className: string, queryJson: string): Promise<{
43
43
  subscriptionId: string;
44
44
  result: any;
45
45
  }>;
@@ -148,22 +148,21 @@ export class PerspectiveClient {
148
148
  }
149
149
  return __classPrivateFieldGet(this, _PerspectiveClient_apiClient, "f").call('perspective.disposeQuery', { uuid, subscriptionId });
150
150
  }
151
- async modelQuery(uuid, className, queryJson, shapeJson) {
152
- const resultJson = await __classPrivateFieldGet(this, _PerspectiveClient_apiClient, "f").call('perspective.modelQuery', { uuid, class_name: className, query_json: queryJson, shape_json: shapeJson });
151
+ async modelQuery(uuid, className, queryJson) {
152
+ const resultJson = await __classPrivateFieldGet(this, _PerspectiveClient_apiClient, "f").call('perspective.modelQuery', { uuid, class_name: className, query_json: queryJson });
153
153
  return JSON.parse(resultJson);
154
154
  }
155
- async evaluateGetters(uuid, className, instanceIds, shapeJson, propertyNames) {
155
+ async evaluateGetters(uuid, className, instanceIds, propertyNames) {
156
156
  const resultJson = await __classPrivateFieldGet(this, _PerspectiveClient_apiClient, "f").call('perspective.evaluateGetters', {
157
157
  uuid,
158
158
  class_name: className,
159
159
  instance_ids: instanceIds,
160
- shape_json: shapeJson,
161
160
  ...(propertyNames && { property_names: propertyNames }),
162
161
  });
163
162
  return JSON.parse(resultJson);
164
163
  }
165
- async modelSubscribe(uuid, className, queryJson, shapeJson) {
166
- const response = await __classPrivateFieldGet(this, _PerspectiveClient_apiClient, "f").call('perspective.modelSubscribe', { uuid, class_name: className, query_json: queryJson, shape_json: shapeJson });
164
+ async modelSubscribe(uuid, className, queryJson) {
165
+ const response = await __classPrivateFieldGet(this, _PerspectiveClient_apiClient, "f").call('perspective.modelSubscribe', { uuid, class_name: className, query_json: queryJson });
167
166
  return {
168
167
  subscriptionId: response.subscription_id,
169
168
  result: JSON.parse(response.result)