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

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 (347) hide show
  1. package/README.md +2 -25
  2. package/jest-setup.ts +1 -1
  3. package/lib/index.cjs +2805 -10556
  4. package/lib/index.js +2513 -10322
  5. package/lib/src/Ad4mClient.d.ts +7 -3
  6. package/lib/src/Ad4mClient.js +29 -13
  7. package/lib/src/agent/Agent.js +26 -272
  8. package/lib/src/agent/AgentClient.d.ts +10 -21
  9. package/lib/src/agent/AgentClient.js +75 -427
  10. package/lib/src/agent/AgentStatus.js +2 -37
  11. package/lib/src/ai/AIClient.d.ts +12 -4
  12. package/lib/src/ai/AIClient.js +81 -285
  13. package/lib/src/ai/AITypes.d.ts +55 -0
  14. package/lib/src/ai/AITypes.js +18 -0
  15. package/lib/src/ai/Tasks.js +10 -133
  16. package/lib/src/apiClient.d.ts +52 -0
  17. package/lib/src/apiClient.js +231 -0
  18. package/lib/src/expression/Expression.d.ts +1 -1
  19. package/lib/src/expression/Expression.js +13 -122
  20. package/lib/src/expression/ExpressionClient.d.ts +3 -3
  21. package/lib/src/expression/ExpressionClient.js +13 -76
  22. package/lib/src/expression/ExpressionRef.js +2 -25
  23. package/lib/src/generated/api/AIModelLoadingStatus.d.ts +7 -0
  24. package/lib/src/generated/api/AIModelLoadingStatus.js +2 -0
  25. package/lib/src/generated/api/AddLinkExpressionRequest.d.ts +6 -0
  26. package/lib/src/generated/api/AddLinkExpressionRequest.js +1 -0
  27. package/lib/src/generated/api/AddLinkRequest.d.ts +6 -0
  28. package/lib/src/generated/api/AddLinkRequest.js +1 -0
  29. package/lib/src/generated/api/AddLinksBulkRequest.d.ts +6 -0
  30. package/lib/src/generated/api/AddLinksBulkRequest.js +1 -0
  31. package/lib/src/generated/api/AddSdnaRequest.d.ts +6 -0
  32. package/lib/src/generated/api/AddSdnaRequest.js +2 -0
  33. package/lib/src/generated/api/ApplyTemplateRequest.d.ts +4 -0
  34. package/lib/src/generated/api/ApplyTemplateRequest.js +2 -0
  35. package/lib/src/generated/api/AuthInfoInput.d.ts +10 -0
  36. package/lib/src/generated/api/AuthInfoInput.js +1 -0
  37. package/lib/src/generated/api/CapabilityInput.d.ts +5 -0
  38. package/lib/src/generated/api/CapabilityInput.js +1 -0
  39. package/lib/src/generated/api/CommitBatchRequest.d.ts +3 -0
  40. package/lib/src/generated/api/CommitBatchRequest.js +2 -0
  41. package/lib/src/generated/api/ComputeLogEntry.d.ts +9 -0
  42. package/lib/src/generated/api/ComputeLogEntry.js +2 -0
  43. package/lib/src/generated/api/CreateExpressionRequest.d.ts +4 -0
  44. package/lib/src/generated/api/CreateExpressionRequest.js +2 -0
  45. package/lib/src/generated/api/CreatePerspectiveRequest.d.ts +3 -0
  46. package/lib/src/generated/api/CreatePerspectiveRequest.js +2 -0
  47. package/lib/src/generated/api/CreateSubjectRequest.d.ts +6 -0
  48. package/lib/src/generated/api/CreateSubjectRequest.js +2 -0
  49. package/lib/src/generated/api/EmbedRequest.d.ts +4 -0
  50. package/lib/src/generated/api/EmbedRequest.js +2 -0
  51. package/lib/src/generated/api/EntanglementProofInput.d.ts +6 -0
  52. package/lib/src/generated/api/EntanglementProofInput.js +2 -0
  53. package/lib/src/generated/api/ExecuteCommandsRequest.d.ts +4 -0
  54. package/lib/src/generated/api/ExecuteCommandsRequest.js +2 -0
  55. package/lib/src/generated/api/ExportRequest.d.ts +5 -0
  56. package/lib/src/generated/api/ExportRequest.js +2 -0
  57. package/lib/src/generated/api/ExpressionManyRequest.d.ts +3 -0
  58. package/lib/src/generated/api/ExpressionManyRequest.js +2 -0
  59. package/lib/src/generated/api/ExpressionProof.d.ts +4 -0
  60. package/lib/src/generated/api/ExpressionProof.js +2 -0
  61. package/lib/src/generated/api/ExpressionProofInput.d.ts +6 -0
  62. package/lib/src/generated/api/ExpressionProofInput.js +2 -0
  63. package/lib/src/generated/api/FriendSendMessageRequest.d.ts +3 -0
  64. package/lib/src/generated/api/FriendSendMessageRequest.js +2 -0
  65. package/lib/src/generated/api/FriendsListRequest.d.ts +3 -0
  66. package/lib/src/generated/api/FriendsListRequest.js +2 -0
  67. package/lib/src/generated/api/GenerateAgentRequest.d.ts +3 -0
  68. package/lib/src/generated/api/GenerateAgentRequest.js +2 -0
  69. package/lib/src/generated/api/GenerateJwtRequest.d.ts +4 -0
  70. package/lib/src/generated/api/GenerateJwtRequest.js +2 -0
  71. package/lib/src/generated/api/GetSubjectDataRequest.d.ts +4 -0
  72. package/lib/src/generated/api/GetSubjectDataRequest.js +2 -0
  73. package/lib/src/generated/api/ImportAgentRequest.d.ts +6 -0
  74. package/lib/src/generated/api/ImportAgentRequest.js +2 -0
  75. package/lib/src/generated/api/ImportRequest.d.ts +4 -0
  76. package/lib/src/generated/api/ImportRequest.js +2 -0
  77. package/lib/src/generated/api/JoinNeighbourhoodRequest.d.ts +3 -0
  78. package/lib/src/generated/api/JoinNeighbourhoodRequest.js +2 -0
  79. package/lib/src/generated/api/LanguageMetaInput.d.ts +6 -0
  80. package/lib/src/generated/api/LanguageMetaInput.js +2 -0
  81. package/lib/src/generated/api/Link.d.ts +5 -0
  82. package/lib/src/generated/api/Link.js +2 -0
  83. package/lib/src/generated/api/LinkExpression.d.ts +10 -0
  84. package/lib/src/generated/api/LinkExpression.js +1 -0
  85. package/lib/src/generated/api/LinkExpressionInput.d.ts +10 -0
  86. package/lib/src/generated/api/LinkExpressionInput.js +1 -0
  87. package/lib/src/generated/api/LinkInput.d.ts +5 -0
  88. package/lib/src/generated/api/LinkInput.js +2 -0
  89. package/lib/src/generated/api/LinkLanguageTemplatesRequest.d.ts +3 -0
  90. package/lib/src/generated/api/LinkLanguageTemplatesRequest.js +2 -0
  91. package/lib/src/generated/api/LinkMutations.d.ts +6 -0
  92. package/lib/src/generated/api/LinkMutations.js +1 -0
  93. package/lib/src/generated/api/LinkStatus.d.ts +1 -0
  94. package/lib/src/generated/api/LinkStatus.js +2 -0
  95. package/lib/src/generated/api/LockAgentRequest.d.ts +3 -0
  96. package/lib/src/generated/api/LockAgentRequest.js +2 -0
  97. package/lib/src/generated/api/ModelType.d.ts +1 -0
  98. package/lib/src/generated/api/ModelType.js +2 -0
  99. package/lib/src/generated/api/NotificationInput.d.ts +10 -0
  100. package/lib/src/generated/api/NotificationInput.js +2 -0
  101. package/lib/src/generated/api/OpenLinkRequest.d.ts +3 -0
  102. package/lib/src/generated/api/OpenLinkRequest.js +2 -0
  103. package/lib/src/generated/api/PermitCapabilityRequest.d.ts +3 -0
  104. package/lib/src/generated/api/PermitCapabilityRequest.js +2 -0
  105. package/lib/src/generated/api/PerspectiveInput.d.ts +4 -0
  106. package/lib/src/generated/api/PerspectiveInput.js +1 -0
  107. package/lib/src/generated/api/PromptRequest.d.ts +4 -0
  108. package/lib/src/generated/api/PromptRequest.js +2 -0
  109. package/lib/src/generated/api/PublishLanguageRequest.d.ts +5 -0
  110. package/lib/src/generated/api/PublishLanguageRequest.js +1 -0
  111. package/lib/src/generated/api/PublishNeighbourhoodRequest.d.ts +6 -0
  112. package/lib/src/generated/api/PublishNeighbourhoodRequest.js +1 -0
  113. package/lib/src/generated/api/QueryRequest.d.ts +7 -0
  114. package/lib/src/generated/api/QueryRequest.js +2 -0
  115. package/lib/src/generated/api/RemoveLinkRequest.d.ts +5 -0
  116. package/lib/src/generated/api/RemoveLinkRequest.js +1 -0
  117. package/lib/src/generated/api/RemoveLinksBulkRequest.d.ts +5 -0
  118. package/lib/src/generated/api/RemoveLinksBulkRequest.js +1 -0
  119. package/lib/src/generated/api/ResourceInput.d.ts +4 -0
  120. package/lib/src/generated/api/ResourceInput.js +2 -0
  121. package/lib/src/generated/api/SetDefaultModelRequest.d.ts +4 -0
  122. package/lib/src/generated/api/SetDefaultModelRequest.js +1 -0
  123. package/lib/src/generated/api/SetFreeHostingEnabledRequest.d.ts +3 -0
  124. package/lib/src/generated/api/SetFreeHostingEnabledRequest.js +2 -0
  125. package/lib/src/generated/api/SetMultiUserRequest.d.ts +3 -0
  126. package/lib/src/generated/api/SetMultiUserRequest.js +2 -0
  127. package/lib/src/generated/api/SetStatusRequest.d.ts +3 -0
  128. package/lib/src/generated/api/SetStatusRequest.js +2 -0
  129. package/lib/src/generated/api/SignMessageRequest.d.ts +3 -0
  130. package/lib/src/generated/api/SignMessageRequest.js +2 -0
  131. package/lib/src/generated/api/TrustedAgentsRequest.d.ts +3 -0
  132. package/lib/src/generated/api/TrustedAgentsRequest.js +2 -0
  133. package/lib/src/generated/api/UnlockAgentRequest.d.ts +4 -0
  134. package/lib/src/generated/api/UnlockAgentRequest.js +2 -0
  135. package/lib/src/generated/api/UpdateLinkRequest.d.ts +7 -0
  136. package/lib/src/generated/api/UpdateLinkRequest.js +1 -0
  137. package/lib/src/generated/api/UpdatePerspectiveRequest.d.ts +3 -0
  138. package/lib/src/generated/api/UpdatePerspectiveRequest.js +2 -0
  139. package/lib/src/generated/api/UserStatistics.d.ts +9 -0
  140. package/lib/src/generated/api/UserStatistics.js +2 -0
  141. package/lib/src/generated/api/VerificationRequestResult.d.ts +6 -0
  142. package/lib/src/generated/api/VerificationRequestResult.js +2 -0
  143. package/lib/src/generated/api/VerifySignatureRequest.d.ts +5 -0
  144. package/lib/src/generated/api/VerifySignatureRequest.js +2 -0
  145. package/lib/src/generated/api/WriteSettingsRequest.d.ts +3 -0
  146. package/lib/src/generated/api/WriteSettingsRequest.js +2 -0
  147. package/lib/src/generated/api/index.d.ts +42 -0
  148. package/lib/src/generated/api/index.js +7 -0
  149. package/lib/src/index.d.ts +6 -2
  150. package/lib/src/index.js +6 -2
  151. package/lib/src/jestSetup.d.ts +0 -1
  152. package/lib/src/jestSetup.js +1 -1
  153. package/lib/src/language/Icon.js +2 -21
  154. package/lib/src/language/Language.d.ts +26 -214
  155. package/lib/src/language/Language.js +32 -72
  156. package/lib/src/language/LanguageClient.d.ts +2 -2
  157. package/lib/src/language/LanguageClient.js +15 -105
  158. package/lib/src/language/LanguageHandle.js +2 -41
  159. package/lib/src/language/LanguageMeta.js +4 -75
  160. package/lib/src/language/LanguageRef.js +2 -25
  161. package/lib/src/links/Links.js +14 -111
  162. package/lib/src/model/Ad4mModel.d.ts +81 -38
  163. package/lib/src/model/Ad4mModel.js +651 -408
  164. package/lib/src/model/Ad4mModel.test.js +488 -750
  165. package/lib/src/model/ModelQueryBuilder.d.ts +28 -21
  166. package/lib/src/model/ModelQueryBuilder.js +160 -195
  167. package/lib/src/model/decorators.d.ts +22 -0
  168. package/lib/src/model/decorators.js +7 -0
  169. package/lib/src/model/hydration-batching.test.d.ts +7 -0
  170. package/lib/src/model/hydration-batching.test.js +456 -0
  171. package/lib/src/model/hydration.d.ts +8 -60
  172. package/lib/src/model/hydration.js +41 -541
  173. package/lib/src/model/index.d.ts +0 -4
  174. package/lib/src/model/index.js +0 -4
  175. package/lib/src/model/model-manifest.d.ts +41 -0
  176. package/lib/src/model/model-manifest.js +11 -0
  177. package/lib/src/model/query-sparql.d.ts +36 -22
  178. package/lib/src/model/query-sparql.js +188 -53
  179. package/lib/src/model/query-sparql.test.d.ts +1 -0
  180. package/lib/src/model/query-sparql.test.js +312 -0
  181. package/lib/src/model/query-utils.js +4 -0
  182. package/lib/src/model/shacl-gen.js +4 -0
  183. package/lib/src/model/subscription-delta.test.d.ts +24 -0
  184. package/lib/src/model/subscription-delta.test.js +180 -0
  185. package/lib/src/model/subscription-pool.js +48 -2
  186. package/lib/src/model/types.d.ts +58 -1
  187. package/lib/src/model/types.js +4 -1
  188. package/lib/src/neighbourhood/Neighbourhood.js +4 -32
  189. package/lib/src/neighbourhood/NeighbourhoodClient.d.ts +3 -3
  190. package/lib/src/neighbourhood/NeighbourhoodClient.js +40 -203
  191. package/lib/src/perspectives/LinkQuery.js +2 -42
  192. package/lib/src/perspectives/Perspective.d.ts +1 -1
  193. package/lib/src/perspectives/Perspective.js +10 -52
  194. package/lib/src/perspectives/PerspectiveClient.d.ts +12 -15
  195. package/lib/src/perspectives/PerspectiveClient.js +168 -400
  196. package/lib/src/perspectives/PerspectiveClient.test.d.ts +1 -0
  197. package/lib/src/perspectives/PerspectiveClient.test.js +224 -0
  198. package/lib/src/perspectives/PerspectiveDiff.js +4 -31
  199. package/lib/src/perspectives/PerspectiveHandle.js +3 -43
  200. package/lib/src/perspectives/PerspectiveProxy.d.ts +95 -71
  201. package/lib/src/perspectives/PerspectiveProxy.js +288 -310
  202. package/lib/src/runtime/RuntimeClient.d.ts +6 -6
  203. package/lib/src/runtime/RuntimeClient.js +93 -467
  204. package/lib/src/runtime/RuntimeTypes.d.ts +101 -0
  205. package/lib/src/runtime/RuntimeTypes.js +45 -0
  206. package/lib/src/shacl/SHACLShape.d.ts +7 -0
  207. package/lib/src/shacl/SHACLShape.js +19 -0
  208. package/lib/src/shacl/SHACLShape.test.js +82 -0
  209. package/lib/src/typeDefs.js +3 -628
  210. package/package.json +9 -24
  211. package/rollup.config.js +0 -7
  212. package/src/Ad4mClient.test.ts +1182 -1288
  213. package/src/Ad4mClient.ts +30 -15
  214. package/src/agent/Agent.ts +0 -99
  215. package/src/agent/AgentClient.ts +112 -526
  216. package/src/agent/AgentStatus.ts +0 -12
  217. package/src/ai/AIClient.ts +96 -296
  218. package/src/ai/AITypes.ts +66 -0
  219. package/src/ai/Tasks.ts +0 -52
  220. package/src/apiClient.ts +283 -0
  221. package/src/expression/Expression.ts +3 -43
  222. package/src/expression/ExpressionClient.ts +14 -77
  223. package/src/expression/ExpressionRef.ts +0 -6
  224. package/src/generated/api/AIModelLoadingStatus.ts +3 -0
  225. package/src/generated/api/AddLinkExpressionRequest.ts +4 -0
  226. package/src/generated/api/AddLinkRequest.ts +4 -0
  227. package/src/generated/api/AddLinksBulkRequest.ts +4 -0
  228. package/src/generated/api/AddSdnaRequest.ts +3 -0
  229. package/src/generated/api/ApplyTemplateRequest.ts +3 -0
  230. package/src/generated/api/AuthInfoInput.ts +4 -0
  231. package/src/generated/api/CapabilityInput.ts +4 -0
  232. package/src/generated/api/CommitBatchRequest.ts +3 -0
  233. package/src/generated/api/ComputeLogEntry.ts +3 -0
  234. package/src/generated/api/CreateExpressionRequest.ts +3 -0
  235. package/src/generated/api/CreatePerspectiveRequest.ts +3 -0
  236. package/src/generated/api/CreateSubjectRequest.ts +3 -0
  237. package/src/generated/api/EmbedRequest.ts +3 -0
  238. package/src/generated/api/EntanglementProofInput.ts +3 -0
  239. package/src/generated/api/ExecuteCommandsRequest.ts +3 -0
  240. package/src/generated/api/ExportRequest.ts +3 -0
  241. package/src/generated/api/ExpressionManyRequest.ts +3 -0
  242. package/src/generated/api/ExpressionProof.ts +3 -0
  243. package/src/generated/api/ExpressionProofInput.ts +3 -0
  244. package/src/generated/api/FriendSendMessageRequest.ts +3 -0
  245. package/src/generated/api/FriendsListRequest.ts +3 -0
  246. package/src/generated/api/GenerateAgentRequest.ts +3 -0
  247. package/src/generated/api/GenerateJwtRequest.ts +3 -0
  248. package/src/generated/api/GetSubjectDataRequest.ts +3 -0
  249. package/src/generated/api/ImportAgentRequest.ts +3 -0
  250. package/src/generated/api/ImportRequest.ts +3 -0
  251. package/src/generated/api/JoinNeighbourhoodRequest.ts +3 -0
  252. package/src/generated/api/LanguageMetaInput.ts +3 -0
  253. package/src/generated/api/Link.ts +3 -0
  254. package/src/generated/api/LinkExpression.ts +6 -0
  255. package/src/generated/api/LinkExpressionInput.ts +6 -0
  256. package/src/generated/api/LinkInput.ts +3 -0
  257. package/src/generated/api/LinkLanguageTemplatesRequest.ts +3 -0
  258. package/src/generated/api/LinkMutations.ts +5 -0
  259. package/src/generated/api/LinkStatus.ts +3 -0
  260. package/src/generated/api/LockAgentRequest.ts +3 -0
  261. package/src/generated/api/ModelType.ts +3 -0
  262. package/src/generated/api/NotificationInput.ts +3 -0
  263. package/src/generated/api/OpenLinkRequest.ts +3 -0
  264. package/src/generated/api/PermitCapabilityRequest.ts +3 -0
  265. package/src/generated/api/PerspectiveInput.ts +4 -0
  266. package/src/generated/api/PromptRequest.ts +3 -0
  267. package/src/generated/api/PublishLanguageRequest.ts +4 -0
  268. package/src/generated/api/PublishNeighbourhoodRequest.ts +4 -0
  269. package/src/generated/api/QueryRequest.ts +6 -0
  270. package/src/generated/api/RemoveLinkRequest.ts +4 -0
  271. package/src/generated/api/RemoveLinksBulkRequest.ts +4 -0
  272. package/src/generated/api/ResourceInput.ts +3 -0
  273. package/src/generated/api/SetDefaultModelRequest.ts +4 -0
  274. package/src/generated/api/SetFreeHostingEnabledRequest.ts +3 -0
  275. package/src/generated/api/SetMultiUserRequest.ts +3 -0
  276. package/src/generated/api/SetStatusRequest.ts +3 -0
  277. package/src/generated/api/SignMessageRequest.ts +3 -0
  278. package/src/generated/api/TrustedAgentsRequest.ts +3 -0
  279. package/src/generated/api/UnlockAgentRequest.ts +3 -0
  280. package/src/generated/api/UpdateLinkRequest.ts +5 -0
  281. package/src/generated/api/UpdatePerspectiveRequest.ts +3 -0
  282. package/src/generated/api/UserStatistics.ts +3 -0
  283. package/src/generated/api/VerificationRequestResult.ts +3 -0
  284. package/src/generated/api/VerifySignatureRequest.ts +3 -0
  285. package/src/generated/api/WriteSettingsRequest.ts +3 -0
  286. package/src/generated/api/index.ts +49 -0
  287. package/src/index.ts +6 -2
  288. package/src/jestSetup.ts +1 -1
  289. package/src/language/Icon.ts +0 -4
  290. package/src/language/Language.ts +50 -292
  291. package/src/language/LanguageClient.ts +21 -132
  292. package/src/language/LanguageHandle.ts +0 -14
  293. package/src/language/LanguageMeta.ts +0 -29
  294. package/src/language/LanguageRef.ts +0 -7
  295. package/src/links/Links.ts +0 -37
  296. package/src/model/Ad4mModel.test.ts +827 -808
  297. package/src/model/Ad4mModel.ts +676 -457
  298. package/src/model/ModelQueryBuilder.ts +199 -217
  299. package/src/model/decorators.ts +29 -0
  300. package/src/model/hydration.ts +17 -572
  301. package/src/model/index.ts +0 -4
  302. package/src/model/query-sparql.test.ts +360 -0
  303. package/src/model/query-sparql.ts +203 -56
  304. package/src/model/query-utils.ts +4 -0
  305. package/src/model/shacl-gen.ts +5 -0
  306. package/src/model/types.ts +62 -1
  307. package/src/neighbourhood/Neighbourhood.ts +0 -9
  308. package/src/neighbourhood/NeighbourhoodClient.ts +42 -207
  309. package/src/neighbourhood/NeighbourhoodProxy.test.ts +34 -36
  310. package/src/perspectives/LinkQuery.ts +0 -15
  311. package/src/perspectives/Perspective.ts +1 -12
  312. package/src/perspectives/PerspectiveClient.test.ts +262 -0
  313. package/src/perspectives/PerspectiveClient.ts +227 -412
  314. package/src/perspectives/PerspectiveDiff.ts +0 -8
  315. package/src/perspectives/PerspectiveHandle.ts +1 -12
  316. package/src/perspectives/PerspectiveProxy.test.ts +41 -0
  317. package/src/perspectives/PerspectiveProxy.ts +325 -348
  318. package/src/runtime/RuntimeClient.ts +112 -474
  319. package/src/runtime/RuntimeTypes.ts +144 -0
  320. package/src/shacl/SHACLShape.test.ts +94 -0
  321. package/src/shacl/SHACLShape.ts +27 -0
  322. package/src/typeDefs.ts +3 -5
  323. package/tsconfig.json +3 -7
  324. package/lib/src/model/query-surreal.d.ts +0 -44
  325. package/lib/src/model/query-surreal.js +0 -249
  326. package/lib/src/model/surreal-utils.d.ts +0 -42
  327. package/lib/src/model/surreal-utils.js +0 -128
  328. package/shims/reflect-metadata.ts +0 -0
  329. package/shims/type-graphql.ts +0 -75
  330. package/src/PubSub.ts +0 -17
  331. package/src/agent/AgentResolver.ts +0 -263
  332. package/src/ai/AIResolver.ts +0 -372
  333. package/src/buildSchema.ts +0 -43
  334. package/src/expression/ExpressionResolver.ts +0 -64
  335. package/src/language/LanguageContext.ts +0 -37
  336. package/src/language/LanguageResolver.ts +0 -98
  337. package/src/model/Subject.ts +0 -159
  338. package/src/model/hydration-batch.ts +0 -205
  339. package/src/model/prolog-facts.ts +0 -145
  340. package/src/model/query-prolog.ts +0 -148
  341. package/src/model/query-sparql-batch.ts +0 -301
  342. package/src/model/subscription-pool.ts +0 -163
  343. package/src/neighbourhood/NeighbourhoodResolver.ts +0 -100
  344. package/src/perspectives/PerspectiveResolver.ts +0 -364
  345. package/src/runtime/RuntimeResolver.ts +0 -749
  346. package/src/unwrapApolloResult.ts +0 -16
  347. package/tsconfig-browser.json +0 -82
@@ -3,30 +3,180 @@ import { Link } from "../links/Links";
3
3
  import { LinkQuery } from "../perspectives/LinkQuery";
4
4
  import { PerspectiveProxy } from "../perspectives/PerspectiveProxy";
5
5
  import { makeRandomId } from "./util";
6
- import { getPropertiesMetadata, getRelationsMetadata } from "./decorators";
6
+ import { getPropertiesMetadata, getRelationsMetadata, buildConformanceFilter, setPropertyRegistryEntry, setRelationRegistryEntry, Model } from "./decorators";
7
7
  import type { PropertyOptions, PropertyMetadataEntry, RelationMetadataEntry } from "./decorators";
8
- import { formatQueryValue } from "./query-utils";
8
+ import { formatQueryValue, compileWhereClause } from "./query-utils";
9
9
  import { resolveParentPredicate } from "./query-common";
10
- import { buildParentQuery, buildAuthorAndTimestampQuery, buildPropertiesQuery, buildWhereQuery, buildCountQuery, buildOrderQuery, buildOffsetQuery, buildLimitQuery } from "./query-prolog";
11
10
  import { isArrayType, determinePredicate, determineNamespace, buildModelFromJSONSchema } from "./json-schema";
11
+ import type { SHACLShape } from "../shacl/SHACLShape";
12
12
  import type { JSONSchemaProperty, JSONSchema, JSONSchemaToModelOptions } from "./json-schema";
13
13
 
14
- import { buildSPARQLQuery, buildSPARQLGetDataQuery, groupSPARQLResults } from "./query-sparql";
15
- import { buildBatchSPARQLQuery } from "./query-sparql-batch";
16
- import { hydrateBatchResult } from "./hydration-batch";
14
+ import { buildSPARQLQuery } from "./query-sparql";
17
15
  import { ModelQueryBuilder } from "./ModelQueryBuilder";
18
16
  import {
19
- normalizeValue, matchesCondition, hydrateFromLinks,
20
- assignValuesToInstance as _assignValuesToInstance,
17
+ normalizeValue,
21
18
  evaluateCustomGettersForInstance,
22
- hydrateRelations,
23
19
  } from "./hydration";
24
20
  import type {
25
21
  ParentScope, IncludeMap, Query,
26
22
  GetOptions, AllInstancesResult, ResultsWithTotalCount,
27
- PaginationResult, PropertyMetadata, RelationMetadata, ModelMetadata, ValueTuple,
23
+ PaginationResult, PropertyMetadata, RelationMetadata, ModelMetadata,
24
+ IncludeProjection,
28
25
  } from "./types";
29
26
 
27
+
28
+ // ---------------------------------------------------------------------------
29
+ // Helpers for Rust-side include resolution
30
+ // ---------------------------------------------------------------------------
31
+
32
+ /**
33
+ * Recursively enrich relation metadata in the shape with target class shapes
34
+ * so the Rust endpoint can resolve includes in-process (no extra GraphQL
35
+ * round-trips per relation).
36
+ */
37
+ function enrichShapeForIncludes(
38
+ metadata: ModelMetadata,
39
+ include: IncludeMap,
40
+ allRelMeta: Record<string, RelationMetadataEntry>,
41
+ ): void {
42
+ for (const [relName, includeVal] of Object.entries(include)) {
43
+ if (!includeVal) continue;
44
+ const meta = allRelMeta[relName];
45
+ if (!meta?.target) continue;
46
+
47
+ const TargetClass = meta.target() as typeof Ad4mModel;
48
+ // Deep-copy so we don't mutate the cached metadata
49
+ const targetMeta = JSON.parse(JSON.stringify(TargetClass.getModelMetadata()));
50
+
51
+ // Ensure the relation is in metadata.relations (fallback for edge cases)
52
+ if (!metadata.relations[relName]) {
53
+ metadata.relations[relName] = {
54
+ name: relName,
55
+ predicate: meta.predicate,
56
+ direction:
57
+ meta.kind === 'belongsToMany' || meta.kind === 'belongsToOne'
58
+ ? 'reverse'
59
+ : 'forward',
60
+ };
61
+ }
62
+ const rel = metadata.relations[relName] as any;
63
+ rel.kind = meta.kind;
64
+ rel.maxCount = meta.maxCount;
65
+ rel.targetShape = targetMeta;
66
+ rel.targetClassName = targetMeta.className;
67
+
68
+ // Recurse for nested includes
69
+ const nested =
70
+ typeof includeVal === 'object' && includeVal !== null
71
+ ? (includeVal as any).include
72
+ : undefined;
73
+ if (nested) {
74
+ const targetRelMeta = getRelationsMetadata(TargetClass as any);
75
+ enrichShapeForIncludes(targetMeta, nested, targetRelMeta);
76
+ }
77
+ }
78
+ }
79
+
80
+ /**
81
+ * Construct a model class instance from a plain JSON object returned by the
82
+ * Rust endpoint. Recursively converts included relation values (which come
83
+ * back as plain JSON objects) into proper model class instances.
84
+ */
85
+ function jsonToModelInstance<T extends Ad4mModel>(
86
+ ModelClass: typeof Ad4mModel & (new (...args: any[]) => T),
87
+ perspective: PerspectiveProxy,
88
+ json: any,
89
+ include?: IncludeMap,
90
+ properties?: string[],
91
+ ): T {
92
+ const instance = new ModelClass(perspective, json.id || json.baseExpression) as any;
93
+
94
+ // When a properties projection is active, remove own properties set by the
95
+ // constructor that are not in the projected JSON. This ensures assertions
96
+ // like `expect(r).to.not.have.own.property("body")` pass.
97
+ if (properties) {
98
+ const jsonKeys = new Set(Object.keys(json));
99
+ for (const key of Object.getOwnPropertyNames(instance)) {
100
+ // Keep internal fields (backing store for getters), id, baseExpression, perspective
101
+ if (key === 'id' || key === 'baseExpression' || key === 'perspective' || key.startsWith('_')) continue;
102
+ if (!jsonKeys.has(key)) {
103
+ delete instance[key];
104
+ }
105
+ }
106
+ }
107
+
108
+ for (const [key, value] of Object.entries(json)) {
109
+ if (key === 'baseExpression' || key === 'id') continue;
110
+
111
+ // Skip getter-only properties anywhere in the prototype chain
112
+ let isReadonly = false;
113
+ let proto = Object.getPrototypeOf(instance);
114
+ while (proto) {
115
+ const desc = Object.getOwnPropertyDescriptor(proto, key);
116
+ if (desc) { isReadonly = !!(desc.get && !desc.set); break; }
117
+ proto = Object.getPrototypeOf(proto);
118
+ }
119
+ if (isReadonly) continue;
120
+
121
+ // Parse ISO timestamps to epoch milliseconds (matches hydrateFromLinks behaviour)
122
+ if ((key === 'createdAt' || key === 'updatedAt') && typeof value === 'string' && value.includes('T')) {
123
+ instance[key] = new Date(value).getTime();
124
+ continue;
125
+ }
126
+
127
+ instance[key] = value;
128
+ }
129
+
130
+ // Apply property transform functions from decorators (only for literal-resolved
131
+ // or no-resolveLanguage properties; non-literal properties are resolved + transformed
132
+ // asynchronously in executeModelQuery).
133
+ try {
134
+ const propsMeta = getPropertiesMetadata(ModelClass as any);
135
+ for (const [propName, opts] of Object.entries(propsMeta)) {
136
+ const o = opts as any;
137
+ if (typeof o.transform !== 'function' || !(propName in json)) continue;
138
+ // Skip non-literal resolveLanguage props — they need async expression resolution first
139
+ if (o.resolveLanguage != null && o.resolveLanguage !== 'literal') continue;
140
+ instance[propName] = o.transform(instance[propName]);
141
+ }
142
+ } catch (_) { /* no metadata available */ }
143
+
144
+ // Recursively convert included relation values to class instances
145
+ if (include) {
146
+ const relMeta = getRelationsMetadata(ModelClass as any);
147
+ for (const [relName, includeVal] of Object.entries(include)) {
148
+ if (!includeVal) continue;
149
+ const meta = relMeta[relName];
150
+ if (!meta?.target) continue;
151
+ const TargetClass = meta.target() as any;
152
+ const nestedInclude =
153
+ typeof includeVal === 'object' && includeVal !== null
154
+ ? (includeVal as any).include
155
+ : undefined;
156
+ const nestedProperties =
157
+ typeof includeVal === 'object' && includeVal !== null
158
+ ? (includeVal as any).properties
159
+ : undefined;
160
+
161
+ const raw = instance[relName];
162
+ if (Array.isArray(raw)) {
163
+ instance[relName] = raw.map((item: any) => {
164
+ if (typeof item === 'object' && item !== null && item.id) {
165
+ return jsonToModelInstance(TargetClass, perspective, item, nestedInclude, nestedProperties);
166
+ }
167
+ return item;
168
+ });
169
+ } else if (typeof raw === 'object' && raw !== null && raw.id) {
170
+ instance[relName] = jsonToModelInstance(
171
+ TargetClass, perspective, raw, nestedInclude, nestedProperties,
172
+ );
173
+ }
174
+ }
175
+ }
176
+
177
+ return instance;
178
+ }
179
+
30
180
  /**
31
181
  * Base class for defining data models in AD4M.
32
182
  *
@@ -131,6 +281,14 @@ export class Ad4mModel {
131
281
  createdAt: any;
132
282
  updatedAt: any;
133
283
 
284
+ /**
285
+ * Backwards compatibility alias for createdAt.
286
+ * @deprecated Use createdAt instead. This will be removed in a future version.
287
+ */
288
+ get timestamp(): any {
289
+ return (this as any).createdAt;
290
+ }
291
+
134
292
  private static classNamesByClass = new WeakMap<typeof Ad4mModel, { [perspectiveId: string]: string }>();
135
293
 
136
294
  /**
@@ -177,14 +335,6 @@ export class Ad4mModel {
177
335
  return classCache[perspectiveID];
178
336
  }
179
337
 
180
- /**
181
- * Backwards compatibility alias for createdAt.
182
- * @deprecated Use createdAt instead. This will be removed in a future version.
183
- */
184
- get timestamp(): any {
185
- return (this as any).createdAt;
186
- }
187
-
188
338
  /**
189
339
  * Extracts metadata from decorators for query building.
190
340
  *
@@ -261,9 +411,7 @@ export class Ad4mModel {
261
411
  // Extract relations (relations) from WeakMap registry
262
412
  const relationsMetadata: Record<string, RelationMetadata> = {};
263
413
  const allRelationsMeta = getRelationsMetadata(this as any);
264
- const prototypeRelations = Object.fromEntries(
265
- Object.entries(allRelationsMeta).filter(([, r]) => r.kind === 'hasMany' || r.kind === 'belongsToMany')
266
- );
414
+ const prototypeRelations = allRelationsMeta;
267
415
 
268
416
  for (const [relationName, opts] of Object.entries(prototypeRelations)) {
269
417
  const options = opts as RelationMetadataEntry;
@@ -273,6 +421,8 @@ export class Ad4mModel {
273
421
  ...(options.local !== undefined && { local: options.local }),
274
422
  ...(options.getter !== undefined && { getter: options.getter }),
275
423
  direction: (options.kind === 'belongsToMany' || options.kind === 'belongsToOne') ? 'reverse' : 'forward',
424
+ ...(options.kind !== undefined && { kind: options.kind }),
425
+ ...(options.maxCount !== undefined && { maxCount: options.maxCount }),
276
426
  ...(options.target !== undefined && { target: options.target }),
277
427
  ...(options.filter !== undefined && { filter: options.filter }),
278
428
  ...(options.where !== undefined && { where: options.where }),
@@ -359,13 +509,6 @@ export class Ad4mModel {
359
509
  return this._baseExpression;
360
510
  }
361
511
 
362
- /**
363
- * @deprecated Use `.id` instead. Will be removed in a future version.
364
- */
365
- get baseExpression(): string {
366
- return this._baseExpression;
367
- }
368
-
369
512
  /**
370
513
  * Protected getter for the perspective.
371
514
  * Allows subclasses to access the perspective while keeping it private from external code.
@@ -462,14 +605,6 @@ export class Ad4mModel {
462
605
  }];
463
606
  }
464
607
 
465
- /**
466
- * Assigns decoded Prolog property values to an instance.
467
- * Delegates to the standalone function in hydration.ts.
468
- */
469
- public static async assignValuesToInstance(perspective: PerspectiveProxy, instance: Ad4mModel, values: ValueTuple[]) {
470
- return _assignValuesToInstance(perspective, instance, values);
471
- }
472
-
473
608
  // ──────────────────────────────────────────────────────────
474
609
  // Snapshot / dirty tracking
475
610
  // ──────────────────────────────────────────────────────────
@@ -603,89 +738,50 @@ export class Ad4mModel {
603
738
  }
604
739
 
605
740
  private async getData(opts?: GetOptions) {
606
- // Builds an object with the author, timestamp, all properties, & all relations on the Ad4mModel and saves it to the instance
607
- // Use SPARQL for data queries
741
+ // Route through the Rust model query endpoint — same pipeline as executeModelQuery
742
+ // but for a single instance by ID.
608
743
  try {
609
744
  const ctor = this.constructor as typeof Ad4mModel;
610
- const metadata = ctor.getModelMetadata();
611
-
612
- // Query for all links from this specific node (base expression)
613
- const linksQuery = buildSPARQLGetDataQuery(this._baseExpression);
614
- const links = await this._perspective.querySparql(linksQuery);
745
+ const query: Query = {
746
+ where: { id: this._baseExpression },
747
+ limit: 1,
748
+ };
749
+ if (opts?.properties) query.properties = opts.properties;
750
+ if (opts?.include) query.include = opts.include;
615
751
 
616
- if (links && links.length > 0) {
617
- // Core hydration: properties (latest-wins), relations, timestamps/author
618
- const requestedProperties = opts?.properties && opts.properties.length > 0 ? opts.properties : undefined;
619
- await hydrateFromLinks(this, links, metadata, this._perspective, requestedProperties);
620
- }
752
+ const { results } = await (ctor as any).executeModelQuery(
753
+ this._perspective, query, null
754
+ );
621
755
 
622
- // Populate reverse relation fields (belongsToOne / belongsToMany) as string IDs.
623
- const allRelsMeta = getRelationsMetadata(ctor as any);
624
- const requestedProps = opts?.properties && opts.properties.length > 0 ? new Set(opts.properties) : null;
625
- for (const [relName, relMeta] of Object.entries(allRelsMeta)) {
626
- if (relMeta.kind !== 'belongsToOne' && relMeta.kind !== 'belongsToMany') continue;
627
- if (requestedProps && !requestedProps.has(relName)) continue;
628
- const reverseLinks = await this._perspective.get(
629
- new LinkQuery({ predicate: relMeta.predicate, target: this._baseExpression })
630
- );
631
- const sourceIds = reverseLinks
632
- .filter((l) => l.data.target === this._baseExpression)
633
- .map((l) => l.data.source);
634
- if (relMeta.kind === 'belongsToOne') {
635
- (this as any)[relName] = sourceIds.length > 0 ? sourceIds[sourceIds.length - 1] : null;
636
- } else {
637
- (this as any)[relName] = sourceIds;
756
+ if (results.length > 0) {
757
+ const hydrated = results[0];
758
+ // Copy all hydrated values from the Rust-side result onto this instance
759
+ for (const [key, value] of Object.entries(hydrated as any)) {
760
+ if (key === '_baseExpression' || key === '_perspective' || key === '_snapshot') continue;
761
+ if (key.startsWith('_')) continue;
762
+ // Check for readonly getters
763
+ let isReadonly = false;
764
+ let proto = Object.getPrototypeOf(this);
765
+ while (proto) {
766
+ const desc = Object.getOwnPropertyDescriptor(proto, key);
767
+ if (desc) { isReadonly = !!(desc.get && !desc.set); break; }
768
+ proto = Object.getPrototypeOf(proto);
769
+ }
770
+ if (isReadonly) continue;
771
+ (this as any)[key] = value;
638
772
  }
639
773
  }
640
774
 
641
- // Evaluate SPARQL getters
642
- const getterOpts = opts?.properties || opts?.include
643
- ? { requestedProperties: opts?.properties, include: opts?.include }
644
- : undefined;
645
- await evaluateCustomGettersForInstance(this, this._perspective, metadata, getterOpts);
646
-
647
- // Eager-load relations if requested
648
- if (opts?.include) {
649
- await hydrateRelations(ctor, [this], this._perspective, opts.include);
650
- }
775
+ // Property getters and relation conformance getters are now evaluated
776
+ // Rust-side via evaluate_getters() in model_query.rs.
651
777
  } catch (e) {
652
- console.error(`SPARQL getData also failed for ${this._baseExpression}:`, e);
778
+ console.error(`getData via Rust model query failed for ${this._baseExpression}:`, e);
653
779
  }
654
780
 
655
- this.takeSnapshot();
781
+ this.takeSnapshot(opts?.include);
656
782
  return this;
657
783
  }
658
784
 
659
- public static async queryToProlog(perspective: PerspectiveProxy, query: Query, modelClassName?: string | null) {
660
- const { properties, where, order, offset, limit, count } = query;
661
- const className = modelClassName || (await this.getClassName(perspective));
662
-
663
- // Resolve parent predicate from model metadata if needed
664
- const resolvedParentPredicate = query.parent
665
- ? resolveParentPredicate(query.parent, this)
666
- : undefined;
667
-
668
- const instanceQueries = [
669
- buildAuthorAndTimestampQuery(),
670
- buildParentQuery(query.parent, resolvedParentPredicate),
671
- buildPropertiesQuery(properties),
672
- buildWhereQuery(where),
673
- ];
674
-
675
- const resultSetQueries = [buildCountQuery(count), buildOrderQuery(order), buildOffsetQuery(offset), buildLimitQuery(limit)];
676
-
677
- const fullQuery = `
678
- findall([Base, Properties, Collections, Timestamp, Author], (
679
- subject_class("${className}", SubjectClass),
680
- instance(SubjectClass, Base),
681
- ${instanceQueries.filter((q) => q).join(", ")}
682
- ), UnsortedInstances),
683
- ${resultSetQueries.filter((q) => q).join(", ")}
684
- `;
685
-
686
- return fullQuery;
687
- }
688
-
689
785
  /**
690
786
  * Generates a SPARQL query from a Query object.
691
787
  *
@@ -728,295 +824,360 @@ export class Ad4mModel {
728
824
  return buildSPARQLQuery(metadata, allRelMeta, query, this);
729
825
  }
730
826
 
731
- public static async instancesFromPrologResult<T extends Ad4mModel>(
732
- this: typeof Ad4mModel & (new (...args: any[]) => T),
733
- perspective: PerspectiveProxy,
734
- query: Query,
735
- result: AllInstancesResult
736
- ): Promise<ResultsWithTotalCount<T>> {
737
- if (!result?.[0]?.AllInstances) return { results: [], totalCount: 0 };
738
- // Map results to instances
739
- const requestedProperties = query?.properties || [];
740
- const allInstances = await Promise.all(
741
- result[0].AllInstances.map(async ([Base, Properties, Collections, Timestamp, Author]) => {
827
+ /**
828
+ * Build the JSON parameters needed for a model query/subscription endpoint.
829
+ * Returns the className, queryJson, and shapeJson that the Rust executor expects.
830
+ * @internal
831
+ */
832
+ static prepareModelQueryParams(
833
+ query: Query = {},
834
+ classNameOverride?: string | null,
835
+ ): { className: string; queryJson: string; shapeJson: string } {
836
+ const metadata = this.getModelMetadata();
837
+ const className = classNameOverride || metadata.className;
838
+
839
+ const queryInput: any = {};
840
+ if (query.parent) {
841
+ const parentPredicate = resolveParentPredicate(query.parent, this);
842
+ queryInput.parent = { id: query.parent.id, predicate: parentPredicate };
843
+ }
844
+ if (query.properties) queryInput.properties = query.properties;
845
+ if (query.include) queryInput.include = query.include;
846
+ if (query.where) queryInput.where = query.where;
847
+ if (query.order) {
848
+ queryInput.order = Object.entries(query.order).map(([k, v]) => [k, v]);
849
+ }
850
+ if (query.offset !== undefined) queryInput.offset = query.offset;
851
+ if (query.limit !== undefined) queryInput.limit = query.limit;
852
+ if (query.count !== undefined) queryInput.count = query.count;
853
+
854
+ if (query.include) {
855
+ const allRelMeta = getRelationsMetadata(this as any);
856
+ enrichShapeForIncludes(metadata, query.include, allRelMeta);
857
+ }
858
+
859
+ // Pre-compute conformance getters (with where-clause support)
860
+ {
861
+ const allRelMeta = getRelationsMetadata(this as any);
862
+ for (const [relName, relMeta] of Object.entries(metadata.relations)) {
863
+ const rel = relMeta as any;
864
+ if (rel.getter || rel.direction === 'reverse' || rel.filter === false) continue;
865
+ const meta = allRelMeta[relName];
866
+ if (!meta?.target) continue;
742
867
  try {
743
- const instance = new this(perspective, Base) as any;
744
- // Remove unrequested attributes from instance
745
- if (requestedProperties.length) {
746
- Object.keys(instance).forEach((key) => {
747
- if (!requestedProperties.includes(key) && key !== 'createdAt' && key !== 'updatedAt' && key !== 'author' && key !== 'id' && key !== 'baseExpression') delete instance[key];
748
- });
868
+ const TargetClass = meta.target();
869
+ const filter = buildConformanceFilter(meta.predicate, TargetClass);
870
+
871
+ // Only compile where clauses to SPARQL when the target properties
872
+ // are stored as plain IRIs (not signed expressions). Properties
873
+ // without resolveLanguage or with resolveLanguage='literal' store
874
+ // values as signed JSON envelopes, so SPARQL exact-match fails.
875
+ let whereConditions: string[] = [];
876
+ if (rel.where) {
877
+ try {
878
+ const targetMetadata = (TargetClass as any).getModelMetadata?.() ?? null;
879
+ let allSparqlFilterable = true;
880
+ if (targetMetadata) {
881
+ for (const propName of Object.keys(rel.where)) {
882
+ if (['id', 'author', 'timestamp'].includes(propName)) continue;
883
+ const propMeta = targetMetadata.properties[propName];
884
+ if (propMeta && (!propMeta.resolveLanguage || propMeta.resolveLanguage === 'literal')) {
885
+ allSparqlFilterable = false;
886
+ break;
887
+ }
888
+ }
889
+ } else {
890
+ allSparqlFilterable = false;
891
+ }
892
+ if (allSparqlFilterable) {
893
+ whereConditions = compileWhereClause(rel.where, targetMetadata);
894
+ }
895
+ } catch (_) {}
749
896
  }
750
- // Collect values to assign to instance
751
- const values = [...Properties, ...Collections, ["createdAt", Timestamp], ["author", Author]];
752
- await Ad4mModel.assignValuesToInstance(perspective, instance, values);
753
-
754
- return instance;
755
- } catch (error) {
756
- console.error(`Failed to process instance ${Base}:`, error);
757
- // Return null for failed instances - we'll filter these out below
758
- return null;
759
- }
760
- })
761
- );
762
- const instances = allInstances.filter((instance) => instance !== null) as T[];
763
897
 
764
- // Eager-load relations if requested (BEFORE snapshot so dirty tracking is accurate)
765
- if (query.include && instances.length > 0) {
766
- await hydrateRelations(this, instances, perspective, query.include);
898
+ if (filter) {
899
+ let getter = filter.getter;
900
+ if (whereConditions.length > 0) {
901
+ getter = getter.replace(/ \}$/, ` ${whereConditions.join(' ')} }`);
902
+ }
903
+ rel.getter = getter;
904
+ } else if (whereConditions.length > 0) {
905
+ const escapedPred = meta.predicate.replace(/[<>"{}|\\^`\u0000-\u0020]/g, '');
906
+ rel.getter = `SELECT ?target WHERE { <Base> <${escapedPred}> ?target . ${whereConditions.join(' ')} }`;
907
+ }
908
+ } catch (_) {}
909
+ }
767
910
  }
768
911
 
769
- // Take snapshots for dirty tracking after ALL hydration is complete
770
- // (including eager-loaded relations).
771
- // When `include` is specified, only snapshot those relations.
772
- // Otherwise snapshot ALL fields (properties + relations) since
773
- // hydrateFromLinks populates relations with stable raw IDs.
774
- const snapshotRelations = query.include;
775
- for (const inst of instances) {
776
- (inst as Ad4mModel).takeSnapshot(snapshotRelations);
777
- }
912
+ return {
913
+ className,
914
+ queryJson: JSON.stringify(queryInput),
915
+ shapeJson: JSON.stringify(metadata),
916
+ };
917
+ }
778
918
 
779
- return { results: instances, totalCount: result[0].TotalCount };
919
+ /**
920
+ * Parse raw model query/subscription result JSON into typed model instances.
921
+ * Used by ModelQueryBuilder to convert subscription updates without circular imports.
922
+ * @internal
923
+ */
924
+ static parseModelResult<T extends Ad4mModel>(
925
+ this: typeof Ad4mModel & (new (...args: any[]) => T),
926
+ perspective: PerspectiveProxy,
927
+ raw: any,
928
+ include?: IncludeMap,
929
+ properties?: string[],
930
+ ): T[] {
931
+ const data = typeof raw === 'string' ? JSON.parse(raw) : raw;
932
+ const arr = data.instances || data;
933
+ if (!Array.isArray(arr)) return [];
934
+ return arr.map((json: any) => jsonToModelInstance(this, perspective, json, include, properties));
780
935
  }
781
936
 
937
+ // instancesFromQueryResult — removed (superseded by Rust executeModelQuery pipeline)
938
+
782
939
  /**
783
- * Converts SPARQL query results to Ad4mModel instances.
940
+ * Execute a model query via the executor-side endpoint.
784
941
  *
785
- * @param perspective - The perspective context
786
- * @param query - The query parameters used
787
- * @param result - Array of result objects from SPARQL
788
- * @returns Promise resolving to results with total count
942
+ * This replaces the old SPARQL-build → hydrate → JS-filter → JS-sort → JS-paginate pipeline
943
+ * with a single RPC to the executor that handles everything in Rust.
789
944
  *
790
945
  * @internal
791
946
  */
792
- public static async instancesFromQueryResult<T extends Ad4mModel>(
793
- this: typeof Ad4mModel & (new (...args: any[]) => T),
947
+ private static async executeModelQuery<T extends Ad4mModel>(
948
+ this: typeof Ad4mModel & (new (...args: any[]) => T),
794
949
  perspective: PerspectiveProxy,
795
- query: Query,
796
- result: any[]
950
+ query: Query = {},
951
+ classNameOverride?: string | null,
797
952
  ): Promise<ResultsWithTotalCount<T>> {
798
- if (!result || result.length === 0) return { results: [], totalCount: 0 };
799
-
800
953
  const metadata = this.getModelMetadata();
801
- const requestedProperties = query?.properties || [];
802
-
803
- // The query used GROUP BY with graph traversal, so each row has:
804
- // - source: the node ID (e.g., "node:abc123")
805
- // - source_uri: the actual URI (the base expression)
806
- // - links: array of link objects with {predicate, target, author, timestamp}
807
-
808
- const instances: T[] = [];
809
- for (const row of result) {
810
- let base;
811
- try {
812
- // Use source_uri as the base (the actual URI), not the node ID
813
- base = row.source_uri;
954
+ const className = classNameOverride || metadata.className;
955
+
956
+ // Expand includeAll: true to a full IncludeMap covering every forward relation.
957
+ // Done before queryInput is built so all downstream uses of query.include see the expansion.
958
+ if (query.includeAll) {
959
+ const allRelMeta = getRelationsMetadata(this as any);
960
+ const expanded: IncludeMap = {};
961
+ for (const [relName, relMeta] of Object.entries(allRelMeta)) {
962
+ if ((relMeta as any).direction !== 'reverse') {
963
+ expanded[relName] = true;
964
+ }
965
+ }
966
+ // Explicit include entries take precedence over the expansion
967
+ query = { ...query, include: { ...expanded, ...query.include } };
968
+ }
814
969
 
815
- // Skip rows without a source_uri field
816
- if (!base) {
817
- continue;
970
+ // Build the query input that the Rust endpoint expects.
971
+ // Convert the TS Query type to the executor's ModelQueryInput format.
972
+ const queryInput: any = {};
973
+ if (query.parent) {
974
+ const parentPredicate = resolveParentPredicate(query.parent, this);
975
+ queryInput.parent = { id: query.parent.id, predicate: parentPredicate };
976
+ }
977
+ if (query.properties) queryInput.properties = query.properties;
978
+ if (query.include) {
979
+ // Split include keys: $-prefixed / IncludeProjection values → queryInput.projections
980
+ // All other keys (boolean | RelationSubQuery) → queryInput.include
981
+ const normalIncludes: IncludeMap = {};
982
+ const projections: Record<string, IncludeProjection> = {};
983
+ for (const [key, val] of Object.entries(query.include)) {
984
+ if (key.startsWith('$')) {
985
+ projections[key] = val as IncludeProjection;
986
+ } else {
987
+ normalIncludes[key] = val;
818
988
  }
819
-
820
- const links = row.links || [];
821
-
822
- const instance = new this(perspective, base) as any;
823
-
824
- // Core hydration via unified helper (pass requestedProperties for sparse fieldset).
825
- // Also hydrate any properties referenced in `where` so the JS post-filter can match them,
826
- // even if they're not in the user's `properties` projection.
827
- let hydrationProps = requestedProperties.length > 0 ? [...requestedProperties] : undefined;
828
- if (hydrationProps && query.where) {
829
- for (const key of Object.keys(query.where)) {
830
- if (!hydrationProps.includes(key)) {
831
- hydrationProps.push(key);
832
- }
989
+ }
990
+ if (Object.keys(normalIncludes).length > 0) queryInput.include = normalIncludes;
991
+ if (Object.keys(projections).length > 0) {
992
+ // Enrich projections with target shapes so Rust can apply where clause filtering
993
+ const allRelMeta = getRelationsMetadata(this as any);
994
+ for (const [, proj] of Object.entries(projections)) {
995
+ const relMeta = allRelMeta[proj.from];
996
+ if (!proj.targetShape && relMeta?.target) {
997
+ try {
998
+ const TargetClass = relMeta.target();
999
+ const targetMeta = (TargetClass as any).getModelMetadata?.();
1000
+ if (targetMeta) {
1001
+ proj.targetShape = targetMeta;
1002
+ }
1003
+ } catch (_) { /* target class may not be available */ }
833
1004
  }
834
1005
  }
835
- await hydrateFromLinks(instance, links, metadata, perspective, hydrationProps);
836
-
837
- // NOTE: Property deletion for sparse fieldsets is deferred until AFTER
838
- // where-filtering so that where conditions can reference any property,
839
- // even ones not in the `properties` projection.
840
-
841
- instances.push(instance);
842
- } catch (error) {
843
- console.error(`Failed to process SPARQL instance ${base}:`, error);
1006
+ queryInput.projections = projections;
844
1007
  }
845
1008
  }
846
-
847
- // Populate reverse relation fields (belongsToOne / belongsToMany) as string IDs.
848
- // These relations point FROM other nodes TO this instance, so they cannot be resolved
849
- // from the node's own outgoing links fetched above. We do a reverse-link lookup here
850
- // so that these fields are populated as IDs even without an explicit include.
851
- const allRelsMeta = getRelationsMetadata(this as any);
852
- const reverseRelEntries = Object.entries(allRelsMeta).filter(
853
- ([relName, meta]) =>
854
- (meta.kind === 'belongsToOne' || meta.kind === 'belongsToMany') &&
855
- (requestedProperties.length === 0 || requestedProperties.includes(relName))
856
- );
857
- if (reverseRelEntries.length > 0 && instances.length > 0) {
858
- await Promise.all(
859
- instances.map(async (inst) => {
860
- for (const [relName, relMeta] of reverseRelEntries) {
861
- const reverseLinks = await perspective.get(
862
- new LinkQuery({ predicate: relMeta.predicate, target: inst.id })
863
- );
864
- const sourceIds = reverseLinks
865
- .filter((l) => l.data.target === inst.id)
866
- .map((l) => l.data.source);
867
- if (relMeta.kind === 'belongsToOne') {
868
- (inst as any)[relName] = sourceIds.length > 0 ? sourceIds[sourceIds.length - 1] : null;
869
- } else {
870
- (inst as any)[relName] = sourceIds;
871
- }
872
- }
873
- })
874
- );
1009
+ if (query.where) queryInput.where = query.where;
1010
+ if (query.order) {
1011
+ // Convert { propName: 'ASC' | 'DESC' } to [[propName, 'ASC'|'DESC'], ...]
1012
+ queryInput.order = Object.entries(query.order).map(([k, v]) => [k, v]);
875
1013
  }
876
-
877
- // Evaluate custom getters for all instances (single pass)
878
- const getterOpts = requestedProperties.length > 0 || query.include
879
- ? { requestedProperties, include: query.include }
880
- : undefined;
881
- for (const instance of instances) {
882
- await evaluateCustomGettersForInstance(instance, perspective, metadata, getterOpts);
1014
+ if (query.offset !== undefined) queryInput.offset = query.offset;
1015
+ if (query.limit !== undefined) queryInput.limit = query.limit;
1016
+ if (query.count !== undefined) queryInput.count = query.count;
1017
+
1018
+ // Enrich relation metadata with target class shapes for Rust-side
1019
+ // include resolution. This eliminates per-relation GraphQL round-trips
1020
+ // by letting the Rust endpoint resolve includes in-process.
1021
+ if (queryInput.include) {
1022
+ const allRelMeta = getRelationsMetadata(this as any);
1023
+ enrichShapeForIncludes(metadata, queryInput.include, allRelMeta);
883
1024
  }
884
-
885
- // Filter by where conditions that couldn't be filtered in SPARQL
886
- // This includes:
887
- // - author/timestamp (computed from grouped links)
888
- // - Properties with comparison operators (gt, gte, lt, lte, between, contains)
889
- // because fn::parse_literal() comparisons in SPARQL subqueries don't work reliably
890
- // - Relation-based where clauses (e.g., { post: postId } for @BelongsToOne)
891
- // which require reverse-link resolution before filtering
892
- let filteredInstances = instances;
893
- if (query.where) {
894
- filteredInstances = instances.filter(instance => {
895
- for (const [propertyName, condition] of Object.entries(query.where!)) {
896
- // Skip 'base'/'id' as it's filtered in SPARQL
897
- if (propertyName === 'base' || propertyName === 'id') continue;
898
-
899
- // For author and timestamp, always filter in JS
900
- if (propertyName === 'author' || propertyName === 'timestamp') {
901
- if (!matchesCondition(instance[propertyName], condition)) {
902
- return false;
903
- }
904
- continue;
905
- }
906
1025
 
907
- // Check if this is a relation field (not in properties metadata)
908
- const isPropField = propertyName in metadata.properties;
1026
+ // ── Pre-compute conformance getters for Rust-side evaluation ──────
1027
+ // For each relation with a target class and filter !== false, compute
1028
+ // the conformance getter SPARQL so Rust can evaluate it in-process
1029
+ // (eliminating N × querySparql round-trips per instance).
1030
+ // When a relation has a `where` clause, compile the where conditions
1031
+ // into the getter SPARQL so Rust applies them during evaluation.
1032
+ {
1033
+ const allRelMeta = getRelationsMetadata(this as any);
1034
+ for (const [relName, relMeta] of Object.entries(metadata.relations)) {
1035
+ const rel = relMeta as any;
1036
+ if (rel.getter) continue; // explicit getter already set
1037
+ if (rel.direction === 'reverse') continue; // reverse relations use reverse link lookup
1038
+ if (rel.filter === false) continue; // opt-out of conformance filtering
1039
+
1040
+ const meta = allRelMeta[relName];
1041
+ if (!meta?.target) continue;
909
1042
 
910
- if (!isPropField) {
911
- // Relation-based where — filter in JS against the populated field
912
- if (!matchesCondition(instance[propertyName], condition)) {
913
- return false;
914
- }
915
- continue;
1043
+ try {
1044
+ const TargetClass = meta.target();
1045
+ const filter = buildConformanceFilter(meta.predicate, TargetClass);
1046
+
1047
+ // Only compile where clauses to SPARQL when the target properties
1048
+ // are stored as plain IRIs (not signed expressions). Properties
1049
+ // without resolveLanguage or with resolveLanguage='literal' store
1050
+ // values as signed JSON envelopes, so SPARQL exact-match fails.
1051
+ let whereConditions: string[] = [];
1052
+ if (rel.where) {
1053
+ try {
1054
+ const targetMetadata = (TargetClass as any).getModelMetadata?.() ?? null;
1055
+ let allSparqlFilterable = true;
1056
+ if (targetMetadata) {
1057
+ for (const propName of Object.keys(rel.where)) {
1058
+ if (['id', 'author', 'timestamp'].includes(propName)) continue;
1059
+ const propMeta = targetMetadata.properties[propName];
1060
+ if (propMeta && (!propMeta.resolveLanguage || propMeta.resolveLanguage === 'literal')) {
1061
+ allSparqlFilterable = false;
1062
+ break;
1063
+ }
1064
+ }
1065
+ } else {
1066
+ allSparqlFilterable = false;
1067
+ }
1068
+ if (allSparqlFilterable) {
1069
+ whereConditions = compileWhereClause(rel.where, targetMetadata);
1070
+ }
1071
+ } catch (_) { /* target metadata unavailable */ }
916
1072
  }
917
1073
 
918
- // Filter ALL property conditions in JS (equality, NOT, IN, comparison operators).
919
- // SPARQL-level filtering with parse_literal is unreliable across environments,
920
- // so we do all property filtering here after hydration resolves values.
921
- if (!matchesCondition(instance[propertyName], condition)) {
922
- return false;
1074
+ if (filter) {
1075
+ let getter = filter.getter;
1076
+ if (whereConditions.length > 0) {
1077
+ // Append where conditions before the closing }
1078
+ getter = getter.replace(/ \}$/, ` ${whereConditions.join(' ')} }`);
1079
+ }
1080
+ rel.getter = getter;
1081
+ } else if (whereConditions.length > 0) {
1082
+ // No conformance filter but where clause exists — build getter from where alone
1083
+ const escapedPred = meta.predicate.replace(/[<>"{}|\\^`\u0000-\u0020]/g, '');
1084
+ rel.getter = `SELECT ?target WHERE { <Base> <${escapedPred}> ?target . ${whereConditions.join(' ')} }`;
923
1085
  }
1086
+ } catch (e) {
1087
+ // Target class may not be available; skip silently
924
1088
  }
925
- return true;
926
- });
1089
+ }
927
1090
  }
928
1091
 
929
- // Apply ordering in JavaScript
930
- // If limit/offset is used but no explicit order, default to ordering by timestamp (ASC)
931
- // This ensures consistent pagination behavior
932
- const effectiveOrder = query.order ||
933
- (query.limit !== undefined || query.offset !== undefined ? { timestamp: 'ASC' as 'ASC' } : null);
934
-
935
- if (effectiveOrder) {
936
- const orderEntries = Object.entries(effectiveOrder);
937
-
938
- filteredInstances.sort((a: any, b: any) => {
939
- for (const [orderPropName, orderDirection] of orderEntries) {
940
- let aVal = a[orderPropName];
941
- let bVal = b[orderPropName];
942
-
943
- // Handle undefined values - push them to the end
944
- if (aVal === undefined && bVal === undefined) continue;
945
- if (aVal === undefined) return orderDirection === 'ASC' ? 1 : -1;
946
- if (bVal === undefined) return orderDirection === 'ASC' ? -1 : 1;
947
-
948
- // Compare values
949
- let comparison = 0;
950
- if (typeof aVal === 'number' && typeof bVal === 'number') {
951
- comparison = aVal - bVal;
952
- } else if (typeof aVal === 'string' && typeof bVal === 'string') {
953
- comparison = aVal.localeCompare(bVal);
954
- } else {
955
- comparison = String(aVal).localeCompare(String(bVal));
1092
+ // Send shape metadata to the executor so it knows the model structure.
1093
+ // This is more reliable than reading SHACL from the store because
1094
+ // the TS decorators are the definitive source of truth.
1095
+ const shapeJson = JSON.stringify(metadata);
1096
+ const queryJson = JSON.stringify(queryInput);
1097
+
1098
+ const result = await perspective.modelQuery(className, queryJson, shapeJson);
1099
+
1100
+ // Convert JSON instances to model class instances, recursively constructing
1101
+ // class instances for any included relations resolved by Rust.
1102
+ const instances: T[] = result.instances.map((json: any) => {
1103
+ return jsonToModelInstance(this, perspective, json, query.include, query.properties);
1104
+ });
1105
+
1106
+ // Resolve non-literal expressions (e.g. file languages where the stored
1107
+ // value is a content-addressed hash that must be fetched from the language
1108
+ // runtime). The Rust endpoint returns raw target URIs; we resolve them here.
1109
+ const propsMeta = getPropertiesMetadata(this as any);
1110
+ const resolveProps = Object.entries(propsMeta).filter(
1111
+ ([, opts]: [string, any]) =>
1112
+ opts.resolveLanguage != null &&
1113
+ opts.resolveLanguage !== 'literal',
1114
+ );
1115
+ if (resolveProps.length > 0) {
1116
+ await Promise.all(
1117
+ instances.map(async (inst: any) => {
1118
+ for (const [propName, opts] of resolveProps) {
1119
+ const val = inst[propName];
1120
+ if (typeof val !== 'string' || !val || val.startsWith('literal:')) continue;
1121
+ try {
1122
+ const expression = await perspective.getExpression(val);
1123
+ if (expression) {
1124
+ let resolved: any;
1125
+ try { resolved = JSON.parse(expression.data); } catch { resolved = expression.data; }
1126
+ const transform = (opts as any).transform;
1127
+ inst[propName] = typeof transform === 'function' ? transform(resolved) : resolved;
1128
+ }
1129
+ } catch (_) { /* resolution failed — keep raw value */ }
956
1130
  }
1131
+ }),
1132
+ );
1133
+ }
957
1134
 
958
- if (comparison !== 0) {
959
- return orderDirection === 'DESC' ? -comparison : comparison;
960
- }
961
- // comparison === 0: continue to next sort field
1135
+ // Relation conformance getters are evaluated Rust-side via evaluate_getters()
1136
+ // in model_query.rs. However, for relations with non-SPARQL-filterable where
1137
+ // clauses (e.g. properties stored as signed expressions), we still need
1138
+ // TS-side evaluation as a fallback. Running evaluateCustomGettersForInstance
1139
+ // with skipPropertyGetters ensures conformance + JS post-filtering for
1140
+ // where clauses that couldn't be compiled to SPARQL.
1141
+ const includedRelNames = queryInput.include ? new Set(Object.keys(queryInput.include)) : new Set<string>();
1142
+ for (const inst of instances) {
1143
+ // Save included relation values that came from Rust hydration
1144
+ const savedIncluded: Record<string, any> = {};
1145
+ for (const relName of includedRelNames) {
1146
+ if ((inst as any)[relName] !== undefined) {
1147
+ savedIncluded[relName] = (inst as any)[relName];
962
1148
  }
963
- return 0;
964
- });
965
- }
1149
+ }
966
1150
 
967
- // Calculate totalCount BEFORE applying limit/offset
968
- const totalCount = filteredInstances.length;
1151
+ await evaluateCustomGettersForInstance(inst, perspective, metadata, {
1152
+ skipPropertyGetters: true,
1153
+ });
969
1154
 
970
- // Apply offset and limit in JavaScript
971
- let paginatedInstances = filteredInstances;
972
- if (query.offset !== undefined || query.limit !== undefined) {
973
- const start = query.offset || 0;
974
- const end = query.limit ? start + query.limit : undefined;
975
- paginatedInstances = filteredInstances.slice(start, end);
976
- }
1155
+ // Restore hydrated include objects that were overwritten by conformance getters
1156
+ for (const [relName, value] of Object.entries(savedIncluded)) {
1157
+ (inst as any)[relName] = value;
1158
+ }
977
1159
 
978
- // Now that where-filtering is done, strip unrequested properties for sparse fieldsets.
979
- // This must happen AFTER where-filtering so conditions can reference any property.
980
- if (requestedProperties.length > 0) {
981
- const requested = new Set(requestedProperties);
982
- for (const inst of paginatedInstances) {
983
- for (const propName of Object.keys(metadata.properties)) {
984
- if (!requested.has(propName)) {
985
- delete (inst as any)[propName];
986
- }
987
- }
988
- for (const relName of Object.keys(metadata.relations)) {
989
- if (!requested.has(relName) && !(query.include && relName in query.include)) {
990
- delete (inst as any)[relName];
991
- }
992
- }
993
- for (const metaField of ['author', 'createdAt', 'updatedAt'] as const) {
994
- if (!requested.has(metaField)) {
995
- delete (inst as any)[metaField];
996
- }
1160
+ // Fix cardinality for non-included HasOne/BelongsToOne relations:
1161
+ // The conformance getter always produces arrays; unwrap to scalar.
1162
+ for (const [relName, relMeta] of Object.entries(metadata.relations)) {
1163
+ if (includedRelNames.has(relName)) continue;
1164
+ const kind = (relMeta as any).kind;
1165
+ if ((kind === 'hasOne' || kind === 'belongsToOne') && Array.isArray((inst as any)[relName])) {
1166
+ const arr = (inst as any)[relName] as any[];
1167
+ (inst as any)[relName] = arr.length > 0 ? arr[0] : null;
997
1168
  }
998
1169
  }
999
1170
  }
1000
1171
 
1001
- // Eager-load relations if requested (BEFORE snapshot so dirty tracking is accurate)
1002
- if (query.include && paginatedInstances.length > 0) {
1003
- await hydrateRelations(this, paginatedInstances, perspective, query.include);
1004
- }
1005
-
1006
- // Take snapshots for dirty tracking after ALL hydration is complete
1007
- // (including eager-loaded relations).
1008
- // When `include` is specified, only snapshot those relations.
1009
- // Otherwise snapshot ALL fields (properties + relations) since
1010
- // hydrateFromLinks populates relations with stable raw IDs —
1011
- // this ensures push-to-array + save() correctly detects dirty relations.
1012
- const snapshotRelations = query.include;
1013
- for (const inst of paginatedInstances) {
1172
+ // Take snapshots for dirty tracking
1173
+ const snapshotRelations = queryInput.include;
1174
+ for (const inst of instances) {
1014
1175
  (inst as Ad4mModel).takeSnapshot(snapshotRelations);
1015
1176
  }
1016
1177
 
1017
1178
  return {
1018
- results: paginatedInstances,
1019
- totalCount
1179
+ results: instances,
1180
+ totalCount: result.totalCount,
1020
1181
  };
1021
1182
  }
1022
1183
 
@@ -1051,33 +1212,14 @@ export class Ad4mModel {
1051
1212
  this: typeof Ad4mModel & (new (...args: any[]) => T),
1052
1213
  perspective: PerspectiveProxy,
1053
1214
  query: Query = {},
1054
- engine: 'sparql' | 'prolog' | boolean = 'sparql'
1215
+ _engine?: 'sparql' | 'prolog' | boolean
1055
1216
  ): Promise<T[]> {
1056
1217
  if (query.properties && query.properties.length === 0) {
1057
1218
  throw new Error("properties[] must not be empty — omit the field to return all properties, or specify at least one field name");
1058
1219
  }
1059
1220
 
1060
- // Backward compatibility: boolean maps to sparql (true) or prolog (false)
1061
- const resolvedEngine = typeof engine === 'boolean'
1062
- ? (engine ? 'sparql' : 'prolog')
1063
- : engine;
1064
-
1065
- if (resolvedEngine === 'sparql') {
1066
- // Always use the regular SPARQL path + JS-level hydrateRelations for includes.
1067
- // The batch SPARQL approach had issues with sub-queries (where/order/limit on includes),
1068
- // non-conforming node filtering, and parse_literal compatibility.
1069
- // hydrateRelations handles all of these correctly via per-relation findAll calls.
1070
- const sparqlQuery = await this.queryToSPARQL(perspective, query);
1071
- const rawResult = await perspective.querySparql(sparqlQuery);
1072
- const grouped = groupSPARQLResults(rawResult);
1073
- const { results } = await this.instancesFromQueryResult(perspective, query, grouped);
1074
- return results;
1075
- } else {
1076
- const prologQuery = await this.queryToProlog(perspective, query);
1077
- const result = await perspective.infer(prologQuery);
1078
- const { results } = await this.instancesFromPrologResult(perspective, query, result);
1079
- return results;
1080
- }
1221
+ const { results } = await this.executeModelQuery(perspective, query);
1222
+ return results;
1081
1223
  }
1082
1224
 
1083
1225
  /**
@@ -1104,10 +1246,10 @@ export class Ad4mModel {
1104
1246
  this: typeof Ad4mModel & (new (...args: any[]) => T),
1105
1247
  perspective: PerspectiveProxy,
1106
1248
  query: Query = {},
1107
- engine: 'sparql' | 'prolog' | boolean = 'sparql',
1249
+ _engine?: 'sparql' | 'prolog' | boolean,
1108
1250
  ): Promise<T | null> {
1109
1251
  const limitedQuery = { ...query, limit: 1 };
1110
- const results = await this.findAll(perspective, limitedQuery, engine);
1252
+ const results = await this.findAll(perspective, limitedQuery);
1111
1253
  return results[0] ?? null;
1112
1254
  }
1113
1255
 
@@ -1135,22 +1277,9 @@ export class Ad4mModel {
1135
1277
  this: typeof Ad4mModel & (new (...args: any[]) => T),
1136
1278
  perspective: PerspectiveProxy,
1137
1279
  query: Query = {},
1138
- engine: 'sparql' | 'prolog' | boolean = 'sparql'
1280
+ _engine?: 'sparql' | 'prolog' | boolean
1139
1281
  ): Promise<ResultsWithTotalCount<T>> {
1140
- const resolvedEngine = typeof engine === 'boolean'
1141
- ? (engine ? 'sparql' : 'prolog')
1142
- : engine;
1143
-
1144
- if (resolvedEngine === 'sparql') {
1145
- const sparqlQuery = await this.queryToSPARQL(perspective, query);
1146
- const rawResult = await perspective.querySparql(sparqlQuery);
1147
- const grouped = groupSPARQLResults(rawResult);
1148
- return await this.instancesFromQueryResult(perspective, query, grouped);
1149
- } else {
1150
- const prologQuery = await this.queryToProlog(perspective, query);
1151
- const result = await perspective.infer(prologQuery);
1152
- return await this.instancesFromPrologResult(perspective, query, result);
1153
- }
1282
+ return await this.executeModelQuery(perspective, query);
1154
1283
  }
1155
1284
 
1156
1285
  /**
@@ -1160,7 +1289,6 @@ export class Ad4mModel {
1160
1289
  * @param pageSize - Number of items per page
1161
1290
  * @param pageNumber - Which page to retrieve (1-based)
1162
1291
  * @param query - Optional additional query parameters
1163
- * @param useSPARQL - Whether to use SPARQL (default: true, 10-100x faster) or Prolog (legacy)
1164
1292
  * @returns Paginated results with metadata
1165
1293
  *
1166
1294
  * @example
@@ -1169,9 +1297,6 @@ export class Ad4mModel {
1169
1297
  * where: { category: "Main Course" }
1170
1298
  * });
1171
1299
  * console.log(`Page ${page.pageNumber} of recipes, ${page.results.length} items`);
1172
- *
1173
- * // Use Prolog explicitly (legacy)
1174
- * const pageProlog = await Recipe.paginate(perspective, 10, 1, {}, false);
1175
1300
  * ```
1176
1301
  */
1177
1302
  static async paginate<T extends Ad4mModel>(
@@ -1180,46 +1305,11 @@ export class Ad4mModel {
1180
1305
  pageSize: number,
1181
1306
  pageNumber: number,
1182
1307
  query?: Query,
1183
- engine: 'sparql' | 'prolog' | boolean = 'sparql'
1308
+ _engine?: 'sparql' | 'prolog' | boolean
1184
1309
  ): Promise<PaginationResult<T>> {
1185
1310
  const paginationQuery = { ...(query || {}), limit: pageSize, offset: pageSize * (pageNumber - 1), count: true };
1186
- const resolvedEngine = typeof engine === 'boolean'
1187
- ? (engine ? 'sparql' : 'prolog')
1188
- : engine;
1189
-
1190
- if (resolvedEngine === 'sparql') {
1191
- const sparqlQuery = await this.queryToSPARQL(perspective, paginationQuery);
1192
- const rawResult = await perspective.querySparql(sparqlQuery);
1193
- const grouped = groupSPARQLResults(rawResult);
1194
- const { results, totalCount } = await this.instancesFromQueryResult(perspective, paginationQuery, grouped);
1195
- return { results, totalCount, pageSize, pageNumber };
1196
- } else {
1197
- const prologQuery = await this.queryToProlog(perspective, paginationQuery);
1198
- const result = await perspective.infer(prologQuery);
1199
- const { results, totalCount } = await this.instancesFromPrologResult(perspective, paginationQuery, result);
1200
- return { results, totalCount, pageSize, pageNumber };
1201
- }
1202
- }
1203
-
1204
- static async countQueryToProlog(perspective: PerspectiveProxy, query: Query = {}, modelClassName?: string | null) {
1205
- const { where } = query;
1206
- const className = modelClassName || (await this.getClassName(perspective));
1207
- const resolvedParentPredicate = query.parent
1208
- ? resolveParentPredicate(query.parent, this)
1209
- : undefined;
1210
- const instanceQueries = [buildAuthorAndTimestampQuery(), buildParentQuery(query.parent, resolvedParentPredicate), buildWhereQuery(where)];
1211
- const resultSetQueries = [buildCountQuery(true), buildOrderQuery(), buildOffsetQuery(), buildLimitQuery()];
1212
-
1213
- const fullQuery = `
1214
- findall([Base, Properties, Collections, Timestamp, Author], (
1215
- subject_class("${className}", SubjectClass),
1216
- instance(SubjectClass, Base),
1217
- ${instanceQueries.filter((q) => q).join(", ")}
1218
- ), UnsortedInstances),
1219
- ${resultSetQueries.filter((q) => q).join(", ")}
1220
- `;
1221
-
1222
- return fullQuery;
1311
+ const { results, totalCount } = await this.executeModelQuery(perspective, paginationQuery);
1312
+ return { results, totalCount, pageSize, pageNumber };
1223
1313
  }
1224
1314
 
1225
1315
  /**
@@ -1231,21 +1321,13 @@ export class Ad4mModel {
1231
1321
  *
1232
1322
  * @private
1233
1323
  */
1234
- public static async countQueryToSPARQL(perspective: PerspectiveProxy, query: Query): Promise<string> {
1235
- // Use the same query as the main query (with GROUP BY), just without LIMIT/OFFSET
1236
- // We'll count the number of rows returned (one row per source)
1237
- const countQuery = { ...query };
1238
- delete countQuery.limit;
1239
- delete countQuery.offset;
1240
- return await this.queryToSPARQL(perspective, countQuery);
1241
- }
1324
+ // countQueryToSPARQL — removed (zero callers; Rust COUNT fast-path supersedes)
1242
1325
 
1243
1326
  /**
1244
1327
  * Gets a count of all matching instances.
1245
1328
  *
1246
1329
  * @param perspective - The perspective to search in
1247
1330
  * @param query - Optional query parameters to filter results
1248
- * @param useSPARQL - Whether to use SPARQL (default: true, 10-100x faster) or Prolog (legacy)
1249
1331
  * @returns Total count of matching entities
1250
1332
  *
1251
1333
  * @example
@@ -1254,26 +1336,11 @@ export class Ad4mModel {
1254
1336
  * const activeRecipes = await Recipe.count(perspective, {
1255
1337
  * where: { status: "active" }
1256
1338
  * });
1257
- *
1258
- * // Use Prolog explicitly (legacy)
1259
- * const countProlog = await Recipe.count(perspective, {}, false);
1260
1339
  * ```
1261
1340
  */
1262
- static async count(perspective: PerspectiveProxy, query: Query = {}, engine: 'sparql' | 'prolog' | boolean = 'sparql') {
1263
- const resolvedEngine = typeof engine === 'boolean'
1264
- ? (engine ? 'sparql' : 'prolog')
1265
- : engine;
1266
-
1267
- if (resolvedEngine === 'sparql') {
1268
- const sparqlQuery = await this.queryToSPARQL(perspective, query);
1269
- const rawResult = await perspective.querySparql(sparqlQuery);
1270
- const grouped = groupSPARQLResults(rawResult);
1271
- const { totalCount } = await this.instancesFromQueryResult(perspective, query, grouped);
1272
- return totalCount;
1273
- } else {
1274
- const result = await perspective.infer(await this.countQueryToProlog(perspective, query));
1275
- return result?.[0]?.TotalCount || 0;
1276
- }
1341
+ static async count(perspective: PerspectiveProxy, query: Query = {}): Promise<number> {
1342
+ const { totalCount } = await this.executeModelQuery(perspective, { ...query, limit: 0 });
1343
+ return totalCount;
1277
1344
  }
1278
1345
 
1279
1346
  private async setProperty(key: string, value: any, batchId?: string) {
@@ -1605,6 +1672,67 @@ export class Ad4mModel {
1605
1672
  }
1606
1673
  }
1607
1674
 
1675
+ /**
1676
+ * Evaluate SPARQL getters for a batch of instances on demand.
1677
+ *
1678
+ * Use after a shallow collection query (the default) to resolve
1679
+ * getter-backed properties for visible items only. This avoids the
1680
+ * O(N × getters) cost of evaluating every getter on every instance in
1681
+ * a large collection query.
1682
+ *
1683
+ * @param instances - Array of model instances to evaluate getters on
1684
+ * @param perspective - The perspective to query against
1685
+ * @param propertyNames - Optional list of getter-backed property names to evaluate.
1686
+ * If omitted, all getters are evaluated.
1687
+ *
1688
+ * @example
1689
+ * ```typescript
1690
+ * const messages = await Message.findAll(perspective, { parent: channel, limit: 30 });
1691
+ * // messages[i].replyingTo is undefined (getter skipped by default)
1692
+ *
1693
+ * // Evaluate getters for the visible subset
1694
+ * await Message.evaluateGetters(messages.slice(0, 10), perspective, ['replyingTo']);
1695
+ * // messages[0..9].replyingTo is now populated
1696
+ * ```
1697
+ */
1698
+ static async evaluateGetters<T extends Ad4mModel>(
1699
+ instances: T[],
1700
+ perspective: PerspectiveProxy,
1701
+ propertyNames?: string[],
1702
+ ): Promise<void> {
1703
+ if (instances.length === 0) return;
1704
+ const metadata = this.getModelMetadata();
1705
+ const opts = propertyNames && propertyNames.length > 0
1706
+ ? { requestedProperties: propertyNames }
1707
+ : undefined;
1708
+
1709
+ // Determine which property names will actually be evaluated
1710
+ const evaluatedPropertyNames: string[] = [];
1711
+ for (const [propName, propMeta] of Object.entries(metadata.properties)) {
1712
+ if ((propMeta as any).getter) {
1713
+ if (!propertyNames || propertyNames.length === 0 || propertyNames.includes(propName)) {
1714
+ evaluatedPropertyNames.push(propName);
1715
+ }
1716
+ }
1717
+ }
1718
+
1719
+ for (const instance of instances) {
1720
+ await evaluateCustomGettersForInstance(instance, perspective, metadata, opts);
1721
+ // Sync snapshot so isDirty() doesn't flag getter-only changes.
1722
+ // evaluateGetters() mutates instances in place, but their snapshots
1723
+ // were already taken during hydration. Without this sync, the computed
1724
+ // getter values would make isDirty() return true and save() would try
1725
+ // to write read-only computed properties.
1726
+ const modelInstance = instance as Ad4mModel;
1727
+ if (modelInstance._snapshot) {
1728
+ for (const propName of evaluatedPropertyNames) {
1729
+ const val = (instance as any)[propName];
1730
+ modelInstance._snapshot[propName] = normalizeValue(Array.isArray(val) ? [...val] : val);
1731
+ }
1732
+ }
1733
+ }
1734
+ }
1735
+
1608
1736
  /**
1609
1737
  * Gets the model instance with all properties and relations populated.
1610
1738
  *
@@ -2018,5 +2146,96 @@ export class Ad4mModel {
2018
2146
  ): typeof Ad4mModel {
2019
2147
  return buildModelFromJSONSchema(this, schema, options);
2020
2148
  }
2149
+
2150
+ /**
2151
+ * Creates a fully functional Ad4mModel subclass from a SHACL shape.
2152
+ *
2153
+ * Unlike `fromJSONSchema()`, no predicate inference is required —
2154
+ * `SHACLShape` already contains the exact predicate URI in `path` for
2155
+ * every property. The method reads each property's `path`, `maxCount`,
2156
+ * `writable`, and `resolveLanguage` directly and writes them to the
2157
+ * WeakMap metadata registries.
2158
+ *
2159
+ * Properties with `hasValue` (flag / type-discrimination markers) are
2160
+ * registered as hidden flag entries so that the SPARQL query builder emits
2161
+ * the fixed triple `?source <predicate> <value>` needed for type discrimination.
2162
+ * Properties without a `name` field are skipped.
2163
+ *
2164
+ * **Backward-compat:** Old Flux SHACL shapes (created before `sh:hasValue`
2165
+ * was persisted on property shapes) carry the flag value only in
2166
+ * `shape.constructor_actions` as the `target` of an `addLink` action.
2167
+ * This method recovers those values so that old perspectives are queried
2168
+ * with the correct type-discriminator triple.
2169
+ *
2170
+ * @param shape - SHACL node shape (as returned by `PerspectiveProxy.getAllShacl()`)
2171
+ * @param name - Class name to assign (e.g. "Channel")
2172
+ * @returns Generated Ad4mModel subclass, ready for querying
2173
+ */
2174
+ static fromSHACL(shape: SHACLShape, name: string): typeof Ad4mModel {
2175
+ const DynamicModelClass = class extends (this as any) {} as unknown as typeof Ad4mModel;
2176
+ (DynamicModelClass as any).className = name;
2177
+ (DynamicModelClass.prototype as any).className = name;
2178
+
2179
+ // Build a backward-compat fallback map: predicate → fixed-IRI-value from
2180
+ // constructor actions. Old SHACL stores (created before sh:hasValue was
2181
+ // persisted on the property shape) don't carry sh:hasValue on properties,
2182
+ // but the shape-level constructor_actions always contain an addLink action
2183
+ // with the fixed flag value as the target.
2184
+ const flagValueFromConstructor = new Map<string, string>();
2185
+ for (const action of shape.constructor_actions ?? []) {
2186
+ if (
2187
+ action.action === 'addLink' &&
2188
+ typeof action.predicate === 'string' &&
2189
+ typeof action.target === 'string' &&
2190
+ action.target !== 'value' &&
2191
+ !action.target.startsWith('literal:')
2192
+ ) {
2193
+ flagValueFromConstructor.set(action.predicate, action.target);
2194
+ }
2195
+ }
2196
+
2197
+ for (const prop of shape.properties) {
2198
+ const resolvedHasValue = prop.hasValue ?? flagValueFromConstructor.get(prop.path);
2199
+
2200
+ if (resolvedHasValue !== undefined) {
2201
+ const flagKey = prop.name ?? `_flag_${prop.path.replace(/[^a-zA-Z0-9_]/g, '_')}`;
2202
+ setPropertyRegistryEntry(DynamicModelClass, flagKey, {
2203
+ through: prop.path,
2204
+ required: true,
2205
+ initial: resolvedHasValue,
2206
+ flag: true,
2207
+ writable: false,
2208
+ readOnly: true,
2209
+ });
2210
+ continue;
2211
+ }
2212
+
2213
+ // Skip properties without a declared name
2214
+ if (!prop.name) continue;
2215
+
2216
+ const isCollection = prop.maxCount === undefined || prop.maxCount > 1;
2217
+
2218
+ if (isCollection) {
2219
+ setRelationRegistryEntry(DynamicModelClass, prop.name, {
2220
+ predicate: prop.path,
2221
+ kind: 'hasMany',
2222
+ ...(prop.local !== undefined && { local: prop.local }),
2223
+ ...(prop.getter !== undefined && { getter: prop.getter }),
2224
+ });
2225
+ } else {
2226
+ setPropertyRegistryEntry(DynamicModelClass, prop.name, {
2227
+ through: prop.path,
2228
+ writable: prop.writable ?? true,
2229
+ ...(prop.resolveLanguage !== undefined && { resolveLanguage: prop.resolveLanguage }),
2230
+ ...(prop.local !== undefined && { local: prop.local }),
2231
+ });
2232
+ }
2233
+ }
2234
+
2235
+ const ModelDecorator = Model({ name });
2236
+ ModelDecorator(DynamicModelClass);
2237
+
2238
+ return DynamicModelClass as typeof Ad4mModel;
2239
+ }
2021
2240
  }
2022
2241