@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
@@ -18,6 +18,7 @@ export declare class Ad4mClient {
18
18
  #private;
19
19
  constructor(baseUrl: string, token?: string, subscribe?: boolean, options?: {
20
20
  webSocketImpl?: new (url: string) => WebSocket;
21
+ fetchImpl?: typeof fetch;
21
22
  });
22
23
  get agent(): AgentClient;
23
24
  get expression(): ExpressionClient;
@@ -42,7 +42,7 @@ export class Ad4mClient {
42
42
  _Ad4mClient_aiClient.set(this, void 0);
43
43
  __classPrivateFieldSet(this, _Ad4mClient_baseUrl, baseUrl, "f");
44
44
  __classPrivateFieldSet(this, _Ad4mClient_token, token, "f");
45
- __classPrivateFieldSet(this, _Ad4mClient_apiClient, new ApiClient(baseUrl, token, options?.webSocketImpl), "f");
45
+ __classPrivateFieldSet(this, _Ad4mClient_apiClient, new ApiClient(baseUrl, token, options?.webSocketImpl, options?.fetchImpl), "f");
46
46
  __classPrivateFieldSet(this, _Ad4mClient_agentClient, new AgentClient(baseUrl, token, subscribe, __classPrivateFieldGet(this, _Ad4mClient_apiClient, "f")), "f");
47
47
  __classPrivateFieldSet(this, _Ad4mClient_expressionClient, new ExpressionClient(baseUrl, token, __classPrivateFieldGet(this, _Ad4mClient_apiClient, "f")), "f");
48
48
  __classPrivateFieldSet(this, _Ad4mClient_languageClient, new LanguageClient(baseUrl, token, __classPrivateFieldGet(this, _Ad4mClient_apiClient, "f")), "f");
@@ -120,7 +120,7 @@ export class AIClient {
120
120
  // Use slice to get only the relevant portion of the underlying ArrayBuffer
121
121
  // (Float32Array may be a view over a larger buffer)
122
122
  const bodyBuffer = typedAudio.buffer.slice(typedAudio.byteOffset, typedAudio.byteOffset + typedAudio.byteLength);
123
- const response = await fetch(`${baseUrl}/api/v1/ai/transcription/feed`, {
123
+ const response = await __classPrivateFieldGet(this, _AIClient_apiClient, "f").doFetch(`${baseUrl}/api/v1/ai/transcription/feed`, {
124
124
  method: 'POST',
125
125
  headers: {
126
126
  'Content-Type': 'application/octet-stream',
@@ -15,9 +15,12 @@ export declare class ApiClient {
15
15
  private baseUrl;
16
16
  private token?;
17
17
  private readonly _webSocketImpl?;
18
- constructor(baseUrl: string, token?: string, webSocketImpl?: new (url: string) => WebSocket);
18
+ private readonly _fetchImpl?;
19
+ constructor(baseUrl: string, token?: string, webSocketImpl?: new (url: string) => WebSocket, fetchImpl?: typeof fetch);
19
20
  getBaseUrl(): string;
20
21
  getToken(): string | undefined;
22
+ /** Perform an HTTP request, using an injected fetch implementation if provided. */
23
+ doFetch(url: string, init: RequestInit): Promise<Response>;
21
24
  setToken(token: string): void;
22
25
  private _ws;
23
26
  private _wsCallbacks;
@@ -19,7 +19,7 @@ function nextId() {
19
19
  return String(++_idCounter);
20
20
  }
21
21
  export class ApiClient {
22
- constructor(baseUrl, token, webSocketImpl) {
22
+ constructor(baseUrl, token, webSocketImpl, fetchImpl) {
23
23
  // ── WebSocket RPC core ──────────────────────────────────────────────────
24
24
  this._ws = null;
25
25
  this._wsCallbacks = new Set();
@@ -33,9 +33,14 @@ export class ApiClient {
33
33
  this.baseUrl = baseUrl;
34
34
  this.token = token;
35
35
  this._webSocketImpl = webSocketImpl;
36
+ this._fetchImpl = fetchImpl;
36
37
  }
37
38
  getBaseUrl() { return this.baseUrl; }
38
39
  getToken() { return this.token; }
40
+ /** Perform an HTTP request, using an injected fetch implementation if provided. */
41
+ doFetch(url, init) {
42
+ return this._fetchImpl ? this._fetchImpl(url, init) : fetch(url, init);
43
+ }
39
44
  setToken(token) {
40
45
  this.token = token;
41
46
  }
@@ -16,6 +16,7 @@ export * from "./Literal";
16
16
  export * from "./perspectives/Perspective";
17
17
  export * from "./perspectives/PerspectiveHandle";
18
18
  export * from "./perspectives/PerspectiveProxy";
19
+ export * from "./perspectives/SparqlBindings";
19
20
  export * from "./perspectives/WakerSubscriptionManager";
20
21
  export * from "./perspectives/PerspectiveDiff";
21
22
  export * from "./perspectives/LinkQuery";
@@ -33,6 +34,9 @@ export * from "./runtime/RuntimeTypes";
33
34
  export { Model as AIModel, ModelApi, TokenizerSource, LocalModel, ModelType, ModelApiInput, TokenizerSourceInput, LocalModelInput, ModelInput, VoiceActivityParamsInput } from "./ai/AITypes";
34
35
  export * from './shacl/SHACLShape';
35
36
  export { SHACLFlow, FlowState, FlowTransition, LinkPattern, FlowableCondition } from './shacl/SHACLFlow';
37
+ export * from './shacl/NodeExpression';
38
+ export * from './shacl/builders';
39
+ export { fileToDataUri } from './shacl/index';
36
40
  export * from "./generated/api";
37
41
  export { RpcError } from "./apiClient";
38
42
  /** @deprecated Use `RpcError` instead. */
package/lib/src/index.js CHANGED
@@ -16,6 +16,7 @@ export * from "./Literal";
16
16
  export * from "./perspectives/Perspective";
17
17
  export * from "./perspectives/PerspectiveHandle";
18
18
  export * from "./perspectives/PerspectiveProxy";
19
+ export * from "./perspectives/SparqlBindings";
19
20
  export * from "./perspectives/WakerSubscriptionManager";
20
21
  export * from "./perspectives/PerspectiveDiff";
21
22
  export * from "./perspectives/LinkQuery";
@@ -33,6 +34,9 @@ export * from "./runtime/RuntimeTypes";
33
34
  export { Model as AIModel, ModelApi, TokenizerSource, LocalModel, ModelApiInput, TokenizerSourceInput, LocalModelInput, ModelInput, VoiceActivityParamsInput } from "./ai/AITypes";
34
35
  export * from './shacl/SHACLShape';
35
36
  export { SHACLFlow } from './shacl/SHACLFlow';
37
+ export * from './shacl/NodeExpression';
38
+ export * from './shacl/builders';
39
+ export { fileToDataUri } from './shacl/index';
36
40
  export * from "./generated/api";
37
41
  export { RpcError } from "./apiClient";
38
42
  /** @deprecated Use `RpcError` instead. */
@@ -2,7 +2,7 @@ import { PerspectiveProxy } from "../perspectives/PerspectiveProxy";
2
2
  import type { SHACLShape } from "../shacl/SHACLShape";
3
3
  import type { JSONSchema, JSONSchemaToModelOptions } from "./json-schema";
4
4
  import { ModelQueryBuilder } from "./ModelQueryBuilder";
5
- import type { ParentScope, IncludeMap, Query, GetOptions, ResultsWithTotalCount, PaginationResult, ModelMetadata } from "./types";
5
+ import type { ParentScope, IncludeMap, Query, GetOptions, ResultsWithTotalCount, PaginationResult, ModelMetadata, TypedQuery, IncludeExtras, IncludeOf } from "./types";
6
6
  /**
7
7
  * Base class for defining data models in AD4M.
8
8
  *
@@ -300,13 +300,13 @@ export declare class Ad4mModel {
300
300
  static queryToSPARQL(perspective: PerspectiveProxy, query: Query): Promise<string>;
301
301
  /**
302
302
  * Build the JSON parameters needed for a model query/subscription endpoint.
303
- * Returns the className, queryJson, and shapeJson that the Rust executor expects.
303
+ * Returns the className and queryJson that the Rust executor expects.
304
+ * Shape resolution happens server-side from the perspective's SHACL triples.
304
305
  * @internal
305
306
  */
306
307
  static prepareModelQueryParams(query?: Query, classNameOverride?: string | null): {
307
308
  className: string;
308
309
  queryJson: string;
309
- shapeJson: string;
310
310
  metadata: ModelMetadata;
311
311
  };
312
312
  /**
@@ -315,21 +315,6 @@ export declare class Ad4mModel {
315
315
  * @internal
316
316
  */
317
317
  static parseModelResult<T extends Ad4mModel>(this: typeof Ad4mModel & (new (...args: any[]) => T), perspective: PerspectiveProxy, raw: any, include?: IncludeMap, properties?: string[]): T[];
318
- /**
319
- * Resolve non-literal (file-language) properties on an array of already-constructed
320
- * model instances. Handles two cases:
321
- *
322
- * 1. The Rust executor returned a raw URI string → fetch via `getExpression` then apply transform.
323
- * 2. The Rust executor already resolved the expression and returned a `FileData` object
324
- * (happens when the perspective backend eagerly fetches file content) → apply transform
325
- * (or `defaultFileDecode` if no transform is registered on the class, e.g. for SHACL-
326
- * synthesised model classes).
327
- *
328
- * Extracted as a public static so `ModelQueryBuilder.subscribe()` can reuse it without
329
- * duplicating logic or introducing a circular dependency.
330
- * @internal
331
- */
332
- static resolveNonLiteralProps<T extends Ad4mModel>(this: typeof Ad4mModel & (new (...args: any[]) => T), perspective: PerspectiveProxy, instances: T[]): Promise<void>;
333
318
  /**
334
319
  * Execute a model query via the executor-side endpoint.
335
320
  *
@@ -362,9 +347,7 @@ export declare class Ad4mModel {
362
347
  * });
363
348
  * ```
364
349
  */
365
- static findAll<T extends Ad4mModel>(this: typeof Ad4mModel & (new (...args: any[]) => T), perspective: PerspectiveProxy, query?: Query,
366
- /** @deprecated Ignored — Prolog engine has been removed. */
367
- _engine?: 'sparql' | 'prolog' | boolean): Promise<T[]>;
350
+ static findAll<T extends Ad4mModel, Q extends TypedQuery<T> = {}>(this: typeof Ad4mModel & (new (...args: any[]) => T), perspective: PerspectiveProxy, query?: Q): Promise<(T & IncludeExtras<T, IncludeOf<Q>>)[]>;
368
351
  /**
369
352
  * Finds the first instance matching the query, or `null` if none exists.
370
353
  *
@@ -385,9 +368,7 @@ export declare class Ad4mModel {
385
368
  * }
386
369
  * ```
387
370
  */
388
- static findOne<T extends Ad4mModel>(this: typeof Ad4mModel & (new (...args: any[]) => T), perspective: PerspectiveProxy, query?: Query,
389
- /** @deprecated Ignored — Prolog engine has been removed. */
390
- _engine?: 'sparql' | 'prolog' | boolean): Promise<T | null>;
371
+ static findOne<T extends Ad4mModel, Q extends TypedQuery<T> = {}>(this: typeof Ad4mModel & (new (...args: any[]) => T), perspective: PerspectiveProxy, query?: Q): Promise<(T & IncludeExtras<T, IncludeOf<Q>>) | null>;
391
372
  /**
392
373
  * Gets all instances with count of total matches without offset & limit applied.
393
374
  *
@@ -405,9 +386,7 @@ export declare class Ad4mModel {
405
386
  * console.log(`Showing 10 of ${totalCount} dessert recipes`);
406
387
  * ```
407
388
  */
408
- static findAllAndCount<T extends Ad4mModel>(this: typeof Ad4mModel & (new (...args: any[]) => T), perspective: PerspectiveProxy, query?: Query,
409
- /** @deprecated Ignored — Prolog engine has been removed. */
410
- _engine?: 'sparql' | 'prolog' | boolean): Promise<ResultsWithTotalCount<T>>;
389
+ static findAllAndCount<T extends Ad4mModel, Q extends TypedQuery<T> = {}>(this: typeof Ad4mModel & (new (...args: any[]) => T), perspective: PerspectiveProxy, query?: Q): Promise<ResultsWithTotalCount<T & IncludeExtras<T, IncludeOf<Q>>>>;
411
390
  /**
412
391
  * Helper function for pagination with explicit page size and number.
413
392
  *
@@ -425,9 +404,7 @@ export declare class Ad4mModel {
425
404
  * console.log(`Page ${page.pageNumber} of recipes, ${page.results.length} items`);
426
405
  * ```
427
406
  */
428
- static paginate<T extends Ad4mModel>(this: typeof Ad4mModel & (new (...args: any[]) => T), perspective: PerspectiveProxy, pageSize: number, pageNumber: number, query?: Query,
429
- /** @deprecated Ignored — Prolog engine has been removed. */
430
- _engine?: 'sparql' | 'prolog' | boolean): Promise<PaginationResult<T>>;
407
+ static paginate<T extends Ad4mModel, Q extends TypedQuery<T> = {}>(this: typeof Ad4mModel & (new (...args: any[]) => T), perspective: PerspectiveProxy, pageSize: number, pageNumber: number, query?: Q): Promise<PaginationResult<T & IncludeExtras<T, IncludeOf<Q>>>>;
431
408
  /**
432
409
  * Generates a SPARQL COUNT query for the model.
433
410
  *
@@ -452,7 +429,7 @@ export declare class Ad4mModel {
452
429
  * });
453
430
  * ```
454
431
  */
455
- static count(perspective: PerspectiveProxy, query?: Query): Promise<number>;
432
+ static count<T extends Ad4mModel>(this: typeof Ad4mModel & (new (...args: any[]) => T), perspective: PerspectiveProxy, query?: TypedQuery<T>): Promise<number>;
456
433
  private setProperty;
457
434
  /** Resolve a relation argument to a plain string ID. Accepts either a raw
458
435
  * string ID or an Ad4mModel instance (in which case `.id` is used). */
@@ -721,7 +698,7 @@ export declare class Ad4mModel {
721
698
  * });
722
699
  * ```
723
700
  */
724
- static query<T extends Ad4mModel>(this: typeof Ad4mModel & (new (...args: any[]) => T), perspective: PerspectiveProxy, query?: Query): ModelQueryBuilder<T>;
701
+ static query<T extends Ad4mModel>(this: typeof Ad4mModel & (new (...args: any[]) => T), perspective: PerspectiveProxy, query?: TypedQuery<T>): ModelQueryBuilder<T>;
725
702
  /**
726
703
  * Creates an Ad4mModel class from a JSON Schema definition.
727
704
  *
@@ -2,97 +2,15 @@ import { Literal } from "../Literal";
2
2
  import { Link } from "../links/Links";
3
3
  import { LinkQuery } from "../perspectives/LinkQuery";
4
4
  import { makeRandomId } from "./util";
5
- import { getPropertiesMetadata, getRelationsMetadata, buildConformanceFilter, setPropertyRegistryEntry, setRelationRegistryEntry, Model } from "./decorators";
5
+ import { getPropertiesMetadata, getRelationsMetadata, setPropertyRegistryEntry, setRelationRegistryEntry, Model } from "./decorators";
6
6
  import { resolveParentPredicate } from "./query-common";
7
7
  import { isArrayType, determinePredicate, determineNamespace, buildModelFromJSONSchema } from "./json-schema";
8
8
  import { buildSPARQLQuery } from "./query-sparql";
9
9
  import { ModelQueryBuilder } from "./ModelQueryBuilder";
10
10
  import { normalizeValue, } from "./hydration";
11
11
  // ---------------------------------------------------------------------------
12
- // Default decoder for file-storage (non-literal resolveLanguage) properties
13
- // ---------------------------------------------------------------------------
14
- /**
15
- * When the Rust executor resolves a non-literal expression it may return a
16
- * `FileData`-shaped object (`{ data_base64, file_type, ... }`) rather than a
17
- * raw URI string. If the model class has no custom `transform` registered
18
- * (e.g. it was synthesised from a SHACL shape at runtime) we still want to
19
- * decode the content rather than passing raw `FileData` to callers.
20
- *
21
- * Decoding rules (mirrors the JS `decodeFileAsJson` / `decodeFileAsString` helpers):
22
- * - `application/json` (default when `file_type` is absent) → JSON.parse
23
- * - anything else → raw decoded string
24
- *
25
- * If `resolved` is not a `FileData` object the value is returned unchanged so
26
- * that callers can use this as a safe unconditional fallback.
27
- */
28
- function defaultFileDecode(resolved) {
29
- if (resolved !== null &&
30
- typeof resolved === 'object' &&
31
- 'data_base64' in resolved) {
32
- const fd = resolved;
33
- let raw;
34
- try {
35
- raw = atob(fd.data_base64);
36
- }
37
- catch {
38
- return resolved; // malformed base64 — keep as-is
39
- }
40
- const isJson = !fd.file_type || fd.file_type === 'application/json';
41
- if (isJson) {
42
- try {
43
- return JSON.parse(raw);
44
- }
45
- catch {
46
- return raw;
47
- }
48
- }
49
- return raw;
50
- }
51
- return resolved;
52
- }
53
- // ---------------------------------------------------------------------------
54
12
  // Helpers for Rust-side include resolution
55
13
  // ---------------------------------------------------------------------------
56
- /**
57
- * Recursively enrich relation metadata in the shape with target class shapes
58
- * so the Rust endpoint can resolve includes in-process (no extra GraphQL
59
- * round-trips per relation).
60
- */
61
- function enrichShapeForIncludes(metadata, include, allRelMeta) {
62
- for (const [relName, includeVal] of Object.entries(include)) {
63
- if (!includeVal)
64
- continue;
65
- const meta = allRelMeta[relName];
66
- if (!meta?.target)
67
- continue;
68
- const TargetClass = meta.target();
69
- // Deep-copy so we don't mutate the cached metadata
70
- const targetMeta = JSON.parse(JSON.stringify(TargetClass.getModelMetadata()));
71
- // Ensure the relation is in metadata.relations (fallback for edge cases)
72
- if (!metadata.relations[relName]) {
73
- metadata.relations[relName] = {
74
- name: relName,
75
- predicate: meta.predicate,
76
- direction: meta.kind === 'belongsToMany' || meta.kind === 'belongsToOne'
77
- ? 'reverse'
78
- : 'forward',
79
- };
80
- }
81
- const rel = metadata.relations[relName];
82
- rel.kind = meta.kind;
83
- rel.maxCount = meta.maxCount;
84
- rel.targetShape = targetMeta;
85
- rel.targetClassName = targetMeta.className;
86
- // Recurse for nested includes
87
- const nested = typeof includeVal === 'object' && includeVal !== null
88
- ? includeVal.include
89
- : undefined;
90
- if (nested) {
91
- const targetRelMeta = getRelationsMetadata(TargetClass);
92
- enrichShapeForIncludes(targetMeta, nested, targetRelMeta);
93
- }
94
- }
95
- }
96
14
  /**
97
15
  * Construct a model class instance from a plain JSON object returned by the
98
16
  * Rust endpoint. Recursively converts included relation values (which come
@@ -137,24 +55,6 @@ function jsonToModelInstance(ModelClass, perspective, json, include, properties)
137
55
  }
138
56
  instance[key] = value;
139
57
  }
140
- // Apply property transform functions from decorators (only for literal-resolved
141
- // or no-resolveLanguage properties; non-literal properties are resolved + transformed
142
- // asynchronously in executeModelQuery).
143
- try {
144
- const propsMeta = getPropertiesMetadata(ModelClass);
145
- for (const [propName, opts] of Object.entries(propsMeta)) {
146
- const o = opts;
147
- if (typeof o.transform !== 'function' || !(propName in json))
148
- continue;
149
- // Skip non-literal resolveLanguage props — they need async expression resolution first
150
- if (o.resolveLanguage != null && o.resolveLanguage !== 'literal')
151
- continue;
152
- instance[propName] = o.transform(instance[propName]);
153
- }
154
- }
155
- catch (e) {
156
- console.debug('jsonToModelInstance: transform metadata unavailable:', e);
157
- }
158
58
  // Recursively convert included relation values to class instances
159
59
  if (include) {
160
60
  const relMeta = getRelationsMetadata(ModelClass);
@@ -392,8 +292,8 @@ export class Ad4mModel {
392
292
  ...(options.getter !== undefined && { getter: options.getter }),
393
293
  ...(options.prologSetter !== undefined && { prologSetter: options.prologSetter }),
394
294
  ...(options.local !== undefined && { local: options.local }),
395
- ...(options.transform !== undefined && { transform: options.transform }),
396
- ...(options.flag !== undefined && { flag: options.flag })
295
+ ...(options.flag !== undefined && { flag: options.flag }),
296
+ ...(options.transform !== undefined && { transform: options.transform })
397
297
  };
398
298
  }
399
299
  // Extract relations (relations) from WeakMap registry
@@ -774,7 +674,8 @@ export class Ad4mModel {
774
674
  }
775
675
  /**
776
676
  * Build the JSON parameters needed for a model query/subscription endpoint.
777
- * Returns the className, queryJson, and shapeJson that the Rust executor expects.
677
+ * Returns the className and queryJson that the Rust executor expects.
678
+ * Shape resolution happens server-side from the perspective's SHACL triples.
778
679
  * @internal
779
680
  */
780
681
  static prepareModelQueryParams(query = {}, classNameOverride) {
@@ -814,16 +715,18 @@ export class Ad4mModel {
814
715
  if (Object.keys(normalIncludes).length > 0)
815
716
  queryInput.include = normalIncludes;
816
717
  if (Object.keys(projections).length > 0) {
817
- // Enrich projections with target shapes so Rust can apply where clause filtering
718
+ // Tag each projection with its target class name so the executor can
719
+ // resolve the target shape through its in-memory cache when applying
720
+ // projection where-clause filters.
818
721
  const allRelMeta = getRelationsMetadata(this);
819
722
  for (const [, proj] of Object.entries(projections)) {
820
723
  const relMeta = allRelMeta[proj.from];
821
- if (!proj.targetShape && relMeta?.target) {
724
+ if (!proj.targetClassName && relMeta?.target) {
822
725
  try {
823
726
  const TargetClass = relMeta.target();
824
727
  const targetMeta = TargetClass.getModelMetadata?.();
825
- if (targetMeta) {
826
- proj.targetShape = targetMeta;
728
+ if (targetMeta?.className) {
729
+ proj.targetClassName = targetMeta.className;
827
730
  }
828
731
  }
829
732
  catch (e) {
@@ -846,64 +749,12 @@ export class Ad4mModel {
846
749
  if (query.count !== undefined)
847
750
  queryInput.count = query.count;
848
751
  queryInput.deepQuery = query.deepQuery ?? true;
849
- if (queryInput.include) {
850
- const allRelMeta = getRelationsMetadata(this);
851
- enrichShapeForIncludes(metadata, queryInput.include, allRelMeta);
852
- }
853
- // Pre-compute conformance getters for Rust-side evaluation.
854
- // Where clauses are NOT compiled into getter SPARQL because stored
855
- // property values are signed expression envelopes (literal:json:...),
856
- // not simple literal:string:X values. Instead, where clauses are
857
- // attached as metadata for Rust-side post-evaluation filtering.
858
- {
859
- const allRelMeta = getRelationsMetadata(this);
860
- for (const [relName, relMeta] of Object.entries(metadata.relations)) {
861
- const rel = relMeta;
862
- if (rel.getter || rel.direction === 'reverse' || rel.filter === false)
863
- continue;
864
- const meta = allRelMeta[relName];
865
- if (!meta?.target)
866
- continue;
867
- try {
868
- const TargetClass = meta.target();
869
- const filter = buildConformanceFilter(meta.predicate, TargetClass);
870
- if (filter) {
871
- rel.getter = filter.getter;
872
- }
873
- // Attach where-clause metadata for Rust-side post-getter filtering
874
- if (rel.where) {
875
- try {
876
- const targetMetadata = TargetClass.getModelMetadata?.() ?? null;
877
- if (targetMetadata) {
878
- const predicates = {};
879
- for (const propName of Object.keys(rel.where)) {
880
- if (['id', 'author', 'timestamp'].includes(propName))
881
- continue;
882
- const propMeta = targetMetadata.properties[propName];
883
- if (propMeta?.predicate) {
884
- predicates[propName] = propMeta.predicate;
885
- }
886
- }
887
- if (Object.keys(predicates).length > 0) {
888
- rel.whereFilter = rel.where;
889
- rel.wherePredicates = predicates;
890
- }
891
- }
892
- }
893
- catch (e) {
894
- console.debug(`prepareModelQueryParams: target metadata unavailable for relation '${relName}':`, e);
895
- }
896
- }
897
- }
898
- catch (e) {
899
- console.debug(`prepareModelQueryParams: target class unavailable for relation '${relName}':`, e);
900
- }
901
- }
902
- }
752
+ // Conformance getters, where filters, and target shapes for includes
753
+ // are all resolved by the executor from the perspective's SHACL triples
754
+ // — no client-side pre-computation is needed any more.
903
755
  return {
904
756
  className,
905
757
  queryJson: JSON.stringify(queryInput),
906
- shapeJson: JSON.stringify(metadata),
907
758
  metadata,
908
759
  };
909
760
  }
@@ -919,57 +770,6 @@ export class Ad4mModel {
919
770
  return [];
920
771
  return arr.map((json) => jsonToModelInstance(this, perspective, json, include, properties));
921
772
  }
922
- /**
923
- * Resolve non-literal (file-language) properties on an array of already-constructed
924
- * model instances. Handles two cases:
925
- *
926
- * 1. The Rust executor returned a raw URI string → fetch via `getExpression` then apply transform.
927
- * 2. The Rust executor already resolved the expression and returned a `FileData` object
928
- * (happens when the perspective backend eagerly fetches file content) → apply transform
929
- * (or `defaultFileDecode` if no transform is registered on the class, e.g. for SHACL-
930
- * synthesised model classes).
931
- *
932
- * Extracted as a public static so `ModelQueryBuilder.subscribe()` can reuse it without
933
- * duplicating logic or introducing a circular dependency.
934
- * @internal
935
- */
936
- static async resolveNonLiteralProps(perspective, instances) {
937
- const propsMeta = getPropertiesMetadata(this);
938
- const resolveProps = Object.entries(propsMeta).filter(([, opts]) => opts.resolveLanguage != null &&
939
- opts.resolveLanguage !== 'literal');
940
- if (resolveProps.length === 0)
941
- return;
942
- await Promise.all(instances.map(async (inst) => {
943
- for (const [propName, opts] of resolveProps) {
944
- const val = inst[propName];
945
- const transform = opts.transform;
946
- const applyTransform = (resolved) => typeof transform === 'function' ? transform(resolved) : defaultFileDecode(resolved);
947
- if (typeof val === 'string' && val && !val.startsWith('literal:')) {
948
- // Case 1: raw URI — fetch from language runtime
949
- try {
950
- const expression = await perspective.getExpression(val);
951
- if (expression) {
952
- let resolved;
953
- try {
954
- resolved = JSON.parse(expression.data);
955
- }
956
- catch {
957
- resolved = expression.data;
958
- }
959
- inst[propName] = applyTransform(resolved);
960
- }
961
- }
962
- catch (e) {
963
- console.debug(`resolveNonLiteralProps: resolution failed for '${propName}':`, e);
964
- }
965
- }
966
- else if (val !== null && val !== undefined && typeof val === 'object') {
967
- // Case 2: already resolved by Rust — apply transform / default decode
968
- inst[propName] = applyTransform(val);
969
- }
970
- }
971
- }));
972
- }
973
773
  // instancesFromQueryResult — removed (superseded by Rust executeModelQuery pipeline)
974
774
  /**
975
775
  * Execute a model query via the executor-side endpoint.
@@ -980,20 +780,15 @@ export class Ad4mModel {
980
780
  * @internal
981
781
  */
982
782
  static async executeModelQuery(perspective, query = {}, classNameOverride) {
983
- // Delegate all query input building, shape enrichment, and getter
984
- // pre-computation to the shared prepareModelQueryParams helper.
985
- const { className, queryJson, shapeJson } = this.prepareModelQueryParams(query, classNameOverride);
986
- const result = await perspective.modelQuery(className, queryJson, shapeJson);
783
+ // Delegate query input building to the shared prepareModelQueryParams
784
+ // helper. The executor resolves the shape from SHACL server-side.
785
+ const { className, queryJson } = this.prepareModelQueryParams(query, classNameOverride);
786
+ const result = await perspective.modelQuery(className, queryJson);
987
787
  // Convert JSON instances to model class instances, recursively constructing
988
788
  // class instances for any included relations resolved by Rust.
989
789
  const instances = result.instances.map((json) => {
990
790
  return jsonToModelInstance(this, perspective, json, query.include, query.properties);
991
791
  });
992
- // Resolve non-literal expressions (e.g. file languages where the stored
993
- // value is a content-addressed hash that must be fetched from the language
994
- // runtime). The Rust endpoint may return either a raw target URI (string)
995
- // or an already-resolved FileData object — both cases are handled here.
996
- await this.resolveNonLiteralProps(perspective, instances);
997
792
  // Take snapshots for dirty tracking (exclude $-prefixed projection keys)
998
793
  const snapshotRelations = query.include
999
794
  ? Object.fromEntries(Object.entries(query.include).filter(([k]) => !k.startsWith('$')))
@@ -1029,13 +824,12 @@ export class Ad4mModel {
1029
824
  * });
1030
825
  * ```
1031
826
  */
1032
- static async findAll(perspective, query = {},
1033
- /** @deprecated Ignored — Prolog engine has been removed. */
1034
- _engine) {
1035
- if (query.properties && query.properties.length === 0) {
827
+ static async findAll(perspective, query) {
828
+ const q = (query ?? {});
829
+ if (q.properties && q.properties.length === 0) {
1036
830
  throw new Error("properties[] must not be empty — omit the field to return all properties, or specify at least one field name");
1037
831
  }
1038
- const { results } = await this.executeModelQuery(perspective, query);
832
+ const { results } = await this.executeModelQuery(perspective, q);
1039
833
  return results;
1040
834
  }
1041
835
  /**
@@ -1058,10 +852,8 @@ export class Ad4mModel {
1058
852
  * }
1059
853
  * ```
1060
854
  */
1061
- static async findOne(perspective, query = {},
1062
- /** @deprecated Ignored — Prolog engine has been removed. */
1063
- _engine) {
1064
- const limitedQuery = { ...query, limit: 1 };
855
+ static async findOne(perspective, query) {
856
+ const limitedQuery = { ...(query ?? {}), limit: 1 };
1065
857
  const results = await this.findAll(perspective, limitedQuery);
1066
858
  return results[0] ?? null;
1067
859
  }
@@ -1082,10 +874,9 @@ export class Ad4mModel {
1082
874
  * console.log(`Showing 10 of ${totalCount} dessert recipes`);
1083
875
  * ```
1084
876
  */
1085
- static async findAllAndCount(perspective, query = {},
1086
- /** @deprecated Ignored — Prolog engine has been removed. */
1087
- _engine) {
1088
- return await this.executeModelQuery(perspective, query);
877
+ static async findAllAndCount(perspective, query) {
878
+ const out = await this.executeModelQuery(perspective, (query ?? {}));
879
+ return out;
1089
880
  }
1090
881
  /**
1091
882
  * Helper function for pagination with explicit page size and number.
@@ -1104,12 +895,10 @@ export class Ad4mModel {
1104
895
  * console.log(`Page ${page.pageNumber} of recipes, ${page.results.length} items`);
1105
896
  * ```
1106
897
  */
1107
- static async paginate(perspective, pageSize, pageNumber, query,
1108
- /** @deprecated Ignored — Prolog engine has been removed. */
1109
- _engine) {
1110
- const paginationQuery = { ...(query || {}), limit: pageSize, offset: pageSize * (pageNumber - 1), count: true };
898
+ static async paginate(perspective, pageSize, pageNumber, query) {
899
+ const paginationQuery = { ...(query ?? {}), limit: pageSize, offset: pageSize * (pageNumber - 1), count: true };
1111
900
  const { results, totalCount } = await this.executeModelQuery(perspective, paginationQuery);
1112
- return { results, totalCount, pageSize, pageNumber };
901
+ return { results: results, totalCount, pageSize, pageNumber };
1113
902
  }
1114
903
  /**
1115
904
  * Generates a SPARQL COUNT query for the model.
@@ -1136,8 +925,8 @@ export class Ad4mModel {
1136
925
  * });
1137
926
  * ```
1138
927
  */
1139
- static async count(perspective, query = {}) {
1140
- const { totalCount } = await this.executeModelQuery(perspective, { ...query, limit: 0 });
928
+ static async count(perspective, query) {
929
+ const { totalCount } = await this.executeModelQuery(perspective, { ...(query ?? {}), limit: 0 });
1141
930
  return totalCount;
1142
931
  }
1143
932
  async setProperty(key, value, batchId) {
@@ -1448,29 +1237,10 @@ export class Ad4mModel {
1448
1237
  if (instances.length === 0)
1449
1238
  return;
1450
1239
  const metadata = this.getModelMetadata();
1451
- // Pre-compute conformance getters so the shape sent to Rust includes them
1452
- const allRelMeta = getRelationsMetadata(this);
1453
- for (const [relName, relMeta] of Object.entries(metadata.relations)) {
1454
- const rel = relMeta;
1455
- if (rel.getter || rel.direction === 'reverse' || rel.filter === false)
1456
- continue;
1457
- const meta = allRelMeta[relName];
1458
- if (!meta?.target)
1459
- continue;
1460
- try {
1461
- const TargetClass = meta.target();
1462
- const filter = buildConformanceFilter(meta.predicate, TargetClass);
1463
- if (filter)
1464
- rel.getter = filter.getter;
1465
- }
1466
- catch (e) {
1467
- console.debug(`evaluateGetters: target class unavailable for relation '${relName}':`, e);
1468
- }
1469
- }
1470
- const shapeJson = JSON.stringify(metadata);
1471
1240
  const instanceIds = instances.map(inst => inst.id || inst._baseExpression);
1472
- // Single RPC call evaluates all getters in-process on the executor
1473
- const result = await perspective.evaluateGetters(metadata.className, instanceIds, shapeJson, propertyNames);
1241
+ // The executor reads getter SPARQL from the perspective's SHACL triples
1242
+ // (written by `addSdna`), so no shape JSON is shipped with the call.
1243
+ const result = await perspective.evaluateGetters(metadata.className, instanceIds, propertyNames);
1474
1244
  // Determine which property names were evaluated for snapshot sync
1475
1245
  const evaluatedPropertyNames = [];
1476
1246
  for (const [propName, propMeta] of Object.entries(metadata.properties)) {
@@ -1834,7 +1604,7 @@ export class Ad4mModel {
1834
1604
  * ```
1835
1605
  */
1836
1606
  static query(perspective, query) {
1837
- return new ModelQueryBuilder(perspective, this, query);
1607
+ return new ModelQueryBuilder(perspective, this, (query ?? {}));
1838
1608
  }
1839
1609
  /**
1840
1610
  * Creates an Ad4mModel class from a JSON Schema definition.