@coasys/ad4m 0.13.0-test-3 → 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 (334) hide show
  1. package/README.md +2 -25
  2. package/jest-setup.ts +1 -1
  3. package/lib/index.cjs +2406 -11070
  4. package/lib/index.js +2209 -10925
  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 -1
  150. package/lib/src/index.js +6 -1
  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 +1 -1
  155. package/lib/src/language/Language.js +10 -76
  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 +57 -38
  163. package/lib/src/model/Ad4mModel.js +594 -460
  164. package/lib/src/model/Ad4mModel.test.js +371 -815
  165. package/lib/src/model/ModelQueryBuilder.d.ts +9 -21
  166. package/lib/src/model/ModelQueryBuilder.js +138 -217
  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.d.ts +7 -60
  170. package/lib/src/model/hydration.js +7 -716
  171. package/lib/src/model/index.d.ts +0 -4
  172. package/lib/src/model/index.js +0 -4
  173. package/lib/src/model/model-manifest.d.ts +41 -0
  174. package/lib/src/model/model-manifest.js +11 -0
  175. package/lib/src/model/query-sparql.d.ts +4 -67
  176. package/lib/src/model/query-sparql.js +26 -322
  177. package/lib/src/model/query-sparql.test.js +35 -218
  178. package/lib/src/model/shacl-gen.js +4 -0
  179. package/lib/src/model/types.d.ts +47 -38
  180. package/lib/src/model/types.js +4 -1
  181. package/lib/src/neighbourhood/Neighbourhood.js +4 -32
  182. package/lib/src/neighbourhood/NeighbourhoodClient.d.ts +3 -3
  183. package/lib/src/neighbourhood/NeighbourhoodClient.js +40 -203
  184. package/lib/src/perspectives/LinkQuery.js +2 -42
  185. package/lib/src/perspectives/Perspective.d.ts +1 -1
  186. package/lib/src/perspectives/Perspective.js +10 -52
  187. package/lib/src/perspectives/PerspectiveClient.d.ts +12 -17
  188. package/lib/src/perspectives/PerspectiveClient.js +169 -429
  189. package/lib/src/perspectives/PerspectiveClient.test.js +55 -0
  190. package/lib/src/perspectives/PerspectiveDiff.js +4 -31
  191. package/lib/src/perspectives/PerspectiveHandle.js +3 -43
  192. package/lib/src/perspectives/PerspectiveProxy.d.ts +92 -71
  193. package/lib/src/perspectives/PerspectiveProxy.js +273 -310
  194. package/lib/src/runtime/RuntimeClient.d.ts +6 -6
  195. package/lib/src/runtime/RuntimeClient.js +93 -467
  196. package/lib/src/runtime/RuntimeTypes.d.ts +101 -0
  197. package/lib/src/runtime/RuntimeTypes.js +45 -0
  198. package/lib/src/shacl/SHACLShape.d.ts +7 -0
  199. package/lib/src/shacl/SHACLShape.js +19 -0
  200. package/lib/src/shacl/SHACLShape.test.js +82 -0
  201. package/lib/src/typeDefs.js +3 -628
  202. package/package.json +9 -24
  203. package/rollup.config.js +0 -7
  204. package/src/Ad4mClient.test.ts +1179 -1340
  205. package/src/Ad4mClient.ts +30 -15
  206. package/src/agent/Agent.ts +0 -99
  207. package/src/agent/AgentClient.ts +112 -526
  208. package/src/agent/AgentStatus.ts +0 -12
  209. package/src/ai/AIClient.ts +96 -296
  210. package/src/ai/AITypes.ts +66 -0
  211. package/src/ai/Tasks.ts +0 -52
  212. package/src/apiClient.ts +283 -0
  213. package/src/expression/Expression.ts +3 -43
  214. package/src/expression/ExpressionClient.ts +14 -77
  215. package/src/expression/ExpressionRef.ts +0 -6
  216. package/src/generated/api/AIModelLoadingStatus.ts +3 -0
  217. package/src/generated/api/AddLinkExpressionRequest.ts +4 -0
  218. package/src/generated/api/AddLinkRequest.ts +4 -0
  219. package/src/generated/api/AddLinksBulkRequest.ts +4 -0
  220. package/src/generated/api/AddSdnaRequest.ts +3 -0
  221. package/src/generated/api/ApplyTemplateRequest.ts +3 -0
  222. package/src/generated/api/AuthInfoInput.ts +4 -0
  223. package/src/generated/api/CapabilityInput.ts +4 -0
  224. package/src/generated/api/CommitBatchRequest.ts +3 -0
  225. package/src/generated/api/ComputeLogEntry.ts +3 -0
  226. package/src/generated/api/CreateExpressionRequest.ts +3 -0
  227. package/src/generated/api/CreatePerspectiveRequest.ts +3 -0
  228. package/src/generated/api/CreateSubjectRequest.ts +3 -0
  229. package/src/generated/api/EmbedRequest.ts +3 -0
  230. package/src/generated/api/EntanglementProofInput.ts +3 -0
  231. package/src/generated/api/ExecuteCommandsRequest.ts +3 -0
  232. package/src/generated/api/ExportRequest.ts +3 -0
  233. package/src/generated/api/ExpressionManyRequest.ts +3 -0
  234. package/src/generated/api/ExpressionProof.ts +3 -0
  235. package/src/generated/api/ExpressionProofInput.ts +3 -0
  236. package/src/generated/api/FriendSendMessageRequest.ts +3 -0
  237. package/src/generated/api/FriendsListRequest.ts +3 -0
  238. package/src/generated/api/GenerateAgentRequest.ts +3 -0
  239. package/src/generated/api/GenerateJwtRequest.ts +3 -0
  240. package/src/generated/api/GetSubjectDataRequest.ts +3 -0
  241. package/src/generated/api/ImportAgentRequest.ts +3 -0
  242. package/src/generated/api/ImportRequest.ts +3 -0
  243. package/src/generated/api/JoinNeighbourhoodRequest.ts +3 -0
  244. package/src/generated/api/LanguageMetaInput.ts +3 -0
  245. package/src/generated/api/Link.ts +3 -0
  246. package/src/generated/api/LinkExpression.ts +6 -0
  247. package/src/generated/api/LinkExpressionInput.ts +6 -0
  248. package/src/generated/api/LinkInput.ts +3 -0
  249. package/src/generated/api/LinkLanguageTemplatesRequest.ts +3 -0
  250. package/src/generated/api/LinkMutations.ts +5 -0
  251. package/src/generated/api/LinkStatus.ts +3 -0
  252. package/src/generated/api/LockAgentRequest.ts +3 -0
  253. package/src/generated/api/ModelType.ts +3 -0
  254. package/src/generated/api/NotificationInput.ts +3 -0
  255. package/src/generated/api/OpenLinkRequest.ts +3 -0
  256. package/src/generated/api/PermitCapabilityRequest.ts +3 -0
  257. package/src/generated/api/PerspectiveInput.ts +4 -0
  258. package/src/generated/api/PromptRequest.ts +3 -0
  259. package/src/generated/api/PublishLanguageRequest.ts +4 -0
  260. package/src/generated/api/PublishNeighbourhoodRequest.ts +4 -0
  261. package/src/generated/api/QueryRequest.ts +6 -0
  262. package/src/generated/api/RemoveLinkRequest.ts +4 -0
  263. package/src/generated/api/RemoveLinksBulkRequest.ts +4 -0
  264. package/src/generated/api/ResourceInput.ts +3 -0
  265. package/src/generated/api/SetDefaultModelRequest.ts +4 -0
  266. package/src/generated/api/SetFreeHostingEnabledRequest.ts +3 -0
  267. package/src/generated/api/SetMultiUserRequest.ts +3 -0
  268. package/src/generated/api/SetStatusRequest.ts +3 -0
  269. package/src/generated/api/SignMessageRequest.ts +3 -0
  270. package/src/generated/api/TrustedAgentsRequest.ts +3 -0
  271. package/src/generated/api/UnlockAgentRequest.ts +3 -0
  272. package/src/generated/api/UpdateLinkRequest.ts +5 -0
  273. package/src/generated/api/UpdatePerspectiveRequest.ts +3 -0
  274. package/src/generated/api/UserStatistics.ts +3 -0
  275. package/src/generated/api/VerificationRequestResult.ts +3 -0
  276. package/src/generated/api/VerifySignatureRequest.ts +3 -0
  277. package/src/generated/api/WriteSettingsRequest.ts +3 -0
  278. package/src/generated/api/index.ts +49 -0
  279. package/src/index.ts +6 -1
  280. package/src/jestSetup.ts +1 -1
  281. package/src/language/Icon.ts +0 -4
  282. package/src/language/Language.ts +2 -23
  283. package/src/language/LanguageClient.ts +21 -132
  284. package/src/language/LanguageHandle.ts +0 -14
  285. package/src/language/LanguageMeta.ts +0 -29
  286. package/src/language/LanguageRef.ts +0 -7
  287. package/src/links/Links.ts +0 -37
  288. package/src/model/Ad4mModel.test.ts +708 -876
  289. package/src/model/Ad4mModel.ts +613 -508
  290. package/src/model/ModelQueryBuilder.ts +178 -244
  291. package/src/model/decorators.ts +29 -0
  292. package/src/model/hydration.ts +9 -766
  293. package/src/model/index.ts +0 -4
  294. package/src/model/query-sparql.test.ts +34 -242
  295. package/src/model/query-sparql.ts +27 -337
  296. package/src/model/shacl-gen.ts +5 -0
  297. package/src/model/types.ts +51 -39
  298. package/src/neighbourhood/Neighbourhood.ts +0 -9
  299. package/src/neighbourhood/NeighbourhoodClient.ts +42 -207
  300. package/src/neighbourhood/NeighbourhoodProxy.test.ts +34 -36
  301. package/src/perspectives/LinkQuery.ts +0 -15
  302. package/src/perspectives/Perspective.ts +1 -12
  303. package/src/perspectives/PerspectiveClient.test.ts +206 -148
  304. package/src/perspectives/PerspectiveClient.ts +228 -442
  305. package/src/perspectives/PerspectiveDiff.ts +0 -8
  306. package/src/perspectives/PerspectiveHandle.ts +1 -12
  307. package/src/perspectives/PerspectiveProxy.test.ts +41 -0
  308. package/src/perspectives/PerspectiveProxy.ts +307 -348
  309. package/src/runtime/RuntimeClient.ts +112 -474
  310. package/src/runtime/RuntimeTypes.ts +144 -0
  311. package/src/shacl/SHACLShape.test.ts +94 -0
  312. package/src/shacl/SHACLShape.ts +27 -0
  313. package/src/typeDefs.ts +3 -5
  314. package/tsconfig.json +3 -7
  315. package/shims/reflect-metadata.ts +0 -0
  316. package/shims/type-graphql.ts +0 -75
  317. package/src/PubSub.ts +0 -17
  318. package/src/agent/AgentResolver.ts +0 -263
  319. package/src/ai/AIResolver.ts +0 -372
  320. package/src/buildSchema.ts +0 -43
  321. package/src/expression/ExpressionResolver.ts +0 -64
  322. package/src/language/LanguageResolver.ts +0 -98
  323. package/src/model/Subject.ts +0 -159
  324. package/src/model/hydration-batch.ts +0 -205
  325. package/src/model/hydration-batching.test.ts +0 -563
  326. package/src/model/prolog-facts.ts +0 -145
  327. package/src/model/query-prolog.ts +0 -148
  328. package/src/model/query-sparql-batch.ts +0 -301
  329. package/src/model/subscription-delta.test.ts +0 -207
  330. package/src/model/subscription-pool.ts +0 -211
  331. package/src/neighbourhood/NeighbourhoodResolver.ts +0 -100
  332. package/src/perspectives/PerspectiveResolver.ts +0 -364
  333. package/src/runtime/RuntimeResolver.ts +0 -749
  334. package/src/unwrapApolloResult.ts +0 -16
@@ -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, buildSPARQLCountQuery, hasJsOnlyWhereFilters, parseSparqlCount } 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,341 +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[],
797
- computeTotalCount: boolean = false
950
+ query: Query = {},
951
+ classNameOverride?: string | null,
798
952
  ): Promise<ResultsWithTotalCount<T>> {
799
- if (!result || result.length === 0) return { results: [], totalCount: 0 };
800
-
801
953
  const metadata = this.getModelMetadata();
802
- const requestedProperties = query?.properties || [];
803
-
804
- // The query used GROUP BY with graph traversal, so each row has:
805
- // - source: the node ID (e.g., "node:abc123")
806
- // - source_uri: the actual URI (the base expression)
807
- // - links: array of link objects with {predicate, target, author, timestamp}
808
-
809
- const instances: T[] = [];
810
- for (const row of result) {
811
- let base;
812
- try {
813
- // Use source_uri as the base (the actual URI), not the node ID
814
- base = row.source_uri;
954
+ const className = classNameOverride || metadata.className;
815
955
 
816
- // Skip rows without a source_uri field
817
- if (!base) {
818
- continue;
819
- }
820
-
821
- const links = row.links || [];
822
-
823
- const instance = new this(perspective, base) as any;
824
-
825
- // Core hydration via unified helper (pass requestedProperties for sparse fieldset).
826
- // Also hydrate any properties referenced in `where` so the JS post-filter can match them,
827
- // even if they're not in the user's `properties` projection.
828
- let hydrationProps = requestedProperties.length > 0 ? [...requestedProperties] : undefined;
829
- if (hydrationProps && query.where) {
830
- for (const key of Object.keys(query.where)) {
831
- if (!hydrationProps.includes(key)) {
832
- hydrationProps.push(key);
833
- }
834
- }
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;
835
964
  }
836
- await hydrateFromLinks(instance, links, metadata, perspective, hydrationProps);
837
-
838
- // NOTE: Property deletion for sparse fieldsets is deferred until AFTER
839
- // where-filtering so that where conditions can reference any property,
840
- // even ones not in the `properties` projection.
841
-
842
- instances.push(instance);
843
- } catch (error) {
844
- console.error(`Failed to process SPARQL instance ${base}:`, error);
845
965
  }
966
+ // Explicit include entries take precedence over the expansion
967
+ query = { ...query, include: { ...expanded, ...query.include } };
846
968
  }
847
969
 
848
- // Populate reverse relation fields (belongsToOne / belongsToMany) as string IDs.
849
- // These relations point FROM other nodes TO this instance, so they cannot be resolved
850
- // from the node's own outgoing links fetched above. We do a reverse-link lookup here
851
- // so that these fields are populated as IDs even without an explicit include.
852
- const allRelsMeta = getRelationsMetadata(this as any);
853
- const reverseRelEntries = Object.entries(allRelsMeta).filter(
854
- ([relName, meta]) =>
855
- (meta.kind === 'belongsToOne' || meta.kind === 'belongsToMany') &&
856
- (requestedProperties.length === 0 || requestedProperties.includes(relName))
857
- );
858
- if (reverseRelEntries.length > 0 && instances.length > 0) {
859
- await Promise.all(
860
- instances.map(async (inst) => {
861
- for (const [relName, relMeta] of reverseRelEntries) {
862
- const reverseLinks = await perspective.get(
863
- new LinkQuery({ predicate: relMeta.predicate, target: inst.id })
864
- );
865
- const sourceIds = reverseLinks
866
- .filter((l) => l.data.target === inst.id)
867
- .map((l) => l.data.source);
868
- if (relMeta.kind === 'belongsToOne') {
869
- (inst as any)[relName] = sourceIds.length > 0 ? sourceIds[sourceIds.length - 1] : null;
870
- } else {
871
- (inst as any)[relName] = sourceIds;
872
- }
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;
988
+ }
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 */ }
873
1004
  }
874
- })
875
- );
1005
+ }
1006
+ queryInput.projections = projections;
1007
+ }
1008
+ }
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]);
1013
+ }
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);
876
1024
  }
877
1025
 
878
- // Evaluate custom getters for all instances.
879
- // Relation getters (type-conformance filtering) always run — they ensure
880
- // correctness of @HasMany/@HasOne targets. Property getters only run when
881
- // deepQuery is true or when where conditions reference getter-backed properties.
882
- const whereGetterProperties = query.where
883
- ? Object.keys(query.where).filter((propName) => (metadata.properties[propName] as any)?.getter)
884
- : [];
885
- const shouldEvaluatePropertyGetters = query.deepQuery === true || whereGetterProperties.length > 0;
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.
886
1032
  {
887
- const skipPropertyGetters = !shouldEvaluatePropertyGetters;
888
- const getterRequestedProperties = shouldEvaluatePropertyGetters
889
- ? (requestedProperties.length > 0
890
- ? Array.from(new Set([...requestedProperties, ...whereGetterProperties]))
891
- : query.deepQuery === true
892
- ? [] // deepQuery: evaluate all getters
893
- : whereGetterProperties) // only evaluate where-referenced getters
894
- : [];
895
- const getterOpts = {
896
- ...(getterRequestedProperties.length > 0 && { requestedProperties: getterRequestedProperties }),
897
- ...(query.include && { include: query.include }),
898
- skipPropertyGetters,
899
- };
900
- for (const instance of instances) {
901
- await evaluateCustomGettersForInstance(instance, perspective, metadata, getterOpts);
902
- }
903
- }
904
-
905
- // Filter by where conditions that couldn't be filtered in SPARQL
906
- // This includes:
907
- // - author/timestamp (computed from grouped links)
908
- // - Properties with comparison operators (gt, gte, lt, lte, between, contains)
909
- // because <ad4m://fn/parse_literal>() returns strings, making numeric/date
910
- // comparisons unreliable. Equality, IN, and NOT are pushed to SPARQL.
911
- // - Relation-based where clauses (e.g., { post: postId } for @BelongsToOne)
912
- // which require reverse-link resolution before filtering
913
- let filteredInstances = instances;
914
- if (query.where) {
915
- filteredInstances = instances.filter(instance => {
916
- for (const [propertyName, condition] of Object.entries(query.where!)) {
917
- // Skip 'base'/'id' as it's filtered in SPARQL
918
- if (propertyName === 'base' || propertyName === 'id') continue;
919
-
920
- // For author and timestamp, always filter in JS
921
- if (propertyName === 'author' || propertyName === 'timestamp') {
922
- if (!matchesCondition(instance[propertyName], condition)) {
923
- return false;
924
- }
925
- continue;
926
- }
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
927
1039
 
928
- // Check if this is a relation field (not in properties metadata)
929
- const isPropField = propertyName in metadata.properties;
1040
+ const meta = allRelMeta[relName];
1041
+ if (!meta?.target) continue;
930
1042
 
931
- if (!isPropField) {
932
- // Relation-based where — filter in JS against the populated field
933
- if (!matchesCondition(instance[propertyName], condition)) {
934
- return false;
935
- }
936
- 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 */ }
937
1072
  }
938
1073
 
939
- // Filter ALL property conditions in JS (safety net).
940
- // Equality/IN/NOT are also filtered in SPARQL via <ad4m://fn/parse_literal>()
941
- // but JS re-validates after hydration resolves values.
942
- if (!matchesCondition(instance[propertyName], condition)) {
943
- 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(' ')} }`;
944
1085
  }
1086
+ } catch (e) {
1087
+ // Target class may not be available; skip silently
945
1088
  }
946
- return true;
947
- });
1089
+ }
948
1090
  }
949
1091
 
950
- // Apply ordering in JavaScript
951
- // If limit/offset is used but no explicit order, default to ordering by timestamp (ASC)
952
- // This ensures consistent pagination behavior
953
- const effectiveOrder = query.order ||
954
- (query.limit !== undefined || query.offset !== undefined ? { createdAt: 'ASC' as 'ASC' } : null);
955
-
956
- if (effectiveOrder) {
957
- const orderEntries = Object.entries(effectiveOrder);
958
-
959
- filteredInstances.sort((a: any, b: any) => {
960
- for (const [orderPropName, orderDirection] of orderEntries) {
961
- let aVal = a[orderPropName];
962
- let bVal = b[orderPropName];
963
-
964
- // Handle undefined values - push them to the end
965
- if (aVal === undefined && bVal === undefined) continue;
966
- if (aVal === undefined) return orderDirection === 'ASC' ? 1 : -1;
967
- if (bVal === undefined) return orderDirection === 'ASC' ? -1 : 1;
968
-
969
- // Compare values
970
- let comparison = 0;
971
- if (typeof aVal === 'number' && typeof bVal === 'number') {
972
- comparison = aVal - bVal;
973
- } else if (typeof aVal === 'string' && typeof bVal === 'string') {
974
- comparison = aVal.localeCompare(bVal);
975
- } else {
976
- 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 */ }
977
1130
  }
1131
+ }),
1132
+ );
1133
+ }
978
1134
 
979
- if (comparison !== 0) {
980
- return orderDirection === 'DESC' ? -comparison : comparison;
981
- }
982
- // 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];
983
1148
  }
984
- return 0;
1149
+ }
1150
+
1151
+ await evaluateCustomGettersForInstance(inst, perspective, metadata, {
1152
+ skipPropertyGetters: true,
985
1153
  });
986
- }
987
1154
 
988
- // Determine if SPARQL already applied LIMIT/OFFSET (i.e., the pagination
989
- // subquery was used). When it was, skip JS-level slicing — instances are
990
- // already the correct page.
991
- const allRelsMeta2 = getRelationsMetadata(this as any);
992
- const sparqlPaginated = !hasJsOnlyWhereFilters(metadata, allRelsMeta2, query.where)
993
- && (query.limit !== undefined || query.offset !== undefined)
994
- && query.order !== undefined && Object.keys(query.order).length > 0;
995
-
996
- // Calculate totalCount BEFORE applying limit/offset.
997
- // When SPARQL already paginated, filteredInstances.length is the page size,
998
- // not the total — use a separate COUNT query for the real total.
999
- // Only run the COUNT query when the caller actually needs it (computeTotalCount=true).
1000
- let totalCount: number;
1001
- if (sparqlPaginated && computeTotalCount) {
1002
- try {
1003
- const countSparql = buildSPARQLCountQuery(metadata, allRelsMeta2, query, this);
1004
- const countResult = await perspective.querySparql(countSparql);
1005
- totalCount = parseSparqlCount(countResult) ?? filteredInstances.length;
1006
- } catch {
1007
- // Fallback: if count query fails, use what we have
1008
- totalCount = filteredInstances.length;
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;
1009
1158
  }
1010
- } else {
1011
- totalCount = filteredInstances.length;
1012
- }
1013
-
1014
- // Apply offset and limit in JavaScript only when SPARQL didn't already paginate.
1015
- // Subscription queries use unpaginated SPARQL, so JS must apply pagination.
1016
- // Direct queries use SPARQL-level pagination, so JS slicing would double-apply.
1017
- let paginatedInstances = filteredInstances;
1018
- if (!sparqlPaginated && (query.offset !== undefined || query.limit !== undefined)) {
1019
- const start = query.offset || 0;
1020
- const end = query.limit ? start + query.limit : undefined;
1021
- paginatedInstances = filteredInstances.slice(start, end);
1022
- }
1023
1159
 
1024
- // Now that where-filtering is done, strip unrequested properties for sparse fieldsets.
1025
- // This must happen AFTER where-filtering so conditions can reference any property.
1026
- if (requestedProperties.length > 0) {
1027
- const requested = new Set(requestedProperties);
1028
- for (const inst of paginatedInstances) {
1029
- for (const propName of Object.keys(metadata.properties)) {
1030
- if (!requested.has(propName)) {
1031
- delete (inst as any)[propName];
1032
- }
1033
- }
1034
- for (const relName of Object.keys(metadata.relations)) {
1035
- if (!requested.has(relName) && !(query.include && relName in query.include)) {
1036
- delete (inst as any)[relName];
1037
- }
1038
- }
1039
- for (const metaField of ['author', 'createdAt', 'updatedAt'] as const) {
1040
- if (!requested.has(metaField)) {
1041
- delete (inst as any)[metaField];
1042
- }
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;
1043
1168
  }
1044
1169
  }
1045
1170
  }
1046
1171
 
1047
- // Eager-load relations if requested (BEFORE snapshot so dirty tracking is accurate)
1048
- if (query.include && paginatedInstances.length > 0) {
1049
- await hydrateRelations(this, paginatedInstances, perspective, query.include);
1050
- }
1051
-
1052
- // Take snapshots for dirty tracking after ALL hydration is complete
1053
- // (including eager-loaded relations).
1054
- // When `include` is specified, only snapshot those relations.
1055
- // Otherwise snapshot ALL fields (properties + relations) since
1056
- // hydrateFromLinks populates relations with stable raw IDs —
1057
- // this ensures push-to-array + save() correctly detects dirty relations.
1058
- const snapshotRelations = query.include;
1059
- for (const inst of paginatedInstances) {
1172
+ // Take snapshots for dirty tracking
1173
+ const snapshotRelations = queryInput.include;
1174
+ for (const inst of instances) {
1060
1175
  (inst as Ad4mModel).takeSnapshot(snapshotRelations);
1061
1176
  }
1062
1177
 
1063
1178
  return {
1064
- results: paginatedInstances,
1065
- totalCount
1179
+ results: instances,
1180
+ totalCount: result.totalCount,
1066
1181
  };
1067
1182
  }
1068
1183
 
@@ -1097,33 +1212,14 @@ export class Ad4mModel {
1097
1212
  this: typeof Ad4mModel & (new (...args: any[]) => T),
1098
1213
  perspective: PerspectiveProxy,
1099
1214
  query: Query = {},
1100
- engine: 'sparql' | 'prolog' | boolean = 'sparql'
1215
+ _engine?: 'sparql' | 'prolog' | boolean
1101
1216
  ): Promise<T[]> {
1102
1217
  if (query.properties && query.properties.length === 0) {
1103
1218
  throw new Error("properties[] must not be empty — omit the field to return all properties, or specify at least one field name");
1104
1219
  }
1105
1220
 
1106
- // Backward compatibility: boolean maps to sparql (true) or prolog (false)
1107
- const resolvedEngine = typeof engine === 'boolean'
1108
- ? (engine ? 'sparql' : 'prolog')
1109
- : engine;
1110
-
1111
- if (resolvedEngine === 'sparql') {
1112
- // Always use the regular SPARQL path + JS-level hydrateRelations for includes.
1113
- // The batch SPARQL approach had issues with sub-queries (where/order/limit on includes),
1114
- // non-conforming node filtering, and parse_literal compatibility.
1115
- // hydrateRelations handles all of these correctly via per-relation findAll calls.
1116
- const sparqlQuery = await this.queryToSPARQL(perspective, query);
1117
- const rawResult = await perspective.querySparql(sparqlQuery);
1118
- const grouped = groupSPARQLResults(rawResult);
1119
- const { results } = await this.instancesFromQueryResult(perspective, query, grouped);
1120
- return results;
1121
- } else {
1122
- const prologQuery = await this.queryToProlog(perspective, query);
1123
- const result = await perspective.infer(prologQuery);
1124
- const { results } = await this.instancesFromPrologResult(perspective, query, result);
1125
- return results;
1126
- }
1221
+ const { results } = await this.executeModelQuery(perspective, query);
1222
+ return results;
1127
1223
  }
1128
1224
 
1129
1225
  /**
@@ -1150,10 +1246,10 @@ export class Ad4mModel {
1150
1246
  this: typeof Ad4mModel & (new (...args: any[]) => T),
1151
1247
  perspective: PerspectiveProxy,
1152
1248
  query: Query = {},
1153
- engine: 'sparql' | 'prolog' | boolean = 'sparql',
1249
+ _engine?: 'sparql' | 'prolog' | boolean,
1154
1250
  ): Promise<T | null> {
1155
1251
  const limitedQuery = { ...query, limit: 1 };
1156
- const results = await this.findAll(perspective, limitedQuery, engine);
1252
+ const results = await this.findAll(perspective, limitedQuery);
1157
1253
  return results[0] ?? null;
1158
1254
  }
1159
1255
 
@@ -1181,22 +1277,9 @@ export class Ad4mModel {
1181
1277
  this: typeof Ad4mModel & (new (...args: any[]) => T),
1182
1278
  perspective: PerspectiveProxy,
1183
1279
  query: Query = {},
1184
- engine: 'sparql' | 'prolog' | boolean = 'sparql'
1280
+ _engine?: 'sparql' | 'prolog' | boolean
1185
1281
  ): Promise<ResultsWithTotalCount<T>> {
1186
- const resolvedEngine = typeof engine === 'boolean'
1187
- ? (engine ? 'sparql' : 'prolog')
1188
- : engine;
1189
-
1190
- if (resolvedEngine === 'sparql') {
1191
- const sparqlQuery = await this.queryToSPARQL(perspective, query);
1192
- const rawResult = await perspective.querySparql(sparqlQuery);
1193
- const grouped = groupSPARQLResults(rawResult);
1194
- return await this.instancesFromQueryResult(perspective, query, grouped, true);
1195
- } else {
1196
- const prologQuery = await this.queryToProlog(perspective, query);
1197
- const result = await perspective.infer(prologQuery);
1198
- return await this.instancesFromPrologResult(perspective, query, result);
1199
- }
1282
+ return await this.executeModelQuery(perspective, query);
1200
1283
  }
1201
1284
 
1202
1285
  /**
@@ -1206,7 +1289,6 @@ export class Ad4mModel {
1206
1289
  * @param pageSize - Number of items per page
1207
1290
  * @param pageNumber - Which page to retrieve (1-based)
1208
1291
  * @param query - Optional additional query parameters
1209
- * @param useSPARQL - Whether to use SPARQL (default: true, 10-100x faster) or Prolog (legacy)
1210
1292
  * @returns Paginated results with metadata
1211
1293
  *
1212
1294
  * @example
@@ -1215,9 +1297,6 @@ export class Ad4mModel {
1215
1297
  * where: { category: "Main Course" }
1216
1298
  * });
1217
1299
  * console.log(`Page ${page.pageNumber} of recipes, ${page.results.length} items`);
1218
- *
1219
- * // Use Prolog explicitly (legacy)
1220
- * const pageProlog = await Recipe.paginate(perspective, 10, 1, {}, false);
1221
1300
  * ```
1222
1301
  */
1223
1302
  static async paginate<T extends Ad4mModel>(
@@ -1226,46 +1305,11 @@ export class Ad4mModel {
1226
1305
  pageSize: number,
1227
1306
  pageNumber: number,
1228
1307
  query?: Query,
1229
- engine: 'sparql' | 'prolog' | boolean = 'sparql'
1308
+ _engine?: 'sparql' | 'prolog' | boolean
1230
1309
  ): Promise<PaginationResult<T>> {
1231
1310
  const paginationQuery = { ...(query || {}), limit: pageSize, offset: pageSize * (pageNumber - 1), count: true };
1232
- const resolvedEngine = typeof engine === 'boolean'
1233
- ? (engine ? 'sparql' : 'prolog')
1234
- : engine;
1235
-
1236
- if (resolvedEngine === 'sparql') {
1237
- const sparqlQuery = await this.queryToSPARQL(perspective, paginationQuery);
1238
- const rawResult = await perspective.querySparql(sparqlQuery);
1239
- const grouped = groupSPARQLResults(rawResult);
1240
- const { results, totalCount } = await this.instancesFromQueryResult(perspective, paginationQuery, grouped, true);
1241
- return { results, totalCount, pageSize, pageNumber };
1242
- } else {
1243
- const prologQuery = await this.queryToProlog(perspective, paginationQuery);
1244
- const result = await perspective.infer(prologQuery);
1245
- const { results, totalCount } = await this.instancesFromPrologResult(perspective, paginationQuery, result);
1246
- return { results, totalCount, pageSize, pageNumber };
1247
- }
1248
- }
1249
-
1250
- static async countQueryToProlog(perspective: PerspectiveProxy, query: Query = {}, modelClassName?: string | null) {
1251
- const { where } = query;
1252
- const className = modelClassName || (await this.getClassName(perspective));
1253
- const resolvedParentPredicate = query.parent
1254
- ? resolveParentPredicate(query.parent, this)
1255
- : undefined;
1256
- const instanceQueries = [buildAuthorAndTimestampQuery(), buildParentQuery(query.parent, resolvedParentPredicate), buildWhereQuery(where)];
1257
- const resultSetQueries = [buildCountQuery(true), buildOrderQuery(), buildOffsetQuery(), buildLimitQuery()];
1258
-
1259
- const fullQuery = `
1260
- findall([Base, Properties, Collections, Timestamp, Author], (
1261
- subject_class("${className}", SubjectClass),
1262
- instance(SubjectClass, Base),
1263
- ${instanceQueries.filter((q) => q).join(", ")}
1264
- ), UnsortedInstances),
1265
- ${resultSetQueries.filter((q) => q).join(", ")}
1266
- `;
1267
-
1268
- return fullQuery;
1311
+ const { results, totalCount } = await this.executeModelQuery(perspective, paginationQuery);
1312
+ return { results, totalCount, pageSize, pageNumber };
1269
1313
  }
1270
1314
 
1271
1315
  /**
@@ -1277,18 +1321,13 @@ export class Ad4mModel {
1277
1321
  *
1278
1322
  * @private
1279
1323
  */
1280
- public static async countQueryToSPARQL(perspective: PerspectiveProxy, query: Query): Promise<string> {
1281
- const metadata = this.getModelMetadata();
1282
- const allRelMeta = getRelationsMetadata(this as any);
1283
- return buildSPARQLCountQuery(metadata, allRelMeta, query, this);
1284
- }
1324
+ // countQueryToSPARQL — removed (zero callers; Rust COUNT fast-path supersedes)
1285
1325
 
1286
1326
  /**
1287
1327
  * Gets a count of all matching instances.
1288
1328
  *
1289
1329
  * @param perspective - The perspective to search in
1290
1330
  * @param query - Optional query parameters to filter results
1291
- * @param useSPARQL - Whether to use SPARQL (default: true, 10-100x faster) or Prolog (legacy)
1292
1331
  * @returns Total count of matching entities
1293
1332
  *
1294
1333
  * @example
@@ -1297,36 +1336,11 @@ export class Ad4mModel {
1297
1336
  * const activeRecipes = await Recipe.count(perspective, {
1298
1337
  * where: { status: "active" }
1299
1338
  * });
1300
- *
1301
- * // Use Prolog explicitly (legacy)
1302
- * const countProlog = await Recipe.count(perspective, {}, false);
1303
1339
  * ```
1304
1340
  */
1305
- static async count(perspective: PerspectiveProxy, query: Query = {}, engine: 'sparql' | 'prolog' | boolean = 'sparql') {
1306
- const resolvedEngine = typeof engine === 'boolean'
1307
- ? (engine ? 'sparql' : 'prolog')
1308
- : engine;
1309
-
1310
- if (resolvedEngine === 'sparql') {
1311
- // When query has JS-only where filters (gt, between, author, timestamp, etc.),
1312
- // we must fall back to full hydration + JS filtering to get accurate count.
1313
- const metadata = this.getModelMetadata();
1314
- const allRelMeta = getRelationsMetadata(this as any);
1315
- if (hasJsOnlyWhereFilters(metadata, allRelMeta, query.where)) {
1316
- // Fall back to full query + JS filter path for accurate count
1317
- const sparqlQuery = await this.queryToSPARQL(perspective, query);
1318
- const rawResult = await perspective.querySparql(sparqlQuery);
1319
- const grouped = groupSPARQLResults(rawResult);
1320
- const { totalCount } = await this.instancesFromQueryResult(perspective, query, grouped, true); return totalCount;
1321
- }
1322
- // No JS-only filters — use efficient COUNT query
1323
- const countSparql = await this.countQueryToSPARQL(perspective, query);
1324
- const countResult = await perspective.querySparql(countSparql);
1325
- return parseSparqlCount(countResult) ?? 0;
1326
- } else {
1327
- const result = await perspective.infer(await this.countQueryToProlog(perspective, query));
1328
- return result?.[0]?.TotalCount || 0;
1329
- }
1341
+ static async count(perspective: PerspectiveProxy, query: Query = {}): Promise<number> {
1342
+ const { totalCount } = await this.executeModelQuery(perspective, { ...query, limit: 0 });
1343
+ return totalCount;
1330
1344
  }
1331
1345
 
1332
1346
  private async setProperty(key: string, value: any, batchId?: string) {
@@ -2132,5 +2146,96 @@ export class Ad4mModel {
2132
2146
  ): typeof Ad4mModel {
2133
2147
  return buildModelFromJSONSchema(this, schema, options);
2134
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
+ }
2135
2240
  }
2136
2241