@coasys/ad4m 0.13.0-test-7 → 0.13.0-test-8

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