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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (264) hide show
  1. package/lib/index.cjs +1109 -828
  2. package/lib/index.js +1096 -828
  3. package/lib/src/Ad4mClient.d.ts +4 -1
  4. package/lib/src/Ad4mClient.js +2 -2
  5. package/lib/src/agent/AgentClient.js +17 -0
  6. package/lib/src/ai/AIClient.js +1 -1
  7. package/lib/src/apiClient.d.ts +5 -1
  8. package/lib/src/apiClient.js +14 -6
  9. package/lib/src/generated/rest/AIModelLoadingStatus.d.ts +7 -0
  10. package/lib/src/generated/rest/AIModelLoadingStatus.js +2 -0
  11. package/lib/src/generated/rest/AddAgentInfosRequest.d.ts +3 -0
  12. package/lib/src/generated/rest/AddAgentInfosRequest.js +2 -0
  13. package/lib/src/generated/rest/AddLinkExpressionRequest.d.ts +6 -0
  14. package/lib/src/generated/rest/AddLinkExpressionRequest.js +1 -0
  15. package/lib/src/generated/rest/AddLinkRequest.d.ts +6 -0
  16. package/lib/src/generated/rest/AddLinkRequest.js +1 -0
  17. package/lib/src/generated/rest/AddLinksBulkRequest.d.ts +6 -0
  18. package/lib/src/generated/rest/AddLinksBulkRequest.js +1 -0
  19. package/lib/src/generated/rest/AddSdnaRequest.d.ts +6 -0
  20. package/lib/src/generated/rest/AddSdnaRequest.js +2 -0
  21. package/lib/src/generated/rest/ApplyTemplateRequest.d.ts +4 -0
  22. package/lib/src/generated/rest/ApplyTemplateRequest.js +2 -0
  23. package/lib/src/generated/rest/AuthInfoInput.d.ts +10 -0
  24. package/lib/src/generated/rest/AuthInfoInput.js +1 -0
  25. package/lib/src/generated/rest/BroadcastRequest.d.ts +6 -0
  26. package/lib/src/generated/rest/BroadcastRequest.js +1 -0
  27. package/lib/src/generated/rest/CapabilityInput.d.ts +5 -0
  28. package/lib/src/generated/rest/CapabilityInput.js +1 -0
  29. package/lib/src/generated/rest/CommitBatchRequest.d.ts +3 -0
  30. package/lib/src/generated/rest/CommitBatchRequest.js +2 -0
  31. package/lib/src/generated/rest/ComputeLogEntry.d.ts +9 -0
  32. package/lib/src/generated/rest/ComputeLogEntry.js +2 -0
  33. package/lib/src/generated/rest/CreateExpressionRequest.d.ts +4 -0
  34. package/lib/src/generated/rest/CreateExpressionRequest.js +2 -0
  35. package/lib/src/generated/rest/CreatePerspectiveRequest.d.ts +3 -0
  36. package/lib/src/generated/rest/CreatePerspectiveRequest.js +2 -0
  37. package/lib/src/generated/rest/CreateSubjectRequest.d.ts +6 -0
  38. package/lib/src/generated/rest/CreateSubjectRequest.js +2 -0
  39. package/lib/src/generated/rest/CreateUserRequest.d.ts +4 -0
  40. package/lib/src/generated/rest/CreateUserRequest.js +2 -0
  41. package/lib/src/generated/rest/CreateUserResponse.d.ts +5 -0
  42. package/lib/src/generated/rest/CreateUserResponse.js +2 -0
  43. package/lib/src/generated/rest/DecoratedExpressionProof.d.ts +6 -0
  44. package/lib/src/generated/rest/DecoratedExpressionProof.js +2 -0
  45. package/lib/src/generated/rest/DecoratedLinkExpression.d.ts +10 -0
  46. package/lib/src/generated/rest/DecoratedLinkExpression.js +1 -0
  47. package/lib/src/generated/rest/DisposeQueryRequest.d.ts +3 -0
  48. package/lib/src/generated/rest/DisposeQueryRequest.js +2 -0
  49. package/lib/src/generated/rest/EmailTestRequest.d.ts +6 -0
  50. package/lib/src/generated/rest/EmailTestRequest.js +2 -0
  51. package/lib/src/generated/rest/EmbedRequest.d.ts +4 -0
  52. package/lib/src/generated/rest/EmbedRequest.js +2 -0
  53. package/lib/src/generated/rest/EntanglementProofInput.d.ts +6 -0
  54. package/lib/src/generated/rest/EntanglementProofInput.js +2 -0
  55. package/lib/src/generated/rest/EntanglementProofPreflightRequest.d.ts +4 -0
  56. package/lib/src/generated/rest/EntanglementProofPreflightRequest.js +2 -0
  57. package/lib/src/generated/rest/ExecuteCommandsRequest.d.ts +4 -0
  58. package/lib/src/generated/rest/ExecuteCommandsRequest.js +2 -0
  59. package/lib/src/generated/rest/ExportRequest.d.ts +5 -0
  60. package/lib/src/generated/rest/ExportRequest.js +2 -0
  61. package/lib/src/generated/rest/ExpressionManyRequest.d.ts +3 -0
  62. package/lib/src/generated/rest/ExpressionManyRequest.js +2 -0
  63. package/lib/src/generated/rest/ExpressionProof.d.ts +4 -0
  64. package/lib/src/generated/rest/ExpressionProof.js +2 -0
  65. package/lib/src/generated/rest/ExpressionProofInput.d.ts +6 -0
  66. package/lib/src/generated/rest/ExpressionProofInput.js +2 -0
  67. package/lib/src/generated/rest/FriendSendMessageRequest.d.ts +3 -0
  68. package/lib/src/generated/rest/FriendSendMessageRequest.js +2 -0
  69. package/lib/src/generated/rest/FriendsListRequest.d.ts +3 -0
  70. package/lib/src/generated/rest/FriendsListRequest.js +2 -0
  71. package/lib/src/generated/rest/GenerateAgentRequest.d.ts +3 -0
  72. package/lib/src/generated/rest/GenerateAgentRequest.js +2 -0
  73. package/lib/src/generated/rest/GenerateJwtRequest.d.ts +4 -0
  74. package/lib/src/generated/rest/GenerateJwtRequest.js +2 -0
  75. package/lib/src/generated/rest/GetSubjectDataRequest.d.ts +4 -0
  76. package/lib/src/generated/rest/GetSubjectDataRequest.js +2 -0
  77. package/lib/src/generated/rest/HostingInfoResponse.d.ts +5 -0
  78. package/lib/src/generated/rest/HostingInfoResponse.js +2 -0
  79. package/lib/src/generated/rest/HostingWalletResponse.d.ts +4 -0
  80. package/lib/src/generated/rest/HostingWalletResponse.js +2 -0
  81. package/lib/src/generated/rest/ImportAgentRequest.d.ts +6 -0
  82. package/lib/src/generated/rest/ImportAgentRequest.js +2 -0
  83. package/lib/src/generated/rest/ImportRequest.d.ts +4 -0
  84. package/lib/src/generated/rest/ImportRequest.js +2 -0
  85. package/lib/src/generated/rest/JoinNeighbourhoodRequest.d.ts +3 -0
  86. package/lib/src/generated/rest/JoinNeighbourhoodRequest.js +2 -0
  87. package/lib/src/generated/rest/KeepAliveQueryRequest.d.ts +3 -0
  88. package/lib/src/generated/rest/KeepAliveQueryRequest.js +2 -0
  89. package/lib/src/generated/rest/LanguageMetaInput.d.ts +6 -0
  90. package/lib/src/generated/rest/LanguageMetaInput.js +2 -0
  91. package/lib/src/generated/rest/Link.d.ts +5 -0
  92. package/lib/src/generated/rest/Link.js +2 -0
  93. package/lib/src/generated/rest/LinkExpression.d.ts +10 -0
  94. package/lib/src/generated/rest/LinkExpression.js +1 -0
  95. package/lib/src/generated/rest/LinkExpressionInput.d.ts +10 -0
  96. package/lib/src/generated/rest/LinkExpressionInput.js +1 -0
  97. package/lib/src/generated/rest/LinkInput.d.ts +5 -0
  98. package/lib/src/generated/rest/LinkInput.js +2 -0
  99. package/lib/src/generated/rest/LinkLanguageTemplatesRequest.d.ts +3 -0
  100. package/lib/src/generated/rest/LinkLanguageTemplatesRequest.js +2 -0
  101. package/lib/src/generated/rest/LinkMutationRequest.d.ts +12 -0
  102. package/lib/src/generated/rest/LinkMutationRequest.js +1 -0
  103. package/lib/src/generated/rest/LinkMutationResponse.d.ts +9 -0
  104. package/lib/src/generated/rest/LinkMutationResponse.js +1 -0
  105. package/lib/src/generated/rest/LinkMutations.d.ts +6 -0
  106. package/lib/src/generated/rest/LinkMutations.js +1 -0
  107. package/lib/src/generated/rest/LinkMutationsRequest.d.ts +5 -0
  108. package/lib/src/generated/rest/LinkMutationsRequest.js +1 -0
  109. package/lib/src/generated/rest/LinkStatus.d.ts +1 -0
  110. package/lib/src/generated/rest/LinkStatus.js +2 -0
  111. package/lib/src/generated/rest/LinkUpdateInput.d.ts +5 -0
  112. package/lib/src/generated/rest/LinkUpdateInput.js +1 -0
  113. package/lib/src/generated/rest/LockAgentRequest.d.ts +3 -0
  114. package/lib/src/generated/rest/LockAgentRequest.js +2 -0
  115. package/lib/src/generated/rest/LoginUserRequest.d.ts +5 -0
  116. package/lib/src/generated/rest/LoginUserRequest.js +2 -0
  117. package/lib/src/generated/rest/ModelType.d.ts +1 -0
  118. package/lib/src/generated/rest/ModelType.js +2 -0
  119. package/lib/src/generated/rest/NotificationGrantRequest.d.ts +3 -0
  120. package/lib/src/generated/rest/NotificationGrantRequest.js +2 -0
  121. package/lib/src/generated/rest/NotificationInput.d.ts +10 -0
  122. package/lib/src/generated/rest/NotificationInput.js +2 -0
  123. package/lib/src/generated/rest/OpenLinkRequest.d.ts +3 -0
  124. package/lib/src/generated/rest/OpenLinkRequest.js +2 -0
  125. package/lib/src/generated/rest/PermitCapabilityRequest.d.ts +3 -0
  126. package/lib/src/generated/rest/PermitCapabilityRequest.js +2 -0
  127. package/lib/src/generated/rest/PerspectiveInput.d.ts +4 -0
  128. package/lib/src/generated/rest/PerspectiveInput.js +1 -0
  129. package/lib/src/generated/rest/PromptRequest.d.ts +4 -0
  130. package/lib/src/generated/rest/PromptRequest.js +2 -0
  131. package/lib/src/generated/rest/PublicPerspectiveInput.d.ts +4 -0
  132. package/lib/src/generated/rest/PublicPerspectiveInput.js +1 -0
  133. package/lib/src/generated/rest/PublishLanguageRequest.d.ts +5 -0
  134. package/lib/src/generated/rest/PublishLanguageRequest.js +1 -0
  135. package/lib/src/generated/rest/PublishNeighbourhoodRequest.d.ts +6 -0
  136. package/lib/src/generated/rest/PublishNeighbourhoodRequest.js +1 -0
  137. package/lib/src/generated/rest/QueryRequest.d.ts +7 -0
  138. package/lib/src/generated/rest/QueryRequest.js +2 -0
  139. package/lib/src/generated/rest/RemoveLinkRequest.d.ts +5 -0
  140. package/lib/src/generated/rest/RemoveLinkRequest.js +1 -0
  141. package/lib/src/generated/rest/RemoveLinksBulkRequest.d.ts +5 -0
  142. package/lib/src/generated/rest/RemoveLinksBulkRequest.js +1 -0
  143. package/lib/src/generated/rest/RequestCapabilityRequest.d.ts +4 -0
  144. package/lib/src/generated/rest/RequestCapabilityRequest.js +1 -0
  145. package/lib/src/generated/rest/RequestPaymentRequest.d.ts +3 -0
  146. package/lib/src/generated/rest/RequestPaymentRequest.js +2 -0
  147. package/lib/src/generated/rest/RequestVerificationRequest.d.ts +4 -0
  148. package/lib/src/generated/rest/RequestVerificationRequest.js +2 -0
  149. package/lib/src/generated/rest/ResourceInput.d.ts +4 -0
  150. package/lib/src/generated/rest/ResourceInput.js +2 -0
  151. package/lib/src/generated/rest/SetDefaultModelRequest.d.ts +4 -0
  152. package/lib/src/generated/rest/SetDefaultModelRequest.js +1 -0
  153. package/lib/src/generated/rest/SetFreeHostingEnabledRequest.d.ts +3 -0
  154. package/lib/src/generated/rest/SetFreeHostingEnabledRequest.js +2 -0
  155. package/lib/src/generated/rest/SetHotWalletAddressRequest.d.ts +3 -0
  156. package/lib/src/generated/rest/SetHotWalletAddressRequest.js +2 -0
  157. package/lib/src/generated/rest/SetMultiUserRequest.d.ts +3 -0
  158. package/lib/src/generated/rest/SetMultiUserRequest.js +2 -0
  159. package/lib/src/generated/rest/SetOnlineStatusRequest.d.ts +5 -0
  160. package/lib/src/generated/rest/SetOnlineStatusRequest.js +1 -0
  161. package/lib/src/generated/rest/SetStatusRequest.d.ts +3 -0
  162. package/lib/src/generated/rest/SetStatusRequest.js +2 -0
  163. package/lib/src/generated/rest/SetUserFreeAccessRequest.d.ts +4 -0
  164. package/lib/src/generated/rest/SetUserFreeAccessRequest.js +2 -0
  165. package/lib/src/generated/rest/SignMessageRequest.d.ts +3 -0
  166. package/lib/src/generated/rest/SignMessageRequest.js +2 -0
  167. package/lib/src/generated/rest/SignalRequest.d.ts +6 -0
  168. package/lib/src/generated/rest/SignalRequest.js +1 -0
  169. package/lib/src/generated/rest/SubscribeQueryRequest.d.ts +3 -0
  170. package/lib/src/generated/rest/SubscribeQueryRequest.js +2 -0
  171. package/lib/src/generated/rest/SubscribeQueryResponse.d.ts +4 -0
  172. package/lib/src/generated/rest/SubscribeQueryResponse.js +2 -0
  173. package/lib/src/generated/rest/TrustedAgentsRequest.d.ts +3 -0
  174. package/lib/src/generated/rest/TrustedAgentsRequest.js +2 -0
  175. package/lib/src/generated/rest/UnlockAgentRequest.d.ts +4 -0
  176. package/lib/src/generated/rest/UnlockAgentRequest.js +2 -0
  177. package/lib/src/generated/rest/UpdateLinkRequest.d.ts +7 -0
  178. package/lib/src/generated/rest/UpdateLinkRequest.js +1 -0
  179. package/lib/src/generated/rest/UpdatePerspectiveRequest.d.ts +3 -0
  180. package/lib/src/generated/rest/UpdatePerspectiveRequest.js +2 -0
  181. package/lib/src/generated/rest/UpdateProfileRequest.d.ts +5 -0
  182. package/lib/src/generated/rest/UpdateProfileRequest.js +1 -0
  183. package/lib/src/generated/rest/UserStatistics.d.ts +9 -0
  184. package/lib/src/generated/rest/UserStatistics.js +2 -0
  185. package/lib/src/generated/rest/VerificationRequestResult.d.ts +6 -0
  186. package/lib/src/generated/rest/VerificationRequestResult.js +2 -0
  187. package/lib/src/generated/rest/VerifyEmailRequest.d.ts +6 -0
  188. package/lib/src/generated/rest/VerifyEmailRequest.js +2 -0
  189. package/lib/src/generated/rest/VerifySignatureRequest.d.ts +5 -0
  190. package/lib/src/generated/rest/VerifySignatureRequest.js +2 -0
  191. package/lib/src/generated/rest/WriteSettingsRequest.d.ts +3 -0
  192. package/lib/src/generated/rest/WriteSettingsRequest.js +2 -0
  193. package/lib/src/generated/rest/index.d.ts +73 -0
  194. package/lib/src/generated/rest/index.js +8 -0
  195. package/lib/src/generated/rest/routes.d.ts +587 -0
  196. package/lib/src/generated/rest/routes.js +3 -0
  197. package/lib/src/index.d.ts +4 -0
  198. package/lib/src/index.js +4 -0
  199. package/lib/src/model/Ad4mModel.d.ts +30 -36
  200. package/lib/src/model/Ad4mModel.js +93 -382
  201. package/lib/src/model/Ad4mModel.test.js +735 -480
  202. package/lib/src/model/ModelQueryBuilder.d.ts +5 -10
  203. package/lib/src/model/ModelQueryBuilder.js +142 -62
  204. package/lib/src/model/decorators.d.ts +7 -4
  205. package/lib/src/model/decorators.js +0 -7
  206. package/lib/src/model/query-sparql.d.ts +0 -10
  207. package/lib/src/model/query-sparql.js +10 -15
  208. package/lib/src/model/query-sparql.test.js +10 -92
  209. package/lib/src/model/query-surreal.d.ts +44 -0
  210. package/lib/src/model/query-surreal.js +249 -0
  211. package/lib/src/model/shacl-gen.js +120 -47
  212. package/lib/src/model/surreal-utils.d.ts +42 -0
  213. package/lib/src/model/surreal-utils.js +128 -0
  214. package/lib/src/model/types.d.ts +140 -4
  215. package/lib/src/neighbourhood/NeighbourhoodProxy.test.js +33 -33
  216. package/lib/src/perspectives/PerspectiveClient.d.ts +13 -4
  217. package/lib/src/perspectives/PerspectiveClient.js +22 -6
  218. package/lib/src/perspectives/PerspectiveProxy.d.ts +27 -7
  219. package/lib/src/perspectives/PerspectiveProxy.js +60 -12
  220. package/lib/src/perspectives/PerspectiveProxy.test.d.ts +1 -0
  221. package/lib/src/perspectives/PerspectiveProxy.test.js +34 -0
  222. package/lib/src/perspectives/SparqlBindings.d.ts +47 -0
  223. package/lib/src/perspectives/SparqlBindings.js +65 -0
  224. package/lib/src/perspectives/WakerSubscriptionManager.js +5 -4
  225. package/lib/src/restClient.d.ts +52 -0
  226. package/lib/src/restClient.js +227 -0
  227. package/lib/src/shacl/NodeExpression.d.ts +44 -0
  228. package/lib/src/shacl/NodeExpression.js +39 -0
  229. package/lib/src/shacl/SHACLShape.d.ts +23 -0
  230. package/lib/src/shacl/SHACLShape.js +115 -1
  231. package/lib/src/shacl/SHACLShape.test.js +0 -82
  232. package/lib/src/shacl/builders.d.ts +58 -0
  233. package/lib/src/shacl/builders.js +76 -0
  234. package/lib/src/shacl/index.d.ts +36 -0
  235. package/lib/src/shacl/index.js +33 -0
  236. package/package.json +11 -8
  237. package/src/Ad4mClient.ts +7 -2
  238. package/src/agent/AgentClient.ts +23 -0
  239. package/src/ai/AIClient.ts +1 -1
  240. package/src/apiClient.ts +17 -6
  241. package/src/index.ts +4 -0
  242. package/src/model/Ad4mModel.test.ts +274 -72
  243. package/src/model/Ad4mModel.ts +140 -420
  244. package/src/model/ModelQueryBuilder.ts +136 -71
  245. package/src/model/decorators.ts +7 -13
  246. package/src/model/query-sparql.test.ts +35 -19
  247. package/src/model/query-sparql.ts +10 -16
  248. package/src/model/relation-filtering.test.ts +46 -39
  249. package/src/model/shacl-gen.ts +128 -54
  250. package/src/model/shacl-roundtrip.test.ts +197 -0
  251. package/src/model/types-typed-query.test.ts +360 -0
  252. package/src/model/types.ts +196 -4
  253. package/src/perspectives/PerspectiveClient.ts +24 -8
  254. package/src/perspectives/PerspectiveProxy.test.ts +85 -1
  255. package/src/perspectives/PerspectiveProxy.ts +65 -20
  256. package/src/perspectives/SparqlBindings.ts +79 -0
  257. package/src/perspectives/WakerSubscriptionManager.ts +5 -4
  258. package/src/shacl/NodeExpression.ts +54 -0
  259. package/src/shacl/SHACLShape.test.ts +172 -0
  260. package/src/shacl/SHACLShape.ts +173 -1
  261. package/src/shacl/builders.ts +86 -0
  262. package/src/shacl/index.ts +72 -0
  263. package/lib/src/model/model-manifest.d.ts +0 -41
  264. package/lib/src/model/model-manifest.js +0 -11
@@ -619,18 +619,17 @@ describe("Ad4mModel.queryToSPARQL()", () => {
619
619
  expect(norm).toContain("&&");
620
620
  });
621
621
  // ---- ORDER BY, LIMIT, OFFSET are JS post-processed ----
622
- it("should include ORDER BY/LIMIT/OFFSET in SPARQL pagination subquery", async () => {
622
+ it("should NOT include ORDER BY/LIMIT/OFFSET in SPARQL (pagination is JS-only)", async () => {
623
623
  const query = await Recipe.queryToSPARQL(mockPerspective, { order: { name: "ASC" }, limit: 10, offset: 5 });
624
624
  const norm = normalizeQuery(query);
625
625
  expect(norm).toContain("SELECT ?source");
626
- // SPARQL-level pagination via subquery
627
- expect(norm).toContain("ORDER BY");
628
- expect(norm).toContain("LIMIT 10");
629
- expect(norm).toContain("OFFSET 5");
630
- expect(norm).toContain("SELECT DISTINCT ?source");
626
+ // Pagination is handled in JS, not SPARQL
627
+ expect(norm).not.toContain("ORDER BY");
628
+ expect(norm).not.toContain("LIMIT");
629
+ expect(norm).not.toContain("OFFSET");
631
630
  });
632
631
  });
633
- describe("Ad4mModel query methods (modelQuery integration)", () => {
632
+ describe("Ad4mModel.instancesFromQueryResult() and SPARQL integration", () => {
634
633
  // Test Recipe model
635
634
  let Recipe = class Recipe extends Ad4mModel {
636
635
  constructor() {
@@ -655,10 +654,9 @@ describe("Ad4mModel query methods (modelQuery integration)", () => {
655
654
  Recipe = __decorate([
656
655
  Model({ name: "Recipe" })
657
656
  ], Recipe);
658
- // Mock perspective with querySparql, modelQuery, and infer methods
657
+ // Mock perspective with both querySparql and infer methods
659
658
  const mockPerspective = {
660
659
  querySparql: jest.fn(),
661
- modelQuery: jest.fn(),
662
660
  infer: jest.fn(),
663
661
  uuid: 'test-perspective-uuid',
664
662
  stringOrTemplateObjectToSubjectClassName: jest.fn().mockResolvedValue('Recipe')
@@ -666,137 +664,246 @@ describe("Ad4mModel query methods (modelQuery integration)", () => {
666
664
  beforeEach(() => {
667
665
  jest.clearAllMocks();
668
666
  });
667
+ it("should convert empty query results correctly", async () => {
668
+ const result = await Recipe.instancesFromQueryResult(mockPerspective, {}, []);
669
+ expect(result.results).toEqual([]);
670
+ expect(result.totalCount).toBe(0);
671
+ });
672
+ it("should convert query results to model instances", async () => {
673
+ const queryResults = [
674
+ {
675
+ source: "node:abc123",
676
+ source_uri: "literal:recipe1",
677
+ links: [
678
+ { predicate: "recipe://name", target: "Pasta", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" },
679
+ { predicate: "recipe://rating", target: "5", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" },
680
+ { predicate: "recipe://ingredient", target: "pasta", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" },
681
+ { predicate: "recipe://ingredient", target: "tomato", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" },
682
+ { predicate: "recipe://ingredient", target: "cheese", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" }
683
+ ]
684
+ },
685
+ {
686
+ source: "node:def456",
687
+ source_uri: "literal:recipe2",
688
+ links: [
689
+ { predicate: "recipe://name", target: "Pizza", author: "did:key:bob", timestamp: "2023-01-02T00:00:00Z" },
690
+ { predicate: "recipe://rating", target: "4", author: "did:key:bob", timestamp: "2023-01-02T00:00:00Z" },
691
+ { predicate: "recipe://ingredient", target: "dough", author: "did:key:bob", timestamp: "2023-01-02T00:00:00Z" },
692
+ { predicate: "recipe://ingredient", target: "cheese", author: "did:key:bob", timestamp: "2023-01-02T00:00:00Z" },
693
+ { predicate: "recipe://ingredient", target: "tomato", author: "did:key:bob", timestamp: "2023-01-02T00:00:00Z" }
694
+ ]
695
+ }
696
+ ];
697
+ const result = await Recipe.instancesFromQueryResult(mockPerspective, {}, queryResults);
698
+ expect(result.results).toHaveLength(2);
699
+ expect(result.totalCount).toBe(2);
700
+ const recipe1 = result.results[0];
701
+ expect(recipe1).toBeInstanceOf(Recipe);
702
+ expect(recipe1.name).toBe("Pasta");
703
+ expect(recipe1.rating).toBe(5);
704
+ expect(recipe1.ingredients).toEqual(["pasta", "tomato", "cheese"]);
705
+ const recipe2 = result.results[1];
706
+ expect(recipe2).toBeInstanceOf(Recipe);
707
+ expect(recipe2.name).toBe("Pizza");
708
+ expect(recipe2.rating).toBe(4);
709
+ });
710
+ it("should filter properties when query specifies properties", async () => {
711
+ const queryResults = [
712
+ {
713
+ source: "node:abc123",
714
+ source_uri: "literal:recipe1",
715
+ links: [
716
+ { predicate: "recipe://name", target: "Pasta", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" },
717
+ { predicate: "recipe://rating", target: "5", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" },
718
+ { predicate: "recipe://ingredient", target: "pasta", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" },
719
+ { predicate: "recipe://ingredient", target: "tomato", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" }
720
+ ]
721
+ }
722
+ ];
723
+ const result = await Recipe.instancesFromQueryResult(mockPerspective, { properties: ["name"] }, queryResults);
724
+ expect(result.results).toHaveLength(1);
725
+ const recipe = result.results[0];
726
+ expect(recipe.name).toBe("Pasta");
727
+ // rating and ingredients should be removed since only "name" was requested
728
+ expect(recipe.rating).toBeUndefined();
729
+ expect(recipe.ingredients).toBeUndefined();
730
+ // author, createdAt, updatedAt are also stripped unless explicitly requested
731
+ expect(recipe.author).toBeUndefined();
732
+ expect(recipe.timestamp).toBeUndefined();
733
+ });
734
+ it("should filter properties when query specifies properties", async () => {
735
+ const queryResults = [
736
+ {
737
+ source: "node:abc123",
738
+ source_uri: "literal:recipe1",
739
+ links: [
740
+ { predicate: "recipe://name", target: "Pasta", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" },
741
+ { predicate: "recipe://rating", target: "5", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" },
742
+ { predicate: "recipe://ingredient", target: "pasta", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" },
743
+ { predicate: "recipe://ingredient", target: "tomato", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" }
744
+ ]
745
+ }
746
+ ];
747
+ const result = await Recipe.instancesFromQueryResult(mockPerspective, { properties: ["name"] }, queryResults);
748
+ expect(result.results).toHaveLength(1);
749
+ const recipe = result.results[0];
750
+ expect(recipe.name).toBe("Pasta");
751
+ // rating and ingredients should be removed since only "name" was requested
752
+ expect(recipe.rating).toBeUndefined();
753
+ });
754
+ it("should handle results missing base field", async () => {
755
+ const queryResults = [
756
+ {
757
+ links: [
758
+ { predicate: "recipe://name", target: "Pasta", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" },
759
+ { predicate: "recipe://rating", target: "5", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" }
760
+ ]
761
+ // Missing source field
762
+ }
763
+ ];
764
+ const result = await Recipe.instancesFromQueryResult(mockPerspective, {}, queryResults);
765
+ // Should filter out the invalid result (or handle gracefully)
766
+ expect(result.results).toHaveLength(0);
767
+ expect(result.totalCount).toBe(0);
768
+ });
669
769
  it("should use SPARQL when engine is 'sparql' in findAll()", async () => {
670
- // modelQuery returns already-hydrated instances from the Rust executor
671
- mockPerspective.modelQuery.mockResolvedValue({
672
- instances: [
673
- { id: "literal:recipe1", name: "Pasta", rating: 5, ingredients: ["pasta"] }
674
- ],
675
- totalCount: 1
676
- });
770
+ // Raw SPARQL rows (flat) — groupSPARQLResults will group them
771
+ const queryResults = [
772
+ { source: "literal:recipe1", predicate: "recipe://name", target: "Pasta", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" },
773
+ { source: "literal:recipe1", predicate: "recipe://rating", target: "5", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" },
774
+ { source: "literal:recipe1", predicate: "recipe://ingredient", target: "pasta", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" }
775
+ ];
776
+ mockPerspective.querySparql.mockResolvedValue(queryResults);
677
777
  const results = await Recipe.findAll(mockPerspective, {}, 'sparql');
678
- expect(mockPerspective.modelQuery).toHaveBeenCalledTimes(1);
778
+ expect(mockPerspective.querySparql).toHaveBeenCalledTimes(1);
679
779
  expect(mockPerspective.infer).not.toHaveBeenCalled();
680
780
  expect(results).toHaveLength(1);
681
781
  expect(results[0].name).toBe("Pasta");
682
782
  });
683
- it("should route through modelQuery when engine is 'prolog' in findAll() (prolog is now no-op)", async () => {
684
- mockPerspective.modelQuery.mockResolvedValue({
685
- instances: [
686
- { id: "literal:recipe1", name: "Pasta", rating: 5, ingredients: ["pasta"] }
687
- ],
688
- totalCount: 1
689
- });
783
+ it("should use Prolog when engine is prolog in findAll()", async () => {
784
+ const prologResults = [{
785
+ AllInstances: [
786
+ ["literal:recipe1", [["name", "Pasta"]], [["ingredients", ["pasta"]]], "2023-01-01T00:00:00Z", "did:key:alice"]
787
+ ],
788
+ TotalCount: 1
789
+ }];
790
+ mockPerspective.infer.mockResolvedValue(prologResults);
690
791
  const results = await Recipe.findAll(mockPerspective, {}, false);
691
- expect(mockPerspective.modelQuery).toHaveBeenCalledTimes(1);
692
- expect(mockPerspective.infer).not.toHaveBeenCalled();
792
+ expect(mockPerspective.infer).toHaveBeenCalledTimes(1);
793
+ expect(mockPerspective.querySparql).not.toHaveBeenCalled();
693
794
  expect(results).toHaveLength(1);
694
795
  });
695
796
  it("should use SPARQL when engine is 'sparql' in findAllAndCount()", async () => {
696
- mockPerspective.modelQuery.mockResolvedValue({
697
- instances: [
698
- { id: "literal:recipe1", name: "Pasta", rating: 5, ingredients: ["pasta"] }
699
- ],
700
- totalCount: 1
701
- });
702
- const { results, totalCount } = await Recipe.findAllAndCount(mockPerspective, {});
703
- expect(mockPerspective.modelQuery).toHaveBeenCalledTimes(1);
797
+ const queryResults = [
798
+ { source: "literal:recipe1", predicate: "recipe://name", target: "Pasta", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" },
799
+ { source: "literal:recipe1", predicate: "recipe://rating", target: "5", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" },
800
+ { source: "literal:recipe1", predicate: "recipe://ingredient", target: "pasta", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" }
801
+ ];
802
+ mockPerspective.querySparql.mockResolvedValue(queryResults);
803
+ const { results, totalCount } = await Recipe.findAllAndCount(mockPerspective, {}, 'sparql');
804
+ expect(mockPerspective.querySparql).toHaveBeenCalledTimes(1);
704
805
  expect(mockPerspective.infer).not.toHaveBeenCalled();
705
806
  expect(results).toHaveLength(1);
706
807
  expect(totalCount).toBe(1);
707
808
  });
708
809
  it("should use SPARQL when engine is 'sparql' in paginate()", async () => {
709
- mockPerspective.modelQuery.mockResolvedValue({
710
- instances: [
711
- { id: "literal:recipe1", name: "Pasta", rating: 5, ingredients: ["pasta"] }
712
- ],
713
- totalCount: 1
714
- });
715
- const page = await Recipe.paginate(mockPerspective, 10, 1, {});
716
- expect(mockPerspective.modelQuery).toHaveBeenCalledTimes(1);
810
+ const queryResults = [
811
+ { source: "literal:recipe1", predicate: "recipe://name", target: "Pasta", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" },
812
+ { source: "literal:recipe1", predicate: "recipe://rating", target: "5", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" },
813
+ { source: "literal:recipe1", predicate: "recipe://ingredient", target: "pasta", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" }
814
+ ];
815
+ mockPerspective.querySparql.mockResolvedValue(queryResults);
816
+ const page = await Recipe.paginate(mockPerspective, 10, 1, {}, 'sparql');
817
+ expect(mockPerspective.querySparql).toHaveBeenCalledTimes(1);
717
818
  expect(mockPerspective.infer).not.toHaveBeenCalled();
718
819
  expect(page.results).toHaveLength(1);
719
820
  expect(page.pageSize).toBe(10);
720
821
  expect(page.pageNumber).toBe(1);
721
- expect(page.totalCount).toBe(1);
722
822
  });
723
- it("should use SPARQL in count()", async () => {
724
- mockPerspective.modelQuery.mockResolvedValue({
725
- instances: [],
726
- totalCount: 5
727
- });
728
- const count = await Recipe.count(mockPerspective, {});
729
- expect(mockPerspective.modelQuery).toHaveBeenCalledTimes(1);
823
+ it("should use SPARQL when engine is 'sparql' in count()", async () => {
824
+ // Since count() uses result.length and GROUP BY returns one row per source,
825
+ // mock 5 recipe sources
826
+ const queryResults = [
827
+ ...Array.from({ length: 5 }, (_, i) => [
828
+ { source: `literal:recipe${i + 1}`, predicate: "recipe://name", target: `Recipe ${i + 1}`, author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" },
829
+ { source: `literal:recipe${i + 1}`, predicate: "recipe://rating", target: "5", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" }
830
+ ]).flat()
831
+ ];
832
+ mockPerspective.querySparql.mockResolvedValue(queryResults);
833
+ const count = await Recipe.count(mockPerspective, {}, 'sparql');
834
+ expect(mockPerspective.querySparql).toHaveBeenCalledTimes(1);
730
835
  expect(mockPerspective.infer).not.toHaveBeenCalled();
731
836
  expect(count).toBe(5);
732
837
  });
733
- it("should return count from modelQuery", async () => {
734
- mockPerspective.modelQuery.mockResolvedValue({
735
- instances: [],
736
- totalCount: 10
737
- });
738
- const count = await Recipe.count(mockPerspective, {});
739
- expect(mockPerspective.modelQuery).toHaveBeenCalledTimes(1);
838
+ it("should use Prolog when engine is prolog in count()", async () => {
839
+ const prologResults = [{ TotalCount: 10 }];
840
+ mockPerspective.infer.mockResolvedValue(prologResults);
841
+ const count = await Recipe.count(mockPerspective, {}, false);
842
+ expect(mockPerspective.infer).toHaveBeenCalledTimes(1);
740
843
  expect(mockPerspective.querySparql).not.toHaveBeenCalled();
741
844
  expect(count).toBe(10);
742
845
  });
743
846
  it("should use SPARQL when engine is 'sparql' in ModelQueryBuilder.get()", async () => {
744
- mockPerspective.modelQuery.mockResolvedValue({
745
- instances: [
746
- { id: "literal:recipe1", name: "Pasta", rating: 5, ingredients: ["pasta"] }
747
- ],
748
- totalCount: 1
749
- });
847
+ const queryResults = [
848
+ { source: "literal:recipe1", predicate: "recipe://name", target: "Pasta", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" },
849
+ { source: "literal:recipe1", predicate: "recipe://rating", target: "5", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" },
850
+ { source: "literal:recipe1", predicate: "recipe://ingredient", target: "pasta", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" }
851
+ ];
852
+ mockPerspective.querySparql.mockResolvedValue(queryResults);
750
853
  const results = await Recipe.query(mockPerspective)
751
854
  .where({ name: "Pasta" })
752
855
  .engine('sparql')
753
856
  .get();
754
- expect(mockPerspective.modelQuery).toHaveBeenCalledTimes(1);
857
+ expect(mockPerspective.querySparql).toHaveBeenCalledTimes(1);
755
858
  expect(mockPerspective.infer).not.toHaveBeenCalled();
756
859
  expect(results).toHaveLength(1);
757
860
  expect(results[0].name).toBe("Pasta");
758
861
  });
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"] }
763
- ],
764
- totalCount: 1
765
- });
862
+ it("should use Prolog when.engine('prolog') in ModelQueryBuilder.get()", async () => {
863
+ const prologResults = [{
864
+ AllInstances: [
865
+ ["literal:recipe1", [["name", "Pasta"]], [["ingredients", ["pasta"]]], "2023-01-01T00:00:00Z", "did:key:alice"]
866
+ ],
867
+ TotalCount: 1
868
+ }];
869
+ mockPerspective.infer.mockResolvedValue(prologResults);
766
870
  const results = await Recipe.query(mockPerspective)
767
871
  .where({ name: "Pasta" })
768
872
  .engine('prolog')
769
873
  .get();
770
- // engine('prolog') is now a no-op — everything goes through modelQuery
771
- expect(mockPerspective.modelQuery).toHaveBeenCalledTimes(1);
772
- expect(mockPerspective.infer).not.toHaveBeenCalled();
874
+ expect(mockPerspective.infer).toHaveBeenCalledTimes(1);
875
+ expect(mockPerspective.querySparql).not.toHaveBeenCalled();
773
876
  expect(results).toHaveLength(1);
774
877
  });
775
878
  it("should use SPARQL when engine is 'sparql' in ModelQueryBuilder.count()", async () => {
776
- mockPerspective.modelQuery.mockResolvedValue({
777
- instances: [],
778
- totalCount: 3
779
- });
879
+ // count() counts the number of rows returned by the query (one row per source)
880
+ const queryResults = [
881
+ ...Array.from({ length: 3 }, (_, i) => [
882
+ { source: `literal:recipe${i + 1}`, predicate: "recipe://name", target: `Recipe ${i + 1}`, author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" },
883
+ { source: `literal:recipe${i + 1}`, predicate: "recipe://rating", target: "5", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" }
884
+ ]).flat()
885
+ ];
886
+ mockPerspective.querySparql.mockResolvedValue(queryResults);
780
887
  const count = await Recipe.query(mockPerspective)
781
888
  .where({ rating: { gt: 4 } })
782
889
  .engine('sparql')
783
890
  .count();
784
- expect(mockPerspective.modelQuery).toHaveBeenCalledTimes(1);
891
+ expect(mockPerspective.querySparql).toHaveBeenCalledTimes(1);
785
892
  expect(mockPerspective.infer).not.toHaveBeenCalled();
786
893
  expect(count).toBe(3);
787
894
  });
788
895
  it("should use SPARQL when engine is 'sparql' in ModelQueryBuilder.paginate()", async () => {
789
- mockPerspective.modelQuery.mockResolvedValue({
790
- instances: [
791
- { id: "literal:recipe1", name: "Pasta", rating: 5, ingredients: ["pasta"] }
792
- ],
793
- totalCount: 1
794
- });
896
+ const queryResults = [
897
+ { source: "literal:recipe1", predicate: "recipe://name", target: "Pasta", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" },
898
+ { source: "literal:recipe1", predicate: "recipe://rating", target: "5", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" },
899
+ { source: "literal:recipe1", predicate: "recipe://ingredient", target: "pasta", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" }
900
+ ];
901
+ mockPerspective.querySparql.mockResolvedValue(queryResults);
795
902
  const page = await Recipe.query(mockPerspective)
796
903
  .where({ rating: { gt: 3 } })
797
904
  .engine('sparql')
798
905
  .paginate(10, 1);
799
- expect(mockPerspective.modelQuery).toHaveBeenCalledTimes(1);
906
+ expect(mockPerspective.querySparql).toHaveBeenCalledTimes(1);
800
907
  expect(mockPerspective.infer).not.toHaveBeenCalled();
801
908
  expect(page.results).toHaveLength(1);
802
909
  expect(page.pageSize).toBe(10);
@@ -831,7 +938,6 @@ describe("Ad4mModel.count() with advanced where conditions", () => {
831
938
  // Mock perspective
832
939
  const mockPerspective = {
833
940
  querySparql: jest.fn(),
834
- modelQuery: jest.fn(),
835
941
  infer: jest.fn(),
836
942
  uuid: 'test-perspective-uuid',
837
943
  stringOrTemplateObjectToSubjectClassName: jest.fn().mockResolvedValue('Recipe')
@@ -839,78 +945,128 @@ describe("Ad4mModel.count() with advanced where conditions", () => {
839
945
  beforeEach(() => {
840
946
  jest.clearAllMocks();
841
947
  });
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
- });
948
+ it("should apply JS-level filtering for gt operator on properties in SPARQL count()", async () => {
949
+ // Mock query results: 5 recipes with ratings 1, 2, 3, 4, 5
950
+ const queryResults = [
951
+ ...Array.from({ length: 5 }, (_, i) => [
952
+ { source: `literal:recipe${i + 1}`, predicate: "recipe://name", target: `Recipe ${i + 1}`, author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" },
953
+ { source: `literal:recipe${i + 1}`, predicate: "recipe://rating", target: `${i + 1}`, author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" }
954
+ ]).flat()
955
+ ];
956
+ mockPerspective.querySparql.mockResolvedValue(queryResults);
848
957
  // Count recipes with rating > 3 (should match 2 recipes: rating 4 and 5)
849
- const count = await Recipe.count(mockPerspective, { where: { rating: { gt: 3 } } });
958
+ const count = await Recipe.count(mockPerspective, { where: { rating: { gt: 3 } } }, 'sparql');
959
+ // Verify count matches the number of instances that would be returned by findAll
960
+ const findAllResults = await Recipe.findAll(mockPerspective, { where: { rating: { gt: 3 } } }, 'sparql');
850
961
  expect(count).toBe(2);
851
- expect(mockPerspective.modelQuery).toHaveBeenCalled();
852
- });
853
- it("should apply filtering for between operator on properties in SPARQL count()", async () => {
854
- mockPerspective.modelQuery.mockResolvedValue({
855
- instances: [],
856
- totalCount: 3
857
- });
962
+ expect(count).toBe(findAllResults.length);
963
+ });
964
+ it("should apply JS-level filtering for between operator on properties in SPARQL count()", async () => {
965
+ // Mock query results: 5 recipes with ratings 1, 2, 3, 4, 5
966
+ const queryResults = [
967
+ ...Array.from({ length: 5 }, (_, i) => [
968
+ { source: `literal:recipe${i + 1}`, predicate: "recipe://name", target: `Recipe ${i + 1}`, author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" },
969
+ { source: `literal:recipe${i + 1}`, predicate: "recipe://rating", target: `${i + 1}`, author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" }
970
+ ]).flat()
971
+ ];
972
+ mockPerspective.querySparql.mockResolvedValue(queryResults);
858
973
  // Count recipes with rating between 2 and 4 (should match 3 recipes: rating 2, 3, 4)
859
- const count = await Recipe.count(mockPerspective, { where: { rating: { between: [2, 4] } } });
974
+ const count = await Recipe.count(mockPerspective, { where: { rating: { between: [2, 4] } } }, 'sparql');
975
+ // Verify count matches the number of instances that would be returned by findAll
976
+ const findAllResults = await Recipe.findAll(mockPerspective, { where: { rating: { between: [2, 4] } } }, 'sparql');
860
977
  expect(count).toBe(3);
861
- expect(mockPerspective.modelQuery).toHaveBeenCalled();
862
- });
863
- it("should apply filtering for timestamp gt operator in SPARQL count()", async () => {
864
- mockPerspective.modelQuery.mockResolvedValue({
865
- instances: [],
866
- totalCount: 2
867
- });
978
+ expect(count).toBe(findAllResults.length);
979
+ });
980
+ it("should apply JS-level filtering for timestamp gt operator in SPARQL count()", async () => {
981
+ // Mock query results: 5 recipes with different timestamps
982
+ const queryResults = [
983
+ ...Array.from({ length: 5 }, (_, i) => [
984
+ { 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` },
985
+ { source: `literal:recipe${i + 1}`, predicate: "recipe://rating", target: "5", author: "did:key:alice", timestamp: `2023-01-0${i + 1}T00:00:00Z` }
986
+ ]).flat()
987
+ ];
988
+ mockPerspective.querySparql.mockResolvedValue(queryResults);
989
+ // Count recipes with timestamp > 2023-01-03 (should match 2 recipes: 2023-01-04 and 2023-01-05)
868
990
  const targetTimestamp = new Date("2023-01-03T00:00:00Z").getTime();
869
- const count = await Recipe.count(mockPerspective, { where: { timestamp: { gt: targetTimestamp } } });
991
+ const count = await Recipe.count(mockPerspective, { where: { timestamp: { gt: targetTimestamp } } }, 'sparql');
992
+ // Verify count matches the number of instances that would be returned by findAll
993
+ const findAllResults = await Recipe.findAll(mockPerspective, { where: { timestamp: { gt: targetTimestamp } } }, 'sparql');
870
994
  expect(count).toBe(2);
871
- expect(mockPerspective.modelQuery).toHaveBeenCalled();
872
- });
873
- it("should apply filtering for timestamp between operator in SPARQL count()", async () => {
874
- mockPerspective.modelQuery.mockResolvedValue({
875
- instances: [],
876
- totalCount: 3
877
- });
995
+ expect(count).toBe(findAllResults.length);
996
+ });
997
+ it("should apply JS-level filtering for timestamp between operator in SPARQL count()", async () => {
998
+ // Mock query results: 5 recipes with different timestamps
999
+ const queryResults = [
1000
+ ...Array.from({ length: 5 }, (_, i) => [
1001
+ { 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` },
1002
+ { source: `literal:recipe${i + 1}`, predicate: "recipe://rating", target: "5", author: "did:key:alice", timestamp: `2023-01-0${i + 1}T00:00:00Z` }
1003
+ ]).flat()
1004
+ ];
1005
+ mockPerspective.querySparql.mockResolvedValue(queryResults);
1006
+ // Count recipes with timestamp between 2023-01-02 and 2023-01-04
878
1007
  const startTimestamp = new Date("2023-01-02T00:00:00Z").getTime();
879
1008
  const endTimestamp = new Date("2023-01-04T00:00:00Z").getTime();
880
1009
  const count = await Recipe.count(mockPerspective, {
881
1010
  where: { timestamp: { between: [startTimestamp, endTimestamp] } }
882
- });
1011
+ }, 'sparql');
1012
+ // Verify count matches the number of instances that would be returned by findAll
1013
+ const findAllResults = await Recipe.findAll(mockPerspective, {
1014
+ where: { timestamp: { between: [startTimestamp, endTimestamp] } }
1015
+ }, 'sparql');
883
1016
  expect(count).toBe(3);
884
- expect(mockPerspective.modelQuery).toHaveBeenCalled();
885
- });
886
- it("should apply filtering for author filtering in SPARQL count()", async () => {
887
- mockPerspective.modelQuery.mockResolvedValue({
888
- instances: [],
889
- totalCount: 3
890
- });
1017
+ expect(count).toBe(findAllResults.length);
1018
+ });
1019
+ it("should apply JS-level filtering for author filtering in SPARQL count()", async () => {
1020
+ // Mock query results: 3 recipes by Alice and 2 by Bob
1021
+ const queryResults = [
1022
+ ...Array.from({ length: 3 }, (_, i) => [
1023
+ { source: `literal:recipe${i + 1}`, predicate: "recipe://name", target: `Recipe ${i + 1}`, author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" },
1024
+ { source: `literal:recipe${i + 1}`, predicate: "recipe://rating", target: "5", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" }
1025
+ ]).flat(),
1026
+ ...Array.from({ length: 2 }, (_, i) => [
1027
+ { source: `literal:recipe${i + 4}`, predicate: "recipe://name", target: `Recipe ${i + 4}`, author: "did:key:bob", timestamp: "2023-01-02T00:00:00Z" },
1028
+ { source: `literal:recipe${i + 4}`, predicate: "recipe://rating", target: "5", author: "did:key:bob", timestamp: "2023-01-02T00:00:00Z" }
1029
+ ]).flat()
1030
+ ];
1031
+ mockPerspective.querySparql.mockResolvedValue(queryResults);
891
1032
  // Count recipes by Alice (should match 3 recipes)
892
- const count = await Recipe.count(mockPerspective, { where: { author: "did:key:alice" } });
1033
+ const count = await Recipe.count(mockPerspective, { where: { author: "did:key:alice" } }, 'sparql');
1034
+ // Verify count matches the number of instances that would be returned by findAll
1035
+ const findAllResults = await Recipe.findAll(mockPerspective, { where: { author: "did:key:alice" } }, 'sparql');
893
1036
  expect(count).toBe(3);
894
- expect(mockPerspective.modelQuery).toHaveBeenCalled();
895
- });
896
- it("should apply filtering in ModelQueryBuilder.count() with gt operator", async () => {
897
- mockPerspective.modelQuery.mockResolvedValue({
898
- instances: [],
899
- totalCount: 2
900
- });
1037
+ expect(count).toBe(findAllResults.length);
1038
+ });
1039
+ it("should apply JS-level filtering in ModelQueryBuilder.count() with gt operator", async () => {
1040
+ // Mock query results: 5 recipes with ratings 1, 2, 3, 4, 5
1041
+ const queryResults = [
1042
+ ...Array.from({ length: 5 }, (_, i) => [
1043
+ { source: `literal:recipe${i + 1}`, predicate: "recipe://name", target: `Recipe ${i + 1}`, author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" },
1044
+ { source: `literal:recipe${i + 1}`, predicate: "recipe://rating", target: `${i + 1}`, author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" }
1045
+ ]).flat()
1046
+ ];
1047
+ mockPerspective.querySparql.mockResolvedValue(queryResults);
901
1048
  // Count recipes with rating > 3 using ModelQueryBuilder
902
1049
  const count = await Recipe.query(mockPerspective)
903
1050
  .where({ rating: { gt: 3 } })
904
1051
  .engine('sparql')
905
1052
  .count();
1053
+ // Verify count matches the number of instances that would be returned by get()
1054
+ const getResults = await Recipe.query(mockPerspective)
1055
+ .where({ rating: { gt: 3 } })
1056
+ .engine('sparql')
1057
+ .get();
906
1058
  expect(count).toBe(2);
907
- expect(mockPerspective.modelQuery).toHaveBeenCalled();
908
- });
909
- it("should apply filtering in ModelQueryBuilder.count() with timestamp between", async () => {
910
- mockPerspective.modelQuery.mockResolvedValue({
911
- instances: [],
912
- totalCount: 3
913
- });
1059
+ expect(count).toBe(getResults.length);
1060
+ });
1061
+ it("should apply JS-level filtering in ModelQueryBuilder.count() with timestamp between", async () => {
1062
+ // Mock query results: 5 recipes with different timestamps
1063
+ const queryResults = [
1064
+ ...Array.from({ length: 5 }, (_, i) => [
1065
+ { 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` },
1066
+ { source: `literal:recipe${i + 1}`, predicate: "recipe://rating", target: "5", author: "did:key:alice", timestamp: `2023-01-0${i + 1}T00:00:00Z` }
1067
+ ]).flat()
1068
+ ];
1069
+ mockPerspective.querySparql.mockResolvedValue(queryResults);
914
1070
  const startTimestamp = new Date("2023-01-02T00:00:00Z").getTime();
915
1071
  const endTimestamp = new Date("2023-01-04T00:00:00Z").getTime();
916
1072
  // Count using ModelQueryBuilder
@@ -918,8 +1074,96 @@ describe("Ad4mModel.count() with advanced where conditions", () => {
918
1074
  .where({ timestamp: { between: [startTimestamp, endTimestamp] } })
919
1075
  .engine('sparql')
920
1076
  .count();
1077
+ // Verify count matches the number of instances that would be returned by get()
1078
+ const getResults = await Recipe.query(mockPerspective)
1079
+ .where({ timestamp: { between: [startTimestamp, endTimestamp] } })
1080
+ .engine('sparql')
1081
+ .get();
921
1082
  expect(count).toBe(3);
922
- expect(mockPerspective.modelQuery).toHaveBeenCalled();
1083
+ expect(count).toBe(getResults.length);
1084
+ });
1085
+ it("should handle count() with Prolog for gt operator (legacy)", async () => {
1086
+ const prologResults = [{ TotalCount: 2 }];
1087
+ mockPerspective.infer.mockResolvedValue(prologResults);
1088
+ const count = await Recipe.count(mockPerspective, { where: { rating: { gt: 3 } } }, false);
1089
+ expect(mockPerspective.infer).toHaveBeenCalledTimes(1);
1090
+ expect(mockPerspective.querySparql).not.toHaveBeenCalled();
1091
+ expect(count).toBe(2);
1092
+ });
1093
+ it("should handle count() with Prolog for timestamp between (legacy)", async () => {
1094
+ const prologResults = [{ TotalCount: 3 }];
1095
+ mockPerspective.infer.mockResolvedValue(prologResults);
1096
+ const startTimestamp = new Date("2023-01-02T00:00:00Z").getTime();
1097
+ const endTimestamp = new Date("2023-01-04T00:00:00Z").getTime();
1098
+ const count = await Recipe.count(mockPerspective, { where: { timestamp: { between: [startTimestamp, endTimestamp] } } }, false);
1099
+ expect(mockPerspective.infer).toHaveBeenCalledTimes(1);
1100
+ expect(mockPerspective.querySparql).not.toHaveBeenCalled();
1101
+ expect(count).toBe(3);
1102
+ });
1103
+ });
1104
+ // ──────────────────────────────────────────────────────────
1105
+ // Batch SPARQL query builder tests
1106
+ // ──────────────────────────────────────────────────────────
1107
+ import { buildBatchSPARQLQuery } from "./query-sparql-batch";
1108
+ describe("buildBatchSPARQLQuery", () => {
1109
+ let Author = class Author extends Ad4mModel {
1110
+ };
1111
+ __decorate([
1112
+ Property({ through: "author://name", required: true }),
1113
+ __metadata("design:type", String)
1114
+ ], Author.prototype, "name", void 0);
1115
+ Author = __decorate([
1116
+ Model({ name: "Author" })
1117
+ ], Author);
1118
+ let Book = class Book extends Ad4mModel {
1119
+ };
1120
+ __decorate([
1121
+ Property({ through: "book://title", required: true }),
1122
+ __metadata("design:type", String)
1123
+ ], Book.prototype, "title", void 0);
1124
+ __decorate([
1125
+ HasMany(() => Author, { through: "book://author" }),
1126
+ __metadata("design:type", Array)
1127
+ ], Book.prototype, "authors", void 0);
1128
+ Book = __decorate([
1129
+ Model({ name: "Book" })
1130
+ ], Book);
1131
+ it("should generate UNION branches for depth 0 and depth 1 includes", () => {
1132
+ const metadata = Book.getModelMetadata();
1133
+ const query = { include: { authors: true } };
1134
+ const sparql = buildBatchSPARQLQuery(metadata, query, Book);
1135
+ expect(sparql).toContain("?depth");
1136
+ expect(sparql).toContain("?parentBase");
1137
+ expect(sparql).toContain("?relationName");
1138
+ expect(sparql).toContain("UNION");
1139
+ expect(sparql).toContain("BIND(\"0\" AS ?depth)");
1140
+ expect(sparql).toContain("BIND(\"1\" AS ?depth)");
1141
+ expect(sparql).toContain("book://author");
1142
+ });
1143
+ it("should include parent filter when query.parent is specified", () => {
1144
+ const metadata = Book.getModelMetadata();
1145
+ const query = {
1146
+ parent: { id: "flux://library1", predicate: "library://books" },
1147
+ include: { authors: true },
1148
+ };
1149
+ const sparql = buildBatchSPARQLQuery(metadata, query, Book);
1150
+ expect(sparql).toContain("flux://library1");
1151
+ expect(sparql).toContain("library://books");
1152
+ });
1153
+ it("should include where filter for simple equality", () => {
1154
+ const metadata = Book.getModelMetadata();
1155
+ const query = {
1156
+ where: { title: "My Book" },
1157
+ include: { authors: true },
1158
+ };
1159
+ const sparql = buildBatchSPARQLQuery(metadata, query, Book);
1160
+ // For literal-stored properties, SPARQL only has a JOIN (no FILTER value) — filtering in JS
1161
+ expect(sparql).toContain("book://title");
1162
+ expect(sparql).toContain("root_wTarget_eq_title");
1163
+ });
1164
+ it("should throw when include is empty", () => {
1165
+ const metadata = Book.getModelMetadata();
1166
+ expect(() => buildBatchSPARQLQuery(metadata, {}, Book)).toThrow("requires query.include");
923
1167
  });
924
1168
  });
925
1169
  describe("SPARQL comparison filters", () => {
@@ -958,7 +1202,7 @@ describe("SPARQL comparison filters", () => {
958
1202
  // ──────────────────────────────────────────────────────────
959
1203
  // SPARQL Direct Triple Pattern & IRI Tests
960
1204
  // ──────────────────────────────────────────────────────────
961
- import { buildSPARQLQuery, formatSPARQLValue } from "./query-sparql";
1205
+ import { buildSPARQLQuery, groupSPARQLResults, formatSPARQLValue, buildSPARQLGetDataQuery } from "./query-sparql";
962
1206
  describe("SPARQL direct triple pattern generation", () => {
963
1207
  let Channel = class Channel extends Ad4mModel {
964
1208
  constructor() {
@@ -1006,20 +1250,68 @@ describe("SPARQL direct triple pattern generation", () => {
1006
1250
  expect(query).toContain("<flux://name>");
1007
1251
  expect(query).toMatch(/\?source\s+<flux:\/\/name>\s+\?cfTarget_name/);
1008
1252
  });
1009
- it("uses RDF 1.2 reifier pattern for author/timestamp", async () => {
1253
+ it("uses GRAPH ?linkGraph pattern for author/timestamp", async () => {
1254
+ const query = await Channel.queryToSPARQL(mockPersp, {});
1255
+ expect(query).toContain("GRAPH ?linkGraph { ?source ?predicate ?target . }");
1256
+ expect(query).toContain("?linkGraph <ad4m://ontology/author> ?author");
1257
+ expect(query).toContain("?linkGraph <ad4m://ontology/timestamp> ?timestamp");
1258
+ });
1259
+ it("does NOT contain RDF-star BIND(<< >> AS ?ann) pattern", async () => {
1010
1260
  const query = await Channel.queryToSPARQL(mockPersp, {});
1011
- expect(query).toContain("<http://www.w3.org/1999/02/22-rdf-syntax-ns#reifies>");
1012
- expect(query).toContain("?source ?predicate ?target .");
1013
- expect(query).toContain("?_reifier <http://www.w3.org/1999/02/22-rdf-syntax-ns#reifies> <<( ?source ?predicate ?target )>>");
1014
- expect(query).toContain("?_reifier <ad4m://ontology/author> ?author");
1015
- expect(query).toContain("?_reifier <ad4m://ontology/timestamp> ?timestamp");
1016
- expect(query).not.toContain("GRAPH");
1261
+ expect(query).not.toContain("BIND(<<");
1262
+ expect(query).not.toContain("?ann ");
1017
1263
  });
1018
1264
  it("uses FILTER(isIRI(?source)) to exclude non-IRI subjects", async () => {
1019
1265
  const query = await Channel.queryToSPARQL(mockPersp, {});
1020
1266
  expect(query).toContain("FILTER(isIRI(?source)");
1021
1267
  });
1022
1268
  });
1269
+ describe("SPARQL IRI formatting", () => {
1270
+ it("wraps AD4M URIs in angle brackets", () => {
1271
+ const query = buildSPARQLGetDataQuery("ad4m://test123");
1272
+ expect(query).toContain("<ad4m://test123>");
1273
+ });
1274
+ it("wraps literal: URIs in angle brackets", () => {
1275
+ const query = buildSPARQLGetDataQuery("literal:string:foo");
1276
+ expect(query).toContain("<literal:string:foo>");
1277
+ });
1278
+ it("wraps flux:// URIs in angle brackets", () => {
1279
+ const query = buildSPARQLGetDataQuery("flux://has_channel");
1280
+ expect(query).toContain("<flux://has_channel>");
1281
+ });
1282
+ it("wraps did:key URIs in angle brackets", () => {
1283
+ const query = buildSPARQLGetDataQuery("did:key:z6MkhaXg");
1284
+ expect(query).toContain("<did:key:z6MkhaXg>");
1285
+ });
1286
+ });
1287
+ describe("groupSPARQLResults", () => {
1288
+ it("groups flat rows by source URI", () => {
1289
+ const rows = [
1290
+ { source: "ad4m://a", predicate: "p1", target: "t1", author: "auth1", timestamp: "ts1" },
1291
+ { source: "ad4m://a", predicate: "p2", target: "t2", author: "auth1", timestamp: "ts1" },
1292
+ { source: "ad4m://b", predicate: "p1", target: "t3", author: "auth2", timestamp: "ts2" },
1293
+ ];
1294
+ const grouped = groupSPARQLResults(rows);
1295
+ expect(grouped).toHaveLength(2);
1296
+ const aGroup = grouped.find(g => g.source_uri === "ad4m://a");
1297
+ expect(aGroup).toBeDefined();
1298
+ expect(aGroup.links).toHaveLength(2);
1299
+ const bGroup = grouped.find(g => g.source_uri === "ad4m://b");
1300
+ expect(bGroup).toBeDefined();
1301
+ expect(bGroup.links).toHaveLength(1);
1302
+ });
1303
+ it("returns empty array for empty input", () => {
1304
+ expect(groupSPARQLResults([])).toEqual([]);
1305
+ });
1306
+ it("preserves metadata in grouped links", () => {
1307
+ const rows = [
1308
+ { source: "x", predicate: "p", target: "t", author: "did:key:z6Mk", timestamp: "2024-01-01T00:00:00Z" },
1309
+ ];
1310
+ const grouped = groupSPARQLResults(rows);
1311
+ expect(grouped[0].links[0].author).toBe("did:key:z6Mk");
1312
+ expect(grouped[0].links[0].timestamp).toBe("2024-01-01T00:00:00Z");
1313
+ });
1314
+ });
1023
1315
  describe("formatSPARQLValue", () => {
1024
1316
  it("wraps strings in double quotes", () => {
1025
1317
  expect(formatSPARQLValue("hello")).toBe('"hello"');
@@ -1034,7 +1326,7 @@ describe("formatSPARQLValue", () => {
1034
1326
  // ──────────────────────────────────────────────────────────
1035
1327
  // Comprehensive SPARQL migration unit tests
1036
1328
  // ──────────────────────────────────────────────────────────
1037
- import { matchesCondition } from "./hydration";
1329
+ import { matchesCondition, hydrateFromLinks } from "./hydration";
1038
1330
  import { Literal } from "../Literal";
1039
1331
  // Helper: create literal URLs using JSON encoding (which handles all types including booleans)
1040
1332
  function literalUrl(value) {
@@ -1132,6 +1424,207 @@ describe("matchesCondition()", () => {
1132
1424
  expect(matchesCondition(undefined, { not: "hello" })).toBe(true);
1133
1425
  });
1134
1426
  });
1427
+ describe("hydrateFromLinks()", () => {
1428
+ // Create a mock perspective that won't be called for literal properties
1429
+ const mockPerspective = {};
1430
+ let HydrationTest = class HydrationTest extends Ad4mModel {
1431
+ constructor() {
1432
+ super(...arguments);
1433
+ this.name = "";
1434
+ this.score = 0;
1435
+ this.active = false;
1436
+ }
1437
+ };
1438
+ __decorate([
1439
+ Property({ through: "test://name", resolveLanguage: "literal" }),
1440
+ __metadata("design:type", String)
1441
+ ], HydrationTest.prototype, "name", void 0);
1442
+ __decorate([
1443
+ Property({ through: "test://score", resolveLanguage: "literal" }),
1444
+ __metadata("design:type", Number)
1445
+ ], HydrationTest.prototype, "score", void 0);
1446
+ __decorate([
1447
+ Property({ through: "test://active", resolveLanguage: "literal" }),
1448
+ __metadata("design:type", Boolean)
1449
+ ], HydrationTest.prototype, "active", void 0);
1450
+ HydrationTest = __decorate([
1451
+ Model({ name: "HydrationTest" })
1452
+ ], HydrationTest);
1453
+ const metadata = HydrationTest.getModelMetadata();
1454
+ it("hydrates all properties when requestedProperties is undefined", async () => {
1455
+ const instance = new HydrationTest(mockPerspective);
1456
+ const links = [
1457
+ { predicate: "test://name", target: literalUrl("Alice"), author: "did:test", timestamp: "1000" },
1458
+ { predicate: "test://score", target: literalUrl(42), author: "did:test", timestamp: "1000" },
1459
+ { predicate: "test://active", target: literalUrl(true), author: "did:test", timestamp: "1000" },
1460
+ ];
1461
+ await hydrateFromLinks(instance, links, metadata, mockPerspective, undefined);
1462
+ expect(instance.name).toBe("Alice");
1463
+ expect(instance.score).toBe(42);
1464
+ expect(instance.active).toBe(true);
1465
+ });
1466
+ it("hydrates only requested properties when requestedProperties is provided", async () => {
1467
+ const instance = new HydrationTest(mockPerspective);
1468
+ const links = [
1469
+ { predicate: "test://name", target: literalUrl("Alice"), author: "did:test", timestamp: "1000" },
1470
+ { predicate: "test://score", target: literalUrl(42), author: "did:test", timestamp: "1000" },
1471
+ { predicate: "test://active", target: literalUrl(true), author: "did:test", timestamp: "1000" },
1472
+ ];
1473
+ await hydrateFromLinks(instance, links, metadata, mockPerspective, ["name"]);
1474
+ expect(instance.name).toBe("Alice");
1475
+ // score and active should remain at defaults since not requested
1476
+ expect(instance.score).toBe(0);
1477
+ expect(instance.active).toBe(false);
1478
+ });
1479
+ it("hydrates where-clause + projection properties when both are in requestedProperties", async () => {
1480
+ const instance = new HydrationTest(mockPerspective);
1481
+ const links = [
1482
+ { predicate: "test://name", target: literalUrl("Recipe 2"), author: "did:test", timestamp: "1000" },
1483
+ { predicate: "test://active", target: literalUrl(true), author: "did:test", timestamp: "1000" },
1484
+ ];
1485
+ // Simulate merged hydration props: projection ["active"] + where clause props ["name"]
1486
+ await hydrateFromLinks(instance, links, metadata, mockPerspective, ["active", "name"]);
1487
+ expect(instance.name).toBe("Recipe 2");
1488
+ expect(instance.active).toBe(true);
1489
+ });
1490
+ it("sets author and timestamps from links", async () => {
1491
+ const instance = new HydrationTest(mockPerspective);
1492
+ const links = [
1493
+ { predicate: "test://name", target: literalUrl("Bob"), author: "did:author1", timestamp: "1000" },
1494
+ { predicate: "test://score", target: literalUrl(10), author: "did:author2", timestamp: "2000" },
1495
+ ];
1496
+ await hydrateFromLinks(instance, links, metadata, mockPerspective);
1497
+ expect(instance.author).toBe("did:author1");
1498
+ expect(instance.createdAt).toBe(1000);
1499
+ expect(instance.updatedAt).toBe(2000);
1500
+ });
1501
+ it("handles empty links array", async () => {
1502
+ const instance = new HydrationTest(mockPerspective);
1503
+ await hydrateFromLinks(instance, [], metadata, mockPerspective);
1504
+ expect(instance.name).toBe("");
1505
+ expect(instance.score).toBe(0);
1506
+ });
1507
+ });
1508
+ describe("instancesFromQueryResult — where + properties interaction", () => {
1509
+ const mockPerspective = {
1510
+ get: jest.fn().mockResolvedValue([]),
1511
+ querySparql: jest.fn().mockResolvedValue([]),
1512
+ getExpression: jest.fn().mockResolvedValue(null),
1513
+ };
1514
+ let Recipe = class Recipe extends Ad4mModel {
1515
+ constructor() {
1516
+ super(...arguments);
1517
+ this.name = "";
1518
+ this.booleanTest = false;
1519
+ this.score = 0;
1520
+ }
1521
+ };
1522
+ __decorate([
1523
+ Property({ through: "recipe://name", resolveLanguage: "literal", required: true }),
1524
+ __metadata("design:type", String)
1525
+ ], Recipe.prototype, "name", void 0);
1526
+ __decorate([
1527
+ Property({ through: "recipe://booleanTest", resolveLanguage: "literal" }),
1528
+ __metadata("design:type", Boolean)
1529
+ ], Recipe.prototype, "booleanTest", void 0);
1530
+ __decorate([
1531
+ Property({ through: "recipe://score", resolveLanguage: "literal" }),
1532
+ __metadata("design:type", Number)
1533
+ ], Recipe.prototype, "score", void 0);
1534
+ Recipe = __decorate([
1535
+ Model({ name: "Recipe" })
1536
+ ], Recipe);
1537
+ it("should filter by where clause property even when not in properties projection", async () => {
1538
+ // Simulate SPARQL result with two recipes
1539
+ const grouped = [
1540
+ {
1541
+ source_uri: "expr:recipe1",
1542
+ links: [
1543
+ { predicate: "recipe://name", target: literalUrl("Recipe 1"), author: "did:test", timestamp: "1000" },
1544
+ { predicate: "recipe://booleanTest", target: literalUrl(true), author: "did:test", timestamp: "1000" },
1545
+ ],
1546
+ },
1547
+ {
1548
+ source_uri: "expr:recipe2",
1549
+ links: [
1550
+ { predicate: "recipe://name", target: literalUrl("Recipe 2"), author: "did:test", timestamp: "1000" },
1551
+ { predicate: "recipe://booleanTest", target: literalUrl(false), author: "did:test", timestamp: "1000" },
1552
+ ],
1553
+ },
1554
+ ];
1555
+ const query = { where: { name: "Recipe 2" }, properties: ["booleanTest"] };
1556
+ const { results } = await Recipe.instancesFromQueryResult(mockPerspective, query, grouped);
1557
+ expect(results.length).toBe(1);
1558
+ expect(results[0].booleanTest).toBe(false);
1559
+ // name should be deleted after filtering since it wasn't in properties projection
1560
+ expect(results[0].name).toBeUndefined();
1561
+ });
1562
+ it("should delete unrequested properties AFTER where-filtering", async () => {
1563
+ const grouped = [
1564
+ {
1565
+ source_uri: "expr:recipe1",
1566
+ links: [
1567
+ { predicate: "recipe://name", target: literalUrl("Recipe 1"), author: "did:test", timestamp: "1000" },
1568
+ { predicate: "recipe://score", target: literalUrl(99), author: "did:test", timestamp: "1000" },
1569
+ ],
1570
+ },
1571
+ ];
1572
+ const query = { where: { name: "Recipe 1" }, properties: ["score"] };
1573
+ const { results } = await Recipe.instancesFromQueryResult(mockPerspective, query, grouped);
1574
+ expect(results.length).toBe(1);
1575
+ expect(results[0].score).toBe(99);
1576
+ // name was used for filtering but should be deleted from final result
1577
+ expect(results[0].name).toBeUndefined();
1578
+ });
1579
+ it("should return all properties when no projection is specified", async () => {
1580
+ const grouped = [
1581
+ {
1582
+ source_uri: "expr:recipe1",
1583
+ links: [
1584
+ { predicate: "recipe://name", target: literalUrl("Test"), author: "did:test", timestamp: "1000" },
1585
+ { predicate: "recipe://booleanTest", target: literalUrl(true), author: "did:test", timestamp: "1000" },
1586
+ { predicate: "recipe://score", target: literalUrl(50), author: "did:test", timestamp: "1000" },
1587
+ ],
1588
+ },
1589
+ ];
1590
+ const query = { where: { name: "Test" } };
1591
+ const { results } = await Recipe.instancesFromQueryResult(mockPerspective, query, grouped);
1592
+ expect(results.length).toBe(1);
1593
+ expect(results[0].name).toBe("Test");
1594
+ expect(results[0].booleanTest).toBe(true);
1595
+ expect(results[0].score).toBe(50);
1596
+ });
1597
+ });
1598
+ describe("groupSPARQLResults()", () => {
1599
+ it("groups rows by source", () => {
1600
+ const rows = [
1601
+ { source: "a", predicate: "p1", target: "t1", author: "auth", timestamp: "ts1" },
1602
+ { source: "a", predicate: "p2", target: "t2", author: "auth", timestamp: "ts2" },
1603
+ { source: "b", predicate: "p1", target: "t3", author: "auth", timestamp: "ts3" },
1604
+ ];
1605
+ const grouped = groupSPARQLResults(rows);
1606
+ expect(grouped.length).toBe(2);
1607
+ const groupA = grouped.find(g => g.source_uri === "a");
1608
+ const groupB = grouped.find(g => g.source_uri === "b");
1609
+ expect(groupA.links.length).toBe(2);
1610
+ expect(groupB.links.length).toBe(1);
1611
+ });
1612
+ it("handles empty input", () => {
1613
+ expect(groupSPARQLResults([])).toEqual([]);
1614
+ });
1615
+ it("preserves link metadata", () => {
1616
+ const rows = [
1617
+ { source: "x", predicate: "pred", target: "tgt", author: "did:auth", timestamp: "2024-01-01" },
1618
+ ];
1619
+ const grouped = groupSPARQLResults(rows);
1620
+ expect(grouped[0].links[0]).toEqual({
1621
+ predicate: "pred",
1622
+ target: "tgt",
1623
+ author: "did:auth",
1624
+ timestamp: "2024-01-01",
1625
+ });
1626
+ });
1627
+ });
1135
1628
  describe("buildSPARQLQuery edge cases", () => {
1136
1629
  let FlagModel = class FlagModel extends Ad4mModel {
1137
1630
  constructor() {
@@ -1197,6 +1690,85 @@ describe("buildSPARQLQuery edge cases", () => {
1197
1690
  expect(sparql).toContain("expr:123");
1198
1691
  });
1199
1692
  });
1693
+ describe("sparse fieldset property deletion timing", () => {
1694
+ const mockPerspective = {
1695
+ get: jest.fn().mockResolvedValue([]),
1696
+ querySparql: jest.fn().mockResolvedValue([]),
1697
+ getExpression: jest.fn().mockResolvedValue(null),
1698
+ };
1699
+ let TimingTest = class TimingTest extends Ad4mModel {
1700
+ constructor() {
1701
+ super(...arguments);
1702
+ this.a = "";
1703
+ this.b = "";
1704
+ this.c = "";
1705
+ }
1706
+ };
1707
+ __decorate([
1708
+ Property({ through: "timing://a", resolveLanguage: "literal" }),
1709
+ __metadata("design:type", String)
1710
+ ], TimingTest.prototype, "a", void 0);
1711
+ __decorate([
1712
+ Property({ through: "timing://b", resolveLanguage: "literal" }),
1713
+ __metadata("design:type", String)
1714
+ ], TimingTest.prototype, "b", void 0);
1715
+ __decorate([
1716
+ Property({ through: "timing://c", resolveLanguage: "literal" }),
1717
+ __metadata("design:type", String)
1718
+ ], TimingTest.prototype, "c", void 0);
1719
+ TimingTest = __decorate([
1720
+ Model({ name: "TimingTest" })
1721
+ ], TimingTest);
1722
+ it("where-clause properties are available during filtering but deleted after", async () => {
1723
+ const grouped = [
1724
+ {
1725
+ source_uri: "expr:1",
1726
+ links: [
1727
+ { predicate: "timing://a", target: literalUrl("match"), author: "did:test", timestamp: "1000" },
1728
+ { predicate: "timing://b", target: literalUrl("keep"), author: "did:test", timestamp: "1000" },
1729
+ { predicate: "timing://c", target: literalUrl("ignore"), author: "did:test", timestamp: "1000" },
1730
+ ],
1731
+ },
1732
+ {
1733
+ source_uri: "expr:2",
1734
+ links: [
1735
+ { predicate: "timing://a", target: literalUrl("no-match"), author: "did:test", timestamp: "1000" },
1736
+ { predicate: "timing://b", target: literalUrl("skip"), author: "did:test", timestamp: "1000" },
1737
+ { predicate: "timing://c", target: literalUrl("skip"), author: "did:test", timestamp: "1000" },
1738
+ ],
1739
+ },
1740
+ ];
1741
+ // properties projection asks for "b" only, where clause filters on "a"
1742
+ const query = { where: { a: "match" }, properties: ["b"] };
1743
+ const { results } = await TimingTest.instancesFromQueryResult(mockPerspective, query, grouped);
1744
+ // Only the matching instance should survive
1745
+ expect(results.length).toBe(1);
1746
+ // "b" was requested — should be present
1747
+ expect(results[0].b).toBe("keep");
1748
+ // "a" was used for filtering but not in projection — should be deleted
1749
+ expect(results[0].a).toBeUndefined();
1750
+ // "c" was not requested — should be deleted
1751
+ expect(results[0].c).toBeUndefined();
1752
+ });
1753
+ it("properties not in projection are undefined after instancesFromQueryResult", async () => {
1754
+ const grouped = [
1755
+ {
1756
+ source_uri: "expr:1",
1757
+ links: [
1758
+ { predicate: "timing://a", target: literalUrl("val-a"), author: "did:test", timestamp: "1000" },
1759
+ { predicate: "timing://b", target: literalUrl("val-b"), author: "did:test", timestamp: "1000" },
1760
+ { predicate: "timing://c", target: literalUrl("val-c"), author: "did:test", timestamp: "1000" },
1761
+ ],
1762
+ },
1763
+ ];
1764
+ const query = { properties: ["a"] };
1765
+ const { results } = await TimingTest.instancesFromQueryResult(mockPerspective, query, grouped);
1766
+ expect(results.length).toBe(1);
1767
+ expect(results[0].a).toBe("val-a");
1768
+ expect(results[0].b).toBeUndefined();
1769
+ expect(results[0].c).toBeUndefined();
1770
+ });
1771
+ });
1200
1772
  // ── Batch hydration for reverse relations (3.4) ─────────────────────────────
1201
1773
  describe("Batch hydration for reverse relations", () => {
1202
1774
  it("batch hydration should correctly group targets by parent instance ID", () => {
@@ -1518,30 +2090,17 @@ describe("Native SPARQL getter evaluation", () => {
1518
2090
  // ── Subscribe callback timing ──────────────────────────────────────────
1519
2091
  describe("ModelQueryBuilder subscribe callback timing", () => {
1520
2092
  it("subscribe should not invoke callback synchronously before Promise resolves", async () => {
1521
- // This test verifies that subscribe() uses the Rust model subscription endpoint
1522
- // and properly handles the subscription lifecycle.
1523
- const mockSubscriptionId = "test-sub-123";
1524
- let updateCallback = null;
1525
- const mockClient = {
1526
- modelSubscribe: jest.fn().mockResolvedValue({
1527
- subscriptionId: mockSubscriptionId,
1528
- result: { instances: [], totalCount: 0 },
1529
- }),
1530
- subscribeToQueryUpdates: jest.fn().mockImplementation((_id, cb) => {
1531
- updateCallback = cb;
1532
- return () => { }; // unsubscribe function
1533
- }),
1534
- keepAliveQuery: jest.fn().mockResolvedValue(true),
1535
- disposeQuerySubscription: jest.fn().mockResolvedValue(true),
1536
- };
2093
+ // This test verifies that the initial callback from subscribe() is deferred
2094
+ // via queueMicrotask, preventing Preact/React hook lifecycle violations
2095
+ // when subscribe() is called from useEffect.
1537
2096
  const mockPerspective = {
1538
- uuid: "test-uuid",
1539
- client: mockClient,
1540
- modelSubscribe: jest.fn().mockImplementation(async (className, queryJson, shapeJson) => {
1541
- return mockClient.modelSubscribe("test-uuid", className, queryJson, shapeJson);
1542
- }),
1543
2097
  getLinks: jest.fn().mockResolvedValue([]),
1544
- modelQuery: jest.fn().mockResolvedValue({ instances: [], totalCount: 0 }),
2098
+ subscribeQuery: jest.fn().mockResolvedValue({
2099
+ result: '[]',
2100
+ onResult: jest.fn(),
2101
+ dispose: jest.fn(),
2102
+ }),
2103
+ querySparql: jest.fn().mockResolvedValue('[]'),
1545
2104
  };
1546
2105
  const { Ad4mModel, Model, Property, Flag } = require("./index");
1547
2106
  let TimingTest = class TimingTest extends Ad4mModel {
@@ -1573,192 +2132,11 @@ describe("ModelQueryBuilder subscribe callback timing", () => {
1573
2132
  // At this point the Promise hasn't resolved yet
1574
2133
  // The callback should NOT have fired synchronously
1575
2134
  expect(callbackInvokedBeforeResolve).toBe(false);
1576
- const initialResults = await promise;
2135
+ await promise;
1577
2136
  promiseResolved = true;
1578
- expect(initialResults).toEqual([]);
1579
- expect(mockPerspective.modelSubscribe).toHaveBeenCalled();
1580
- });
1581
- });
1582
- describe("ModelQueryBuilder paginateSubscribe", () => {
1583
- it("paginateSubscribe should use a single query with count: true", async () => {
1584
- const mockSubscriptionId = "paginate-sub-123";
1585
- const mockClient = {
1586
- modelSubscribe: jest.fn().mockResolvedValue({
1587
- subscriptionId: mockSubscriptionId,
1588
- result: { instances: [], totalCount: 0 },
1589
- }),
1590
- subscribeToQueryUpdates: jest.fn().mockImplementation((_id, _cb) => {
1591
- return () => { };
1592
- }),
1593
- keepAliveQuery: jest.fn().mockResolvedValue(true),
1594
- disposeQuerySubscription: jest.fn().mockResolvedValue(true),
1595
- };
1596
- const mockPerspective = {
1597
- uuid: "test-uuid",
1598
- client: mockClient,
1599
- modelSubscribe: jest.fn().mockImplementation(async (className, queryJson, shapeJson) => {
1600
- return mockClient.modelSubscribe("test-uuid", className, queryJson, shapeJson);
1601
- }),
1602
- modelQuery: jest.fn().mockResolvedValue({ instances: [{ id: "item1", type: "test://paginate" }], totalCount: 42 }),
1603
- };
1604
- const { Ad4mModel, Model, Flag, Property } = require("./index");
1605
- let PaginateTest = class PaginateTest extends Ad4mModel {
1606
- constructor() {
1607
- super(...arguments);
1608
- this.type = "test://paginate";
1609
- this.name = "";
1610
- }
1611
- };
1612
- __decorate([
1613
- Flag({ through: "test://type", value: "test://paginate" }),
1614
- __metadata("design:type", String)
1615
- ], PaginateTest.prototype, "type", void 0);
1616
- __decorate([
1617
- Property({ through: "test://name" }),
1618
- __metadata("design:type", String)
1619
- ], PaginateTest.prototype, "name", void 0);
1620
- PaginateTest = __decorate([
1621
- Model({ name: "PaginateTest" })
1622
- ], PaginateTest);
1623
- const builder = PaginateTest.query(mockPerspective);
1624
- const result = await builder.paginateSubscribe(10, 1, () => { });
1625
- // Should return paginated result structure
1626
- expect(result).toHaveProperty("results");
1627
- expect(result).toHaveProperty("totalCount");
1628
- expect(result).toHaveProperty("pageSize", 10);
1629
- expect(result).toHaveProperty("pageNumber", 1);
1630
- // modelQuery should be called exactly once (not twice — no separate count query)
1631
- expect(mockPerspective.modelQuery).toHaveBeenCalledTimes(1);
1632
- // The query should have count: true
1633
- const callArgs = mockPerspective.modelQuery.mock.calls[0];
1634
- const queryJson = JSON.parse(callArgs[1]);
1635
- expect(queryJson.count).toBe(true);
1636
- expect(queryJson.limit).toBe(10);
1637
- expect(queryJson.offset).toBe(0);
1638
- });
1639
- it("paginateSubscribe should skip isInit messages from subscription", async () => {
1640
- const mockSubscriptionId = "paginate-init-sub";
1641
- let capturedCallback = null;
1642
- const mockClient = {
1643
- modelSubscribe: jest.fn().mockResolvedValue({
1644
- subscriptionId: mockSubscriptionId,
1645
- result: { instances: [], totalCount: 0 },
1646
- }),
1647
- subscribeToQueryUpdates: jest.fn().mockImplementation((_id, cb) => {
1648
- capturedCallback = cb;
1649
- return () => { };
1650
- }),
1651
- keepAliveQuery: jest.fn().mockResolvedValue(true),
1652
- disposeQuerySubscription: jest.fn().mockResolvedValue(true),
1653
- };
1654
- let modelQueryCallCount = 0;
1655
- const mockPerspective = {
1656
- uuid: "test-uuid",
1657
- client: mockClient,
1658
- modelSubscribe: jest.fn().mockImplementation(async (className, queryJson, shapeJson) => {
1659
- return mockClient.modelSubscribe("test-uuid", className, queryJson, shapeJson);
1660
- }),
1661
- modelQuery: jest.fn().mockImplementation(async () => {
1662
- modelQueryCallCount++;
1663
- return { instances: [], totalCount: 0 };
1664
- }),
1665
- };
1666
- const { Ad4mModel, Model, Flag, Property } = require("./index");
1667
- let InitGuardTest = class InitGuardTest extends Ad4mModel {
1668
- constructor() {
1669
- super(...arguments);
1670
- this.type = "test://init";
1671
- this.name = "";
1672
- }
1673
- };
1674
- __decorate([
1675
- Flag({ through: "test://type", value: "test://init" }),
1676
- __metadata("design:type", String)
1677
- ], InitGuardTest.prototype, "type", void 0);
1678
- __decorate([
1679
- Property({ through: "test://name" }),
1680
- __metadata("design:type", String)
1681
- ], InitGuardTest.prototype, "name", void 0);
1682
- InitGuardTest = __decorate([
1683
- Model({ name: "InitGuardTest" })
1684
- ], InitGuardTest);
1685
- const userCallback = jest.fn();
1686
- const builder = InitGuardTest.query(mockPerspective);
1687
- await builder.paginateSubscribe(10, 1, userCallback);
1688
- // Reset the count after initial fetch
1689
- const initialCallCount = modelQueryCallCount;
1690
- // Simulate an isInit message from subscription
1691
- expect(capturedCallback).not.toBeNull();
1692
- capturedCallback({ isInit: true });
1693
- // Wait for any async processing
1694
- await new Promise(r => setTimeout(r, 50));
1695
- // modelQuery should NOT have been called again (isInit was filtered)
1696
- expect(modelQueryCallCount).toBe(initialCallCount);
1697
- // User callback should NOT have been invoked by isInit
1698
- expect(userCallback).not.toHaveBeenCalled();
1699
- });
1700
- it("paginateSubscribe should re-fetch on real subscription updates", async () => {
1701
- const mockSubscriptionId = "paginate-update-sub";
1702
- let capturedCallback = null;
1703
- const mockClient = {
1704
- modelSubscribe: jest.fn().mockResolvedValue({
1705
- subscriptionId: mockSubscriptionId,
1706
- result: { instances: [], totalCount: 0 },
1707
- }),
1708
- subscribeToQueryUpdates: jest.fn().mockImplementation((_id, cb) => {
1709
- capturedCallback = cb;
1710
- return () => { };
1711
- }),
1712
- keepAliveQuery: jest.fn().mockResolvedValue(true),
1713
- disposeQuerySubscription: jest.fn().mockResolvedValue(true),
1714
- };
1715
- let modelQueryCallCount = 0;
1716
- const mockPerspective = {
1717
- uuid: "test-uuid",
1718
- client: mockClient,
1719
- modelSubscribe: jest.fn().mockImplementation(async (className, queryJson, shapeJson) => {
1720
- return mockClient.modelSubscribe("test-uuid", className, queryJson, shapeJson);
1721
- }),
1722
- modelQuery: jest.fn().mockImplementation(async () => {
1723
- modelQueryCallCount++;
1724
- return { instances: [{ id: "new-item", type: "test://update" }], totalCount: 1 };
1725
- }),
1726
- };
1727
- const { Ad4mModel, Model, Flag, Property } = require("./index");
1728
- let UpdateTest = class UpdateTest extends Ad4mModel {
1729
- constructor() {
1730
- super(...arguments);
1731
- this.type = "test://update";
1732
- this.name = "";
1733
- }
1734
- };
1735
- __decorate([
1736
- Flag({ through: "test://type", value: "test://update" }),
1737
- __metadata("design:type", String)
1738
- ], UpdateTest.prototype, "type", void 0);
1739
- __decorate([
1740
- Property({ through: "test://name" }),
1741
- __metadata("design:type", String)
1742
- ], UpdateTest.prototype, "name", void 0);
1743
- UpdateTest = __decorate([
1744
- Model({ name: "UpdateTest" })
1745
- ], UpdateTest);
1746
- const userCallback = jest.fn();
1747
- const builder = UpdateTest.query(mockPerspective);
1748
- await builder.paginateSubscribe(10, 1, userCallback);
1749
- const initialCallCount = modelQueryCallCount;
1750
- // Simulate a real subscription update (not isInit)
1751
- capturedCallback({ instances: [{ id: "new-item" }], totalCount: 1 });
1752
- // Wait for async processing
1753
- await new Promise(r => setTimeout(r, 100));
1754
- // modelQuery should have been called again for the re-fetch
1755
- expect(modelQueryCallCount).toBeGreaterThan(initialCallCount);
1756
- // User callback should have been invoked with paginated results
1757
- expect(userCallback).toHaveBeenCalled();
1758
- const callArg = userCallback.mock.calls[0][0];
1759
- expect(callArg).toHaveProperty("totalCount");
1760
- expect(callArg).toHaveProperty("pageSize", 10);
1761
- expect(callArg).toHaveProperty("pageNumber", 1);
2137
+ // After the microtask queue drains, the callback should fire
2138
+ await new Promise(r => setTimeout(r, 10));
2139
+ // The callback was deferred — it fires after the Promise resolves
1762
2140
  });
1763
2141
  });
1764
2142
  // ============================================================================
@@ -1930,126 +2308,3 @@ describe("Lazy Conformance Filters", () => {
1930
2308
  expect(shacl.name).toBe("LazyParent2");
1931
2309
  });
1932
2310
  });
1933
- // ──────────────────────────────────────────────────────────
1934
- // deepQuery opt-in — getter evaluation on collection queries
1935
- // ──────────────────────────────────────────────────────────
1936
- describe("deepQuery opt-in — getter evaluation", () => {
1937
- let DeepQueryTestMessage = class DeepQueryTestMessage extends Ad4mModel {
1938
- constructor() {
1939
- super(...arguments);
1940
- this.type = "";
1941
- this.body = "";
1942
- this.isPopular = false;
1943
- this.reactions = [];
1944
- }
1945
- };
1946
- __decorate([
1947
- Flag({ through: "flux://entry_type", value: "flux://message" }),
1948
- __metadata("design:type", String)
1949
- ], DeepQueryTestMessage.prototype, "type", void 0);
1950
- __decorate([
1951
- Property({ through: "flux://body", resolveLanguage: "literal" }),
1952
- __metadata("design:type", String)
1953
- ], DeepQueryTestMessage.prototype, "body", void 0);
1954
- __decorate([
1955
- Property({
1956
- through: "flux://has_reply",
1957
- getter: `SELECT ?target WHERE { ?source <flux://has_reply> ?target . } LIMIT 1`,
1958
- }),
1959
- __metadata("design:type", String)
1960
- ], DeepQueryTestMessage.prototype, "replyingTo", void 0);
1961
- __decorate([
1962
- ReadOnly({
1963
- through: "flux://is_popular",
1964
- getter: `ASK WHERE { ?source <flux://is_popular> "true" . }`,
1965
- }),
1966
- __metadata("design:type", Boolean)
1967
- ], DeepQueryTestMessage.prototype, "isPopular", void 0);
1968
- __decorate([
1969
- HasMany({ through: "flux://reaction" }),
1970
- __metadata("design:type", Array)
1971
- ], DeepQueryTestMessage.prototype, "reactions", void 0);
1972
- DeepQueryTestMessage = __decorate([
1973
- Model({ name: "DeepQueryTestMessage" })
1974
- ], DeepQueryTestMessage);
1975
- let sparqlCalls;
1976
- const mockPerspective = {
1977
- uuid: "test-uuid",
1978
- modelQuery: jest.fn(async (className, queryJson, shapeJson) => {
1979
- // Return a basic result for the single-instance getData() path
1980
- const query = JSON.parse(queryJson);
1981
- const id = query?.where?.id;
1982
- if (id) {
1983
- return {
1984
- instances: [{ id, body: "Hello" }],
1985
- totalCount: 1,
1986
- };
1987
- }
1988
- return { instances: [], totalCount: 0 };
1989
- }),
1990
- querySparql: jest.fn(async (q) => {
1991
- sparqlCalls.push(q);
1992
- return [];
1993
- }),
1994
- get: jest.fn().mockResolvedValue([]),
1995
- getExpression: jest.fn().mockResolvedValue(null),
1996
- stringOrTemplateObjectToSubjectClassName: jest.fn().mockResolvedValue("DeepQueryTestMessage"),
1997
- };
1998
- beforeEach(() => {
1999
- sparqlCalls = [];
2000
- mockPerspective.querySparql.mockClear();
2001
- mockPerspective.get.mockClear();
2002
- });
2003
- function makeInstances(count) {
2004
- return Array.from({ length: count }, (_, i) => new DeepQueryTestMessage(mockPerspective, `flux://msg-${i}`));
2005
- }
2006
- it("single-instance get() delegates getter evaluation to Rust (no JS-side SPARQL)", async () => {
2007
- const instance = new DeepQueryTestMessage(mockPerspective, "flux://msg-single");
2008
- mockPerspective.querySparql.mockImplementation(async (q) => {
2009
- sparqlCalls.push(q);
2010
- if (q.includes("flux://msg-single") && !q.includes("flux://has_reply") && !q.includes("flux://is_popular")) {
2011
- return [
2012
- { source: "flux://msg-single", predicate: "flux://entry_type", target: "flux://message", author: "did:key:a", timestamp: "3000" },
2013
- { source: "flux://msg-single", predicate: "flux://body", target: "literal:string:Hello", author: "did:key:a", timestamp: "3000" },
2014
- ];
2015
- }
2016
- return [];
2017
- });
2018
- await instance.get();
2019
- // Getter evaluation now happens Rust-side via evaluate_getters() — no JS SPARQL calls
2020
- const getterCalls = sparqlCalls.filter((q) => q.includes("flux://has_reply") || q.includes("flux://is_popular"));
2021
- expect(getterCalls.length).toBe(0);
2022
- });
2023
- describe("Ad4mModel.evaluateGetters()", () => {
2024
- it("resolves getters for a batch of instances", async () => {
2025
- const instances = makeInstances(4);
2026
- sparqlCalls = [];
2027
- await DeepQueryTestMessage.evaluateGetters(instances.slice(0, 2), mockPerspective, ["replyingTo"]);
2028
- const replyCalls = sparqlCalls.filter((q) => q.includes("flux://has_reply"));
2029
- expect(replyCalls.length).toBe(2);
2030
- const popularCalls = sparqlCalls.filter((q) => q.includes("flux://is_popular"));
2031
- expect(popularCalls.length).toBe(0);
2032
- });
2033
- it("evaluates all getters when propertyNames is omitted", async () => {
2034
- const instances = makeInstances(2);
2035
- sparqlCalls = [];
2036
- await DeepQueryTestMessage.evaluateGetters(instances, mockPerspective);
2037
- const replyCalls = sparqlCalls.filter((q) => q.includes("flux://has_reply"));
2038
- const popularCalls = sparqlCalls.filter((q) => q.includes("flux://is_popular"));
2039
- expect(replyCalls.length).toBe(2);
2040
- expect(popularCalls.length).toBe(2);
2041
- });
2042
- it("handles empty array gracefully", async () => {
2043
- sparqlCalls = [];
2044
- await DeepQueryTestMessage.evaluateGetters([], mockPerspective);
2045
- expect(sparqlCalls.length).toBe(0);
2046
- });
2047
- });
2048
- describe("deepQuery via ModelQueryBuilder", () => {
2049
- it("deepQuery() method sets deepQuery flag on queryParams", () => {
2050
- const builder = DeepQueryTestMessage.query(mockPerspective);
2051
- builder.deepQuery();
2052
- expect(builder.queryParams.deepQuery).toBe(true);
2053
- });
2054
- });
2055
- });