@coasys/ad4m 0.13.0-test-7 → 0.13.0-test-8-profile-cache-fix

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 (63) hide show
  1. package/lib/index.cjs +1121 -835
  2. package/lib/index.js +1108 -835
  3. package/lib/src/Ad4mClient.d.ts +4 -1
  4. package/lib/src/Ad4mClient.js +2 -2
  5. package/lib/src/agent/AgentClient.d.ts +3 -0
  6. package/lib/src/agent/AgentClient.js +27 -5
  7. package/lib/src/ai/AIClient.js +1 -1
  8. package/lib/src/apiClient.d.ts +5 -1
  9. package/lib/src/apiClient.js +14 -6
  10. package/lib/src/index.d.ts +4 -0
  11. package/lib/src/index.js +4 -0
  12. package/lib/src/model/Ad4mModel.d.ts +30 -36
  13. package/lib/src/model/Ad4mModel.js +93 -382
  14. package/lib/src/model/ModelQueryBuilder.d.ts +5 -10
  15. package/lib/src/model/ModelQueryBuilder.js +142 -62
  16. package/lib/src/model/decorators.d.ts +7 -4
  17. package/lib/src/model/decorators.js +0 -7
  18. package/lib/src/model/query-sparql.d.ts +0 -10
  19. package/lib/src/model/query-sparql.js +12 -17
  20. package/lib/src/model/shacl-gen.js +120 -47
  21. package/lib/src/model/types.d.ts +140 -4
  22. package/lib/src/perspectives/PerspectiveClient.d.ts +13 -4
  23. package/lib/src/perspectives/PerspectiveClient.js +22 -6
  24. package/lib/src/perspectives/PerspectiveProxy.d.ts +27 -7
  25. package/lib/src/perspectives/PerspectiveProxy.js +60 -12
  26. package/lib/src/perspectives/SparqlBindings.d.ts +47 -0
  27. package/lib/src/perspectives/SparqlBindings.js +65 -0
  28. package/lib/src/perspectives/WakerSubscriptionManager.js +5 -4
  29. package/lib/src/shacl/NodeExpression.d.ts +44 -0
  30. package/lib/src/shacl/NodeExpression.js +39 -0
  31. package/lib/src/shacl/SHACLShape.d.ts +23 -0
  32. package/lib/src/shacl/SHACLShape.js +115 -1
  33. package/lib/src/shacl/builders.d.ts +58 -0
  34. package/lib/src/shacl/builders.js +76 -0
  35. package/lib/src/shacl/index.d.ts +36 -0
  36. package/lib/src/shacl/index.js +33 -0
  37. package/package.json +1 -1
  38. package/src/Ad4mClient.ts +7 -2
  39. package/src/agent/AgentClient.ts +35 -7
  40. package/src/ai/AIClient.ts +1 -1
  41. package/src/apiClient.ts +17 -6
  42. package/src/index.ts +4 -0
  43. package/src/model/Ad4mModel.test.ts +274 -72
  44. package/src/model/Ad4mModel.ts +140 -420
  45. package/src/model/ModelQueryBuilder.ts +136 -71
  46. package/src/model/decorators.ts +7 -13
  47. package/src/model/query-sparql.test.ts +36 -20
  48. package/src/model/query-sparql.ts +12 -18
  49. package/src/model/relation-filtering.test.ts +46 -39
  50. package/src/model/shacl-gen.ts +128 -54
  51. package/src/model/shacl-roundtrip.test.ts +197 -0
  52. package/src/model/types-typed-query.test.ts +360 -0
  53. package/src/model/types.ts +196 -4
  54. package/src/perspectives/PerspectiveClient.ts +24 -8
  55. package/src/perspectives/PerspectiveProxy.test.ts +85 -1
  56. package/src/perspectives/PerspectiveProxy.ts +65 -20
  57. package/src/perspectives/SparqlBindings.ts +79 -0
  58. package/src/perspectives/WakerSubscriptionManager.ts +5 -4
  59. package/src/shacl/NodeExpression.ts +54 -0
  60. package/src/shacl/SHACLShape.test.ts +172 -0
  61. package/src/shacl/SHACLShape.ts +173 -1
  62. package/src/shacl/builders.ts +86 -0
  63. package/src/shacl/index.ts +72 -0
package/lib/index.js CHANGED
@@ -19,7 +19,7 @@ function nextId() {
19
19
  return String(++_idCounter);
20
20
  }
21
21
  class ApiClient {
22
- constructor(baseUrl, token) {
22
+ constructor(baseUrl, token, webSocketImpl, fetchImpl) {
23
23
  // ── WebSocket RPC core ──────────────────────────────────────────────────
24
24
  this._ws = null;
25
25
  this._wsCallbacks = new Set();
@@ -32,9 +32,15 @@ class ApiClient {
32
32
  this._wsPingTimer = null;
33
33
  this.baseUrl = baseUrl;
34
34
  this.token = token;
35
+ this._webSocketImpl = webSocketImpl;
36
+ this._fetchImpl = fetchImpl;
35
37
  }
36
38
  getBaseUrl() { return this.baseUrl; }
37
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
+ }
38
44
  setToken(token) {
39
45
  this.token = token;
40
46
  }
@@ -47,7 +53,7 @@ class ApiClient {
47
53
  return tokenParam ? `${wsBase}${path}?${tokenParam}` : `${wsBase}${path}`;
48
54
  }
49
55
  _ensureWs() {
50
- if (this._ws && (this._ws.readyState === WebSocket.OPEN || this._ws.readyState === WebSocket.CONNECTING)) {
56
+ if (this._ws && (this._ws.readyState === 1 /* OPEN */ || this._ws.readyState === 0 /* CONNECTING */)) {
51
57
  return;
52
58
  }
53
59
  // Prevent duplicate connections from concurrent callers
@@ -58,7 +64,8 @@ class ApiClient {
58
64
  this._wsReadyResolve = resolve;
59
65
  });
60
66
  const url = this._getWsUrl();
61
- const ws = new WebSocket(url);
67
+ const WsImpl = this._webSocketImpl ?? WebSocket;
68
+ const ws = new WsImpl(url);
62
69
  this._ws = ws;
63
70
  ws.onopen = () => {
64
71
  this._wsReconnectDelay = INITIAL_RECONNECT_DELAY_MS;
@@ -108,12 +115,13 @@ class ApiClient {
108
115
  // Reset the readiness promise so future calls reconnect
109
116
  this._wsReady = null;
110
117
  // Reject all pending calls
118
+ const hadPendingCalls = this._pendingCalls.size > 0;
111
119
  for (const [id, pending] of this._pendingCalls) {
112
120
  clearTimeout(pending.timer);
113
121
  pending.reject(new RpcError(503, 'WebSocket connection closed'));
114
122
  }
115
123
  this._pendingCalls.clear();
116
- if (!this._wsClosed && (this._wsCallbacks.size > 0 || this._pendingCalls.size > 0)) {
124
+ if (!this._wsClosed && (this._wsCallbacks.size > 0 || hadPendingCalls)) {
117
125
  this._scheduleReconnect();
118
126
  }
119
127
  };
@@ -121,7 +129,7 @@ class ApiClient {
121
129
  _startPing() {
122
130
  this._stopPing();
123
131
  this._wsPingTimer = setInterval(() => {
124
- if (this._ws && this._ws.readyState === WebSocket.OPEN) {
132
+ if (this._ws && this._ws.readyState === 1 /* OPEN */) {
125
133
  this._ws.send(JSON.stringify({ type: 'ping' }));
126
134
  }
127
135
  }, 30000);
@@ -174,7 +182,7 @@ class ApiClient {
174
182
  reject,
175
183
  timer,
176
184
  });
177
- if (this._ws && this._ws.readyState === WebSocket.OPEN) {
185
+ if (this._ws && this._ws.readyState === 1 /* OPEN */) {
178
186
  this._ws.send(JSON.stringify(message));
179
187
  }
180
188
  else {
@@ -951,6 +959,46 @@ function buildSDNA(subjectName, obj, properties, allRelationsMeta) {
951
959
  };
952
960
  }
953
961
 
962
+ /**
963
+ * SHACL-AF Node Expressions for property transforms.
964
+ *
965
+ * A `NodeExpression` is a JSON-serializable tree that describes how to transform
966
+ * a resolved property value. Unlike JS lambdas, these are portable, inspectable,
967
+ * and can be executed in the Rust model query engine.
968
+ *
969
+ * Each expression is a tagged union that evaluates to a `Value` (JSON-compatible).
970
+ */
971
+ /**
972
+ * Type guard to check if a value is a valid NodeExpression.
973
+ */
974
+ function isNodeExpression(v) {
975
+ if (typeof v !== 'object' || v === null)
976
+ return false;
977
+ const obj = v;
978
+ const type = obj.type;
979
+ switch (type) {
980
+ case 'focus':
981
+ return typeof obj.type === 'string';
982
+ case 'literal':
983
+ return typeof obj.value === 'string' || typeof obj.value === 'number' || typeof obj.value === 'boolean';
984
+ case 'path':
985
+ return typeof obj.predicate === 'string';
986
+ case 'exists':
987
+ return isNodeExpression(obj.expr);
988
+ case 'if':
989
+ return isNodeExpression(obj.cond) && isNodeExpression(obj.then) &&
990
+ (obj.else === undefined || isNodeExpression(obj.else));
991
+ case 'concat':
992
+ return Array.isArray(obj.args) && obj.args.every(isNodeExpression);
993
+ case 'coalesce':
994
+ return Array.isArray(obj.args) && obj.args.every(isNodeExpression);
995
+ case 'function':
996
+ return typeof obj.iri === 'string' && Array.isArray(obj.args) && obj.args.every(isNodeExpression);
997
+ default:
998
+ return false;
999
+ }
1000
+ }
1001
+
954
1002
  /**
955
1003
  * Extract namespace from a URI
956
1004
  * Examples:
@@ -1281,7 +1329,7 @@ class SHACLShape {
1281
1329
  target: `literal:${prop.writable}`
1282
1330
  });
1283
1331
  }
1284
- if (prop.resolveLanguage) {
1332
+ if (prop.resolveLanguage != null) {
1285
1333
  links.push({
1286
1334
  source: propShapeId,
1287
1335
  predicate: "ad4m://resolveLanguage",
@@ -1338,6 +1386,48 @@ class SHACLShape {
1338
1386
  target: `literal:string:${JSON.stringify(prop.in)}`
1339
1387
  });
1340
1388
  }
1389
+ if (prop.relationKind) {
1390
+ links.push({
1391
+ source: propShapeId,
1392
+ predicate: "ad4m://relationKind",
1393
+ target: `literal:string:${prop.relationKind}`
1394
+ });
1395
+ }
1396
+ if (prop.targetClassName) {
1397
+ links.push({
1398
+ source: propShapeId,
1399
+ predicate: "ad4m://targetClassName",
1400
+ target: `literal:string:${prop.targetClassName}`
1401
+ });
1402
+ }
1403
+ if (prop.whereFilter !== undefined && prop.whereFilter !== null) {
1404
+ links.push({
1405
+ source: propShapeId,
1406
+ predicate: "ad4m://whereFilter",
1407
+ target: `literal:string:${JSON.stringify(prop.whereFilter)}`
1408
+ });
1409
+ }
1410
+ if (prop.wherePredicates && Object.keys(prop.wherePredicates).length > 0) {
1411
+ links.push({
1412
+ source: propShapeId,
1413
+ predicate: "ad4m://wherePredicates",
1414
+ target: `literal:string:${JSON.stringify(prop.wherePredicates)}`
1415
+ });
1416
+ }
1417
+ if (prop.filter !== undefined) {
1418
+ links.push({
1419
+ source: propShapeId,
1420
+ predicate: "ad4m://filter",
1421
+ target: `literal:${prop.filter}`
1422
+ });
1423
+ }
1424
+ if (prop.transform && typeof prop.transform === 'object') {
1425
+ links.push({
1426
+ source: propShapeId,
1427
+ predicate: "ad4m://transform",
1428
+ target: `literal:string:${JSON.stringify(prop.transform)}`
1429
+ });
1430
+ }
1341
1431
  }
1342
1432
  return links;
1343
1433
  }
@@ -1519,6 +1609,60 @@ class SHACLShape {
1519
1609
  // Ignore parse errors
1520
1610
  }
1521
1611
  }
1612
+ const relationKindLink = links.find(l => l.source === propShapeId && l.predicate === "ad4m://relationKind");
1613
+ if (relationKindLink) {
1614
+ const val = relationKindLink.target.replace(/^literal:\/\/string:|^literal:string:/, '');
1615
+ if (val === 'hasMany' || val === 'hasOne' || val === 'belongsToOne' || val === 'belongsToMany') {
1616
+ prop.relationKind = val;
1617
+ }
1618
+ }
1619
+ const targetClassNameLink = links.find(l => l.source === propShapeId && l.predicate === "ad4m://targetClassName");
1620
+ if (targetClassNameLink) {
1621
+ prop.targetClassName = targetClassNameLink.target.replace(/^literal:\/\/string:|^literal:string:/, '');
1622
+ }
1623
+ const whereFilterLink = links.find(l => l.source === propShapeId && l.predicate === "ad4m://whereFilter");
1624
+ if (whereFilterLink) {
1625
+ try {
1626
+ const jsonStr = whereFilterLink.target.replace(/^literal:\/\/string:|^literal:string:/, '');
1627
+ prop.whereFilter = JSON.parse(jsonStr);
1628
+ }
1629
+ catch (e) {
1630
+ // Ignore parse errors
1631
+ }
1632
+ }
1633
+ const wherePredicatesLink = links.find(l => l.source === propShapeId && l.predicate === "ad4m://wherePredicates");
1634
+ if (wherePredicatesLink) {
1635
+ try {
1636
+ const jsonStr = wherePredicatesLink.target.replace(/^literal:\/\/string:|^literal:string:/, '');
1637
+ prop.wherePredicates = JSON.parse(jsonStr);
1638
+ }
1639
+ catch (e) {
1640
+ // Ignore parse errors
1641
+ }
1642
+ }
1643
+ const filterLink = links.find(l => l.source === propShapeId && l.predicate === "ad4m://filter");
1644
+ if (filterLink) {
1645
+ let val = filterLink.target.replace(/^literal:\/\/|^literal:/, '');
1646
+ if (val.startsWith('boolean:'))
1647
+ val = val.substring(8);
1648
+ prop.filter = val === 'true';
1649
+ }
1650
+ const transformLink = links.find(l => l.source === propShapeId && l.predicate === "ad4m://transform");
1651
+ if (transformLink) {
1652
+ const jsonStr = transformLink.target.replace(/^literal:\/\/string:|^literal:string:/, '');
1653
+ try {
1654
+ const parsed = JSON.parse(jsonStr);
1655
+ if (!isNodeExpression(parsed)) {
1656
+ throw new Error(`Invalid transform for property ${propShapeId}: ` +
1657
+ `payload is not a valid NodeExpression. Received: ${jsonStr}`);
1658
+ }
1659
+ prop.transform = parsed;
1660
+ }
1661
+ catch (e) {
1662
+ throw new Error(`Failed to deserialize transform for property ${propShapeId}: ` +
1663
+ `${e instanceof Error ? e.message : String(e)}. Payload: ${jsonStr}`);
1664
+ }
1665
+ }
1522
1666
  shape.addProperty(prop);
1523
1667
  }
1524
1668
  return shape;
@@ -1555,6 +1699,12 @@ class SHACLShape {
1555
1699
  conformance_conditions: p.conformanceConditions,
1556
1700
  class: p.class,
1557
1701
  in: p.in,
1702
+ relation_kind: p.relationKind,
1703
+ target_class_name: p.targetClassName,
1704
+ where_filter: p.whereFilter,
1705
+ where_predicates: p.wherePredicates,
1706
+ filter: p.filter,
1707
+ transform: p.transform,
1558
1708
  })),
1559
1709
  constructor_actions: this.constructor_actions,
1560
1710
  destructor_actions: this.destructor_actions,
@@ -1568,6 +1718,11 @@ class SHACLShape {
1568
1718
  ? new SHACLShape(json.node_shape_uri, json.target_class)
1569
1719
  : new SHACLShape(json.target_class);
1570
1720
  for (const p of json.properties || []) {
1721
+ // Validate transform if present
1722
+ if (p.transform && !isNodeExpression(p.transform)) {
1723
+ throw new Error(`Invalid transform for property ${p.name}: ` +
1724
+ `payload is not a valid NodeExpression. Received: ${JSON.stringify(p.transform)}`);
1725
+ }
1571
1726
  shape.addProperty({
1572
1727
  path: p.path,
1573
1728
  name: p.name,
@@ -1589,6 +1744,12 @@ class SHACLShape {
1589
1744
  conformanceConditions: p.conformance_conditions,
1590
1745
  class: p.class,
1591
1746
  in: p.in,
1747
+ relationKind: p.relation_kind,
1748
+ targetClassName: p.target_class_name,
1749
+ whereFilter: p.where_filter,
1750
+ wherePredicates: p.where_predicates,
1751
+ filter: p.filter,
1752
+ transform: p.transform,
1592
1753
  });
1593
1754
  }
1594
1755
  if (json.constructor_actions) {
@@ -1606,303 +1767,61 @@ class SHACLShape {
1606
1767
  }
1607
1768
  }
1608
1769
 
1609
- function formatList(list) {
1610
- if (!list?.length) {
1611
- return "";
1612
- }
1613
- if (list.length === 1) {
1614
- return list.toString();
1615
- }
1616
- if (list.length === 2) {
1617
- return list.join(' and ');
1618
- }
1619
- return list.slice(0, -1).join(', ') + ', and ' + list.slice(-1);
1620
- }
1621
- function capSentence(cap) {
1622
- const can = cap.can.includes("*") ? ["READ", "WRITE", "UPDATE"] : cap.can;
1623
- const domain = cap.with.domain === "*" ? "" : cap.with.domain;
1624
- const pointers = cap.with.pointers.includes("*")
1625
- ? ["all AD4M data"]
1626
- : cap.with.pointers;
1627
- return `${formatList(can)} your ${domain} actions, with access to ${formatList(pointers)}`;
1628
- }
1629
- /**
1630
- * Escapes a string value for safe use in query strings.
1631
- *
1632
- * @description
1633
- * Prevents SQL injection by properly escaping special characters in string values
1634
- * that will be interpolated into query strings. This handles the most common
1635
- * special characters that could break SQL queries or enable injection attacks.
1636
- *
1637
- * Single quotes, backslashes, and other special characters are escaped using
1638
- * backslash notation, which is the standard escaping mechanism for query.
1639
- *
1640
- * @param value - The string value to escape
1641
- * @returns The escaped string safe for query interpolation (without surrounding quotes)
1642
- *
1643
- * @example
1644
- * ```typescript
1645
- * const userInput = "user's input with 'quotes'";
1646
- * const escaped = escapeQueryString(userInput);
1647
- * const query = `SELECT * FROM link WHERE uri = '${escaped}'`;
1648
- * // Results in: SELECT * FROM link WHERE uri = 'user\'s input with \'quotes\''
1649
- * ```
1650
- */
1651
- function escapeQueryString(value) {
1652
- return value
1653
- .replace(/\\/g, '\\\\') // Backslash -> \\
1654
- .replace(/'/g, "\\'") // Single quote -> \'
1655
- .replace(/"/g, '\\"') // Double quote -> \"
1656
- .replace(/\n/g, '\\n') // Newline -> \n
1657
- .replace(/\r/g, '\\r') // Carriage return -> \r
1658
- .replace(/\t/g, '\\t'); // Tab -> \t
1659
- }
1660
-
1661
- /**
1662
- * Shared query compilation utilities.
1663
- *
1664
- * These functions are used by both the runtime query builder (`Ad4mModel`) and
1665
- * the compile-time SHACL generator (`decorators.ts`).
1666
- *
1667
- * All output uses native SPARQL syntax.
1668
- */
1669
1770
  /**
1670
- * Format a JavaScript value for embedding in a query expression.
1771
+ * SHACL shape generation for AD4M model classes.
1671
1772
  *
1672
- * - Strings are single-quoted with backslash / quote / newline escaping
1673
- * - Numbers and booleans are passed through as-is
1674
- * - Arrays are recursed
1773
+ * Builds a W3C SHACL `SHACLShape` (with AD4M-specific action extensions)
1774
+ * from a model's property and relation metadata. The heavy lifting used
1775
+ * to live inside the `@Model` decorator closure — it is extracted here so
1776
+ * decorators.ts stays focused on decorator registration logic.
1675
1777
  */
1676
- function formatQueryValue(value) {
1677
- if (typeof value === 'string') {
1678
- // Escape backslashes first, then single quotes and other special characters
1679
- const escaped = value
1680
- .replace(/\\/g, '\\\\') // Backslash -> \\
1681
- .replace(/'/g, "\\'") // Single quote -> \'
1682
- .replace(/"/g, '\\"') // Double quote -> \"
1683
- .replace(/\n/g, '\\n') // Newline -> \n
1684
- .replace(/\r/g, '\\r') // Carriage return -> \r
1685
- .replace(/\t/g, '\\t'); // Tab -> \t
1686
- return `'${escaped}'`;
1687
- }
1688
- else if (typeof value === 'number' || typeof value === 'boolean') {
1689
- return String(value);
1690
- }
1691
- else if (Array.isArray(value)) {
1692
- return `[${value.map(v => formatQueryValue(v)).join(', ')}]`;
1693
- }
1694
- else {
1695
- return String(value);
1696
- }
1697
- }
1698
1778
  /**
1699
- * Compile a single Where condition for a property into a SPARQL triple pattern
1700
- * that can be embedded in a getter's WHERE clause.
1701
- *
1702
- * The generated pattern operates on `?target` — e.g.:
1703
- * `?target <pred> <value> .`
1704
- * `FILTER EXISTS { ?target <pred> ?_v0 }`
1779
+ * Build a SHACL shape for a model class.
1705
1780
  *
1706
- * @param predicate - The predicate URI for the property
1707
- * @param condition - The Where condition value
1708
- * @param opts - Optional settings (e.g. `resolveLanguage`)
1709
- * @returns A single SPARQL condition string
1781
+ * @param subjectName - The model's registered name (from `@Model({ name })`)
1782
+ * @param target - The class constructor (used for prototype access,
1783
+ * inheritance chain, and relation target resolution)
1784
+ * @param properties - Merged property metadata (from `getPropertiesMetadata`)
1785
+ * @param allRelationsMeta - Merged relation metadata (from `getRelationsMetadata`)
1786
+ * @param conformanceFilterFn - Injected conformance-filter builder
1787
+ * (avoids circular dependency back into decorators.ts)
1710
1788
  */
1711
- function buildWhereCondition(predicate, condition, opts) {
1712
- const escapedPredicate = escapeQueryString(predicate);
1713
- // For literal-resolved properties, we match against the raw IRI (which is a literal: URI)
1714
- // For language-resolved properties, we match against the plain URI
1715
- // For literal-resolved properties, values are stored as IRIs like <literal:string:VALUE>
1716
- // For language-resolved properties, values are plain URIs
1717
- const isLiteral = !opts?.resolveLanguage || opts.resolveLanguage === 'literal';
1718
- const varSuffix = opts?.varIndex ?? 0;
1719
- function formatValue(v) {
1720
- if (typeof v === 'string') {
1721
- return isLiteral
1722
- ? `<literal:string:${escapeQueryString(v)}>`
1723
- : `<${escapeQueryString(v)}>`;
1789
+ function buildSHACL(subjectName, target, properties, allRelationsMeta, conformanceFilterFn) {
1790
+ const obj = target.prototype;
1791
+ // ── Determine namespace from first property or relation ─────────────
1792
+ let namespace = "ad4m://";
1793
+ // Try properties first
1794
+ if (Object.keys(properties).length > 0) {
1795
+ const firstProp = properties[Object.keys(properties)[0]];
1796
+ if (firstProp.through) {
1797
+ const match = firstProp.through.match(/^([^:]+:\/\/)/);
1798
+ if (match) {
1799
+ namespace = match[1];
1800
+ }
1724
1801
  }
1725
- // Numbers/booleans — also stored as literal:string: in AD4M
1726
- return `<literal:string:${v}>`;
1727
1802
  }
1728
- /**
1729
- * For literal properties, generate a FILTER-based match that handles both
1730
- * the raw value and the literal-encoded value. This mirrors the Rust
1731
- * `build_projection_where_patterns` approach which uses:
1732
- * FILTER(STR(?var) = "value" || STR(?var) = "literal:string:encodedValue")
1733
- * This is more robust than exact IRI matching because it handles edge cases
1734
- * where the stored format might vary.
1735
- */
1736
- function formatLiteralFilter(varName, v) {
1737
- const raw = escapeQueryString(String(v));
1738
- const encoded = encodeURIComponent(String(v))
1739
- .replace(/!/g, '%21')
1740
- .replace(/'/g, '%27')
1741
- .replace(/\(/g, '%28')
1742
- .replace(/\)/g, '%29')
1743
- .replace(/\*/g, '%2A');
1744
- if (typeof v === 'string') {
1745
- return `FILTER(STR(${varName}) = "${raw}" || STR(${varName}) = "literal:string:${encoded}")`;
1746
- }
1747
- else if (typeof v === 'number') {
1748
- return `FILTER(STR(${varName}) = "${v}" || STR(${varName}) = "literal:number:${v}")`;
1749
- }
1750
- else if (typeof v === 'boolean') {
1751
- return `FILTER(STR(${varName}) = "${v}" || STR(${varName}) = "literal:boolean:${v}")`;
1803
+ // Fall back to relations if no properties
1804
+ else if (Object.keys(allRelationsMeta).length > 0) {
1805
+ const firstRel = allRelationsMeta[Object.keys(allRelationsMeta)[0]];
1806
+ if (firstRel.predicate) {
1807
+ const match = firstRel.predicate.match(/^([^:]+:\/\/)/);
1808
+ if (match) {
1809
+ namespace = match[1];
1810
+ }
1752
1811
  }
1753
- return `FILTER(STR(${varName}) = "${raw}")`;
1754
1812
  }
1755
- if (Array.isArray(condition)) {
1756
- // Array values → FILTER IN
1757
- if (isLiteral) {
1758
- const varName = `?_wc${varSuffix}`;
1759
- const inValues = condition.flatMap(v => {
1760
- const raw = escapeQueryString(String(v));
1761
- const encoded = encodeURIComponent(String(v))
1762
- .replace(/!/g, '%21').replace(/'/g, '%27')
1763
- .replace(/\(/g, '%28').replace(/\)/g, '%29').replace(/\*/g, '%2A');
1764
- return [`"${raw}"`, `"literal:string:${encoded}"`];
1765
- }).join(', ');
1766
- return `?target <${escapedPredicate}> ${varName} . FILTER(STR(${varName}) IN (${inValues}))`;
1767
- }
1768
- const formattedValues = condition.map(formatValue).join(', ');
1769
- return `FILTER EXISTS { ?target <${escapedPredicate}> ?_val . FILTER(?_val IN (${formattedValues})) }`;
1770
- }
1771
- else if (typeof condition === 'object' && condition !== null) {
1772
- // Operator object
1773
- const ops = condition;
1774
- const parts = [];
1775
- if (ops.not !== undefined) {
1776
- if (Array.isArray(ops.not)) {
1777
- const formattedValues = ops.not.map((v) => formatValue(v)).join(', ');
1778
- // FILTER NOT EXISTS here is scoped to a specific predicate, not a global scan,
1779
- // so O(N²) behavior is bounded by the number of values for this property.
1780
- parts.push(`FILTER NOT EXISTS { ?target <${escapedPredicate}> ?_nval . FILTER(?_nval IN (${formattedValues})) }`);
1781
- }
1782
- else {
1783
- // FILTER NOT EXISTS here is scoped to a specific predicate, not a global scan,
1784
- // so O(N²) behavior is bounded by the number of values for this property.
1785
- parts.push(`FILTER NOT EXISTS { ?target <${escapedPredicate}> ${formatValue(ops.not)} }`);
1786
- }
1787
- }
1788
- // Comparison operators — ensure property exists
1789
- const hasComparisonOps = ops.gt !== undefined || ops.gte !== undefined ||
1790
- ops.lt !== undefined || ops.lte !== undefined ||
1791
- ops.between !== undefined || ops.contains !== undefined;
1792
- if (hasComparisonOps) {
1793
- parts.push(`FILTER EXISTS { ?target <${escapedPredicate}> ?_cmp }`);
1794
- }
1795
- return parts.join(' ');
1796
- }
1797
- else {
1798
- // Simple equality
1799
- if (isLiteral) {
1800
- // Use FILTER matching (mirrors Rust build_projection_where_patterns)
1801
- // to handle both raw values and literal-encoded IRIs robustly.
1802
- const varName = `?_wc${varSuffix}`;
1803
- return `?target <${escapedPredicate}> ${varName} . ${formatLiteralFilter(varName, condition)}`;
1804
- }
1805
- return `?target <${escapedPredicate}> ${formatValue(condition)} .`;
1806
- }
1807
- }
1808
- /**
1809
- * Compile a full `Where` clause to an array of SPARQL condition strings.
1810
- *
1811
- * When `metadata` is provided, property names are resolved to predicates
1812
- * using the model's property metadata. When `metadata` is `null`, property
1813
- * names are treated as raw predicate URIs.
1814
- *
1815
- * Only handles **regular properties** — special fields (`id`, `author`,
1816
- * `timestamp`) and relation fields are skipped (they are only relevant at
1817
- * runtime query time, not for compile-time getter generation).
1818
- */
1819
- function compileWhereClause(where, metadata) {
1820
- const conditions = [];
1821
- for (const [propertyName, condition] of Object.entries(where)) {
1822
- // Skip special fields that don't apply at compile time
1823
- if (['id', 'author', 'timestamp'].includes(propertyName))
1824
- continue;
1825
- let predicate;
1826
- let resolveLanguage;
1827
- if (metadata) {
1828
- const propMeta = metadata.properties[propertyName];
1829
- if (propMeta) {
1830
- predicate = propMeta.predicate;
1831
- resolveLanguage = propMeta.resolveLanguage;
1832
- }
1833
- else {
1834
- // Property not found in metadata — treat name as raw predicate URI
1835
- predicate = propertyName;
1836
- }
1837
- }
1838
- else {
1839
- // No metadata — treat name as raw predicate URI
1840
- predicate = propertyName;
1841
- }
1842
- const cond = buildWhereCondition(predicate, condition, { resolveLanguage, varIndex: conditions.length });
1843
- if (cond) {
1844
- conditions.push(cond);
1845
- }
1846
- }
1847
- return conditions;
1848
- }
1849
-
1850
- /**
1851
- * SHACL shape generation for AD4M model classes.
1852
- *
1853
- * Builds a W3C SHACL `SHACLShape` (with AD4M-specific action extensions)
1854
- * from a model's property and relation metadata. The heavy lifting used
1855
- * to live inside the `@Model` decorator closure — it is extracted here so
1856
- * decorators.ts stays focused on decorator registration logic.
1857
- */
1858
- /**
1859
- * Build a SHACL shape for a model class.
1860
- *
1861
- * @param subjectName - The model's registered name (from `@Model({ name })`)
1862
- * @param target - The class constructor (used for prototype access,
1863
- * inheritance chain, and relation target resolution)
1864
- * @param properties - Merged property metadata (from `getPropertiesMetadata`)
1865
- * @param allRelationsMeta - Merged relation metadata (from `getRelationsMetadata`)
1866
- * @param conformanceFilterFn - Injected conformance-filter builder
1867
- * (avoids circular dependency back into decorators.ts)
1868
- */
1869
- function buildSHACL(subjectName, target, properties, allRelationsMeta, conformanceFilterFn) {
1870
- const obj = target.prototype;
1871
- // ── Determine namespace from first property or relation ─────────────
1872
- let namespace = "ad4m://";
1873
- const relations = Object.fromEntries(Object.entries(allRelationsMeta).filter(([, r]) => r.kind === 'hasMany' || r.kind === 'belongsToMany'));
1874
- // Try properties first
1875
- if (Object.keys(properties).length > 0) {
1876
- const firstProp = properties[Object.keys(properties)[0]];
1877
- if (firstProp.through) {
1878
- const match = firstProp.through.match(/^([^:]+:\/\/)/);
1879
- if (match) {
1880
- namespace = match[1];
1881
- }
1882
- }
1883
- }
1884
- // Fall back to relations if no properties
1885
- else if (Object.keys(relations).length > 0) {
1886
- const firstRel = relations[Object.keys(relations)[0]];
1887
- if (firstRel.predicate) {
1888
- const match = firstRel.predicate.match(/^([^:]+:\/\/)/);
1889
- if (match) {
1890
- namespace = match[1];
1891
- }
1892
- }
1893
- }
1894
- // ── Create SHACL shape ──────────────────────────────────────────────
1895
- const shapeUri = `${namespace}${subjectName}Shape`;
1896
- const targetClass = `${namespace}${subjectName}`;
1897
- const shape = new SHACLShape(shapeUri, targetClass);
1898
- // Detect @Model inheritance — if the parent class also has
1899
- // generateSHACL it is itself a @Model and we reference its shape
1900
- // via sh:node so SHACL validators can walk the hierarchy.
1901
- const parentCtor = Object.getPrototypeOf(target);
1902
- if (parentCtor && typeof parentCtor.generateSHACL === 'function') {
1903
- const parentSHACL = parentCtor.generateSHACL();
1904
- if (parentSHACL?.shape?.nodeShapeUri) {
1905
- shape.addParentShape(parentSHACL.shape.nodeShapeUri);
1813
+ // ── Create SHACL shape ──────────────────────────────────────────────
1814
+ const shapeUri = `${namespace}${subjectName}Shape`;
1815
+ const targetClass = `${namespace}${subjectName}`;
1816
+ const shape = new SHACLShape(shapeUri, targetClass);
1817
+ // Detect @Model inheritance — if the parent class also has
1818
+ // generateSHACL it is itself a @Model and we reference its shape
1819
+ // via sh:node so SHACL validators can walk the hierarchy.
1820
+ const parentCtor = Object.getPrototypeOf(target);
1821
+ if (parentCtor && typeof parentCtor.generateSHACL === 'function') {
1822
+ const parentSHACL = parentCtor.generateSHACL();
1823
+ if (parentSHACL?.shape?.nodeShapeUri) {
1824
+ shape.addParentShape(parentSHACL.shape.nodeShapeUri);
1906
1825
  }
1907
1826
  }
1908
1827
  // ── Constructor / Destructor actions ────────────────────────────────
@@ -1957,9 +1876,19 @@ function buildSHACL(subjectName, target, properties, allRelationsMeta, conforman
1957
1876
  if (propMeta.writable !== undefined) {
1958
1877
  propShape.writable = propMeta.writable;
1959
1878
  }
1960
- if (propMeta.resolveLanguage) {
1879
+ if (propMeta.resolveLanguage != null) {
1961
1880
  propShape.resolveLanguage = propMeta.resolveLanguage;
1962
1881
  }
1882
+ // Explicit getter SPARQL — the executor evaluates this when
1883
+ // hydrating the property, in addition to (or instead of)
1884
+ // reading raw links via `propMeta.through`.
1885
+ if (propMeta.getter) {
1886
+ propShape.getter = propMeta.getter;
1887
+ }
1888
+ // Serializable transform expression (SHACL-AF Node Expression)
1889
+ if (propMeta.transform) {
1890
+ propShape.transform = propMeta.transform;
1891
+ }
1963
1892
  // ── Setter actions ──────────────────────────────────────────────
1964
1893
  if (propMeta.prologSetter) {
1965
1894
  console.warn(`[SHACL Generation] Custom Prolog setter for property '${propName}' in class '${subjectName}' is not yet supported. ` +
@@ -1998,63 +1927,82 @@ function buildSHACL(subjectName, target, properties, allRelationsMeta, conforman
1998
1927
  shape.addProperty(propShape);
1999
1928
  }
2000
1929
  // ── Convert relations to SHACL property shapes ─────────────────────
2001
- for (const relName in relations) {
2002
- const relMeta = relations[relName];
2003
- if (!relMeta.predicate)
1930
+ for (const relName in allRelationsMeta) {
1931
+ const relMeta = allRelationsMeta[relName];
1932
+ // Getter-only relations (no `through`) have no real link predicate
1933
+ // but still need a SHACL property entry so the executor can find
1934
+ // the getter expression. Synthesize a deterministic IRI so the
1935
+ // SHACL graph is well-formed; the predicate is never used to match
1936
+ // links because the getter is the sole source of values. Use
1937
+ // slash separators so the result is a valid IRI (colons in the
1938
+ // authority confuse strict SPARQL IRI parsers).
1939
+ if (!relMeta.predicate && !relMeta.getter)
2004
1940
  continue;
1941
+ const synthesizedPath = relMeta.predicate
1942
+ || `ad4m://getter/${subjectName}/${relName}`;
2005
1943
  const relShape = {
2006
1944
  name: relName,
2007
- path: relMeta.predicate,
1945
+ path: synthesizedPath,
2008
1946
  };
2009
1947
  // Relations typically contain IRIs
2010
1948
  relShape.nodeKind = 'IRI';
1949
+ // Encode relation kind so the executor can derive direction and
1950
+ // scalar-vs-collection rendering without consulting the JS class.
1951
+ relShape.relationKind = relMeta.kind;
1952
+ // Scalar relations cap at 1.
1953
+ if (relMeta.kind === 'hasOne' || relMeta.kind === 'belongsToOne') {
1954
+ relShape.maxCount = 1;
1955
+ }
1956
+ else if (relMeta.maxCount !== undefined) {
1957
+ relShape.maxCount = relMeta.maxCount;
1958
+ }
1959
+ // Encode opt-out of type filtering (default true; only emit when false).
1960
+ if (relMeta.filter === false) {
1961
+ relShape.filter = false;
1962
+ }
2011
1963
  // AD4M-specific metadata
2012
1964
  if (relMeta.local !== undefined) {
2013
1965
  relShape.local = relMeta.local;
2014
1966
  }
2015
- // Adder action
2016
- relShape.adder = [{
2017
- action: "addLink",
2018
- source: "this",
2019
- predicate: relMeta.predicate,
2020
- target: "value",
2021
- ...(relMeta.local && { local: true })
2022
- }];
2023
- // Remover action
2024
- relShape.remover = [{
2025
- action: "removeLink",
2026
- source: "this",
2027
- predicate: relMeta.predicate,
2028
- target: "value",
2029
- ...(relMeta.local && { local: true })
2030
- }];
1967
+ // Adder / Remover actions — only meaningful for relations backed
1968
+ // by a real link predicate. Getter-only relations are read-only.
1969
+ if (relMeta.predicate) {
1970
+ relShape.adder = [{
1971
+ action: "addLink",
1972
+ source: "this",
1973
+ predicate: relMeta.predicate,
1974
+ target: "value",
1975
+ ...(relMeta.local && { local: true })
1976
+ }];
1977
+ relShape.remover = [{
1978
+ action: "removeLink",
1979
+ source: "this",
1980
+ predicate: relMeta.predicate,
1981
+ target: "value",
1982
+ ...(relMeta.local && { local: true })
1983
+ }];
1984
+ }
2031
1985
  // ── Build Getter (conformance filter) ───────────────────────────
2032
1986
  // Priority chain:
2033
1987
  // 1. Explicit getter string → use verbatim
2034
- // 2. `where` clause → compile DSL to SPARQL getter
2035
- // 3. target + filter !== false → auto-derive from shape
1988
+ // 2. target + filter !== false → auto-derive conformance getter
1989
+ // from the shape. Where-clause filtering is applied as a
1990
+ // post-getter pass via `whereFilter` / `wherePredicates`, which
1991
+ // use `parse_literal_value` and so transparently handle
1992
+ // `literal:json:` envelopes that simple FILTER(STR(?x) = ...)
1993
+ // comparisons can't.
2036
1994
  if (relMeta.getter) {
2037
1995
  relShape.getter = relMeta.getter;
2038
1996
  }
2039
- else if (relMeta.where) {
2040
- try {
2041
- const TargetClass = relMeta.target?.();
2042
- const targetMetadata = TargetClass
2043
- ? TargetClass.getModelMetadata?.() ?? null
2044
- : null;
2045
- const conditions = compileWhereClause(relMeta.where, targetMetadata);
2046
- if (conditions.length > 0) {
2047
- const escapedPredicate = escapeQueryString(relMeta.predicate);
2048
- relShape.getter = `SELECT ?target WHERE { <Base> <${escapedPredicate}> ?target . ${conditions.join(' ')} }`;
2049
- }
2050
- }
2051
- catch (e) {
2052
- // Target metadata may not be available yet
2053
- }
2054
- }
2055
- else if (relMeta.target && relMeta.filter !== false) {
1997
+ else if (relMeta.target
1998
+ && relMeta.filter !== false
1999
+ && relMeta.kind !== 'belongsToOne'
2000
+ && relMeta.kind !== 'belongsToMany') {
2056
2001
  // Lazy conformance filter: store deferred reference,
2057
- // resolve on first access via a getter on relShape
2002
+ // resolve on first access via a getter on relShape.
2003
+ // Skipped for reverse relations (belongsTo*) because the
2004
+ // auto-derived getter assumes forward direction; the executor's
2005
+ // `resolve_reverse_relations` already populates these correctly.
2058
2006
  const targetThunk = relMeta.target;
2059
2007
  const predicate = relMeta.predicate;
2060
2008
  let resolved = false;
@@ -2091,6 +2039,8 @@ function buildSHACL(subjectName, target, properties, allRelationsMeta, conforman
2091
2039
  });
2092
2040
  }
2093
2041
  // ── sh:class — target shape reference ───────────────────────────
2042
+ // Also emit ad4m:targetClassName so the executor can look up the
2043
+ // target class shape through its in-memory cache by bare name.
2094
2044
  if (relMeta.target) {
2095
2045
  try {
2096
2046
  const TargetClass = relMeta.target();
@@ -2098,9 +2048,54 @@ function buildSHACL(subjectName, target, properties, allRelationsMeta, conforman
2098
2048
  if (targetSHACL?.shape?.nodeShapeUri) {
2099
2049
  relShape.class = targetSHACL.shape.nodeShapeUri;
2100
2050
  }
2051
+ if (targetSHACL?.name) {
2052
+ relShape.targetClassName = targetSHACL.name;
2053
+ }
2054
+ else {
2055
+ const targetProto = TargetClass.prototype;
2056
+ if (targetProto?.className) {
2057
+ relShape.targetClassName = targetProto.className;
2058
+ }
2059
+ }
2060
+ }
2061
+ catch (e) {
2062
+ // Target class resolution failed (typically a circular
2063
+ // decorator dependency). Since the executor no longer
2064
+ // receives target metadata over the wire, dropping the
2065
+ // reference here would turn a transient build-time issue
2066
+ // into a permanent broken-include at query time. Log
2067
+ // loudly so the failure is discoverable.
2068
+ console.warn(`[shacl-gen] Failed to resolve target class for relation `
2069
+ + `"${subjectName}.${relName}": ${e instanceof Error ? e.message : String(e)}`);
2070
+ }
2071
+ }
2072
+ // ── Where-clause metadata for post-getter filtering ─────────────
2073
+ // The executor uses these to apply where conditions against the
2074
+ // target class without needing the target's ModelMetadata at query time.
2075
+ if (relMeta.where) {
2076
+ relShape.whereFilter = relMeta.where;
2077
+ try {
2078
+ const TargetClass = relMeta.target?.();
2079
+ const targetMetadata = TargetClass
2080
+ ? TargetClass.getModelMetadata?.() ?? null
2081
+ : null;
2082
+ if (targetMetadata?.properties) {
2083
+ const predicates = {};
2084
+ for (const propName of Object.keys(relMeta.where)) {
2085
+ if (['id', 'author', 'timestamp'].includes(propName))
2086
+ continue;
2087
+ const propMeta = targetMetadata.properties[propName];
2088
+ if (propMeta?.predicate) {
2089
+ predicates[propName] = propMeta.predicate;
2090
+ }
2091
+ }
2092
+ if (Object.keys(predicates).length > 0) {
2093
+ relShape.wherePredicates = predicates;
2094
+ }
2095
+ }
2101
2096
  }
2102
2097
  catch (e) {
2103
- // Target class may not be available yet
2098
+ // Target metadata may not be available yet
2104
2099
  }
2105
2100
  }
2106
2101
  shape.addProperty(relShape);
@@ -2118,6 +2113,58 @@ function buildSHACL(subjectName, target, properties, allRelationsMeta, conforman
2118
2113
  };
2119
2114
  }
2120
2115
 
2116
+ function formatList(list) {
2117
+ if (!list?.length) {
2118
+ return "";
2119
+ }
2120
+ if (list.length === 1) {
2121
+ return list.toString();
2122
+ }
2123
+ if (list.length === 2) {
2124
+ return list.join(' and ');
2125
+ }
2126
+ return list.slice(0, -1).join(', ') + ', and ' + list.slice(-1);
2127
+ }
2128
+ function capSentence(cap) {
2129
+ const can = cap.can.includes("*") ? ["READ", "WRITE", "UPDATE"] : cap.can;
2130
+ const domain = cap.with.domain === "*" ? "" : cap.with.domain;
2131
+ const pointers = cap.with.pointers.includes("*")
2132
+ ? ["all AD4M data"]
2133
+ : cap.with.pointers;
2134
+ return `${formatList(can)} your ${domain} actions, with access to ${formatList(pointers)}`;
2135
+ }
2136
+ /**
2137
+ * Escapes a string value for safe use in query strings.
2138
+ *
2139
+ * @description
2140
+ * Prevents SQL injection by properly escaping special characters in string values
2141
+ * that will be interpolated into query strings. This handles the most common
2142
+ * special characters that could break SQL queries or enable injection attacks.
2143
+ *
2144
+ * Single quotes, backslashes, and other special characters are escaped using
2145
+ * backslash notation, which is the standard escaping mechanism for query.
2146
+ *
2147
+ * @param value - The string value to escape
2148
+ * @returns The escaped string safe for query interpolation (without surrounding quotes)
2149
+ *
2150
+ * @example
2151
+ * ```typescript
2152
+ * const userInput = "user's input with 'quotes'";
2153
+ * const escaped = escapeQueryString(userInput);
2154
+ * const query = `SELECT * FROM link WHERE uri = '${escaped}'`;
2155
+ * // Results in: SELECT * FROM link WHERE uri = 'user\'s input with \'quotes\''
2156
+ * ```
2157
+ */
2158
+ function escapeQueryString(value) {
2159
+ return value
2160
+ .replace(/\\/g, '\\\\') // Backslash -> \\
2161
+ .replace(/'/g, "\\'") // Single quote -> \'
2162
+ .replace(/"/g, '\\"') // Double quote -> \"
2163
+ .replace(/\n/g, '\\n') // Newline -> \n
2164
+ .replace(/\r/g, '\\r') // Carriage return -> \r
2165
+ .replace(/\t/g, '\\t'); // Tab -> \t
2166
+ }
2167
+
2121
2168
  /** Registry of property metadata keyed by constructor → { propName → metadata } */
2122
2169
  const propertyRegistry = new WeakMap();
2123
2170
  /** Registry of relation metadata keyed by constructor → { propName → metadata } */
@@ -2637,15 +2684,8 @@ function resolveRelationArgs(first, second) {
2637
2684
  return opts;
2638
2685
  }
2639
2686
  function HasMany(first, second) {
2640
- const explicitThrough = typeof first === 'function' ? second?.through : first.through;
2641
2687
  const opts = resolveRelationArgs(first, second);
2642
2688
  return function (target, key) {
2643
- if (!explicitThrough && !opts.getter) {
2644
- const className = (target.constructor?.name) ?? 'unknown';
2645
- console.warn(`@HasMany on ${className}.${String(key)} has no 'through' predicate — defaulting to 'ad4m://has_child'. ` +
2646
- `Add { through: 'ad4m://has_child' } to silence this warning, or use a semantic predicate ` +
2647
- `like { through: 'myns://has_${String(key)}' } for efficient targeted queries.`);
2648
- }
2649
2689
  // --- relation registry ---
2650
2690
  const ctor = target.constructor;
2651
2691
  if (!relationRegistry.has(ctor))
@@ -3741,13 +3781,16 @@ class PerspectiveProxy {
3741
3781
  /**
3742
3782
  * Execute a model query — the executor-side replacement for SPARQL query building + JS hydration.
3743
3783
  *
3784
+ * The executor resolves the model's shape from the perspective's SHACL
3785
+ * triples (written by `addSdna`). Callers no longer ship shape
3786
+ * metadata with the query; the perspective is the source of truth.
3787
+ *
3744
3788
  * @param className - The model class name (e.g. "Recipe")
3745
3789
  * @param queryJson - Structured query as JSON string
3746
- * @param shapeJson - Optional shape metadata JSON from the model class
3747
3790
  * @returns Object with `instances` array and `totalCount`
3748
3791
  */
3749
- async modelQuery(className, queryJson, shapeJson) {
3750
- return await __classPrivateFieldGet$a(this, _PerspectiveProxy_client, "f").modelQuery(__classPrivateFieldGet$a(this, _PerspectiveProxy_handle, "f").uuid, className, queryJson, shapeJson);
3792
+ async modelQuery(className, queryJson) {
3793
+ return await __classPrivateFieldGet$a(this, _PerspectiveProxy_client, "f").modelQuery(__classPrivateFieldGet$a(this, _PerspectiveProxy_handle, "f").uuid, className, queryJson);
3751
3794
  }
3752
3795
  /**
3753
3796
  * Evaluate property getters for a batch of instances in a single RPC call.
@@ -3758,12 +3801,11 @@ class PerspectiveProxy {
3758
3801
  *
3759
3802
  * @param className - The model class name (e.g. "Message")
3760
3803
  * @param instanceIds - Array of instance base expression URIs
3761
- * @param shapeJson - Shape metadata JSON from the model class
3762
3804
  * @param propertyNames - Optional subset of property names to evaluate
3763
3805
  * @returns Map of instance ID → evaluated property values
3764
3806
  */
3765
- async evaluateGetters(className, instanceIds, shapeJson, propertyNames) {
3766
- return await __classPrivateFieldGet$a(this, _PerspectiveProxy_client, "f").evaluateGetters(__classPrivateFieldGet$a(this, _PerspectiveProxy_handle, "f").uuid, className, instanceIds, shapeJson, propertyNames);
3807
+ async evaluateGetters(className, instanceIds, propertyNames) {
3808
+ return await __classPrivateFieldGet$a(this, _PerspectiveProxy_client, "f").evaluateGetters(__classPrivateFieldGet$a(this, _PerspectiveProxy_handle, "f").uuid, className, instanceIds, propertyNames);
3767
3809
  }
3768
3810
  /**
3769
3811
  * Subscribe to model query changes. Builds trigger SPARQL from the model shape
@@ -3775,11 +3817,10 @@ class PerspectiveProxy {
3775
3817
  *
3776
3818
  * @param className - The model class name
3777
3819
  * @param queryJson - JSON-serialized query parameters (same as modelQuery)
3778
- * @param shapeJson - Optional shape metadata JSON from the model class
3779
3820
  * @returns Object with `subscriptionId` and initial `result`
3780
3821
  */
3781
- async modelSubscribe(className, queryJson, shapeJson) {
3782
- return await __classPrivateFieldGet$a(this, _PerspectiveProxy_client, "f").modelSubscribe(__classPrivateFieldGet$a(this, _PerspectiveProxy_handle, "f").uuid, className, queryJson, shapeJson);
3822
+ async modelSubscribe(className, queryJson) {
3823
+ return await __classPrivateFieldGet$a(this, _PerspectiveProxy_client, "f").modelSubscribe(__classPrivateFieldGet$a(this, _PerspectiveProxy_handle, "f").uuid, className, queryJson);
3783
3824
  }
3784
3825
  /**
3785
3826
  * Adds a new link to the perspective.
@@ -3967,17 +4008,30 @@ class PerspectiveProxy {
3967
4008
  async removeListener(type, cb) {
3968
4009
  if (type === 'link-added') {
3969
4010
  const index = __classPrivateFieldGet$a(this, _PerspectiveProxy_perspectiveLinkAddedCallbacks, "f").indexOf(cb);
3970
- __classPrivateFieldGet$a(this, _PerspectiveProxy_perspectiveLinkAddedCallbacks, "f").splice(index, 1);
4011
+ if (index >= 0)
4012
+ __classPrivateFieldGet$a(this, _PerspectiveProxy_perspectiveLinkAddedCallbacks, "f").splice(index, 1);
3971
4013
  }
3972
4014
  else if (type === 'link-removed') {
3973
4015
  const index = __classPrivateFieldGet$a(this, _PerspectiveProxy_perspectiveLinkRemovedCallbacks, "f").indexOf(cb);
3974
- __classPrivateFieldGet$a(this, _PerspectiveProxy_perspectiveLinkRemovedCallbacks, "f").splice(index, 1);
4016
+ if (index >= 0)
4017
+ __classPrivateFieldGet$a(this, _PerspectiveProxy_perspectiveLinkRemovedCallbacks, "f").splice(index, 1);
3975
4018
  }
3976
4019
  else if (type === 'link-updated') {
3977
4020
  const index = __classPrivateFieldGet$a(this, _PerspectiveProxy_perspectiveLinkUpdatedCallbacks, "f").indexOf(cb);
3978
- __classPrivateFieldGet$a(this, _PerspectiveProxy_perspectiveLinkUpdatedCallbacks, "f").splice(index, 1);
4021
+ if (index >= 0)
4022
+ __classPrivateFieldGet$a(this, _PerspectiveProxy_perspectiveLinkUpdatedCallbacks, "f").splice(index, 1);
3979
4023
  }
3980
4024
  }
4025
+ /** Clean up all subscriptions registered by this proxy.
4026
+ * Call this when the proxy is no longer needed to prevent subscription leaks.
4027
+ * After calling dispose(), the proxy should not be used. */
4028
+ dispose() {
4029
+ __classPrivateFieldGet$a(this, _PerspectiveProxy_client, "f").removeAllListeners(__classPrivateFieldGet$a(this, _PerspectiveProxy_handle, "f").uuid);
4030
+ __classPrivateFieldGet$a(this, _PerspectiveProxy_perspectiveLinkAddedCallbacks, "f").length = 0;
4031
+ __classPrivateFieldGet$a(this, _PerspectiveProxy_perspectiveLinkRemovedCallbacks, "f").length = 0;
4032
+ __classPrivateFieldGet$a(this, _PerspectiveProxy_perspectiveLinkUpdatedCallbacks, "f").length = 0;
4033
+ __classPrivateFieldGet$a(this, _PerspectiveProxy_perspectiveSyncStateChangeCallbacks, "f").length = 0;
4034
+ }
3981
4035
  /**
3982
4036
  * Creates a snapshot of the current perspective state.
3983
4037
  * Useful for backup or sharing.
@@ -4267,6 +4321,40 @@ class PerspectiveProxy {
4267
4321
  async addSdna(name, sdnaCode, sdnaType, shaclJson) {
4268
4322
  return __classPrivateFieldGet$a(this, _PerspectiveProxy_client, "f").addSdna(__classPrivateFieldGet$a(this, _PerspectiveProxy_handle, "f").uuid, name, sdnaCode, sdnaType, shaclJson);
4269
4323
  }
4324
+ /**
4325
+ * Batch variant of addSdna — registers multiple SDNA entries in a single RPC call.
4326
+ * Acquires the Rust-side mutex once for the entire batch.
4327
+ */
4328
+ async addSdnaAll(entries) {
4329
+ return __classPrivateFieldGet$a(this, _PerspectiveProxy_client, "f").addSdnaBatch(__classPrivateFieldGet$a(this, _PerspectiveProxy_handle, "f").uuid, entries);
4330
+ }
4331
+ /**
4332
+ * Batch-registers multiple model classes as SHACL subject classes in a single RPC call.
4333
+ * Skips classes already registered on this perspective instance.
4334
+ */
4335
+ async ensureSubjectClasses(jsClasses) {
4336
+ const entries = [];
4337
+ for (const jsClass of jsClasses) {
4338
+ const className = jsClass.className || jsClass.prototype?.className || jsClass.name;
4339
+ if (__classPrivateFieldGet$a(this, _PerspectiveProxy_ensuredSubjectClasses, "f").has(className))
4340
+ continue;
4341
+ if (!jsClass.generateSHACL) {
4342
+ throw new Error(`Class ${jsClass.name} must have generateSHACL(). Use @Model decorator.`);
4343
+ }
4344
+ const { shape } = jsClass.generateSHACL();
4345
+ entries.push({
4346
+ name: className,
4347
+ sdnaType: 'subject_class',
4348
+ shaclJson: JSON.stringify(shape.toJSON()),
4349
+ });
4350
+ }
4351
+ if (entries.length === 0)
4352
+ return;
4353
+ await this.addSdnaAll(entries);
4354
+ for (const entry of entries) {
4355
+ __classPrivateFieldGet$a(this, _PerspectiveProxy_ensuredSubjectClasses, "f").add(entry.name);
4356
+ }
4357
+ }
4270
4358
  /**
4271
4359
  * Adds a subject class to the perspective.
4272
4360
  * Alias for addSdna() with sdnaType='subject_class'.
@@ -5374,22 +5462,21 @@ class PerspectiveClient {
5374
5462
  }
5375
5463
  return __classPrivateFieldGet$9(this, _PerspectiveClient_apiClient, "f").call('perspective.disposeQuery', { uuid, subscriptionId });
5376
5464
  }
5377
- async modelQuery(uuid, className, queryJson, shapeJson) {
5378
- const resultJson = await __classPrivateFieldGet$9(this, _PerspectiveClient_apiClient, "f").call('perspective.modelQuery', { uuid, class_name: className, query_json: queryJson, shape_json: shapeJson });
5465
+ async modelQuery(uuid, className, queryJson) {
5466
+ const resultJson = await __classPrivateFieldGet$9(this, _PerspectiveClient_apiClient, "f").call('perspective.modelQuery', { uuid, class_name: className, query_json: queryJson });
5379
5467
  return JSON.parse(resultJson);
5380
5468
  }
5381
- async evaluateGetters(uuid, className, instanceIds, shapeJson, propertyNames) {
5469
+ async evaluateGetters(uuid, className, instanceIds, propertyNames) {
5382
5470
  const resultJson = await __classPrivateFieldGet$9(this, _PerspectiveClient_apiClient, "f").call('perspective.evaluateGetters', {
5383
5471
  uuid,
5384
5472
  class_name: className,
5385
5473
  instance_ids: instanceIds,
5386
- shape_json: shapeJson,
5387
5474
  ...(propertyNames && { property_names: propertyNames }),
5388
5475
  });
5389
5476
  return JSON.parse(resultJson);
5390
5477
  }
5391
- async modelSubscribe(uuid, className, queryJson, shapeJson) {
5392
- const response = await __classPrivateFieldGet$9(this, _PerspectiveClient_apiClient, "f").call('perspective.modelSubscribe', { uuid, class_name: className, query_json: queryJson, shape_json: shapeJson });
5478
+ async modelSubscribe(uuid, className, queryJson) {
5479
+ const response = await __classPrivateFieldGet$9(this, _PerspectiveClient_apiClient, "f").call('perspective.modelSubscribe', { uuid, class_name: className, query_json: queryJson });
5393
5480
  return {
5394
5481
  subscriptionId: response.subscription_id,
5395
5482
  result: JSON.parse(response.result)
@@ -5435,6 +5522,9 @@ class PerspectiveClient {
5435
5522
  async addSdna(uuid, name, sdnaCode, sdnaType, shaclJson) {
5436
5523
  return __classPrivateFieldGet$9(this, _PerspectiveClient_apiClient, "f").call('perspective.addSdna', { uuid, name, sdnaCode: sdnaCode || "", sdnaType, shaclJson });
5437
5524
  }
5525
+ async addSdnaBatch(uuid, entries) {
5526
+ return __classPrivateFieldGet$9(this, _PerspectiveClient_apiClient, "f").call('perspective.addSdna', { uuid, entries: entries.map(e => ({ ...e, sdnaCode: e.sdnaCode || "" })) });
5527
+ }
5438
5528
  async executeCommands(uuid, commands, expression, parameters, batchId) {
5439
5529
  return __classPrivateFieldGet$9(this, _PerspectiveClient_apiClient, "f").call('perspective.executeCommands', { uuid, commands, expression, parameters, batchId });
5440
5530
  }
@@ -5542,7 +5632,21 @@ class PerspectiveClient {
5542
5632
  __classPrivateFieldGet$9(this, _PerspectiveClient_linkUnsubscribers, "f").set(uuid, existing);
5543
5633
  await __classPrivateFieldGet$9(this, _PerspectiveClient_apiClient, "f").waitForSubscription();
5544
5634
  }
5545
- getNeighbourhoodProxy(uuid) {
5635
+ /** Unsubscribe all link/sync-state listeners registered for the given perspective UUID.
5636
+ * Called by PerspectiveProxy.dispose() to prevent subscription leaks. */
5637
+ removeAllListeners(uuid) {
5638
+ const unsubs = __classPrivateFieldGet$9(this, _PerspectiveClient_linkUnsubscribers, "f").get(uuid);
5639
+ if (unsubs) {
5640
+ for (const fn of unsubs) {
5641
+ try {
5642
+ fn();
5643
+ }
5644
+ catch { }
5645
+ }
5646
+ __classPrivateFieldGet$9(this, _PerspectiveClient_linkUnsubscribers, "f").delete(uuid);
5647
+ }
5648
+ }
5649
+ getNeighbourhoodProxy(uuid) {
5546
5650
  return new NeighbourhoodProxy(__classPrivateFieldGet$9(this, _PerspectiveClient_neighbourhoodClient, "f"), uuid);
5547
5651
  }
5548
5652
  async createBatch(uuid) {
@@ -5721,6 +5825,7 @@ class AgentClient {
5721
5825
  // L1: in-memory promise cache with timestamps for TTL
5722
5826
  _AgentClient_memCache.set(this, new Map());
5723
5827
  // L2: persistent cache (IndexedDB in browser, NullCache in Node)
5828
+ // Entries are wrapped with a timestamp so the TTL can be enforced across restarts.
5724
5829
  _AgentClient_persistent.set(this, void 0);
5725
5830
  // Self-DID for event-driven invalidation (no TTL for own profile)
5726
5831
  _AgentClient_selfDid.set(this, null);
@@ -5744,6 +5849,11 @@ class AgentClient {
5744
5849
  const agent = await __classPrivateFieldGet$7(this, _AgentClient_apiClient, "f").call('agent.get');
5745
5850
  let agentObject = new Agent(agent.did, agent.perspective);
5746
5851
  agentObject.directMessageLanguage = agent.directMessageLanguage;
5852
+ // Auto-set selfDid so event-driven cache invalidation works
5853
+ // without requiring apps to call setSelfDid() manually
5854
+ if (agentObject.did && !__classPrivateFieldGet$7(this, _AgentClient_selfDid, "f")) {
5855
+ __classPrivateFieldSet$7(this, _AgentClient_selfDid, agentObject.did, "f");
5856
+ }
5747
5857
  return agentObject;
5748
5858
  }
5749
5859
  async status() {
@@ -5780,13 +5890,14 @@ class AgentClient {
5780
5890
  // Deduplicate: store the promise immediately so concurrent calls share one RPC
5781
5891
  const promise = (async () => {
5782
5892
  // L2: check persistent cache before network
5783
- const persisted = await __classPrivateFieldGet$7(this, _AgentClient_persistent, "f").get(did);
5784
- if (persisted) {
5785
- return persisted;
5893
+ const entry = await __classPrivateFieldGet$7(this, _AgentClient_persistent, "f").get(did);
5894
+ // entry.agent may be undefined for pre-TTL cache entries (migration) — treat as expired
5895
+ if (entry?.agent && (now - (entry.ts ?? 0)) < AgentClient.REMOTE_AGENT_TTL_L2_MS) {
5896
+ return entry.agent;
5786
5897
  }
5787
5898
  // L3: network fetch
5788
5899
  const result = await __classPrivateFieldGet$7(this, _AgentClient_apiClient, "f").call('agent.byDid', { did });
5789
- __classPrivateFieldGet$7(this, _AgentClient_persistent, "f").put(did, result); // fire-and-forget write to L2
5900
+ __classPrivateFieldGet$7(this, _AgentClient_persistent, "f").put(did, { agent: result, ts: Date.now() }); // fire-and-forget write to L2
5790
5901
  return result;
5791
5902
  })();
5792
5903
  __classPrivateFieldGet$7(this, _AgentClient_memCache, "f").set(did, { promise, ts: now });
@@ -5831,6 +5942,12 @@ class AgentClient {
5831
5942
  const a = await __classPrivateFieldGet$7(this, _AgentClient_apiClient, "f").call('agent.updateProfile', { publicPerspective: cleanedPerspective });
5832
5943
  const agent = new Agent(a.did, a.perspective);
5833
5944
  agent.directMessageLanguage = a.directMessageLanguage;
5945
+ // Immediately update byDID cache so subsequent byDID() calls
5946
+ // return fresh data without waiting for the subscription event
5947
+ if (agent.did) {
5948
+ __classPrivateFieldGet$7(this, _AgentClient_memCache, "f").set(agent.did, { promise: Promise.resolve(agent), ts: Date.now() });
5949
+ __classPrivateFieldGet$7(this, _AgentClient_persistent, "f").put(agent.did, { agent, ts: Date.now() }); // fire-and-forget
5950
+ }
5834
5951
  return agent;
5835
5952
  }
5836
5953
  async mutatePublicPerspective(mutations) {
@@ -5855,6 +5972,12 @@ class AgentClient {
5855
5972
  const a = await __classPrivateFieldGet$7(this, _AgentClient_apiClient, "f").call('agent.updateProfile', { dmLanguage: directMessageLanguage });
5856
5973
  const agent = new Agent(a.did, a.perspective);
5857
5974
  agent.directMessageLanguage = a.directMessageLanguage;
5975
+ // Immediately update byDID cache so subsequent byDID() calls
5976
+ // return fresh data without waiting for the subscription event
5977
+ if (agent.did) {
5978
+ __classPrivateFieldGet$7(this, _AgentClient_memCache, "f").set(agent.did, { promise: Promise.resolve(agent), ts: Date.now() });
5979
+ __classPrivateFieldGet$7(this, _AgentClient_persistent, "f").put(agent.did, { agent, ts: Date.now() }); // fire-and-forget
5980
+ }
5858
5981
  return agent;
5859
5982
  }
5860
5983
  async addEntanglementProofs(proofs) {
@@ -5885,7 +6008,7 @@ class AgentClient {
5885
6008
  promise: Promise.resolve(agent),
5886
6009
  ts: Date.now(),
5887
6010
  });
5888
- __classPrivateFieldGet$7(this, _AgentClient_persistent, "f").put(agent.did, agent); // fire-and-forget
6011
+ __classPrivateFieldGet$7(this, _AgentClient_persistent, "f").put(agent.did, { agent, ts: Date.now() }); // fire-and-forget
5889
6012
  }
5890
6013
  __classPrivateFieldGet$7(this, _AgentClient_updatedCallbacks, "f").forEach((cb) => cb(agent));
5891
6014
  }
@@ -5989,6 +6112,9 @@ class AgentClient {
5989
6112
  _AgentClient_apiClient = new WeakMap(), _AgentClient_baseUrl = new WeakMap(), _AgentClient_token = new WeakMap(), _AgentClient_appsChangedCallback = new WeakMap(), _AgentClient_updatedCallbacks = new WeakMap(), _AgentClient_agentStatusChangedCallbacks = new WeakMap(), _AgentClient_hostingUserInfoChangedCallbacks = new WeakMap(), _AgentClient_computeLogUpdatedCallbacks = new WeakMap(), _AgentClient_unsubscribers = new WeakMap(), _AgentClient_memCache = new WeakMap(), _AgentClient_persistent = new WeakMap(), _AgentClient_selfDid = new WeakMap();
5990
6113
  /** TTL for remote (non-self) agent profiles in L1 cache (ms). */
5991
6114
  AgentClient.REMOTE_AGENT_TTL_MS = 5 * 60000; // 5 minutes
6115
+ /** TTL for remote agent profiles in the L2 (IndexedDB) cache (ms).
6116
+ * After this window any restart triggers a fresh network fetch. */
6117
+ AgentClient.REMOTE_AGENT_TTL_L2_MS = 5 * 60000; // 5 minutes
5992
6118
 
5993
6119
  var __classPrivateFieldSet$6 = (undefined && undefined.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {
5994
6120
  if (kind === "m") throw new TypeError("Private method is not writable");
@@ -13750,7 +13876,7 @@ class AIClient {
13750
13876
  // Use slice to get only the relevant portion of the underlying ArrayBuffer
13751
13877
  // (Float32Array may be a view over a larger buffer)
13752
13878
  const bodyBuffer = typedAudio.buffer.slice(typedAudio.byteOffset, typedAudio.byteOffset + typedAudio.byteLength);
13753
- const response = await fetch(`${baseUrl}/api/v1/ai/transcription/feed`, {
13879
+ const response = await __classPrivateFieldGet$2(this, _AIClient_apiClient, "f").doFetch(`${baseUrl}/api/v1/ai/transcription/feed`, {
13754
13880
  method: 'POST',
13755
13881
  headers: {
13756
13882
  'Content-Type': 'application/octet-stream',
@@ -14212,7 +14338,9 @@ function escapeSPARQL(value) {
14212
14338
  .replace(/"/g, '\\"')
14213
14339
  .replace(/\n/g, "\\n")
14214
14340
  .replace(/\r/g, "\\r")
14215
- .replace(/\t/g, "\\t");
14341
+ .replace(/\t/g, "\\t")
14342
+ .replace(/\0/g, "")
14343
+ .replace(/\f/g, "\\u000C");
14216
14344
  }
14217
14345
  /**
14218
14346
  * Format a value as a SPARQL string literal (double-quoted).
@@ -14227,8 +14355,14 @@ function formatSPARQLValue(value) {
14227
14355
  * Format an AD4M URI as an RDF IRI for use in SPARQL triple patterns.
14228
14356
  * All AD4M link source/predicate/target values become IRIs in angle brackets.
14229
14357
  * The Rust SPARQL service transparently transforms these to valid IRI format.
14358
+ *
14359
+ * Rejects characters that would break or inject into a SPARQL IRI token,
14360
+ * matching the Rust-side `validate_iri()` function.
14230
14361
  */
14231
14362
  function iri(value) {
14363
+ if (/[<>{}" ]/.test(value)) {
14364
+ throw new Error(`Invalid IRI component: '${value}'`);
14365
+ }
14232
14366
  return `<${value}>`;
14233
14367
  }
14234
14368
  /**
@@ -14374,21 +14508,8 @@ function buildSPARQLQuery(metadata, allRelationsMetadata, query, modelClass) {
14374
14508
  ?_reifier <ad4m://ontology/timestamp> ?timestamp .
14375
14509
  ${filterClause}
14376
14510
  }
14377
- ${buildSPARQLOrderLimitOffset()}
14378
14511
  `.trim();
14379
14512
  }
14380
- /**
14381
- * Build ORDER BY / LIMIT / OFFSET clauses for the SPARQL query.
14382
- *
14383
- * NOTE: The outer SELECT returns multiple rows per instance (one per link),
14384
- * so LIMIT/OFFSET at the outer level would cut off links mid-instance.
14385
- * This function is kept for backward compatibility and always returns "".
14386
- * SPARQL-level pagination is handled via a subquery in buildSPARQLQuery
14387
- * using buildPaginationSubquery().
14388
- */
14389
- function buildSPARQLOrderLimitOffset(_metadata, query) {
14390
- return "";
14391
- }
14392
14513
  /**
14393
14514
  * Build an inner subquery that selects DISTINCT ?source URIs with
14394
14515
  * ORDER BY, LIMIT, and OFFSET applied at the instance level.
@@ -14435,7 +14556,7 @@ function buildPaginationSubquery(joinPatterns, filterExpressions, metadata, quer
14435
14556
  { SELECT DISTINCT ?source${tsSelect} WHERE {${innerJoin}${orderJoinPatterns.join('')}${tsPattern}
14436
14557
  FILTER(isIRI(?source))
14437
14558
  ${innerFilter}
14438
- } GROUP BY ?source ${orderByClause} ${limitClause} ${offsetClause} }\n`;
14559
+ } ${orderByClause} ${limitClause} ${offsetClause} }\n`;
14439
14560
  }
14440
14561
  /**
14441
14562
  * Build SPARQL FILTER expressions from user `where` conditions.
@@ -14487,8 +14608,8 @@ function buildSPARQLWhereFilters(metadata, _allRelationsMetadata, where) {
14487
14608
  const useParseLiteral = isLiteralStoredProperty(propMeta);
14488
14609
  // For literal-stored properties, push equality/IN/NOT filters to SPARQL using
14489
14610
  // <ad4m://fn/parse_literal>() which extracts the raw value from literal: IRIs.
14490
- // The correct SPARQL syntax is <ad4m://fn/parse_literal>(?var) — NOT fn::parse_literal
14491
- // (which was SurrealDB syntax that Oxigraph rejects at parse time).
14611
+ // Use IRI form <ad4m://fn/parse_literal>(?var); the namespaced form
14612
+ // fn::parse_literal is invalid SPARQL and Oxigraph rejects it at parse time.
14492
14613
  // Comparison operators (gt/lt/gte/lte/between/contains) remain JS-only because
14493
14614
  // parse_literal returns strings and numeric/date comparisons would be unreliable.
14494
14615
  // JS post-filter in instancesFromQueryResult remains as a safety net for all cases.
@@ -14831,13 +14952,6 @@ class ModelQueryBuilder {
14831
14952
  this.modelClassName = className;
14832
14953
  return this;
14833
14954
  }
14834
- /**
14835
- * Sets the query engine to use.
14836
- * @deprecated Prolog engine has been removed. All queries use SPARQL/Rust.
14837
- */
14838
- engine(_eng) {
14839
- return this;
14840
- }
14841
14955
  /**
14842
14956
  * Executes the query once and returns the results.
14843
14957
  *
@@ -14881,8 +14995,10 @@ class ModelQueryBuilder {
14881
14995
  * ```
14882
14996
  */
14883
14997
  async first() {
14998
+ const savedLimit = this.queryParams.limit;
14884
14999
  this.queryParams.limit = 1;
14885
15000
  const results = await this.get();
15001
+ this.queryParams.limit = savedLimit;
14886
15002
  return results[0] ?? null;
14887
15003
  }
14888
15004
  /**
@@ -14917,23 +15033,18 @@ class ModelQueryBuilder {
14917
15033
  // Clean up any existing subscription
14918
15034
  this.dispose();
14919
15035
  const ctor = this.ctor;
14920
- // Build the model query params (className, queryJson, shapeJson)
14921
- const { className, queryJson, shapeJson } = ctor.prepareModelQueryParams(this.queryParams, this.modelClassName);
15036
+ // Build the model query params (className, queryJson). The executor
15037
+ // resolves the shape from the perspective's SHACL triples.
15038
+ const { className, queryJson } = ctor.prepareModelQueryParams(this.queryParams, this.modelClassName);
14922
15039
  // Register model subscription via Rust — this builds trigger SPARQL internally,
14923
15040
  // registers the subscription, and runs the initial query in one call.
14924
- const { subscriptionId, result: initialModelResult } = await this.perspective.modelSubscribe(className, queryJson, shapeJson);
15041
+ const { subscriptionId, result: initialModelResult } = await this.perspective.modelSubscribe(className, queryJson);
14925
15042
  // Convert JSON instances to model class instances
14926
15043
  const parseResults = (raw) => {
14927
15044
  return ctor.parseModelResult(this.perspective, raw, this.queryParams.include, this.queryParams.properties);
14928
15045
  };
14929
- // Resolve non-literal (file-language) properties — handles both raw URI strings
14930
- // and already-resolved FileData objects returned by the Rust executor.
14931
- const resolveAndReturn = async (instances) => {
14932
- await ctor.resolveNonLiteralProps(this.perspective, instances);
14933
- return instances;
14934
- };
14935
- // Parse initial results (with non-literal resolution)
14936
- const initialResults = await resolveAndReturn(parseResults(initialModelResult));
15046
+ // Transforms are now applied by the Rust executor during hydration
15047
+ const initialResults = parseResults(initialModelResult);
14937
15048
  // Track last emitted result fingerprint to suppress duplicate callbacks
14938
15049
  let lastResultFingerprint = null;
14939
15050
  const buildFingerprint = (results) => {
@@ -14946,34 +15057,65 @@ class ModelQueryBuilder {
14946
15057
  // When Rust re-runs the model query and finds changed results, it pushes them.
14947
15058
  const unsubscribe = this.perspective.client.subscribeToQueryUpdates(subscriptionId, (rawResult) => {
14948
15059
  try {
14949
- resolveAndReturn(parseResults(rawResult)).then((results) => {
14950
- const fp = buildFingerprint(results);
14951
- if (fp === lastResultFingerprint)
14952
- return;
14953
- lastResultFingerprint = fp;
14954
- callback(results);
14955
- }).catch((e) => {
14956
- console.error('Model subscription update resolve error:', e);
14957
- });
15060
+ const results = parseResults(rawResult);
15061
+ console.debug(`[ModelQueryBuilder.subscribe] Update received for ${subscriptionId}: ${results.length} instances`);
15062
+ const fp = buildFingerprint(results);
15063
+ if (fp === lastResultFingerprint) {
15064
+ console.debug(`[ModelQueryBuilder.subscribe] Fingerprint unchanged, skipping callback`);
15065
+ return;
15066
+ }
15067
+ console.debug(`[ModelQueryBuilder.subscribe] Fingerprint changed, calling callback with ${results.length} results`);
15068
+ lastResultFingerprint = fp;
15069
+ callback(results);
14958
15070
  }
14959
15071
  catch (e) {
14960
15072
  console.error('Model subscription update parse error:', e);
14961
15073
  }
14962
15074
  });
14963
- // Set up keepalive with failure tracking
14964
- let keepaliveFailures = 0;
14965
- const keepaliveTimer = setInterval(() => {
14966
- this.perspective.client.keepAliveQuery(this.perspective.uuid, subscriptionId).then(() => {
14967
- keepaliveFailures = 0;
14968
- }).catch((e) => {
14969
- keepaliveFailures++;
14970
- console.warn(`Model subscription keepalive failed (attempt ${keepaliveFailures}) for ${subscriptionId}:`, e);
14971
- });
14972
- }, 30000);
15075
+ // Set up keepalive with recovery — uses setTimeout loop so we can
15076
+ // break out and resubscribe when the server evicts the subscription.
15077
+ let disposed = false;
15078
+ let keepaliveTimer;
15079
+ let resubscribeAttempts = 0;
15080
+ const MAX_RESUBSCRIBE_ATTEMPTS = 5;
15081
+ const keepaliveLoop = async () => {
15082
+ if (disposed)
15083
+ return;
15084
+ try {
15085
+ await this.perspective.client.keepAliveQuery(this.perspective.uuid, subscriptionId);
15086
+ resubscribeAttempts = 0; // Reset on success
15087
+ }
15088
+ catch (e) {
15089
+ console.warn(`Model subscription keepalive failed for ${subscriptionId}:`, e);
15090
+ if (!disposed && resubscribeAttempts < MAX_RESUBSCRIBE_ATTEMPTS) {
15091
+ resubscribeAttempts++;
15092
+ const backoffMs = Math.min(1000 * Math.pow(2, resubscribeAttempts), 60000);
15093
+ console.warn(`Resubscribing (attempt ${resubscribeAttempts}/${MAX_RESUBSCRIBE_ATTEMPTS}, backoff ${backoffMs}ms)...`);
15094
+ await new Promise(r => setTimeout(r, backoffMs));
15095
+ try {
15096
+ unsubscribe();
15097
+ await this.subscribe(callback);
15098
+ }
15099
+ catch (resubErr) {
15100
+ console.error('Model subscription resubscribe failed:', resubErr);
15101
+ }
15102
+ }
15103
+ else if (resubscribeAttempts >= MAX_RESUBSCRIBE_ATTEMPTS) {
15104
+ console.error(`Model subscription ${subscriptionId}: max resubscribe attempts reached, giving up.`);
15105
+ }
15106
+ return; // new subscription owns its own keepalive loop
15107
+ }
15108
+ if (!disposed) {
15109
+ keepaliveTimer = setTimeout(keepaliveLoop, 30000);
15110
+ }
15111
+ };
15112
+ keepaliveTimer = setTimeout(keepaliveLoop, 30000);
14973
15113
  // Store dispose function
14974
15114
  this.currentSubscription = {
14975
15115
  dispose: () => {
14976
- clearInterval(keepaliveTimer);
15116
+ disposed = true;
15117
+ if (keepaliveTimer)
15118
+ clearTimeout(keepaliveTimer);
14977
15119
  unsubscribe();
14978
15120
  this.perspective.client.disposeQuerySubscription(this.perspective.uuid, subscriptionId).catch(() => { });
14979
15121
  },
@@ -15046,8 +15188,8 @@ class ModelQueryBuilder {
15046
15188
  // Clean up any existing subscription
15047
15189
  this.dispose();
15048
15190
  const countParams = { ...this.queryParams, limit: 0 };
15049
- const { className, queryJson, shapeJson } = this.ctor.prepareModelQueryParams(countParams, this.modelClassName);
15050
- const { subscriptionId, result: initialModelResult } = await this.perspective.modelSubscribe(className, queryJson, shapeJson);
15191
+ const { className, queryJson } = this.ctor.prepareModelQueryParams(countParams, this.modelClassName);
15192
+ const { subscriptionId, result: initialModelResult } = await this.perspective.modelSubscribe(className, queryJson);
15051
15193
  const parseCount = (raw) => {
15052
15194
  const data = typeof raw === 'string' ? JSON.parse(raw) : raw;
15053
15195
  return data.totalCount ?? 0;
@@ -15061,18 +15203,47 @@ class ModelQueryBuilder {
15061
15203
  console.error('Count subscription update parse error:', e);
15062
15204
  }
15063
15205
  });
15064
- let keepaliveFailures = 0;
15065
- const keepaliveTimer = setInterval(() => {
15066
- this.perspective.client.keepAliveQuery(this.perspective.uuid, subscriptionId).then(() => {
15067
- keepaliveFailures = 0;
15068
- }).catch((e) => {
15069
- keepaliveFailures++;
15070
- console.warn(`Count subscription keepalive failed (attempt ${keepaliveFailures}) for ${subscriptionId}:`, e);
15071
- });
15072
- }, 30000);
15206
+ let disposed = false;
15207
+ let keepaliveTimer;
15208
+ let resubscribeAttempts = 0;
15209
+ const MAX_RESUBSCRIBE_ATTEMPTS = 5;
15210
+ const keepaliveLoop = async () => {
15211
+ if (disposed)
15212
+ return;
15213
+ try {
15214
+ await this.perspective.client.keepAliveQuery(this.perspective.uuid, subscriptionId);
15215
+ resubscribeAttempts = 0;
15216
+ }
15217
+ catch (e) {
15218
+ console.warn(`Count subscription keepalive failed for ${subscriptionId}:`, e);
15219
+ if (!disposed && resubscribeAttempts < MAX_RESUBSCRIBE_ATTEMPTS) {
15220
+ resubscribeAttempts++;
15221
+ const backoffMs = Math.min(1000 * Math.pow(2, resubscribeAttempts), 60000);
15222
+ console.warn(`Count resubscribing (attempt ${resubscribeAttempts}/${MAX_RESUBSCRIBE_ATTEMPTS}, backoff ${backoffMs}ms)...`);
15223
+ await new Promise(r => setTimeout(r, backoffMs));
15224
+ try {
15225
+ unsubscribe();
15226
+ await this.countSubscribe(callback);
15227
+ }
15228
+ catch (resubErr) {
15229
+ console.error('Count subscription resubscribe failed:', resubErr);
15230
+ }
15231
+ }
15232
+ else if (resubscribeAttempts >= MAX_RESUBSCRIBE_ATTEMPTS) {
15233
+ console.error(`Count subscription ${subscriptionId}: max resubscribe attempts reached, giving up.`);
15234
+ }
15235
+ return;
15236
+ }
15237
+ if (!disposed) {
15238
+ keepaliveTimer = setTimeout(keepaliveLoop, 30000);
15239
+ }
15240
+ };
15241
+ keepaliveTimer = setTimeout(keepaliveLoop, 30000);
15073
15242
  this.currentSubscription = {
15074
15243
  dispose: () => {
15075
- clearInterval(keepaliveTimer);
15244
+ disposed = true;
15245
+ if (keepaliveTimer)
15246
+ clearTimeout(keepaliveTimer);
15076
15247
  unsubscribe();
15077
15248
  this.perspective.client.disposeQuerySubscription(this.perspective.uuid, subscriptionId).catch(() => { });
15078
15249
  },
@@ -15153,8 +15324,8 @@ class ModelQueryBuilder {
15153
15324
  const subscriptionParams = { ...(this.queryParams || {}) };
15154
15325
  delete subscriptionParams.limit;
15155
15326
  delete subscriptionParams.offset;
15156
- const { className, queryJson, shapeJson } = ctor.prepareModelQueryParams(subscriptionParams, this.modelClassName);
15157
- const { subscriptionId } = await this.perspective.modelSubscribe(className, queryJson, shapeJson);
15327
+ const { className, queryJson } = ctor.prepareModelQueryParams(subscriptionParams, this.modelClassName);
15328
+ const { subscriptionId } = await this.perspective.modelSubscribe(className, queryJson);
15158
15329
  // Build the paginated query for Rust endpoint (count: true fetches both results and totalCount in one call)
15159
15330
  const paginatedQuery = {
15160
15331
  ...(this.queryParams || {}),
@@ -15167,20 +15338,50 @@ class ModelQueryBuilder {
15167
15338
  callback({ results, totalCount, pageSize, pageNumber });
15168
15339
  };
15169
15340
  const unsubscribe = this.perspective.client.subscribeToQueryUpdates(subscriptionId, (rawResult) => {
15341
+ console.debug(`[ModelQueryBuilder.paginateSubscribe] Update received for ${subscriptionId}, re-fetching paginated data...`);
15170
15342
  processResults().catch(e => console.error('Paginate subscription error:', e));
15171
15343
  });
15172
- let keepaliveFailures = 0;
15173
- const keepaliveTimer = setInterval(() => {
15174
- this.perspective.client.keepAliveQuery(this.perspective.uuid, subscriptionId).then(() => {
15175
- keepaliveFailures = 0;
15176
- }).catch((e) => {
15177
- keepaliveFailures++;
15178
- console.warn(`Paginate subscription keepalive failed (attempt ${keepaliveFailures}) for ${subscriptionId}:`, e);
15179
- });
15180
- }, 30000);
15344
+ let disposed = false;
15345
+ let keepaliveTimer;
15346
+ let resubscribeAttempts = 0;
15347
+ const MAX_RESUBSCRIBE_ATTEMPTS = 5;
15348
+ const keepaliveLoop = async () => {
15349
+ if (disposed)
15350
+ return;
15351
+ try {
15352
+ await this.perspective.client.keepAliveQuery(this.perspective.uuid, subscriptionId);
15353
+ resubscribeAttempts = 0;
15354
+ }
15355
+ catch (e) {
15356
+ console.warn(`Paginate subscription keepalive failed for ${subscriptionId}:`, e);
15357
+ if (!disposed && resubscribeAttempts < MAX_RESUBSCRIBE_ATTEMPTS) {
15358
+ resubscribeAttempts++;
15359
+ const backoffMs = Math.min(1000 * Math.pow(2, resubscribeAttempts), 60000);
15360
+ console.warn(`Paginate resubscribing (attempt ${resubscribeAttempts}/${MAX_RESUBSCRIBE_ATTEMPTS}, backoff ${backoffMs}ms)...`);
15361
+ await new Promise(r => setTimeout(r, backoffMs));
15362
+ try {
15363
+ unsubscribe();
15364
+ await this.paginateSubscribe(pageSize, pageNumber, callback);
15365
+ }
15366
+ catch (resubErr) {
15367
+ console.error('Paginate subscription resubscribe failed:', resubErr);
15368
+ }
15369
+ }
15370
+ else if (resubscribeAttempts >= MAX_RESUBSCRIBE_ATTEMPTS) {
15371
+ console.error(`Paginate subscription ${subscriptionId}: max resubscribe attempts reached, giving up.`);
15372
+ }
15373
+ return;
15374
+ }
15375
+ if (!disposed) {
15376
+ keepaliveTimer = setTimeout(keepaliveLoop, 30000);
15377
+ }
15378
+ };
15379
+ keepaliveTimer = setTimeout(keepaliveLoop, 30000);
15181
15380
  this.currentSubscription = {
15182
15381
  dispose: () => {
15183
- clearInterval(keepaliveTimer);
15382
+ disposed = true;
15383
+ if (keepaliveTimer)
15384
+ clearTimeout(keepaliveTimer);
15184
15385
  unsubscribe();
15185
15386
  this.perspective.client.disposeQuerySubscription(this.perspective.uuid, subscriptionId).catch(() => { });
15186
15387
  },
@@ -15220,91 +15421,9 @@ function normalizeValue(value) {
15220
15421
  return value;
15221
15422
  }
15222
15423
 
15223
- // ---------------------------------------------------------------------------
15224
- // Default decoder for file-storage (non-literal resolveLanguage) properties
15225
- // ---------------------------------------------------------------------------
15226
- /**
15227
- * When the Rust executor resolves a non-literal expression it may return a
15228
- * `FileData`-shaped object (`{ data_base64, file_type, ... }`) rather than a
15229
- * raw URI string. If the model class has no custom `transform` registered
15230
- * (e.g. it was synthesised from a SHACL shape at runtime) we still want to
15231
- * decode the content rather than passing raw `FileData` to callers.
15232
- *
15233
- * Decoding rules (mirrors the JS `decodeFileAsJson` / `decodeFileAsString` helpers):
15234
- * - `application/json` (default when `file_type` is absent) → JSON.parse
15235
- * - anything else → raw decoded string
15236
- *
15237
- * If `resolved` is not a `FileData` object the value is returned unchanged so
15238
- * that callers can use this as a safe unconditional fallback.
15239
- */
15240
- function defaultFileDecode(resolved) {
15241
- if (resolved !== null &&
15242
- typeof resolved === 'object' &&
15243
- 'data_base64' in resolved) {
15244
- const fd = resolved;
15245
- let raw;
15246
- try {
15247
- raw = atob(fd.data_base64);
15248
- }
15249
- catch {
15250
- return resolved; // malformed base64 — keep as-is
15251
- }
15252
- const isJson = !fd.file_type || fd.file_type === 'application/json';
15253
- if (isJson) {
15254
- try {
15255
- return JSON.parse(raw);
15256
- }
15257
- catch {
15258
- return raw;
15259
- }
15260
- }
15261
- return raw;
15262
- }
15263
- return resolved;
15264
- }
15265
15424
  // ---------------------------------------------------------------------------
15266
15425
  // Helpers for Rust-side include resolution
15267
15426
  // ---------------------------------------------------------------------------
15268
- /**
15269
- * Recursively enrich relation metadata in the shape with target class shapes
15270
- * so the Rust endpoint can resolve includes in-process (no extra GraphQL
15271
- * round-trips per relation).
15272
- */
15273
- function enrichShapeForIncludes(metadata, include, allRelMeta) {
15274
- for (const [relName, includeVal] of Object.entries(include)) {
15275
- if (!includeVal)
15276
- continue;
15277
- const meta = allRelMeta[relName];
15278
- if (!meta?.target)
15279
- continue;
15280
- const TargetClass = meta.target();
15281
- // Deep-copy so we don't mutate the cached metadata
15282
- const targetMeta = JSON.parse(JSON.stringify(TargetClass.getModelMetadata()));
15283
- // Ensure the relation is in metadata.relations (fallback for edge cases)
15284
- if (!metadata.relations[relName]) {
15285
- metadata.relations[relName] = {
15286
- name: relName,
15287
- predicate: meta.predicate,
15288
- direction: meta.kind === 'belongsToMany' || meta.kind === 'belongsToOne'
15289
- ? 'reverse'
15290
- : 'forward',
15291
- };
15292
- }
15293
- const rel = metadata.relations[relName];
15294
- rel.kind = meta.kind;
15295
- rel.maxCount = meta.maxCount;
15296
- rel.targetShape = targetMeta;
15297
- rel.targetClassName = targetMeta.className;
15298
- // Recurse for nested includes
15299
- const nested = typeof includeVal === 'object' && includeVal !== null
15300
- ? includeVal.include
15301
- : undefined;
15302
- if (nested) {
15303
- const targetRelMeta = getRelationsMetadata(TargetClass);
15304
- enrichShapeForIncludes(targetMeta, nested, targetRelMeta);
15305
- }
15306
- }
15307
- }
15308
15427
  /**
15309
15428
  * Construct a model class instance from a plain JSON object returned by the
15310
15429
  * Rust endpoint. Recursively converts included relation values (which come
@@ -15349,22 +15468,6 @@ function jsonToModelInstance(ModelClass, perspective, json, include, properties)
15349
15468
  }
15350
15469
  instance[key] = value;
15351
15470
  }
15352
- // Apply property transform functions from decorators (only for literal-resolved
15353
- // or no-resolveLanguage properties; non-literal properties are resolved + transformed
15354
- // asynchronously in executeModelQuery).
15355
- try {
15356
- const propsMeta = getPropertiesMetadata(ModelClass);
15357
- for (const [propName, opts] of Object.entries(propsMeta)) {
15358
- const o = opts;
15359
- if (typeof o.transform !== 'function' || !(propName in json))
15360
- continue;
15361
- // Skip non-literal resolveLanguage props — they need async expression resolution first
15362
- if (o.resolveLanguage != null && o.resolveLanguage !== 'literal')
15363
- continue;
15364
- instance[propName] = o.transform(instance[propName]);
15365
- }
15366
- }
15367
- catch (_) { /* no metadata available */ }
15368
15471
  // Recursively convert included relation values to class instances
15369
15472
  if (include) {
15370
15473
  const relMeta = getRelationsMetadata(ModelClass);
@@ -15602,8 +15705,8 @@ class Ad4mModel {
15602
15705
  ...(options.getter !== undefined && { getter: options.getter }),
15603
15706
  ...(options.prologSetter !== undefined && { prologSetter: options.prologSetter }),
15604
15707
  ...(options.local !== undefined && { local: options.local }),
15605
- ...(options.transform !== undefined && { transform: options.transform }),
15606
- ...(options.flag !== undefined && { flag: options.flag })
15708
+ ...(options.flag !== undefined && { flag: options.flag }),
15709
+ ...(options.transform !== undefined && { transform: options.transform })
15607
15710
  };
15608
15711
  }
15609
15712
  // Extract relations (relations) from WeakMap registry
@@ -15788,6 +15891,7 @@ class Ad4mModel {
15788
15891
  * • `null` / empty object — skip ALL relations (used by bare
15789
15892
  * subscriptions that don't eagerly load relations).
15790
15893
  */
15894
+ /** @internal */
15791
15895
  takeSnapshot(includedRelations) {
15792
15896
  const ctor = this.constructor;
15793
15897
  const metadata = ctor.getModelMetadata();
@@ -15983,164 +16087,14 @@ class Ad4mModel {
15983
16087
  }
15984
16088
  /**
15985
16089
  * Build the JSON parameters needed for a model query/subscription endpoint.
15986
- * Returns the className, queryJson, and shapeJson that the Rust executor expects.
16090
+ * Returns the className and queryJson that the Rust executor expects.
16091
+ * Shape resolution happens server-side from the perspective's SHACL triples.
15987
16092
  * @internal
15988
16093
  */
15989
16094
  static prepareModelQueryParams(query = {}, classNameOverride) {
15990
- const metadata = this.getModelMetadata();
15991
- const className = classNameOverride || metadata.className;
15992
- const queryInput = {};
15993
- if (query.parent) {
15994
- const parentPredicate = resolveParentPredicate(query.parent, this);
15995
- queryInput.parent = { id: query.parent.id, predicate: parentPredicate };
15996
- }
15997
- if (query.properties)
15998
- queryInput.properties = query.properties;
15999
- if (query.include)
16000
- queryInput.include = query.include;
16001
- if (query.where)
16002
- queryInput.where = query.where;
16003
- if (query.order) {
16004
- queryInput.order = Object.entries(query.order).map(([k, v]) => [k, v]);
16005
- }
16006
- if (query.offset !== undefined)
16007
- queryInput.offset = query.offset;
16008
- if (query.limit !== undefined)
16009
- queryInput.limit = query.limit;
16010
- if (query.count !== undefined)
16011
- queryInput.count = query.count;
16012
- queryInput.deepQuery = query.deepQuery ?? true;
16013
- if (query.include) {
16014
- const allRelMeta = getRelationsMetadata(this);
16015
- enrichShapeForIncludes(metadata, query.include, allRelMeta);
16016
- }
16017
- // Pre-compute conformance getters for Rust-side evaluation.
16018
- // Where clauses are NOT compiled into getter SPARQL because stored
16019
- // property values are signed expression envelopes (literal:json:...),
16020
- // not simple literal:string:X values. Instead, where clauses are
16021
- // attached as metadata for Rust-side post-evaluation filtering.
16022
- {
16023
- const allRelMeta = getRelationsMetadata(this);
16024
- for (const [relName, relMeta] of Object.entries(metadata.relations)) {
16025
- const rel = relMeta;
16026
- if (rel.getter || rel.direction === 'reverse' || rel.filter === false)
16027
- continue;
16028
- const meta = allRelMeta[relName];
16029
- if (!meta?.target)
16030
- continue;
16031
- try {
16032
- const TargetClass = meta.target();
16033
- const filter = buildConformanceFilter(meta.predicate, TargetClass);
16034
- if (filter) {
16035
- rel.getter = filter.getter;
16036
- }
16037
- // Attach where-clause metadata for Rust-side post-getter filtering
16038
- if (rel.where) {
16039
- try {
16040
- const targetMetadata = TargetClass.getModelMetadata?.() ?? null;
16041
- if (targetMetadata) {
16042
- const predicates = {};
16043
- for (const propName of Object.keys(rel.where)) {
16044
- if (['id', 'author', 'timestamp'].includes(propName))
16045
- continue;
16046
- const propMeta = targetMetadata.properties[propName];
16047
- if (propMeta?.predicate) {
16048
- predicates[propName] = propMeta.predicate;
16049
- }
16050
- }
16051
- if (Object.keys(predicates).length > 0) {
16052
- rel.whereFilter = rel.where;
16053
- rel.wherePredicates = predicates;
16054
- }
16055
- }
16056
- }
16057
- catch (_) { }
16058
- }
16059
- }
16060
- catch (_) { }
16061
- }
16062
- }
16063
- return {
16064
- className,
16065
- queryJson: JSON.stringify(queryInput),
16066
- shapeJson: JSON.stringify(metadata),
16067
- };
16068
- }
16069
- /**
16070
- * Parse raw model query/subscription result JSON into typed model instances.
16071
- * Used by ModelQueryBuilder to convert subscription updates without circular imports.
16072
- * @internal
16073
- */
16074
- static parseModelResult(perspective, raw, include, properties) {
16075
- const data = typeof raw === 'string' ? JSON.parse(raw) : raw;
16076
- const arr = data.instances || data;
16077
- if (!Array.isArray(arr))
16078
- return [];
16079
- return arr.map((json) => jsonToModelInstance(this, perspective, json, include, properties));
16080
- }
16081
- /**
16082
- * Resolve non-literal (file-language) properties on an array of already-constructed
16083
- * model instances. Handles two cases:
16084
- *
16085
- * 1. The Rust executor returned a raw URI string → fetch via `getExpression` then apply transform.
16086
- * 2. The Rust executor already resolved the expression and returned a `FileData` object
16087
- * (happens when the perspective backend eagerly fetches file content) → apply transform
16088
- * (or `defaultFileDecode` if no transform is registered on the class, e.g. for SHACL-
16089
- * synthesised model classes).
16090
- *
16091
- * Extracted as a public static so `ModelQueryBuilder.subscribe()` can reuse it without
16092
- * duplicating logic or introducing a circular dependency.
16093
- * @internal
16094
- */
16095
- static async resolveNonLiteralProps(perspective, instances) {
16096
- const propsMeta = getPropertiesMetadata(this);
16097
- const resolveProps = Object.entries(propsMeta).filter(([, opts]) => opts.resolveLanguage != null &&
16098
- opts.resolveLanguage !== 'literal');
16099
- if (resolveProps.length === 0)
16100
- return;
16101
- await Promise.all(instances.map(async (inst) => {
16102
- for (const [propName, opts] of resolveProps) {
16103
- const val = inst[propName];
16104
- const transform = opts.transform;
16105
- const applyTransform = (resolved) => typeof transform === 'function' ? transform(resolved) : defaultFileDecode(resolved);
16106
- if (typeof val === 'string' && val && !val.startsWith('literal:')) {
16107
- // Case 1: raw URI — fetch from language runtime
16108
- try {
16109
- const expression = await perspective.getExpression(val);
16110
- if (expression) {
16111
- let resolved;
16112
- try {
16113
- resolved = JSON.parse(expression.data);
16114
- }
16115
- catch {
16116
- resolved = expression.data;
16117
- }
16118
- inst[propName] = applyTransform(resolved);
16119
- }
16120
- }
16121
- catch (_) { /* resolution failed — keep raw value */ }
16122
- }
16123
- else if (val !== null && val !== undefined && typeof val === 'object') {
16124
- // Case 2: already resolved by Rust — apply transform / default decode
16125
- inst[propName] = applyTransform(val);
16126
- }
16127
- }
16128
- }));
16129
- }
16130
- // instancesFromQueryResult — removed (superseded by Rust executeModelQuery pipeline)
16131
- /**
16132
- * Execute a model query via the executor-side endpoint.
16133
- *
16134
- * This replaces the old SPARQL-build → hydrate → JS-filter → JS-sort → JS-paginate pipeline
16135
- * with a single RPC to the executor that handles everything in Rust.
16136
- *
16137
- * @internal
16138
- */
16139
- static async executeModelQuery(perspective, query = {}, classNameOverride) {
16140
16095
  const metadata = this.getModelMetadata();
16141
16096
  const className = classNameOverride || metadata.className;
16142
16097
  // Expand includeAll: true to a full IncludeMap covering every forward relation.
16143
- // Done before queryInput is built so all downstream uses of query.include see the expansion.
16144
16098
  if (query.includeAll) {
16145
16099
  const allRelMeta = getRelationsMetadata(this);
16146
16100
  const expanded = {};
@@ -16149,11 +16103,8 @@ class Ad4mModel {
16149
16103
  expanded[relName] = true;
16150
16104
  }
16151
16105
  }
16152
- // Explicit include entries take precedence over the expansion
16153
16106
  query = { ...query, include: { ...expanded, ...query.include } };
16154
16107
  }
16155
- // Build the query input that the Rust endpoint expects.
16156
- // Convert the TS Query type to the executor's ModelQueryInput format.
16157
16108
  const queryInput = {};
16158
16109
  if (query.parent) {
16159
16110
  const parentPredicate = resolveParentPredicate(query.parent, this);
@@ -16177,19 +16128,23 @@ class Ad4mModel {
16177
16128
  if (Object.keys(normalIncludes).length > 0)
16178
16129
  queryInput.include = normalIncludes;
16179
16130
  if (Object.keys(projections).length > 0) {
16180
- // Enrich projections with target shapes so Rust can apply where clause filtering
16131
+ // Tag each projection with its target class name so the executor can
16132
+ // resolve the target shape through its in-memory cache when applying
16133
+ // projection where-clause filters.
16181
16134
  const allRelMeta = getRelationsMetadata(this);
16182
16135
  for (const [, proj] of Object.entries(projections)) {
16183
16136
  const relMeta = allRelMeta[proj.from];
16184
- if (!proj.targetShape && relMeta?.target) {
16137
+ if (!proj.targetClassName && relMeta?.target) {
16185
16138
  try {
16186
16139
  const TargetClass = relMeta.target();
16187
16140
  const targetMeta = TargetClass.getModelMetadata?.();
16188
- if (targetMeta) {
16189
- proj.targetShape = targetMeta;
16141
+ if (targetMeta?.className) {
16142
+ proj.targetClassName = targetMeta.className;
16190
16143
  }
16191
16144
  }
16192
- catch (_) { /* target class may not be available */ }
16145
+ catch (e) {
16146
+ console.debug(`prepareModelQueryParams: target class unavailable for projection:`, e);
16147
+ }
16193
16148
  }
16194
16149
  }
16195
16150
  queryInput.projections = projections;
@@ -16198,7 +16153,6 @@ class Ad4mModel {
16198
16153
  if (query.where)
16199
16154
  queryInput.where = query.where;
16200
16155
  if (query.order) {
16201
- // Convert { propName: 'ASC' | 'DESC' } to [[propName, 'ASC'|'DESC'], ...]
16202
16156
  queryInput.order = Object.entries(query.order).map(([k, v]) => [k, v]);
16203
16157
  }
16204
16158
  if (query.offset !== undefined)
@@ -16208,88 +16162,52 @@ class Ad4mModel {
16208
16162
  if (query.count !== undefined)
16209
16163
  queryInput.count = query.count;
16210
16164
  queryInput.deepQuery = query.deepQuery ?? true;
16211
- // Enrich relation metadata with target class shapes for Rust-side
16212
- // include resolution. This eliminates per-relation GraphQL round-trips
16213
- // by letting the Rust endpoint resolve includes in-process.
16214
- if (queryInput.include) {
16215
- const allRelMeta = getRelationsMetadata(this);
16216
- enrichShapeForIncludes(metadata, queryInput.include, allRelMeta);
16217
- }
16218
- // ── Pre-compute conformance getters for Rust-side evaluation ──────
16219
- // For each relation with a target class and filter !== false, compute
16220
- // the conformance getter SPARQL so Rust can evaluate it in-process
16221
- // (eliminating N × querySparql round-trips per instance).
16222
- // When a relation has a `where` clause, compile the where conditions
16223
- // into the getter SPARQL so Rust applies them during evaluation.
16224
- {
16225
- const allRelMeta = getRelationsMetadata(this);
16226
- for (const [relName, relMeta] of Object.entries(metadata.relations)) {
16227
- const rel = relMeta;
16228
- if (rel.getter)
16229
- continue; // explicit getter already set
16230
- if (rel.direction === 'reverse')
16231
- continue; // reverse relations use reverse link lookup
16232
- if (rel.filter === false)
16233
- continue; // opt-out of conformance filtering
16234
- const meta = allRelMeta[relName];
16235
- if (!meta?.target)
16236
- continue;
16237
- try {
16238
- const TargetClass = meta.target();
16239
- const filter = buildConformanceFilter(meta.predicate, TargetClass);
16240
- if (filter) {
16241
- rel.getter = filter.getter;
16242
- }
16243
- // Attach where-clause metadata for Rust-side post-getter filtering.
16244
- // Property values are signed expression envelopes (literal:json:...)
16245
- // and cannot be matched by SPARQL FILTER on the raw IRI.
16246
- if (rel.where) {
16247
- try {
16248
- const targetMetadata = TargetClass.getModelMetadata?.() ?? null;
16249
- if (targetMetadata) {
16250
- const predicates = {};
16251
- for (const propName of Object.keys(rel.where)) {
16252
- if (['id', 'author', 'timestamp'].includes(propName))
16253
- continue;
16254
- const propMeta = targetMetadata.properties[propName];
16255
- if (propMeta?.predicate) {
16256
- predicates[propName] = propMeta.predicate;
16257
- }
16258
- }
16259
- if (Object.keys(predicates).length > 0) {
16260
- rel.whereFilter = rel.where;
16261
- rel.wherePredicates = predicates;
16262
- }
16263
- }
16264
- }
16265
- catch (_) { /* target metadata unavailable */ }
16266
- }
16267
- }
16268
- catch (e) {
16269
- // Target class may not be available; skip silently
16270
- }
16271
- }
16272
- }
16273
- // Send shape metadata to the executor so it knows the model structure.
16274
- // This is more reliable than reading SHACL from the store because
16275
- // the TS decorators are the definitive source of truth.
16276
- const shapeJson = JSON.stringify(metadata);
16277
- const queryJson = JSON.stringify(queryInput);
16278
- const result = await perspective.modelQuery(className, queryJson, shapeJson);
16165
+ // Conformance getters, where filters, and target shapes for includes
16166
+ // are all resolved by the executor from the perspective's SHACL triples
16167
+ // — no client-side pre-computation is needed any more.
16168
+ return {
16169
+ className,
16170
+ queryJson: JSON.stringify(queryInput),
16171
+ metadata,
16172
+ };
16173
+ }
16174
+ /**
16175
+ * Parse raw model query/subscription result JSON into typed model instances.
16176
+ * Used by ModelQueryBuilder to convert subscription updates without circular imports.
16177
+ * @internal
16178
+ */
16179
+ static parseModelResult(perspective, raw, include, properties) {
16180
+ const data = typeof raw === 'string' ? JSON.parse(raw) : raw;
16181
+ const arr = data.instances || data;
16182
+ if (!Array.isArray(arr))
16183
+ return [];
16184
+ return arr.map((json) => jsonToModelInstance(this, perspective, json, include, properties));
16185
+ }
16186
+ // instancesFromQueryResult — removed (superseded by Rust executeModelQuery pipeline)
16187
+ /**
16188
+ * Execute a model query via the executor-side endpoint.
16189
+ *
16190
+ * This replaces the old SPARQL-build → hydrate → JS-filter → JS-sort → JS-paginate pipeline
16191
+ * with a single RPC to the executor that handles everything in Rust.
16192
+ *
16193
+ * @internal
16194
+ */
16195
+ static async executeModelQuery(perspective, query = {}, classNameOverride) {
16196
+ // Delegate query input building to the shared prepareModelQueryParams
16197
+ // helper. The executor resolves the shape from SHACL server-side.
16198
+ const { className, queryJson } = this.prepareModelQueryParams(query, classNameOverride);
16199
+ const result = await perspective.modelQuery(className, queryJson);
16279
16200
  // Convert JSON instances to model class instances, recursively constructing
16280
16201
  // class instances for any included relations resolved by Rust.
16281
16202
  const instances = result.instances.map((json) => {
16282
16203
  return jsonToModelInstance(this, perspective, json, query.include, query.properties);
16283
16204
  });
16284
- // Resolve non-literal expressions (e.g. file languages where the stored
16285
- // value is a content-addressed hash that must be fetched from the language
16286
- // runtime). The Rust endpoint may return either a raw target URI (string)
16287
- // or an already-resolved FileData object — both cases are handled here.
16288
- await this.resolveNonLiteralProps(perspective, instances);
16289
- // Take snapshots for dirty tracking
16290
- const snapshotRelations = queryInput.include;
16205
+ // Take snapshots for dirty tracking (exclude $-prefixed projection keys)
16206
+ const snapshotRelations = query.include
16207
+ ? Object.fromEntries(Object.entries(query.include).filter(([k]) => !k.startsWith('$')))
16208
+ : undefined;
16291
16209
  for (const inst of instances) {
16292
- inst.takeSnapshot(snapshotRelations);
16210
+ inst.takeSnapshot(snapshotRelations && Object.keys(snapshotRelations).length > 0 ? snapshotRelations : undefined);
16293
16211
  }
16294
16212
  return {
16295
16213
  results: instances,
@@ -16301,15 +16219,14 @@ class Ad4mModel {
16301
16219
  *
16302
16220
  * @param perspective - The perspective to search in
16303
16221
  * @param query - Optional query parameters to filter results
16304
- * @param useSPARQL - Whether to use SPARQL (default: true, 10-100x faster) or Prolog (legacy)
16222
+ * @param _engine - **Deprecated.** Accepted for backward compatibility but ignored.
16223
+ * All queries now use the Rust SPARQL pipeline.
16305
16224
  * @returns Array of matching models
16306
16225
  *
16307
16226
  * @example
16308
16227
  * ```typescript
16309
- * // Get all recipes (uses SPARQL by default)
16310
16228
  * const allRecipes = await Recipe.findAll(perspective);
16311
16229
  *
16312
- * // Get recipes with specific criteria (uses SPARQL)
16313
16230
  * const recipes = await Recipe.findAll(perspective, {
16314
16231
  * where: {
16315
16232
  * name: "Pasta",
@@ -16318,16 +16235,14 @@ class Ad4mModel {
16318
16235
  * order: { createdAt: "DESC" },
16319
16236
  * limit: 10
16320
16237
  * });
16321
- *
16322
- * // Explicitly use Prolog (legacy, for backward compatibility)
16323
- * const recipesProlog = await Recipe.findAll(perspective, {}, false);
16324
16238
  * ```
16325
16239
  */
16326
- static async findAll(perspective, query = {}, _engine) {
16327
- if (query.properties && query.properties.length === 0) {
16240
+ static async findAll(perspective, query) {
16241
+ const q = (query ?? {});
16242
+ if (q.properties && q.properties.length === 0) {
16328
16243
  throw new Error("properties[] must not be empty — omit the field to return all properties, or specify at least one field name");
16329
16244
  }
16330
- const { results } = await this.executeModelQuery(perspective, query);
16245
+ const { results } = await this.executeModelQuery(perspective, q);
16331
16246
  return results;
16332
16247
  }
16333
16248
  /**
@@ -16337,7 +16252,7 @@ class Ad4mModel {
16337
16252
  *
16338
16253
  * @param perspective - The perspective to search in
16339
16254
  * @param query - Optional query parameters to filter results
16340
- * @param useSPARQL - Whether to use SPARQL (default: true) or Prolog (legacy)
16255
+ * @param _engine - **Deprecated.** Accepted for backward compatibility but ignored.
16341
16256
  * @returns The first matching instance, or `null`
16342
16257
  *
16343
16258
  * @example
@@ -16350,8 +16265,8 @@ class Ad4mModel {
16350
16265
  * }
16351
16266
  * ```
16352
16267
  */
16353
- static async findOne(perspective, query = {}, _engine) {
16354
- const limitedQuery = { ...query, limit: 1 };
16268
+ static async findOne(perspective, query) {
16269
+ const limitedQuery = { ...(query ?? {}), limit: 1 };
16355
16270
  const results = await this.findAll(perspective, limitedQuery);
16356
16271
  return results[0] ?? null;
16357
16272
  }
@@ -16360,7 +16275,7 @@ class Ad4mModel {
16360
16275
  *
16361
16276
  * @param perspective - The perspective to search in
16362
16277
  * @param query - Optional query parameters to filter results
16363
- * @param useSPARQL - Whether to use SPARQL (default: true, 10-100x faster) or Prolog (legacy)
16278
+ * @param _engine - **Deprecated.** Accepted for backward compatibility but ignored.
16364
16279
  * @returns Object containing results array and total count
16365
16280
  *
16366
16281
  * @example
@@ -16370,13 +16285,11 @@ class Ad4mModel {
16370
16285
  * limit: 10
16371
16286
  * });
16372
16287
  * console.log(`Showing 10 of ${totalCount} dessert recipes`);
16373
- *
16374
- * // Use Prolog explicitly (legacy)
16375
- * const { results, totalCount } = await Recipe.findAllAndCount(perspective, {}, false);
16376
16288
  * ```
16377
16289
  */
16378
- static async findAllAndCount(perspective, query = {}, _engine) {
16379
- return await this.executeModelQuery(perspective, query);
16290
+ static async findAllAndCount(perspective, query) {
16291
+ const out = await this.executeModelQuery(perspective, (query ?? {}));
16292
+ return out;
16380
16293
  }
16381
16294
  /**
16382
16295
  * Helper function for pagination with explicit page size and number.
@@ -16395,10 +16308,10 @@ class Ad4mModel {
16395
16308
  * console.log(`Page ${page.pageNumber} of recipes, ${page.results.length} items`);
16396
16309
  * ```
16397
16310
  */
16398
- static async paginate(perspective, pageSize, pageNumber, query, _engine) {
16399
- const paginationQuery = { ...(query || {}), limit: pageSize, offset: pageSize * (pageNumber - 1), count: true };
16311
+ static async paginate(perspective, pageSize, pageNumber, query) {
16312
+ const paginationQuery = { ...(query ?? {}), limit: pageSize, offset: pageSize * (pageNumber - 1), count: true };
16400
16313
  const { results, totalCount } = await this.executeModelQuery(perspective, paginationQuery);
16401
- return { results, totalCount, pageSize, pageNumber };
16314
+ return { results: results, totalCount, pageSize, pageNumber };
16402
16315
  }
16403
16316
  /**
16404
16317
  * Generates a SPARQL COUNT query for the model.
@@ -16425,8 +16338,8 @@ class Ad4mModel {
16425
16338
  * });
16426
16339
  * ```
16427
16340
  */
16428
- static async count(perspective, query = {}) {
16429
- const { totalCount } = await this.executeModelQuery(perspective, { ...query, limit: 0 });
16341
+ static async count(perspective, query) {
16342
+ const { totalCount } = await this.executeModelQuery(perspective, { ...(query ?? {}), limit: 0 });
16430
16343
  return totalCount;
16431
16344
  }
16432
16345
  async setProperty(key, value, batchId) {
@@ -16737,27 +16650,10 @@ class Ad4mModel {
16737
16650
  if (instances.length === 0)
16738
16651
  return;
16739
16652
  const metadata = this.getModelMetadata();
16740
- // Pre-compute conformance getters so the shape sent to Rust includes them
16741
- const allRelMeta = getRelationsMetadata(this);
16742
- for (const [relName, relMeta] of Object.entries(metadata.relations)) {
16743
- const rel = relMeta;
16744
- if (rel.getter || rel.direction === 'reverse' || rel.filter === false)
16745
- continue;
16746
- const meta = allRelMeta[relName];
16747
- if (!meta?.target)
16748
- continue;
16749
- try {
16750
- const TargetClass = meta.target();
16751
- const filter = buildConformanceFilter(meta.predicate, TargetClass);
16752
- if (filter)
16753
- rel.getter = filter.getter;
16754
- }
16755
- catch (_) { /* target class may not be available */ }
16756
- }
16757
- const shapeJson = JSON.stringify(metadata);
16758
16653
  const instanceIds = instances.map(inst => inst.id || inst._baseExpression);
16759
- // Single RPC call evaluates all getters in-process on the executor
16760
- const result = await perspective.evaluateGetters(metadata.className, instanceIds, shapeJson, propertyNames);
16654
+ // The executor reads getter SPARQL from the perspective's SHACL triples
16655
+ // (written by `addSdna`), so no shape JSON is shipped with the call.
16656
+ const result = await perspective.evaluateGetters(metadata.className, instanceIds, propertyNames);
16761
16657
  // Determine which property names were evaluated for snapshot sync
16762
16658
  const evaluatedPropertyNames = [];
16763
16659
  for (const [propName, propMeta] of Object.entries(metadata.properties)) {
@@ -17048,6 +16944,22 @@ class Ad4mModel {
17048
16944
  static async register(perspective) {
17049
16945
  await perspective.ensureSDNASubjectClass(this);
17050
16946
  }
16947
+ /**
16948
+ * Batch-registers multiple model classes on a perspective in a single RPC call.
16949
+ * This is significantly faster than calling `register()` on each model individually
16950
+ * because it eliminates N-1 round-trips and mutex acquisitions.
16951
+ *
16952
+ * @param perspective - The perspective to register the models on
16953
+ * @param models - Array of Ad4mModel subclasses to register
16954
+ *
16955
+ * @example
16956
+ * ```typescript
16957
+ * await Ad4mModel.registerAll(perspective, [Community, Channel, Message, Task]);
16958
+ * ```
16959
+ */
16960
+ static async registerAll(perspective, models) {
16961
+ await perspective.ensureSubjectClasses(models);
16962
+ }
17051
16963
  /**
17052
16964
  * Executes a set of model operations inside a single batch (transaction).
17053
16965
  *
@@ -17105,7 +17017,7 @@ class Ad4mModel {
17105
17017
  * ```
17106
17018
  */
17107
17019
  static query(perspective, query) {
17108
- return new ModelQueryBuilder(perspective, this, query);
17020
+ return new ModelQueryBuilder(perspective, this, (query ?? {}));
17109
17021
  }
17110
17022
  /**
17111
17023
  * Creates an Ad4mModel class from a JSON Schema definition.
@@ -17292,7 +17204,7 @@ var _Ad4mClient_baseUrl, _Ad4mClient_token, _Ad4mClient_apiClient, _Ad4mClient_a
17292
17204
  * for the respective functionality.
17293
17205
  */
17294
17206
  class Ad4mClient {
17295
- constructor(baseUrl, token, subscribe = true) {
17207
+ constructor(baseUrl, token, subscribe = true, options) {
17296
17208
  _Ad4mClient_baseUrl.set(this, void 0);
17297
17209
  _Ad4mClient_token.set(this, void 0);
17298
17210
  _Ad4mClient_apiClient.set(this, void 0);
@@ -17305,7 +17217,7 @@ class Ad4mClient {
17305
17217
  _Ad4mClient_aiClient.set(this, void 0);
17306
17218
  __classPrivateFieldSet$1(this, _Ad4mClient_baseUrl, baseUrl, "f");
17307
17219
  __classPrivateFieldSet$1(this, _Ad4mClient_token, token, "f");
17308
- __classPrivateFieldSet$1(this, _Ad4mClient_apiClient, new ApiClient(baseUrl, token), "f");
17220
+ __classPrivateFieldSet$1(this, _Ad4mClient_apiClient, new ApiClient(baseUrl, token, options?.webSocketImpl, options?.fetchImpl), "f");
17309
17221
  __classPrivateFieldSet$1(this, _Ad4mClient_agentClient, new AgentClient(baseUrl, token, subscribe, __classPrivateFieldGet$1(this, _Ad4mClient_apiClient, "f")), "f");
17310
17222
  __classPrivateFieldSet$1(this, _Ad4mClient_expressionClient, new ExpressionClient(baseUrl, token, __classPrivateFieldGet$1(this, _Ad4mClient_apiClient, "f")), "f");
17311
17223
  __classPrivateFieldSet$1(this, _Ad4mClient_languageClient, new LanguageClient(baseUrl, token, __classPrivateFieldGet$1(this, _Ad4mClient_apiClient, "f")), "f");
@@ -17514,6 +17426,71 @@ class PerspectiveHandle {
17514
17426
  }
17515
17427
  }
17516
17428
 
17429
+ /**
17430
+ * SPARQL binding helpers — typed shapes and parsers for `querySparql<T>()`.
17431
+ *
17432
+ * AD4M stores non-string property values as URL-encoded `Literal` payloads
17433
+ * (see {@link Literal}). When raw SPARQL queries pull these values out of the
17434
+ * RDF store the bindings are still in encoded form; consumers must decode
17435
+ * before use. The helpers here centralise that decode step so each call site
17436
+ * can pick the variant matching its declared binding type.
17437
+ *
17438
+ * @example
17439
+ * ```ts
17440
+ * interface MessageBinding {
17441
+ * id: string;
17442
+ * timestamp: string; // raw literal — decode with parseLitNumber
17443
+ * body?: string; // raw literal — decode with parseLit
17444
+ * }
17445
+ * const rows = await perspective.querySparql<MessageBinding[]>(query);
17446
+ * const ts = parseLitNumber(rows[0].timestamp); // number
17447
+ * const body = rows[0].body ? parseLit(rows[0].body) : '';
17448
+ * ```
17449
+ */
17450
+ /** Sum a SPARQL COUNT(?x) result down to a plain number (returns 0 on empty). */
17451
+ function parseSparqlCount(result) {
17452
+ if (!result || result.length === 0)
17453
+ return 0;
17454
+ const raw = result[0].count;
17455
+ const n = parseInt(raw, 10);
17456
+ return Number.isNaN(n) ? 0 : n;
17457
+ }
17458
+ /**
17459
+ * Decode a `Literal`-encoded SPARQL binding back to a plain string.
17460
+ *
17461
+ * Mirrors Flux's local `parseLit` helper. Returns `''` for `undefined`/empty
17462
+ * input. Falls through to the raw value if decoding fails (defensive — the
17463
+ * binding may already be a plain string for unwrapped properties).
17464
+ */
17465
+ function parseLit(val) {
17466
+ if (val === undefined || val === null || val === '')
17467
+ return '';
17468
+ try {
17469
+ const result = Literal.fromUrl(val).get();
17470
+ if (result && typeof result === 'object') {
17471
+ return result.data ?? JSON.stringify(result);
17472
+ }
17473
+ return String(result);
17474
+ }
17475
+ catch {
17476
+ return val;
17477
+ }
17478
+ }
17479
+ /** Decode a `Literal`-encoded binding to a number. Returns 0 on empty/invalid input. */
17480
+ function parseLitNumber(val) {
17481
+ if (val === undefined || val === null || val === '')
17482
+ return 0;
17483
+ const decoded = parseLit(val);
17484
+ const n = Number(decoded);
17485
+ return Number.isNaN(n) ? 0 : n;
17486
+ }
17487
+ /** Decode a `Literal`-encoded binding to a boolean. Returns false on empty input. */
17488
+ function parseLitBoolean(val) {
17489
+ if (val === undefined || val === null || val === '')
17490
+ return false;
17491
+ return parseLit(val) === 'true';
17492
+ }
17493
+
17517
17494
  /**
17518
17495
  * WakerSubscriptionManager — manages live query subscriptions for the waker.
17519
17496
  *
@@ -17613,10 +17590,11 @@ class WakerSubscriptionManager {
17613
17590
  const parentQuery = `SELECT ?source WHERE { ?source <ad4m://has_child> <${msgAddr}> . }`;
17614
17591
  this.logger.info(`[waker] ${sub.id}: resolving parents for ${msgAddr}`);
17615
17592
  const parentResult = await this.perspectiveClient.querySparql(sub.perspective, parentQuery);
17616
- if (Array.isArray(parentResult)) {
17617
- for (const link of parentResult) {
17618
- if (link && link.source) {
17619
- parents.push(link.source);
17593
+ const bindings = parentResult?.results?.bindings;
17594
+ if (Array.isArray(bindings)) {
17595
+ for (const binding of bindings) {
17596
+ if (binding?.source?.value) {
17597
+ parents.push(binding.source.value);
17620
17598
  }
17621
17599
  }
17622
17600
  }
@@ -17799,6 +17777,195 @@ function isIncludeProjection(val) {
17799
17777
  return typeof val === 'object' && val !== null && 'from' in val;
17800
17778
  }
17801
17779
 
17780
+ /**
17781
+ * Shared query compilation utilities.
17782
+ *
17783
+ * These functions are used by both the runtime query builder (`Ad4mModel`) and
17784
+ * the compile-time SHACL generator (`decorators.ts`).
17785
+ *
17786
+ * All output uses native SPARQL syntax.
17787
+ */
17788
+ /**
17789
+ * Format a JavaScript value for embedding in a query expression.
17790
+ *
17791
+ * - Strings are single-quoted with backslash / quote / newline escaping
17792
+ * - Numbers and booleans are passed through as-is
17793
+ * - Arrays are recursed
17794
+ */
17795
+ function formatQueryValue(value) {
17796
+ if (typeof value === 'string') {
17797
+ // Escape backslashes first, then single quotes and other special characters
17798
+ const escaped = value
17799
+ .replace(/\\/g, '\\\\') // Backslash -> \\
17800
+ .replace(/'/g, "\\'") // Single quote -> \'
17801
+ .replace(/"/g, '\\"') // Double quote -> \"
17802
+ .replace(/\n/g, '\\n') // Newline -> \n
17803
+ .replace(/\r/g, '\\r') // Carriage return -> \r
17804
+ .replace(/\t/g, '\\t'); // Tab -> \t
17805
+ return `'${escaped}'`;
17806
+ }
17807
+ else if (typeof value === 'number' || typeof value === 'boolean') {
17808
+ return String(value);
17809
+ }
17810
+ else if (Array.isArray(value)) {
17811
+ return `[${value.map(v => formatQueryValue(v)).join(', ')}]`;
17812
+ }
17813
+ else {
17814
+ return String(value);
17815
+ }
17816
+ }
17817
+ /**
17818
+ * Compile a single Where condition for a property into a SPARQL triple pattern
17819
+ * that can be embedded in a getter's WHERE clause.
17820
+ *
17821
+ * The generated pattern operates on `?target` — e.g.:
17822
+ * `?target <pred> <value> .`
17823
+ * `FILTER EXISTS { ?target <pred> ?_v0 }`
17824
+ *
17825
+ * @param predicate - The predicate URI for the property
17826
+ * @param condition - The Where condition value
17827
+ * @param opts - Optional settings (e.g. `resolveLanguage`)
17828
+ * @returns A single SPARQL condition string
17829
+ */
17830
+ function buildWhereCondition(predicate, condition, opts) {
17831
+ const escapedPredicate = escapeQueryString(predicate);
17832
+ // For literal-resolved properties, we match against the raw IRI (which is a literal: URI)
17833
+ // For language-resolved properties, we match against the plain URI
17834
+ // For literal-resolved properties, values are stored as IRIs like <literal:string:VALUE>
17835
+ // For language-resolved properties, values are plain URIs
17836
+ const isLiteral = !opts?.resolveLanguage || opts.resolveLanguage === 'literal';
17837
+ const varSuffix = opts?.varIndex ?? 0;
17838
+ function formatValue(v) {
17839
+ if (typeof v === 'string') {
17840
+ return isLiteral
17841
+ ? `<literal:string:${escapeQueryString(v)}>`
17842
+ : `<${escapeQueryString(v)}>`;
17843
+ }
17844
+ // Numbers/booleans — also stored as literal:string: in AD4M
17845
+ return `<literal:string:${v}>`;
17846
+ }
17847
+ /**
17848
+ * For literal properties, generate a FILTER-based match that handles both
17849
+ * the raw value and the literal-encoded value. This mirrors the Rust
17850
+ * `build_projection_where_patterns` approach which uses:
17851
+ * FILTER(STR(?var) = "value" || STR(?var) = "literal:string:encodedValue")
17852
+ * This is more robust than exact IRI matching because it handles edge cases
17853
+ * where the stored format might vary.
17854
+ */
17855
+ function formatLiteralFilter(varName, v) {
17856
+ const raw = escapeQueryString(String(v));
17857
+ const encoded = encodeURIComponent(String(v))
17858
+ .replace(/!/g, '%21')
17859
+ .replace(/'/g, '%27')
17860
+ .replace(/\(/g, '%28')
17861
+ .replace(/\)/g, '%29')
17862
+ .replace(/\*/g, '%2A');
17863
+ if (typeof v === 'string') {
17864
+ return `FILTER(STR(${varName}) = "${raw}" || STR(${varName}) = "literal:string:${encoded}")`;
17865
+ }
17866
+ else if (typeof v === 'number') {
17867
+ return `FILTER(STR(${varName}) = "${v}" || STR(${varName}) = "literal:number:${v}")`;
17868
+ }
17869
+ else if (typeof v === 'boolean') {
17870
+ return `FILTER(STR(${varName}) = "${v}" || STR(${varName}) = "literal:boolean:${v}")`;
17871
+ }
17872
+ return `FILTER(STR(${varName}) = "${raw}")`;
17873
+ }
17874
+ if (Array.isArray(condition)) {
17875
+ // Array values → FILTER IN
17876
+ if (isLiteral) {
17877
+ const varName = `?_wc${varSuffix}`;
17878
+ const inValues = condition.flatMap(v => {
17879
+ const raw = escapeQueryString(String(v));
17880
+ const encoded = encodeURIComponent(String(v))
17881
+ .replace(/!/g, '%21').replace(/'/g, '%27')
17882
+ .replace(/\(/g, '%28').replace(/\)/g, '%29').replace(/\*/g, '%2A');
17883
+ return [`"${raw}"`, `"literal:string:${encoded}"`];
17884
+ }).join(', ');
17885
+ return `?target <${escapedPredicate}> ${varName} . FILTER(STR(${varName}) IN (${inValues}))`;
17886
+ }
17887
+ const formattedValues = condition.map(formatValue).join(', ');
17888
+ return `FILTER EXISTS { ?target <${escapedPredicate}> ?_val . FILTER(?_val IN (${formattedValues})) }`;
17889
+ }
17890
+ else if (typeof condition === 'object' && condition !== null) {
17891
+ // Operator object
17892
+ const ops = condition;
17893
+ const parts = [];
17894
+ if (ops.not !== undefined) {
17895
+ if (Array.isArray(ops.not)) {
17896
+ const formattedValues = ops.not.map((v) => formatValue(v)).join(', ');
17897
+ // FILTER NOT EXISTS here is scoped to a specific predicate, not a global scan,
17898
+ // so O(N²) behavior is bounded by the number of values for this property.
17899
+ parts.push(`FILTER NOT EXISTS { ?target <${escapedPredicate}> ?_nval . FILTER(?_nval IN (${formattedValues})) }`);
17900
+ }
17901
+ else {
17902
+ // FILTER NOT EXISTS here is scoped to a specific predicate, not a global scan,
17903
+ // so O(N²) behavior is bounded by the number of values for this property.
17904
+ parts.push(`FILTER NOT EXISTS { ?target <${escapedPredicate}> ${formatValue(ops.not)} }`);
17905
+ }
17906
+ }
17907
+ // Comparison operators — ensure property exists
17908
+ const hasComparisonOps = ops.gt !== undefined || ops.gte !== undefined ||
17909
+ ops.lt !== undefined || ops.lte !== undefined ||
17910
+ ops.between !== undefined || ops.contains !== undefined;
17911
+ if (hasComparisonOps) {
17912
+ parts.push(`FILTER EXISTS { ?target <${escapedPredicate}> ?_cmp }`);
17913
+ }
17914
+ return parts.join(' ');
17915
+ }
17916
+ else {
17917
+ // Simple equality
17918
+ if (isLiteral) {
17919
+ // Use FILTER matching (mirrors Rust build_projection_where_patterns)
17920
+ // to handle both raw values and literal-encoded IRIs robustly.
17921
+ const varName = `?_wc${varSuffix}`;
17922
+ return `?target <${escapedPredicate}> ${varName} . ${formatLiteralFilter(varName, condition)}`;
17923
+ }
17924
+ return `?target <${escapedPredicate}> ${formatValue(condition)} .`;
17925
+ }
17926
+ }
17927
+ /**
17928
+ * Compile a full `Where` clause to an array of SPARQL condition strings.
17929
+ *
17930
+ * When `metadata` is provided, property names are resolved to predicates
17931
+ * using the model's property metadata. When `metadata` is `null`, property
17932
+ * names are treated as raw predicate URIs.
17933
+ *
17934
+ * Only handles **regular properties** — special fields (`id`, `author`,
17935
+ * `timestamp`) and relation fields are skipped (they are only relevant at
17936
+ * runtime query time, not for compile-time getter generation).
17937
+ */
17938
+ function compileWhereClause(where, metadata) {
17939
+ const conditions = [];
17940
+ for (const [propertyName, condition] of Object.entries(where)) {
17941
+ // Skip special fields that don't apply at compile time
17942
+ if (['id', 'author', 'timestamp'].includes(propertyName))
17943
+ continue;
17944
+ let predicate;
17945
+ let resolveLanguage;
17946
+ if (metadata) {
17947
+ const propMeta = metadata.properties[propertyName];
17948
+ if (propMeta) {
17949
+ predicate = propMeta.predicate;
17950
+ resolveLanguage = propMeta.resolveLanguage;
17951
+ }
17952
+ else {
17953
+ // Property not found in metadata — treat name as raw predicate URI
17954
+ predicate = propertyName;
17955
+ }
17956
+ }
17957
+ else {
17958
+ // No metadata — treat name as raw predicate URI
17959
+ predicate = propertyName;
17960
+ }
17961
+ const cond = buildWhereCondition(predicate, condition, { resolveLanguage, varIndex: conditions.length });
17962
+ if (cond) {
17963
+ conditions.push(cond);
17964
+ }
17965
+ }
17966
+ return conditions;
17967
+ }
17968
+
17802
17969
  class Neighbourhood {
17803
17970
  constructor(linkLanguage, meta) {
17804
17971
  this.linkLanguage = linkLanguage;
@@ -17831,4 +17998,110 @@ class ModelInput {
17831
17998
  class VoiceActivityParamsInput {
17832
17999
  }
17833
18000
 
17834
- export { AIClient, Model as AIModel, AIModelLoadingStatus, AIPromptExamples, AIPromptExamplesInput, AITask, AITaskInput, Ad4mClient, Ad4mModel, Agent, AgentClient, AgentExpression, AgentSignature, AgentStatus, Apps, AuthInfo, AuthInfoInput, BelongsToMany, BelongsToOne, Capability, CapabilityInput, ComputeLogEntry, EntanglementProof, EntanglementProofInput, ExceptionInfo, ExceptionType, Expression, ExpressionGeneric, ExpressionGenericInput, ExpressionProof, ExpressionProofInput, ExpressionRef, ExpressionRendered, Flag, HasMany, HasOne, HostingUserInfo, IDBCache, Icon, ImportResult, ImportStats, InteractionCall, InteractionMeta, InteractionParameter, LanguageExpression, LanguageHandle, LanguageLanguageInput, LanguageMeta, LanguageMetaInput, LanguageMetaInternal, LanguageRef, Link, LinkExpression, LinkExpressionInput, LinkExpressionMutations, LinkExpressionUpdated, LinkInput, LinkMutations, LinkQuery, Literal, LocalModel, LocalModelInput, Model$1 as Model, ModelApi, ModelApiInput, ModelInput, ModelQueryBuilder, Neighbourhood, NeighbourhoodExpression, NeighbourhoodProxy, Notification, NotificationInput, NullCache, OnlineAgent, Optional, PaymentRequestResult, Perspective, PerspectiveDiff, PerspectiveDiffExpression, PerspectiveExpression, PerspectiveHandle, PerspectiveInput, PerspectiveProxy, PerspectiveState, PerspectiveUnsignedInput, Property, QuerySubscriptionProxy, ReadOnly, Resource, ResourceInput, RpcError as RestError, RpcError, RuntimeInfo, SHACLFlow, SHACLShape, SMART_LITERAL_CONTENT_PREDICATE, SentMessage, SmartLiteral, TokenizerSource, TokenizerSourceInput, TriggeredNotification, UserCreationResult, UserStatistics, VerificationRequestResult, VoiceActivityParamsInput, WakerSubscriptionManager, buildConformanceFilter, buildModelFromJSONSchema, buildPaginationSubquery, buildSDNA, buildSHACL, buildSPARQLOrderLimitOffset, buildSPARQLQuery, buildWhereCondition, capSentence, clearQueryCache, compileWhereClause, createPersistentCache, determineNamespace, determinePredicate, escapeQueryString, exprRef2String, formatList, formatQueryValue, formatSPARQLValue, getCachedResult, getDefaultValueForType, getMemoizedSHACL, getPropertiesMetadata, getPropertyOption, getRelationsMetadata, hasJsOnlyWhereFilters, invalidatePerspectiveCache, isArrayType, isExpression, isIncludeProjection, isLink, isNumericType, isObjectType, isSchemaType, linkEqual, normalizeNamespaceString, normalizeSchemaType, normalizeValue, parseExprUrl, queryCacheSize, resolveParentPredicate, setCachedResult, setPropertyRegistryEntry, setRelationRegistryEntry, typeDefsString };
18001
+ /**
18002
+ * Builder functions for SHACL-AF Node Expressions.
18003
+ *
18004
+ * These functions construct JSON-serializable expression trees for property transforms.
18005
+ * All builders return frozen objects to prevent accidental mutation.
18006
+ */
18007
+ /**
18008
+ * Identity expression: pass the focus node through unchanged.
18009
+ */
18010
+ function focus() {
18011
+ return Object.freeze({ type: 'focus' });
18012
+ }
18013
+ /**
18014
+ * Literal constant expression.
18015
+ */
18016
+ function literal(value) {
18017
+ return Object.freeze({ type: 'literal', value });
18018
+ }
18019
+ /**
18020
+ * Path expression: navigate to a property on the resolved object.
18021
+ * The predicate can be a full IRI (e.g., "file_storage://data_base64")
18022
+ * or a simple property name. The Rust evaluator will strip the namespace.
18023
+ */
18024
+ function path(predicate) {
18025
+ return Object.freeze({ type: 'path', predicate });
18026
+ }
18027
+ /**
18028
+ * Existence check: returns true if the inner expression is non-null and non-empty.
18029
+ */
18030
+ function exists(expr) {
18031
+ return Object.freeze({ type: 'exists', expr });
18032
+ }
18033
+ /**
18034
+ * Conditional expression with optional else branch.
18035
+ * Returns a chainable builder that supports `.then()` and `.else()`.
18036
+ */
18037
+ function ifExpr(cond) {
18038
+ return {
18039
+ then: (thenExpr) => ({
18040
+ else: (elseExpr) => {
18041
+ return Object.freeze({
18042
+ type: 'if',
18043
+ cond,
18044
+ then: thenExpr,
18045
+ ...(elseExpr !== undefined && { else: elseExpr }),
18046
+ });
18047
+ },
18048
+ // Allow chaining without explicit else()
18049
+ toExpression: () => Object.freeze({
18050
+ type: 'if',
18051
+ cond,
18052
+ then: thenExpr,
18053
+ }),
18054
+ }),
18055
+ };
18056
+ }
18057
+ /**
18058
+ * String concatenation: joins evaluated arguments as strings.
18059
+ * Null/undefined arguments are skipped.
18060
+ */
18061
+ function concat(...args) {
18062
+ return Object.freeze({ type: 'concat', args });
18063
+ }
18064
+ /**
18065
+ * Coalesce: returns the first non-null evaluated argument.
18066
+ */
18067
+ function coalesce(...args) {
18068
+ return Object.freeze({ type: 'coalesce', args });
18069
+ }
18070
+ /**
18071
+ * Function call: invoke a named transform function by IRI.
18072
+ * Primarily used for built-in functions like "ad4m://fn/defaultFileDecode".
18073
+ */
18074
+ function fn(iri, args = []) {
18075
+ return Object.freeze({ type: 'function', iri, args });
18076
+ }
18077
+
18078
+ /**
18079
+ * SHACL-AF Transform DSL — public API
18080
+ *
18081
+ * Re-exports builder functions and provides common built-in transforms.
18082
+ */
18083
+ /**
18084
+ * Built-in transform: FileData → data: URI
18085
+ *
18086
+ * Converts a file stored via FILE_STORAGE_LANGUAGE into a data: URL.
18087
+ * If the object has a `data_base64` field, returns:
18088
+ * `data:{file_type};base64,{data_base64}`
18089
+ * Otherwise passes through the input unchanged.
18090
+ *
18091
+ * This is the Rust equivalent of the JS `defaultFileDecode` function.
18092
+ *
18093
+ * Usage:
18094
+ * ```typescript
18095
+ * @Property({
18096
+ * through: 'we://image',
18097
+ * resolveLanguage: FILE_STORAGE_LANGUAGE,
18098
+ * transform: fileToDataUri,
18099
+ * })
18100
+ * avatar?: string;
18101
+ * ```
18102
+ */
18103
+ const fileToDataUri = ifExpr(exists(path('file_storage://data_base64')))
18104
+ .then(concat(literal('data:'), coalesce(path('file_storage://file_type'), literal('image/png')), literal(';base64,'), path('file_storage://data_base64')))
18105
+ .else(focus());
18106
+
18107
+ export { AIClient, Model as AIModel, AIModelLoadingStatus, AIPromptExamples, AIPromptExamplesInput, AITask, AITaskInput, Ad4mClient, Ad4mModel, Agent, AgentClient, AgentExpression, AgentSignature, AgentStatus, Apps, AuthInfo, AuthInfoInput, BelongsToMany, BelongsToOne, Capability, CapabilityInput, ComputeLogEntry, EntanglementProof, EntanglementProofInput, ExceptionInfo, ExceptionType, Expression, ExpressionGeneric, ExpressionGenericInput, ExpressionProof, ExpressionProofInput, ExpressionRef, ExpressionRendered, Flag, HasMany, HasOne, HostingUserInfo, IDBCache, Icon, ImportResult, ImportStats, InteractionCall, InteractionMeta, InteractionParameter, LanguageExpression, LanguageHandle, LanguageLanguageInput, LanguageMeta, LanguageMetaInput, LanguageMetaInternal, LanguageRef, Link, LinkExpression, LinkExpressionInput, LinkExpressionMutations, LinkExpressionUpdated, LinkInput, LinkMutations, LinkQuery, Literal, LocalModel, LocalModelInput, Model$1 as Model, ModelApi, ModelApiInput, ModelInput, ModelQueryBuilder, Neighbourhood, NeighbourhoodExpression, NeighbourhoodProxy, Notification, NotificationInput, NullCache, OnlineAgent, Optional, PaymentRequestResult, Perspective, PerspectiveDiff, PerspectiveDiffExpression, PerspectiveExpression, PerspectiveHandle, PerspectiveInput, PerspectiveProxy, PerspectiveState, PerspectiveUnsignedInput, Property, QuerySubscriptionProxy, ReadOnly, Resource, ResourceInput, RpcError as RestError, RpcError, RuntimeInfo, SHACLFlow, SHACLShape, SMART_LITERAL_CONTENT_PREDICATE, SentMessage, SmartLiteral, TokenizerSource, TokenizerSourceInput, TriggeredNotification, UserCreationResult, UserStatistics, VerificationRequestResult, VoiceActivityParamsInput, WakerSubscriptionManager, buildConformanceFilter, buildModelFromJSONSchema, buildPaginationSubquery, buildSDNA, buildSHACL, buildSPARQLQuery, buildWhereCondition, capSentence, clearQueryCache, coalesce, compileWhereClause, concat, createPersistentCache, determineNamespace, determinePredicate, escapeQueryString, exists, exprRef2String, fileToDataUri, fn, focus, formatList, formatQueryValue, formatSPARQLValue, getCachedResult, getDefaultValueForType, getMemoizedSHACL, getPropertiesMetadata, getPropertyOption, getRelationsMetadata, hasJsOnlyWhereFilters, ifExpr, invalidatePerspectiveCache, isArrayType, isExpression, isIncludeProjection, isLink, isNodeExpression, isNumericType, isObjectType, isSchemaType, linkEqual, literal, normalizeNamespaceString, normalizeSchemaType, normalizeValue, parseExprUrl, parseLit, parseLitBoolean, parseLitNumber, parseSparqlCount, path, queryCacheSize, resolveParentPredicate, setCachedResult, setPropertyRegistryEntry, setRelationRegistryEntry, typeDefsString };