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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (72) hide show
  1. package/lib/index.cjs +1507 -1372
  2. package/lib/index.js +1505 -1370
  3. package/lib/src/Ad4mClient.d.ts +1 -1
  4. package/lib/src/Ad4mClient.js +12 -1
  5. package/lib/src/agent/AgentClient.d.ts +16 -0
  6. package/lib/src/agent/AgentClient.js +74 -4
  7. package/lib/src/cache/PersistentCache.d.ts +40 -0
  8. package/lib/src/cache/PersistentCache.js +139 -0
  9. package/lib/src/expression/ExpressionClient.d.ts +8 -0
  10. package/lib/src/expression/ExpressionClient.js +113 -5
  11. package/lib/src/index.d.ts +1 -0
  12. package/lib/src/index.js +1 -0
  13. package/lib/src/model/Ad4mModel.d.ts +20 -7
  14. package/lib/src/model/Ad4mModel.js +102 -108
  15. package/lib/src/model/Ad4mModel.test.js +688 -1434
  16. package/lib/src/model/ModelQueryBuilder.d.ts +6 -6
  17. package/lib/src/model/ModelQueryBuilder.js +29 -20
  18. package/lib/src/model/Subject.js +6 -6
  19. package/lib/src/model/hydration.d.ts +2 -39
  20. package/lib/src/model/hydration.js +2 -260
  21. package/lib/src/model/query-surreal.d.ts +44 -0
  22. package/lib/src/model/query-surreal.js +249 -0
  23. package/lib/src/model/query-utils.d.ts +1 -0
  24. package/lib/src/model/query-utils.js +46 -1
  25. package/lib/src/model/relation-filtering.test.js +15 -15
  26. package/lib/src/model/surreal-utils.d.ts +42 -0
  27. package/lib/src/model/surreal-utils.js +128 -0
  28. package/lib/src/model/types.d.ts +4 -6
  29. package/lib/src/perspectives/PerspectiveClient.d.ts +1 -1
  30. package/lib/src/perspectives/PerspectiveClient.js +15 -13
  31. package/lib/src/perspectives/PerspectiveProxy.d.ts +14 -0
  32. package/lib/src/perspectives/PerspectiveProxy.js +16 -3
  33. package/lib/src/perspectives/PerspectiveResolver.d.ts +1 -0
  34. package/lib/src/perspectives/PerspectiveResolver.js +11 -0
  35. package/lib/src/runtime/RuntimeResolver.d.ts +1 -28
  36. package/lib/src/runtime/RuntimeResolver.js +4 -197
  37. package/lib/src/schema.gql +1 -27
  38. package/lib/src/shacl/SHACLShape.test.js +0 -82
  39. package/package.json +11 -8
  40. package/src/Ad4mClient.test.ts +14 -4
  41. package/src/Ad4mClient.ts +12 -1
  42. package/src/agent/AgentClient.ts +84 -2
  43. package/src/cache/PersistentCache.ts +145 -0
  44. package/src/cache/cache.test.ts +713 -0
  45. package/src/expression/ExpressionClient.ts +137 -3
  46. package/src/index.ts +1 -0
  47. package/src/model/Ad4mModel.test.ts +59 -358
  48. package/src/model/Ad4mModel.ts +112 -108
  49. package/src/model/ModelQueryBuilder.ts +29 -17
  50. package/src/model/hydration.ts +2 -279
  51. package/src/model/query-utils.ts +47 -2
  52. package/src/model/types.ts +5 -6
  53. package/src/perspectives/PerspectiveClient.ts +26 -17
  54. package/src/perspectives/PerspectiveProxy.ts +24 -3
  55. package/lib/src/model/hydration-batch.d.ts +0 -34
  56. package/lib/src/model/hydration-batch.js +0 -147
  57. package/lib/src/model/hydration-batching.test.d.ts +0 -7
  58. package/lib/src/model/hydration-batching.test.js +0 -456
  59. package/lib/src/model/model-manifest.d.ts +0 -41
  60. package/lib/src/model/model-manifest.js +0 -11
  61. package/lib/src/model/query-cache.test.d.ts +0 -1
  62. package/lib/src/model/query-cache.test.js +0 -43
  63. package/lib/src/model/query-sparql-batch.d.ts +0 -17
  64. package/lib/src/model/query-sparql-batch.js +0 -260
  65. package/lib/src/model/query-sparql.test.d.ts +0 -1
  66. package/lib/src/model/query-sparql.test.js +0 -312
  67. package/lib/src/model/subscription-delta.test.d.ts +0 -24
  68. package/lib/src/model/subscription-delta.test.js +0 -180
  69. package/lib/src/model/subscription-pool.d.ts +0 -39
  70. package/lib/src/model/subscription-pool.js +0 -165
  71. package/lib/src/perspectives/PerspectiveClient.test.d.ts +0 -1
  72. package/lib/src/perspectives/PerspectiveClient.test.js +0 -224
package/lib/index.cjs CHANGED
@@ -555,13 +555,13 @@ class AgentStatus {
555
555
  }
556
556
  }
557
557
 
558
- var __classPrivateFieldSet$b = (undefined && undefined.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {
558
+ var __classPrivateFieldSet$c = (undefined && undefined.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {
559
559
  if (kind === "m") throw new TypeError("Private method is not writable");
560
560
  if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
561
561
  if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
562
562
  return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
563
563
  };
564
- var __classPrivateFieldGet$b = (undefined && undefined.__classPrivateFieldGet) || function (receiver, state, kind, f) {
564
+ var __classPrivateFieldGet$c = (undefined && undefined.__classPrivateFieldGet) || function (receiver, state, kind, f) {
565
565
  if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
566
566
  if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
567
567
  return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
@@ -571,41 +571,41 @@ class NeighbourhoodProxy {
571
571
  constructor(client, pID) {
572
572
  _NeighbourhoodProxy_client.set(this, void 0);
573
573
  _NeighbourhoodProxy_pID.set(this, void 0);
574
- __classPrivateFieldSet$b(this, _NeighbourhoodProxy_client, client, "f");
575
- __classPrivateFieldSet$b(this, _NeighbourhoodProxy_pID, pID, "f");
574
+ __classPrivateFieldSet$c(this, _NeighbourhoodProxy_client, client, "f");
575
+ __classPrivateFieldSet$c(this, _NeighbourhoodProxy_pID, pID, "f");
576
576
  }
577
577
  async otherAgents() {
578
- return await __classPrivateFieldGet$b(this, _NeighbourhoodProxy_client, "f").otherAgents(__classPrivateFieldGet$b(this, _NeighbourhoodProxy_pID, "f"));
578
+ return await __classPrivateFieldGet$c(this, _NeighbourhoodProxy_client, "f").otherAgents(__classPrivateFieldGet$c(this, _NeighbourhoodProxy_pID, "f"));
579
579
  }
580
580
  async hasTelepresenceAdapter() {
581
- return await __classPrivateFieldGet$b(this, _NeighbourhoodProxy_client, "f").hasTelepresenceAdapter(__classPrivateFieldGet$b(this, _NeighbourhoodProxy_pID, "f"));
581
+ return await __classPrivateFieldGet$c(this, _NeighbourhoodProxy_client, "f").hasTelepresenceAdapter(__classPrivateFieldGet$c(this, _NeighbourhoodProxy_pID, "f"));
582
582
  }
583
583
  async onlineAgents() {
584
- return await __classPrivateFieldGet$b(this, _NeighbourhoodProxy_client, "f").onlineAgents(__classPrivateFieldGet$b(this, _NeighbourhoodProxy_pID, "f"));
584
+ return await __classPrivateFieldGet$c(this, _NeighbourhoodProxy_client, "f").onlineAgents(__classPrivateFieldGet$c(this, _NeighbourhoodProxy_pID, "f"));
585
585
  }
586
586
  async setOnlineStatus(status) {
587
- return await __classPrivateFieldGet$b(this, _NeighbourhoodProxy_client, "f").setOnlineStatus(__classPrivateFieldGet$b(this, _NeighbourhoodProxy_pID, "f"), status);
587
+ return await __classPrivateFieldGet$c(this, _NeighbourhoodProxy_client, "f").setOnlineStatus(__classPrivateFieldGet$c(this, _NeighbourhoodProxy_pID, "f"), status);
588
588
  }
589
589
  async setOnlineStatusU(status) {
590
- return await __classPrivateFieldGet$b(this, _NeighbourhoodProxy_client, "f").setOnlineStatusU(__classPrivateFieldGet$b(this, _NeighbourhoodProxy_pID, "f"), status);
590
+ return await __classPrivateFieldGet$c(this, _NeighbourhoodProxy_client, "f").setOnlineStatusU(__classPrivateFieldGet$c(this, _NeighbourhoodProxy_pID, "f"), status);
591
591
  }
592
592
  async sendSignal(remoteAgentDid, payload) {
593
- return await __classPrivateFieldGet$b(this, _NeighbourhoodProxy_client, "f").sendSignal(__classPrivateFieldGet$b(this, _NeighbourhoodProxy_pID, "f"), remoteAgentDid, payload);
593
+ return await __classPrivateFieldGet$c(this, _NeighbourhoodProxy_client, "f").sendSignal(__classPrivateFieldGet$c(this, _NeighbourhoodProxy_pID, "f"), remoteAgentDid, payload);
594
594
  }
595
595
  async sendSignalU(remoteAgentDid, payload) {
596
- return await __classPrivateFieldGet$b(this, _NeighbourhoodProxy_client, "f").sendSignalU(__classPrivateFieldGet$b(this, _NeighbourhoodProxy_pID, "f"), remoteAgentDid, payload);
596
+ return await __classPrivateFieldGet$c(this, _NeighbourhoodProxy_client, "f").sendSignalU(__classPrivateFieldGet$c(this, _NeighbourhoodProxy_pID, "f"), remoteAgentDid, payload);
597
597
  }
598
598
  async sendBroadcast(payload, loopback = false) {
599
- return await __classPrivateFieldGet$b(this, _NeighbourhoodProxy_client, "f").sendBroadcast(__classPrivateFieldGet$b(this, _NeighbourhoodProxy_pID, "f"), payload, loopback);
599
+ return await __classPrivateFieldGet$c(this, _NeighbourhoodProxy_client, "f").sendBroadcast(__classPrivateFieldGet$c(this, _NeighbourhoodProxy_pID, "f"), payload, loopback);
600
600
  }
601
601
  async sendBroadcastU(payload, loopback = false) {
602
- return await __classPrivateFieldGet$b(this, _NeighbourhoodProxy_client, "f").sendBroadcastU(__classPrivateFieldGet$b(this, _NeighbourhoodProxy_pID, "f"), payload, loopback);
602
+ return await __classPrivateFieldGet$c(this, _NeighbourhoodProxy_client, "f").sendBroadcastU(__classPrivateFieldGet$c(this, _NeighbourhoodProxy_pID, "f"), payload, loopback);
603
603
  }
604
604
  async addSignalHandler(handler) {
605
- await __classPrivateFieldGet$b(this, _NeighbourhoodProxy_client, "f").addSignalHandler(__classPrivateFieldGet$b(this, _NeighbourhoodProxy_pID, "f"), handler);
605
+ await __classPrivateFieldGet$c(this, _NeighbourhoodProxy_client, "f").addSignalHandler(__classPrivateFieldGet$c(this, _NeighbourhoodProxy_pID, "f"), handler);
606
606
  }
607
607
  removeSignalHandler(handler) {
608
- __classPrivateFieldGet$b(this, _NeighbourhoodProxy_client, "f").removeSignalHandler(__classPrivateFieldGet$b(this, _NeighbourhoodProxy_pID, "f"), handler);
608
+ __classPrivateFieldGet$c(this, _NeighbourhoodProxy_client, "f").removeSignalHandler(__classPrivateFieldGet$c(this, _NeighbourhoodProxy_pID, "f"), handler);
609
609
  }
610
610
  }
611
611
  _NeighbourhoodProxy_client = new WeakMap(), _NeighbourhoodProxy_pID = new WeakMap();
@@ -699,13 +699,13 @@ class LinkQuery {
699
699
  }
700
700
  }
701
701
 
702
- var __classPrivateFieldSet$a = (undefined && undefined.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {
702
+ var __classPrivateFieldSet$b = (undefined && undefined.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {
703
703
  if (kind === "m") throw new TypeError("Private method is not writable");
704
704
  if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
705
705
  if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
706
706
  return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
707
707
  };
708
- var __classPrivateFieldGet$a = (undefined && undefined.__classPrivateFieldGet) || function (receiver, state, kind, f) {
708
+ var __classPrivateFieldGet$b = (undefined && undefined.__classPrivateFieldGet) || function (receiver, state, kind, f) {
709
709
  if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
710
710
  if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
711
711
  return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
@@ -726,44 +726,44 @@ class Literal {
726
726
  if (url.startsWith("literal://"))
727
727
  throw new Error("literal:// format is no longer supported. Use literal: instead.");
728
728
  const l = new Literal();
729
- __classPrivateFieldSet$a(l, _Literal_url, url, "f");
729
+ __classPrivateFieldSet$b(l, _Literal_url, url, "f");
730
730
  return l;
731
731
  }
732
732
  static from(literal) {
733
733
  const l = new Literal();
734
- __classPrivateFieldSet$a(l, _Literal_literal, literal, "f");
734
+ __classPrivateFieldSet$b(l, _Literal_literal, literal, "f");
735
735
  return l;
736
736
  }
737
737
  toUrl() {
738
- if (__classPrivateFieldGet$a(this, _Literal_url, "f") && !__classPrivateFieldGet$a(this, _Literal_literal, "f"))
739
- return __classPrivateFieldGet$a(this, _Literal_url, "f");
740
- if (!__classPrivateFieldGet$a(this, _Literal_url, "f") && (__classPrivateFieldGet$a(this, _Literal_literal, "f") === undefined || __classPrivateFieldGet$a(this, _Literal_literal, "f") === "" || __classPrivateFieldGet$a(this, _Literal_literal, "f") === null))
738
+ if (__classPrivateFieldGet$b(this, _Literal_url, "f") && !__classPrivateFieldGet$b(this, _Literal_literal, "f"))
739
+ return __classPrivateFieldGet$b(this, _Literal_url, "f");
740
+ if (!__classPrivateFieldGet$b(this, _Literal_url, "f") && (__classPrivateFieldGet$b(this, _Literal_literal, "f") === undefined || __classPrivateFieldGet$b(this, _Literal_literal, "f") === "" || __classPrivateFieldGet$b(this, _Literal_literal, "f") === null))
741
741
  throw new Error("Can't turn empty Literal into URL");
742
742
  let encoded;
743
- switch (typeof __classPrivateFieldGet$a(this, _Literal_literal, "f")) {
743
+ switch (typeof __classPrivateFieldGet$b(this, _Literal_literal, "f")) {
744
744
  case 'string':
745
- encoded = `string:${encodeRFC3986URIComponent(__classPrivateFieldGet$a(this, _Literal_literal, "f"))}`;
745
+ encoded = `string:${encodeRFC3986URIComponent(__classPrivateFieldGet$b(this, _Literal_literal, "f"))}`;
746
746
  break;
747
747
  case 'number':
748
- encoded = `number:${encodeRFC3986URIComponent(__classPrivateFieldGet$a(this, _Literal_literal, "f"))}`;
748
+ encoded = `number:${encodeRFC3986URIComponent(__classPrivateFieldGet$b(this, _Literal_literal, "f"))}`;
749
749
  break;
750
750
  case 'boolean':
751
- encoded = `boolean:${encodeRFC3986URIComponent(__classPrivateFieldGet$a(this, _Literal_literal, "f"))}`;
751
+ encoded = `boolean:${encodeRFC3986URIComponent(__classPrivateFieldGet$b(this, _Literal_literal, "f"))}`;
752
752
  break;
753
753
  case 'object':
754
- encoded = `json:${encodeRFC3986URIComponent(JSON.stringify(__classPrivateFieldGet$a(this, _Literal_literal, "f")))}`;
754
+ encoded = `json:${encodeRFC3986URIComponent(JSON.stringify(__classPrivateFieldGet$b(this, _Literal_literal, "f")))}`;
755
755
  break;
756
756
  }
757
757
  return `literal:${encoded}`;
758
758
  }
759
759
  get() {
760
- if (__classPrivateFieldGet$a(this, _Literal_literal, "f"))
761
- return __classPrivateFieldGet$a(this, _Literal_literal, "f");
762
- if (!__classPrivateFieldGet$a(this, _Literal_url, "f"))
760
+ if (__classPrivateFieldGet$b(this, _Literal_literal, "f"))
761
+ return __classPrivateFieldGet$b(this, _Literal_literal, "f");
762
+ if (!__classPrivateFieldGet$b(this, _Literal_url, "f"))
763
763
  throw new Error("Can't render empty Literal");
764
- if (!__classPrivateFieldGet$a(this, _Literal_url, "f").startsWith("literal:"))
764
+ if (!__classPrivateFieldGet$b(this, _Literal_url, "f").startsWith("literal:"))
765
765
  throw new Error("Can't render Literal from non-literal URL");
766
- const body = __classPrivateFieldGet$a(this, _Literal_url, "f").substring(8);
766
+ const body = __classPrivateFieldGet$b(this, _Literal_url, "f").substring(8);
767
767
  if (body.startsWith("string:")) {
768
768
  return decodeURIComponent(body.substring(7));
769
769
  }
@@ -1719,6 +1719,7 @@ function buildWhereCondition(predicate, condition, opts) {
1719
1719
  // For literal-resolved properties, values are stored as IRIs like <literal:string:VALUE>
1720
1720
  // For language-resolved properties, values are plain URIs
1721
1721
  const isLiteral = !opts?.resolveLanguage || opts.resolveLanguage === 'literal';
1722
+ const varSuffix = opts?.varIndex ?? 0;
1722
1723
  function formatValue(v) {
1723
1724
  if (typeof v === 'string') {
1724
1725
  return isLiteral
@@ -1728,8 +1729,46 @@ function buildWhereCondition(predicate, condition, opts) {
1728
1729
  // Numbers/booleans — also stored as literal:string: in AD4M
1729
1730
  return `<literal:string:${v}>`;
1730
1731
  }
1732
+ /**
1733
+ * For literal properties, generate a FILTER-based match that handles both
1734
+ * the raw value and the literal-encoded value. This mirrors the Rust
1735
+ * `build_projection_where_patterns` approach which uses:
1736
+ * FILTER(STR(?var) = "value" || STR(?var) = "literal:string:encodedValue")
1737
+ * This is more robust than exact IRI matching because it handles edge cases
1738
+ * where the stored format might vary.
1739
+ */
1740
+ function formatLiteralFilter(varName, v) {
1741
+ const raw = escapeQueryString(String(v));
1742
+ const encoded = encodeURIComponent(String(v))
1743
+ .replace(/!/g, '%21')
1744
+ .replace(/'/g, '%27')
1745
+ .replace(/\(/g, '%28')
1746
+ .replace(/\)/g, '%29')
1747
+ .replace(/\*/g, '%2A');
1748
+ if (typeof v === 'string') {
1749
+ return `FILTER(STR(${varName}) = "${raw}" || STR(${varName}) = "literal:string:${encoded}")`;
1750
+ }
1751
+ else if (typeof v === 'number') {
1752
+ return `FILTER(STR(${varName}) = "${v}" || STR(${varName}) = "literal:number:${v}")`;
1753
+ }
1754
+ else if (typeof v === 'boolean') {
1755
+ return `FILTER(STR(${varName}) = "${v}" || STR(${varName}) = "literal:boolean:${v}")`;
1756
+ }
1757
+ return `FILTER(STR(${varName}) = "${raw}")`;
1758
+ }
1731
1759
  if (Array.isArray(condition)) {
1732
1760
  // Array values → FILTER IN
1761
+ if (isLiteral) {
1762
+ const varName = `?_wc${varSuffix}`;
1763
+ const inValues = condition.flatMap(v => {
1764
+ const raw = escapeQueryString(String(v));
1765
+ const encoded = encodeURIComponent(String(v))
1766
+ .replace(/!/g, '%21').replace(/'/g, '%27')
1767
+ .replace(/\(/g, '%28').replace(/\)/g, '%29').replace(/\*/g, '%2A');
1768
+ return [`"${raw}"`, `"literal:string:${encoded}"`];
1769
+ }).join(', ');
1770
+ return `?target <${escapedPredicate}> ${varName} . FILTER(STR(${varName}) IN (${inValues}))`;
1771
+ }
1733
1772
  const formattedValues = condition.map(formatValue).join(', ');
1734
1773
  return `FILTER EXISTS { ?target <${escapedPredicate}> ?_val . FILTER(?_val IN (${formattedValues})) }`;
1735
1774
  }
@@ -1761,6 +1800,12 @@ function buildWhereCondition(predicate, condition, opts) {
1761
1800
  }
1762
1801
  else {
1763
1802
  // Simple equality
1803
+ if (isLiteral) {
1804
+ // Use FILTER matching (mirrors Rust build_projection_where_patterns)
1805
+ // to handle both raw values and literal-encoded IRIs robustly.
1806
+ const varName = `?_wc${varSuffix}`;
1807
+ return `?target <${escapedPredicate}> ${varName} . ${formatLiteralFilter(varName, condition)}`;
1808
+ }
1764
1809
  return `?target <${escapedPredicate}> ${formatValue(condition)} .`;
1765
1810
  }
1766
1811
  }
@@ -1798,7 +1843,7 @@ function compileWhereClause(where, metadata) {
1798
1843
  // No metadata — treat name as raw predicate URI
1799
1844
  predicate = propertyName;
1800
1845
  }
1801
- const cond = buildWhereCondition(predicate, condition, { resolveLanguage });
1846
+ const cond = buildWhereCondition(predicate, condition, { resolveLanguage, varIndex: conditions.length });
1802
1847
  if (cond) {
1803
1848
  conditions.push(cond);
1804
1849
  }
@@ -3165,13 +3210,13 @@ class SHACLFlow {
3165
3210
  }
3166
3211
  }
3167
3212
 
3168
- var __classPrivateFieldSet$9 = (undefined && undefined.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {
3213
+ var __classPrivateFieldSet$a = (undefined && undefined.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {
3169
3214
  if (kind === "m") throw new TypeError("Private method is not writable");
3170
3215
  if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
3171
3216
  if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
3172
3217
  return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
3173
3218
  };
3174
- var __classPrivateFieldGet$9 = (undefined && undefined.__classPrivateFieldGet) || function (receiver, state, kind, f) {
3219
+ var __classPrivateFieldGet$a = (undefined && undefined.__classPrivateFieldGet) || function (receiver, state, kind, f) {
3175
3220
  if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
3176
3221
  if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
3177
3222
  return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
@@ -3244,56 +3289,56 @@ class QuerySubscriptionProxy {
3244
3289
  _QuerySubscriptionProxy_initReject.set(this, void 0);
3245
3290
  _QuerySubscriptionProxy_initTimeoutId.set(this, void 0);
3246
3291
  _QuerySubscriptionProxy_query.set(this, void 0);
3247
- __classPrivateFieldSet$9(this, _QuerySubscriptionProxy_uuid, uuid, "f");
3248
- __classPrivateFieldSet$9(this, _QuerySubscriptionProxy_query, query, "f");
3249
- __classPrivateFieldSet$9(this, _QuerySubscriptionProxy_client, client, "f");
3250
- __classPrivateFieldSet$9(this, _QuerySubscriptionProxy_callbacks, new Set(), "f");
3251
- __classPrivateFieldSet$9(this, _QuerySubscriptionProxy_latestResult, null, "f");
3292
+ __classPrivateFieldSet$a(this, _QuerySubscriptionProxy_uuid, uuid, "f");
3293
+ __classPrivateFieldSet$a(this, _QuerySubscriptionProxy_query, query, "f");
3294
+ __classPrivateFieldSet$a(this, _QuerySubscriptionProxy_client, client, "f");
3295
+ __classPrivateFieldSet$a(this, _QuerySubscriptionProxy_callbacks, new Set(), "f");
3296
+ __classPrivateFieldSet$a(this, _QuerySubscriptionProxy_latestResult, null, "f");
3252
3297
  // Create the promise once and store its resolve/reject
3253
- __classPrivateFieldSet$9(this, _QuerySubscriptionProxy_initialized, new Promise((resolve, reject) => {
3254
- __classPrivateFieldSet$9(this, _QuerySubscriptionProxy_initResolve, resolve, "f");
3255
- __classPrivateFieldSet$9(this, _QuerySubscriptionProxy_initReject, reject, "f");
3298
+ __classPrivateFieldSet$a(this, _QuerySubscriptionProxy_initialized, new Promise((resolve, reject) => {
3299
+ __classPrivateFieldSet$a(this, _QuerySubscriptionProxy_initResolve, resolve, "f");
3300
+ __classPrivateFieldSet$a(this, _QuerySubscriptionProxy_initReject, reject, "f");
3256
3301
  }), "f");
3257
3302
  }
3258
3303
  async subscribe() {
3259
3304
  // Clean up previous subscription attempt if retrying
3260
- if (__classPrivateFieldGet$9(this, _QuerySubscriptionProxy_unsubscribe, "f")) {
3261
- __classPrivateFieldGet$9(this, _QuerySubscriptionProxy_unsubscribe, "f").call(this);
3262
- __classPrivateFieldSet$9(this, _QuerySubscriptionProxy_unsubscribe, undefined, "f");
3305
+ if (__classPrivateFieldGet$a(this, _QuerySubscriptionProxy_unsubscribe, "f")) {
3306
+ __classPrivateFieldGet$a(this, _QuerySubscriptionProxy_unsubscribe, "f").call(this);
3307
+ __classPrivateFieldSet$a(this, _QuerySubscriptionProxy_unsubscribe, undefined, "f");
3263
3308
  }
3264
3309
  // Clear any existing timeout
3265
- if (__classPrivateFieldGet$9(this, _QuerySubscriptionProxy_initTimeoutId, "f")) {
3266
- clearTimeout(__classPrivateFieldGet$9(this, _QuerySubscriptionProxy_initTimeoutId, "f"));
3267
- __classPrivateFieldSet$9(this, _QuerySubscriptionProxy_initTimeoutId, undefined, "f");
3310
+ if (__classPrivateFieldGet$a(this, _QuerySubscriptionProxy_initTimeoutId, "f")) {
3311
+ clearTimeout(__classPrivateFieldGet$a(this, _QuerySubscriptionProxy_initTimeoutId, "f"));
3312
+ __classPrivateFieldSet$a(this, _QuerySubscriptionProxy_initTimeoutId, undefined, "f");
3268
3313
  }
3269
3314
  // Clear any existing keepalive timer to prevent accumulation
3270
- if (__classPrivateFieldGet$9(this, _QuerySubscriptionProxy_keepaliveTimer, "f")) {
3271
- clearTimeout(__classPrivateFieldGet$9(this, _QuerySubscriptionProxy_keepaliveTimer, "f"));
3272
- __classPrivateFieldSet$9(this, _QuerySubscriptionProxy_keepaliveTimer, undefined, "f");
3315
+ if (__classPrivateFieldGet$a(this, _QuerySubscriptionProxy_keepaliveTimer, "f")) {
3316
+ clearTimeout(__classPrivateFieldGet$a(this, _QuerySubscriptionProxy_keepaliveTimer, "f"));
3317
+ __classPrivateFieldSet$a(this, _QuerySubscriptionProxy_keepaliveTimer, undefined, "f");
3273
3318
  }
3274
3319
  try {
3275
3320
  // Initialize the query subscription
3276
3321
  let initialResult;
3277
- initialResult = await __classPrivateFieldGet$9(this, _QuerySubscriptionProxy_client, "f").subscribeQuery(__classPrivateFieldGet$9(this, _QuerySubscriptionProxy_uuid, "f"), __classPrivateFieldGet$9(this, _QuerySubscriptionProxy_query, "f"));
3278
- __classPrivateFieldSet$9(this, _QuerySubscriptionProxy_subscriptionId, initialResult.subscriptionId, "f");
3322
+ initialResult = await __classPrivateFieldGet$a(this, _QuerySubscriptionProxy_client, "f").subscribeQuery(__classPrivateFieldGet$a(this, _QuerySubscriptionProxy_uuid, "f"), __classPrivateFieldGet$a(this, _QuerySubscriptionProxy_query, "f"));
3323
+ __classPrivateFieldSet$a(this, _QuerySubscriptionProxy_subscriptionId, initialResult.subscriptionId, "f");
3279
3324
  // Process the initial result immediately for fast UX.
3280
3325
  // The subscribeQuery() RPC call already returns the initial result,
3281
3326
  // so treat that as successful initialization instead of waiting for a
3282
3327
  // follow-up WebSocket update that may never arrive until the query changes.
3283
3328
  if (initialResult.result !== undefined) {
3284
- __classPrivateFieldSet$9(this, _QuerySubscriptionProxy_latestResult, initialResult.result, "f");
3285
- __classPrivateFieldGet$9(this, _QuerySubscriptionProxy_instances, "m", _QuerySubscriptionProxy_notifyCallbacks).call(this, initialResult.result);
3286
- if (__classPrivateFieldGet$9(this, _QuerySubscriptionProxy_initResolve, "f")) {
3287
- __classPrivateFieldGet$9(this, _QuerySubscriptionProxy_initResolve, "f").call(this, true);
3288
- __classPrivateFieldSet$9(this, _QuerySubscriptionProxy_initResolve, undefined, "f");
3289
- __classPrivateFieldSet$9(this, _QuerySubscriptionProxy_initReject, undefined, "f");
3329
+ __classPrivateFieldSet$a(this, _QuerySubscriptionProxy_latestResult, initialResult.result, "f");
3330
+ __classPrivateFieldGet$a(this, _QuerySubscriptionProxy_instances, "m", _QuerySubscriptionProxy_notifyCallbacks).call(this, initialResult.result);
3331
+ if (__classPrivateFieldGet$a(this, _QuerySubscriptionProxy_initResolve, "f")) {
3332
+ __classPrivateFieldGet$a(this, _QuerySubscriptionProxy_initResolve, "f").call(this, true);
3333
+ __classPrivateFieldSet$a(this, _QuerySubscriptionProxy_initResolve, undefined, "f");
3334
+ __classPrivateFieldSet$a(this, _QuerySubscriptionProxy_initReject, undefined, "f");
3290
3335
  }
3291
3336
  }
3292
3337
  else {
3293
3338
  console.warn('⚠️ No initial result returned from subscribeQuery!');
3294
3339
  // Only keep the initialization timeout when the backend did not
3295
3340
  // provide an initial result up front.
3296
- __classPrivateFieldSet$9(this, _QuerySubscriptionProxy_initTimeoutId, setTimeout(() => {
3341
+ __classPrivateFieldSet$a(this, _QuerySubscriptionProxy_initTimeoutId, setTimeout(() => {
3297
3342
  console.error('Subscription initialization timed out after 30 seconds. Resubscribing...');
3298
3343
  // Recursively retry subscription, catching any errors
3299
3344
  this.subscribe().catch(error => {
@@ -3302,46 +3347,43 @@ class QuerySubscriptionProxy {
3302
3347
  }, 30000), "f");
3303
3348
  }
3304
3349
  // Subscribe to query updates
3305
- __classPrivateFieldSet$9(this, _QuerySubscriptionProxy_unsubscribe, __classPrivateFieldGet$9(this, _QuerySubscriptionProxy_client, "f").subscribeToQueryUpdates(__classPrivateFieldGet$9(this, _QuerySubscriptionProxy_subscriptionId, "f"), (updateResult) => {
3350
+ __classPrivateFieldSet$a(this, _QuerySubscriptionProxy_unsubscribe, __classPrivateFieldGet$a(this, _QuerySubscriptionProxy_client, "f").subscribeToQueryUpdates(__classPrivateFieldGet$a(this, _QuerySubscriptionProxy_subscriptionId, "f"), (updateResult) => {
3306
3351
  // Clear timeout on first message
3307
- if (__classPrivateFieldGet$9(this, _QuerySubscriptionProxy_initTimeoutId, "f")) {
3308
- clearTimeout(__classPrivateFieldGet$9(this, _QuerySubscriptionProxy_initTimeoutId, "f"));
3309
- __classPrivateFieldSet$9(this, _QuerySubscriptionProxy_initTimeoutId, undefined, "f");
3352
+ if (__classPrivateFieldGet$a(this, _QuerySubscriptionProxy_initTimeoutId, "f")) {
3353
+ clearTimeout(__classPrivateFieldGet$a(this, _QuerySubscriptionProxy_initTimeoutId, "f"));
3354
+ __classPrivateFieldSet$a(this, _QuerySubscriptionProxy_initTimeoutId, undefined, "f");
3310
3355
  }
3311
3356
  // Resolve the initialization promise (only resolves once)
3312
- if (__classPrivateFieldGet$9(this, _QuerySubscriptionProxy_initResolve, "f")) {
3313
- __classPrivateFieldGet$9(this, _QuerySubscriptionProxy_initResolve, "f").call(this, true);
3314
- __classPrivateFieldSet$9(this, _QuerySubscriptionProxy_initResolve, undefined, "f"); // Prevent double-resolve
3315
- __classPrivateFieldSet$9(this, _QuerySubscriptionProxy_initReject, undefined, "f");
3357
+ if (__classPrivateFieldGet$a(this, _QuerySubscriptionProxy_initResolve, "f")) {
3358
+ __classPrivateFieldGet$a(this, _QuerySubscriptionProxy_initResolve, "f").call(this, true);
3359
+ __classPrivateFieldSet$a(this, _QuerySubscriptionProxy_initResolve, undefined, "f"); // Prevent double-resolve
3360
+ __classPrivateFieldSet$a(this, _QuerySubscriptionProxy_initReject, undefined, "f");
3316
3361
  }
3317
- // Skip duplicate init messages
3318
- if (updateResult.isInit && __classPrivateFieldGet$9(this, _QuerySubscriptionProxy_latestResult, "f"))
3319
- return;
3320
- __classPrivateFieldSet$9(this, _QuerySubscriptionProxy_latestResult, updateResult, "f");
3321
- __classPrivateFieldGet$9(this, _QuerySubscriptionProxy_instances, "m", _QuerySubscriptionProxy_notifyCallbacks).call(this, updateResult);
3362
+ __classPrivateFieldSet$a(this, _QuerySubscriptionProxy_latestResult, updateResult, "f");
3363
+ __classPrivateFieldGet$a(this, _QuerySubscriptionProxy_instances, "m", _QuerySubscriptionProxy_notifyCallbacks).call(this, updateResult);
3322
3364
  }), "f");
3323
3365
  }
3324
3366
  catch (error) {
3325
3367
  console.error('Error setting up subscription:', error);
3326
3368
  // Reject the promise if this is the first attempt
3327
- if (__classPrivateFieldGet$9(this, _QuerySubscriptionProxy_initReject, "f")) {
3328
- __classPrivateFieldGet$9(this, _QuerySubscriptionProxy_initReject, "f").call(this, error);
3329
- __classPrivateFieldSet$9(this, _QuerySubscriptionProxy_initResolve, undefined, "f");
3330
- __classPrivateFieldSet$9(this, _QuerySubscriptionProxy_initReject, undefined, "f");
3369
+ if (__classPrivateFieldGet$a(this, _QuerySubscriptionProxy_initReject, "f")) {
3370
+ __classPrivateFieldGet$a(this, _QuerySubscriptionProxy_initReject, "f").call(this, error);
3371
+ __classPrivateFieldSet$a(this, _QuerySubscriptionProxy_initResolve, undefined, "f");
3372
+ __classPrivateFieldSet$a(this, _QuerySubscriptionProxy_initReject, undefined, "f");
3331
3373
  }
3332
3374
  throw error; // Re-throw so caller knows it failed
3333
3375
  }
3334
3376
  // Start keepalive loop using platform-agnostic setTimeout
3335
3377
  const keepaliveLoop = async () => {
3336
- if (__classPrivateFieldGet$9(this, _QuerySubscriptionProxy_disposed, "f"))
3378
+ if (__classPrivateFieldGet$a(this, _QuerySubscriptionProxy_disposed, "f"))
3337
3379
  return;
3338
3380
  try {
3339
- await __classPrivateFieldGet$9(this, _QuerySubscriptionProxy_client, "f").keepAliveQuery(__classPrivateFieldGet$9(this, _QuerySubscriptionProxy_uuid, "f"), __classPrivateFieldGet$9(this, _QuerySubscriptionProxy_subscriptionId, "f"));
3381
+ await __classPrivateFieldGet$a(this, _QuerySubscriptionProxy_client, "f").keepAliveQuery(__classPrivateFieldGet$a(this, _QuerySubscriptionProxy_uuid, "f"), __classPrivateFieldGet$a(this, _QuerySubscriptionProxy_subscriptionId, "f"));
3340
3382
  }
3341
3383
  catch (e) {
3342
3384
  console.error('Error in keepalive:', e);
3343
3385
  // try to reinitialize the subscription
3344
- console.log('Reinitializing subscription for query:', __classPrivateFieldGet$9(this, _QuerySubscriptionProxy_query, "f"));
3386
+ console.log('Reinitializing subscription for query:', __classPrivateFieldGet$a(this, _QuerySubscriptionProxy_query, "f"));
3345
3387
  try {
3346
3388
  await this.subscribe();
3347
3389
  console.log('Subscription reinitialized');
@@ -3353,12 +3395,12 @@ class QuerySubscriptionProxy {
3353
3395
  }
3354
3396
  }
3355
3397
  // Schedule next keepalive if not disposed
3356
- if (!__classPrivateFieldGet$9(this, _QuerySubscriptionProxy_disposed, "f")) {
3357
- __classPrivateFieldSet$9(this, _QuerySubscriptionProxy_keepaliveTimer, setTimeout(keepaliveLoop, 30000), "f");
3398
+ if (!__classPrivateFieldGet$a(this, _QuerySubscriptionProxy_disposed, "f")) {
3399
+ __classPrivateFieldSet$a(this, _QuerySubscriptionProxy_keepaliveTimer, setTimeout(keepaliveLoop, 30000), "f");
3358
3400
  }
3359
3401
  };
3360
3402
  // Start the first keepalive loop
3361
- __classPrivateFieldSet$9(this, _QuerySubscriptionProxy_keepaliveTimer, setTimeout(keepaliveLoop, 30000), "f");
3403
+ __classPrivateFieldSet$a(this, _QuerySubscriptionProxy_keepaliveTimer, setTimeout(keepaliveLoop, 30000), "f");
3362
3404
  }
3363
3405
  /** Get the subscription ID for this query subscription
3364
3406
  *
@@ -3369,7 +3411,7 @@ class QuerySubscriptionProxy {
3369
3411
  * @returns The subscription ID string
3370
3412
  */
3371
3413
  get id() {
3372
- return __classPrivateFieldGet$9(this, _QuerySubscriptionProxy_subscriptionId, "f");
3414
+ return __classPrivateFieldGet$a(this, _QuerySubscriptionProxy_subscriptionId, "f");
3373
3415
  }
3374
3416
  /** Promise that resolves when the subscription has received its first result
3375
3417
  * through the subscription channel. This ensures the subscription is fully
@@ -3383,7 +3425,7 @@ class QuerySubscriptionProxy {
3383
3425
  * creation methods (like subscribeInfer) already wait for initialization.
3384
3426
  */
3385
3427
  get initialized() {
3386
- return __classPrivateFieldGet$9(this, _QuerySubscriptionProxy_initialized, "f");
3428
+ return __classPrivateFieldGet$a(this, _QuerySubscriptionProxy_initialized, "f");
3387
3429
  }
3388
3430
  /** Get the latest query result
3389
3431
  *
@@ -3394,7 +3436,7 @@ class QuerySubscriptionProxy {
3394
3436
  * @returns The latest query result as a string (usually a JSON array of bindings)
3395
3437
  */
3396
3438
  get result() {
3397
- return __classPrivateFieldGet$9(this, _QuerySubscriptionProxy_latestResult, "f");
3439
+ return __classPrivateFieldGet$a(this, _QuerySubscriptionProxy_latestResult, "f");
3398
3440
  }
3399
3441
  /** Add a callback that will be called whenever new results arrive
3400
3442
  *
@@ -3416,8 +3458,8 @@ class QuerySubscriptionProxy {
3416
3458
  * ```
3417
3459
  */
3418
3460
  onResult(callback) {
3419
- __classPrivateFieldGet$9(this, _QuerySubscriptionProxy_callbacks, "f").add(callback);
3420
- return () => __classPrivateFieldGet$9(this, _QuerySubscriptionProxy_callbacks, "f").delete(callback);
3461
+ __classPrivateFieldGet$a(this, _QuerySubscriptionProxy_callbacks, "f").add(callback);
3462
+ return () => __classPrivateFieldGet$a(this, _QuerySubscriptionProxy_callbacks, "f").delete(callback);
3421
3463
  }
3422
3464
  /** Clean up the subscription and stop keepalive signals
3423
3465
  *
@@ -3431,25 +3473,25 @@ class QuerySubscriptionProxy {
3431
3473
  * will not receive any more updates. The instance should be discarded.
3432
3474
  */
3433
3475
  dispose() {
3434
- __classPrivateFieldSet$9(this, _QuerySubscriptionProxy_disposed, true, "f");
3435
- clearTimeout(__classPrivateFieldGet$9(this, _QuerySubscriptionProxy_keepaliveTimer, "f"));
3436
- if (__classPrivateFieldGet$9(this, _QuerySubscriptionProxy_unsubscribe, "f")) {
3437
- __classPrivateFieldGet$9(this, _QuerySubscriptionProxy_unsubscribe, "f").call(this);
3476
+ __classPrivateFieldSet$a(this, _QuerySubscriptionProxy_disposed, true, "f");
3477
+ clearTimeout(__classPrivateFieldGet$a(this, _QuerySubscriptionProxy_keepaliveTimer, "f"));
3478
+ if (__classPrivateFieldGet$a(this, _QuerySubscriptionProxy_unsubscribe, "f")) {
3479
+ __classPrivateFieldGet$a(this, _QuerySubscriptionProxy_unsubscribe, "f").call(this);
3438
3480
  }
3439
- __classPrivateFieldGet$9(this, _QuerySubscriptionProxy_callbacks, "f").clear();
3440
- if (__classPrivateFieldGet$9(this, _QuerySubscriptionProxy_initTimeoutId, "f")) {
3441
- clearTimeout(__classPrivateFieldGet$9(this, _QuerySubscriptionProxy_initTimeoutId, "f"));
3442
- __classPrivateFieldSet$9(this, _QuerySubscriptionProxy_initTimeoutId, undefined, "f");
3481
+ __classPrivateFieldGet$a(this, _QuerySubscriptionProxy_callbacks, "f").clear();
3482
+ if (__classPrivateFieldGet$a(this, _QuerySubscriptionProxy_initTimeoutId, "f")) {
3483
+ clearTimeout(__classPrivateFieldGet$a(this, _QuerySubscriptionProxy_initTimeoutId, "f"));
3484
+ __classPrivateFieldSet$a(this, _QuerySubscriptionProxy_initTimeoutId, undefined, "f");
3443
3485
  }
3444
3486
  // Tell the backend to dispose of the subscription
3445
- if (__classPrivateFieldGet$9(this, _QuerySubscriptionProxy_subscriptionId, "f")) {
3446
- __classPrivateFieldGet$9(this, _QuerySubscriptionProxy_client, "f").disposeQuerySubscription(__classPrivateFieldGet$9(this, _QuerySubscriptionProxy_uuid, "f"), __classPrivateFieldGet$9(this, _QuerySubscriptionProxy_subscriptionId, "f"))
3487
+ if (__classPrivateFieldGet$a(this, _QuerySubscriptionProxy_subscriptionId, "f")) {
3488
+ __classPrivateFieldGet$a(this, _QuerySubscriptionProxy_client, "f").disposeQuerySubscription(__classPrivateFieldGet$a(this, _QuerySubscriptionProxy_uuid, "f"), __classPrivateFieldGet$a(this, _QuerySubscriptionProxy_subscriptionId, "f"))
3447
3489
  .catch(e => console.error('Error disposing query subscription:', e));
3448
3490
  }
3449
3491
  }
3450
3492
  }
3451
3493
  _QuerySubscriptionProxy_uuid = new WeakMap(), _QuerySubscriptionProxy_subscriptionId = new WeakMap(), _QuerySubscriptionProxy_client = new WeakMap(), _QuerySubscriptionProxy_callbacks = new WeakMap(), _QuerySubscriptionProxy_keepaliveTimer = new WeakMap(), _QuerySubscriptionProxy_unsubscribe = new WeakMap(), _QuerySubscriptionProxy_latestResult = new WeakMap(), _QuerySubscriptionProxy_disposed = new WeakMap(), _QuerySubscriptionProxy_initialized = new WeakMap(), _QuerySubscriptionProxy_initResolve = new WeakMap(), _QuerySubscriptionProxy_initReject = new WeakMap(), _QuerySubscriptionProxy_initTimeoutId = new WeakMap(), _QuerySubscriptionProxy_query = new WeakMap(), _QuerySubscriptionProxy_instances = new WeakSet(), _QuerySubscriptionProxy_notifyCallbacks = function _QuerySubscriptionProxy_notifyCallbacks(result) {
3452
- for (const callback of __classPrivateFieldGet$9(this, _QuerySubscriptionProxy_callbacks, "f")) {
3494
+ for (const callback of __classPrivateFieldGet$a(this, _QuerySubscriptionProxy_callbacks, "f")) {
3453
3495
  try {
3454
3496
  callback(result);
3455
3497
  }
@@ -3499,7 +3541,7 @@ _QuerySubscriptionProxy_uuid = new WeakMap(), _QuerySubscriptionProxy_subscripti
3499
3541
  */
3500
3542
  class PerspectiveProxy {
3501
3543
  /** @internal Exposed for ModelQueryBuilder subscription management */
3502
- get client() { return __classPrivateFieldGet$9(this, _PerspectiveProxy_client, "f"); }
3544
+ get client() { return __classPrivateFieldGet$a(this, _PerspectiveProxy_client, "f"); }
3503
3545
  /**
3504
3546
  * Creates a new PerspectiveProxy instance.
3505
3547
  * Note: Don't create this directly, use ad4m.perspective.add() instead.
@@ -3517,31 +3559,31 @@ class PerspectiveProxy {
3517
3559
  * Note: Don't create this directly, use ad4m.perspective.add() instead.
3518
3560
  */
3519
3561
  );
3520
- __classPrivateFieldSet$9(this, _PerspectiveProxy_perspectiveLinkAddedCallbacks, [], "f");
3521
- __classPrivateFieldSet$9(this, _PerspectiveProxy_perspectiveLinkRemovedCallbacks, [], "f");
3522
- __classPrivateFieldSet$9(this, _PerspectiveProxy_perspectiveLinkUpdatedCallbacks, [], "f");
3523
- __classPrivateFieldSet$9(this, _PerspectiveProxy_perspectiveSyncStateChangeCallbacks, [], "f");
3524
- __classPrivateFieldSet$9(this, _PerspectiveProxy_handle, handle, "f");
3525
- __classPrivateFieldSet$9(this, _PerspectiveProxy_client, ad4m, "f");
3526
- this.uuid = __classPrivateFieldGet$9(this, _PerspectiveProxy_handle, "f").uuid;
3527
- this.name = __classPrivateFieldGet$9(this, _PerspectiveProxy_handle, "f").name;
3528
- this.owners = __classPrivateFieldGet$9(this, _PerspectiveProxy_handle, "f").owners;
3529
- this.sharedUrl = __classPrivateFieldGet$9(this, _PerspectiveProxy_handle, "f").sharedUrl;
3530
- this.neighbourhood = __classPrivateFieldGet$9(this, _PerspectiveProxy_handle, "f").neighbourhood;
3531
- this.state = __classPrivateFieldGet$9(this, _PerspectiveProxy_handle, "f").state;
3532
- __classPrivateFieldGet$9(this, _PerspectiveProxy_client, "f").addPerspectiveLinkAddedListener(__classPrivateFieldGet$9(this, _PerspectiveProxy_handle, "f").uuid, __classPrivateFieldGet$9(this, _PerspectiveProxy_perspectiveLinkAddedCallbacks, "f"));
3533
- __classPrivateFieldGet$9(this, _PerspectiveProxy_client, "f").addPerspectiveLinkRemovedListener(__classPrivateFieldGet$9(this, _PerspectiveProxy_handle, "f").uuid, __classPrivateFieldGet$9(this, _PerspectiveProxy_perspectiveLinkRemovedCallbacks, "f"));
3534
- __classPrivateFieldGet$9(this, _PerspectiveProxy_client, "f").addPerspectiveLinkUpdatedListener(__classPrivateFieldGet$9(this, _PerspectiveProxy_handle, "f").uuid, __classPrivateFieldGet$9(this, _PerspectiveProxy_perspectiveLinkUpdatedCallbacks, "f"));
3535
- __classPrivateFieldGet$9(this, _PerspectiveProxy_client, "f").addPerspectiveSyncStateChangeListener(__classPrivateFieldGet$9(this, _PerspectiveProxy_handle, "f").uuid, __classPrivateFieldGet$9(this, _PerspectiveProxy_perspectiveSyncStateChangeCallbacks, "f"));
3562
+ __classPrivateFieldSet$a(this, _PerspectiveProxy_perspectiveLinkAddedCallbacks, [], "f");
3563
+ __classPrivateFieldSet$a(this, _PerspectiveProxy_perspectiveLinkRemovedCallbacks, [], "f");
3564
+ __classPrivateFieldSet$a(this, _PerspectiveProxy_perspectiveLinkUpdatedCallbacks, [], "f");
3565
+ __classPrivateFieldSet$a(this, _PerspectiveProxy_perspectiveSyncStateChangeCallbacks, [], "f");
3566
+ __classPrivateFieldSet$a(this, _PerspectiveProxy_handle, handle, "f");
3567
+ __classPrivateFieldSet$a(this, _PerspectiveProxy_client, ad4m, "f");
3568
+ this.uuid = __classPrivateFieldGet$a(this, _PerspectiveProxy_handle, "f").uuid;
3569
+ this.name = __classPrivateFieldGet$a(this, _PerspectiveProxy_handle, "f").name;
3570
+ this.owners = __classPrivateFieldGet$a(this, _PerspectiveProxy_handle, "f").owners;
3571
+ this.sharedUrl = __classPrivateFieldGet$a(this, _PerspectiveProxy_handle, "f").sharedUrl;
3572
+ this.neighbourhood = __classPrivateFieldGet$a(this, _PerspectiveProxy_handle, "f").neighbourhood;
3573
+ this.state = __classPrivateFieldGet$a(this, _PerspectiveProxy_handle, "f").state;
3574
+ __classPrivateFieldGet$a(this, _PerspectiveProxy_client, "f").addPerspectiveLinkAddedListener(__classPrivateFieldGet$a(this, _PerspectiveProxy_handle, "f").uuid, __classPrivateFieldGet$a(this, _PerspectiveProxy_perspectiveLinkAddedCallbacks, "f"));
3575
+ __classPrivateFieldGet$a(this, _PerspectiveProxy_client, "f").addPerspectiveLinkRemovedListener(__classPrivateFieldGet$a(this, _PerspectiveProxy_handle, "f").uuid, __classPrivateFieldGet$a(this, _PerspectiveProxy_perspectiveLinkRemovedCallbacks, "f"));
3576
+ __classPrivateFieldGet$a(this, _PerspectiveProxy_client, "f").addPerspectiveLinkUpdatedListener(__classPrivateFieldGet$a(this, _PerspectiveProxy_handle, "f").uuid, __classPrivateFieldGet$a(this, _PerspectiveProxy_perspectiveLinkUpdatedCallbacks, "f"));
3577
+ __classPrivateFieldGet$a(this, _PerspectiveProxy_client, "f").addPerspectiveSyncStateChangeListener(__classPrivateFieldGet$a(this, _PerspectiveProxy_handle, "f").uuid, __classPrivateFieldGet$a(this, _PerspectiveProxy_perspectiveSyncStateChangeCallbacks, "f"));
3536
3578
  }
3537
3579
  /** Update the proxy's internal handle and public fields in-place.
3538
3580
  * Keeps the same object reference so all holders see the update. */
3539
3581
  updateHandle(handle) {
3540
- if (handle.uuid !== __classPrivateFieldGet$9(this, _PerspectiveProxy_handle, "f").uuid) {
3541
- throw new Error(`PerspectiveProxy.updateHandle: UUID mismatch — proxy is bound to "${__classPrivateFieldGet$9(this, _PerspectiveProxy_handle, "f").uuid}" but received handle with UUID "${handle.uuid}". ` +
3582
+ if (handle.uuid !== __classPrivateFieldGet$a(this, _PerspectiveProxy_handle, "f").uuid) {
3583
+ throw new Error(`PerspectiveProxy.updateHandle: UUID mismatch — proxy is bound to "${__classPrivateFieldGet$a(this, _PerspectiveProxy_handle, "f").uuid}" but received handle with UUID "${handle.uuid}". ` +
3542
3584
  `This would silently diverge from listeners registered under the original UUID.`);
3543
3585
  }
3544
- __classPrivateFieldSet$9(this, _PerspectiveProxy_handle, handle, "f");
3586
+ __classPrivateFieldSet$a(this, _PerspectiveProxy_handle, handle, "f");
3545
3587
  this.uuid = handle.uuid;
3546
3588
  this.name = handle.name;
3547
3589
  this.owners = handle.owners;
@@ -3622,8 +3664,8 @@ class PerspectiveProxy {
3622
3664
  * @param batchId - Optional batch ID to group this operation with others
3623
3665
  */
3624
3666
  async executeAction(actions, expression, parameters, batchId) {
3625
- const result = await __classPrivateFieldGet$9(this, _PerspectiveProxy_client, "f").executeCommands(__classPrivateFieldGet$9(this, _PerspectiveProxy_handle, "f").uuid, JSON.stringify(actions), expression, JSON.stringify(parameters), batchId);
3626
- invalidatePerspectiveCache(__classPrivateFieldGet$9(this, _PerspectiveProxy_handle, "f").uuid);
3667
+ const result = await __classPrivateFieldGet$a(this, _PerspectiveProxy_client, "f").executeCommands(__classPrivateFieldGet$a(this, _PerspectiveProxy_handle, "f").uuid, JSON.stringify(actions), expression, JSON.stringify(parameters), batchId);
3668
+ invalidatePerspectiveCache(__classPrivateFieldGet$a(this, _PerspectiveProxy_handle, "f").uuid);
3627
3669
  return result;
3628
3670
  }
3629
3671
  /**
@@ -3648,7 +3690,7 @@ class PerspectiveProxy {
3648
3690
  * ```
3649
3691
  */
3650
3692
  async get(query) {
3651
- return await __classPrivateFieldGet$9(this, _PerspectiveProxy_client, "f").queryLinks(__classPrivateFieldGet$9(this, _PerspectiveProxy_handle, "f").uuid, query);
3693
+ return await __classPrivateFieldGet$a(this, _PerspectiveProxy_client, "f").queryLinks(__classPrivateFieldGet$a(this, _PerspectiveProxy_handle, "f").uuid, query);
3652
3694
  }
3653
3695
  /**
3654
3696
  * Executes a Prolog query against the perspective's knowledge base.
@@ -3674,7 +3716,7 @@ class PerspectiveProxy {
3674
3716
  * ```
3675
3717
  */
3676
3718
  async infer(query) {
3677
- return await __classPrivateFieldGet$9(this, _PerspectiveProxy_client, "f").queryProlog(__classPrivateFieldGet$9(this, _PerspectiveProxy_handle, "f").uuid, query);
3719
+ return await __classPrivateFieldGet$a(this, _PerspectiveProxy_client, "f").queryProlog(__classPrivateFieldGet$a(this, _PerspectiveProxy_handle, "f").uuid, query);
3678
3720
  }
3679
3721
  /**
3680
3722
  * Executes a SPARQL query against the perspective's link cache.
@@ -3693,11 +3735,11 @@ class PerspectiveProxy {
3693
3735
  * @returns Query results as parsed JSON
3694
3736
  */
3695
3737
  async querySparql(query) {
3696
- const cached = getCachedResult(__classPrivateFieldGet$9(this, _PerspectiveProxy_handle, "f").uuid, query);
3738
+ const cached = getCachedResult(__classPrivateFieldGet$a(this, _PerspectiveProxy_handle, "f").uuid, query);
3697
3739
  if (cached !== undefined)
3698
3740
  return cached;
3699
- const result = await __classPrivateFieldGet$9(this, _PerspectiveProxy_client, "f").querySparql(__classPrivateFieldGet$9(this, _PerspectiveProxy_handle, "f").uuid, query);
3700
- setCachedResult(__classPrivateFieldGet$9(this, _PerspectiveProxy_handle, "f").uuid, query, result);
3741
+ const result = await __classPrivateFieldGet$a(this, _PerspectiveProxy_client, "f").querySparql(__classPrivateFieldGet$a(this, _PerspectiveProxy_handle, "f").uuid, query);
3742
+ setCachedResult(__classPrivateFieldGet$a(this, _PerspectiveProxy_handle, "f").uuid, query, result);
3701
3743
  return result;
3702
3744
  }
3703
3745
  /**
@@ -3709,7 +3751,23 @@ class PerspectiveProxy {
3709
3751
  * @returns Object with `instances` array and `totalCount`
3710
3752
  */
3711
3753
  async modelQuery(className, queryJson, shapeJson) {
3712
- return await __classPrivateFieldGet$9(this, _PerspectiveProxy_client, "f").modelQuery(__classPrivateFieldGet$9(this, _PerspectiveProxy_handle, "f").uuid, className, queryJson, shapeJson);
3754
+ return await __classPrivateFieldGet$a(this, _PerspectiveProxy_client, "f").modelQuery(__classPrivateFieldGet$a(this, _PerspectiveProxy_handle, "f").uuid, className, queryJson, shapeJson);
3755
+ }
3756
+ /**
3757
+ * Evaluate property getters for a batch of instances in a single RPC call.
3758
+ * Returns a map of `{ instanceId: { prop: value, ... } }`.
3759
+ *
3760
+ * Use this instead of `Ad4mModel.evaluateGetters()` for lazy-loading
3761
+ * getter-backed properties on visible items (e.g. `replyingTo` on messages).
3762
+ *
3763
+ * @param className - The model class name (e.g. "Message")
3764
+ * @param instanceIds - Array of instance base expression URIs
3765
+ * @param shapeJson - Shape metadata JSON from the model class
3766
+ * @param propertyNames - Optional subset of property names to evaluate
3767
+ * @returns Map of instance ID → evaluated property values
3768
+ */
3769
+ async evaluateGetters(className, instanceIds, shapeJson, propertyNames) {
3770
+ return await __classPrivateFieldGet$a(this, _PerspectiveProxy_client, "f").evaluateGetters(__classPrivateFieldGet$a(this, _PerspectiveProxy_handle, "f").uuid, className, instanceIds, shapeJson, propertyNames);
3713
3771
  }
3714
3772
  /**
3715
3773
  * Subscribe to model query changes. Builds trigger SPARQL from the model shape
@@ -3725,7 +3783,7 @@ class PerspectiveProxy {
3725
3783
  * @returns Object with `subscriptionId` and initial `result`
3726
3784
  */
3727
3785
  async modelSubscribe(className, queryJson, shapeJson) {
3728
- return await __classPrivateFieldGet$9(this, _PerspectiveProxy_client, "f").modelSubscribe(__classPrivateFieldGet$9(this, _PerspectiveProxy_handle, "f").uuid, className, queryJson, shapeJson);
3786
+ return await __classPrivateFieldGet$a(this, _PerspectiveProxy_client, "f").modelSubscribe(__classPrivateFieldGet$a(this, _PerspectiveProxy_handle, "f").uuid, className, queryJson, shapeJson);
3729
3787
  }
3730
3788
  /**
3731
3789
  * Adds a new link to the perspective.
@@ -3753,8 +3811,8 @@ class PerspectiveProxy {
3753
3811
  * ```
3754
3812
  */
3755
3813
  async add(link, status = 'shared', batchId) {
3756
- const result = await __classPrivateFieldGet$9(this, _PerspectiveProxy_client, "f").addLink(__classPrivateFieldGet$9(this, _PerspectiveProxy_handle, "f").uuid, link, status, batchId);
3757
- invalidatePerspectiveCache(__classPrivateFieldGet$9(this, _PerspectiveProxy_handle, "f").uuid);
3814
+ const result = await __classPrivateFieldGet$a(this, _PerspectiveProxy_client, "f").addLink(__classPrivateFieldGet$a(this, _PerspectiveProxy_handle, "f").uuid, link, status, batchId);
3815
+ invalidatePerspectiveCache(__classPrivateFieldGet$a(this, _PerspectiveProxy_handle, "f").uuid);
3758
3816
  return result;
3759
3817
  }
3760
3818
  /**
@@ -3767,8 +3825,8 @@ class PerspectiveProxy {
3767
3825
  * @returns Array of created LinkExpressions
3768
3826
  */
3769
3827
  async addLinks(links, status = 'shared', batchId) {
3770
- const result = await __classPrivateFieldGet$9(this, _PerspectiveProxy_client, "f").addLinks(__classPrivateFieldGet$9(this, _PerspectiveProxy_handle, "f").uuid, links, status, batchId);
3771
- invalidatePerspectiveCache(__classPrivateFieldGet$9(this, _PerspectiveProxy_handle, "f").uuid);
3828
+ const result = await __classPrivateFieldGet$a(this, _PerspectiveProxy_client, "f").addLinks(__classPrivateFieldGet$a(this, _PerspectiveProxy_handle, "f").uuid, links, status, batchId);
3829
+ invalidatePerspectiveCache(__classPrivateFieldGet$a(this, _PerspectiveProxy_handle, "f").uuid);
3772
3830
  return result;
3773
3831
  }
3774
3832
  /**
@@ -3779,8 +3837,8 @@ class PerspectiveProxy {
3779
3837
  * @returns Array of removed LinkExpressions
3780
3838
  */
3781
3839
  async removeLinks(links, batchId) {
3782
- const result = await __classPrivateFieldGet$9(this, _PerspectiveProxy_client, "f").removeLinks(__classPrivateFieldGet$9(this, _PerspectiveProxy_handle, "f").uuid, links, batchId);
3783
- invalidatePerspectiveCache(__classPrivateFieldGet$9(this, _PerspectiveProxy_handle, "f").uuid);
3840
+ const result = await __classPrivateFieldGet$a(this, _PerspectiveProxy_client, "f").removeLinks(__classPrivateFieldGet$a(this, _PerspectiveProxy_handle, "f").uuid, links, batchId);
3841
+ invalidatePerspectiveCache(__classPrivateFieldGet$a(this, _PerspectiveProxy_handle, "f").uuid);
3784
3842
  return result;
3785
3843
  }
3786
3844
  /**
@@ -3792,8 +3850,8 @@ class PerspectiveProxy {
3792
3850
  * @returns Object containing results of the mutations
3793
3851
  */
3794
3852
  async linkMutations(mutations, status = 'shared') {
3795
- const result = await __classPrivateFieldGet$9(this, _PerspectiveProxy_client, "f").linkMutations(__classPrivateFieldGet$9(this, _PerspectiveProxy_handle, "f").uuid, mutations, status);
3796
- invalidatePerspectiveCache(__classPrivateFieldGet$9(this, _PerspectiveProxy_handle, "f").uuid);
3853
+ const result = await __classPrivateFieldGet$a(this, _PerspectiveProxy_client, "f").linkMutations(__classPrivateFieldGet$a(this, _PerspectiveProxy_handle, "f").uuid, mutations, status);
3854
+ invalidatePerspectiveCache(__classPrivateFieldGet$a(this, _PerspectiveProxy_handle, "f").uuid);
3797
3855
  return result;
3798
3856
  }
3799
3857
  /**
@@ -3805,7 +3863,7 @@ class PerspectiveProxy {
3805
3863
  * @returns The added LinkExpression
3806
3864
  */
3807
3865
  async addLinkExpression(link, status = 'shared', batchId) {
3808
- return await __classPrivateFieldGet$9(this, _PerspectiveProxy_client, "f").addLinkExpression(__classPrivateFieldGet$9(this, _PerspectiveProxy_handle, "f").uuid, link, status, batchId);
3866
+ return await __classPrivateFieldGet$a(this, _PerspectiveProxy_client, "f").addLinkExpression(__classPrivateFieldGet$a(this, _PerspectiveProxy_handle, "f").uuid, link, status, batchId);
3809
3867
  }
3810
3868
  /**
3811
3869
  * Updates an existing link with new data.
@@ -3815,8 +3873,8 @@ class PerspectiveProxy {
3815
3873
  * @param batchId - Optional batch ID to group this operation with others
3816
3874
  */
3817
3875
  async update(oldLink, newLink, batchId) {
3818
- const result = await __classPrivateFieldGet$9(this, _PerspectiveProxy_client, "f").updateLink(__classPrivateFieldGet$9(this, _PerspectiveProxy_handle, "f").uuid, oldLink, newLink, batchId);
3819
- invalidatePerspectiveCache(__classPrivateFieldGet$9(this, _PerspectiveProxy_handle, "f").uuid);
3876
+ const result = await __classPrivateFieldGet$a(this, _PerspectiveProxy_client, "f").updateLink(__classPrivateFieldGet$a(this, _PerspectiveProxy_handle, "f").uuid, oldLink, newLink, batchId);
3877
+ invalidatePerspectiveCache(__classPrivateFieldGet$a(this, _PerspectiveProxy_handle, "f").uuid);
3820
3878
  return result;
3821
3879
  }
3822
3880
  /**
@@ -3826,18 +3884,18 @@ class PerspectiveProxy {
3826
3884
  * @param batchId - Optional batch ID to group this operation with others
3827
3885
  */
3828
3886
  async remove(link, batchId) {
3829
- const result = await __classPrivateFieldGet$9(this, _PerspectiveProxy_client, "f").removeLink(__classPrivateFieldGet$9(this, _PerspectiveProxy_handle, "f").uuid, link, batchId);
3830
- invalidatePerspectiveCache(__classPrivateFieldGet$9(this, _PerspectiveProxy_handle, "f").uuid);
3887
+ const result = await __classPrivateFieldGet$a(this, _PerspectiveProxy_client, "f").removeLink(__classPrivateFieldGet$a(this, _PerspectiveProxy_handle, "f").uuid, link, batchId);
3888
+ invalidatePerspectiveCache(__classPrivateFieldGet$a(this, _PerspectiveProxy_handle, "f").uuid);
3831
3889
  return result;
3832
3890
  }
3833
3891
  /** Creates a new batch for grouping operations */
3834
3892
  async createBatch() {
3835
- return await __classPrivateFieldGet$9(this, _PerspectiveProxy_client, "f").createBatch(__classPrivateFieldGet$9(this, _PerspectiveProxy_handle, "f").uuid);
3893
+ return await __classPrivateFieldGet$a(this, _PerspectiveProxy_client, "f").createBatch(__classPrivateFieldGet$a(this, _PerspectiveProxy_handle, "f").uuid);
3836
3894
  }
3837
3895
  /** Commits a batch of operations */
3838
3896
  async commitBatch(batchId) {
3839
- const result = await __classPrivateFieldGet$9(this, _PerspectiveProxy_client, "f").commitBatch(__classPrivateFieldGet$9(this, _PerspectiveProxy_handle, "f").uuid, batchId);
3840
- invalidatePerspectiveCache(__classPrivateFieldGet$9(this, _PerspectiveProxy_handle, "f").uuid);
3897
+ const result = await __classPrivateFieldGet$a(this, _PerspectiveProxy_client, "f").commitBatch(__classPrivateFieldGet$a(this, _PerspectiveProxy_handle, "f").uuid, batchId);
3898
+ invalidatePerspectiveCache(__classPrivateFieldGet$a(this, _PerspectiveProxy_handle, "f").uuid);
3841
3899
  return result;
3842
3900
  }
3843
3901
  /**
@@ -3847,7 +3905,7 @@ class PerspectiveProxy {
3847
3905
  * @returns The rendered Expression
3848
3906
  */
3849
3907
  async getExpression(expressionURI) {
3850
- return await __classPrivateFieldGet$9(this, _PerspectiveProxy_client, "f").getExpression(expressionURI);
3908
+ return await __classPrivateFieldGet$a(this, _PerspectiveProxy_client, "f").getExpression(expressionURI);
3851
3909
  }
3852
3910
  /**
3853
3911
  * Creates a new Expression in the specified Language.
@@ -3857,7 +3915,7 @@ class PerspectiveProxy {
3857
3915
  * @returns URI of the created Expression
3858
3916
  */
3859
3917
  async createExpression(content, languageAddress) {
3860
- return await __classPrivateFieldGet$9(this, _PerspectiveProxy_client, "f").createExpression(content, languageAddress);
3918
+ return await __classPrivateFieldGet$a(this, _PerspectiveProxy_client, "f").createExpression(content, languageAddress);
3861
3919
  }
3862
3920
  /**
3863
3921
  * Subscribes to link changes in the perspective.
@@ -3880,13 +3938,13 @@ class PerspectiveProxy {
3880
3938
  */
3881
3939
  async addListener(type, cb) {
3882
3940
  if (type === 'link-added') {
3883
- __classPrivateFieldGet$9(this, _PerspectiveProxy_perspectiveLinkAddedCallbacks, "f").push(cb);
3941
+ __classPrivateFieldGet$a(this, _PerspectiveProxy_perspectiveLinkAddedCallbacks, "f").push(cb);
3884
3942
  }
3885
3943
  else if (type === 'link-removed') {
3886
- __classPrivateFieldGet$9(this, _PerspectiveProxy_perspectiveLinkRemovedCallbacks, "f").push(cb);
3944
+ __classPrivateFieldGet$a(this, _PerspectiveProxy_perspectiveLinkRemovedCallbacks, "f").push(cb);
3887
3945
  }
3888
3946
  else if (type === 'link-updated') {
3889
- __classPrivateFieldGet$9(this, _PerspectiveProxy_perspectiveLinkUpdatedCallbacks, "f").push(cb);
3947
+ __classPrivateFieldGet$a(this, _PerspectiveProxy_perspectiveLinkUpdatedCallbacks, "f").push(cb);
3890
3948
  }
3891
3949
  }
3892
3950
  /**
@@ -3902,7 +3960,7 @@ class PerspectiveProxy {
3902
3960
  * ```
3903
3961
  */
3904
3962
  async addSyncStateChangeListener(cb) {
3905
- __classPrivateFieldGet$9(this, _PerspectiveProxy_perspectiveSyncStateChangeCallbacks, "f").push(cb);
3963
+ __classPrivateFieldGet$a(this, _PerspectiveProxy_perspectiveSyncStateChangeCallbacks, "f").push(cb);
3906
3964
  }
3907
3965
  /**
3908
3966
  * Unsubscribes from link changes.
@@ -3912,16 +3970,16 @@ class PerspectiveProxy {
3912
3970
  */
3913
3971
  async removeListener(type, cb) {
3914
3972
  if (type === 'link-added') {
3915
- const index = __classPrivateFieldGet$9(this, _PerspectiveProxy_perspectiveLinkAddedCallbacks, "f").indexOf(cb);
3916
- __classPrivateFieldGet$9(this, _PerspectiveProxy_perspectiveLinkAddedCallbacks, "f").splice(index, 1);
3973
+ const index = __classPrivateFieldGet$a(this, _PerspectiveProxy_perspectiveLinkAddedCallbacks, "f").indexOf(cb);
3974
+ __classPrivateFieldGet$a(this, _PerspectiveProxy_perspectiveLinkAddedCallbacks, "f").splice(index, 1);
3917
3975
  }
3918
3976
  else if (type === 'link-removed') {
3919
- const index = __classPrivateFieldGet$9(this, _PerspectiveProxy_perspectiveLinkRemovedCallbacks, "f").indexOf(cb);
3920
- __classPrivateFieldGet$9(this, _PerspectiveProxy_perspectiveLinkRemovedCallbacks, "f").splice(index, 1);
3977
+ const index = __classPrivateFieldGet$a(this, _PerspectiveProxy_perspectiveLinkRemovedCallbacks, "f").indexOf(cb);
3978
+ __classPrivateFieldGet$a(this, _PerspectiveProxy_perspectiveLinkRemovedCallbacks, "f").splice(index, 1);
3921
3979
  }
3922
3980
  else if (type === 'link-updated') {
3923
- const index = __classPrivateFieldGet$9(this, _PerspectiveProxy_perspectiveLinkUpdatedCallbacks, "f").indexOf(cb);
3924
- __classPrivateFieldGet$9(this, _PerspectiveProxy_perspectiveLinkUpdatedCallbacks, "f").splice(index, 1);
3981
+ const index = __classPrivateFieldGet$a(this, _PerspectiveProxy_perspectiveLinkUpdatedCallbacks, "f").indexOf(cb);
3982
+ __classPrivateFieldGet$a(this, _PerspectiveProxy_perspectiveLinkUpdatedCallbacks, "f").splice(index, 1);
3925
3983
  }
3926
3984
  }
3927
3985
  /**
@@ -3931,7 +3989,7 @@ class PerspectiveProxy {
3931
3989
  * @returns Perspective object containing all links
3932
3990
  */
3933
3991
  async snapshot() {
3934
- return __classPrivateFieldGet$9(this, _PerspectiveProxy_client, "f").snapshotByUUID(__classPrivateFieldGet$9(this, _PerspectiveProxy_handle, "f").uuid);
3992
+ return __classPrivateFieldGet$a(this, _PerspectiveProxy_client, "f").snapshotByUUID(__classPrivateFieldGet$a(this, _PerspectiveProxy_handle, "f").uuid);
3935
3993
  }
3936
3994
  /**
3937
3995
  * Loads a perspective snapshot, replacing current content.
@@ -4211,7 +4269,7 @@ class PerspectiveProxy {
4211
4269
  * await perspective.addSdna('Recipe', prologCode, 'subject_class');
4212
4270
  */
4213
4271
  async addSdna(name, sdnaCode, sdnaType, shaclJson) {
4214
- return __classPrivateFieldGet$9(this, _PerspectiveProxy_client, "f").addSdna(__classPrivateFieldGet$9(this, _PerspectiveProxy_handle, "f").uuid, name, sdnaCode, sdnaType, shaclJson);
4272
+ return __classPrivateFieldGet$a(this, _PerspectiveProxy_client, "f").addSdna(__classPrivateFieldGet$a(this, _PerspectiveProxy_handle, "f").uuid, name, sdnaCode, sdnaType, shaclJson);
4215
4273
  }
4216
4274
  /**
4217
4275
  * Adds a subject class to the perspective.
@@ -4481,7 +4539,7 @@ class PerspectiveProxy {
4481
4539
  let className;
4482
4540
  if (typeof subjectClass === "string") {
4483
4541
  className = subjectClass;
4484
- await __classPrivateFieldGet$9(this, _PerspectiveProxy_client, "f").createSubject(__classPrivateFieldGet$9(this, _PerspectiveProxy_handle, "f").uuid, JSON.stringify({
4542
+ await __classPrivateFieldGet$a(this, _PerspectiveProxy_client, "f").createSubject(__classPrivateFieldGet$a(this, _PerspectiveProxy_handle, "f").uuid, JSON.stringify({
4485
4543
  className,
4486
4544
  initialValues
4487
4545
  }), exprAddr, initialValues ? JSON.stringify(initialValues) : undefined, batchId);
@@ -4493,7 +4551,7 @@ class PerspectiveProxy {
4493
4551
  if (!resolvedClassName) {
4494
4552
  throw new Error("Could not resolve subject class name from object. Use a decorated class or pass a className string.");
4495
4553
  }
4496
- await __classPrivateFieldGet$9(this, _PerspectiveProxy_client, "f").createSubject(__classPrivateFieldGet$9(this, _PerspectiveProxy_handle, "f").uuid, JSON.stringify({
4554
+ await __classPrivateFieldGet$a(this, _PerspectiveProxy_client, "f").createSubject(__classPrivateFieldGet$a(this, _PerspectiveProxy_handle, "f").uuid, JSON.stringify({
4497
4555
  className: resolvedClassName,
4498
4556
  initialValues
4499
4557
  }), exprAddr, initialValues ? JSON.stringify(initialValues) : undefined, batchId);
@@ -4508,7 +4566,7 @@ class PerspectiveProxy {
4508
4566
  }
4509
4567
  async getSubjectData(subjectClass, exprAddr) {
4510
4568
  if (typeof subjectClass === "string") {
4511
- return JSON.parse(await __classPrivateFieldGet$9(this, _PerspectiveProxy_client, "f").getSubjectData(__classPrivateFieldGet$9(this, _PerspectiveProxy_handle, "f").uuid, JSON.stringify({ className: subjectClass }), exprAddr));
4569
+ return JSON.parse(await __classPrivateFieldGet$a(this, _PerspectiveProxy_client, "f").getSubjectData(__classPrivateFieldGet$a(this, _PerspectiveProxy_handle, "f").uuid, JSON.stringify({ className: subjectClass }), exprAddr));
4512
4570
  }
4513
4571
  const obj = subjectClass;
4514
4572
  const resolvedClassName = obj.className || obj.constructor?.className || obj.constructor?.prototype?.className
@@ -4516,7 +4574,7 @@ class PerspectiveProxy {
4516
4574
  if (!resolvedClassName) {
4517
4575
  throw new Error("Could not resolve subject class name from object. Use a decorated class or pass a className string.");
4518
4576
  }
4519
- return JSON.parse(await __classPrivateFieldGet$9(this, _PerspectiveProxy_client, "f").getSubjectData(__classPrivateFieldGet$9(this, _PerspectiveProxy_handle, "f").uuid, JSON.stringify({ className: resolvedClassName }), exprAddr));
4577
+ return JSON.parse(await __classPrivateFieldGet$a(this, _PerspectiveProxy_client, "f").getSubjectData(__classPrivateFieldGet$a(this, _PerspectiveProxy_handle, "f").uuid, JSON.stringify({ className: resolvedClassName }), exprAddr));
4520
4578
  }
4521
4579
  /**
4522
4580
  * Gets actions from SHACL links for a given predicate (e.g., ad4m://constructor, ad4m://destructor).
@@ -4880,7 +4938,7 @@ class PerspectiveProxy {
4880
4938
  // Get the class name from the JS class
4881
4939
  const className = jsClass.className || jsClass.prototype?.className || jsClass.name;
4882
4940
  // Skip if already registered for this perspective instance
4883
- if (__classPrivateFieldGet$9(this, _PerspectiveProxy_ensuredSubjectClasses, "f").has(className))
4941
+ if (__classPrivateFieldGet$a(this, _PerspectiveProxy_ensuredSubjectClasses, "f").has(className))
4884
4942
  return;
4885
4943
  // Note: Duplicate checking is handled on the Rust side in add_sdna
4886
4944
  // Generate SHACL SDNA (Prolog-free)
@@ -4895,13 +4953,13 @@ class PerspectiveProxy {
4895
4953
  // Backend stores SHACL links directly
4896
4954
  await this.addSdna(className, '', 'subject_class', shaclJson);
4897
4955
  // Mark as registered for this perspective instance
4898
- __classPrivateFieldGet$9(this, _PerspectiveProxy_ensuredSubjectClasses, "f").add(className);
4956
+ __classPrivateFieldGet$a(this, _PerspectiveProxy_ensuredSubjectClasses, "f").add(className);
4899
4957
  }
4900
4958
  /** Clear the per-instance ensured subject class cache.
4901
4959
  * Call this after wiping a perspective's links so that
4902
4960
  * subsequent register() calls re-add SHACL definitions. */
4903
4961
  clearEnsuredSubjectClasses() {
4904
- __classPrivateFieldGet$9(this, _PerspectiveProxy_ensuredSubjectClasses, "f").clear();
4962
+ __classPrivateFieldGet$a(this, _PerspectiveProxy_ensuredSubjectClasses, "f").clear();
4905
4963
  }
4906
4964
  /**
4907
4965
  * Returns a list of all class names that have been registered as SHACL
@@ -5076,7 +5134,7 @@ class PerspectiveProxy {
5076
5134
  }));
5077
5135
  }
5078
5136
  getNeighbourhoodProxy() {
5079
- return __classPrivateFieldGet$9(this, _PerspectiveProxy_client, "f").getNeighbourhoodProxy(__classPrivateFieldGet$9(this, _PerspectiveProxy_handle, "f").uuid);
5137
+ return __classPrivateFieldGet$a(this, _PerspectiveProxy_client, "f").getNeighbourhoodProxy(__classPrivateFieldGet$a(this, _PerspectiveProxy_handle, "f").uuid);
5080
5138
  }
5081
5139
  /**
5082
5140
  * Returns a proxy object for working with AI capabilities.
@@ -5093,7 +5151,7 @@ class PerspectiveProxy {
5093
5151
  * ```
5094
5152
  */
5095
5153
  get ai() {
5096
- return __classPrivateFieldGet$9(this, _PerspectiveProxy_client, "f").aiClient;
5154
+ return __classPrivateFieldGet$a(this, _PerspectiveProxy_client, "f").aiClient;
5097
5155
  }
5098
5156
  /**
5099
5157
  * Creates a subscription for a Prolog query that updates in real-time.
@@ -5135,7 +5193,7 @@ class PerspectiveProxy {
5135
5193
  * ```
5136
5194
  */
5137
5195
  async subscribeInfer(query) {
5138
- const subscriptionProxy = new QuerySubscriptionProxy(this.uuid, query, __classPrivateFieldGet$9(this, _PerspectiveProxy_client, "f"));
5196
+ const subscriptionProxy = new QuerySubscriptionProxy(this.uuid, query, __classPrivateFieldGet$a(this, _PerspectiveProxy_client, "f"));
5139
5197
  // Start the subscription on the Rust side first to get the real subscription ID
5140
5198
  await subscriptionProxy.subscribe();
5141
5199
  // Wait for the initial result
@@ -5163,7 +5221,7 @@ class PerspectiveProxy {
5163
5221
  * @returns Initialized QuerySubscriptionProxy instance
5164
5222
  */
5165
5223
  async subscribeQuery(query) {
5166
- const subscriptionProxy = new QuerySubscriptionProxy(this.uuid, query, __classPrivateFieldGet$9(this, _PerspectiveProxy_client, "f"));
5224
+ const subscriptionProxy = new QuerySubscriptionProxy(this.uuid, query, __classPrivateFieldGet$a(this, _PerspectiveProxy_client, "f"));
5167
5225
  // Start the subscription on the Rust side first to get the real subscription ID
5168
5226
  await subscriptionProxy.subscribe();
5169
5227
  // Wait for the initial result
@@ -5173,13 +5231,13 @@ class PerspectiveProxy {
5173
5231
  }
5174
5232
  _PerspectiveProxy_handle = new WeakMap(), _PerspectiveProxy_client = new WeakMap(), _PerspectiveProxy_perspectiveLinkAddedCallbacks = new WeakMap(), _PerspectiveProxy_perspectiveLinkRemovedCallbacks = new WeakMap(), _PerspectiveProxy_perspectiveLinkUpdatedCallbacks = new WeakMap(), _PerspectiveProxy_perspectiveSyncStateChangeCallbacks = new WeakMap(), _PerspectiveProxy_ensuredSubjectClasses = new WeakMap();
5175
5233
 
5176
- var __classPrivateFieldSet$8 = (undefined && undefined.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {
5234
+ var __classPrivateFieldSet$9 = (undefined && undefined.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {
5177
5235
  if (kind === "m") throw new TypeError("Private method is not writable");
5178
5236
  if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
5179
5237
  if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
5180
5238
  return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
5181
5239
  };
5182
- var __classPrivateFieldGet$8 = (undefined && undefined.__classPrivateFieldGet) || function (receiver, state, kind, f) {
5240
+ var __classPrivateFieldGet$9 = (undefined && undefined.__classPrivateFieldGet) || function (receiver, state, kind, f) {
5183
5241
  if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
5184
5242
  if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
5185
5243
  return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
@@ -5187,11 +5245,6 @@ var __classPrivateFieldGet$8 = (undefined && undefined.__classPrivateFieldGet) |
5187
5245
  var _PerspectiveClient_apiClient, _PerspectiveClient_perspectiveAddedCallbacks, _PerspectiveClient_perspectiveUpdatedCallbacks, _PerspectiveClient_perspectiveRemovedCallbacks, _PerspectiveClient_perspectiveSyncStateChangeCallbacks, _PerspectiveClient_expressionClient, _PerspectiveClient_neighbourhoodClient, _PerspectiveClient_aiClient, _PerspectiveClient_unsubscribers, _PerspectiveClient_linkUnsubscribers, _PerspectiveClient_querySubscriptionUnsubscribers;
5188
5246
  function normalizeQueryResult(raw, errorContext) {
5189
5247
  let finalResult = raw;
5190
- let isInit = false;
5191
- if (typeof finalResult === 'string' && finalResult.startsWith('#init#')) {
5192
- finalResult = finalResult.substring(6);
5193
- isInit = true;
5194
- }
5195
5248
  if (typeof finalResult === 'string') {
5196
5249
  try {
5197
5250
  finalResult = JSON.parse(finalResult);
@@ -5200,10 +5253,7 @@ function normalizeQueryResult(raw, errorContext) {
5200
5253
  console.error(errorContext, e);
5201
5254
  }
5202
5255
  }
5203
- if (isInit && typeof finalResult === 'object' && finalResult !== null) {
5204
- finalResult.isInit = true;
5205
- }
5206
- return { result: finalResult, isInit };
5256
+ return finalResult;
5207
5257
  }
5208
5258
  class PerspectiveClient {
5209
5259
  constructor(baseUrl, token, subscribe = true, sharedApiClient) {
@@ -5218,14 +5268,14 @@ class PerspectiveClient {
5218
5268
  _PerspectiveClient_unsubscribers.set(this, void 0);
5219
5269
  _PerspectiveClient_linkUnsubscribers.set(this, void 0);
5220
5270
  _PerspectiveClient_querySubscriptionUnsubscribers.set(this, void 0);
5221
- __classPrivateFieldSet$8(this, _PerspectiveClient_apiClient, sharedApiClient || new ApiClient(baseUrl, token), "f");
5222
- __classPrivateFieldSet$8(this, _PerspectiveClient_perspectiveAddedCallbacks, [], "f");
5223
- __classPrivateFieldSet$8(this, _PerspectiveClient_perspectiveUpdatedCallbacks, [], "f");
5224
- __classPrivateFieldSet$8(this, _PerspectiveClient_perspectiveRemovedCallbacks, [], "f");
5225
- __classPrivateFieldSet$8(this, _PerspectiveClient_perspectiveSyncStateChangeCallbacks, [], "f");
5226
- __classPrivateFieldSet$8(this, _PerspectiveClient_unsubscribers, [], "f");
5227
- __classPrivateFieldSet$8(this, _PerspectiveClient_linkUnsubscribers, new Map(), "f");
5228
- __classPrivateFieldSet$8(this, _PerspectiveClient_querySubscriptionUnsubscribers, new Map(), "f");
5271
+ __classPrivateFieldSet$9(this, _PerspectiveClient_apiClient, sharedApiClient || new ApiClient(baseUrl, token), "f");
5272
+ __classPrivateFieldSet$9(this, _PerspectiveClient_perspectiveAddedCallbacks, [], "f");
5273
+ __classPrivateFieldSet$9(this, _PerspectiveClient_perspectiveUpdatedCallbacks, [], "f");
5274
+ __classPrivateFieldSet$9(this, _PerspectiveClient_perspectiveRemovedCallbacks, [], "f");
5275
+ __classPrivateFieldSet$9(this, _PerspectiveClient_perspectiveSyncStateChangeCallbacks, [], "f");
5276
+ __classPrivateFieldSet$9(this, _PerspectiveClient_unsubscribers, [], "f");
5277
+ __classPrivateFieldSet$9(this, _PerspectiveClient_linkUnsubscribers, new Map(), "f");
5278
+ __classPrivateFieldSet$9(this, _PerspectiveClient_querySubscriptionUnsubscribers, new Map(), "f");
5229
5279
  if (subscribe) {
5230
5280
  this.subscribePerspectiveAdded();
5231
5281
  this.subscribePerspectiveUpdated();
@@ -5233,24 +5283,24 @@ class PerspectiveClient {
5233
5283
  }
5234
5284
  }
5235
5285
  setExpressionClient(client) {
5236
- __classPrivateFieldSet$8(this, _PerspectiveClient_expressionClient, client, "f");
5286
+ __classPrivateFieldSet$9(this, _PerspectiveClient_expressionClient, client, "f");
5237
5287
  }
5238
5288
  setNeighbourhoodClient(client) {
5239
- __classPrivateFieldSet$8(this, _PerspectiveClient_neighbourhoodClient, client, "f");
5289
+ __classPrivateFieldSet$9(this, _PerspectiveClient_neighbourhoodClient, client, "f");
5240
5290
  }
5241
5291
  setAIClient(client) {
5242
- __classPrivateFieldSet$8(this, _PerspectiveClient_aiClient, client, "f");
5292
+ __classPrivateFieldSet$9(this, _PerspectiveClient_aiClient, client, "f");
5243
5293
  }
5244
5294
  get aiClient() {
5245
- return __classPrivateFieldGet$8(this, _PerspectiveClient_aiClient, "f");
5295
+ return __classPrivateFieldGet$9(this, _PerspectiveClient_aiClient, "f");
5246
5296
  }
5247
5297
  async all() {
5248
- const perspectives = await __classPrivateFieldGet$8(this, _PerspectiveClient_apiClient, "f").call('perspective.all');
5298
+ const perspectives = await __classPrivateFieldGet$9(this, _PerspectiveClient_apiClient, "f").call('perspective.all');
5249
5299
  return perspectives.map(handle => new PerspectiveProxy(handle, this));
5250
5300
  }
5251
5301
  async byUUID(uuid) {
5252
5302
  try {
5253
- const perspective = await __classPrivateFieldGet$8(this, _PerspectiveClient_apiClient, "f").call('perspective.get', { uuid });
5303
+ const perspective = await __classPrivateFieldGet$9(this, _PerspectiveClient_apiClient, "f").call('perspective.get', { uuid });
5254
5304
  if (!perspective)
5255
5305
  return null;
5256
5306
  return new PerspectiveProxy(perspective, this);
@@ -5262,10 +5312,10 @@ class PerspectiveClient {
5262
5312
  }
5263
5313
  }
5264
5314
  async snapshotByUUID(uuid) {
5265
- return __classPrivateFieldGet$8(this, _PerspectiveClient_apiClient, "f").call('perspective.snapshot', { uuid });
5315
+ return __classPrivateFieldGet$9(this, _PerspectiveClient_apiClient, "f").call('perspective.snapshot', { uuid });
5266
5316
  }
5267
5317
  async publishSnapshotByUUID(uuid) {
5268
- return __classPrivateFieldGet$8(this, _PerspectiveClient_apiClient, "f").call('perspective.publishSnapshot', { uuid });
5318
+ return __classPrivateFieldGet$9(this, _PerspectiveClient_apiClient, "f").call('perspective.publishSnapshot', { uuid });
5269
5319
  }
5270
5320
  async queryLinks(uuid, query) {
5271
5321
  const params = { uuid };
@@ -5281,179 +5331,189 @@ class PerspectiveClient {
5281
5331
  params.untilDate = query.untilDate instanceof Date ? query.untilDate.toISOString() : String(query.untilDate);
5282
5332
  if (query.limit !== undefined)
5283
5333
  params.limit = query.limit;
5284
- return __classPrivateFieldGet$8(this, _PerspectiveClient_apiClient, "f").call('perspective.queryLinks', params);
5334
+ return __classPrivateFieldGet$9(this, _PerspectiveClient_apiClient, "f").call('perspective.queryLinks', params);
5285
5335
  }
5286
5336
  async queryProlog(uuid, query) {
5287
- const result = await __classPrivateFieldGet$8(this, _PerspectiveClient_apiClient, "f").call('perspective.queryProlog', { uuid, query });
5337
+ const result = await __classPrivateFieldGet$9(this, _PerspectiveClient_apiClient, "f").call('perspective.queryProlog', { uuid, query });
5288
5338
  return JSON.parse(result);
5289
5339
  }
5290
5340
  async querySparql(uuid, query) {
5291
- const result = await __classPrivateFieldGet$8(this, _PerspectiveClient_apiClient, "f").call('perspective.querySparql', { uuid, engine: 'sparql', query });
5341
+ const result = await __classPrivateFieldGet$9(this, _PerspectiveClient_apiClient, "f").call('perspective.querySparql', { uuid, engine: 'sparql', query });
5292
5342
  return JSON.parse(result);
5293
5343
  }
5294
5344
  async subscribeQuery(uuid, query) {
5295
- const response = await __classPrivateFieldGet$8(this, _PerspectiveClient_apiClient, "f").call('perspective.subscribeQuery', { uuid, query });
5345
+ const response = await __classPrivateFieldGet$9(this, _PerspectiveClient_apiClient, "f").call('perspective.subscribeQuery', { uuid, query });
5296
5346
  const { subscriptionId, result } = response;
5297
- const normalized = normalizeQueryResult(result, 'Error parsing subscribeQuery result:');
5298
- return { subscriptionId, result: normalized.result, isInit: normalized.isInit };
5347
+ const parsed = normalizeQueryResult(result, 'Error parsing subscribeQuery result:');
5348
+ return { subscriptionId, result: parsed };
5299
5349
  }
5300
5350
  async perspectiveKeepAliveQuery(uuid, subscriptionId) {
5301
- return __classPrivateFieldGet$8(this, _PerspectiveClient_apiClient, "f").call('perspective.keepAliveQuery', { uuid, subscriptionId });
5351
+ return __classPrivateFieldGet$9(this, _PerspectiveClient_apiClient, "f").call('perspective.keepAliveQuery', { uuid, subscriptionId });
5302
5352
  }
5303
5353
  async perspectiveDisposeQuerySubscription(uuid, subscriptionId) {
5304
- return __classPrivateFieldGet$8(this, _PerspectiveClient_apiClient, "f").call('perspective.disposeQuery', { uuid, subscriptionId });
5354
+ return __classPrivateFieldGet$9(this, _PerspectiveClient_apiClient, "f").call('perspective.disposeQuery', { uuid, subscriptionId });
5305
5355
  }
5306
5356
  subscribeToQueryUpdates(subscriptionId, onData) {
5307
- const unsub = __classPrivateFieldGet$8(this, _PerspectiveClient_apiClient, "f").subscribe((data) => {
5357
+ const unsub = __classPrivateFieldGet$9(this, _PerspectiveClient_apiClient, "f").subscribe((data) => {
5308
5358
  const event = data;
5309
5359
  if (event.type !== 'query-subscription-update')
5310
5360
  return;
5311
5361
  const eventSubscriptionId = event.subscriptionId || event.subscription_id;
5312
5362
  if (eventSubscriptionId !== subscriptionId)
5313
5363
  return;
5314
- const normalized = normalizeQueryResult(event.result, 'Error parsing query subscription:');
5315
- onData(normalized.result);
5364
+ const parsed = normalizeQueryResult(event.result, 'Error parsing query subscription:');
5365
+ onData(parsed);
5316
5366
  });
5317
- __classPrivateFieldGet$8(this, _PerspectiveClient_querySubscriptionUnsubscribers, "f").set(subscriptionId, unsub);
5367
+ __classPrivateFieldGet$9(this, _PerspectiveClient_querySubscriptionUnsubscribers, "f").set(subscriptionId, unsub);
5318
5368
  return unsub;
5319
5369
  }
5320
5370
  async keepAliveQuery(uuid, subscriptionId) {
5321
- return __classPrivateFieldGet$8(this, _PerspectiveClient_apiClient, "f").call('perspective.keepAliveQuery', { uuid, subscriptionId });
5371
+ return __classPrivateFieldGet$9(this, _PerspectiveClient_apiClient, "f").call('perspective.keepAliveQuery', { uuid, subscriptionId });
5322
5372
  }
5323
5373
  async disposeQuerySubscription(uuid, subscriptionId) {
5324
- const unsub = __classPrivateFieldGet$8(this, _PerspectiveClient_querySubscriptionUnsubscribers, "f").get(subscriptionId);
5374
+ const unsub = __classPrivateFieldGet$9(this, _PerspectiveClient_querySubscriptionUnsubscribers, "f").get(subscriptionId);
5325
5375
  if (unsub) {
5326
5376
  unsub();
5327
- __classPrivateFieldGet$8(this, _PerspectiveClient_querySubscriptionUnsubscribers, "f").delete(subscriptionId);
5377
+ __classPrivateFieldGet$9(this, _PerspectiveClient_querySubscriptionUnsubscribers, "f").delete(subscriptionId);
5328
5378
  }
5329
- return __classPrivateFieldGet$8(this, _PerspectiveClient_apiClient, "f").call('perspective.disposeQuery', { uuid, subscriptionId });
5379
+ return __classPrivateFieldGet$9(this, _PerspectiveClient_apiClient, "f").call('perspective.disposeQuery', { uuid, subscriptionId });
5330
5380
  }
5331
5381
  async modelQuery(uuid, className, queryJson, shapeJson) {
5332
- const resultJson = await __classPrivateFieldGet$8(this, _PerspectiveClient_apiClient, "f").call('perspective.modelQuery', { uuid, class_name: className, query_json: queryJson, shape_json: shapeJson });
5382
+ const resultJson = await __classPrivateFieldGet$9(this, _PerspectiveClient_apiClient, "f").call('perspective.modelQuery', { uuid, class_name: className, query_json: queryJson, shape_json: shapeJson });
5383
+ return JSON.parse(resultJson);
5384
+ }
5385
+ async evaluateGetters(uuid, className, instanceIds, shapeJson, propertyNames) {
5386
+ const resultJson = await __classPrivateFieldGet$9(this, _PerspectiveClient_apiClient, "f").call('perspective.evaluateGetters', {
5387
+ uuid,
5388
+ class_name: className,
5389
+ instance_ids: instanceIds,
5390
+ shape_json: shapeJson,
5391
+ ...(propertyNames && { property_names: propertyNames }),
5392
+ });
5333
5393
  return JSON.parse(resultJson);
5334
5394
  }
5335
5395
  async modelSubscribe(uuid, className, queryJson, shapeJson) {
5336
- const response = await __classPrivateFieldGet$8(this, _PerspectiveClient_apiClient, "f").call('perspective.modelSubscribe', { uuid, class_name: className, query_json: queryJson, shape_json: shapeJson });
5396
+ const response = await __classPrivateFieldGet$9(this, _PerspectiveClient_apiClient, "f").call('perspective.modelSubscribe', { uuid, class_name: className, query_json: queryJson, shape_json: shapeJson });
5337
5397
  return {
5338
5398
  subscriptionId: response.subscription_id,
5339
5399
  result: JSON.parse(response.result)
5340
5400
  };
5341
5401
  }
5342
5402
  async add(name) {
5343
- const handle = await __classPrivateFieldGet$8(this, _PerspectiveClient_apiClient, "f").call('perspective.create', { name });
5403
+ const handle = await __classPrivateFieldGet$9(this, _PerspectiveClient_apiClient, "f").call('perspective.create', { name });
5344
5404
  return new PerspectiveProxy(handle, this);
5345
5405
  }
5346
5406
  async update(uuid, name) {
5347
- const handle = await __classPrivateFieldGet$8(this, _PerspectiveClient_apiClient, "f").call('perspective.update', { uuid, name });
5407
+ const handle = await __classPrivateFieldGet$9(this, _PerspectiveClient_apiClient, "f").call('perspective.update', { uuid, name });
5348
5408
  return new PerspectiveProxy(handle, this);
5349
5409
  }
5350
5410
  async remove(uuid) {
5351
- const result = await __classPrivateFieldGet$8(this, _PerspectiveClient_apiClient, "f").call('perspective.remove', { uuid });
5411
+ const result = await __classPrivateFieldGet$9(this, _PerspectiveClient_apiClient, "f").call('perspective.remove', { uuid });
5352
5412
  return { perspectiveRemove: result };
5353
5413
  }
5354
5414
  async addLink(uuid, link, status = 'shared', batchId) {
5355
- return __classPrivateFieldGet$8(this, _PerspectiveClient_apiClient, "f").call('perspective.addLink', { uuid, link, status, batchId });
5415
+ return __classPrivateFieldGet$9(this, _PerspectiveClient_apiClient, "f").call('perspective.addLink', { uuid, link, status, batchId });
5356
5416
  }
5357
5417
  async addLinks(uuid, links, status = 'shared', batchId) {
5358
- return __classPrivateFieldGet$8(this, _PerspectiveClient_apiClient, "f").call('perspective.addLinks', { uuid, links, status, batchId });
5418
+ return __classPrivateFieldGet$9(this, _PerspectiveClient_apiClient, "f").call('perspective.addLinks', { uuid, links, status, batchId });
5359
5419
  }
5360
5420
  async removeLinks(uuid, links, batchId) {
5361
- return __classPrivateFieldGet$8(this, _PerspectiveClient_apiClient, "f").call('perspective.removeLinks', { uuid, links, batchId });
5421
+ return __classPrivateFieldGet$9(this, _PerspectiveClient_apiClient, "f").call('perspective.removeLinks', { uuid, links, batchId });
5362
5422
  }
5363
5423
  async linkMutations(uuid, mutations, status) {
5364
- return __classPrivateFieldGet$8(this, _PerspectiveClient_apiClient, "f").call('perspective.linkMutations', { uuid, mutations, status });
5424
+ return __classPrivateFieldGet$9(this, _PerspectiveClient_apiClient, "f").call('perspective.linkMutations', { uuid, mutations, status });
5365
5425
  }
5366
5426
  async addLinkExpression(uuid, link, status = 'shared', batchId) {
5367
- return __classPrivateFieldGet$8(this, _PerspectiveClient_apiClient, "f").call('perspective.addLinkExpression', { uuid, link, status, batchId });
5427
+ return __classPrivateFieldGet$9(this, _PerspectiveClient_apiClient, "f").call('perspective.addLinkExpression', { uuid, link, status, batchId });
5368
5428
  }
5369
5429
  async updateLink(uuid, oldLink, newLink, batchId) {
5370
- return __classPrivateFieldGet$8(this, _PerspectiveClient_apiClient, "f").call('perspective.updateLink', { uuid, oldLink, newLink, batchId });
5430
+ return __classPrivateFieldGet$9(this, _PerspectiveClient_apiClient, "f").call('perspective.updateLink', { uuid, oldLink, newLink, batchId });
5371
5431
  }
5372
5432
  async removeLink(uuid, link, batchId) {
5373
5433
  delete link.__typename;
5374
5434
  delete link.data.__typename;
5375
5435
  delete link.proof.__typename;
5376
5436
  delete link.status;
5377
- return __classPrivateFieldGet$8(this, _PerspectiveClient_apiClient, "f").call('perspective.removeLink', { uuid, link, batchId });
5437
+ return __classPrivateFieldGet$9(this, _PerspectiveClient_apiClient, "f").call('perspective.removeLink', { uuid, link, batchId });
5378
5438
  }
5379
5439
  async addSdna(uuid, name, sdnaCode, sdnaType, shaclJson) {
5380
- return __classPrivateFieldGet$8(this, _PerspectiveClient_apiClient, "f").call('perspective.addSdna', { uuid, name, sdnaCode: sdnaCode || "", sdnaType, shaclJson });
5440
+ return __classPrivateFieldGet$9(this, _PerspectiveClient_apiClient, "f").call('perspective.addSdna', { uuid, name, sdnaCode: sdnaCode || "", sdnaType, shaclJson });
5381
5441
  }
5382
5442
  async executeCommands(uuid, commands, expression, parameters, batchId) {
5383
- return __classPrivateFieldGet$8(this, _PerspectiveClient_apiClient, "f").call('perspective.executeCommands', { uuid, commands, expression, parameters, batchId });
5443
+ return __classPrivateFieldGet$9(this, _PerspectiveClient_apiClient, "f").call('perspective.executeCommands', { uuid, commands, expression, parameters, batchId });
5384
5444
  }
5385
5445
  async createSubject(uuid, subjectClass, expressionAddress, initialValues, batchId) {
5386
- return __classPrivateFieldGet$8(this, _PerspectiveClient_apiClient, "f").call('perspective.createSubject', { uuid, subjectClass, expressionAddress, initialValues, batchId });
5446
+ return __classPrivateFieldGet$9(this, _PerspectiveClient_apiClient, "f").call('perspective.createSubject', { uuid, subjectClass, expressionAddress, initialValues, batchId });
5387
5447
  }
5388
5448
  async getSubjectData(uuid, subjectClass, expressionAddress) {
5389
- return __classPrivateFieldGet$8(this, _PerspectiveClient_apiClient, "f").call('perspective.getSubjectData', { uuid, subjectClass, expressionAddress });
5449
+ return __classPrivateFieldGet$9(this, _PerspectiveClient_apiClient, "f").call('perspective.getSubjectData', { uuid, subjectClass, expressionAddress });
5390
5450
  }
5391
5451
  // ExpressionClient functions, needed for Subjects:
5392
5452
  async getExpression(expressionURI) {
5393
- return await __classPrivateFieldGet$8(this, _PerspectiveClient_expressionClient, "f").get(expressionURI);
5453
+ return await __classPrivateFieldGet$9(this, _PerspectiveClient_expressionClient, "f").get(expressionURI);
5394
5454
  }
5395
5455
  async createExpression(content, languageAddress) {
5396
- return await __classPrivateFieldGet$8(this, _PerspectiveClient_expressionClient, "f").create(content, languageAddress);
5456
+ return await __classPrivateFieldGet$9(this, _PerspectiveClient_expressionClient, "f").create(content, languageAddress);
5397
5457
  }
5398
5458
  // Subscriptions:
5399
5459
  addPerspectiveAddedListener(cb) {
5400
- __classPrivateFieldGet$8(this, _PerspectiveClient_perspectiveAddedCallbacks, "f").push(cb);
5460
+ __classPrivateFieldGet$9(this, _PerspectiveClient_perspectiveAddedCallbacks, "f").push(cb);
5401
5461
  }
5402
5462
  subscribePerspectiveAdded() {
5403
- const unsub = __classPrivateFieldGet$8(this, _PerspectiveClient_apiClient, "f").subscribe((data) => {
5463
+ const unsub = __classPrivateFieldGet$9(this, _PerspectiveClient_apiClient, "f").subscribe((data) => {
5404
5464
  if (data.type === 'perspective-added') {
5405
- __classPrivateFieldGet$8(this, _PerspectiveClient_perspectiveAddedCallbacks, "f").forEach(cb => cb(data.perspective));
5465
+ __classPrivateFieldGet$9(this, _PerspectiveClient_perspectiveAddedCallbacks, "f").forEach(cb => cb(data.perspective));
5406
5466
  }
5407
5467
  });
5408
- __classPrivateFieldGet$8(this, _PerspectiveClient_unsubscribers, "f").push(unsub);
5468
+ __classPrivateFieldGet$9(this, _PerspectiveClient_unsubscribers, "f").push(unsub);
5409
5469
  }
5410
5470
  addPerspectiveUpdatedListener(cb) {
5411
- __classPrivateFieldGet$8(this, _PerspectiveClient_perspectiveUpdatedCallbacks, "f").push(cb);
5471
+ __classPrivateFieldGet$9(this, _PerspectiveClient_perspectiveUpdatedCallbacks, "f").push(cb);
5412
5472
  }
5413
5473
  subscribePerspectiveUpdated() {
5414
- const unsub = __classPrivateFieldGet$8(this, _PerspectiveClient_apiClient, "f").subscribe((data) => {
5474
+ const unsub = __classPrivateFieldGet$9(this, _PerspectiveClient_apiClient, "f").subscribe((data) => {
5415
5475
  if (data.type === 'perspective-updated') {
5416
- __classPrivateFieldGet$8(this, _PerspectiveClient_perspectiveUpdatedCallbacks, "f").forEach(cb => cb(data.perspective));
5476
+ __classPrivateFieldGet$9(this, _PerspectiveClient_perspectiveUpdatedCallbacks, "f").forEach(cb => cb(data.perspective));
5417
5477
  }
5418
5478
  });
5419
- __classPrivateFieldGet$8(this, _PerspectiveClient_unsubscribers, "f").push(unsub);
5479
+ __classPrivateFieldGet$9(this, _PerspectiveClient_unsubscribers, "f").push(unsub);
5420
5480
  }
5421
5481
  addPerspectiveSyncedListener(cb) {
5422
- __classPrivateFieldGet$8(this, _PerspectiveClient_perspectiveSyncStateChangeCallbacks, "f").push(cb);
5482
+ __classPrivateFieldGet$9(this, _PerspectiveClient_perspectiveSyncStateChangeCallbacks, "f").push(cb);
5423
5483
  }
5424
5484
  async addPerspectiveSyncStateChangeListener(uuid, cb) {
5425
- const unsub = __classPrivateFieldGet$8(this, _PerspectiveClient_apiClient, "f").subscribe((data) => {
5485
+ const unsub = __classPrivateFieldGet$9(this, _PerspectiveClient_apiClient, "f").subscribe((data) => {
5426
5486
  if (data.type === 'sync-state-change' && data.uuid === uuid) {
5427
5487
  cb.forEach(c => c(data.state));
5428
5488
  }
5429
5489
  });
5430
- __classPrivateFieldGet$8(this, _PerspectiveClient_unsubscribers, "f").push(unsub);
5490
+ __classPrivateFieldGet$9(this, _PerspectiveClient_unsubscribers, "f").push(unsub);
5431
5491
  await new Promise(resolve => setTimeout(resolve, 500));
5432
5492
  }
5433
5493
  addPerspectiveRemovedListener(cb) {
5434
- __classPrivateFieldGet$8(this, _PerspectiveClient_perspectiveRemovedCallbacks, "f").push(cb);
5494
+ __classPrivateFieldGet$9(this, _PerspectiveClient_perspectiveRemovedCallbacks, "f").push(cb);
5435
5495
  }
5436
5496
  subscribePerspectiveRemoved() {
5437
- const unsub = __classPrivateFieldGet$8(this, _PerspectiveClient_apiClient, "f").subscribe((data) => {
5497
+ const unsub = __classPrivateFieldGet$9(this, _PerspectiveClient_apiClient, "f").subscribe((data) => {
5438
5498
  if (data.type === 'perspective-removed') {
5439
- __classPrivateFieldGet$8(this, _PerspectiveClient_perspectiveRemovedCallbacks, "f").forEach(cb => cb(data.uuid));
5499
+ __classPrivateFieldGet$9(this, _PerspectiveClient_perspectiveRemovedCallbacks, "f").forEach(cb => cb(data.uuid));
5440
5500
  }
5441
5501
  });
5442
- __classPrivateFieldGet$8(this, _PerspectiveClient_unsubscribers, "f").push(unsub);
5502
+ __classPrivateFieldGet$9(this, _PerspectiveClient_unsubscribers, "f").push(unsub);
5443
5503
  }
5444
5504
  async addPerspectiveLinkAddedListener(uuid, cb) {
5445
- const unsub = __classPrivateFieldGet$8(this, _PerspectiveClient_apiClient, "f").subscribe((data) => {
5505
+ const unsub = __classPrivateFieldGet$9(this, _PerspectiveClient_apiClient, "f").subscribe((data) => {
5446
5506
  if (data.type === 'link-added' && data.perspectiveUuid === uuid) {
5447
5507
  cb.forEach(c => c(data.link));
5448
5508
  }
5449
5509
  });
5450
- let existing = __classPrivateFieldGet$8(this, _PerspectiveClient_linkUnsubscribers, "f").get(uuid) || [];
5510
+ let existing = __classPrivateFieldGet$9(this, _PerspectiveClient_linkUnsubscribers, "f").get(uuid) || [];
5451
5511
  existing.push(unsub);
5452
- __classPrivateFieldGet$8(this, _PerspectiveClient_linkUnsubscribers, "f").set(uuid, existing);
5453
- await __classPrivateFieldGet$8(this, _PerspectiveClient_apiClient, "f").waitForSubscription();
5512
+ __classPrivateFieldGet$9(this, _PerspectiveClient_linkUnsubscribers, "f").set(uuid, existing);
5513
+ await __classPrivateFieldGet$9(this, _PerspectiveClient_apiClient, "f").waitForSubscription();
5454
5514
  }
5455
5515
  async addPerspectiveLinkRemovedListener(uuid, cb) {
5456
- const unsub = __classPrivateFieldGet$8(this, _PerspectiveClient_apiClient, "f").subscribe((data) => {
5516
+ const unsub = __classPrivateFieldGet$9(this, _PerspectiveClient_apiClient, "f").subscribe((data) => {
5457
5517
  if (data.type === 'link-removed' && data.perspectiveUuid === uuid) {
5458
5518
  const link = data.link;
5459
5519
  if (!link.status) {
@@ -5462,13 +5522,13 @@ class PerspectiveClient {
5462
5522
  cb.forEach(c => c(link));
5463
5523
  }
5464
5524
  });
5465
- let existing = __classPrivateFieldGet$8(this, _PerspectiveClient_linkUnsubscribers, "f").get(uuid) || [];
5525
+ let existing = __classPrivateFieldGet$9(this, _PerspectiveClient_linkUnsubscribers, "f").get(uuid) || [];
5466
5526
  existing.push(unsub);
5467
- __classPrivateFieldGet$8(this, _PerspectiveClient_linkUnsubscribers, "f").set(uuid, existing);
5468
- await __classPrivateFieldGet$8(this, _PerspectiveClient_apiClient, "f").waitForSubscription();
5527
+ __classPrivateFieldGet$9(this, _PerspectiveClient_linkUnsubscribers, "f").set(uuid, existing);
5528
+ await __classPrivateFieldGet$9(this, _PerspectiveClient_apiClient, "f").waitForSubscription();
5469
5529
  }
5470
5530
  async addPerspectiveLinkUpdatedListener(uuid, cb) {
5471
- const unsub = __classPrivateFieldGet$8(this, _PerspectiveClient_apiClient, "f").subscribe((data) => {
5531
+ const unsub = __classPrivateFieldGet$9(this, _PerspectiveClient_apiClient, "f").subscribe((data) => {
5472
5532
  if (data.type === 'link-updated' && data.perspectiveUuid === uuid) {
5473
5533
  const newLink = data.newLink;
5474
5534
  const oldLink = data.oldLink;
@@ -5481,23 +5541,163 @@ class PerspectiveClient {
5481
5541
  cb.forEach(c => c(data));
5482
5542
  }
5483
5543
  });
5484
- let existing = __classPrivateFieldGet$8(this, _PerspectiveClient_linkUnsubscribers, "f").get(uuid) || [];
5544
+ let existing = __classPrivateFieldGet$9(this, _PerspectiveClient_linkUnsubscribers, "f").get(uuid) || [];
5485
5545
  existing.push(unsub);
5486
- __classPrivateFieldGet$8(this, _PerspectiveClient_linkUnsubscribers, "f").set(uuid, existing);
5487
- await __classPrivateFieldGet$8(this, _PerspectiveClient_apiClient, "f").waitForSubscription();
5546
+ __classPrivateFieldGet$9(this, _PerspectiveClient_linkUnsubscribers, "f").set(uuid, existing);
5547
+ await __classPrivateFieldGet$9(this, _PerspectiveClient_apiClient, "f").waitForSubscription();
5488
5548
  }
5489
5549
  getNeighbourhoodProxy(uuid) {
5490
- return new NeighbourhoodProxy(__classPrivateFieldGet$8(this, _PerspectiveClient_neighbourhoodClient, "f"), uuid);
5550
+ return new NeighbourhoodProxy(__classPrivateFieldGet$9(this, _PerspectiveClient_neighbourhoodClient, "f"), uuid);
5491
5551
  }
5492
5552
  async createBatch(uuid) {
5493
- return __classPrivateFieldGet$8(this, _PerspectiveClient_apiClient, "f").call('perspective.createBatch', { uuid });
5553
+ return __classPrivateFieldGet$9(this, _PerspectiveClient_apiClient, "f").call('perspective.createBatch', { uuid });
5494
5554
  }
5495
5555
  async commitBatch(uuid, batchId) {
5496
- return __classPrivateFieldGet$8(this, _PerspectiveClient_apiClient, "f").call('perspective.commitBatch', { uuid, batchId });
5556
+ return __classPrivateFieldGet$9(this, _PerspectiveClient_apiClient, "f").call('perspective.commitBatch', { uuid, batchId });
5497
5557
  }
5498
5558
  }
5499
5559
  _PerspectiveClient_apiClient = new WeakMap(), _PerspectiveClient_perspectiveAddedCallbacks = new WeakMap(), _PerspectiveClient_perspectiveUpdatedCallbacks = new WeakMap(), _PerspectiveClient_perspectiveRemovedCallbacks = new WeakMap(), _PerspectiveClient_perspectiveSyncStateChangeCallbacks = new WeakMap(), _PerspectiveClient_expressionClient = new WeakMap(), _PerspectiveClient_neighbourhoodClient = new WeakMap(), _PerspectiveClient_aiClient = new WeakMap(), _PerspectiveClient_unsubscribers = new WeakMap(), _PerspectiveClient_linkUnsubscribers = new WeakMap(), _PerspectiveClient_querySubscriptionUnsubscribers = new WeakMap();
5500
5560
 
5561
+ /**
5562
+ * PersistentCache — two-tier persistent key-value cache abstraction.
5563
+ *
5564
+ * Provides an IndexedDB-backed implementation for browsers and a no-op
5565
+ * NullCache fallback for Node.js / environments without IndexedDB.
5566
+ *
5567
+ * Design goals:
5568
+ * - Lazy open: IDB connection is deferred until first access
5569
+ * - Fire-and-forget writes: put() resolves immediately (best-effort persistence)
5570
+ * - Graceful degradation: all IDB errors resolve (never reject), so callers
5571
+ * never need try/catch around cache operations
5572
+ * - Tree-shakeable: import only what you need
5573
+ */
5574
+ var __classPrivateFieldSet$8 = (undefined && undefined.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {
5575
+ if (kind === "m") throw new TypeError("Private method is not writable");
5576
+ if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
5577
+ if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
5578
+ return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
5579
+ };
5580
+ var __classPrivateFieldGet$8 = (undefined && undefined.__classPrivateFieldGet) || function (receiver, state, kind, f) {
5581
+ if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
5582
+ if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
5583
+ return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
5584
+ };
5585
+ var _IDBCache_instances, _IDBCache_dbName, _IDBCache_storeName, _IDBCache_dbPromise, _IDBCache_version, _IDBCache_open;
5586
+ // ── IndexedDB Implementation ─────────────────────────────────────────
5587
+ class IDBCache {
5588
+ constructor(dbName, storeName) {
5589
+ _IDBCache_instances.add(this);
5590
+ _IDBCache_dbName.set(this, void 0);
5591
+ _IDBCache_storeName.set(this, void 0);
5592
+ _IDBCache_dbPromise.set(this, null);
5593
+ _IDBCache_version.set(this, 1);
5594
+ __classPrivateFieldSet$8(this, _IDBCache_dbName, dbName, "f");
5595
+ __classPrivateFieldSet$8(this, _IDBCache_storeName, storeName, "f");
5596
+ }
5597
+ async get(key) {
5598
+ try {
5599
+ const db = await __classPrivateFieldGet$8(this, _IDBCache_instances, "m", _IDBCache_open).call(this);
5600
+ return new Promise((resolve) => {
5601
+ const tx = db.transaction(__classPrivateFieldGet$8(this, _IDBCache_storeName, "f"), 'readonly');
5602
+ const store = tx.objectStore(__classPrivateFieldGet$8(this, _IDBCache_storeName, "f"));
5603
+ const req = store.get(key);
5604
+ req.onsuccess = () => resolve(req.result ?? undefined);
5605
+ req.onerror = () => resolve(undefined);
5606
+ });
5607
+ }
5608
+ catch {
5609
+ return undefined;
5610
+ }
5611
+ }
5612
+ async put(key, value) {
5613
+ try {
5614
+ const db = await __classPrivateFieldGet$8(this, _IDBCache_instances, "m", _IDBCache_open).call(this);
5615
+ return new Promise((resolve) => {
5616
+ const tx = db.transaction(__classPrivateFieldGet$8(this, _IDBCache_storeName, "f"), 'readwrite');
5617
+ const store = tx.objectStore(__classPrivateFieldGet$8(this, _IDBCache_storeName, "f"));
5618
+ store.put(value, key);
5619
+ tx.oncomplete = () => resolve();
5620
+ tx.onerror = () => resolve(); // fire-and-forget
5621
+ });
5622
+ }
5623
+ catch {
5624
+ // degrade gracefully
5625
+ }
5626
+ }
5627
+ async delete(key) {
5628
+ try {
5629
+ const db = await __classPrivateFieldGet$8(this, _IDBCache_instances, "m", _IDBCache_open).call(this);
5630
+ return new Promise((resolve) => {
5631
+ const tx = db.transaction(__classPrivateFieldGet$8(this, _IDBCache_storeName, "f"), 'readwrite');
5632
+ const store = tx.objectStore(__classPrivateFieldGet$8(this, _IDBCache_storeName, "f"));
5633
+ store.delete(key);
5634
+ tx.oncomplete = () => resolve();
5635
+ tx.onerror = () => resolve();
5636
+ });
5637
+ }
5638
+ catch {
5639
+ // degrade gracefully
5640
+ }
5641
+ }
5642
+ async clear() {
5643
+ try {
5644
+ const db = await __classPrivateFieldGet$8(this, _IDBCache_instances, "m", _IDBCache_open).call(this);
5645
+ return new Promise((resolve) => {
5646
+ const tx = db.transaction(__classPrivateFieldGet$8(this, _IDBCache_storeName, "f"), 'readwrite');
5647
+ const store = tx.objectStore(__classPrivateFieldGet$8(this, _IDBCache_storeName, "f"));
5648
+ store.clear();
5649
+ tx.oncomplete = () => resolve();
5650
+ tx.onerror = () => resolve();
5651
+ });
5652
+ }
5653
+ catch {
5654
+ // degrade gracefully
5655
+ }
5656
+ }
5657
+ }
5658
+ _IDBCache_dbName = new WeakMap(), _IDBCache_storeName = new WeakMap(), _IDBCache_dbPromise = new WeakMap(), _IDBCache_version = new WeakMap(), _IDBCache_instances = new WeakSet(), _IDBCache_open = function _IDBCache_open() {
5659
+ if (!__classPrivateFieldGet$8(this, _IDBCache_dbPromise, "f")) {
5660
+ __classPrivateFieldSet$8(this, _IDBCache_dbPromise, new Promise((resolve, reject) => {
5661
+ const storeName = __classPrivateFieldGet$8(this, _IDBCache_storeName, "f");
5662
+ const req = indexedDB.open(__classPrivateFieldGet$8(this, _IDBCache_dbName, "f"), __classPrivateFieldGet$8(this, _IDBCache_version, "f"));
5663
+ req.onupgradeneeded = () => {
5664
+ const db = req.result;
5665
+ if (!db.objectStoreNames.contains(storeName)) {
5666
+ db.createObjectStore(storeName);
5667
+ }
5668
+ };
5669
+ req.onsuccess = () => resolve(req.result);
5670
+ req.onerror = () => reject(req.error);
5671
+ }), "f");
5672
+ }
5673
+ return __classPrivateFieldGet$8(this, _IDBCache_dbPromise, "f");
5674
+ };
5675
+ // ── NullCache (no-op fallback for Node.js) ───────────────────────────
5676
+ class NullCache {
5677
+ async get(_key) { return undefined; }
5678
+ async put(_key, _value) { }
5679
+ async delete(_key) { }
5680
+ async clear() { }
5681
+ }
5682
+ // ── Factory ──────────────────────────────────────────────────────────
5683
+ /**
5684
+ * Create a PersistentCache backed by IndexedDB (browser) or NullCache (Node.js).
5685
+ *
5686
+ * @param dbName - IndexedDB database name
5687
+ * @param storeName - IndexedDB object store name
5688
+ */
5689
+ function createPersistentCache(dbName, storeName) {
5690
+ try {
5691
+ if (typeof indexedDB !== 'undefined') {
5692
+ return new IDBCache(dbName, storeName);
5693
+ }
5694
+ }
5695
+ catch {
5696
+ // indexedDB access threw (e.g. in a worker with restricted globals)
5697
+ }
5698
+ return new NullCache();
5699
+ }
5700
+
5501
5701
  var __classPrivateFieldSet$7 = (undefined && undefined.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {
5502
5702
  if (kind === "m") throw new TypeError("Private method is not writable");
5503
5703
  if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
@@ -5509,7 +5709,7 @@ var __classPrivateFieldGet$7 = (undefined && undefined.__classPrivateFieldGet) |
5509
5709
  if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
5510
5710
  return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
5511
5711
  };
5512
- var _AgentClient_apiClient, _AgentClient_baseUrl, _AgentClient_token, _AgentClient_appsChangedCallback, _AgentClient_updatedCallbacks, _AgentClient_agentStatusChangedCallbacks, _AgentClient_hostingUserInfoChangedCallbacks, _AgentClient_computeLogUpdatedCallbacks, _AgentClient_unsubscribers;
5712
+ var _AgentClient_apiClient, _AgentClient_baseUrl, _AgentClient_token, _AgentClient_appsChangedCallback, _AgentClient_updatedCallbacks, _AgentClient_agentStatusChangedCallbacks, _AgentClient_hostingUserInfoChangedCallbacks, _AgentClient_computeLogUpdatedCallbacks, _AgentClient_unsubscribers, _AgentClient_memCache, _AgentClient_persistent, _AgentClient_selfDid;
5513
5713
  class AgentClient {
5514
5714
  constructor(baseUrl, token, subscribe = true, sharedApiClient) {
5515
5715
  _AgentClient_apiClient.set(this, void 0);
@@ -5521,6 +5721,13 @@ class AgentClient {
5521
5721
  _AgentClient_hostingUserInfoChangedCallbacks.set(this, void 0);
5522
5722
  _AgentClient_computeLogUpdatedCallbacks.set(this, void 0);
5523
5723
  _AgentClient_unsubscribers.set(this, void 0);
5724
+ // ── byDID cache ────────────────────────────────────────────────────
5725
+ // L1: in-memory promise cache with timestamps for TTL
5726
+ _AgentClient_memCache.set(this, new Map());
5727
+ // L2: persistent cache (IndexedDB in browser, NullCache in Node)
5728
+ _AgentClient_persistent.set(this, void 0);
5729
+ // Self-DID for event-driven invalidation (no TTL for own profile)
5730
+ _AgentClient_selfDid.set(this, null);
5524
5731
  __classPrivateFieldSet$7(this, _AgentClient_baseUrl, baseUrl, "f");
5525
5732
  __classPrivateFieldSet$7(this, _AgentClient_token, token, "f");
5526
5733
  __classPrivateFieldSet$7(this, _AgentClient_apiClient, sharedApiClient || new ApiClient(baseUrl, token), "f");
@@ -5530,6 +5737,7 @@ class AgentClient {
5530
5737
  __classPrivateFieldSet$7(this, _AgentClient_hostingUserInfoChangedCallbacks, [], "f");
5531
5738
  __classPrivateFieldSet$7(this, _AgentClient_computeLogUpdatedCallbacks, [], "f");
5532
5739
  __classPrivateFieldSet$7(this, _AgentClient_unsubscribers, [], "f");
5740
+ __classPrivateFieldSet$7(this, _AgentClient_persistent, createPersistentCache('ad4m-agent-cache', 'agents'), "f");
5533
5741
  if (subscribe) {
5534
5742
  this.subscribeAgentUpdated();
5535
5743
  this.subscribeAgentStatusChanged();
@@ -5563,7 +5771,57 @@ class AgentClient {
5563
5771
  return new AgentStatus(result);
5564
5772
  }
5565
5773
  async byDID(did) {
5566
- return __classPrivateFieldGet$7(this, _AgentClient_apiClient, "f").call('agent.byDid', { did });
5774
+ const now = Date.now();
5775
+ const cached = __classPrivateFieldGet$7(this, _AgentClient_memCache, "f").get(did);
5776
+ if (cached) {
5777
+ const isSelf = did === __classPrivateFieldGet$7(this, _AgentClient_selfDid, "f");
5778
+ // Self-DID: L1 always valid (event-driven invalidation)
5779
+ // Remote DID: L1 valid within TTL
5780
+ if (isSelf || (now - cached.ts) < AgentClient.REMOTE_AGENT_TTL_MS) {
5781
+ return cached.promise;
5782
+ }
5783
+ }
5784
+ // Deduplicate: store the promise immediately so concurrent calls share one RPC
5785
+ const promise = (async () => {
5786
+ // L2: check persistent cache before network
5787
+ const persisted = await __classPrivateFieldGet$7(this, _AgentClient_persistent, "f").get(did);
5788
+ if (persisted) {
5789
+ return persisted;
5790
+ }
5791
+ // L3: network fetch
5792
+ const result = await __classPrivateFieldGet$7(this, _AgentClient_apiClient, "f").call('agent.byDid', { did });
5793
+ __classPrivateFieldGet$7(this, _AgentClient_persistent, "f").put(did, result); // fire-and-forget write to L2
5794
+ return result;
5795
+ })();
5796
+ __classPrivateFieldGet$7(this, _AgentClient_memCache, "f").set(did, { promise, ts: now });
5797
+ // Clean up on failure so next call retries
5798
+ promise.catch(() => {
5799
+ if (__classPrivateFieldGet$7(this, _AgentClient_memCache, "f").get(did)?.promise === promise) {
5800
+ __classPrivateFieldGet$7(this, _AgentClient_memCache, "f").delete(did);
5801
+ }
5802
+ });
5803
+ return promise;
5804
+ }
5805
+ /**
5806
+ * Set the current agent's own DID.
5807
+ * The self-DID receives event-driven invalidation and is never TTL-expired.
5808
+ */
5809
+ setSelfDid(did) {
5810
+ __classPrivateFieldSet$7(this, _AgentClient_selfDid, did, "f");
5811
+ }
5812
+ /**
5813
+ * Invalidate a specific DID's cache entry in both L1 and L2.
5814
+ */
5815
+ invalidateByDid(did) {
5816
+ __classPrivateFieldGet$7(this, _AgentClient_memCache, "f").delete(did);
5817
+ __classPrivateFieldGet$7(this, _AgentClient_persistent, "f").delete(did); // fire-and-forget
5818
+ }
5819
+ /**
5820
+ * Clear the entire L1 (memory) byDID cache.
5821
+ * L2 (IndexedDB) is preserved — agent data remains valid across sessions.
5822
+ */
5823
+ clearByDidCache() {
5824
+ __classPrivateFieldGet$7(this, _AgentClient_memCache, "f").clear();
5567
5825
  }
5568
5826
  async updatePublicPerspective(perspective) {
5569
5827
  const cleanedPerspective = JSON.parse(JSON.stringify(perspective));
@@ -5624,7 +5882,16 @@ class AgentClient {
5624
5882
  subscribeAgentUpdated() {
5625
5883
  const unsub = __classPrivateFieldGet$7(this, _AgentClient_apiClient, "f").subscribe((data) => {
5626
5884
  if (data.type === 'agent-updated') {
5627
- __classPrivateFieldGet$7(this, _AgentClient_updatedCallbacks, "f").forEach((cb) => cb((data.agent || data)));
5885
+ const agent = (data.agent || data);
5886
+ // Update L1 and L2 cache from the event payload
5887
+ if (agent.did) {
5888
+ __classPrivateFieldGet$7(this, _AgentClient_memCache, "f").set(agent.did, {
5889
+ promise: Promise.resolve(agent),
5890
+ ts: Date.now(),
5891
+ });
5892
+ __classPrivateFieldGet$7(this, _AgentClient_persistent, "f").put(agent.did, agent); // fire-and-forget
5893
+ }
5894
+ __classPrivateFieldGet$7(this, _AgentClient_updatedCallbacks, "f").forEach((cb) => cb(agent));
5628
5895
  }
5629
5896
  });
5630
5897
  __classPrivateFieldGet$7(this, _AgentClient_unsubscribers, "f").push(unsub);
@@ -5723,7 +5990,9 @@ class AgentClient {
5723
5990
  return __classPrivateFieldGet$7(this, _AgentClient_apiClient, "f").call('hosting.requestPayment', { amountHOT });
5724
5991
  }
5725
5992
  }
5726
- _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();
5993
+ _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();
5994
+ /** TTL for remote (non-self) agent profiles in L1 cache (ms). */
5995
+ AgentClient.REMOTE_AGENT_TTL_MS = 5 * 60000; // 5 minutes
5727
5996
 
5728
5997
  var __classPrivateFieldSet$6 = (undefined && undefined.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {
5729
5998
  if (kind === "m") throw new TypeError("Private method is not writable");
@@ -6152,13 +6421,22 @@ var __classPrivateFieldGet$3 = (undefined && undefined.__classPrivateFieldGet) |
6152
6421
  if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
6153
6422
  return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
6154
6423
  };
6155
- var _ExpressionClient_apiClient;
6424
+ var _ExpressionClient_instances, _ExpressionClient_apiClient, _ExpressionClient_memCache, _ExpressionClient_inflight, _ExpressionClient_totalMemBytes, _ExpressionClient_persistent, _ExpressionClient_memCacheResult;
6156
6425
  class ExpressionClient {
6157
6426
  constructor(baseUrl, token, sharedApiClient) {
6427
+ _ExpressionClient_instances.add(this);
6158
6428
  _ExpressionClient_apiClient.set(this, void 0);
6429
+ // L1: in-memory LRU cache (hot path, sub-ms)
6430
+ _ExpressionClient_memCache.set(this, new Map());
6431
+ _ExpressionClient_inflight.set(this, new Map());
6432
+ _ExpressionClient_totalMemBytes.set(this, 0);
6433
+ // L2: persistent cache (IndexedDB in browser, NullCache in Node)
6434
+ _ExpressionClient_persistent.set(this, void 0);
6159
6435
  __classPrivateFieldSet$3(this, _ExpressionClient_apiClient, sharedApiClient || new ApiClient(baseUrl, token), "f");
6436
+ __classPrivateFieldSet$3(this, _ExpressionClient_persistent, createPersistentCache('ad4m-expression-cache', 'expressions'), "f");
6160
6437
  }
6161
6438
  async get(url, alwaysGet = false) {
6439
+ // Existing literal fast-path
6162
6440
  if (!alwaysGet) {
6163
6441
  try {
6164
6442
  let literalValue = Literal.fromUrl(url).get();
@@ -6170,10 +6448,85 @@ class ExpressionClient {
6170
6448
  }
6171
6449
  catch (e) { }
6172
6450
  }
6173
- return __classPrivateFieldGet$3(this, _ExpressionClient_apiClient, "f").call('expression.get', { url });
6451
+ // L1: memory hit
6452
+ if (!alwaysGet) {
6453
+ const memHit = __classPrivateFieldGet$3(this, _ExpressionClient_memCache, "f").get(url);
6454
+ if (memHit)
6455
+ return memHit.data;
6456
+ }
6457
+ // Deduplicate in-flight requests
6458
+ if (!alwaysGet) {
6459
+ const existing = __classPrivateFieldGet$3(this, _ExpressionClient_inflight, "f").get(url);
6460
+ if (existing)
6461
+ return existing;
6462
+ }
6463
+ // L2 check + L3 network
6464
+ const promise = (async () => {
6465
+ if (!alwaysGet) {
6466
+ const persisted = await __classPrivateFieldGet$3(this, _ExpressionClient_persistent, "f").get(url);
6467
+ if (persisted) {
6468
+ __classPrivateFieldGet$3(this, _ExpressionClient_instances, "m", _ExpressionClient_memCacheResult).call(this, url, persisted); // promote to L1
6469
+ return persisted;
6470
+ }
6471
+ }
6472
+ // L3: network fetch
6473
+ const result = await __classPrivateFieldGet$3(this, _ExpressionClient_apiClient, "f").call('expression.get', { url });
6474
+ __classPrivateFieldGet$3(this, _ExpressionClient_instances, "m", _ExpressionClient_memCacheResult).call(this, url, result);
6475
+ __classPrivateFieldGet$3(this, _ExpressionClient_persistent, "f").put(url, result); // fire-and-forget write to L2
6476
+ return result;
6477
+ })();
6478
+ __classPrivateFieldGet$3(this, _ExpressionClient_inflight, "f").set(url, promise);
6479
+ try {
6480
+ return await promise;
6481
+ }
6482
+ finally {
6483
+ __classPrivateFieldGet$3(this, _ExpressionClient_inflight, "f").delete(url);
6484
+ }
6174
6485
  }
6175
6486
  async getMany(urls) {
6176
- return __classPrivateFieldGet$3(this, _ExpressionClient_apiClient, "f").call('expression.getMany', { urls });
6487
+ // Check L1 first
6488
+ const results = urls.map(u => __classPrivateFieldGet$3(this, _ExpressionClient_memCache, "f").get(u)?.data ?? null);
6489
+ let uncachedIndices = results
6490
+ .map((r, i) => r === null ? i : -1)
6491
+ .filter(i => i >= 0);
6492
+ if (uncachedIndices.length === 0)
6493
+ return results;
6494
+ // Check L2 for remaining misses
6495
+ const l2Results = await Promise.all(uncachedIndices.map(i => __classPrivateFieldGet$3(this, _ExpressionClient_persistent, "f").get(urls[i])));
6496
+ const stillMissing = [];
6497
+ for (let j = 0; j < uncachedIndices.length; j++) {
6498
+ const idx = uncachedIndices[j];
6499
+ if (l2Results[j]) {
6500
+ results[idx] = l2Results[j];
6501
+ __classPrivateFieldGet$3(this, _ExpressionClient_instances, "m", _ExpressionClient_memCacheResult).call(this, urls[idx], l2Results[j]); // promote to L1
6502
+ }
6503
+ else {
6504
+ stillMissing.push(idx);
6505
+ }
6506
+ }
6507
+ if (stillMissing.length === 0)
6508
+ return results;
6509
+ // L3: fetch only truly uncached URLs
6510
+ const uncachedUrls = stillMissing.map(i => urls[i]);
6511
+ const fetched = await __classPrivateFieldGet$3(this, _ExpressionClient_apiClient, "f").call('expression.getMany', { urls: uncachedUrls });
6512
+ for (let i = 0; i < stillMissing.length; i++) {
6513
+ const idx = stillMissing[i];
6514
+ results[idx] = fetched[i];
6515
+ if (fetched[i]) {
6516
+ __classPrivateFieldGet$3(this, _ExpressionClient_instances, "m", _ExpressionClient_memCacheResult).call(this, uncachedUrls[i], fetched[i]);
6517
+ __classPrivateFieldGet$3(this, _ExpressionClient_persistent, "f").put(uncachedUrls[i], fetched[i]); // fire-and-forget
6518
+ }
6519
+ }
6520
+ return results;
6521
+ }
6522
+ /**
6523
+ * Clear both L1 (memory) and L2 (persistent) expression caches.
6524
+ */
6525
+ clearCache() {
6526
+ __classPrivateFieldGet$3(this, _ExpressionClient_memCache, "f").clear();
6527
+ __classPrivateFieldGet$3(this, _ExpressionClient_inflight, "f").clear();
6528
+ __classPrivateFieldSet$3(this, _ExpressionClient_totalMemBytes, 0, "f");
6529
+ __classPrivateFieldGet$3(this, _ExpressionClient_persistent, "f").clear(); // fire-and-forget
6177
6530
  }
6178
6531
  async getRaw(url) {
6179
6532
  return __classPrivateFieldGet$3(this, _ExpressionClient_apiClient, "f").call('expression.get', { url, raw: true });
@@ -6186,10 +6539,33 @@ class ExpressionClient {
6186
6539
  return __classPrivateFieldGet$3(this, _ExpressionClient_apiClient, "f").call('expression.interactions', { url });
6187
6540
  }
6188
6541
  async interact(url, interactionCall) {
6189
- return __classPrivateFieldGet$3(this, _ExpressionClient_apiClient, "f").call('expression.interact', { url, interactionCall });
6542
+ const result = await __classPrivateFieldGet$3(this, _ExpressionClient_apiClient, "f").call('expression.interact', { url, interactionCall });
6543
+ // Interactions can mutate the expression — invalidate cache so next get() fetches fresh
6544
+ __classPrivateFieldGet$3(this, _ExpressionClient_memCache, "f").delete(url);
6545
+ __classPrivateFieldGet$3(this, _ExpressionClient_inflight, "f").delete(url);
6546
+ __classPrivateFieldGet$3(this, _ExpressionClient_persistent, "f").delete(url); // fire-and-forget
6547
+ return result;
6190
6548
  }
6191
6549
  }
6192
- _ExpressionClient_apiClient = new WeakMap();
6550
+ _ExpressionClient_apiClient = new WeakMap(), _ExpressionClient_memCache = new WeakMap(), _ExpressionClient_inflight = new WeakMap(), _ExpressionClient_totalMemBytes = new WeakMap(), _ExpressionClient_persistent = new WeakMap(), _ExpressionClient_instances = new WeakSet(), _ExpressionClient_memCacheResult = function _ExpressionClient_memCacheResult(url, data) {
6551
+ const size = JSON.stringify(data).length;
6552
+ // Evict oldest entries if we'd exceed limits
6553
+ while (__classPrivateFieldGet$3(this, _ExpressionClient_memCache, "f").size >= ExpressionClient.MAX_MEM_ENTRIES ||
6554
+ __classPrivateFieldGet$3(this, _ExpressionClient_totalMemBytes, "f") + size > ExpressionClient.MAX_MEM_BYTES) {
6555
+ const oldest = __classPrivateFieldGet$3(this, _ExpressionClient_memCache, "f").keys().next().value;
6556
+ if (!oldest)
6557
+ break;
6558
+ const entry = __classPrivateFieldGet$3(this, _ExpressionClient_memCache, "f").get(oldest);
6559
+ __classPrivateFieldSet$3(this, _ExpressionClient_totalMemBytes, __classPrivateFieldGet$3(this, _ExpressionClient_totalMemBytes, "f") - entry.size, "f");
6560
+ __classPrivateFieldGet$3(this, _ExpressionClient_memCache, "f").delete(oldest);
6561
+ }
6562
+ __classPrivateFieldGet$3(this, _ExpressionClient_memCache, "f").set(url, { data, size });
6563
+ __classPrivateFieldSet$3(this, _ExpressionClient_totalMemBytes, __classPrivateFieldGet$3(this, _ExpressionClient_totalMemBytes, "f") + size, "f");
6564
+ };
6565
+ /** Maximum number of entries in the L1 memory cache. */
6566
+ ExpressionClient.MAX_MEM_ENTRIES = 200;
6567
+ /** Maximum total size (in bytes) of L1 memory cache values. */
6568
+ ExpressionClient.MAX_MEM_BYTES = 5 * 1024 * 1024; // 5 MB
6193
6569
 
6194
6570
  var base64Js = {};
6195
6571
 
@@ -13395,721 +13771,202 @@ class AIClient {
13395
13771
  }
13396
13772
  _AIClient_apiClient = new WeakMap(), _AIClient_transcriptionUnsubscribers = new WeakMap(), _AIClient_pendingStreamIds = new WeakMap();
13397
13773
 
13398
- var __classPrivateFieldSet$1 = (undefined && undefined.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {
13399
- if (kind === "m") throw new TypeError("Private method is not writable");
13400
- if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
13401
- if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
13402
- return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
13403
- };
13404
- var __classPrivateFieldGet$1 = (undefined && undefined.__classPrivateFieldGet) || function (receiver, state, kind, f) {
13405
- if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
13406
- if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
13407
- return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
13408
- };
13409
- var _Ad4mClient_baseUrl, _Ad4mClient_token, _Ad4mClient_apiClient, _Ad4mClient_agentClient, _Ad4mClient_expressionClient, _Ad4mClient_languageClient, _Ad4mClient_neighbourhoodClient, _Ad4mClient_perspectiveClient, _Ad4mClient_runtimeClient, _Ad4mClient_aiClient;
13410
13774
  /**
13411
- * Client for the Ad4m interface wrapping WebSocket RPC calls
13412
- * for convenient use in user facing code.
13775
+ * Shared query helpers used by both the Prolog and SPARQL query pipelines.
13776
+ */
13777
+ /**
13778
+ * Resolves the predicate for a parent query.
13413
13779
  *
13414
- * Aggregates the six sub-clients:
13415
- * AgentClient, ExpressionClient, LanguageClient,
13416
- * NeighbourhoodClient, PerspectiveClient and RuntimeClient
13417
- * for the respective functionality.
13780
+ * Uses TS discriminated union narrowing:
13781
+ * - Raw form (`{ id, predicate }`) → predicate used as-is
13782
+ * - Model form (`{ model, id, field? }`) → lookup from relation metadata
13783
+ * - With `field`: direct key lookup
13784
+ * - Without `field`: scan for a relation whose `target()` matches `childCtor`
13418
13785
  */
13419
- class Ad4mClient {
13420
- constructor(baseUrl, token, subscribe = true) {
13421
- _Ad4mClient_baseUrl.set(this, void 0);
13422
- _Ad4mClient_token.set(this, void 0);
13423
- _Ad4mClient_apiClient.set(this, void 0);
13424
- _Ad4mClient_agentClient.set(this, void 0);
13425
- _Ad4mClient_expressionClient.set(this, void 0);
13426
- _Ad4mClient_languageClient.set(this, void 0);
13427
- _Ad4mClient_neighbourhoodClient.set(this, void 0);
13428
- _Ad4mClient_perspectiveClient.set(this, void 0);
13429
- _Ad4mClient_runtimeClient.set(this, void 0);
13430
- _Ad4mClient_aiClient.set(this, void 0);
13431
- __classPrivateFieldSet$1(this, _Ad4mClient_baseUrl, baseUrl, "f");
13432
- __classPrivateFieldSet$1(this, _Ad4mClient_token, token, "f");
13433
- __classPrivateFieldSet$1(this, _Ad4mClient_apiClient, new ApiClient(baseUrl, token), "f");
13434
- __classPrivateFieldSet$1(this, _Ad4mClient_agentClient, new AgentClient(baseUrl, token, subscribe, __classPrivateFieldGet$1(this, _Ad4mClient_apiClient, "f")), "f");
13435
- __classPrivateFieldSet$1(this, _Ad4mClient_expressionClient, new ExpressionClient(baseUrl, token, __classPrivateFieldGet$1(this, _Ad4mClient_apiClient, "f")), "f");
13436
- __classPrivateFieldSet$1(this, _Ad4mClient_languageClient, new LanguageClient(baseUrl, token, __classPrivateFieldGet$1(this, _Ad4mClient_apiClient, "f")), "f");
13437
- __classPrivateFieldSet$1(this, _Ad4mClient_neighbourhoodClient, new NeighbourhoodClient(baseUrl, token, __classPrivateFieldGet$1(this, _Ad4mClient_apiClient, "f")), "f");
13438
- __classPrivateFieldSet$1(this, _Ad4mClient_aiClient, new AIClient(baseUrl, token, subscribe, __classPrivateFieldGet$1(this, _Ad4mClient_apiClient, "f")), "f");
13439
- __classPrivateFieldSet$1(this, _Ad4mClient_perspectiveClient, new PerspectiveClient(baseUrl, token, subscribe, __classPrivateFieldGet$1(this, _Ad4mClient_apiClient, "f")), "f");
13440
- __classPrivateFieldGet$1(this, _Ad4mClient_perspectiveClient, "f").setExpressionClient(__classPrivateFieldGet$1(this, _Ad4mClient_expressionClient, "f"));
13441
- __classPrivateFieldGet$1(this, _Ad4mClient_perspectiveClient, "f").setNeighbourhoodClient(__classPrivateFieldGet$1(this, _Ad4mClient_neighbourhoodClient, "f"));
13442
- __classPrivateFieldGet$1(this, _Ad4mClient_perspectiveClient, "f").setAIClient(__classPrivateFieldGet$1(this, _Ad4mClient_aiClient, "f"));
13443
- __classPrivateFieldSet$1(this, _Ad4mClient_runtimeClient, new RuntimeClient(baseUrl, token, subscribe, __classPrivateFieldGet$1(this, _Ad4mClient_apiClient, "f")), "f");
13444
- }
13445
- get agent() {
13446
- return __classPrivateFieldGet$1(this, _Ad4mClient_agentClient, "f");
13447
- }
13448
- get expression() {
13449
- return __classPrivateFieldGet$1(this, _Ad4mClient_expressionClient, "f");
13450
- }
13451
- get languages() {
13452
- return __classPrivateFieldGet$1(this, _Ad4mClient_languageClient, "f");
13453
- }
13454
- get neighbourhood() {
13455
- return __classPrivateFieldGet$1(this, _Ad4mClient_neighbourhoodClient, "f");
13456
- }
13457
- get perspective() {
13458
- return __classPrivateFieldGet$1(this, _Ad4mClient_perspectiveClient, "f");
13459
- }
13460
- get runtime() {
13461
- return __classPrivateFieldGet$1(this, _Ad4mClient_runtimeClient, "f");
13786
+ function resolveParentPredicate(parent, childCtor) {
13787
+ // Raw form — explicit predicate
13788
+ if ('predicate' in parent)
13789
+ return parent.predicate;
13790
+ // Model form — resolve from relation metadata
13791
+ const { model } = parent;
13792
+ const relMeta = getRelationsMetadata(model);
13793
+ // Direct lookup by field name when provided
13794
+ if (parent.field) {
13795
+ const entry = relMeta[parent.field];
13796
+ if (!entry) {
13797
+ throw new Error(`parent(): field "${parent.field}" is not a registered relation on ${model.name}`);
13798
+ }
13799
+ return entry.predicate;
13462
13800
  }
13463
- get ai() {
13464
- return __classPrivateFieldGet$1(this, _Ad4mClient_aiClient, "f");
13801
+ // Fallback: scan for a relation whose target matches the child class
13802
+ for (const [, entry] of Object.entries(relMeta)) {
13803
+ if (entry.target && entry.target() === childCtor) {
13804
+ return entry.predicate;
13805
+ }
13465
13806
  }
13466
- /** Start event subscriptions (agent-updated, agent-status-changed, apps-changed).
13467
- * Safe to call if subscriptions were deferred at construction (subscribe=false). */
13468
- startSubscriptions() {
13469
- __classPrivateFieldGet$1(this, _Ad4mClient_agentClient, "f").subscribeAgentUpdated();
13470
- __classPrivateFieldGet$1(this, _Ad4mClient_agentClient, "f").subscribeAgentStatusChanged();
13471
- __classPrivateFieldGet$1(this, _Ad4mClient_agentClient, "f").subscribeAppsChanged();
13807
+ throw new Error(`parent(): could not resolve predicate — no relation on ${model.name} targets ${childCtor.name || 'the queried class'}`);
13808
+ }
13809
+
13810
+ /**
13811
+ * JSON Schema → Ad4mModel class builder and related utilities.
13812
+ *
13813
+ * Contains:
13814
+ * - JSON Schema type definitions (JSONSchemaProperty, JSONSchema, JSONSchemaToModelOptions)
13815
+ * - Schema type helpers (normalizeNamespaceString, isArrayType, etc.)
13816
+ * - Predicate / namespace resolution helpers
13817
+ * - `buildModelFromJSONSchema()` — core implementation of `Ad4mModel.fromJSONSchema()`
13818
+ *
13819
+ * @module
13820
+ */
13821
+ // ─── Schema Type Helpers ─────────────────────────────────────────────────────
13822
+ function normalizeNamespaceString(namespace) {
13823
+ if (!namespace)
13824
+ return '';
13825
+ if (namespace.includes('://')) {
13826
+ const [scheme, rest] = namespace.split('://');
13827
+ const path = (rest || '').replace(/\/+$/, '');
13828
+ return `${scheme}://${path}`;
13472
13829
  }
13473
- /** Close all event connections */
13474
- close() {
13475
- __classPrivateFieldGet$1(this, _Ad4mClient_apiClient, "f").closeAll();
13830
+ else {
13831
+ return namespace.replace(/\/+$/, '');
13476
13832
  }
13477
13833
  }
13478
- _Ad4mClient_baseUrl = new WeakMap(), _Ad4mClient_token = new WeakMap(), _Ad4mClient_apiClient = new WeakMap(), _Ad4mClient_agentClient = new WeakMap(), _Ad4mClient_expressionClient = new WeakMap(), _Ad4mClient_languageClient = new WeakMap(), _Ad4mClient_neighbourhoodClient = new WeakMap(), _Ad4mClient_perspectiveClient = new WeakMap(), _Ad4mClient_runtimeClient = new WeakMap(), _Ad4mClient_aiClient = new WeakMap();
13479
-
13480
- exports.ExceptionType = void 0;
13481
- (function (ExceptionType) {
13482
- ExceptionType["LanguageIsNotLoaded"] = "LANGUAGE_IS_NOT_LOADED";
13483
- ExceptionType["ExpressionIsNotVerified"] = "EXPRESSION_IS_NOT_VERIFIED";
13484
- ExceptionType["AgentIsUntrusted"] = "AGENT_IS_UNTRUSTED";
13485
- ExceptionType["CapabilityRequested"] = "CAPABILITY_REQUESTED";
13486
- ExceptionType["InstallNotificationRequest"] = "INSTALL_NOTIFICATION_REQUEST";
13487
- })(exports.ExceptionType || (exports.ExceptionType = {}));
13488
-
13489
- // Unique Language ID with option type
13490
- class LanguageRef {
13491
- constructor(address, name) {
13492
- this.address = address;
13493
- this.name = name;
13834
+ function normalizeSchemaType(type) {
13835
+ if (!type)
13836
+ return undefined;
13837
+ if (typeof type === "string")
13838
+ return type;
13839
+ if (Array.isArray(type) && type.length > 0) {
13840
+ const nonNull = type.find((t) => t !== "null");
13841
+ return nonNull || type[0];
13494
13842
  }
13843
+ return undefined;
13495
13844
  }
13496
-
13497
- // Expression address + unique Language ID = global expression URL
13498
- class ExpressionRef {
13499
- constructor(lang, expr) {
13500
- this.language = lang;
13501
- this.expression = expr;
13502
- }
13845
+ function isSchemaType(schema, expectedType) {
13846
+ return normalizeSchemaType(schema.type) === expectedType;
13503
13847
  }
13504
- // Creates unique expression URI like this:
13505
- // expr:Qm3490gfwe489hf34:Qm90ghjoaw4iehioefwe4ort
13506
- function exprRef2String(ref) {
13507
- if (ref.language.address === 'did')
13508
- return ref.expression.toString();
13509
- else
13510
- return `${ref.language.address}://${ref.expression}`;
13848
+ function isArrayType(schema) {
13849
+ return isSchemaType(schema, "array");
13511
13850
  }
13512
- function parseExprUrl(url) {
13513
- if (url.startsWith("literal:")) {
13514
- const languageRef = new LanguageRef();
13515
- languageRef.address = 'literal';
13516
- languageRef.name = 'literal';
13517
- const content = url.substring(8);
13518
- return new ExpressionRef(languageRef, content);
13519
- }
13520
- const URIregexp = /^([^:^\s]+):\/\/([\s\S]+)$/;
13521
- const URImatches = URIregexp.exec(url);
13522
- if (URImatches && URImatches.length == 3) {
13523
- const language = URImatches[1];
13524
- const expression = URImatches[2];
13525
- const languageRef = new LanguageRef();
13526
- languageRef.address = language;
13527
- const ref = new ExpressionRef(languageRef, expression);
13528
- return ref;
13529
- }
13530
- const DIDregexp = /^did:([^\s]+)$/;
13531
- const DIDmatches = DIDregexp.exec(url);
13532
- if (DIDmatches && DIDmatches.length == 2) {
13533
- const languageRef = new LanguageRef();
13534
- languageRef.address = 'did';
13535
- const ref = new ExpressionRef(languageRef, url);
13536
- return ref;
13537
- }
13538
- throw new Error("Couldn't parse string as expression URL or DID: " + url);
13851
+ function isObjectType(schema) {
13852
+ return isSchemaType(schema, "object");
13539
13853
  }
13540
-
13541
- class Icon {
13542
- constructor(code) {
13543
- this.code = code;
13544
- }
13854
+ function isNumericType(schema) {
13855
+ const normalized = normalizeSchemaType(schema.type);
13856
+ return normalized === "number" || normalized === "integer";
13545
13857
  }
13546
-
13858
+ // ─── Predicate / Namespace Resolution ────────────────────────────────────────
13547
13859
  /**
13548
- * # AD4M Language — client-side types
13549
- *
13550
- * This file only contains the client-visible types that the AD4M REST
13551
- * API exposes on top of a running Language — interaction metadata, online
13552
- * agent records, and the telepresence-signal callback shape.
13553
- *
13554
- * **If you're authoring an AD4M Language**, you don't consume types from
13555
- * here — use [`@coasys/ad4m-ldk`](https://www.npmjs.com/package/@coasys/ad4m-ldk)
13556
- * (or the [Rust ALDK](https://crates.io/crates/ad4m-ldk)), which provide
13557
- * the capability traits, typed runtime-import wrappers, and authoring
13558
- * macros/helpers.
13559
- *
13560
- * The normative interface definition lives in
13561
- * [`docs-src/ad4m-lang.wit`](https://github.com/coasys/ad4m/blob/dev/docs-src/ad4m-lang.wit).
13562
- * The prose spec is
13563
- * [`docs-src/language-interface-spec.md`](https://github.com/coasys/ad4m/blob/dev/docs-src/language-interface-spec.md).
13860
+ * Determines the namespace for predicates using cascading precedence:
13861
+ * 1. Explicit namespace in options
13862
+ * 2. x-ad4m metadata in schema
13863
+ * 3. Infer from schema title
13864
+ * 4. Try to extract from $id
13865
+ * 5. Error if nothing works
13564
13866
  */
13565
- // ----- Interaction metadata --------------------------------------------------
13566
- //
13567
- // Languages optionally publish a list of user-invocable actions per
13568
- // Expression ("interactions"). The runtime surfaces these to UIs via
13569
- // the API as first-class objects.
13570
- class InteractionParameter {
13571
- }
13572
- class InteractionMeta {
13573
- }
13574
- class InteractionCall {
13575
- get parameters() {
13576
- return JSON.parse(this.parametersStringified);
13867
+ function determineNamespace(schema, options) {
13868
+ // 1. Explicit namespace in options (highest precedence)
13869
+ if (options.namespace) {
13870
+ return options.namespace;
13577
13871
  }
13578
- constructor(name, parameters) {
13579
- this.name = name;
13580
- this.parametersStringified = JSON.stringify(parameters);
13872
+ // 2. x-ad4m metadata in schema
13873
+ if (schema["x-ad4m"]?.namespace) {
13874
+ return schema["x-ad4m"].namespace;
13581
13875
  }
13582
- }
13583
- // ----- Telepresence ----------------------------------------------------------
13584
- class OnlineAgent {
13585
- }
13586
-
13587
- class LanguageHandle {
13588
- }
13589
-
13590
- class LanguageMeta {
13591
- }
13592
- class LanguageMetaInput {
13593
- constructor(name, description) {
13594
- this.name = name;
13595
- this.description = description;
13596
- if (!this.description)
13597
- this.description = "";
13876
+ // 3. Infer from schema title
13877
+ if (schema.title) {
13878
+ return `${schema.title.toLowerCase()}://`;
13598
13879
  }
13599
- }
13600
- class LanguageMetaInternal {
13601
- }
13602
- class LanguageExpression extends ExpressionGeneric() {
13603
- }
13604
- class LanguageLanguageInput {
13605
- }
13606
-
13607
- exports.PerspectiveState = void 0;
13608
- (function (PerspectiveState) {
13609
- PerspectiveState["Private"] = "PRIVATE";
13610
- PerspectiveState["NeighboudhoodCreationInitiated"] = "NEIGHBOURHOOD_CREATION_INITIATED";
13611
- PerspectiveState["NeighbourhoodJoinInitiated"] = "NEIGHBOURHOOD_JOIN_INITIATED";
13612
- PerspectiveState["LinkLanguageFailedToInstall"] = "LINK_LANGUAGE_FAILED_TO_INSTALL";
13613
- PerspectiveState["LinkLanguageInstalledButNotSynced"] = "LINK_LANGUAGE_INSTALLED_BUT_NOT_SYNCED";
13614
- PerspectiveState["Synced"] = "SYNCED";
13615
- })(exports.PerspectiveState || (exports.PerspectiveState = {}));
13616
- // This type is used in the REST interface to reference a mutable
13617
- // prespective that is implemented locally by the Ad4m runtime.
13618
- // The UUID is used in mutations to identify the perspective that gets mutated.
13619
- class PerspectiveHandle {
13620
- constructor(uuid, name, state) {
13621
- this.uuid = uuid;
13622
- this.name = name;
13623
- if (state) {
13624
- this.state = state;
13880
+ // 4. Try to extract from $id if it's a URL
13881
+ if (schema.$id) {
13882
+ try {
13883
+ const url = new URL(schema.$id);
13884
+ const pathParts = url.pathname.split('/').filter(p => p);
13885
+ if (pathParts.length > 0) {
13886
+ const lastPart = pathParts[pathParts.length - 1];
13887
+ const baseName = lastPart.replace(/\.schema\.json$/, '').replace(/\.json$/, '');
13888
+ return `${baseName.toLowerCase()}://`;
13889
+ }
13625
13890
  }
13626
- else {
13627
- this.state = exports.PerspectiveState.Private;
13891
+ catch {
13892
+ // If $id is not a valid URL, continue to error
13628
13893
  }
13629
13894
  }
13895
+ // 5. Error if no namespace can be determined
13896
+ throw new Error(`Cannot infer namespace for JSON Schema. Please provide one of:
13897
+ - options.namespace
13898
+ - schema["x-ad4m"].namespace
13899
+ - schema.title
13900
+ - valid schema.$id`);
13630
13901
  }
13631
-
13632
13902
  /**
13633
- * WakerSubscriptionManager — manages live query subscriptions for the waker.
13634
- *
13635
- * Lives in core so it can be imported by both the plugin and integration tests
13636
- * without ESM/CJS import issues.
13637
- *
13638
- * NOTE: keep in sync with plugins/ad4m/wakerSubscriptionManager.ts
13903
+ * Determines the predicate for a specific property using cascading precedence:
13904
+ * 1. Explicit property mapping
13905
+ * 2. x-ad4m metadata in property schema
13906
+ * 3. Predicate template
13907
+ * 4. Custom predicate generator
13908
+ * 5. Default: namespace + property name
13639
13909
  */
13640
- class WakerSubscriptionManager {
13641
- constructor(options) {
13642
- this.proxies = new Map();
13643
- this.activeSubscriptions = new Map();
13644
- this.debounceTimers = new Map();
13645
- /** Per-subscription set of already-processed message addresses (for mention subs)
13646
- * or serialized result hash (for channel-messages subs). */
13647
- this.seenMessages = new Map();
13648
- this.perspectiveClient = options.perspectiveClient;
13649
- this.logger = options.logger;
13650
- this.debounceMs = options.debounceMs ?? 2000;
13651
- this.onWake = options.onWake;
13652
- this.onPersist = options.onPersist;
13653
- this.QuerySubscriptionProxyCtor = options.QuerySubscriptionProxy ?? null;
13654
- this.previousSeenMessages = options.previousSeenMessages ?? {};
13910
+ function determinePredicate(schema, propertyName, propertySchema, namespace, options) {
13911
+ // 1. Explicit property mapping (highest precedence)
13912
+ if (options.propertyMapping?.[propertyName]) {
13913
+ return options.propertyMapping[propertyName];
13655
13914
  }
13656
- /**
13657
- * Create a live SPARQL subscription.
13658
- * If a subscription with the same id already exists, it is disposed first.
13659
- */
13660
- async subscribe(sub) {
13661
- // Dispose existing subscription with same id if any
13662
- this.dispose(sub.id, false);
13663
- if (!this.QuerySubscriptionProxyCtor) {
13664
- throw new Error("WakerSubscriptionManager: QuerySubscriptionProxy must be provided via constructor options");
13665
- }
13666
- const QuerySubscriptionProxy = this.QuerySubscriptionProxyCtor;
13667
- this.logger.info(`[waker] ${sub.id}: creating subscription (perspective=${sub.perspective}, type=${sub.type})`);
13668
- this.logger.info(`[waker] ${sub.id}: SPARQL query:\n${sub.query}`);
13669
- const proxy = new QuerySubscriptionProxy(sub.perspective, sub.query, this.perspectiveClient);
13670
- proxy.isSPARQL = true;
13671
- // Suppress unhandled rejection from proxy.initialized — QuerySubscriptionProxy
13672
- // rejects this promise internally when subscribe() fails, and if nobody catches
13673
- // it before the next microtask it crashes the process.
13674
- if (proxy.initialized && typeof proxy.initialized.catch === "function") {
13675
- proxy.initialized.catch(() => { });
13676
- }
13677
- try {
13678
- await proxy.subscribe();
13679
- await proxy.initialized;
13680
- }
13681
- catch (err) {
13682
- const msg = err?.message ?? String(err);
13683
- this.logger.warn(`[waker] ${sub.id}: subscription failed — ${msg}`);
13684
- try {
13685
- proxy.dispose();
13686
- }
13687
- catch { }
13688
- // Remove from active state so it doesn't get persisted/retried
13689
- this.activeSubscriptions.delete(sub.id);
13690
- this.seenMessages.delete(sub.id);
13691
- this.persist();
13692
- return; // Don't throw — caller should not crash
13693
- }
13694
- this.logger.info(`[waker] ${sub.id}: subscription initialized successfully`);
13695
- // Seed from persisted seen messages so we don't re-wake after restart
13696
- const seen = new Set(this.previousSeenMessages[sub.id] ?? []);
13697
- this.seenMessages.set(sub.id, seen);
13698
- if (seen.size > 0) {
13699
- this.logger.info(`[waker] ${sub.id}: seeded ${seen.size} seen message(s) from persisted state`);
13700
- }
13701
- proxy.onResult(async (result) => {
13702
- this.logger.info(`[waker] ${sub.id}: onResult fired — type=${typeof result}, isArray=${Array.isArray(result)}, value=${String(JSON.stringify(result)).substring(0, 500)}`);
13703
- // Query engine can deliver non-array values (e.g. false) on disconnect/reconnect — ignore them
13704
- if (!Array.isArray(result)) {
13705
- this.logger.warn(`[waker] ${sub.id}: ignoring non-array result: ${JSON.stringify(result)}`);
13706
- return;
13707
- }
13708
- if (sub.type === "mention") {
13709
- // For mention subscriptions: track seen message addresses.
13710
- // Only wake for messages we haven't seen before.
13711
- const currentSeen = this.seenMessages.get(sub.id) ?? new Set();
13712
- const newMessages = [];
13713
- for (const item of result) {
13714
- if (item && item.source && !currentSeen.has(item.source)) {
13715
- newMessages.push(item.source);
13716
- }
13717
- }
13718
- if (newMessages.length === 0) {
13719
- this.logger.info(`[waker] ${sub.id}: all ${result.length} items already seen, skipping`);
13720
- return;
13721
- }
13722
- this.logger.info(`[waker] ${sub.id}: ${newMessages.length} new message(s) out of ${result.length} total`);
13723
- // Resolve parents per new message
13724
- const mentions = [];
13725
- for (const msgAddr of newMessages) {
13726
- const parents = [];
13727
- try {
13728
- const parentQuery = `SELECT ?source WHERE { ?source <ad4m://has_child> <${msgAddr}> . }`;
13729
- this.logger.info(`[waker] ${sub.id}: resolving parents for ${msgAddr}`);
13730
- const parentResult = await this.perspectiveClient.querySparql(sub.perspective, parentQuery);
13731
- if (Array.isArray(parentResult)) {
13732
- for (const link of parentResult) {
13733
- if (link && link.source) {
13734
- parents.push(link.source);
13735
- }
13736
- }
13737
- }
13738
- }
13739
- catch (err) {
13740
- this.logger.warn(`[waker] ${sub.id}: parent resolution failed for ${msgAddr} — ${err?.message ?? err}`);
13741
- }
13742
- this.logger.info(`[waker] ${sub.id}: message ${msgAddr} has ${parents.length} parent(s): ${parents.join(", ")}`);
13743
- mentions.push({ address: msgAddr, parents });
13744
- }
13745
- // Mark all new messages as seen
13746
- for (const addr of newMessages) {
13747
- currentSeen.add(addr);
13748
- }
13749
- this.seenMessages.set(sub.id, currentSeen);
13750
- // Debounce the wake callback
13751
- const existing = this.debounceTimers.get(sub.id);
13752
- if (existing)
13753
- clearTimeout(existing);
13754
- this.debounceTimers.set(sub.id, setTimeout(() => {
13755
- this.onWake(sub, result, mentions);
13756
- this.debounceTimers.delete(sub.id);
13757
- this.persist();
13758
- }, this.debounceMs));
13759
- }
13760
- else {
13761
- // For channel-messages: always notify the agent on every subscription push.
13762
- // No deduplication — the agent reads recent messages itself.
13763
- this.logger.info(`[waker] ${sub.id}: channel update (${result.length} items)`);
13764
- const existing = this.debounceTimers.get(sub.id);
13765
- if (existing)
13766
- clearTimeout(existing);
13767
- this.debounceTimers.set(sub.id, setTimeout(() => {
13768
- this.onWake(sub, result);
13769
- this.debounceTimers.delete(sub.id);
13770
- }, this.debounceMs));
13771
- }
13772
- });
13773
- this.proxies.set(sub.id, proxy);
13774
- this.activeSubscriptions.set(sub.id, sub);
13775
- this.persist();
13776
- this.logger.info(`[waker] Subscription ${sub.id} active (type=${sub.type}, perspective=${sub.perspective})`);
13777
- }
13778
- /**
13779
- * Dispose a single subscription.
13780
- * @param persist — if false, skip calling onPersist (used during batch cleanup).
13781
- */
13782
- dispose(id, persist = true) {
13783
- const proxy = this.proxies.get(id);
13784
- if (proxy) {
13785
- try {
13786
- proxy.dispose();
13787
- }
13788
- catch {
13789
- /* ignore */
13790
- }
13791
- this.proxies.delete(id);
13792
- }
13793
- const timer = this.debounceTimers.get(id);
13794
- if (timer) {
13795
- clearTimeout(timer);
13796
- this.debounceTimers.delete(id);
13797
- }
13798
- this.activeSubscriptions.delete(id);
13799
- this.seenMessages.delete(id);
13800
- if (persist)
13801
- this.persist();
13802
- }
13803
- /** Dispose all active subscriptions. */
13804
- disposeAll() {
13805
- for (const [id] of this.proxies) {
13806
- this.dispose(id, false);
13807
- }
13915
+ // 2. x-ad4m metadata in property schema
13916
+ if (propertySchema["x-ad4m"]?.through) {
13917
+ return propertySchema["x-ad4m"].through;
13808
13918
  }
13809
- /** Get all active subscriptions. */
13810
- getActive() {
13811
- return Array.from(this.activeSubscriptions.values());
13919
+ // 3. Generate from namespace + property name
13920
+ if (options.predicateTemplate) {
13921
+ const normalizedNs = normalizeNamespaceString(namespace);
13922
+ const [scheme, rest] = normalizedNs.includes('://') ? normalizedNs.split('://') : ['', normalizedNs];
13923
+ const nsNoScheme = rest || '';
13924
+ return options.predicateTemplate
13925
+ .replace('${namespace}', nsNoScheme)
13926
+ .replace('${scheme}', scheme)
13927
+ .replace('${ns}', nsNoScheme)
13928
+ .replace('${title}', schema.title || '')
13929
+ .replace('${property}', propertyName);
13812
13930
  }
13813
- /** Check if a subscription exists. */
13814
- has(id) {
13815
- return this.activeSubscriptions.has(id);
13931
+ // 4. Custom predicate generator
13932
+ if (options.predicateGenerator) {
13933
+ return options.predicateGenerator(schema.title || '', propertyName);
13816
13934
  }
13817
- persist() {
13818
- if (this.onPersist) {
13819
- const seen = {};
13820
- for (const [id, set] of this.seenMessages) {
13821
- seen[id] = Array.from(set);
13822
- }
13823
- this.onPersist(this.getActive(), seen);
13824
- }
13935
+ // 5. Default: namespace + property name
13936
+ const normalizedNs = normalizeNamespaceString(namespace);
13937
+ if (normalizedNs.includes('://')) {
13938
+ // For namespaces like "product://", append property directly
13939
+ return `${normalizedNs}${propertyName}`;
13825
13940
  }
13826
- }
13827
-
13828
- class PerspectiveDiff {
13829
- }
13830
- class PerspectiveDiffExpression extends ExpressionGeneric() {
13831
- }
13832
-
13833
- var __classPrivateFieldSet = (undefined && undefined.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {
13834
- if (kind === "m") throw new TypeError("Private method is not writable");
13835
- if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
13836
- if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
13837
- return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
13838
- };
13839
- var __classPrivateFieldGet = (undefined && undefined.__classPrivateFieldGet) || function (receiver, state, kind, f) {
13840
- if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
13841
- if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
13842
- return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
13843
- };
13844
- var _SmartLiteral_perspective, _SmartLiteral_base;
13845
- const SMART_LITERAL_CONTENT_PREDICATE = "smart_literal://content";
13846
- function makeRandomStringID(length) {
13847
- let result = '';
13848
- let characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
13849
- let charactersLength = characters.length;
13850
- for (let i = 0; i < length; i++) {
13851
- result += characters.charAt(Math.floor(Math.random() * charactersLength));
13941
+ else {
13942
+ return `${normalizedNs}://${propertyName}`;
13852
13943
  }
13853
- return result;
13854
13944
  }
13855
- class SmartLiteral {
13856
- constructor(perspective, base) {
13857
- _SmartLiteral_perspective.set(this, void 0);
13858
- _SmartLiteral_base.set(this, void 0);
13859
- __classPrivateFieldSet(this, _SmartLiteral_perspective, perspective, "f");
13860
- __classPrivateFieldSet(this, _SmartLiteral_base, base, "f");
13861
- }
13862
- get base() {
13863
- return __classPrivateFieldGet(this, _SmartLiteral_base, "f");
13864
- }
13865
- static async create(perspective, literal) {
13866
- const base = Literal.from(makeRandomStringID(10)).toUrl();
13867
- const smartLiteral = new SmartLiteral(perspective, base);
13868
- await smartLiteral.set(literal);
13869
- return smartLiteral;
13870
- }
13871
- static async isSmartLiteralBase(perspective, base) {
13872
- let links = await perspective.get(new LinkQuery({
13873
- source: base,
13874
- predicate: SMART_LITERAL_CONTENT_PREDICATE
13875
- }));
13876
- return links.length > 0;
13877
- }
13878
- static async getAllSmartLiterals(perspective) {
13879
- let links = await perspective.get(new LinkQuery({
13880
- predicate: SMART_LITERAL_CONTENT_PREDICATE
13881
- }));
13882
- return links.map(link => new SmartLiteral(perspective, link.data.source));
13945
+ /**
13946
+ * Gets property-specific options using cascading precedence:
13947
+ * 1. Property-specific options
13948
+ * 2. x-ad4m metadata in property
13949
+ * 3. Global option
13950
+ * 4. Default value
13951
+ */
13952
+ function getPropertyOption(propertyName, propertySchema, options, optionName, defaultValue) {
13953
+ // 1. Property-specific options
13954
+ if (options.propertyOptions?.[propertyName]?.[optionName] !== undefined) {
13955
+ return options.propertyOptions[propertyName][optionName];
13883
13956
  }
13884
- async get() {
13885
- let link = await __classPrivateFieldGet(this, _SmartLiteral_perspective, "f").getSingleTarget(new LinkQuery({
13886
- source: __classPrivateFieldGet(this, _SmartLiteral_base, "f"),
13887
- predicate: SMART_LITERAL_CONTENT_PREDICATE
13888
- }));
13889
- if (!link) {
13890
- throw `No content for smart literal ${__classPrivateFieldGet(this, _SmartLiteral_base, "f")}`;
13891
- }
13892
- return Literal.fromUrl(link).get();
13957
+ // 2. x-ad4m metadata in property
13958
+ if (propertySchema["x-ad4m"]?.[optionName] !== undefined) {
13959
+ return propertySchema["x-ad4m"][optionName];
13893
13960
  }
13894
- async set(content) {
13895
- let literal = Literal.from(content);
13896
- await __classPrivateFieldGet(this, _SmartLiteral_perspective, "f").setSingleTarget(new Link({
13897
- source: __classPrivateFieldGet(this, _SmartLiteral_base, "f"),
13898
- predicate: SMART_LITERAL_CONTENT_PREDICATE,
13899
- target: literal.toUrl()
13900
- }));
13961
+ // 3. Global option
13962
+ if (options[optionName] !== undefined) {
13963
+ return options[optionName];
13901
13964
  }
13965
+ // 4. Default value
13966
+ return defaultValue;
13902
13967
  }
13903
- _SmartLiteral_perspective = new WeakMap(), _SmartLiteral_base = new WeakMap();
13904
-
13905
13968
  /**
13906
- * Shared type definitions for the Ad4mModel system.
13907
- *
13908
- * Extracted into a standalone module so that utility files
13909
- * (`query-utils.ts`, `decorators.ts`, etc.) can import types without
13910
- * creating circular runtime dependencies on `Ad4mModel.ts`.
13911
- */
13912
- /** Type guard for IncludeProjection objects. */
13913
- function isIncludeProjection(val) {
13914
- return typeof val === 'object' && val !== null && 'from' in val;
13915
- }
13916
-
13917
- /**
13918
- * Shared query helpers used by both the Prolog and SPARQL query pipelines.
13919
- */
13920
- /**
13921
- * Resolves the predicate for a parent query.
13922
- *
13923
- * Uses TS discriminated union narrowing:
13924
- * - Raw form (`{ id, predicate }`) → predicate used as-is
13925
- * - Model form (`{ model, id, field? }`) → lookup from relation metadata
13926
- * - With `field`: direct key lookup
13927
- * - Without `field`: scan for a relation whose `target()` matches `childCtor`
13928
- */
13929
- function resolveParentPredicate(parent, childCtor) {
13930
- // Raw form — explicit predicate
13931
- if ('predicate' in parent)
13932
- return parent.predicate;
13933
- // Model form — resolve from relation metadata
13934
- const { model } = parent;
13935
- const relMeta = getRelationsMetadata(model);
13936
- // Direct lookup by field name when provided
13937
- if (parent.field) {
13938
- const entry = relMeta[parent.field];
13939
- if (!entry) {
13940
- throw new Error(`parent(): field "${parent.field}" is not a registered relation on ${model.name}`);
13941
- }
13942
- return entry.predicate;
13943
- }
13944
- // Fallback: scan for a relation whose target matches the child class
13945
- for (const [, entry] of Object.entries(relMeta)) {
13946
- if (entry.target && entry.target() === childCtor) {
13947
- return entry.predicate;
13948
- }
13949
- }
13950
- throw new Error(`parent(): could not resolve predicate — no relation on ${model.name} targets ${childCtor.name || 'the queried class'}`);
13951
- }
13952
-
13953
- /**
13954
- * JSON Schema → Ad4mModel class builder and related utilities.
13955
- *
13956
- * Contains:
13957
- * - JSON Schema type definitions (JSONSchemaProperty, JSONSchema, JSONSchemaToModelOptions)
13958
- * - Schema type helpers (normalizeNamespaceString, isArrayType, etc.)
13959
- * - Predicate / namespace resolution helpers
13960
- * - `buildModelFromJSONSchema()` — core implementation of `Ad4mModel.fromJSONSchema()`
13961
- *
13962
- * @module
13963
- */
13964
- // ─── Schema Type Helpers ─────────────────────────────────────────────────────
13965
- function normalizeNamespaceString(namespace) {
13966
- if (!namespace)
13967
- return '';
13968
- if (namespace.includes('://')) {
13969
- const [scheme, rest] = namespace.split('://');
13970
- const path = (rest || '').replace(/\/+$/, '');
13971
- return `${scheme}://${path}`;
13972
- }
13973
- else {
13974
- return namespace.replace(/\/+$/, '');
13975
- }
13976
- }
13977
- function normalizeSchemaType(type) {
13978
- if (!type)
13979
- return undefined;
13980
- if (typeof type === "string")
13981
- return type;
13982
- if (Array.isArray(type) && type.length > 0) {
13983
- const nonNull = type.find((t) => t !== "null");
13984
- return nonNull || type[0];
13985
- }
13986
- return undefined;
13987
- }
13988
- function isSchemaType(schema, expectedType) {
13989
- return normalizeSchemaType(schema.type) === expectedType;
13990
- }
13991
- function isArrayType(schema) {
13992
- return isSchemaType(schema, "array");
13993
- }
13994
- function isObjectType(schema) {
13995
- return isSchemaType(schema, "object");
13996
- }
13997
- function isNumericType(schema) {
13998
- const normalized = normalizeSchemaType(schema.type);
13999
- return normalized === "number" || normalized === "integer";
14000
- }
14001
- // ─── Predicate / Namespace Resolution ────────────────────────────────────────
14002
- /**
14003
- * Determines the namespace for predicates using cascading precedence:
14004
- * 1. Explicit namespace in options
14005
- * 2. x-ad4m metadata in schema
14006
- * 3. Infer from schema title
14007
- * 4. Try to extract from $id
14008
- * 5. Error if nothing works
14009
- */
14010
- function determineNamespace(schema, options) {
14011
- // 1. Explicit namespace in options (highest precedence)
14012
- if (options.namespace) {
14013
- return options.namespace;
14014
- }
14015
- // 2. x-ad4m metadata in schema
14016
- if (schema["x-ad4m"]?.namespace) {
14017
- return schema["x-ad4m"].namespace;
14018
- }
14019
- // 3. Infer from schema title
14020
- if (schema.title) {
14021
- return `${schema.title.toLowerCase()}://`;
14022
- }
14023
- // 4. Try to extract from $id if it's a URL
14024
- if (schema.$id) {
14025
- try {
14026
- const url = new URL(schema.$id);
14027
- const pathParts = url.pathname.split('/').filter(p => p);
14028
- if (pathParts.length > 0) {
14029
- const lastPart = pathParts[pathParts.length - 1];
14030
- const baseName = lastPart.replace(/\.schema\.json$/, '').replace(/\.json$/, '');
14031
- return `${baseName.toLowerCase()}://`;
14032
- }
14033
- }
14034
- catch {
14035
- // If $id is not a valid URL, continue to error
14036
- }
14037
- }
14038
- // 5. Error if no namespace can be determined
14039
- throw new Error(`Cannot infer namespace for JSON Schema. Please provide one of:
14040
- - options.namespace
14041
- - schema["x-ad4m"].namespace
14042
- - schema.title
14043
- - valid schema.$id`);
14044
- }
14045
- /**
14046
- * Determines the predicate for a specific property using cascading precedence:
14047
- * 1. Explicit property mapping
14048
- * 2. x-ad4m metadata in property schema
14049
- * 3. Predicate template
14050
- * 4. Custom predicate generator
14051
- * 5. Default: namespace + property name
14052
- */
14053
- function determinePredicate(schema, propertyName, propertySchema, namespace, options) {
14054
- // 1. Explicit property mapping (highest precedence)
14055
- if (options.propertyMapping?.[propertyName]) {
14056
- return options.propertyMapping[propertyName];
14057
- }
14058
- // 2. x-ad4m metadata in property schema
14059
- if (propertySchema["x-ad4m"]?.through) {
14060
- return propertySchema["x-ad4m"].through;
14061
- }
14062
- // 3. Generate from namespace + property name
14063
- if (options.predicateTemplate) {
14064
- const normalizedNs = normalizeNamespaceString(namespace);
14065
- const [scheme, rest] = normalizedNs.includes('://') ? normalizedNs.split('://') : ['', normalizedNs];
14066
- const nsNoScheme = rest || '';
14067
- return options.predicateTemplate
14068
- .replace('${namespace}', nsNoScheme)
14069
- .replace('${scheme}', scheme)
14070
- .replace('${ns}', nsNoScheme)
14071
- .replace('${title}', schema.title || '')
14072
- .replace('${property}', propertyName);
14073
- }
14074
- // 4. Custom predicate generator
14075
- if (options.predicateGenerator) {
14076
- return options.predicateGenerator(schema.title || '', propertyName);
14077
- }
14078
- // 5. Default: namespace + property name
14079
- const normalizedNs = normalizeNamespaceString(namespace);
14080
- if (normalizedNs.includes('://')) {
14081
- // For namespaces like "product://", append property directly
14082
- return `${normalizedNs}${propertyName}`;
14083
- }
14084
- else {
14085
- return `${normalizedNs}://${propertyName}`;
14086
- }
14087
- }
14088
- /**
14089
- * Gets property-specific options using cascading precedence:
14090
- * 1. Property-specific options
14091
- * 2. x-ad4m metadata in property
14092
- * 3. Global option
14093
- * 4. Default value
14094
- */
14095
- function getPropertyOption(propertyName, propertySchema, options, optionName, defaultValue) {
14096
- // 1. Property-specific options
14097
- if (options.propertyOptions?.[propertyName]?.[optionName] !== undefined) {
14098
- return options.propertyOptions[propertyName][optionName];
14099
- }
14100
- // 2. x-ad4m metadata in property
14101
- if (propertySchema["x-ad4m"]?.[optionName] !== undefined) {
14102
- return propertySchema["x-ad4m"][optionName];
14103
- }
14104
- // 3. Global option
14105
- if (options[optionName] !== undefined) {
14106
- return options[optionName];
14107
- }
14108
- // 4. Default value
14109
- return defaultValue;
14110
- }
14111
- /**
14112
- * Gets default value for a JSON Schema type.
13969
+ * Gets default value for a JSON Schema type.
14113
13970
  */
14114
13971
  function getDefaultValueForType(type) {
14115
13972
  switch (type) {
@@ -14923,25 +14780,25 @@ class ModelQueryBuilder {
14923
14780
  return this;
14924
14781
  }
14925
14782
  /**
14926
- * Opts in to evaluating SPARQL property getters during collection hydration.
14783
+ * Controls whether SPARQL property getters are evaluated during hydration.
14927
14784
  *
14928
- * By default, collection queries skip getter evaluation for performance.
14929
- * Call `.deepQuery()` when you need getter-backed properties in the result set.
14785
+ * By default, collection queries evaluate property getters (deepQuery=true).
14786
+ * Call `.deepQuery(false)` to skip getter evaluation for performance.
14930
14787
  *
14788
+ * @param enabled - Whether to evaluate property getters (default: true)
14931
14789
  * @returns The query builder for chaining
14932
14790
  *
14933
14791
  * @example
14934
14792
  * ```typescript
14935
14793
  * const messages = await Message.query(perspective)
14936
14794
  * .parent(channel)
14937
- * .deepQuery()
14795
+ * .deepQuery(false) // skip property getters for performance
14938
14796
  * .limit(30)
14939
14797
  * .get();
14940
- * // messages[i].replyingTo is populated
14941
14798
  * ```
14942
14799
  */
14943
- deepQuery() {
14944
- this.queryParams.deepQuery = true;
14800
+ deepQuery(enabled = true) {
14801
+ this.queryParams.deepQuery = enabled;
14945
14802
  return this;
14946
14803
  }
14947
14804
  /**
@@ -15086,11 +14943,6 @@ class ModelQueryBuilder {
15086
14943
  // Listen for subscription updates via the same GraphQL subscription channel.
15087
14944
  // When Rust re-runs the model query and finds changed results, it pushes them.
15088
14945
  const unsubscribe = this.perspective.client.subscribeToQueryUpdates(subscriptionId, (rawResult) => {
15089
- // Skip delayed #init# messages — initial data was already returned
15090
- // synchronously from modelSubscribe(). Late init messages contain stale
15091
- // data that would overwrite real subscription updates.
15092
- if (rawResult && rawResult.isInit)
15093
- return;
15094
14946
  try {
15095
14947
  const results = parseResults(rawResult);
15096
14948
  const fp = buildFingerprint(results);
@@ -15103,9 +14955,15 @@ class ModelQueryBuilder {
15103
14955
  console.error('Model subscription update parse error:', e);
15104
14956
  }
15105
14957
  });
15106
- // Set up keepalive
14958
+ // Set up keepalive with failure tracking
14959
+ let keepaliveFailures = 0;
15107
14960
  const keepaliveTimer = setInterval(() => {
15108
- this.perspective.client.keepAliveQuery(this.perspective.uuid, subscriptionId).catch(() => { });
14961
+ this.perspective.client.keepAliveQuery(this.perspective.uuid, subscriptionId).then(() => {
14962
+ keepaliveFailures = 0;
14963
+ }).catch((e) => {
14964
+ keepaliveFailures++;
14965
+ console.warn(`Model subscription keepalive failed (attempt ${keepaliveFailures}) for ${subscriptionId}:`, e);
14966
+ });
15109
14967
  }, 30000);
15110
14968
  // Store dispose function
15111
14969
  this.currentSubscription = {
@@ -15191,8 +15049,6 @@ class ModelQueryBuilder {
15191
15049
  };
15192
15050
  const initialCount = parseCount(initialModelResult);
15193
15051
  const unsubscribe = this.perspective.client.subscribeToQueryUpdates(subscriptionId, (rawResult) => {
15194
- if (rawResult && rawResult.isInit)
15195
- return;
15196
15052
  try {
15197
15053
  callback(parseCount(rawResult));
15198
15054
  }
@@ -15200,8 +15056,14 @@ class ModelQueryBuilder {
15200
15056
  console.error('Count subscription update parse error:', e);
15201
15057
  }
15202
15058
  });
15059
+ let keepaliveFailures = 0;
15203
15060
  const keepaliveTimer = setInterval(() => {
15204
- this.perspective.client.keepAliveQuery(this.perspective.uuid, subscriptionId).catch(() => { });
15061
+ this.perspective.client.keepAliveQuery(this.perspective.uuid, subscriptionId).then(() => {
15062
+ keepaliveFailures = 0;
15063
+ }).catch((e) => {
15064
+ keepaliveFailures++;
15065
+ console.warn(`Count subscription keepalive failed (attempt ${keepaliveFailures}) for ${subscriptionId}:`, e);
15066
+ });
15205
15067
  }, 30000);
15206
15068
  this.currentSubscription = {
15207
15069
  dispose: () => {
@@ -15300,12 +15162,16 @@ class ModelQueryBuilder {
15300
15162
  callback({ results, totalCount, pageSize, pageNumber });
15301
15163
  };
15302
15164
  const unsubscribe = this.perspective.client.subscribeToQueryUpdates(subscriptionId, (rawResult) => {
15303
- if (rawResult && rawResult.isInit)
15304
- return;
15305
15165
  processResults().catch(e => console.error('Paginate subscription error:', e));
15306
15166
  });
15167
+ let keepaliveFailures = 0;
15307
15168
  const keepaliveTimer = setInterval(() => {
15308
- this.perspective.client.keepAliveQuery(this.perspective.uuid, subscriptionId).catch(() => { });
15169
+ this.perspective.client.keepAliveQuery(this.perspective.uuid, subscriptionId).then(() => {
15170
+ keepaliveFailures = 0;
15171
+ }).catch((e) => {
15172
+ keepaliveFailures++;
15173
+ console.warn(`Paginate subscription keepalive failed (attempt ${keepaliveFailures}) for ${subscriptionId}:`, e);
15174
+ });
15309
15175
  }, 30000);
15310
15176
  this.currentSubscription = {
15311
15177
  dispose: () => {
@@ -15330,12 +15196,9 @@ class ModelQueryBuilder {
15330
15196
  /**
15331
15197
  * hydration.ts — Instance hydration helpers extracted from Ad4mModel.
15332
15198
  *
15333
- * After the Rust model_query pipeline migration (Phases 1-13), most hydration
15334
- * logic moved to Rust. This file retains:
15199
+ * After the Rust model_query pipeline migration, most hydration logic moved
15200
+ * to Rust. This file retains:
15335
15201
  * - normalizeValue() — snapshot dirty-tracking
15336
- * - matchesCondition() — JS-side post-filter (used by evaluateCustomGettersForInstance)
15337
- * - evaluateCustomGettersForInstance() — lazy getter evaluation (Ad4mModel.evaluateGetters)
15338
- * - buildConformanceGetter() — conformance SPARQL generation for relation getters
15339
15202
  */
15340
15203
  // ──────────────────────────────────────────────────────────
15341
15204
  // Pure helpers
@@ -15351,299 +15214,47 @@ function normalizeValue(value) {
15351
15214
  }
15352
15215
  return value;
15353
15216
  }
15217
+
15218
+ // ---------------------------------------------------------------------------
15219
+ // Helpers for Rust-side include resolution
15220
+ // ---------------------------------------------------------------------------
15354
15221
  /**
15355
- * Checks if a value matches a where-condition (for post-query filtering).
15222
+ * Recursively enrich relation metadata in the shape with target class shapes
15223
+ * so the Rust endpoint can resolve includes in-process (no extra GraphQL
15224
+ * round-trips per relation).
15356
15225
  */
15357
- function matchesCondition(value, condition) {
15358
- // Handle array values (IN clause)
15359
- if (Array.isArray(condition)) {
15360
- return condition.includes(value);
15361
- }
15362
- // Handle operator object
15363
- if (typeof condition === 'object' && condition !== null) {
15364
- const ops = condition;
15365
- // Special case: 'not' operator (exclusive with other operators)
15366
- if (ops.not !== undefined) {
15367
- if (Array.isArray(ops.not)) {
15368
- return !ops.not.includes(value);
15369
- }
15370
- else {
15371
- return value !== ops.not;
15372
- }
15373
- }
15374
- // Special case: 'between' operator (inclusive range, exclusive with gt/gte/lt/lte)
15375
- if (ops.between !== undefined && Array.isArray(ops.between) && ops.between.length === 2) {
15376
- return value >= ops.between[0] && value <= ops.between[1];
15377
- }
15378
- // For all other operators (gt, gte, lt, lte, contains), we need to check ALL of them
15379
- // and return true only if ALL conditions are satisfied
15380
- let allConditionsMet = true;
15381
- if (ops.gt !== undefined) {
15382
- allConditionsMet = allConditionsMet && (value > ops.gt);
15383
- }
15384
- if (ops.gte !== undefined) {
15385
- allConditionsMet = allConditionsMet && (value >= ops.gte);
15386
- }
15387
- if (ops.lt !== undefined) {
15388
- allConditionsMet = allConditionsMet && (value < ops.lt);
15226
+ function enrichShapeForIncludes(metadata, include, allRelMeta) {
15227
+ for (const [relName, includeVal] of Object.entries(include)) {
15228
+ if (!includeVal)
15229
+ continue;
15230
+ const meta = allRelMeta[relName];
15231
+ if (!meta?.target)
15232
+ continue;
15233
+ const TargetClass = meta.target();
15234
+ // Deep-copy so we don't mutate the cached metadata
15235
+ const targetMeta = JSON.parse(JSON.stringify(TargetClass.getModelMetadata()));
15236
+ // Ensure the relation is in metadata.relations (fallback for edge cases)
15237
+ if (!metadata.relations[relName]) {
15238
+ metadata.relations[relName] = {
15239
+ name: relName,
15240
+ predicate: meta.predicate,
15241
+ direction: meta.kind === 'belongsToMany' || meta.kind === 'belongsToOne'
15242
+ ? 'reverse'
15243
+ : 'forward',
15244
+ };
15389
15245
  }
15390
- if (ops.lte !== undefined) {
15391
- allConditionsMet = allConditionsMet && (value <= ops.lte);
15392
- }
15393
- if (ops.contains !== undefined) {
15394
- if (typeof value === 'string') {
15395
- allConditionsMet = allConditionsMet && value.includes(String(ops.contains));
15396
- }
15397
- else if (Array.isArray(value)) {
15398
- allConditionsMet = allConditionsMet && value.includes(ops.contains);
15399
- }
15400
- else {
15401
- allConditionsMet = false;
15402
- }
15403
- }
15404
- return allConditionsMet;
15405
- }
15406
- // Simple equality
15407
- return value === condition;
15408
- }
15409
- // ──────────────────────────────────────────────────────────
15410
- // SPARQL custom getter evaluation
15411
- // ──────────────────────────────────────────────────────────
15412
- /**
15413
- * Builds a SPARQL conformance getter for a relation whose `target` model
15414
- * is known but no explicit `getter` string was supplied.
15415
- *
15416
- * The generated getter traverses outgoing links matching the relation's
15417
- * predicate and then filters the target nodes to only those that conform to
15418
- * the target model's shape (required properties / flags).
15419
- *
15420
- * Delegates to the shared `buildConformanceFilter()` utility in decorators.ts
15421
- * so the same logic is used at shape-definition time and at query time.
15422
- *
15423
- * @param relationPredicate - The relation's predicate URI (e.g. "flux://entry_type")
15424
- * @param targetClass - The target model class (result of calling the `target()` thunk)
15425
- * @returns A SPARQL expression string, or `undefined` if no conformance
15426
- * conditions could be derived from the target model.
15427
- */
15428
- function buildConformanceGetter(relationPredicate, targetClass) {
15429
- const filter = buildConformanceFilter(relationPredicate, targetClass);
15430
- if (!filter) {
15431
- const targetName = targetClass?.prototype?.className || targetClass?.name || 'unknown';
15432
- console.warn(`[Ad4mModel] buildConformanceGetter: no conditions found for target "${targetName}".`);
15433
- return undefined;
15434
- }
15435
- return filter.getter;
15436
- }
15437
- /**
15438
- * Evaluates custom SurrealQL getters for properties and relations on a specific instance.
15439
- *
15440
- * For relations that declare a `target` but no explicit `getter`, a conformance
15441
- * getter is auto-generated from the target model's metadata (unless `filter: false`).
15442
- */
15443
- async function evaluateCustomGettersForInstance(instance, perspective, metadata, options) {
15444
- `<${instance.id}>`;
15445
- // Build projection filter — when requestedProperties is active, only
15446
- // evaluate getters for fields that are requested (or included).
15447
- const projectionActive = options?.requestedProperties && options.requestedProperties.length > 0;
15448
- const projectionSet = projectionActive ? new Set(options.requestedProperties) : null;
15449
- // Evaluate property getters (skip when caller only wants relation type-filtering)
15450
- if (!options?.skipPropertyGetters) {
15451
- for (const [propName, propMeta] of Object.entries(metadata.properties)) {
15452
- if (projectionSet && !projectionSet.has(propName))
15453
- continue;
15454
- if (propMeta.getter) {
15455
- try {
15456
- const rawGetter = propMeta.getter;
15457
- const getterWithBase = rawGetter.replace(/\?source\b/g, `<${instance.id}>`).replace(/<Base>/g, `<${instance.id}>`).replace(/Base/g, `<${instance.id}>`);
15458
- // If the getter is already SPARQL (starts with SELECT/ASK/CONSTRUCT), execute directly
15459
- const trimmed = getterWithBase.trim().toUpperCase();
15460
- if (trimmed.startsWith('SELECT') || trimmed.startsWith('ASK') || trimmed.startsWith('CONSTRUCT')) {
15461
- const result = await perspective.querySparql(getterWithBase);
15462
- if (trimmed.startsWith('ASK')) {
15463
- instance[propName] = result === true || result === 'true';
15464
- }
15465
- else if (result && result.length > 0) {
15466
- // Get first binding's first value
15467
- const firstRow = result[0];
15468
- const firstKey = Object.keys(firstRow)[0];
15469
- const val = firstRow[firstKey]?.value ?? firstRow[firstKey];
15470
- if (val !== undefined && val !== null && val !== 'None' && val !== '') {
15471
- instance[propName] = val;
15472
- }
15473
- }
15474
- }
15475
- else {
15476
- // Legacy SurrealDB-style getter — safety guard for getters that don't match
15477
- // SPARQL patterns (SELECT/ASK). Logs a warning but does not crash.
15478
- console.warn(`Unsupported legacy getter syntax for property ${propName} — use native SPARQL (SELECT/ASK): ${rawGetter.slice(0, 100)}`);
15479
- }
15480
- }
15481
- catch (error) {
15482
- console.warn(`Failed to evaluate getter for ${propName}:`, error);
15483
- }
15484
- }
15485
- }
15486
- } // end skipPropertyGetters guard
15487
- // Evaluate relation getters (explicit or auto-generated from target)
15488
- for (const [relName, relMeta] of Object.entries(metadata.relations)) {
15489
- // Skip relations excluded by property projection (unless in include map)
15490
- if (projectionSet && !projectionSet.has(relName) && !(options?.include && relName in options.include))
15491
- continue;
15492
- const meta = relMeta;
15493
- // Determine the getter to execute:
15494
- // 1. Explicit `getter` always wins
15495
- // 2. If `target` is set and `filter !== false`, auto-generate conformance getter
15496
- // BUT skip auto-generation for reverse relations (belongsToMany / belongsToOne)
15497
- // because buildConformanceGetter traverses outgoing links which is wrong for
15498
- // reverse relations. Their values are already populated by the reverse link
15499
- // lookup in instancesFromQueryResult / getData.
15500
- let getter = meta.getter;
15501
- if (!getter && meta.where && meta.direction !== 'reverse') {
15502
- try {
15503
- const TargetClass = meta.target?.();
15504
- const targetMetadata = TargetClass
15505
- ? TargetClass.getModelMetadata?.() ?? null
15506
- : null;
15507
- // Check if all where conditions can be SPARQL-filtered.
15508
- // literal-resolved properties store signed expressions (literal:json:{…}),
15509
- // not raw literal:string: IRIs, so SPARQL exact-match fails for them.
15510
- let allSparqlFilterable = true;
15511
- if (targetMetadata) {
15512
- for (const propName of Object.keys(meta.where)) {
15513
- if (['id', 'author', 'timestamp'].includes(propName))
15514
- continue;
15515
- const propMeta = targetMetadata.properties[propName];
15516
- if (propMeta && (!propMeta.resolveLanguage || propMeta.resolveLanguage === 'literal')) {
15517
- allSparqlFilterable = false;
15518
- break;
15519
- }
15520
- }
15521
- }
15522
- else {
15523
- allSparqlFilterable = false;
15524
- }
15525
- if (allSparqlFilterable) {
15526
- const conditions = compileWhereClause(meta.where, targetMetadata);
15527
- if (conditions.length > 0) {
15528
- const escapedPredicate = escapeQueryString(meta.predicate);
15529
- getter = `SELECT ?target WHERE { <Base> <${escapedPredicate}> ?target . ${conditions.join(' ')} }`;
15530
- }
15531
- }
15532
- // If not filterable, fall through to buildConformanceGetter + JS post-filter below
15533
- }
15534
- catch (e) {
15535
- console.warn(`[Ad4mModel] where-clause compilation failed for relation "${relName}":`, e);
15536
- }
15537
- }
15538
- if (!getter && meta.target && meta.filter !== false && meta.direction !== 'reverse') {
15539
- try {
15540
- const TargetClass = meta.target();
15541
- getter = buildConformanceGetter(meta.predicate, TargetClass);
15542
- if (!getter) {
15543
- console.warn(`[Ad4mModel] buildConformanceGetter returned undefined for relation "${relName}" (predicate: "${meta.predicate}")`);
15544
- }
15545
- }
15546
- catch (e) {
15547
- console.warn(`[Ad4mModel] auto-generation failed for relation "${relName}":`, e);
15548
- }
15549
- }
15550
- if (getter) {
15551
- try {
15552
- const getterWithBase = getter.replace(/\?source\b/g, `<${instance.id}>`).replace(/<Base>/g, `<${instance.id}>`).replace(/\bBase\b/g, `<${instance.id}>`);
15553
- const trimmed = getterWithBase.trim().toUpperCase();
15554
- if (trimmed.startsWith('SELECT') || trimmed.startsWith('ASK') || trimmed.startsWith('CONSTRUCT')) {
15555
- // Native SPARQL getter — execute directly
15556
- const result = await perspective.querySparql(getterWithBase);
15557
- if (result && result.length > 0) {
15558
- const values = result.map((r) => {
15559
- const firstKey = Object.keys(r)[0];
15560
- return r[firstKey]?.value ?? r[firstKey];
15561
- }).filter((v) => v !== undefined && v !== null && v !== '' && v !== 'None');
15562
- instance[relName] = values;
15563
- }
15564
- }
15565
- else {
15566
- // Legacy SurrealDB-style getter — safety guard for relation getters that don't
15567
- // match SPARQL patterns (SELECT/ASK). Logs a warning but does not crash.
15568
- console.warn(`Unsupported legacy getter syntax for relation ${relName} — use native SPARQL (SELECT/ASK): ${getter.slice(0, 100)}`);
15569
- }
15570
- }
15571
- catch (error) {
15572
- console.warn(`Failed to evaluate getter for ${relName}:`, error);
15573
- }
15574
- }
15575
- // JS post-filter for where conditions that couldn't be SPARQL-filtered
15576
- // (e.g. literal-resolved properties storing signed expressions)
15577
- const currentValues = instance[relName];
15578
- if (meta.where && Array.isArray(currentValues) && currentValues.length > 0) {
15579
- const TargetClass = meta.target?.();
15580
- if (TargetClass) {
15581
- const filtered = [];
15582
- for (const targetId of currentValues) {
15583
- try {
15584
- const inst = new TargetClass(perspective, targetId);
15585
- await inst.get();
15586
- let matches = true;
15587
- for (const [prop, expected] of Object.entries(meta.where)) {
15588
- if (inst[prop] !== expected) {
15589
- matches = false;
15590
- break;
15591
- }
15592
- }
15593
- if (matches)
15594
- filtered.push(targetId);
15595
- }
15596
- catch {
15597
- // If we can't hydrate, keep the value (conservative)
15598
- filtered.push(targetId);
15599
- }
15600
- }
15601
- instance[relName] = filtered;
15602
- }
15603
- }
15604
- }
15605
- }
15606
-
15607
- // ---------------------------------------------------------------------------
15608
- // Helpers for Rust-side include resolution
15609
- // ---------------------------------------------------------------------------
15610
- /**
15611
- * Recursively enrich relation metadata in the shape with target class shapes
15612
- * so the Rust endpoint can resolve includes in-process (no extra GraphQL
15613
- * round-trips per relation).
15614
- */
15615
- function enrichShapeForIncludes(metadata, include, allRelMeta) {
15616
- for (const [relName, includeVal] of Object.entries(include)) {
15617
- if (!includeVal)
15618
- continue;
15619
- const meta = allRelMeta[relName];
15620
- if (!meta?.target)
15621
- continue;
15622
- const TargetClass = meta.target();
15623
- // Deep-copy so we don't mutate the cached metadata
15624
- const targetMeta = JSON.parse(JSON.stringify(TargetClass.getModelMetadata()));
15625
- // Ensure the relation is in metadata.relations (fallback for edge cases)
15626
- if (!metadata.relations[relName]) {
15627
- metadata.relations[relName] = {
15628
- name: relName,
15629
- predicate: meta.predicate,
15630
- direction: meta.kind === 'belongsToMany' || meta.kind === 'belongsToOne'
15631
- ? 'reverse'
15632
- : 'forward',
15633
- };
15634
- }
15635
- const rel = metadata.relations[relName];
15636
- rel.kind = meta.kind;
15637
- rel.maxCount = meta.maxCount;
15638
- rel.targetShape = targetMeta;
15639
- rel.targetClassName = targetMeta.className;
15640
- // Recurse for nested includes
15641
- const nested = typeof includeVal === 'object' && includeVal !== null
15642
- ? includeVal.include
15643
- : undefined;
15644
- if (nested) {
15645
- const targetRelMeta = getRelationsMetadata(TargetClass);
15646
- enrichShapeForIncludes(targetMeta, nested, targetRelMeta);
15246
+ const rel = metadata.relations[relName];
15247
+ rel.kind = meta.kind;
15248
+ rel.maxCount = meta.maxCount;
15249
+ rel.targetShape = targetMeta;
15250
+ rel.targetClassName = targetMeta.className;
15251
+ // Recurse for nested includes
15252
+ const nested = typeof includeVal === 'object' && includeVal !== null
15253
+ ? includeVal.include
15254
+ : undefined;
15255
+ if (nested) {
15256
+ const targetRelMeta = getRelationsMetadata(TargetClass);
15257
+ enrichShapeForIncludes(targetMeta, nested, targetRelMeta);
15647
15258
  }
15648
15259
  }
15649
15260
  }
@@ -16242,6 +15853,7 @@ class Ad4mModel {
16242
15853
  const query = {
16243
15854
  where: { id: this._baseExpression },
16244
15855
  limit: 1,
15856
+ deepQuery: true, // Single-instance get() always evaluates property getters
16245
15857
  };
16246
15858
  if (opts?.properties)
16247
15859
  query.properties = opts.properties;
@@ -16350,11 +15962,16 @@ class Ad4mModel {
16350
15962
  queryInput.limit = query.limit;
16351
15963
  if (query.count !== undefined)
16352
15964
  queryInput.count = query.count;
15965
+ queryInput.deepQuery = query.deepQuery ?? true;
16353
15966
  if (query.include) {
16354
15967
  const allRelMeta = getRelationsMetadata(this);
16355
15968
  enrichShapeForIncludes(metadata, query.include, allRelMeta);
16356
15969
  }
16357
- // Pre-compute conformance getters (with where-clause support)
15970
+ // Pre-compute conformance getters for Rust-side evaluation.
15971
+ // Where clauses are NOT compiled into getter SPARQL because stored
15972
+ // property values are signed expression envelopes (literal:json:...),
15973
+ // not simple literal:string:X values. Instead, where clauses are
15974
+ // attached as metadata for Rust-side post-evaluation filtering.
16358
15975
  {
16359
15976
  const allRelMeta = getRelationsMetadata(this);
16360
15977
  for (const [relName, relMeta] of Object.entries(metadata.relations)) {
@@ -16367,46 +15984,31 @@ class Ad4mModel {
16367
15984
  try {
16368
15985
  const TargetClass = meta.target();
16369
15986
  const filter = buildConformanceFilter(meta.predicate, TargetClass);
16370
- // Only compile where clauses to SPARQL when the target properties
16371
- // are stored as plain IRIs (not signed expressions). Properties
16372
- // without resolveLanguage or with resolveLanguage='literal' store
16373
- // values as signed JSON envelopes, so SPARQL exact-match fails.
16374
- let whereConditions = [];
15987
+ if (filter) {
15988
+ rel.getter = filter.getter;
15989
+ }
15990
+ // Attach where-clause metadata for Rust-side post-getter filtering
16375
15991
  if (rel.where) {
16376
15992
  try {
16377
15993
  const targetMetadata = TargetClass.getModelMetadata?.() ?? null;
16378
- let allSparqlFilterable = true;
16379
15994
  if (targetMetadata) {
15995
+ const predicates = {};
16380
15996
  for (const propName of Object.keys(rel.where)) {
16381
15997
  if (['id', 'author', 'timestamp'].includes(propName))
16382
15998
  continue;
16383
15999
  const propMeta = targetMetadata.properties[propName];
16384
- if (propMeta && (!propMeta.resolveLanguage || propMeta.resolveLanguage === 'literal')) {
16385
- allSparqlFilterable = false;
16386
- break;
16000
+ if (propMeta?.predicate) {
16001
+ predicates[propName] = propMeta.predicate;
16387
16002
  }
16388
16003
  }
16389
- }
16390
- else {
16391
- allSparqlFilterable = false;
16392
- }
16393
- if (allSparqlFilterable) {
16394
- whereConditions = compileWhereClause(rel.where, targetMetadata);
16004
+ if (Object.keys(predicates).length > 0) {
16005
+ rel.whereFilter = rel.where;
16006
+ rel.wherePredicates = predicates;
16007
+ }
16395
16008
  }
16396
16009
  }
16397
16010
  catch (_) { }
16398
16011
  }
16399
- if (filter) {
16400
- let getter = filter.getter;
16401
- if (whereConditions.length > 0) {
16402
- getter = getter.replace(/ \}$/, ` ${whereConditions.join(' ')} }`);
16403
- }
16404
- rel.getter = getter;
16405
- }
16406
- else if (whereConditions.length > 0) {
16407
- const escapedPred = meta.predicate.replace(/[<>"{}|\\^`\u0000-\u0020]/g, '');
16408
- rel.getter = `SELECT ?target WHERE { <Base> <${escapedPred}> ?target . ${whereConditions.join(' ')} }`;
16409
- }
16410
16012
  }
16411
16013
  catch (_) { }
16412
16014
  }
@@ -16509,6 +16111,7 @@ class Ad4mModel {
16509
16111
  queryInput.limit = query.limit;
16510
16112
  if (query.count !== undefined)
16511
16113
  queryInput.count = query.count;
16114
+ queryInput.deepQuery = query.deepQuery ?? true;
16512
16115
  // Enrich relation metadata with target class shapes for Rust-side
16513
16116
  // include resolution. This eliminates per-relation GraphQL round-trips
16514
16117
  // by letting the Rust endpoint resolve includes in-process.
@@ -16538,48 +16141,33 @@ class Ad4mModel {
16538
16141
  try {
16539
16142
  const TargetClass = meta.target();
16540
16143
  const filter = buildConformanceFilter(meta.predicate, TargetClass);
16541
- // Only compile where clauses to SPARQL when the target properties
16542
- // are stored as plain IRIs (not signed expressions). Properties
16543
- // without resolveLanguage or with resolveLanguage='literal' store
16544
- // values as signed JSON envelopes, so SPARQL exact-match fails.
16545
- let whereConditions = [];
16144
+ if (filter) {
16145
+ rel.getter = filter.getter;
16146
+ }
16147
+ // Attach where-clause metadata for Rust-side post-getter filtering.
16148
+ // Property values are signed expression envelopes (literal:json:...)
16149
+ // and cannot be matched by SPARQL FILTER on the raw IRI.
16546
16150
  if (rel.where) {
16547
16151
  try {
16548
16152
  const targetMetadata = TargetClass.getModelMetadata?.() ?? null;
16549
- let allSparqlFilterable = true;
16550
16153
  if (targetMetadata) {
16154
+ const predicates = {};
16551
16155
  for (const propName of Object.keys(rel.where)) {
16552
16156
  if (['id', 'author', 'timestamp'].includes(propName))
16553
16157
  continue;
16554
16158
  const propMeta = targetMetadata.properties[propName];
16555
- if (propMeta && (!propMeta.resolveLanguage || propMeta.resolveLanguage === 'literal')) {
16556
- allSparqlFilterable = false;
16557
- break;
16159
+ if (propMeta?.predicate) {
16160
+ predicates[propName] = propMeta.predicate;
16558
16161
  }
16559
16162
  }
16560
- }
16561
- else {
16562
- allSparqlFilterable = false;
16563
- }
16564
- if (allSparqlFilterable) {
16565
- whereConditions = compileWhereClause(rel.where, targetMetadata);
16163
+ if (Object.keys(predicates).length > 0) {
16164
+ rel.whereFilter = rel.where;
16165
+ rel.wherePredicates = predicates;
16166
+ }
16566
16167
  }
16567
16168
  }
16568
16169
  catch (_) { /* target metadata unavailable */ }
16569
16170
  }
16570
- if (filter) {
16571
- let getter = filter.getter;
16572
- if (whereConditions.length > 0) {
16573
- // Append where conditions before the closing }
16574
- getter = getter.replace(/ \}$/, ` ${whereConditions.join(' ')} }`);
16575
- }
16576
- rel.getter = getter;
16577
- }
16578
- else if (whereConditions.length > 0) {
16579
- // No conformance filter but where clause exists — build getter from where alone
16580
- const escapedPred = meta.predicate.replace(/[<>"{}|\\^`\u0000-\u0020]/g, '');
16581
- rel.getter = `SELECT ?target WHERE { <Base> <${escapedPred}> ?target . ${whereConditions.join(' ')} }`;
16582
- }
16583
16171
  }
16584
16172
  catch (e) {
16585
16173
  // Target class may not be available; skip silently
@@ -16627,40 +16215,6 @@ class Ad4mModel {
16627
16215
  }
16628
16216
  }));
16629
16217
  }
16630
- // Relation conformance getters are evaluated Rust-side via evaluate_getters()
16631
- // in model_query.rs. However, for relations with non-SPARQL-filterable where
16632
- // clauses (e.g. properties stored as signed expressions), we still need
16633
- // TS-side evaluation as a fallback. Running evaluateCustomGettersForInstance
16634
- // with skipPropertyGetters ensures conformance + JS post-filtering for
16635
- // where clauses that couldn't be compiled to SPARQL.
16636
- const includedRelNames = queryInput.include ? new Set(Object.keys(queryInput.include)) : new Set();
16637
- for (const inst of instances) {
16638
- // Save included relation values that came from Rust hydration
16639
- const savedIncluded = {};
16640
- for (const relName of includedRelNames) {
16641
- if (inst[relName] !== undefined) {
16642
- savedIncluded[relName] = inst[relName];
16643
- }
16644
- }
16645
- await evaluateCustomGettersForInstance(inst, perspective, metadata, {
16646
- skipPropertyGetters: true,
16647
- });
16648
- // Restore hydrated include objects that were overwritten by conformance getters
16649
- for (const [relName, value] of Object.entries(savedIncluded)) {
16650
- inst[relName] = value;
16651
- }
16652
- // Fix cardinality for non-included HasOne/BelongsToOne relations:
16653
- // The conformance getter always produces arrays; unwrap to scalar.
16654
- for (const [relName, relMeta] of Object.entries(metadata.relations)) {
16655
- if (includedRelNames.has(relName))
16656
- continue;
16657
- const kind = relMeta.kind;
16658
- if ((kind === 'hasOne' || kind === 'belongsToOne') && Array.isArray(inst[relName])) {
16659
- const arr = inst[relName];
16660
- inst[relName] = arr.length > 0 ? arr[0] : null;
16661
- }
16662
- }
16663
- }
16664
16218
  // Take snapshots for dirty tracking
16665
16219
  const snapshotRelations = queryInput.include;
16666
16220
  for (const inst of instances) {
@@ -17088,10 +16642,10 @@ class Ad4mModel {
17088
16642
  /**
17089
16643
  * Evaluate SPARQL getters for a batch of instances on demand.
17090
16644
  *
17091
- * Use after a shallow collection query (the default) to resolve
17092
- * getter-backed properties for visible items only. This avoids the
17093
- * O(N × getters) cost of evaluating every getter on every instance in
17094
- * a large collection query.
16645
+ * Since deepQuery defaults to true, property getters are evaluated
16646
+ * automatically during collection queries. Use this method when
16647
+ * deepQuery was explicitly set to false and you want to lazily
16648
+ * resolve getter-backed properties for a subset of instances.
17095
16649
  *
17096
16650
  * @param instances - Array of model instances to evaluate getters on
17097
16651
  * @param perspective - The perspective to query against
@@ -17100,8 +16654,8 @@ class Ad4mModel {
17100
16654
  *
17101
16655
  * @example
17102
16656
  * ```typescript
17103
- * const messages = await Message.findAll(perspective, { parent: channel, limit: 30 });
17104
- * // messages[i].replyingTo is undefined (getter skipped by default)
16657
+ * const messages = await Message.query(perspective).deepQuery(false).limit(30).get();
16658
+ * // messages[i].replyingTo is undefined (getter skipped)
17105
16659
  *
17106
16660
  * // Evaluate getters for the visible subset
17107
16661
  * await Message.evaluateGetters(messages.slice(0, 10), perspective, ['replyingTo']);
@@ -17112,10 +16666,28 @@ class Ad4mModel {
17112
16666
  if (instances.length === 0)
17113
16667
  return;
17114
16668
  const metadata = this.getModelMetadata();
17115
- const opts = propertyNames && propertyNames.length > 0
17116
- ? { requestedProperties: propertyNames }
17117
- : undefined;
17118
- // Determine which property names will actually be evaluated
16669
+ // Pre-compute conformance getters so the shape sent to Rust includes them
16670
+ const allRelMeta = getRelationsMetadata(this);
16671
+ for (const [relName, relMeta] of Object.entries(metadata.relations)) {
16672
+ const rel = relMeta;
16673
+ if (rel.getter || rel.direction === 'reverse' || rel.filter === false)
16674
+ continue;
16675
+ const meta = allRelMeta[relName];
16676
+ if (!meta?.target)
16677
+ continue;
16678
+ try {
16679
+ const TargetClass = meta.target();
16680
+ const filter = buildConformanceFilter(meta.predicate, TargetClass);
16681
+ if (filter)
16682
+ rel.getter = filter.getter;
16683
+ }
16684
+ catch (_) { /* target class may not be available */ }
16685
+ }
16686
+ const shapeJson = JSON.stringify(metadata);
16687
+ const instanceIds = instances.map(inst => inst.id || inst._baseExpression);
16688
+ // Single RPC call evaluates all getters in-process on the executor
16689
+ const result = await perspective.evaluateGetters(metadata.className, instanceIds, shapeJson, propertyNames);
16690
+ // Determine which property names were evaluated for snapshot sync
17119
16691
  const evaluatedPropertyNames = [];
17120
16692
  for (const [propName, propMeta] of Object.entries(metadata.properties)) {
17121
16693
  if (propMeta.getter) {
@@ -17124,13 +16696,24 @@ class Ad4mModel {
17124
16696
  }
17125
16697
  }
17126
16698
  }
16699
+ // Also include relation getters
16700
+ for (const [relName, relMeta] of Object.entries(metadata.relations)) {
16701
+ if (relMeta.getter) {
16702
+ if (!propertyNames || propertyNames.length === 0 || propertyNames.includes(relName)) {
16703
+ evaluatedPropertyNames.push(relName);
16704
+ }
16705
+ }
16706
+ }
16707
+ // Apply results to instances and sync snapshots
17127
16708
  for (const instance of instances) {
17128
- await evaluateCustomGettersForInstance(instance, perspective, metadata, opts);
17129
- // Sync snapshot so isDirty() doesn't flag getter-only changes.
17130
- // evaluateGetters() mutates instances in place, but their snapshots
17131
- // were already taken during hydration. Without this sync, the computed
17132
- // getter values would make isDirty() return true and save() would try
17133
- // to write read-only computed properties.
16709
+ const id = instance.id || instance._baseExpression;
16710
+ const props = result[id];
16711
+ if (props) {
16712
+ for (const [key, value] of Object.entries(props)) {
16713
+ instance[key] = value;
16714
+ }
16715
+ }
16716
+ // Sync snapshot so isDirty() doesn't flag getter-only changes
17134
16717
  const modelInstance = instance;
17135
16718
  if (modelInstance._snapshot) {
17136
16719
  for (const propName of evaluatedPropertyNames) {
@@ -17531,7 +17114,20 @@ class Ad4mModel {
17531
17114
  * @param name - Class name to assign (e.g. "Channel")
17532
17115
  * @returns Generated Ad4mModel subclass, ready for querying
17533
17116
  */
17534
- static fromSHACL(shape, name) {
17117
+ /**
17118
+ * Synthesise an `Ad4mModel` subclass from a SHACL shape.
17119
+ *
17120
+ * @param shape - The SHACL shape to synthesise from.
17121
+ * @param name - The model name (e.g. "Channel").
17122
+ * @param classResolver - Optional thunk factory. When provided, any collection
17123
+ * property that carries a `sh:class` URI will have its `target` wired up lazily:
17124
+ * `target: () => classResolver(localName)`. Because `target` is only called at
17125
+ * query time (inside `enrichShapeForIncludes` / `jsonToModelInstance`), the
17126
+ * resolver just needs to return the correct class by the time a query runs —
17127
+ * making it safe to pass a closure over a registry object that is still being
17128
+ * populated (e.g. the `result` record inside `getModelClasses`).
17129
+ */
17130
+ static fromSHACL(shape, name, classResolver) {
17535
17131
  const DynamicModelClass = class extends this {
17536
17132
  };
17537
17133
  DynamicModelClass.className = name;
@@ -17570,9 +17166,19 @@ class Ad4mModel {
17570
17166
  continue;
17571
17167
  const isCollection = prop.maxCount === undefined || prop.maxCount > 1;
17572
17168
  if (isCollection) {
17169
+ // Derive a lazy `target` thunk when a sh:class URI is present and a
17170
+ // classResolver was supplied. The thunk is evaluated at query time so
17171
+ // it is safe even if the target class hasn't been registered yet.
17172
+ let targetThunk;
17173
+ if (prop.class && classResolver) {
17174
+ const sep = Math.max(prop.class.lastIndexOf('#'), prop.class.lastIndexOf('/'));
17175
+ const localName = sep >= 0 ? prop.class.slice(sep + 1) : prop.class;
17176
+ targetThunk = () => classResolver(localName);
17177
+ }
17573
17178
  setRelationRegistryEntry(DynamicModelClass, prop.name, {
17574
17179
  predicate: prop.path,
17575
17180
  kind: 'hasMany',
17181
+ ...(targetThunk !== undefined && { target: targetThunk }),
17576
17182
  ...(prop.local !== undefined && { local: prop.local }),
17577
17183
  ...(prop.getter !== undefined && { getter: prop.getter }),
17578
17184
  });
@@ -17593,6 +17199,535 @@ class Ad4mModel {
17593
17199
  }
17594
17200
  Ad4mModel.classNamesByClass = new WeakMap();
17595
17201
 
17202
+ var __classPrivateFieldSet$1 = (undefined && undefined.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {
17203
+ if (kind === "m") throw new TypeError("Private method is not writable");
17204
+ if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
17205
+ if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
17206
+ return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
17207
+ };
17208
+ var __classPrivateFieldGet$1 = (undefined && undefined.__classPrivateFieldGet) || function (receiver, state, kind, f) {
17209
+ if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
17210
+ if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
17211
+ return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
17212
+ };
17213
+ var _Ad4mClient_baseUrl, _Ad4mClient_token, _Ad4mClient_apiClient, _Ad4mClient_agentClient, _Ad4mClient_expressionClient, _Ad4mClient_languageClient, _Ad4mClient_neighbourhoodClient, _Ad4mClient_perspectiveClient, _Ad4mClient_runtimeClient, _Ad4mClient_aiClient;
17214
+ /**
17215
+ * Client for the Ad4m interface wrapping WebSocket RPC calls
17216
+ * for convenient use in user facing code.
17217
+ *
17218
+ * Aggregates the six sub-clients:
17219
+ * AgentClient, ExpressionClient, LanguageClient,
17220
+ * NeighbourhoodClient, PerspectiveClient and RuntimeClient
17221
+ * for the respective functionality.
17222
+ */
17223
+ class Ad4mClient {
17224
+ constructor(baseUrl, token, subscribe = true) {
17225
+ _Ad4mClient_baseUrl.set(this, void 0);
17226
+ _Ad4mClient_token.set(this, void 0);
17227
+ _Ad4mClient_apiClient.set(this, void 0);
17228
+ _Ad4mClient_agentClient.set(this, void 0);
17229
+ _Ad4mClient_expressionClient.set(this, void 0);
17230
+ _Ad4mClient_languageClient.set(this, void 0);
17231
+ _Ad4mClient_neighbourhoodClient.set(this, void 0);
17232
+ _Ad4mClient_perspectiveClient.set(this, void 0);
17233
+ _Ad4mClient_runtimeClient.set(this, void 0);
17234
+ _Ad4mClient_aiClient.set(this, void 0);
17235
+ __classPrivateFieldSet$1(this, _Ad4mClient_baseUrl, baseUrl, "f");
17236
+ __classPrivateFieldSet$1(this, _Ad4mClient_token, token, "f");
17237
+ __classPrivateFieldSet$1(this, _Ad4mClient_apiClient, new ApiClient(baseUrl, token), "f");
17238
+ __classPrivateFieldSet$1(this, _Ad4mClient_agentClient, new AgentClient(baseUrl, token, subscribe, __classPrivateFieldGet$1(this, _Ad4mClient_apiClient, "f")), "f");
17239
+ __classPrivateFieldSet$1(this, _Ad4mClient_expressionClient, new ExpressionClient(baseUrl, token, __classPrivateFieldGet$1(this, _Ad4mClient_apiClient, "f")), "f");
17240
+ __classPrivateFieldSet$1(this, _Ad4mClient_languageClient, new LanguageClient(baseUrl, token, __classPrivateFieldGet$1(this, _Ad4mClient_apiClient, "f")), "f");
17241
+ __classPrivateFieldSet$1(this, _Ad4mClient_neighbourhoodClient, new NeighbourhoodClient(baseUrl, token, __classPrivateFieldGet$1(this, _Ad4mClient_apiClient, "f")), "f");
17242
+ __classPrivateFieldSet$1(this, _Ad4mClient_aiClient, new AIClient(baseUrl, token, subscribe, __classPrivateFieldGet$1(this, _Ad4mClient_apiClient, "f")), "f");
17243
+ __classPrivateFieldSet$1(this, _Ad4mClient_perspectiveClient, new PerspectiveClient(baseUrl, token, subscribe, __classPrivateFieldGet$1(this, _Ad4mClient_apiClient, "f")), "f");
17244
+ __classPrivateFieldGet$1(this, _Ad4mClient_perspectiveClient, "f").setExpressionClient(__classPrivateFieldGet$1(this, _Ad4mClient_expressionClient, "f"));
17245
+ __classPrivateFieldGet$1(this, _Ad4mClient_perspectiveClient, "f").setNeighbourhoodClient(__classPrivateFieldGet$1(this, _Ad4mClient_neighbourhoodClient, "f"));
17246
+ __classPrivateFieldGet$1(this, _Ad4mClient_perspectiveClient, "f").setAIClient(__classPrivateFieldGet$1(this, _Ad4mClient_aiClient, "f"));
17247
+ __classPrivateFieldSet$1(this, _Ad4mClient_runtimeClient, new RuntimeClient(baseUrl, token, subscribe, __classPrivateFieldGet$1(this, _Ad4mClient_apiClient, "f")), "f");
17248
+ // Register with AD4M DevTools if the bridge is installed (e.g. browser extension)
17249
+ try {
17250
+ const dt = globalThis.__AD4M_DEVTOOLS__;
17251
+ if (dt) {
17252
+ dt._client = this;
17253
+ dt._Ad4mModel = Ad4mModel;
17254
+ }
17255
+ }
17256
+ catch { }
17257
+ }
17258
+ get agent() {
17259
+ return __classPrivateFieldGet$1(this, _Ad4mClient_agentClient, "f");
17260
+ }
17261
+ get expression() {
17262
+ return __classPrivateFieldGet$1(this, _Ad4mClient_expressionClient, "f");
17263
+ }
17264
+ get languages() {
17265
+ return __classPrivateFieldGet$1(this, _Ad4mClient_languageClient, "f");
17266
+ }
17267
+ get neighbourhood() {
17268
+ return __classPrivateFieldGet$1(this, _Ad4mClient_neighbourhoodClient, "f");
17269
+ }
17270
+ get perspective() {
17271
+ return __classPrivateFieldGet$1(this, _Ad4mClient_perspectiveClient, "f");
17272
+ }
17273
+ get runtime() {
17274
+ return __classPrivateFieldGet$1(this, _Ad4mClient_runtimeClient, "f");
17275
+ }
17276
+ get ai() {
17277
+ return __classPrivateFieldGet$1(this, _Ad4mClient_aiClient, "f");
17278
+ }
17279
+ /** Start event subscriptions (agent-updated, agent-status-changed, apps-changed).
17280
+ * Safe to call if subscriptions were deferred at construction (subscribe=false). */
17281
+ startSubscriptions() {
17282
+ __classPrivateFieldGet$1(this, _Ad4mClient_agentClient, "f").subscribeAgentUpdated();
17283
+ __classPrivateFieldGet$1(this, _Ad4mClient_agentClient, "f").subscribeAgentStatusChanged();
17284
+ __classPrivateFieldGet$1(this, _Ad4mClient_agentClient, "f").subscribeAppsChanged();
17285
+ }
17286
+ /** Close all event connections and clear in-memory caches */
17287
+ close() {
17288
+ __classPrivateFieldGet$1(this, _Ad4mClient_agentClient, "f").clearByDidCache();
17289
+ __classPrivateFieldGet$1(this, _Ad4mClient_apiClient, "f").closeAll();
17290
+ }
17291
+ }
17292
+ _Ad4mClient_baseUrl = new WeakMap(), _Ad4mClient_token = new WeakMap(), _Ad4mClient_apiClient = new WeakMap(), _Ad4mClient_agentClient = new WeakMap(), _Ad4mClient_expressionClient = new WeakMap(), _Ad4mClient_languageClient = new WeakMap(), _Ad4mClient_neighbourhoodClient = new WeakMap(), _Ad4mClient_perspectiveClient = new WeakMap(), _Ad4mClient_runtimeClient = new WeakMap(), _Ad4mClient_aiClient = new WeakMap();
17293
+
17294
+ exports.ExceptionType = void 0;
17295
+ (function (ExceptionType) {
17296
+ ExceptionType["LanguageIsNotLoaded"] = "LANGUAGE_IS_NOT_LOADED";
17297
+ ExceptionType["ExpressionIsNotVerified"] = "EXPRESSION_IS_NOT_VERIFIED";
17298
+ ExceptionType["AgentIsUntrusted"] = "AGENT_IS_UNTRUSTED";
17299
+ ExceptionType["CapabilityRequested"] = "CAPABILITY_REQUESTED";
17300
+ ExceptionType["InstallNotificationRequest"] = "INSTALL_NOTIFICATION_REQUEST";
17301
+ })(exports.ExceptionType || (exports.ExceptionType = {}));
17302
+
17303
+ // Unique Language ID with option type
17304
+ class LanguageRef {
17305
+ constructor(address, name) {
17306
+ this.address = address;
17307
+ this.name = name;
17308
+ }
17309
+ }
17310
+
17311
+ // Expression address + unique Language ID = global expression URL
17312
+ class ExpressionRef {
17313
+ constructor(lang, expr) {
17314
+ this.language = lang;
17315
+ this.expression = expr;
17316
+ }
17317
+ }
17318
+ // Creates unique expression URI like this:
17319
+ // expr:Qm3490gfwe489hf34:Qm90ghjoaw4iehioefwe4ort
17320
+ function exprRef2String(ref) {
17321
+ if (ref.language.address === 'did')
17322
+ return ref.expression.toString();
17323
+ else
17324
+ return `${ref.language.address}://${ref.expression}`;
17325
+ }
17326
+ function parseExprUrl(url) {
17327
+ if (url.startsWith("literal:")) {
17328
+ const languageRef = new LanguageRef();
17329
+ languageRef.address = 'literal';
17330
+ languageRef.name = 'literal';
17331
+ const content = url.substring(8);
17332
+ return new ExpressionRef(languageRef, content);
17333
+ }
17334
+ const URIregexp = /^([^:^\s]+):\/\/([\s\S]+)$/;
17335
+ const URImatches = URIregexp.exec(url);
17336
+ if (URImatches && URImatches.length == 3) {
17337
+ const language = URImatches[1];
17338
+ const expression = URImatches[2];
17339
+ const languageRef = new LanguageRef();
17340
+ languageRef.address = language;
17341
+ const ref = new ExpressionRef(languageRef, expression);
17342
+ return ref;
17343
+ }
17344
+ const DIDregexp = /^did:([^\s]+)$/;
17345
+ const DIDmatches = DIDregexp.exec(url);
17346
+ if (DIDmatches && DIDmatches.length == 2) {
17347
+ const languageRef = new LanguageRef();
17348
+ languageRef.address = 'did';
17349
+ const ref = new ExpressionRef(languageRef, url);
17350
+ return ref;
17351
+ }
17352
+ throw new Error("Couldn't parse string as expression URL or DID: " + url);
17353
+ }
17354
+
17355
+ class Icon {
17356
+ constructor(code) {
17357
+ this.code = code;
17358
+ }
17359
+ }
17360
+
17361
+ /**
17362
+ * # AD4M Language — client-side types
17363
+ *
17364
+ * This file only contains the client-visible types that the AD4M REST
17365
+ * API exposes on top of a running Language — interaction metadata, online
17366
+ * agent records, and the telepresence-signal callback shape.
17367
+ *
17368
+ * **If you're authoring an AD4M Language**, you don't consume types from
17369
+ * here — use [`@coasys/ad4m-ldk`](https://www.npmjs.com/package/@coasys/ad4m-ldk)
17370
+ * (or the [Rust ALDK](https://crates.io/crates/ad4m-ldk)), which provide
17371
+ * the capability traits, typed runtime-import wrappers, and authoring
17372
+ * macros/helpers.
17373
+ *
17374
+ * The normative interface definition lives in
17375
+ * [`docs-src/ad4m-lang.wit`](https://github.com/coasys/ad4m/blob/dev/docs-src/ad4m-lang.wit).
17376
+ * The prose spec is
17377
+ * [`docs-src/language-interface-spec.md`](https://github.com/coasys/ad4m/blob/dev/docs-src/language-interface-spec.md).
17378
+ */
17379
+ // ----- Interaction metadata --------------------------------------------------
17380
+ //
17381
+ // Languages optionally publish a list of user-invocable actions per
17382
+ // Expression ("interactions"). The runtime surfaces these to UIs via
17383
+ // the API as first-class objects.
17384
+ class InteractionParameter {
17385
+ }
17386
+ class InteractionMeta {
17387
+ }
17388
+ class InteractionCall {
17389
+ get parameters() {
17390
+ return JSON.parse(this.parametersStringified);
17391
+ }
17392
+ constructor(name, parameters) {
17393
+ this.name = name;
17394
+ this.parametersStringified = JSON.stringify(parameters);
17395
+ }
17396
+ }
17397
+ // ----- Telepresence ----------------------------------------------------------
17398
+ class OnlineAgent {
17399
+ }
17400
+
17401
+ class LanguageHandle {
17402
+ }
17403
+
17404
+ class LanguageMeta {
17405
+ }
17406
+ class LanguageMetaInput {
17407
+ constructor(name, description) {
17408
+ this.name = name;
17409
+ this.description = description;
17410
+ if (!this.description)
17411
+ this.description = "";
17412
+ }
17413
+ }
17414
+ class LanguageMetaInternal {
17415
+ }
17416
+ class LanguageExpression extends ExpressionGeneric() {
17417
+ }
17418
+ class LanguageLanguageInput {
17419
+ }
17420
+
17421
+ exports.PerspectiveState = void 0;
17422
+ (function (PerspectiveState) {
17423
+ PerspectiveState["Private"] = "PRIVATE";
17424
+ PerspectiveState["NeighboudhoodCreationInitiated"] = "NEIGHBOURHOOD_CREATION_INITIATED";
17425
+ PerspectiveState["NeighbourhoodJoinInitiated"] = "NEIGHBOURHOOD_JOIN_INITIATED";
17426
+ PerspectiveState["LinkLanguageFailedToInstall"] = "LINK_LANGUAGE_FAILED_TO_INSTALL";
17427
+ PerspectiveState["LinkLanguageInstalledButNotSynced"] = "LINK_LANGUAGE_INSTALLED_BUT_NOT_SYNCED";
17428
+ PerspectiveState["Synced"] = "SYNCED";
17429
+ })(exports.PerspectiveState || (exports.PerspectiveState = {}));
17430
+ // This type is used in the REST interface to reference a mutable
17431
+ // prespective that is implemented locally by the Ad4m runtime.
17432
+ // The UUID is used in mutations to identify the perspective that gets mutated.
17433
+ class PerspectiveHandle {
17434
+ constructor(uuid, name, state) {
17435
+ this.uuid = uuid;
17436
+ this.name = name;
17437
+ if (state) {
17438
+ this.state = state;
17439
+ }
17440
+ else {
17441
+ this.state = exports.PerspectiveState.Private;
17442
+ }
17443
+ }
17444
+ }
17445
+
17446
+ /**
17447
+ * WakerSubscriptionManager — manages live query subscriptions for the waker.
17448
+ *
17449
+ * Lives in core so it can be imported by both the plugin and integration tests
17450
+ * without ESM/CJS import issues.
17451
+ *
17452
+ * NOTE: keep in sync with plugins/ad4m/wakerSubscriptionManager.ts
17453
+ */
17454
+ class WakerSubscriptionManager {
17455
+ constructor(options) {
17456
+ this.proxies = new Map();
17457
+ this.activeSubscriptions = new Map();
17458
+ this.debounceTimers = new Map();
17459
+ /** Per-subscription set of already-processed message addresses (for mention subs)
17460
+ * or serialized result hash (for channel-messages subs). */
17461
+ this.seenMessages = new Map();
17462
+ this.perspectiveClient = options.perspectiveClient;
17463
+ this.logger = options.logger;
17464
+ this.debounceMs = options.debounceMs ?? 2000;
17465
+ this.onWake = options.onWake;
17466
+ this.onPersist = options.onPersist;
17467
+ this.QuerySubscriptionProxyCtor = options.QuerySubscriptionProxy ?? null;
17468
+ this.previousSeenMessages = options.previousSeenMessages ?? {};
17469
+ }
17470
+ /**
17471
+ * Create a live SPARQL subscription.
17472
+ * If a subscription with the same id already exists, it is disposed first.
17473
+ */
17474
+ async subscribe(sub) {
17475
+ // Dispose existing subscription with same id if any
17476
+ this.dispose(sub.id, false);
17477
+ if (!this.QuerySubscriptionProxyCtor) {
17478
+ throw new Error("WakerSubscriptionManager: QuerySubscriptionProxy must be provided via constructor options");
17479
+ }
17480
+ const QuerySubscriptionProxy = this.QuerySubscriptionProxyCtor;
17481
+ this.logger.info(`[waker] ${sub.id}: creating subscription (perspective=${sub.perspective}, type=${sub.type})`);
17482
+ this.logger.info(`[waker] ${sub.id}: SPARQL query:\n${sub.query}`);
17483
+ const proxy = new QuerySubscriptionProxy(sub.perspective, sub.query, this.perspectiveClient);
17484
+ proxy.isSPARQL = true;
17485
+ // Suppress unhandled rejection from proxy.initialized — QuerySubscriptionProxy
17486
+ // rejects this promise internally when subscribe() fails, and if nobody catches
17487
+ // it before the next microtask it crashes the process.
17488
+ if (proxy.initialized && typeof proxy.initialized.catch === "function") {
17489
+ proxy.initialized.catch(() => { });
17490
+ }
17491
+ try {
17492
+ await proxy.subscribe();
17493
+ await proxy.initialized;
17494
+ }
17495
+ catch (err) {
17496
+ const msg = err?.message ?? String(err);
17497
+ this.logger.warn(`[waker] ${sub.id}: subscription failed — ${msg}`);
17498
+ try {
17499
+ proxy.dispose();
17500
+ }
17501
+ catch { }
17502
+ // Remove from active state so it doesn't get persisted/retried
17503
+ this.activeSubscriptions.delete(sub.id);
17504
+ this.seenMessages.delete(sub.id);
17505
+ this.persist();
17506
+ return; // Don't throw — caller should not crash
17507
+ }
17508
+ this.logger.info(`[waker] ${sub.id}: subscription initialized successfully`);
17509
+ // Seed from persisted seen messages so we don't re-wake after restart
17510
+ const seen = new Set(this.previousSeenMessages[sub.id] ?? []);
17511
+ this.seenMessages.set(sub.id, seen);
17512
+ if (seen.size > 0) {
17513
+ this.logger.info(`[waker] ${sub.id}: seeded ${seen.size} seen message(s) from persisted state`);
17514
+ }
17515
+ proxy.onResult(async (result) => {
17516
+ this.logger.info(`[waker] ${sub.id}: onResult fired — type=${typeof result}, isArray=${Array.isArray(result)}, value=${String(JSON.stringify(result)).substring(0, 500)}`);
17517
+ // Query engine can deliver non-array values (e.g. false) on disconnect/reconnect — ignore them
17518
+ if (!Array.isArray(result)) {
17519
+ this.logger.warn(`[waker] ${sub.id}: ignoring non-array result: ${JSON.stringify(result)}`);
17520
+ return;
17521
+ }
17522
+ if (sub.type === "mention") {
17523
+ // For mention subscriptions: track seen message addresses.
17524
+ // Only wake for messages we haven't seen before.
17525
+ const currentSeen = this.seenMessages.get(sub.id) ?? new Set();
17526
+ const newMessages = [];
17527
+ for (const item of result) {
17528
+ if (item && item.source && !currentSeen.has(item.source)) {
17529
+ newMessages.push(item.source);
17530
+ }
17531
+ }
17532
+ if (newMessages.length === 0) {
17533
+ this.logger.info(`[waker] ${sub.id}: all ${result.length} items already seen, skipping`);
17534
+ return;
17535
+ }
17536
+ this.logger.info(`[waker] ${sub.id}: ${newMessages.length} new message(s) out of ${result.length} total`);
17537
+ // Resolve parents per new message
17538
+ const mentions = [];
17539
+ for (const msgAddr of newMessages) {
17540
+ const parents = [];
17541
+ try {
17542
+ const parentQuery = `SELECT ?source WHERE { ?source <ad4m://has_child> <${msgAddr}> . }`;
17543
+ this.logger.info(`[waker] ${sub.id}: resolving parents for ${msgAddr}`);
17544
+ const parentResult = await this.perspectiveClient.querySparql(sub.perspective, parentQuery);
17545
+ if (Array.isArray(parentResult)) {
17546
+ for (const link of parentResult) {
17547
+ if (link && link.source) {
17548
+ parents.push(link.source);
17549
+ }
17550
+ }
17551
+ }
17552
+ }
17553
+ catch (err) {
17554
+ this.logger.warn(`[waker] ${sub.id}: parent resolution failed for ${msgAddr} — ${err?.message ?? err}`);
17555
+ }
17556
+ this.logger.info(`[waker] ${sub.id}: message ${msgAddr} has ${parents.length} parent(s): ${parents.join(", ")}`);
17557
+ mentions.push({ address: msgAddr, parents });
17558
+ }
17559
+ // Mark all new messages as seen
17560
+ for (const addr of newMessages) {
17561
+ currentSeen.add(addr);
17562
+ }
17563
+ this.seenMessages.set(sub.id, currentSeen);
17564
+ // Debounce the wake callback
17565
+ const existing = this.debounceTimers.get(sub.id);
17566
+ if (existing)
17567
+ clearTimeout(existing);
17568
+ this.debounceTimers.set(sub.id, setTimeout(() => {
17569
+ this.onWake(sub, result, mentions);
17570
+ this.debounceTimers.delete(sub.id);
17571
+ this.persist();
17572
+ }, this.debounceMs));
17573
+ }
17574
+ else {
17575
+ // For channel-messages: always notify the agent on every subscription push.
17576
+ // No deduplication — the agent reads recent messages itself.
17577
+ this.logger.info(`[waker] ${sub.id}: channel update (${result.length} items)`);
17578
+ const existing = this.debounceTimers.get(sub.id);
17579
+ if (existing)
17580
+ clearTimeout(existing);
17581
+ this.debounceTimers.set(sub.id, setTimeout(() => {
17582
+ this.onWake(sub, result);
17583
+ this.debounceTimers.delete(sub.id);
17584
+ }, this.debounceMs));
17585
+ }
17586
+ });
17587
+ this.proxies.set(sub.id, proxy);
17588
+ this.activeSubscriptions.set(sub.id, sub);
17589
+ this.persist();
17590
+ this.logger.info(`[waker] Subscription ${sub.id} active (type=${sub.type}, perspective=${sub.perspective})`);
17591
+ }
17592
+ /**
17593
+ * Dispose a single subscription.
17594
+ * @param persist — if false, skip calling onPersist (used during batch cleanup).
17595
+ */
17596
+ dispose(id, persist = true) {
17597
+ const proxy = this.proxies.get(id);
17598
+ if (proxy) {
17599
+ try {
17600
+ proxy.dispose();
17601
+ }
17602
+ catch {
17603
+ /* ignore */
17604
+ }
17605
+ this.proxies.delete(id);
17606
+ }
17607
+ const timer = this.debounceTimers.get(id);
17608
+ if (timer) {
17609
+ clearTimeout(timer);
17610
+ this.debounceTimers.delete(id);
17611
+ }
17612
+ this.activeSubscriptions.delete(id);
17613
+ this.seenMessages.delete(id);
17614
+ if (persist)
17615
+ this.persist();
17616
+ }
17617
+ /** Dispose all active subscriptions. */
17618
+ disposeAll() {
17619
+ for (const [id] of this.proxies) {
17620
+ this.dispose(id, false);
17621
+ }
17622
+ }
17623
+ /** Get all active subscriptions. */
17624
+ getActive() {
17625
+ return Array.from(this.activeSubscriptions.values());
17626
+ }
17627
+ /** Check if a subscription exists. */
17628
+ has(id) {
17629
+ return this.activeSubscriptions.has(id);
17630
+ }
17631
+ persist() {
17632
+ if (this.onPersist) {
17633
+ const seen = {};
17634
+ for (const [id, set] of this.seenMessages) {
17635
+ seen[id] = Array.from(set);
17636
+ }
17637
+ this.onPersist(this.getActive(), seen);
17638
+ }
17639
+ }
17640
+ }
17641
+
17642
+ class PerspectiveDiff {
17643
+ }
17644
+ class PerspectiveDiffExpression extends ExpressionGeneric() {
17645
+ }
17646
+
17647
+ var __classPrivateFieldSet = (undefined && undefined.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {
17648
+ if (kind === "m") throw new TypeError("Private method is not writable");
17649
+ if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
17650
+ if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
17651
+ return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
17652
+ };
17653
+ var __classPrivateFieldGet = (undefined && undefined.__classPrivateFieldGet) || function (receiver, state, kind, f) {
17654
+ if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
17655
+ if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
17656
+ return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
17657
+ };
17658
+ var _SmartLiteral_perspective, _SmartLiteral_base;
17659
+ const SMART_LITERAL_CONTENT_PREDICATE = "smart_literal://content";
17660
+ function makeRandomStringID(length) {
17661
+ let result = '';
17662
+ let characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
17663
+ let charactersLength = characters.length;
17664
+ for (let i = 0; i < length; i++) {
17665
+ result += characters.charAt(Math.floor(Math.random() * charactersLength));
17666
+ }
17667
+ return result;
17668
+ }
17669
+ class SmartLiteral {
17670
+ constructor(perspective, base) {
17671
+ _SmartLiteral_perspective.set(this, void 0);
17672
+ _SmartLiteral_base.set(this, void 0);
17673
+ __classPrivateFieldSet(this, _SmartLiteral_perspective, perspective, "f");
17674
+ __classPrivateFieldSet(this, _SmartLiteral_base, base, "f");
17675
+ }
17676
+ get base() {
17677
+ return __classPrivateFieldGet(this, _SmartLiteral_base, "f");
17678
+ }
17679
+ static async create(perspective, literal) {
17680
+ const base = Literal.from(makeRandomStringID(10)).toUrl();
17681
+ const smartLiteral = new SmartLiteral(perspective, base);
17682
+ await smartLiteral.set(literal);
17683
+ return smartLiteral;
17684
+ }
17685
+ static async isSmartLiteralBase(perspective, base) {
17686
+ let links = await perspective.get(new LinkQuery({
17687
+ source: base,
17688
+ predicate: SMART_LITERAL_CONTENT_PREDICATE
17689
+ }));
17690
+ return links.length > 0;
17691
+ }
17692
+ static async getAllSmartLiterals(perspective) {
17693
+ let links = await perspective.get(new LinkQuery({
17694
+ predicate: SMART_LITERAL_CONTENT_PREDICATE
17695
+ }));
17696
+ return links.map(link => new SmartLiteral(perspective, link.data.source));
17697
+ }
17698
+ async get() {
17699
+ let link = await __classPrivateFieldGet(this, _SmartLiteral_perspective, "f").getSingleTarget(new LinkQuery({
17700
+ source: __classPrivateFieldGet(this, _SmartLiteral_base, "f"),
17701
+ predicate: SMART_LITERAL_CONTENT_PREDICATE
17702
+ }));
17703
+ if (!link) {
17704
+ throw `No content for smart literal ${__classPrivateFieldGet(this, _SmartLiteral_base, "f")}`;
17705
+ }
17706
+ return Literal.fromUrl(link).get();
17707
+ }
17708
+ async set(content) {
17709
+ let literal = Literal.from(content);
17710
+ await __classPrivateFieldGet(this, _SmartLiteral_perspective, "f").setSingleTarget(new Link({
17711
+ source: __classPrivateFieldGet(this, _SmartLiteral_base, "f"),
17712
+ predicate: SMART_LITERAL_CONTENT_PREDICATE,
17713
+ target: literal.toUrl()
17714
+ }));
17715
+ }
17716
+ }
17717
+ _SmartLiteral_perspective = new WeakMap(), _SmartLiteral_base = new WeakMap();
17718
+
17719
+ /**
17720
+ * Shared type definitions for the Ad4mModel system.
17721
+ *
17722
+ * Extracted into a standalone module so that utility files
17723
+ * (`query-utils.ts`, `decorators.ts`, etc.) can import types without
17724
+ * creating circular runtime dependencies on `Ad4mModel.ts`.
17725
+ */
17726
+ /** Type guard for IncludeProjection objects. */
17727
+ function isIncludeProjection(val) {
17728
+ return typeof val === 'object' && val !== null && 'from' in val;
17729
+ }
17730
+
17596
17731
  class Neighbourhood {
17597
17732
  constructor(linkLanguage, meta) {
17598
17733
  this.linkLanguage = linkLanguage;
@@ -17661,6 +17796,7 @@ exports.Flag = Flag;
17661
17796
  exports.HasMany = HasMany;
17662
17797
  exports.HasOne = HasOne;
17663
17798
  exports.HostingUserInfo = HostingUserInfo;
17799
+ exports.IDBCache = IDBCache;
17664
17800
  exports.Icon = Icon;
17665
17801
  exports.ImportResult = ImportResult;
17666
17802
  exports.ImportStats = ImportStats;
@@ -17695,6 +17831,7 @@ exports.NeighbourhoodExpression = NeighbourhoodExpression;
17695
17831
  exports.NeighbourhoodProxy = NeighbourhoodProxy;
17696
17832
  exports.Notification = Notification;
17697
17833
  exports.NotificationInput = NotificationInput;
17834
+ exports.NullCache = NullCache;
17698
17835
  exports.OnlineAgent = OnlineAgent;
17699
17836
  exports.Optional = Optional;
17700
17837
  exports.PaymentRequestResult = PaymentRequestResult;
@@ -17728,7 +17865,6 @@ exports.VerificationRequestResult = VerificationRequestResult;
17728
17865
  exports.VoiceActivityParamsInput = VoiceActivityParamsInput;
17729
17866
  exports.WakerSubscriptionManager = WakerSubscriptionManager;
17730
17867
  exports.buildConformanceFilter = buildConformanceFilter;
17731
- exports.buildConformanceGetter = buildConformanceGetter;
17732
17868
  exports.buildModelFromJSONSchema = buildModelFromJSONSchema;
17733
17869
  exports.buildPaginationSubquery = buildPaginationSubquery;
17734
17870
  exports.buildSDNA = buildSDNA;
@@ -17739,10 +17875,10 @@ exports.buildWhereCondition = buildWhereCondition;
17739
17875
  exports.capSentence = capSentence;
17740
17876
  exports.clearQueryCache = clearQueryCache;
17741
17877
  exports.compileWhereClause = compileWhereClause;
17878
+ exports.createPersistentCache = createPersistentCache;
17742
17879
  exports.determineNamespace = determineNamespace;
17743
17880
  exports.determinePredicate = determinePredicate;
17744
17881
  exports.escapeQueryString = escapeQueryString;
17745
- exports.evaluateCustomGettersForInstance = evaluateCustomGettersForInstance;
17746
17882
  exports.exprRef2String = exprRef2String;
17747
17883
  exports.formatList = formatList;
17748
17884
  exports.formatQueryValue = formatQueryValue;
@@ -17763,7 +17899,6 @@ exports.isNumericType = isNumericType;
17763
17899
  exports.isObjectType = isObjectType;
17764
17900
  exports.isSchemaType = isSchemaType;
17765
17901
  exports.linkEqual = linkEqual;
17766
- exports.matchesCondition = matchesCondition;
17767
17902
  exports.normalizeNamespaceString = normalizeNamespaceString;
17768
17903
  exports.normalizeSchemaType = normalizeSchemaType;
17769
17904
  exports.normalizeValue = normalizeValue;