@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
@@ -1,5 +1,6 @@
1
1
  import { Ad4mModel } from "./Ad4mModel";
2
- import { Model, Property, Optional, ReadOnly, HasMany, Flag } from "./decorators";
2
+ import { isIncludeProjection } from "./types";
3
+ import { Model, Property, Optional, ReadOnly, HasMany, HasOne, Flag } from "./decorators";
3
4
 
4
5
  describe("Ad4mModel.getModelMetadata()", () => {
5
6
  it("should extract basic model metadata with className", () => {
@@ -606,28 +607,18 @@ describe("Ad4mModel.queryToSPARQL()", () => {
606
607
 
607
608
  // ---- ORDER BY, LIMIT, OFFSET are JS post-processed ----
608
609
 
609
- it("should not include ORDER BY in SPARQL (JS post-processed)", async () => {
610
- const query = await (Recipe as any).queryToSPARQL(mockPerspective, { order: { name: "ASC" } });
610
+ it("should include ORDER BY/LIMIT/OFFSET in SPARQL pagination subquery", async () => {
611
+ const query = await (Recipe as any).queryToSPARQL(mockPerspective, { order: { name: "ASC" }, limit: 10, offset: 5 });
611
612
  const norm = normalizeQuery(query);
612
613
  expect(norm).toContain("SELECT ?source");
613
- expect(norm).not.toContain("ORDER BY");
614
- });
615
-
616
- it("should not include LIMIT in SPARQL (JS post-processed)", async () => {
617
- const query = await (Recipe as any).queryToSPARQL(mockPerspective, { limit: 10 });
618
- const norm = normalizeQuery(query);
619
- expect(norm).toContain("SELECT ?source");
620
- expect(norm).not.toContain("LIMIT");
621
- });
622
-
623
- it("should not include OFFSET in SPARQL (JS post-processed)", async () => {
624
- const query = await (Recipe as any).queryToSPARQL(mockPerspective, { offset: 5 });
625
- const norm = normalizeQuery(query);
626
- expect(norm).toContain("SELECT ?source");
627
- expect(norm).not.toContain("OFFSET");
614
+ // SPARQL-level pagination via subquery
615
+ expect(norm).toContain("ORDER BY");
616
+ expect(norm).toContain("LIMIT 10");
617
+ expect(norm).toContain("OFFSET 5");
618
+ expect(norm).toContain("SELECT DISTINCT ?source");
628
619
  });
629
620
  });
630
- describe("Ad4mModel.instancesFromQueryResult() and SPARQL integration", () => {
621
+ describe("Ad4mModel query methods (modelQuery integration)", () => {
631
622
  // Test Recipe model
632
623
  @Model({ name: "Recipe" })
633
624
  class Recipe extends Ad4mModel {
@@ -641,9 +632,10 @@ describe("Ad4mModel.instancesFromQueryResult() and SPARQL integration", () => {
641
632
  ingredients: string[] = [];
642
633
  }
643
634
 
644
- // Mock perspective with both querySparql and infer methods
635
+ // Mock perspective with querySparql, modelQuery, and infer methods
645
636
  const mockPerspective = {
646
637
  querySparql: jest.fn(),
638
+ modelQuery: jest.fn(),
647
639
  infer: jest.fn(),
648
640
  uuid: 'test-perspective-uuid',
649
641
  stringOrTemplateObjectToSubjectClassName: jest.fn().mockResolvedValue('Recipe')
@@ -653,307 +645,166 @@ describe("Ad4mModel.instancesFromQueryResult() and SPARQL integration", () => {
653
645
  jest.clearAllMocks();
654
646
  });
655
647
 
656
- it("should convert empty query results correctly", async () => {
657
- const result = await Recipe.instancesFromQueryResult(mockPerspective, {}, []);
658
-
659
- expect(result.results).toEqual([]);
660
- expect(result.totalCount).toBe(0);
661
- });
662
-
663
- it("should convert query results to model instances", async () => {
664
- const queryResults = [
665
- {
666
- source: "node:abc123",
667
- source_uri: "literal:recipe1",
668
- links: [
669
- { predicate: "recipe://name", target: "Pasta", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" },
670
- { predicate: "recipe://rating", target: "5", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" },
671
- { predicate: "recipe://ingredient", target: "pasta", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" },
672
- { predicate: "recipe://ingredient", target: "tomato", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" },
673
- { predicate: "recipe://ingredient", target: "cheese", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" }
674
- ]
675
- },
676
- {
677
- source: "node:def456",
678
- source_uri: "literal:recipe2",
679
- links: [
680
- { predicate: "recipe://name", target: "Pizza", author: "did:key:bob", timestamp: "2023-01-02T00:00:00Z" },
681
- { predicate: "recipe://rating", target: "4", author: "did:key:bob", timestamp: "2023-01-02T00:00:00Z" },
682
- { predicate: "recipe://ingredient", target: "dough", author: "did:key:bob", timestamp: "2023-01-02T00:00:00Z" },
683
- { predicate: "recipe://ingredient", target: "cheese", author: "did:key:bob", timestamp: "2023-01-02T00:00:00Z" },
684
- { predicate: "recipe://ingredient", target: "tomato", author: "did:key:bob", timestamp: "2023-01-02T00:00:00Z" }
685
- ]
686
- }
687
- ];
688
-
689
- const result = await Recipe.instancesFromQueryResult(mockPerspective, {}, queryResults);
690
-
691
- expect(result.results).toHaveLength(2);
692
- expect(result.totalCount).toBe(2);
693
-
694
- const recipe1 = result.results[0];
695
- expect(recipe1).toBeInstanceOf(Recipe);
696
- expect(recipe1.name).toBe("Pasta");
697
- expect(recipe1.rating).toBe(5);
698
- expect(recipe1.ingredients).toEqual(["pasta", "tomato", "cheese"]);
699
-
700
- const recipe2 = result.results[1];
701
- expect(recipe2).toBeInstanceOf(Recipe);
702
- expect(recipe2.name).toBe("Pizza");
703
- expect(recipe2.rating).toBe(4);
704
- });
705
-
706
- it("should filter properties when query specifies properties", async () => {
707
- const queryResults = [
708
- {
709
- source: "node:abc123",
710
- source_uri: "literal:recipe1",
711
- links: [
712
- { predicate: "recipe://name", target: "Pasta", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" },
713
- { predicate: "recipe://rating", target: "5", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" },
714
- { predicate: "recipe://ingredient", target: "pasta", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" },
715
- { predicate: "recipe://ingredient", target: "tomato", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" }
716
- ]
717
- }
718
- ];
719
-
720
- const result = await Recipe.instancesFromQueryResult(
721
- mockPerspective,
722
- { properties: ["name"] },
723
- queryResults
724
- );
725
-
726
- expect(result.results).toHaveLength(1);
727
- const recipe = result.results[0];
728
- expect(recipe.name).toBe("Pasta");
729
- // rating and ingredients should be removed since only "name" was requested
730
- expect(recipe.rating).toBeUndefined();
731
- expect(recipe.ingredients).toBeUndefined();
732
- // author, createdAt, updatedAt are also stripped unless explicitly requested
733
- expect(recipe.author).toBeUndefined();
734
- expect(recipe.timestamp).toBeUndefined();
735
- });
736
-
737
- it("should filter properties when query specifies properties", async () => {
738
- const queryResults = [
739
- {
740
- source: "node:abc123",
741
- source_uri: "literal:recipe1",
742
- links: [
743
- { predicate: "recipe://name", target: "Pasta", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" },
744
- { predicate: "recipe://rating", target: "5", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" },
745
- { predicate: "recipe://ingredient", target: "pasta", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" },
746
- { predicate: "recipe://ingredient", target: "tomato", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" }
747
- ]
748
- }
749
- ];
750
-
751
- const result = await Recipe.instancesFromQueryResult(
752
- mockPerspective,
753
- { properties: ["name"] },
754
- queryResults
755
- );
756
-
757
- expect(result.results).toHaveLength(1);
758
- const recipe = result.results[0];
759
- expect(recipe.name).toBe("Pasta");
760
- // rating and ingredients should be removed since only "name" was requested
761
- expect(recipe.rating).toBeUndefined();
762
- });
763
-
764
- it("should handle results missing base field", async () => {
765
- const queryResults = [
766
- {
767
- links: [
768
- { predicate: "recipe://name", target: "Pasta", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" },
769
- { predicate: "recipe://rating", target: "5", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" }
770
- ]
771
- // Missing source field
772
- } as any
773
- ];
774
-
775
- const result = await Recipe.instancesFromQueryResult(mockPerspective, {}, queryResults);
776
-
777
- // Should filter out the invalid result (or handle gracefully)
778
- expect(result.results).toHaveLength(0);
779
- expect(result.totalCount).toBe(0);
780
- });
781
-
782
648
  it("should use SPARQL when engine is 'sparql' in findAll()", async () => {
783
- // Raw SPARQL rows (flat) — groupSPARQLResults will group them
784
- const queryResults = [
785
- { source: "literal:recipe1", predicate: "recipe://name", target: "Pasta", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" },
786
- { source: "literal:recipe1", predicate: "recipe://rating", target: "5", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" },
787
- { source: "literal:recipe1", predicate: "recipe://ingredient", target: "pasta", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" }
788
- ];
789
-
790
- mockPerspective.querySparql.mockResolvedValue(queryResults);
649
+ // modelQuery returns already-hydrated instances from the Rust executor
650
+ mockPerspective.modelQuery.mockResolvedValue({
651
+ instances: [
652
+ { id: "literal:recipe1", name: "Pasta", rating: 5, ingredients: ["pasta"] }
653
+ ],
654
+ totalCount: 1
655
+ });
791
656
 
792
657
  const results = await Recipe.findAll(mockPerspective, {}, 'sparql');
793
658
 
794
- expect(mockPerspective.querySparql).toHaveBeenCalledTimes(1);
659
+ expect(mockPerspective.modelQuery).toHaveBeenCalledTimes(1);
795
660
  expect(mockPerspective.infer).not.toHaveBeenCalled();
796
661
  expect(results).toHaveLength(1);
797
662
  expect(results[0].name).toBe("Pasta");
798
663
  });
799
664
 
800
- it("should use Prolog when engine is prolog in findAll()", async () => {
801
- const prologResults = [{
802
- AllInstances: [
803
- ["literal:recipe1", [["name", "Pasta"]], [["ingredients", ["pasta"]]], "2023-01-01T00:00:00Z", "did:key:alice"]
665
+ it("should route through modelQuery when engine is 'prolog' in findAll() (prolog is now no-op)", async () => {
666
+ mockPerspective.modelQuery.mockResolvedValue({
667
+ instances: [
668
+ { id: "literal:recipe1", name: "Pasta", rating: 5, ingredients: ["pasta"] }
804
669
  ],
805
- TotalCount: 1
806
- }];
807
-
808
- mockPerspective.infer.mockResolvedValue(prologResults);
670
+ totalCount: 1
671
+ });
809
672
 
810
673
  const results = await Recipe.findAll(mockPerspective, {}, false);
811
674
 
812
- expect(mockPerspective.infer).toHaveBeenCalledTimes(1);
813
- expect(mockPerspective.querySparql).not.toHaveBeenCalled();
675
+ expect(mockPerspective.modelQuery).toHaveBeenCalledTimes(1);
676
+ expect(mockPerspective.infer).not.toHaveBeenCalled();
814
677
  expect(results).toHaveLength(1);
815
678
  });
816
679
 
817
680
  it("should use SPARQL when engine is 'sparql' in findAllAndCount()", async () => {
818
- const queryResults = [
819
- { source: "literal:recipe1", predicate: "recipe://name", target: "Pasta", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" },
820
- { source: "literal:recipe1", predicate: "recipe://rating", target: "5", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" },
821
- { source: "literal:recipe1", predicate: "recipe://ingredient", target: "pasta", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" }
822
- ];
823
-
824
- mockPerspective.querySparql.mockResolvedValue(queryResults);
681
+ mockPerspective.modelQuery.mockResolvedValue({
682
+ instances: [
683
+ { id: "literal:recipe1", name: "Pasta", rating: 5, ingredients: ["pasta"] }
684
+ ],
685
+ totalCount: 1
686
+ });
825
687
 
826
- const { results, totalCount } = await Recipe.findAllAndCount(mockPerspective, {}, 'sparql');
688
+ const { results, totalCount } = await Recipe.findAllAndCount(mockPerspective, {});
827
689
 
828
- expect(mockPerspective.querySparql).toHaveBeenCalledTimes(1);
690
+ expect(mockPerspective.modelQuery).toHaveBeenCalledTimes(1);
829
691
  expect(mockPerspective.infer).not.toHaveBeenCalled();
830
692
  expect(results).toHaveLength(1);
831
693
  expect(totalCount).toBe(1);
832
694
  });
833
695
 
834
696
  it("should use SPARQL when engine is 'sparql' in paginate()", async () => {
835
- const queryResults = [
836
- { source: "literal:recipe1", predicate: "recipe://name", target: "Pasta", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" },
837
- { source: "literal:recipe1", predicate: "recipe://rating", target: "5", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" },
838
- { source: "literal:recipe1", predicate: "recipe://ingredient", target: "pasta", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" }
839
- ];
840
-
841
- mockPerspective.querySparql.mockResolvedValue(queryResults);
697
+ mockPerspective.modelQuery.mockResolvedValue({
698
+ instances: [
699
+ { id: "literal:recipe1", name: "Pasta", rating: 5, ingredients: ["pasta"] }
700
+ ],
701
+ totalCount: 1
702
+ });
842
703
 
843
- const page = await Recipe.paginate(mockPerspective, 10, 1, {}, 'sparql');
704
+ const page = await Recipe.paginate(mockPerspective, 10, 1, {});
844
705
 
845
- expect(mockPerspective.querySparql).toHaveBeenCalledTimes(1);
706
+ expect(mockPerspective.modelQuery).toHaveBeenCalledTimes(1);
846
707
  expect(mockPerspective.infer).not.toHaveBeenCalled();
847
708
  expect(page.results).toHaveLength(1);
848
709
  expect(page.pageSize).toBe(10);
849
710
  expect(page.pageNumber).toBe(1);
711
+ expect(page.totalCount).toBe(1);
850
712
  });
851
713
 
852
- it("should use SPARQL when engine is 'sparql' in count()", async () => {
853
- // Since count() uses result.length and GROUP BY returns one row per source,
854
- // mock 5 recipe sources
855
- const queryResults = [
856
- ...Array.from({ length: 5 }, (_, i) => [
857
- { source: `literal:recipe${i+1}`, predicate: "recipe://name", target: `Recipe ${i+1}`, author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" },
858
- { source: `literal:recipe${i+1}`, predicate: "recipe://rating", target: "5", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" }
859
- ]).flat()
860
- ];
861
-
862
- mockPerspective.querySparql.mockResolvedValue(queryResults);
714
+ it("should use SPARQL in count()", async () => {
715
+ mockPerspective.modelQuery.mockResolvedValue({
716
+ instances: [],
717
+ totalCount: 5
718
+ });
863
719
 
864
- const count = await Recipe.count(mockPerspective, {}, 'sparql');
720
+ const count = await Recipe.count(mockPerspective, {});
865
721
 
866
- expect(mockPerspective.querySparql).toHaveBeenCalledTimes(1);
722
+ expect(mockPerspective.modelQuery).toHaveBeenCalledTimes(1);
867
723
  expect(mockPerspective.infer).not.toHaveBeenCalled();
868
724
  expect(count).toBe(5);
869
725
  });
870
726
 
871
- it("should use Prolog when engine is prolog in count()", async () => {
872
- const prologResults = [{ TotalCount: 10 }];
873
- mockPerspective.infer.mockResolvedValue(prologResults);
727
+ it("should return count from modelQuery", async () => {
728
+ mockPerspective.modelQuery.mockResolvedValue({
729
+ instances: [],
730
+ totalCount: 10
731
+ });
874
732
 
875
- const count = await Recipe.count(mockPerspective, {}, false);
733
+ const count = await Recipe.count(mockPerspective, {});
876
734
 
877
- expect(mockPerspective.infer).toHaveBeenCalledTimes(1);
735
+ expect(mockPerspective.modelQuery).toHaveBeenCalledTimes(1);
878
736
  expect(mockPerspective.querySparql).not.toHaveBeenCalled();
879
737
  expect(count).toBe(10);
880
738
  });
881
739
 
882
740
  it("should use SPARQL when engine is 'sparql' in ModelQueryBuilder.get()", async () => {
883
- const queryResults = [
884
- { source: "literal:recipe1", predicate: "recipe://name", target: "Pasta", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" },
885
- { source: "literal:recipe1", predicate: "recipe://rating", target: "5", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" },
886
- { source: "literal:recipe1", predicate: "recipe://ingredient", target: "pasta", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" }
887
- ];
888
-
889
- mockPerspective.querySparql.mockResolvedValue(queryResults);
741
+ mockPerspective.modelQuery.mockResolvedValue({
742
+ instances: [
743
+ { id: "literal:recipe1", name: "Pasta", rating: 5, ingredients: ["pasta"] }
744
+ ],
745
+ totalCount: 1
746
+ });
890
747
 
891
748
  const results = await Recipe.query(mockPerspective)
892
749
  .where({ name: "Pasta" })
893
750
  .engine('sparql')
894
751
  .get();
895
752
 
896
- expect(mockPerspective.querySparql).toHaveBeenCalledTimes(1);
753
+ expect(mockPerspective.modelQuery).toHaveBeenCalledTimes(1);
897
754
  expect(mockPerspective.infer).not.toHaveBeenCalled();
898
755
  expect(results).toHaveLength(1);
899
756
  expect(results[0].name).toBe("Pasta");
900
757
  });
901
758
 
902
- it("should use Prolog when.engine('prolog') in ModelQueryBuilder.get()", async () => {
903
- const prologResults = [{
904
- AllInstances: [
905
- ["literal:recipe1", [["name", "Pasta"]], [["ingredients", ["pasta"]]], "2023-01-01T00:00:00Z", "did:key:alice"]
759
+ it("should use modelQuery when .engine('prolog') is called (engine is now a no-op)", async () => {
760
+ mockPerspective.modelQuery.mockResolvedValue({
761
+ instances: [
762
+ { id: "literal:recipe1", name: "Pasta", rating: 5, ingredients: ["pasta"] }
906
763
  ],
907
- TotalCount: 1
908
- }];
909
-
910
- mockPerspective.infer.mockResolvedValue(prologResults);
764
+ totalCount: 1
765
+ });
911
766
 
912
767
  const results = await Recipe.query(mockPerspective)
913
768
  .where({ name: "Pasta" })
914
769
  .engine('prolog')
915
770
  .get();
916
771
 
917
- expect(mockPerspective.infer).toHaveBeenCalledTimes(1);
918
- expect(mockPerspective.querySparql).not.toHaveBeenCalled();
772
+ // engine('prolog') is now a no-op — everything goes through modelQuery
773
+ expect(mockPerspective.modelQuery).toHaveBeenCalledTimes(1);
774
+ expect(mockPerspective.infer).not.toHaveBeenCalled();
919
775
  expect(results).toHaveLength(1);
920
776
  });
921
777
 
922
778
  it("should use SPARQL when engine is 'sparql' in ModelQueryBuilder.count()", async () => {
923
- // count() counts the number of rows returned by the query (one row per source)
924
- const queryResults = [
925
- ...Array.from({ length: 3 }, (_, i) => [
926
- { source: `literal:recipe${i+1}`, predicate: "recipe://name", target: `Recipe ${i+1}`, author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" },
927
- { source: `literal:recipe${i+1}`, predicate: "recipe://rating", target: "5", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" }
928
- ]).flat()
929
- ];
930
- mockPerspective.querySparql.mockResolvedValue(queryResults);
779
+ mockPerspective.modelQuery.mockResolvedValue({
780
+ instances: [],
781
+ totalCount: 3
782
+ });
931
783
 
932
784
  const count = await Recipe.query(mockPerspective)
933
785
  .where({ rating: { gt: 4 } })
934
786
  .engine('sparql')
935
787
  .count();
936
788
 
937
- expect(mockPerspective.querySparql).toHaveBeenCalledTimes(1);
789
+ expect(mockPerspective.modelQuery).toHaveBeenCalledTimes(1);
938
790
  expect(mockPerspective.infer).not.toHaveBeenCalled();
939
791
  expect(count).toBe(3);
940
792
  });
941
793
 
942
794
  it("should use SPARQL when engine is 'sparql' in ModelQueryBuilder.paginate()", async () => {
943
- const queryResults = [
944
- { source: "literal:recipe1", predicate: "recipe://name", target: "Pasta", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" },
945
- { source: "literal:recipe1", predicate: "recipe://rating", target: "5", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" },
946
- { source: "literal:recipe1", predicate: "recipe://ingredient", target: "pasta", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" }
947
- ];
948
-
949
- mockPerspective.querySparql.mockResolvedValue(queryResults);
795
+ mockPerspective.modelQuery.mockResolvedValue({
796
+ instances: [
797
+ { id: "literal:recipe1", name: "Pasta", rating: 5, ingredients: ["pasta"] }
798
+ ],
799
+ totalCount: 1
800
+ });
950
801
 
951
802
  const page = await Recipe.query(mockPerspective)
952
803
  .where({ rating: { gt: 3 } })
953
804
  .engine('sparql')
954
805
  .paginate(10, 1);
955
806
 
956
- expect(mockPerspective.querySparql).toHaveBeenCalledTimes(1);
807
+ expect(mockPerspective.modelQuery).toHaveBeenCalledTimes(1);
957
808
  expect(mockPerspective.infer).not.toHaveBeenCalled();
958
809
  expect(page.results).toHaveLength(1);
959
810
  expect(page.pageSize).toBe(10);
@@ -978,6 +829,7 @@ describe("Ad4mModel.count() with advanced where conditions", () => {
978
829
  // Mock perspective
979
830
  const mockPerspective = {
980
831
  querySparql: jest.fn(),
832
+ modelQuery: jest.fn(),
981
833
  infer: jest.fn(),
982
834
  uuid: 'test-perspective-uuid',
983
835
  stringOrTemplateObjectToSubjectClassName: jest.fn().mockResolvedValue('Recipe')
@@ -987,132 +839,80 @@ describe("Ad4mModel.count() with advanced where conditions", () => {
987
839
  jest.clearAllMocks();
988
840
  });
989
841
 
990
- it("should apply JS-level filtering for gt operator on properties in SPARQL count()", async () => {
991
- // Mock query results: 5 recipes with ratings 1, 2, 3, 4, 5
992
- const queryResults = [
993
- ...Array.from({ length: 5 }, (_, i) => [
994
- { source: `literal:recipe${i+1}`, predicate: "recipe://name", target: `Recipe ${i+1}`, author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" },
995
- { source: `literal:recipe${i+1}`, predicate: "recipe://rating", target: `${i+1}`, author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" }
996
- ]).flat()
997
- ];
998
-
999
- mockPerspective.querySparql.mockResolvedValue(queryResults);
842
+ it("should apply filtering for gt operator on properties in SPARQL count()", async () => {
843
+ // With the new modelQuery endpoint, filtering happens server-side in Rust
844
+ mockPerspective.modelQuery.mockResolvedValue({
845
+ instances: [],
846
+ totalCount: 2
847
+ });
1000
848
 
1001
849
  // Count recipes with rating > 3 (should match 2 recipes: rating 4 and 5)
1002
- const count = await Recipe.count(mockPerspective, { where: { rating: { gt: 3 } } }, 'sparql');
1003
-
1004
- // Verify count matches the number of instances that would be returned by findAll
1005
- const findAllResults = await Recipe.findAll(mockPerspective, { where: { rating: { gt: 3 } } }, 'sparql');
850
+ const count = await Recipe.count(mockPerspective, { where: { rating: { gt: 3 } } });
1006
851
 
1007
852
  expect(count).toBe(2);
1008
- expect(count).toBe(findAllResults.length);
853
+ expect(mockPerspective.modelQuery).toHaveBeenCalled();
1009
854
  });
1010
855
 
1011
- it("should apply JS-level filtering for between operator on properties in SPARQL count()", async () => {
1012
- // Mock query results: 5 recipes with ratings 1, 2, 3, 4, 5
1013
- const queryResults = [
1014
- ...Array.from({ length: 5 }, (_, i) => [
1015
- { source: `literal:recipe${i+1}`, predicate: "recipe://name", target: `Recipe ${i+1}`, author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" },
1016
- { source: `literal:recipe${i+1}`, predicate: "recipe://rating", target: `${i+1}`, author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" }
1017
- ]).flat()
1018
- ];
1019
-
1020
- mockPerspective.querySparql.mockResolvedValue(queryResults);
856
+ it("should apply filtering for between operator on properties in SPARQL count()", async () => {
857
+ mockPerspective.modelQuery.mockResolvedValue({
858
+ instances: [],
859
+ totalCount: 3
860
+ });
1021
861
 
1022
862
  // Count recipes with rating between 2 and 4 (should match 3 recipes: rating 2, 3, 4)
1023
- const count = await Recipe.count(mockPerspective, { where: { rating: { between: [2, 4] } } }, 'sparql');
1024
-
1025
- // Verify count matches the number of instances that would be returned by findAll
1026
- const findAllResults = await Recipe.findAll(mockPerspective, { where: { rating: { between: [2, 4] } } }, 'sparql');
863
+ const count = await Recipe.count(mockPerspective, { where: { rating: { between: [2, 4] } } });
1027
864
 
1028
865
  expect(count).toBe(3);
1029
- expect(count).toBe(findAllResults.length);
866
+ expect(mockPerspective.modelQuery).toHaveBeenCalled();
1030
867
  });
1031
868
 
1032
- it("should apply JS-level filtering for timestamp gt operator in SPARQL count()", async () => {
1033
- // Mock query results: 5 recipes with different timestamps
1034
- const queryResults = [
1035
- ...Array.from({ length: 5 }, (_, i) => [
1036
- { source: `literal:recipe${i+1}`, predicate: "recipe://name", target: `Recipe ${i+1}`, author: "did:key:alice", timestamp: `2023-01-0${i+1}T00:00:00Z` },
1037
- { source: `literal:recipe${i+1}`, predicate: "recipe://rating", target: "5", author: "did:key:alice", timestamp: `2023-01-0${i+1}T00:00:00Z` }
1038
- ]).flat()
1039
- ];
1040
-
1041
- mockPerspective.querySparql.mockResolvedValue(queryResults);
869
+ it("should apply filtering for timestamp gt operator in SPARQL count()", async () => {
870
+ mockPerspective.modelQuery.mockResolvedValue({
871
+ instances: [],
872
+ totalCount: 2
873
+ });
1042
874
 
1043
- // Count recipes with timestamp > 2023-01-03 (should match 2 recipes: 2023-01-04 and 2023-01-05)
1044
875
  const targetTimestamp = new Date("2023-01-03T00:00:00Z").getTime();
1045
- const count = await Recipe.count(mockPerspective, { where: { timestamp: { gt: targetTimestamp } } }, 'sparql');
1046
-
1047
- // Verify count matches the number of instances that would be returned by findAll
1048
- const findAllResults = await Recipe.findAll(mockPerspective, { where: { timestamp: { gt: targetTimestamp } } }, 'sparql');
876
+ const count = await Recipe.count(mockPerspective, { where: { timestamp: { gt: targetTimestamp } } });
1049
877
 
1050
878
  expect(count).toBe(2);
1051
- expect(count).toBe(findAllResults.length);
879
+ expect(mockPerspective.modelQuery).toHaveBeenCalled();
1052
880
  });
1053
881
 
1054
- it("should apply JS-level filtering for timestamp between operator in SPARQL count()", async () => {
1055
- // Mock query results: 5 recipes with different timestamps
1056
- const queryResults = [
1057
- ...Array.from({ length: 5 }, (_, i) => [
1058
- { source: `literal:recipe${i+1}`, predicate: "recipe://name", target: `Recipe ${i+1}`, author: "did:key:alice", timestamp: `2023-01-0${i+1}T00:00:00Z` },
1059
- { source: `literal:recipe${i+1}`, predicate: "recipe://rating", target: "5", author: "did:key:alice", timestamp: `2023-01-0${i+1}T00:00:00Z` }
1060
- ]).flat()
1061
- ];
1062
-
1063
- mockPerspective.querySparql.mockResolvedValue(queryResults);
882
+ it("should apply filtering for timestamp between operator in SPARQL count()", async () => {
883
+ mockPerspective.modelQuery.mockResolvedValue({
884
+ instances: [],
885
+ totalCount: 3
886
+ });
1064
887
 
1065
- // Count recipes with timestamp between 2023-01-02 and 2023-01-04
1066
888
  const startTimestamp = new Date("2023-01-02T00:00:00Z").getTime();
1067
889
  const endTimestamp = new Date("2023-01-04T00:00:00Z").getTime();
1068
890
  const count = await Recipe.count(mockPerspective, {
1069
891
  where: { timestamp: { between: [startTimestamp, endTimestamp] } }
1070
- }, 'sparql');
1071
-
1072
- // Verify count matches the number of instances that would be returned by findAll
1073
- const findAllResults = await Recipe.findAll(mockPerspective, {
1074
- where: { timestamp: { between: [startTimestamp, endTimestamp] } }
1075
- }, 'sparql');
892
+ });
1076
893
 
1077
894
  expect(count).toBe(3);
1078
- expect(count).toBe(findAllResults.length);
1079
- });
1080
-
1081
- it("should apply JS-level filtering for author filtering in SPARQL count()", async () => {
1082
- // Mock query results: 3 recipes by Alice and 2 by Bob
1083
- const queryResults = [
1084
- ...Array.from({ length: 3 }, (_, i) => [
1085
- { source: `literal:recipe${i+1}`, predicate: "recipe://name", target: `Recipe ${i+1}`, author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" },
1086
- { source: `literal:recipe${i+1}`, predicate: "recipe://rating", target: "5", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" }
1087
- ]).flat(),
1088
- ...Array.from({ length: 2 }, (_, i) => [
1089
- { source: `literal:recipe${i+4}`, predicate: "recipe://name", target: `Recipe ${i+4}`, author: "did:key:bob", timestamp: "2023-01-02T00:00:00Z" },
1090
- { source: `literal:recipe${i+4}`, predicate: "recipe://rating", target: "5", author: "did:key:bob", timestamp: "2023-01-02T00:00:00Z" }
1091
- ]).flat()
1092
- ];
1093
-
1094
- mockPerspective.querySparql.mockResolvedValue(queryResults);
895
+ expect(mockPerspective.modelQuery).toHaveBeenCalled();
896
+ });
897
+
898
+ it("should apply filtering for author filtering in SPARQL count()", async () => {
899
+ mockPerspective.modelQuery.mockResolvedValue({
900
+ instances: [],
901
+ totalCount: 3
902
+ });
1095
903
 
1096
904
  // Count recipes by Alice (should match 3 recipes)
1097
- const count = await Recipe.count(mockPerspective, { where: { author: "did:key:alice" } }, 'sparql');
1098
-
1099
- // Verify count matches the number of instances that would be returned by findAll
1100
- const findAllResults = await Recipe.findAll(mockPerspective, { where: { author: "did:key:alice" } }, 'sparql');
905
+ const count = await Recipe.count(mockPerspective, { where: { author: "did:key:alice" } });
1101
906
 
1102
907
  expect(count).toBe(3);
1103
- expect(count).toBe(findAllResults.length);
908
+ expect(mockPerspective.modelQuery).toHaveBeenCalled();
1104
909
  });
1105
910
 
1106
- it("should apply JS-level filtering in ModelQueryBuilder.count() with gt operator", async () => {
1107
- // Mock query results: 5 recipes with ratings 1, 2, 3, 4, 5
1108
- const queryResults = [
1109
- ...Array.from({ length: 5 }, (_, i) => [
1110
- { source: `literal:recipe${i+1}`, predicate: "recipe://name", target: `Recipe ${i+1}`, author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" },
1111
- { source: `literal:recipe${i+1}`, predicate: "recipe://rating", target: `${i+1}`, author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" }
1112
- ]).flat()
1113
- ];
1114
-
1115
- mockPerspective.querySparql.mockResolvedValue(queryResults);
911
+ it("should apply filtering in ModelQueryBuilder.count() with gt operator", async () => {
912
+ mockPerspective.modelQuery.mockResolvedValue({
913
+ instances: [],
914
+ totalCount: 2
915
+ });
1116
916
 
1117
917
  // Count recipes with rating > 3 using ModelQueryBuilder
1118
918
  const count = await Recipe.query(mockPerspective)
@@ -1120,26 +920,15 @@ describe("Ad4mModel.count() with advanced where conditions", () => {
1120
920
  .engine('sparql')
1121
921
  .count();
1122
922
 
1123
- // Verify count matches the number of instances that would be returned by get()
1124
- const getResults = await Recipe.query(mockPerspective)
1125
- .where({ rating: { gt: 3 } })
1126
- .engine('sparql')
1127
- .get();
1128
-
1129
923
  expect(count).toBe(2);
1130
- expect(count).toBe(getResults.length);
924
+ expect(mockPerspective.modelQuery).toHaveBeenCalled();
1131
925
  });
1132
926
 
1133
- it("should apply JS-level filtering in ModelQueryBuilder.count() with timestamp between", async () => {
1134
- // Mock query results: 5 recipes with different timestamps
1135
- const queryResults = [
1136
- ...Array.from({ length: 5 }, (_, i) => [
1137
- { source: `literal:recipe${i+1}`, predicate: "recipe://name", target: `Recipe ${i+1}`, author: "did:key:alice", timestamp: `2023-01-0${i+1}T00:00:00Z` },
1138
- { source: `literal:recipe${i+1}`, predicate: "recipe://rating", target: "5", author: "did:key:alice", timestamp: `2023-01-0${i+1}T00:00:00Z` }
1139
- ]).flat()
1140
- ];
1141
-
1142
- mockPerspective.querySparql.mockResolvedValue(queryResults);
927
+ it("should apply filtering in ModelQueryBuilder.count() with timestamp between", async () => {
928
+ mockPerspective.modelQuery.mockResolvedValue({
929
+ instances: [],
930
+ totalCount: 3
931
+ });
1143
932
 
1144
933
  const startTimestamp = new Date("2023-01-02T00:00:00Z").getTime();
1145
934
  const endTimestamp = new Date("2023-01-04T00:00:00Z").getTime();
@@ -1150,114 +939,13 @@ describe("Ad4mModel.count() with advanced where conditions", () => {
1150
939
  .engine('sparql')
1151
940
  .count();
1152
941
 
1153
- // Verify count matches the number of instances that would be returned by get()
1154
- const getResults = await Recipe.query(mockPerspective)
1155
- .where({ timestamp: { between: [startTimestamp, endTimestamp] } })
1156
- .engine('sparql')
1157
- .get();
1158
-
1159
942
  expect(count).toBe(3);
1160
- expect(count).toBe(getResults.length);
943
+ expect(mockPerspective.modelQuery).toHaveBeenCalled();
1161
944
  });
1162
945
 
1163
- it("should handle count() with Prolog for gt operator (legacy)", async () => {
1164
- const prologResults = [{ TotalCount: 2 }];
1165
- mockPerspective.infer.mockResolvedValue(prologResults);
1166
-
1167
- const count = await Recipe.count(mockPerspective, { where: { rating: { gt: 3 } } }, false);
1168
-
1169
- expect(mockPerspective.infer).toHaveBeenCalledTimes(1);
1170
- expect(mockPerspective.querySparql).not.toHaveBeenCalled();
1171
- expect(count).toBe(2);
1172
- });
1173
-
1174
- it("should handle count() with Prolog for timestamp between (legacy)", async () => {
1175
- const prologResults = [{ TotalCount: 3 }];
1176
- mockPerspective.infer.mockResolvedValue(prologResults);
1177
-
1178
- const startTimestamp = new Date("2023-01-02T00:00:00Z").getTime();
1179
- const endTimestamp = new Date("2023-01-04T00:00:00Z").getTime();
1180
-
1181
- const count = await Recipe.count(
1182
- mockPerspective,
1183
- { where: { timestamp: { between: [startTimestamp, endTimestamp] } } },
1184
- false
1185
- );
1186
-
1187
- expect(mockPerspective.infer).toHaveBeenCalledTimes(1);
1188
- expect(mockPerspective.querySparql).not.toHaveBeenCalled();
1189
- expect(count).toBe(3);
1190
- });
1191
946
  });
1192
947
 
1193
948
 
1194
- // ──────────────────────────────────────────────────────────
1195
- // Batch SPARQL query builder tests
1196
- // ──────────────────────────────────────────────────────────
1197
-
1198
- import { buildBatchSPARQLQuery } from "./query-sparql-batch";
1199
-
1200
- describe("buildBatchSPARQLQuery", () => {
1201
- @Model({ name: "Author" })
1202
- class Author extends Ad4mModel {
1203
- @Property({ through: "author://name", required: true })
1204
- name!: string;
1205
- }
1206
-
1207
- @Model({ name: "Book" })
1208
- class Book extends Ad4mModel {
1209
- @Property({ through: "book://title", required: true })
1210
- title!: string;
1211
-
1212
- @HasMany(() => Author, { through: "book://author" })
1213
- authors!: Author[];
1214
- }
1215
-
1216
- it("should generate UNION branches for depth 0 and depth 1 includes", () => {
1217
- const metadata = Book.getModelMetadata();
1218
- const query = { include: { authors: true } };
1219
- const sparql = buildBatchSPARQLQuery(metadata, query, Book);
1220
-
1221
- expect(sparql).toContain("?depth");
1222
- expect(sparql).toContain("?parentBase");
1223
- expect(sparql).toContain("?relationName");
1224
- expect(sparql).toContain("UNION");
1225
- expect(sparql).toContain("BIND(\"0\" AS ?depth)");
1226
- expect(sparql).toContain("BIND(\"1\" AS ?depth)");
1227
- expect(sparql).toContain("book://author");
1228
- });
1229
-
1230
- it("should include parent filter when query.parent is specified", () => {
1231
- const metadata = Book.getModelMetadata();
1232
- const query = {
1233
- parent: { id: "flux://library1", predicate: "library://books" },
1234
- include: { authors: true },
1235
- };
1236
- const sparql = buildBatchSPARQLQuery(metadata, query, Book);
1237
-
1238
- expect(sparql).toContain("flux://library1");
1239
- expect(sparql).toContain("library://books");
1240
- });
1241
-
1242
- it("should include where filter for simple equality", () => {
1243
- const metadata = Book.getModelMetadata();
1244
- const query = {
1245
- where: { title: "My Book" },
1246
- include: { authors: true },
1247
- };
1248
- const sparql = buildBatchSPARQLQuery(metadata, query, Book);
1249
-
1250
- // For literal-stored properties, SPARQL only has a JOIN (no FILTER value) — filtering in JS
1251
- expect(sparql).toContain("book://title");
1252
- expect(sparql).toContain("root_wTarget_eq_title");
1253
- });
1254
-
1255
- it("should throw when include is empty", () => {
1256
- const metadata = Book.getModelMetadata();
1257
- expect(() => buildBatchSPARQLQuery(metadata, {}, Book)).toThrow("requires query.include");
1258
- });
1259
- });
1260
-
1261
949
  describe("SPARQL comparison filters", () => {
1262
950
  @Model({ name: "Item" })
1263
951
  class Item extends Ad4mModel {
@@ -1294,7 +982,8 @@ describe("SPARQL comparison filters", () => {
1294
982
  // SPARQL Direct Triple Pattern & IRI Tests
1295
983
  // ──────────────────────────────────────────────────────────
1296
984
 
1297
- import { buildSPARQLQuery, groupSPARQLResults, formatSPARQLValue, buildSPARQLGetDataQuery } from "./query-sparql";
985
+ import { buildSPARQLQuery, formatSPARQLValue } from "./query-sparql";
986
+ import { SHACLShape } from "../shacl/SHACLShape";
1298
987
 
1299
988
  describe("SPARQL direct triple pattern generation", () => {
1300
989
  @Model({ name: "Channel" })
@@ -1334,17 +1023,14 @@ describe("SPARQL direct triple pattern generation", () => {
1334
1023
  expect(query).toMatch(/\?source\s+<flux:\/\/name>\s+\?cfTarget_name/);
1335
1024
  });
1336
1025
 
1337
- it("uses GRAPH ?linkGraph pattern for author/timestamp", async () => {
1338
- const query = await (Channel as any).queryToSPARQL(mockPersp, {});
1339
- expect(query).toContain("GRAPH ?linkGraph { ?source ?predicate ?target . }");
1340
- expect(query).toContain("?linkGraph <ad4m://ontology/author> ?author");
1341
- expect(query).toContain("?linkGraph <ad4m://ontology/timestamp> ?timestamp");
1342
- });
1343
-
1344
- it("does NOT contain RDF-star BIND(<< >> AS ?ann) pattern", async () => {
1026
+ it("uses RDF 1.2 reifier pattern for author/timestamp", async () => {
1345
1027
  const query = await (Channel as any).queryToSPARQL(mockPersp, {});
1346
- expect(query).not.toContain("BIND(<<");
1347
- expect(query).not.toContain("?ann ");
1028
+ expect(query).toContain("<http://www.w3.org/1999/02/22-rdf-syntax-ns#reifies>");
1029
+ expect(query).toContain("?source ?predicate ?target .");
1030
+ expect(query).toContain("?_reifier <http://www.w3.org/1999/02/22-rdf-syntax-ns#reifies> <<( ?source ?predicate ?target )>>");
1031
+ expect(query).toContain("?_reifier <ad4m://ontology/author> ?author");
1032
+ expect(query).toContain("?_reifier <ad4m://ontology/timestamp> ?timestamp");
1033
+ expect(query).not.toContain("GRAPH");
1348
1034
  });
1349
1035
 
1350
1036
  it("uses FILTER(isIRI(?source)) to exclude non-IRI subjects", async () => {
@@ -1353,60 +1039,7 @@ describe("SPARQL direct triple pattern generation", () => {
1353
1039
  });
1354
1040
  });
1355
1041
 
1356
- describe("SPARQL IRI formatting", () => {
1357
- it("wraps AD4M URIs in angle brackets", () => {
1358
- const query = buildSPARQLGetDataQuery("ad4m://test123");
1359
- expect(query).toContain("<ad4m://test123>");
1360
- });
1361
-
1362
- it("wraps literal: URIs in angle brackets", () => {
1363
- const query = buildSPARQLGetDataQuery("literal:string:foo");
1364
- expect(query).toContain("<literal:string:foo>");
1365
- });
1366
-
1367
- it("wraps flux:// URIs in angle brackets", () => {
1368
- const query = buildSPARQLGetDataQuery("flux://has_channel");
1369
- expect(query).toContain("<flux://has_channel>");
1370
- });
1371
-
1372
- it("wraps did:key URIs in angle brackets", () => {
1373
- const query = buildSPARQLGetDataQuery("did:key:z6MkhaXg");
1374
- expect(query).toContain("<did:key:z6MkhaXg>");
1375
- });
1376
- });
1377
-
1378
- describe("groupSPARQLResults", () => {
1379
- it("groups flat rows by source URI", () => {
1380
- const rows = [
1381
- { source: "ad4m://a", predicate: "p1", target: "t1", author: "auth1", timestamp: "ts1" },
1382
- { source: "ad4m://a", predicate: "p2", target: "t2", author: "auth1", timestamp: "ts1" },
1383
- { source: "ad4m://b", predicate: "p1", target: "t3", author: "auth2", timestamp: "ts2" },
1384
- ];
1385
- const grouped = groupSPARQLResults(rows);
1386
- expect(grouped).toHaveLength(2);
1387
-
1388
- const aGroup = grouped.find(g => g.source_uri === "ad4m://a");
1389
- expect(aGroup).toBeDefined();
1390
- expect(aGroup!.links).toHaveLength(2);
1391
1042
 
1392
- const bGroup = grouped.find(g => g.source_uri === "ad4m://b");
1393
- expect(bGroup).toBeDefined();
1394
- expect(bGroup!.links).toHaveLength(1);
1395
- });
1396
-
1397
- it("returns empty array for empty input", () => {
1398
- expect(groupSPARQLResults([])).toEqual([]);
1399
- });
1400
-
1401
- it("preserves metadata in grouped links", () => {
1402
- const rows = [
1403
- { source: "x", predicate: "p", target: "t", author: "did:key:z6Mk", timestamp: "2024-01-01T00:00:00Z" },
1404
- ];
1405
- const grouped = groupSPARQLResults(rows);
1406
- expect(grouped[0].links[0].author).toBe("did:key:z6Mk");
1407
- expect(grouped[0].links[0].timestamp).toBe("2024-01-01T00:00:00Z");
1408
- });
1409
- });
1410
1043
 
1411
1044
  describe("formatSPARQLValue", () => {
1412
1045
  it("wraps strings in double quotes", () => {
@@ -1426,7 +1059,7 @@ describe("formatSPARQLValue", () => {
1426
1059
  // Comprehensive SPARQL migration unit tests
1427
1060
  // ──────────────────────────────────────────────────────────
1428
1061
 
1429
- import { matchesCondition, hydrateFromLinks } from "./hydration";
1062
+ import { matchesCondition } from "./hydration";
1430
1063
  import { Literal } from "../Literal";
1431
1064
 
1432
1065
  // Helper: create literal URLs using JSON encoding (which handles all types including booleans)
@@ -1532,205 +1165,6 @@ describe("matchesCondition()", () => {
1532
1165
  });
1533
1166
  });
1534
1167
 
1535
- describe("hydrateFromLinks()", () => {
1536
- // Create a mock perspective that won't be called for literal properties
1537
- const mockPerspective = {} as any;
1538
-
1539
- @Model({ name: "HydrationTest" })
1540
- class HydrationTest extends Ad4mModel {
1541
- @Property({ through: "test://name", resolveLanguage: "literal" })
1542
- name: string = "";
1543
-
1544
- @Property({ through: "test://score", resolveLanguage: "literal" })
1545
- score: number = 0;
1546
-
1547
- @Property({ through: "test://active", resolveLanguage: "literal" })
1548
- active: boolean = false;
1549
- }
1550
-
1551
- const metadata = HydrationTest.getModelMetadata();
1552
-
1553
- it("hydrates all properties when requestedProperties is undefined", async () => {
1554
- const instance = new HydrationTest(mockPerspective) as any;
1555
- const links = [
1556
- { predicate: "test://name", target: literalUrl("Alice"), author: "did:test", timestamp: "1000" },
1557
- { predicate: "test://score", target: literalUrl(42), author: "did:test", timestamp: "1000" },
1558
- { predicate: "test://active", target: literalUrl(true), author: "did:test", timestamp: "1000" },
1559
- ];
1560
- await hydrateFromLinks(instance, links, metadata, mockPerspective, undefined);
1561
- expect(instance.name).toBe("Alice");
1562
- expect(instance.score).toBe(42);
1563
- expect(instance.active).toBe(true);
1564
- });
1565
-
1566
- it("hydrates only requested properties when requestedProperties is provided", async () => {
1567
- const instance = new HydrationTest(mockPerspective) as any;
1568
- const links = [
1569
- { predicate: "test://name", target: literalUrl("Alice"), author: "did:test", timestamp: "1000" },
1570
- { predicate: "test://score", target: literalUrl(42), author: "did:test", timestamp: "1000" },
1571
- { predicate: "test://active", target: literalUrl(true), author: "did:test", timestamp: "1000" },
1572
- ];
1573
- await hydrateFromLinks(instance, links, metadata, mockPerspective, ["name"]);
1574
- expect(instance.name).toBe("Alice");
1575
- // score and active should remain at defaults since not requested
1576
- expect(instance.score).toBe(0);
1577
- expect(instance.active).toBe(false);
1578
- });
1579
-
1580
- it("hydrates where-clause + projection properties when both are in requestedProperties", async () => {
1581
- const instance = new HydrationTest(mockPerspective) as any;
1582
- const links = [
1583
- { predicate: "test://name", target: literalUrl("Recipe 2"), author: "did:test", timestamp: "1000" },
1584
- { predicate: "test://active", target: literalUrl(true), author: "did:test", timestamp: "1000" },
1585
- ];
1586
- // Simulate merged hydration props: projection ["active"] + where clause props ["name"]
1587
- await hydrateFromLinks(instance, links, metadata, mockPerspective, ["active", "name"]);
1588
- expect(instance.name).toBe("Recipe 2");
1589
- expect(instance.active).toBe(true);
1590
- });
1591
-
1592
- it("sets author and timestamps from links", async () => {
1593
- const instance = new HydrationTest(mockPerspective) as any;
1594
- const links = [
1595
- { predicate: "test://name", target: literalUrl("Bob"), author: "did:author1", timestamp: "1000" },
1596
- { predicate: "test://score", target: literalUrl(10), author: "did:author2", timestamp: "2000" },
1597
- ];
1598
- await hydrateFromLinks(instance, links, metadata, mockPerspective);
1599
- expect(instance.author).toBe("did:author1");
1600
- expect(instance.createdAt).toBe(1000);
1601
- expect(instance.updatedAt).toBe(2000);
1602
- });
1603
-
1604
- it("handles empty links array", async () => {
1605
- const instance = new HydrationTest(mockPerspective) as any;
1606
- await hydrateFromLinks(instance, [], metadata, mockPerspective);
1607
- expect(instance.name).toBe("");
1608
- expect(instance.score).toBe(0);
1609
- });
1610
- });
1611
-
1612
- describe("instancesFromQueryResult — where + properties interaction", () => {
1613
- const mockPerspective = {
1614
- get: jest.fn().mockResolvedValue([]),
1615
- querySparql: jest.fn().mockResolvedValue([]),
1616
- getExpression: jest.fn().mockResolvedValue(null),
1617
- } as any;
1618
-
1619
- @Model({ name: "Recipe" })
1620
- class Recipe extends Ad4mModel {
1621
- @Property({ through: "recipe://name", resolveLanguage: "literal", required: true })
1622
- name: string = "";
1623
-
1624
- @Property({ through: "recipe://booleanTest", resolveLanguage: "literal" })
1625
- booleanTest: boolean = false;
1626
-
1627
- @Property({ through: "recipe://score", resolveLanguage: "literal" })
1628
- score: number = 0;
1629
- }
1630
-
1631
- it("should filter by where clause property even when not in properties projection", async () => {
1632
- // Simulate SPARQL result with two recipes
1633
- const grouped = [
1634
- {
1635
- source_uri: "expr:recipe1",
1636
- links: [
1637
- { predicate: "recipe://name", target: literalUrl("Recipe 1"), author: "did:test", timestamp: "1000" },
1638
- { predicate: "recipe://booleanTest", target: literalUrl(true), author: "did:test", timestamp: "1000" },
1639
- ],
1640
- },
1641
- {
1642
- source_uri: "expr:recipe2",
1643
- links: [
1644
- { predicate: "recipe://name", target: literalUrl("Recipe 2"), author: "did:test", timestamp: "1000" },
1645
- { predicate: "recipe://booleanTest", target: literalUrl(false), author: "did:test", timestamp: "1000" },
1646
- ],
1647
- },
1648
- ];
1649
-
1650
- const query = { where: { name: "Recipe 2" }, properties: ["booleanTest"] };
1651
- const { results } = await Recipe.instancesFromQueryResult(mockPerspective, query, grouped);
1652
-
1653
- expect(results.length).toBe(1);
1654
- expect((results[0] as any).booleanTest).toBe(false);
1655
- // name should be deleted after filtering since it wasn't in properties projection
1656
- expect((results[0] as any).name).toBeUndefined();
1657
- });
1658
-
1659
- it("should delete unrequested properties AFTER where-filtering", async () => {
1660
- const grouped = [
1661
- {
1662
- source_uri: "expr:recipe1",
1663
- links: [
1664
- { predicate: "recipe://name", target: literalUrl("Recipe 1"), author: "did:test", timestamp: "1000" },
1665
- { predicate: "recipe://score", target: literalUrl(99), author: "did:test", timestamp: "1000" },
1666
- ],
1667
- },
1668
- ];
1669
-
1670
- const query = { where: { name: "Recipe 1" }, properties: ["score"] };
1671
- const { results } = await Recipe.instancesFromQueryResult(mockPerspective, query, grouped);
1672
-
1673
- expect(results.length).toBe(1);
1674
- expect((results[0] as any).score).toBe(99);
1675
- // name was used for filtering but should be deleted from final result
1676
- expect((results[0] as any).name).toBeUndefined();
1677
- });
1678
-
1679
- it("should return all properties when no projection is specified", async () => {
1680
- const grouped = [
1681
- {
1682
- source_uri: "expr:recipe1",
1683
- links: [
1684
- { predicate: "recipe://name", target: literalUrl("Test"), author: "did:test", timestamp: "1000" },
1685
- { predicate: "recipe://booleanTest", target: literalUrl(true), author: "did:test", timestamp: "1000" },
1686
- { predicate: "recipe://score", target: literalUrl(50), author: "did:test", timestamp: "1000" },
1687
- ],
1688
- },
1689
- ];
1690
-
1691
- const query = { where: { name: "Test" } };
1692
- const { results } = await Recipe.instancesFromQueryResult(mockPerspective, query, grouped);
1693
-
1694
- expect(results.length).toBe(1);
1695
- expect((results[0] as any).name).toBe("Test");
1696
- expect((results[0] as any).booleanTest).toBe(true);
1697
- expect((results[0] as any).score).toBe(50);
1698
- });
1699
- });
1700
-
1701
- describe("groupSPARQLResults()", () => {
1702
- it("groups rows by source", () => {
1703
- const rows = [
1704
- { source: "a", predicate: "p1", target: "t1", author: "auth", timestamp: "ts1" },
1705
- { source: "a", predicate: "p2", target: "t2", author: "auth", timestamp: "ts2" },
1706
- { source: "b", predicate: "p1", target: "t3", author: "auth", timestamp: "ts3" },
1707
- ];
1708
- const grouped = groupSPARQLResults(rows);
1709
- expect(grouped.length).toBe(2);
1710
- const groupA = grouped.find(g => g.source_uri === "a")!;
1711
- const groupB = grouped.find(g => g.source_uri === "b")!;
1712
- expect(groupA.links.length).toBe(2);
1713
- expect(groupB.links.length).toBe(1);
1714
- });
1715
-
1716
- it("handles empty input", () => {
1717
- expect(groupSPARQLResults([])).toEqual([]);
1718
- });
1719
-
1720
- it("preserves link metadata", () => {
1721
- const rows = [
1722
- { source: "x", predicate: "pred", target: "tgt", author: "did:auth", timestamp: "2024-01-01" },
1723
- ];
1724
- const grouped = groupSPARQLResults(rows);
1725
- expect(grouped[0].links[0]).toEqual({
1726
- predicate: "pred",
1727
- target: "tgt",
1728
- author: "did:auth",
1729
- timestamp: "2024-01-01",
1730
- });
1731
- });
1732
- });
1733
-
1734
1168
  describe("buildSPARQLQuery edge cases", () => {
1735
1169
  @Model({ name: "FlagModel" })
1736
1170
  class FlagModel extends Ad4mModel {
@@ -1784,81 +1218,6 @@ describe("buildSPARQLQuery edge cases", () => {
1784
1218
  });
1785
1219
  });
1786
1220
 
1787
- describe("sparse fieldset property deletion timing", () => {
1788
- const mockPerspective = {
1789
- get: jest.fn().mockResolvedValue([]),
1790
- querySparql: jest.fn().mockResolvedValue([]),
1791
- getExpression: jest.fn().mockResolvedValue(null),
1792
- } as any;
1793
-
1794
- @Model({ name: "TimingTest" })
1795
- class TimingTest extends Ad4mModel {
1796
- @Property({ through: "timing://a", resolveLanguage: "literal" })
1797
- a: string = "";
1798
-
1799
- @Property({ through: "timing://b", resolveLanguage: "literal" })
1800
- b: string = "";
1801
-
1802
- @Property({ through: "timing://c", resolveLanguage: "literal" })
1803
- c: string = "";
1804
- }
1805
-
1806
- it("where-clause properties are available during filtering but deleted after", async () => {
1807
- const grouped = [
1808
- {
1809
- source_uri: "expr:1",
1810
- links: [
1811
- { predicate: "timing://a", target: literalUrl("match"), author: "did:test", timestamp: "1000" },
1812
- { predicate: "timing://b", target: literalUrl("keep"), author: "did:test", timestamp: "1000" },
1813
- { predicate: "timing://c", target: literalUrl("ignore"), author: "did:test", timestamp: "1000" },
1814
- ],
1815
- },
1816
- {
1817
- source_uri: "expr:2",
1818
- links: [
1819
- { predicate: "timing://a", target: literalUrl("no-match"), author: "did:test", timestamp: "1000" },
1820
- { predicate: "timing://b", target: literalUrl("skip"), author: "did:test", timestamp: "1000" },
1821
- { predicate: "timing://c", target: literalUrl("skip"), author: "did:test", timestamp: "1000" },
1822
- ],
1823
- },
1824
- ];
1825
-
1826
- // properties projection asks for "b" only, where clause filters on "a"
1827
- const query = { where: { a: "match" }, properties: ["b"] };
1828
- const { results } = await TimingTest.instancesFromQueryResult(mockPerspective, query, grouped);
1829
-
1830
- // Only the matching instance should survive
1831
- expect(results.length).toBe(1);
1832
- // "b" was requested — should be present
1833
- expect((results[0] as any).b).toBe("keep");
1834
- // "a" was used for filtering but not in projection — should be deleted
1835
- expect((results[0] as any).a).toBeUndefined();
1836
- // "c" was not requested — should be deleted
1837
- expect((results[0] as any).c).toBeUndefined();
1838
- });
1839
-
1840
- it("properties not in projection are undefined after instancesFromQueryResult", async () => {
1841
- const grouped = [
1842
- {
1843
- source_uri: "expr:1",
1844
- links: [
1845
- { predicate: "timing://a", target: literalUrl("val-a"), author: "did:test", timestamp: "1000" },
1846
- { predicate: "timing://b", target: literalUrl("val-b"), author: "did:test", timestamp: "1000" },
1847
- { predicate: "timing://c", target: literalUrl("val-c"), author: "did:test", timestamp: "1000" },
1848
- ],
1849
- },
1850
- ];
1851
-
1852
- const query = { properties: ["a"] };
1853
- const { results } = await TimingTest.instancesFromQueryResult(mockPerspective, query, grouped);
1854
-
1855
- expect(results.length).toBe(1);
1856
- expect((results[0] as any).a).toBe("val-a");
1857
- expect((results[0] as any).b).toBeUndefined();
1858
- expect((results[0] as any).c).toBeUndefined();
1859
- });
1860
- });
1861
-
1862
1221
  // ── Batch hydration for reverse relations (3.4) ─────────────────────────────
1863
1222
  describe("Batch hydration for reverse relations", () => {
1864
1223
  it("batch hydration should correctly group targets by parent instance ID", () => {
@@ -1970,26 +1329,28 @@ describe("Push-down FILTER for literal equality", () => {
1970
1329
 
1971
1330
  const normalizeQuery = (q: string) => q.replace(/\s+/g, " ").trim();
1972
1331
 
1973
- it("SPARQL query for where: { name: 'Alice' } should add JOIN but NOT parse_literal FILTER", async () => {
1332
+ it("SPARQL query for where: { name: 'Alice' } should use <ad4m://fn/parse_literal> FILTER", async () => {
1974
1333
  const query = await (FilterTest as any).queryToSPARQL(mockPerspective, { where: { name: "Alice" } });
1975
1334
  const norm = normalizeQuery(query);
1976
- // JOIN pattern exists (ensures property is present for JS post-filter)
1335
+ // JOIN pattern exists
1977
1336
  expect(norm).toContain("?wTarget_name");
1978
- // No parse_literal FILTER — custom fn:: functions aren't valid in parsed SPARQL
1337
+ // parse_literal push-down FILTER is present (using correct SPARQL IRI syntax)
1338
+ expect(norm).toContain("ad4m://fn/parse_literal");
1979
1339
  expect(norm).not.toContain("fn::parse_literal");
1980
1340
  });
1981
1341
 
1982
- it("SPARQL query for where: { name: ['Alice', 'Bob'] } should add JOIN but NOT parse_literal FILTER", async () => {
1342
+ it("SPARQL query for where: { name: ['Alice', 'Bob'] } should use <ad4m://fn/parse_literal> IN FILTER", async () => {
1983
1343
  const query = await (FilterTest as any).queryToSPARQL(mockPerspective, { where: { name: ["Alice", "Bob"] } });
1984
1344
  const norm = normalizeQuery(query);
1985
1345
  expect(norm).toContain("?wTarget_name");
1346
+ expect(norm).toContain("ad4m://fn/parse_literal");
1986
1347
  expect(norm).not.toContain("fn::parse_literal");
1987
1348
  });
1988
1349
 
1989
1350
  it("SPARQL query for where: { rating: { gt: 5 } } should NOT include parse_literal FILTER", async () => {
1990
1351
  const query = await (FilterTest as any).queryToSPARQL(mockPerspective, { where: { rating: { gt: 5 } } });
1991
1352
  const norm = normalizeQuery(query);
1992
- expect(norm).not.toContain("fn::parse_literal");
1353
+ expect(norm).not.toContain("parse_literal");
1993
1354
  });
1994
1355
 
1995
1356
  it("literal property where clause adds JOIN for JS post-filter", async () => {
@@ -2229,18 +1590,33 @@ describe("Native SPARQL getter evaluation", () => {
2229
1590
  // ── Subscribe callback timing ──────────────────────────────────────────
2230
1591
  describe("ModelQueryBuilder subscribe callback timing", () => {
2231
1592
  it("subscribe should not invoke callback synchronously before Promise resolves", async () => {
2232
- // This test verifies that the initial callback from subscribe() is deferred
2233
- // via queueMicrotask, preventing Preact/React hook lifecycle violations
2234
- // when subscribe() is called from useEffect.
1593
+ // This test verifies that subscribe() uses the Rust model subscription endpoint
1594
+ // and properly handles the subscription lifecycle.
2235
1595
 
1596
+ const mockSubscriptionId = "test-sub-123";
1597
+ let updateCallback: ((result: any) => void) | null = null;
1598
+
1599
+ const mockClient = {
1600
+ modelSubscribe: jest.fn().mockResolvedValue({
1601
+ subscriptionId: mockSubscriptionId,
1602
+ result: { instances: [], totalCount: 0 },
1603
+ }),
1604
+ subscribeToQueryUpdates: jest.fn().mockImplementation((_id: string, cb: any) => {
1605
+ updateCallback = cb;
1606
+ return () => {}; // unsubscribe function
1607
+ }),
1608
+ keepAliveQuery: jest.fn().mockResolvedValue(true),
1609
+ disposeQuerySubscription: jest.fn().mockResolvedValue(true),
1610
+ };
1611
+
2236
1612
  const mockPerspective = {
2237
- getLinks: jest.fn().mockResolvedValue([]),
2238
- subscribeQuery: jest.fn().mockResolvedValue({
2239
- result: '[]',
2240
- onResult: jest.fn(),
2241
- dispose: jest.fn(),
1613
+ uuid: "test-uuid",
1614
+ client: mockClient,
1615
+ modelSubscribe: jest.fn().mockImplementation(async (className: string, queryJson: string, shapeJson?: string) => {
1616
+ return mockClient.modelSubscribe("test-uuid", className, queryJson, shapeJson);
2242
1617
  }),
2243
- querySparql: jest.fn().mockResolvedValue('[]'),
1618
+ getLinks: jest.fn().mockResolvedValue([]),
1619
+ modelQuery: jest.fn().mockResolvedValue({ instances: [], totalCount: 0 }),
2244
1620
  } as any;
2245
1621
 
2246
1622
  const { Ad4mModel, Model, Property, Flag } = require("./index");
@@ -2267,12 +1643,189 @@ describe("ModelQueryBuilder subscribe callback timing", () => {
2267
1643
  // The callback should NOT have fired synchronously
2268
1644
  expect(callbackInvokedBeforeResolve).toBe(false);
2269
1645
 
2270
- await promise;
1646
+ const initialResults = await promise;
2271
1647
  promiseResolved = true;
2272
1648
 
2273
- // After the microtask queue drains, the callback should fire
2274
- await new Promise(r => setTimeout(r, 10));
2275
- // The callback was deferred — it fires after the Promise resolves
1649
+ expect(initialResults).toEqual([]);
1650
+ expect(mockPerspective.modelSubscribe).toHaveBeenCalled();
1651
+ });
1652
+ });
1653
+
1654
+ describe("ModelQueryBuilder paginateSubscribe", () => {
1655
+ it("paginateSubscribe should use a single query with count: true", async () => {
1656
+ const mockSubscriptionId = "paginate-sub-123";
1657
+
1658
+ const mockClient = {
1659
+ modelSubscribe: jest.fn().mockResolvedValue({
1660
+ subscriptionId: mockSubscriptionId,
1661
+ result: { instances: [], totalCount: 0 },
1662
+ }),
1663
+ subscribeToQueryUpdates: jest.fn().mockImplementation((_id: string, _cb: any) => {
1664
+ return () => {};
1665
+ }),
1666
+ keepAliveQuery: jest.fn().mockResolvedValue(true),
1667
+ disposeQuerySubscription: jest.fn().mockResolvedValue(true),
1668
+ };
1669
+
1670
+ const mockPerspective = {
1671
+ uuid: "test-uuid",
1672
+ client: mockClient,
1673
+ modelSubscribe: jest.fn().mockImplementation(async (className: string, queryJson: string, shapeJson?: string) => {
1674
+ return mockClient.modelSubscribe("test-uuid", className, queryJson, shapeJson);
1675
+ }),
1676
+ modelQuery: jest.fn().mockResolvedValue({ instances: [{ id: "item1", type: "test://paginate" }], totalCount: 42 }),
1677
+ } as any;
1678
+
1679
+ const { Ad4mModel, Model, Flag, Property } = require("./index");
1680
+
1681
+ @Model({ name: "PaginateTest" })
1682
+ class PaginateTest extends Ad4mModel {
1683
+ @Flag({ through: "test://type", value: "test://paginate" })
1684
+ type: string = "test://paginate";
1685
+ @Property({ through: "test://name" })
1686
+ name: string = "";
1687
+ }
1688
+
1689
+ const builder = PaginateTest.query(mockPerspective);
1690
+ const result = await builder.paginateSubscribe(10, 1, () => {});
1691
+
1692
+ // Should return paginated result structure
1693
+ expect(result).toHaveProperty("results");
1694
+ expect(result).toHaveProperty("totalCount");
1695
+ expect(result).toHaveProperty("pageSize", 10);
1696
+ expect(result).toHaveProperty("pageNumber", 1);
1697
+
1698
+ // modelQuery should be called exactly once (not twice — no separate count query)
1699
+ expect(mockPerspective.modelQuery).toHaveBeenCalledTimes(1);
1700
+
1701
+ // The query should have count: true
1702
+ const callArgs = mockPerspective.modelQuery.mock.calls[0];
1703
+ const queryJson = JSON.parse(callArgs[1]);
1704
+ expect(queryJson.count).toBe(true);
1705
+ expect(queryJson.limit).toBe(10);
1706
+ expect(queryJson.offset).toBe(0);
1707
+ });
1708
+
1709
+ it("paginateSubscribe should skip isInit messages from subscription", async () => {
1710
+ const mockSubscriptionId = "paginate-init-sub";
1711
+ let capturedCallback: ((result: any) => void) | null = null;
1712
+
1713
+ const mockClient = {
1714
+ modelSubscribe: jest.fn().mockResolvedValue({
1715
+ subscriptionId: mockSubscriptionId,
1716
+ result: { instances: [], totalCount: 0 },
1717
+ }),
1718
+ subscribeToQueryUpdates: jest.fn().mockImplementation((_id: string, cb: any) => {
1719
+ capturedCallback = cb;
1720
+ return () => {};
1721
+ }),
1722
+ keepAliveQuery: jest.fn().mockResolvedValue(true),
1723
+ disposeQuerySubscription: jest.fn().mockResolvedValue(true),
1724
+ };
1725
+
1726
+ let modelQueryCallCount = 0;
1727
+ const mockPerspective = {
1728
+ uuid: "test-uuid",
1729
+ client: mockClient,
1730
+ modelSubscribe: jest.fn().mockImplementation(async (className: string, queryJson: string, shapeJson?: string) => {
1731
+ return mockClient.modelSubscribe("test-uuid", className, queryJson, shapeJson);
1732
+ }),
1733
+ modelQuery: jest.fn().mockImplementation(async () => {
1734
+ modelQueryCallCount++;
1735
+ return { instances: [], totalCount: 0 };
1736
+ }),
1737
+ } as any;
1738
+
1739
+ const { Ad4mModel, Model, Flag, Property } = require("./index");
1740
+
1741
+ @Model({ name: "InitGuardTest" })
1742
+ class InitGuardTest extends Ad4mModel {
1743
+ @Flag({ through: "test://type", value: "test://init" })
1744
+ type: string = "test://init";
1745
+ @Property({ through: "test://name" })
1746
+ name: string = "";
1747
+ }
1748
+
1749
+ const userCallback = jest.fn();
1750
+ const builder = InitGuardTest.query(mockPerspective);
1751
+ await builder.paginateSubscribe(10, 1, userCallback);
1752
+
1753
+ // Reset the count after initial fetch
1754
+ const initialCallCount = modelQueryCallCount;
1755
+
1756
+ // Simulate an isInit message from subscription
1757
+ expect(capturedCallback).not.toBeNull();
1758
+ capturedCallback!({ isInit: true });
1759
+
1760
+ // Wait for any async processing
1761
+ await new Promise(r => setTimeout(r, 50));
1762
+
1763
+ // modelQuery should NOT have been called again (isInit was filtered)
1764
+ expect(modelQueryCallCount).toBe(initialCallCount);
1765
+ // User callback should NOT have been invoked by isInit
1766
+ expect(userCallback).not.toHaveBeenCalled();
1767
+ });
1768
+
1769
+ it("paginateSubscribe should re-fetch on real subscription updates", async () => {
1770
+ const mockSubscriptionId = "paginate-update-sub";
1771
+ let capturedCallback: ((result: any) => void) | null = null;
1772
+
1773
+ const mockClient = {
1774
+ modelSubscribe: jest.fn().mockResolvedValue({
1775
+ subscriptionId: mockSubscriptionId,
1776
+ result: { instances: [], totalCount: 0 },
1777
+ }),
1778
+ subscribeToQueryUpdates: jest.fn().mockImplementation((_id: string, cb: any) => {
1779
+ capturedCallback = cb;
1780
+ return () => {};
1781
+ }),
1782
+ keepAliveQuery: jest.fn().mockResolvedValue(true),
1783
+ disposeQuerySubscription: jest.fn().mockResolvedValue(true),
1784
+ };
1785
+
1786
+ let modelQueryCallCount = 0;
1787
+ const mockPerspective = {
1788
+ uuid: "test-uuid",
1789
+ client: mockClient,
1790
+ modelSubscribe: jest.fn().mockImplementation(async (className: string, queryJson: string, shapeJson?: string) => {
1791
+ return mockClient.modelSubscribe("test-uuid", className, queryJson, shapeJson);
1792
+ }),
1793
+ modelQuery: jest.fn().mockImplementation(async () => {
1794
+ modelQueryCallCount++;
1795
+ return { instances: [{ id: "new-item", type: "test://update" }], totalCount: 1 };
1796
+ }),
1797
+ } as any;
1798
+
1799
+ const { Ad4mModel, Model, Flag, Property } = require("./index");
1800
+
1801
+ @Model({ name: "UpdateTest" })
1802
+ class UpdateTest extends Ad4mModel {
1803
+ @Flag({ through: "test://type", value: "test://update" })
1804
+ type: string = "test://update";
1805
+ @Property({ through: "test://name" })
1806
+ name: string = "";
1807
+ }
1808
+
1809
+ const userCallback = jest.fn();
1810
+ const builder = UpdateTest.query(mockPerspective);
1811
+ await builder.paginateSubscribe(10, 1, userCallback);
1812
+
1813
+ const initialCallCount = modelQueryCallCount;
1814
+
1815
+ // Simulate a real subscription update (not isInit)
1816
+ capturedCallback!({ instances: [{ id: "new-item" }], totalCount: 1 });
1817
+
1818
+ // Wait for async processing
1819
+ await new Promise(r => setTimeout(r, 100));
1820
+
1821
+ // modelQuery should have been called again for the re-fetch
1822
+ expect(modelQueryCallCount).toBeGreaterThan(initialCallCount);
1823
+ // User callback should have been invoked with paginated results
1824
+ expect(userCallback).toHaveBeenCalled();
1825
+ const callArg = userCallback.mock.calls[0][0];
1826
+ expect(callArg).toHaveProperty("totalCount");
1827
+ expect(callArg).toHaveProperty("pageSize", 10);
1828
+ expect(callArg).toHaveProperty("pageNumber", 1);
2276
1829
  });
2277
1830
  });
2278
1831
 
@@ -2281,7 +1834,6 @@ describe("ModelQueryBuilder subscribe callback timing", () => {
2281
1834
  // ============================================================================
2282
1835
 
2283
1836
  import { getCachedResult, setCachedResult, clearQueryCache, queryCacheSize } from "./query-cache";
2284
- import { clearSubscriptionPool, subscriptionPoolSize } from "./subscription-pool";
2285
1837
  import { getPropertiesMetadata, getRelationsMetadata, getMemoizedSHACL } from "./decorators";
2286
1838
 
2287
1839
  describe("QueryCache", () => {
@@ -2407,3 +1959,470 @@ describe("Lazy Conformance Filters", () => {
2407
1959
  expect(shacl.name).toBe("LazyParent2");
2408
1960
  });
2409
1961
  });
1962
+
1963
+ // ──────────────────────────────────────────────────────────
1964
+ // deepQuery opt-in — getter evaluation on collection queries
1965
+ // ──────────────────────────────────────────────────────────
1966
+
1967
+ describe("deepQuery opt-in — getter evaluation", () => {
1968
+ @Model({ name: "DeepQueryTestMessage" })
1969
+ class DeepQueryTestMessage extends Ad4mModel {
1970
+ @Flag({ through: "flux://entry_type", value: "flux://message" })
1971
+ type: string = "";
1972
+
1973
+ @Property({ through: "flux://body", resolveLanguage: "literal" })
1974
+ body: string = "";
1975
+
1976
+ @Property({
1977
+ through: "flux://has_reply",
1978
+ getter: `SELECT ?target WHERE { ?source <flux://has_reply> ?target . } LIMIT 1`,
1979
+ })
1980
+ replyingTo?: string;
1981
+
1982
+ @ReadOnly({
1983
+ through: "flux://is_popular",
1984
+ getter: `ASK WHERE { ?source <flux://is_popular> "true" . }`,
1985
+ })
1986
+ isPopular: boolean = false;
1987
+
1988
+ @HasMany({ through: "flux://reaction" })
1989
+ reactions: string[] = [];
1990
+ }
1991
+
1992
+ let sparqlCalls: string[];
1993
+ const mockPerspective: any = {
1994
+ uuid: "test-uuid",
1995
+ modelQuery: jest.fn(async (className: string, queryJson: string, shapeJson: string) => {
1996
+ // Return a basic result for the single-instance getData() path
1997
+ const query = JSON.parse(queryJson);
1998
+ const id = query?.where?.id;
1999
+ if (id) {
2000
+ return {
2001
+ instances: [{ id, body: "Hello" }],
2002
+ totalCount: 1,
2003
+ };
2004
+ }
2005
+ return { instances: [], totalCount: 0 };
2006
+ }),
2007
+ querySparql: jest.fn(async (q: string) => {
2008
+ sparqlCalls.push(q);
2009
+ return [];
2010
+ }),
2011
+ get: jest.fn().mockResolvedValue([]),
2012
+ getExpression: jest.fn().mockResolvedValue(null),
2013
+ stringOrTemplateObjectToSubjectClassName: jest.fn().mockResolvedValue("DeepQueryTestMessage"),
2014
+ };
2015
+
2016
+ beforeEach(() => {
2017
+ sparqlCalls = [];
2018
+ mockPerspective.querySparql.mockClear();
2019
+ mockPerspective.get.mockClear();
2020
+ });
2021
+
2022
+ function makeInstances(count: number): InstanceType<typeof DeepQueryTestMessage>[] {
2023
+ return Array.from({ length: count }, (_, i) =>
2024
+ new DeepQueryTestMessage(mockPerspective, `flux://msg-${i}`)
2025
+ );
2026
+ }
2027
+
2028
+ it("single-instance get() delegates getter evaluation to Rust (no JS-side SPARQL)", async () => {
2029
+ const instance = new DeepQueryTestMessage(mockPerspective, "flux://msg-single");
2030
+ mockPerspective.querySparql.mockImplementation(async (q: string) => {
2031
+ sparqlCalls.push(q);
2032
+ if (q.includes("flux://msg-single") && !q.includes("flux://has_reply") && !q.includes("flux://is_popular")) {
2033
+ return [
2034
+ { source: "flux://msg-single", predicate: "flux://entry_type", target: "flux://message", author: "did:key:a", timestamp: "3000" },
2035
+ { source: "flux://msg-single", predicate: "flux://body", target: "literal:string:Hello", author: "did:key:a", timestamp: "3000" },
2036
+ ];
2037
+ }
2038
+ return [];
2039
+ });
2040
+
2041
+ await instance.get();
2042
+ // Getter evaluation now happens Rust-side via evaluate_getters() — no JS SPARQL calls
2043
+ const getterCalls = sparqlCalls.filter(
2044
+ (q) => q.includes("flux://has_reply") || q.includes("flux://is_popular")
2045
+ );
2046
+ expect(getterCalls.length).toBe(0);
2047
+ });
2048
+
2049
+ describe("Ad4mModel.evaluateGetters()", () => {
2050
+ it("resolves getters for a batch of instances", async () => {
2051
+ const instances = makeInstances(4);
2052
+ sparqlCalls = [];
2053
+
2054
+ await DeepQueryTestMessage.evaluateGetters(instances.slice(0, 2), mockPerspective, ["replyingTo"]);
2055
+
2056
+ const replyCalls = sparqlCalls.filter((q) => q.includes("flux://has_reply"));
2057
+ expect(replyCalls.length).toBe(2);
2058
+ const popularCalls = sparqlCalls.filter((q) => q.includes("flux://is_popular"));
2059
+ expect(popularCalls.length).toBe(0);
2060
+ });
2061
+
2062
+ it("evaluates all getters when propertyNames is omitted", async () => {
2063
+ const instances = makeInstances(2);
2064
+ sparqlCalls = [];
2065
+
2066
+ await DeepQueryTestMessage.evaluateGetters(instances, mockPerspective);
2067
+
2068
+ const replyCalls = sparqlCalls.filter((q) => q.includes("flux://has_reply"));
2069
+ const popularCalls = sparqlCalls.filter((q) => q.includes("flux://is_popular"));
2070
+ expect(replyCalls.length).toBe(2);
2071
+ expect(popularCalls.length).toBe(2);
2072
+ });
2073
+
2074
+ it("handles empty array gracefully", async () => {
2075
+ sparqlCalls = [];
2076
+ await DeepQueryTestMessage.evaluateGetters([], mockPerspective);
2077
+ expect(sparqlCalls.length).toBe(0);
2078
+ });
2079
+ });
2080
+
2081
+ describe("deepQuery via ModelQueryBuilder", () => {
2082
+ it("deepQuery() method sets deepQuery flag on queryParams", () => {
2083
+ const builder = DeepQueryTestMessage.query(mockPerspective);
2084
+ (builder as any).deepQuery();
2085
+ expect((builder as any).queryParams.deepQuery).toBe(true);
2086
+ });
2087
+ });
2088
+ });
2089
+
2090
+ // ─── Ad4mModel.fromSHACL() ───────────────────────────────────────────────────
2091
+
2092
+ describe("Ad4mModel.fromSHACL()", () => {
2093
+ function makeShape(targetClass: string, props: Array<import("../shacl/SHACLShape").SHACLPropertyShape>) {
2094
+ const shape = new SHACLShape(targetClass);
2095
+ for (const p of props) shape.addProperty(p);
2096
+ return shape;
2097
+ }
2098
+
2099
+ it("assigns the given name as className", () => {
2100
+ const shape = makeShape("flux://Channel", []);
2101
+ const Cls = Ad4mModel.fromSHACL(shape, "Channel");
2102
+ expect((Cls as any).className).toBe("Channel");
2103
+ expect((new (Cls as any)({}, "flux://1")).className).toBe("Channel");
2104
+ });
2105
+
2106
+ it("registers scalar property (maxCount=1) via setPropertyRegistryEntry", () => {
2107
+ const shape = makeShape("flux://Channel", [
2108
+ { name: "title", path: "flux://has_title", maxCount: 1, writable: true },
2109
+ ]);
2110
+ const Cls = Ad4mModel.fromSHACL(shape, "Channel");
2111
+ const meta = Cls.getModelMetadata();
2112
+ expect(meta.properties["title"]).toBeDefined();
2113
+ expect(meta.properties["title"].predicate).toBe("flux://has_title");
2114
+ expect(meta.properties["title"].readOnly).toBe(false);
2115
+ });
2116
+
2117
+ it("registers collection property (no maxCount) as hasMany relation", () => {
2118
+ const shape = makeShape("flux://Channel", [
2119
+ { name: "messages", path: "flux://has_message" },
2120
+ ]);
2121
+ const Cls = Ad4mModel.fromSHACL(shape, "Channel");
2122
+ const meta = Cls.getModelMetadata();
2123
+ expect(meta.relations["messages"]).toBeDefined();
2124
+ expect(meta.relations["messages"].predicate).toBe("flux://has_message");
2125
+ expect(meta.relations["messages"].direction).toBe("forward");
2126
+ });
2127
+
2128
+ it("registers collection property (maxCount=5) as hasMany relation", () => {
2129
+ const shape = makeShape("flux://Channel", [
2130
+ { name: "participants", path: "flux://participant", maxCount: 5 },
2131
+ ]);
2132
+ const Cls = Ad4mModel.fromSHACL(shape, "Channel");
2133
+ const meta = Cls.getModelMetadata();
2134
+ expect(meta.relations["participants"]).toBeDefined();
2135
+ expect(meta.relations["participants"].direction).toBe("forward");
2136
+ });
2137
+
2138
+ it("propagates resolveLanguage onto scalar properties", () => {
2139
+ const shape = makeShape("flux://Post", [
2140
+ { name: "body", path: "flux://body", maxCount: 1, resolveLanguage: "literal" },
2141
+ ]);
2142
+ const Cls = Ad4mModel.fromSHACL(shape, "Post");
2143
+ const meta = Cls.getModelMetadata();
2144
+ expect(meta.properties["body"].resolveLanguage).toBe("literal");
2145
+ });
2146
+
2147
+ it("defaults writable to true when not specified", () => {
2148
+ const shape = makeShape("flux://Post", [
2149
+ { name: "body", path: "flux://body", maxCount: 1 },
2150
+ ]);
2151
+ const Cls = Ad4mModel.fromSHACL(shape, "Post");
2152
+ const meta = Cls.getModelMetadata();
2153
+ expect(meta.properties["body"].readOnly).toBe(false);
2154
+ });
2155
+
2156
+ it("respects writable:false", () => {
2157
+ const shape = makeShape("flux://Post", [
2158
+ { name: "id", path: "flux://id", maxCount: 1, writable: false },
2159
+ ]);
2160
+ const Cls = Ad4mModel.fromSHACL(shape, "Post");
2161
+ const meta = Cls.getModelMetadata();
2162
+ expect(meta.properties["id"].readOnly).toBe(true);
2163
+ });
2164
+
2165
+ it("registers flag properties (hasValue) as type-discrimination entries", () => {
2166
+ const shape = makeShape("flux://Message", [
2167
+ { name: "type", path: "flux://entry_type", hasValue: "flux://message" },
2168
+ { name: "body", path: "flux://body", maxCount: 1 },
2169
+ ]);
2170
+ const Cls = Ad4mModel.fromSHACL(shape, "Message");
2171
+ const meta = Cls.getModelMetadata();
2172
+ expect(meta.properties["type"]).toBeDefined();
2173
+ expect(meta.properties["type"].predicate).toBe("flux://entry_type");
2174
+ expect(meta.properties["type"].flag).toBe(true);
2175
+ expect(meta.properties["type"].required).toBe(true);
2176
+ expect(meta.properties["type"].initial).toBe("flux://message");
2177
+ expect(meta.properties["body"]).toBeDefined();
2178
+ });
2179
+
2180
+ it("flag property from fromSHACL produces SPARQL type-discriminator triple", () => {
2181
+ const shape = makeShape("flux://Message", [
2182
+ { name: "type", path: "flux://entry_type", hasValue: "flux://message" },
2183
+ { name: "body", path: "flux://body", maxCount: 1 },
2184
+ ]);
2185
+ const Cls = Ad4mModel.fromSHACL(shape, "Message");
2186
+ const meta = Cls.getModelMetadata();
2187
+ const allRelsMeta = {} as any;
2188
+ const sparql = buildSPARQLQuery(meta, allRelsMeta, {}, Cls);
2189
+ expect(sparql).toContain("<flux://entry_type>");
2190
+ expect(sparql).toContain("<flux://message>");
2191
+ });
2192
+
2193
+ it("recovers flag value from constructor_actions (backward-compat for old shapes)", () => {
2194
+ const shape = new SHACLShape("flux://Channel");
2195
+ // An old shape: property has NO hasValue, but constructor_actions carries it
2196
+ shape.addProperty({ name: "type", path: "flux://entry_type", maxCount: 1 });
2197
+ shape.addProperty({ name: "name", path: "flux://name", maxCount: 1 });
2198
+ shape.constructor_actions = [
2199
+ { action: "addLink", source: "this", predicate: "flux://entry_type", target: "flux://channel" },
2200
+ ];
2201
+ const Cls = Ad4mModel.fromSHACL(shape, "Channel");
2202
+ const meta = Cls.getModelMetadata();
2203
+ expect(meta.properties["type"]).toBeDefined();
2204
+ expect(meta.properties["type"].flag).toBe(true);
2205
+ expect(meta.properties["type"].initial).toBe("flux://channel");
2206
+ });
2207
+
2208
+ it("skips properties without a name field", () => {
2209
+ const shape = makeShape("flux://Message", [
2210
+ { path: "flux://anonymous" } as any,
2211
+ { name: "body", path: "flux://body", maxCount: 1 },
2212
+ ]);
2213
+ const Cls = Ad4mModel.fromSHACL(shape, "Message");
2214
+ const meta = Cls.getModelMetadata();
2215
+ expect(Object.keys(meta.properties)).toEqual(["body"]);
2216
+ });
2217
+
2218
+ it("propagates local flag onto relations", () => {
2219
+ const shape = makeShape("flux://Channel", [
2220
+ { name: "drafts", path: "flux://draft", local: true },
2221
+ ]);
2222
+ const Cls = Ad4mModel.fromSHACL(shape, "Channel");
2223
+ const meta = Cls.getModelMetadata();
2224
+ expect(meta.relations["drafts"].local).toBe(true);
2225
+ });
2226
+
2227
+ it("applies Model decorator so generateSHACL and generateSDNA are available", () => {
2228
+ const shape = makeShape("flux://Channel", [
2229
+ { name: "title", path: "flux://has_title", maxCount: 1 },
2230
+ ]);
2231
+ const Cls = Ad4mModel.fromSHACL(shape, "Channel");
2232
+ expect(typeof (Cls as any).generateSDNA).toBe("function");
2233
+ expect(typeof (Cls as any).generateSHACL).toBe("function");
2234
+ });
2235
+
2236
+ it("handles shapes with no properties", () => {
2237
+ const shape = makeShape("flux://Empty", []);
2238
+ const Cls = Ad4mModel.fromSHACL(shape, "Empty");
2239
+ const meta = Cls.getModelMetadata();
2240
+ expect(Object.keys(meta.properties)).toHaveLength(0);
2241
+ expect(Object.keys(meta.relations)).toHaveLength(0);
2242
+ });
2243
+ });
2244
+
2245
+ // ---------------------------------------------------------------------------
2246
+ // IncludeProjection — key splitting and query routing
2247
+ // ---------------------------------------------------------------------------
2248
+
2249
+ describe("IncludeProjection type guard and key splitting", () => {
2250
+ // Shared test models
2251
+ @Model({ name: "Signal" })
2252
+ class Signal extends Ad4mModel {
2253
+ @Property({ through: "signal://type" })
2254
+ signalTypeId: string = "";
2255
+
2256
+ @Property({ through: "signal://author" })
2257
+ author: string = "";
2258
+ }
2259
+
2260
+ @Model({ name: "Post" })
2261
+ class Post extends Ad4mModel {
2262
+ @Property({ through: "post://title" })
2263
+ title: string = "";
2264
+
2265
+ @HasMany({ through: "post://signal", target: () => Signal })
2266
+ signals: Signal[] = [];
2267
+
2268
+ @HasMany({ through: "post://comment" })
2269
+ comments: string[] = [];
2270
+ }
2271
+
2272
+ const mockPerspective = {
2273
+ querySparql: jest.fn(),
2274
+ modelQuery: jest.fn(),
2275
+ infer: jest.fn(),
2276
+ uuid: "test-perspective-uuid",
2277
+ stringOrTemplateObjectToSubjectClassName: jest.fn().mockResolvedValue("Post"),
2278
+ } as any;
2279
+
2280
+ beforeEach(() => {
2281
+ jest.clearAllMocks();
2282
+ mockPerspective.modelQuery.mockResolvedValue({
2283
+ instances: [{ id: "post://1", title: "Hello", $signalCount: 3 }],
2284
+ totalCount: 1,
2285
+ });
2286
+ });
2287
+
2288
+ // --- isIncludeProjection type guard ---
2289
+
2290
+ it("isIncludeProjection returns true for objects with a 'from' field", () => {
2291
+ expect(isIncludeProjection({ from: "signals", count: true })).toBe(true);
2292
+ expect(isIncludeProjection({ from: "comments", limit: 1 })).toBe(true);
2293
+ });
2294
+
2295
+ it("isIncludeProjection returns false for non-projection values", () => {
2296
+ expect(isIncludeProjection(true)).toBe(false);
2297
+ expect(isIncludeProjection(false)).toBe(false);
2298
+ expect(isIncludeProjection(null)).toBe(false);
2299
+ expect(isIncludeProjection(undefined)).toBe(false);
2300
+ expect(isIncludeProjection(42)).toBe(false);
2301
+ // RelationSubQuery (has no 'from' key)
2302
+ expect(isIncludeProjection({ limit: 5, order: { timestamp: "DESC" } })).toBe(false);
2303
+ });
2304
+
2305
+ // --- $-key splitting ---
2306
+
2307
+ it("routes $-prefixed keys to queryInput.projections, not queryInput.include", async () => {
2308
+ await Post.findAll(mockPerspective, {
2309
+ include: {
2310
+ $signalCount: { from: "signals", count: true },
2311
+ comments: true,
2312
+ },
2313
+ });
2314
+
2315
+ const [, queryJson] = mockPerspective.modelQuery.mock.calls[0];
2316
+ const qi = JSON.parse(queryJson);
2317
+
2318
+ // Normal relation goes to include
2319
+ expect(qi.include?.comments).toBe(true);
2320
+ expect(qi.include?.$signalCount).toBeUndefined();
2321
+
2322
+ // Projection goes to projections
2323
+ expect(qi.projections?.$signalCount).toMatchObject({ from: "signals", count: true });
2324
+ expect(qi.projections?.comments).toBeUndefined();
2325
+ });
2326
+
2327
+ it("routes $-prefixed IncludeProjection values to projections ($ prefix required)", async () => {
2328
+ await Post.findAll(mockPerspective, {
2329
+ include: {
2330
+ $mySignals: { from: "signals", limit: 1 },
2331
+ comments: true,
2332
+ },
2333
+ });
2334
+
2335
+ const [, queryJson] = mockPerspective.modelQuery.mock.calls[0];
2336
+ const qi = JSON.parse(queryJson);
2337
+
2338
+ expect(qi.projections?.$mySignals).toMatchObject({ from: "signals", limit: 1 });
2339
+ expect(qi.include?.comments).toBe(true);
2340
+ });
2341
+
2342
+ it("does NOT route non-$ keys to projections even if value has 'from' shape", async () => {
2343
+ // $ prefix is required — a key without it goes to include, not projections
2344
+ await Post.findAll(mockPerspective, {
2345
+ include: {
2346
+ mySignals: { from: "signals", limit: 1 } as any,
2347
+ comments: true,
2348
+ },
2349
+ });
2350
+
2351
+ const [, queryJson] = mockPerspective.modelQuery.mock.calls[0];
2352
+ const qi = JSON.parse(queryJson);
2353
+
2354
+ // Without $ prefix it stays in include (behaviour is undefined/broken but not silently rerouted)
2355
+ expect(qi.projections?.mySignals).toBeUndefined();
2356
+ expect(qi.include?.mySignals).toBeDefined();
2357
+ });
2358
+
2359
+ it("omits queryInput.include when all keys are projections", async () => {
2360
+ await Post.findAll(mockPerspective, {
2361
+ include: {
2362
+ $count: { from: "signals", count: true },
2363
+ },
2364
+ });
2365
+
2366
+ const [, queryJson] = mockPerspective.modelQuery.mock.calls[0];
2367
+ const qi = JSON.parse(queryJson);
2368
+
2369
+ expect(qi.include).toBeUndefined();
2370
+ expect(qi.projections?.$count).toMatchObject({ from: "signals", count: true });
2371
+ });
2372
+
2373
+ it("omits queryInput.projections when all keys are normal includes", async () => {
2374
+ await Post.findAll(mockPerspective, {
2375
+ include: { comments: true },
2376
+ });
2377
+
2378
+ const [, queryJson] = mockPerspective.modelQuery.mock.calls[0];
2379
+ const qi = JSON.parse(queryJson);
2380
+
2381
+ expect(qi.projections).toBeUndefined();
2382
+ expect(qi.include?.comments).toBe(true);
2383
+ });
2384
+
2385
+ it("enriches projection with targetShape when relation target is registered", async () => {
2386
+ await Post.findAll(mockPerspective, {
2387
+ include: {
2388
+ $signalCount: { from: "signals", count: true },
2389
+ },
2390
+ });
2391
+
2392
+ const [, queryJson] = mockPerspective.modelQuery.mock.calls[0];
2393
+ const qi = JSON.parse(queryJson);
2394
+
2395
+ // targetShape should have been injected from the Signal model
2396
+ // ($ prefix is required for projection enrichment to apply)
2397
+ expect(qi.projections?.$signalCount?.targetShape?.className).toBe("Signal");
2398
+ });
2399
+
2400
+ it("leaves targetShape absent when relation has no target decorator", async () => {
2401
+ await Post.findAll(mockPerspective, {
2402
+ include: {
2403
+ $commentCount: { from: "comments", count: true },
2404
+ },
2405
+ });
2406
+
2407
+ const [, queryJson] = mockPerspective.modelQuery.mock.calls[0];
2408
+ const qi = JSON.parse(queryJson);
2409
+
2410
+ // 'comments' HasMany has no target() thunk → no targetShape
2411
+ expect(qi.projections?.$commentCount?.targetShape).toBeUndefined();
2412
+ });
2413
+
2414
+ // --- result passthrough ---
2415
+
2416
+ it("returns $-keyed projection values attached by Rust on instances", async () => {
2417
+ mockPerspective.modelQuery.mockResolvedValue({
2418
+ instances: [{ id: "post://1", title: "Hello", $signalCount: 7 }],
2419
+ totalCount: 1,
2420
+ });
2421
+
2422
+ const results = await Post.findAll(mockPerspective, {
2423
+ include: { $signalCount: { from: "signals", count: true } },
2424
+ });
2425
+
2426
+ expect((results[0] as any).$signalCount).toBe(7);
2427
+ });
2428
+ });