@coasys/ad4m 0.13.0-test-6 → 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 (279) hide show
  1. package/lib/index.cjs +1103 -747
  2. package/lib/index.js +1090 -747
  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 -21
  200. package/lib/src/model/Ad4mModel.js +93 -316
  201. package/lib/src/model/Ad4mModel.test.js +1536 -535
  202. package/lib/src/model/ModelQueryBuilder.d.ts +5 -10
  203. package/lib/src/model/ModelQueryBuilder.js +136 -47
  204. package/lib/src/model/Subject.js +6 -6
  205. package/lib/src/model/decorators.d.ts +7 -4
  206. package/lib/src/model/decorators.js +0 -7
  207. package/lib/src/model/hydration-batch.d.ts +34 -0
  208. package/lib/src/model/hydration-batch.js +147 -0
  209. package/lib/src/model/hydration-batching.test.d.ts +7 -0
  210. package/lib/src/model/hydration-batching.test.js +456 -0
  211. package/lib/src/model/query-cache.test.d.ts +1 -0
  212. package/lib/src/model/query-cache.test.js +43 -0
  213. package/lib/src/model/query-sparql-batch.d.ts +17 -0
  214. package/lib/src/model/query-sparql-batch.js +260 -0
  215. package/lib/src/model/query-sparql.d.ts +0 -10
  216. package/lib/src/model/query-sparql.js +10 -15
  217. package/lib/src/model/query-sparql.test.d.ts +1 -0
  218. package/lib/src/model/query-sparql.test.js +230 -0
  219. package/lib/src/model/relation-filtering.test.js +15 -15
  220. package/lib/src/model/shacl-gen.js +120 -47
  221. package/lib/src/model/subscription-delta.test.d.ts +24 -0
  222. package/lib/src/model/subscription-delta.test.js +180 -0
  223. package/lib/src/model/subscription-pool.d.ts +39 -0
  224. package/lib/src/model/subscription-pool.js +165 -0
  225. package/lib/src/model/types.d.ts +140 -4
  226. package/lib/src/neighbourhood/NeighbourhoodProxy.test.js +33 -33
  227. package/lib/src/perspectives/PerspectiveClient.d.ts +13 -4
  228. package/lib/src/perspectives/PerspectiveClient.js +22 -6
  229. package/lib/src/perspectives/PerspectiveClient.test.d.ts +1 -0
  230. package/lib/src/perspectives/PerspectiveClient.test.js +224 -0
  231. package/lib/src/perspectives/PerspectiveProxy.d.ts +27 -7
  232. package/lib/src/perspectives/PerspectiveProxy.js +60 -12
  233. package/lib/src/perspectives/PerspectiveProxy.test.d.ts +1 -0
  234. package/lib/src/perspectives/PerspectiveProxy.test.js +34 -0
  235. package/lib/src/perspectives/PerspectiveResolver.d.ts +0 -1
  236. package/lib/src/perspectives/PerspectiveResolver.js +0 -11
  237. package/lib/src/perspectives/SparqlBindings.d.ts +47 -0
  238. package/lib/src/perspectives/SparqlBindings.js +65 -0
  239. package/lib/src/perspectives/WakerSubscriptionManager.js +5 -4
  240. package/lib/src/restClient.d.ts +52 -0
  241. package/lib/src/restClient.js +227 -0
  242. package/lib/src/runtime/RuntimeResolver.d.ts +28 -1
  243. package/lib/src/runtime/RuntimeResolver.js +197 -4
  244. package/lib/src/schema.gql +27 -1
  245. package/lib/src/shacl/NodeExpression.d.ts +44 -0
  246. package/lib/src/shacl/NodeExpression.js +39 -0
  247. package/lib/src/shacl/SHACLShape.d.ts +23 -0
  248. package/lib/src/shacl/SHACLShape.js +115 -1
  249. package/lib/src/shacl/builders.d.ts +58 -0
  250. package/lib/src/shacl/builders.js +76 -0
  251. package/lib/src/shacl/index.d.ts +36 -0
  252. package/lib/src/shacl/index.js +33 -0
  253. package/package.json +1 -1
  254. package/src/Ad4mClient.ts +7 -2
  255. package/src/agent/AgentClient.ts +23 -0
  256. package/src/ai/AIClient.ts +1 -1
  257. package/src/apiClient.ts +17 -6
  258. package/src/index.ts +4 -0
  259. package/src/model/Ad4mModel.test.ts +274 -72
  260. package/src/model/Ad4mModel.ts +141 -350
  261. package/src/model/ModelQueryBuilder.ts +131 -56
  262. package/src/model/decorators.ts +7 -13
  263. package/src/model/query-sparql.test.ts +35 -19
  264. package/src/model/query-sparql.ts +10 -16
  265. package/src/model/relation-filtering.test.ts +46 -39
  266. package/src/model/shacl-gen.ts +128 -54
  267. package/src/model/shacl-roundtrip.test.ts +197 -0
  268. package/src/model/types-typed-query.test.ts +360 -0
  269. package/src/model/types.ts +196 -4
  270. package/src/perspectives/PerspectiveClient.ts +24 -8
  271. package/src/perspectives/PerspectiveProxy.test.ts +85 -1
  272. package/src/perspectives/PerspectiveProxy.ts +65 -20
  273. package/src/perspectives/SparqlBindings.ts +79 -0
  274. package/src/perspectives/WakerSubscriptionManager.ts +5 -4
  275. package/src/shacl/NodeExpression.ts +54 -0
  276. package/src/shacl/SHACLShape.test.ts +172 -0
  277. package/src/shacl/SHACLShape.ts +173 -1
  278. package/src/shacl/builders.ts +86 -0
  279. package/src/shacl/index.ts +72 -0
@@ -437,14 +437,11 @@ describe("Ad4mModel.fromJSONSchema() with getModelMetadata()", () => {
437
437
  expect(shape.destructor_actions).toEqual([]);
438
438
  });
439
439
  });
440
- describe("Ad4mModel.queryToSurrealQL()", () => {
441
- // Mock perspective proxy (minimal since queryToSurrealQL doesn't actually call it)
440
+ describe("Ad4mModel.queryToSPARQL()", () => {
442
441
  const mockPerspective = {};
443
- // Helper function to normalize whitespace in queries for easier comparison
444
442
  function normalizeQuery(query) {
445
443
  return query.replace(/\s+/g, ' ').trim();
446
444
  }
447
- // Test Recipe model — explicit required: true to test required-property query filters
448
445
  let Recipe = class Recipe extends Ad4mModel {
449
446
  constructor() {
450
447
  super(...arguments);
@@ -468,328 +465,171 @@ describe("Ad4mModel.queryToSurrealQL()", () => {
468
465
  Recipe = __decorate([
469
466
  Model({ name: "Recipe" })
470
467
  ], Recipe);
471
- it("should generate basic query with no filters", async () => {
472
- const query = await Recipe.queryToSurrealQL(mockPerspective, {});
473
- expect(query).toContain("id AS source");
474
- expect(query).toContain("uri AS source_uri");
475
- expect(query).toContain("FROM node");
476
- expect(query).toContain("->link AS links");
477
- expect(query).toContain("WHERE");
478
- // Should have graph traversal filters for required properties
479
- expect(query).toContain("count(->link[WHERE");
468
+ it("should generate basic SPARQL query with no filters", async () => {
469
+ const query = await Recipe.queryToSPARQL(mockPerspective, {});
470
+ const norm = normalizeQuery(query);
471
+ // Must be a SPARQL SELECT
472
+ expect(norm).toContain("SELECT ?source ?predicate ?target ?author ?timestamp");
473
+ // Must have conformance JOIN for required properties using direct triple patterns
474
+ expect(norm).toContain("cfTarget_name");
475
+ expect(norm).toContain("recipe://name");
480
476
  });
481
477
  it("should generate query with simple property filter", async () => {
482
- const query = await Recipe.queryToSurrealQL(mockPerspective, { where: { name: "Pasta" } });
483
- // Should have graph traversal filters for required properties and user filter
484
- expect(query).toContain("count(->link[WHERE predicate = 'recipe://name']) > 0");
485
- expect(query).toContain("count(->link[WHERE predicate = 'recipe://rating']) > 0");
486
- expect(query).toContain("count(->link[WHERE predicate = 'recipe://name' AND fn::parse_literal(out.uri) = 'Pasta']) > 0");
487
- });
488
- it("should generate query with multiple property filters", async () => {
489
- const query = await Recipe.queryToSurrealQL(mockPerspective, { where: { name: "Pasta", rating: 5 } });
490
- expect(query).toContain("WHERE");
491
- expect(query).toContain("count(->link[WHERE predicate = 'recipe://name' AND fn::parse_literal(out.uri) = 'Pasta']) > 0");
492
- expect(query).toContain("count(->link[WHERE predicate = 'recipe://rating' AND fn::parse_literal(out.uri) = 5]) > 0");
493
- expect(query).toContain("AND");
494
- });
495
- it("should handle gt operator (filtered in JavaScript, not SQL)", async () => {
496
- const query = await Recipe.queryToSurrealQL(mockPerspective, { where: { rating: { gt: 4 } } });
497
- // Comparison operators for regular properties are now filtered in JavaScript post-query
498
- // The SQL just filters on the predicate existing
499
- expect(query).toContain("FROM node");
500
- // Should NOT contain comparison operators in SQL for regular properties
501
- expect(query).not.toContain("target > 4");
502
- });
503
- it("should handle lt operator (filtered in JavaScript, not SQL)", async () => {
504
- const query = await Recipe.queryToSurrealQL(mockPerspective, { where: { rating: { lt: 3 } } });
505
- // Comparison operators are filtered in JavaScript post-query
506
- expect(query).toContain("FROM node");
507
- expect(query).not.toContain("target < 3");
508
- });
509
- it("should handle gte and lte operators (filtered in JavaScript, not SQL)", async () => {
510
- const query = await Recipe.queryToSurrealQL(mockPerspective, { where: { rating: { gte: 3, lte: 5 } } });
511
- // Comparison operators are filtered in JavaScript post-query
512
- expect(query).toContain("FROM node");
513
- expect(query).not.toContain("target >= 3");
514
- expect(query).not.toContain("target <= 5");
515
- });
516
- it("should handle not operator with single value", async () => {
517
- const query = await Recipe.queryToSurrealQL(mockPerspective, { where: { name: { not: "Salad" } } });
518
- // Not operator uses graph traversal with count = 0
519
- expect(query).toContain("count(->link[WHERE predicate = 'recipe://name' AND fn::parse_literal(out.uri) = 'Salad']) = 0");
520
- });
521
- it("should handle not operator with array (NOT IN)", async () => {
522
- const query = await Recipe.queryToSurrealQL(mockPerspective, { where: { name: { not: ["Salad", "Soup"] } } });
523
- // Not operator with array uses graph traversal with count = 0
524
- expect(query).toContain("count(->link[WHERE predicate = 'recipe://name' AND fn::parse_literal(out.uri) IN ['Salad', 'Soup']]) = 0");
525
- });
526
- it("should handle between operator (filtered in JavaScript, not SQL)", async () => {
527
- const query = await Recipe.queryToSurrealQL(mockPerspective, { where: { rating: { between: [3, 5] } } });
528
- // Between operator for regular properties is now filtered in JavaScript post-query
529
- expect(query).toContain("FROM node");
530
- expect(query).not.toContain("target >= 3");
531
- expect(query).not.toContain("target <= 5");
532
- });
533
- it("should handle contains operator on string property (filtered in JavaScript, not SQL)", async () => {
534
- const query = await Recipe.queryToSurrealQL(mockPerspective, { where: { name: { contains: "Past" } } });
535
- // Contains operator for regular properties is now filtered in JavaScript post-query
536
- expect(query).toContain("FROM node");
537
- expect(query).not.toContain("target CONTAINS 'Past'");
538
- });
539
- it("should handle contains operator on regular property with substring (filtered in JavaScript, not SQL)", async () => {
540
- const query = await Recipe.queryToSurrealQL(mockPerspective, { where: { name: { contains: "Salad" } } });
541
- // Contains operator is filtered in JavaScript post-query
542
- expect(query).toContain("FROM node");
543
- expect(query).not.toContain("target CONTAINS 'Salad'");
544
- });
545
- it.skip("should handle contains operator on special field (author)", async () => {
546
- const query = await Recipe.queryToSurrealQL(mockPerspective, { where: { author: { contains: "alice" } } });
547
- expect(query).toContain("WHERE author CONTAINS 'alice'");
548
- // Should not use a subquery pattern
549
- expect(query).not.toContain("SELECT source FROM node");
550
- });
551
- it.skip("should handle contains operator on special field (id)", async () => {
552
- const query = await Recipe.queryToSurrealQL(mockPerspective, { where: { id: { contains: "test" } } });
553
- expect(query).toContain("WHERE source CONTAINS 'test'");
554
- });
555
- it("should handle array values (IN clause)", async () => {
556
- const query = await Recipe.queryToSurrealQL(mockPerspective, { where: { name: ["Pasta", "Pizza"] } });
557
- expect(query).toContain("count(->link[WHERE predicate = 'recipe://name' AND fn::parse_literal(out.uri) IN ['Pasta', 'Pizza']]) > 0");
558
- });
559
- it.skip("should handle special fields (author, timestamp) without subqueries", async () => {
560
- const query = await Recipe.queryToSurrealQL(mockPerspective, { where: { author: "did:key:alice" } });
561
- expect(query).toContain("WHERE author = 'did:key:alice'");
562
- // Ensure it's NOT using a subquery pattern for author in WHERE clause
563
- expect(normalizeQuery(query)).not.toMatch(/WHERE.*source IN.*SELECT source FROM node.*author/);
564
- });
565
- it("should not generate ORDER BY clause in SQL (handled in JavaScript)", async () => {
566
- const query = await Recipe.queryToSurrealQL(mockPerspective, { order: { timestamp: "DESC" } });
567
- // ORDER BY is now handled in JavaScript post-query
568
- expect(query).toContain("FROM node");
569
- expect(query).not.toContain("ORDER BY");
570
- });
571
- it("should not generate LIMIT clause in SQL (handled in JavaScript)", async () => {
572
- const query = await Recipe.queryToSurrealQL(mockPerspective, { limit: 10 });
573
- // LIMIT is now handled in JavaScript post-query
574
- expect(query).toContain("FROM node");
575
- expect(query).not.toContain("LIMIT");
576
- });
577
- it("should not generate START clause in SQL (handled in JavaScript)", async () => {
578
- const query = await Recipe.queryToSurrealQL(mockPerspective, { offset: 20 });
579
- // START/offset is now handled in JavaScript post-query
580
- expect(query).toContain("FROM node");
581
- expect(query).not.toContain("START");
582
- });
583
- it("should generate complete query with all options (ORDER BY, LIMIT, START handled in JS)", async () => {
584
- const query = await Recipe.queryToSurrealQL(mockPerspective, {
585
- where: { name: "Pasta", rating: { gt: 4 } },
586
- order: { timestamp: "DESC" },
587
- limit: 10,
588
- offset: 20
589
- });
590
- // WHERE clause uses graph traversal filters
591
- expect(query).toContain("WHERE");
592
- expect(query).toContain("count(->link[WHERE predicate = 'recipe://name' AND fn::parse_literal(out.uri) = 'Pasta']) > 0");
593
- // Comparison operators (gt) are filtered in JavaScript, not SQL
594
- expect(query).not.toContain("out.uri > 4");
595
- expect(query).not.toContain("target > 4");
596
- // ORDER BY, LIMIT, START are now handled in JavaScript post-query
597
- expect(query).not.toContain("ORDER BY");
598
- expect(query).not.toContain("LIMIT");
599
- expect(query).not.toContain("START");
600
- });
601
- it("should only select requested properties", async () => {
602
- const query = await Recipe.queryToSurrealQL(mockPerspective, { properties: ["name"] });
603
- // With array::group(), all link data is selected, filtering happens in instancesFromSurrealResult
604
- expect(query).toContain("->link AS links");
605
- });
606
- it("should select all link data for relations", async () => {
607
- let MultiRelationModel = class MultiRelationModel extends Ad4mModel {
608
- constructor() {
609
- super(...arguments);
610
- this.coll1 = [];
611
- this.coll2 = [];
612
- }
613
- };
614
- __decorate([
615
- HasMany({ through: "test://coll1" }),
616
- __metadata("design:type", Array)
617
- ], MultiRelationModel.prototype, "coll1", void 0);
618
- __decorate([
619
- HasMany({ through: "test://coll2" }),
620
- __metadata("design:type", Array)
621
- ], MultiRelationModel.prototype, "coll2", void 0);
622
- MultiRelationModel = __decorate([
623
- Model({ name: "MultiRelationModel" })
624
- ], MultiRelationModel);
625
- const query = await MultiRelationModel.queryToSurrealQL(mockPerspective, {});
626
- // With array::group(), all link data is selected
627
- expect(query).toContain("->link AS links");
628
- });
629
- it("should escape single quotes in string values", async () => {
630
- const query = await Recipe.queryToSurrealQL(mockPerspective, { where: { name: "O'Brien's Recipe" } });
631
- // Single quotes are escaped with backslash in SurrealDB
632
- expect(query).toContain("O\\'Brien\\'s Recipe");
633
- });
634
- it("should handle numeric values without quotes", async () => {
635
- const query = await Recipe.queryToSurrealQL(mockPerspective, { where: { rating: 5 } });
636
- // Numeric values should not have quotes around them
637
- expect(query).toContain("fn::parse_literal(out.uri) = 5");
638
- expect(query).not.toContain("fn::parse_literal(out.uri) = '5'");
639
- });
640
- it("should handle complex nested query (comparisons, ORDER BY, LIMIT handled in JS)", async () => {
641
- const query = await Recipe.queryToSurrealQL(mockPerspective, {
642
- where: {
643
- name: "Pasta",
644
- rating: { gte: 4, lte: 5 },
645
- author: "did:key:alice"
646
- },
647
- order: { rating: "DESC" },
648
- limit: 5
649
- });
650
- const normalized = normalizeQuery(query);
651
- // Verify graph traversal filters are present
652
- expect(normalized).toContain("count(->link[WHERE predicate = 'recipe://name' AND fn::parse_literal(out.uri) = 'Pasta']) > 0");
653
- // Comparison operators (gte, lte) are filtered in JavaScript, not SQL
654
- expect(normalized).not.toContain("out.uri >= 4");
655
- expect(normalized).not.toContain("target >= 4");
656
- expect(normalized).not.toContain("out.uri <= 5");
657
- expect(normalized).not.toContain("target <= 5");
658
- // author and timestamp filtering is done in JavaScript post-query
659
- expect(normalized).not.toContain("author = 'did:key:alice'");
660
- // ORDER BY and LIMIT are handled in JavaScript post-query
661
- expect(normalized).not.toContain("ORDER BY");
662
- expect(normalized).not.toContain("LIMIT");
663
- // Verify query structure (FROM node, no GROUP BY)
664
- expect(normalized).toContain("FROM node");
665
- });
666
- it("should handle empty query object", async () => {
667
- const query = await Recipe.queryToSurrealQL(mockPerspective, {});
668
- // Should generate valid query with WHERE clause for required properties (name and rating)
669
- expect(query).toContain("id AS source");
670
- expect(query).toContain("uri AS source_uri");
671
- expect(query).toContain("FROM node");
672
- // Should have WHERE clause filtering for required properties using graph traversal
673
- expect(query).toContain("WHERE");
674
- expect(query).toContain("count(->link[WHERE predicate = 'recipe://name']) > 0");
675
- expect(query).toContain("count(->link[WHERE predicate = 'recipe://rating']) > 0");
676
- expect(query).not.toContain("ORDER BY");
677
- expect(query).not.toContain("START");
678
- });
679
- it("should handle id special field", async () => {
680
- const query = await Recipe.queryToSurrealQL(mockPerspective, { where: { id: "literal://test" } });
681
- expect(query).toContain("uri = 'literal://test'");
682
- });
683
- it("should handle id special field with array (IN clause)", async () => {
684
- const query = await Recipe.queryToSurrealQL(mockPerspective, { where: { id: ["literal://test1", "literal://test2"] } });
685
- expect(query).toContain("uri IN ['literal://test1', 'literal://test2']");
686
- });
687
- it("should handle id special field with not operator", async () => {
688
- const query = await Recipe.queryToSurrealQL(mockPerspective, { where: { id: { not: "literal://test" } } });
689
- expect(query).toContain("uri != 'literal://test'");
690
- });
691
- it("should handle id special field with not operator and array (NOT IN)", async () => {
692
- const query = await Recipe.queryToSurrealQL(mockPerspective, { where: { id: { not: ["literal://test1", "literal://test2"] } } });
693
- expect(query).toContain("uri NOT IN ['literal://test1', 'literal://test2']");
694
- });
695
- it("should handle id special field with between operator", async () => {
696
- const query = await Recipe.queryToSurrealQL(mockPerspective, { where: { id: { between: ["literal://a", "literal://z"] } } });
697
- const normalized = normalizeQuery(query);
698
- expect(normalized).toContain("uri >= 'literal://a' AND uri <= 'literal://z'");
699
- });
700
- it("should handle id special field with gt operator", async () => {
701
- const query = await Recipe.queryToSurrealQL(mockPerspective, { where: { id: { gt: "literal://m" } } });
702
- expect(query).toContain("uri > 'literal://m'");
703
- });
704
- it("should handle id special field with gte and lte operators", async () => {
705
- const query = await Recipe.queryToSurrealQL(mockPerspective, { where: { id: { gte: "literal://a", lte: "literal://z" } } });
706
- const normalized = normalizeQuery(query);
707
- expect(normalized).toContain("uri >= 'literal://a'");
708
- expect(normalized).toContain("uri <= 'literal://z'");
709
- });
710
- it("should handle timestamp special field with gt operator (filtered in JavaScript)", async () => {
711
- const query = await Recipe.queryToSurrealQL(mockPerspective, { where: { timestamp: { gt: 1234567890 } } });
712
- // timestamp filtering is done in JavaScript post-query
713
- expect(query).toContain("FROM node");
714
- expect(query).not.toContain("timestamp > 1234567890");
715
- });
716
- it("should handle multiple special fields (filtered in JavaScript)", async () => {
717
- const query = await Recipe.queryToSurrealQL(mockPerspective, {
718
- where: {
719
- author: "did:key:alice",
720
- timestamp: { gt: 1000 }
721
- }
722
- });
723
- // author and timestamp filtering is done in JavaScript post-query
724
- expect(query).toContain("FROM node");
725
- expect(query).not.toContain("author = 'did:key:alice'");
726
- expect(query).not.toContain("timestamp > 1000");
727
- });
728
- it("should handle mixed special and regular properties", async () => {
729
- const query = await Recipe.queryToSurrealQL(mockPerspective, {
730
- where: {
731
- name: "Pasta",
732
- author: "did:key:alice",
733
- rating: { gt: 4 }
734
- }
478
+ const query = await Recipe.queryToSPARQL(mockPerspective, { where: { name: "Pasta" } });
479
+ const norm = normalizeQuery(query);
480
+ expect(norm).toContain("SELECT ?source ?predicate ?target ?author ?timestamp");
481
+ // For literal-stored properties, SPARQL only adds a JOIN (no FILTER value) — filtering is in JS
482
+ expect(norm).toContain("recipe://name");
483
+ // Value should NOT be in SPARQL — filtering happens in JS post-filter
484
+ expect(norm).toContain("?wTarget_name");
485
+ });
486
+ it("should generate query with NOT operator", async () => {
487
+ const query = await Recipe.queryToSPARQL(mockPerspective, { where: { name: { not: "Salad" } } });
488
+ const norm = normalizeQuery(query);
489
+ // For literal-stored properties, NOT filtering is done in JS — no NOT EXISTS in SPARQL
490
+ expect(norm).toContain("recipe://name");
491
+ });
492
+ it("should generate query with NOT IN operator (array)", async () => {
493
+ const query = await Recipe.queryToSPARQL(mockPerspective, { where: { name: { not: ["Salad", "Soup"] } } });
494
+ const norm = normalizeQuery(query);
495
+ // For literal-stored properties, NOT IN filtering is done in JS — no filter values in SPARQL
496
+ expect(norm).toContain("recipe://name");
497
+ });
498
+ it("should generate query with IN clause (array values)", async () => {
499
+ const query = await Recipe.queryToSPARQL(mockPerspective, { where: { name: ["Pasta", "Pizza"] } });
500
+ const norm = normalizeQuery(query);
501
+ // For literal-stored properties, IN filtering is done in JS — only a JOIN exists
502
+ expect(norm).toContain("recipe://name");
503
+ expect(norm).toContain("?wTarget_name");
504
+ });
505
+ it("should generate query with base filter", async () => {
506
+ const query = await Recipe.queryToSPARQL(mockPerspective, { where: { base: "ad4m://test123" } });
507
+ const norm = normalizeQuery(query);
508
+ expect(norm).toContain("?source =");
509
+ expect(norm).toContain("ad4m://test123");
510
+ });
511
+ it("should escape special characters in SPARQL strings", async () => {
512
+ const query = await Recipe.queryToSPARQL(mockPerspective, { where: { name: 'O\'Brien' } });
513
+ const norm = normalizeQuery(query);
514
+ // Should not break the query
515
+ expect(norm).toContain("SELECT ?source");
516
+ });
517
+ // =========================================================================
518
+ // Additional models for thorough SPARQL structure tests
519
+ // =========================================================================
520
+ let Task = class Task extends Ad4mModel {
521
+ constructor() {
522
+ super(...arguments);
523
+ this.title = "";
524
+ this.priority = 0;
525
+ this.done = false;
526
+ this.description = "";
527
+ this.tags = [];
528
+ this.assignees = [];
529
+ }
530
+ };
531
+ __decorate([
532
+ Property({ through: "task://title", resolveLanguage: "literal", required: true }),
533
+ __metadata("design:type", String)
534
+ ], Task.prototype, "title", void 0);
535
+ __decorate([
536
+ Property({ through: "task://priority", resolveLanguage: "literal" }),
537
+ __metadata("design:type", Number)
538
+ ], Task.prototype, "priority", void 0);
539
+ __decorate([
540
+ Property({ through: "task://done", resolveLanguage: "literal" }),
541
+ __metadata("design:type", Boolean)
542
+ ], Task.prototype, "done", void 0);
543
+ __decorate([
544
+ Optional({ through: "task://description" }),
545
+ __metadata("design:type", String)
546
+ ], Task.prototype, "description", void 0);
547
+ __decorate([
548
+ HasMany({ through: "task://tag" }),
549
+ __metadata("design:type", Array)
550
+ ], Task.prototype, "tags", void 0);
551
+ __decorate([
552
+ HasMany({ through: "task://assignee" }),
553
+ __metadata("design:type", Array)
554
+ ], Task.prototype, "assignees", void 0);
555
+ Task = __decorate([
556
+ Model({ name: "Task" })
557
+ ], Task);
558
+ let EmptyModel = class EmptyModel extends Ad4mModel {
559
+ constructor() {
560
+ super(...arguments);
561
+ this.optField = "";
562
+ }
563
+ };
564
+ __decorate([
565
+ Optional({ through: "empty://optField" }),
566
+ __metadata("design:type", String)
567
+ ], EmptyModel.prototype, "optField", void 0);
568
+ EmptyModel = __decorate([
569
+ Model({ name: "EmptyModel" })
570
+ ], EmptyModel);
571
+ // ---- Comparison operators (gt, lt, gte, lte, between, contains) ----
572
+ // These are handled in JS post-processing, NOT in SPARQL.
573
+ // The tests verify that the SPARQL still generates valid output (conformance filters)
574
+ // but does NOT inject FILTER clauses for these operators.
575
+ it("should inject SPARQL FILTER for gt operator", async () => {
576
+ const query = await Recipe.queryToSPARQL(mockPerspective, { where: { rating: { gt: 3 } } });
577
+ const norm = normalizeQuery(query);
578
+ expect(norm).toContain("SELECT ?source");
579
+ // gt is now handled via JS post-filter — SPARQL just joins the property
580
+ expect(norm).toContain("wTarget_cmp_rating");
581
+ });
582
+ it("should inject SPARQL FILTER for lt operator", async () => {
583
+ const query = await Recipe.queryToSPARQL(mockPerspective, { where: { rating: { lt: 5 } } });
584
+ const norm = normalizeQuery(query);
585
+ expect(norm).toContain("SELECT ?source");
586
+ // lt is now handled via JS post-filter
587
+ expect(norm).toContain("wTarget_cmp_rating");
588
+ });
589
+ it("should inject SPARQL FILTER for gte/lte combined", async () => {
590
+ const query = await Recipe.queryToSPARQL(mockPerspective, { where: { rating: { gte: 2, lte: 8 } } });
591
+ const norm = normalizeQuery(query);
592
+ expect(norm).toContain("SELECT ?source");
593
+ // gte/lte are now handled via JS post-filter
594
+ expect(norm).toContain("wTarget_cmp_rating");
595
+ });
596
+ it("should inject SPARQL FILTER for between operator", async () => {
597
+ const query = await Recipe.queryToSPARQL(mockPerspective, { where: { rating: { between: [1, 10] } } });
598
+ const norm = normalizeQuery(query);
599
+ expect(norm).toContain("SELECT ?source");
600
+ // between is now handled via JS post-filter
601
+ expect(norm).toContain("wTarget_cmp_rating");
602
+ });
603
+ it("should inject SPARQL FILTER for contains operator", async () => {
604
+ const query = await Recipe.queryToSPARQL(mockPerspective, { where: { name: { contains: "pasta" } } });
605
+ const norm = normalizeQuery(query);
606
+ expect(norm).toContain("SELECT ?source");
607
+ // contains is now handled via JS post-filter
608
+ expect(norm).toContain("wTarget_cmp_name");
609
+ });
610
+ // ---- Multiple property filters combined ----
611
+ it("should combine multiple property equality filters with &&", async () => {
612
+ const query = await Recipe.queryToSPARQL(mockPerspective, {
613
+ where: { name: "Pasta", rating: ["4", "5"] }
735
614
  });
736
- const normalized = normalizeQuery(query);
737
- // Regular properties use graph traversal filters
738
- expect(normalized).toContain("count(->link[WHERE predicate = 'recipe://name' AND fn::parse_literal(out.uri) = 'Pasta']) > 0");
739
- // Comparison operators (gt) are filtered in JavaScript, not SQL
740
- expect(normalized).not.toContain("out.uri > 4");
741
- expect(normalized).not.toContain("target > 4");
742
- // author filtering is done in JavaScript post-query
743
- expect(normalized).not.toContain("author = 'did:key:alice'");
744
- });
745
- it("should handle boolean values", async () => {
746
- let Task = class Task extends Ad4mModel {
747
- constructor() {
748
- super(...arguments);
749
- this.completed = false;
750
- }
751
- };
752
- __decorate([
753
- Property({ through: "task://completed" }),
754
- __metadata("design:type", Boolean)
755
- ], Task.prototype, "completed", void 0);
756
- Task = __decorate([
757
- Model({ name: "Task" })
758
- ], Task);
759
- const query = await Task.queryToSurrealQL(mockPerspective, { where: { completed: true } });
760
- expect(query).toContain("fn::parse_literal(out.uri) = true");
761
- });
762
- it("should handle array of numbers", async () => {
763
- const query = await Recipe.queryToSurrealQL(mockPerspective, { where: { rating: [4, 5] } });
764
- expect(query).toContain("count(->link[WHERE predicate = 'recipe://rating' AND fn::parse_literal(out.uri) IN [4, 5]]) > 0");
765
- });
766
- it("should skip unknown properties in where clause", async () => {
767
- const query = await Recipe.queryToSurrealQL(mockPerspective, { where: { unknownProp: "value" } });
768
- // Should not throw error, just skip the unknown property
769
- expect(query).toContain("source");
770
- // Should not contain any condition for unknownProp
771
- expect(query).not.toContain("unknownProp");
772
- });
773
- it.skip("should skip unknown properties in select clause", async () => {
774
- const query = await Recipe.queryToSurrealQL(mockPerspective, { properties: ["name", "unknownProp"] });
775
- // Should include name using aggregation
776
- expect(query).toContain("array::first(target[WHERE predicate = 'recipe://name']) AS name");
777
- // Should not error on unknownProp, just skip it
778
- expect(query).not.toContain("unknownProp");
779
- });
780
- it("should handle order by regular property (handled in JavaScript)", async () => {
781
- const query = await Recipe.queryToSurrealQL(mockPerspective, { order: { name: "ASC" } });
782
- // ORDER BY is now handled in JavaScript post-query
783
- expect(query).toContain("FROM node");
784
- expect(query).not.toContain("ORDER BY");
785
- });
786
- it("should generate query with only properties specified", async () => {
787
- const query = await Recipe.queryToSurrealQL(mockPerspective, { properties: ["name", "rating"] });
788
- // With array::group(), all link data is selected, filtering happens in instancesFromSurrealResult
789
- expect(query).toContain("->link AS links");
615
+ const norm = normalizeQuery(query);
616
+ // Should have EXISTS blocks for both name and rating
617
+ expect(norm).toContain("recipe://name");
618
+ expect(norm).toContain("recipe://rating");
619
+ expect(norm).toContain("&&");
620
+ });
621
+ // ---- ORDER BY, LIMIT, OFFSET are JS post-processed ----
622
+ it("should NOT include ORDER BY/LIMIT/OFFSET in SPARQL (pagination is JS-only)", async () => {
623
+ const query = await Recipe.queryToSPARQL(mockPerspective, { order: { name: "ASC" }, limit: 10, offset: 5 });
624
+ const norm = normalizeQuery(query);
625
+ expect(norm).toContain("SELECT ?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");
790
630
  });
791
631
  });
792
- describe("Ad4mModel.instancesFromSurrealResult() and SurrealDB integration", () => {
632
+ describe("Ad4mModel.instancesFromQueryResult() and SPARQL integration", () => {
793
633
  // Test Recipe model
794
634
  let Recipe = class Recipe extends Ad4mModel {
795
635
  constructor() {
@@ -814,9 +654,9 @@ describe("Ad4mModel.instancesFromSurrealResult() and SurrealDB integration", ()
814
654
  Recipe = __decorate([
815
655
  Model({ name: "Recipe" })
816
656
  ], Recipe);
817
- // Mock perspective with both querySurrealDB and infer methods
657
+ // Mock perspective with both querySparql and infer methods
818
658
  const mockPerspective = {
819
- querySurrealDB: jest.fn(),
659
+ querySparql: jest.fn(),
820
660
  infer: jest.fn(),
821
661
  uuid: 'test-perspective-uuid',
822
662
  stringOrTemplateObjectToSubjectClassName: jest.fn().mockResolvedValue('Recipe')
@@ -824,16 +664,16 @@ describe("Ad4mModel.instancesFromSurrealResult() and SurrealDB integration", ()
824
664
  beforeEach(() => {
825
665
  jest.clearAllMocks();
826
666
  });
827
- it("should convert empty SurrealDB results correctly", async () => {
828
- const result = await Recipe.instancesFromSurrealResult(mockPerspective, {}, []);
667
+ it("should convert empty query results correctly", async () => {
668
+ const result = await Recipe.instancesFromQueryResult(mockPerspective, {}, []);
829
669
  expect(result.results).toEqual([]);
830
670
  expect(result.totalCount).toBe(0);
831
671
  });
832
- it("should convert SurrealDB results to model instances", async () => {
833
- const surrealResults = [
672
+ it("should convert query results to model instances", async () => {
673
+ const queryResults = [
834
674
  {
835
675
  source: "node:abc123",
836
- source_uri: "literal://recipe1",
676
+ source_uri: "literal:recipe1",
837
677
  links: [
838
678
  { predicate: "recipe://name", target: "Pasta", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" },
839
679
  { predicate: "recipe://rating", target: "5", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" },
@@ -844,7 +684,7 @@ describe("Ad4mModel.instancesFromSurrealResult() and SurrealDB integration", ()
844
684
  },
845
685
  {
846
686
  source: "node:def456",
847
- source_uri: "literal://recipe2",
687
+ source_uri: "literal:recipe2",
848
688
  links: [
849
689
  { predicate: "recipe://name", target: "Pizza", author: "did:key:bob", timestamp: "2023-01-02T00:00:00Z" },
850
690
  { predicate: "recipe://rating", target: "4", author: "did:key:bob", timestamp: "2023-01-02T00:00:00Z" },
@@ -854,7 +694,7 @@ describe("Ad4mModel.instancesFromSurrealResult() and SurrealDB integration", ()
854
694
  ]
855
695
  }
856
696
  ];
857
- const result = await Recipe.instancesFromSurrealResult(mockPerspective, {}, surrealResults);
697
+ const result = await Recipe.instancesFromQueryResult(mockPerspective, {}, queryResults);
858
698
  expect(result.results).toHaveLength(2);
859
699
  expect(result.totalCount).toBe(2);
860
700
  const recipe1 = result.results[0];
@@ -868,10 +708,10 @@ describe("Ad4mModel.instancesFromSurrealResult() and SurrealDB integration", ()
868
708
  expect(recipe2.rating).toBe(4);
869
709
  });
870
710
  it("should filter properties when query specifies properties", async () => {
871
- const surrealResults = [
711
+ const queryResults = [
872
712
  {
873
713
  source: "node:abc123",
874
- source_uri: "literal://recipe1",
714
+ source_uri: "literal:recipe1",
875
715
  links: [
876
716
  { predicate: "recipe://name", target: "Pasta", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" },
877
717
  { predicate: "recipe://rating", target: "5", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" },
@@ -880,7 +720,7 @@ describe("Ad4mModel.instancesFromSurrealResult() and SurrealDB integration", ()
880
720
  ]
881
721
  }
882
722
  ];
883
- const result = await Recipe.instancesFromSurrealResult(mockPerspective, { properties: ["name"] }, surrealResults);
723
+ const result = await Recipe.instancesFromQueryResult(mockPerspective, { properties: ["name"] }, queryResults);
884
724
  expect(result.results).toHaveLength(1);
885
725
  const recipe = result.results[0];
886
726
  expect(recipe.name).toBe("Pasta");
@@ -892,10 +732,10 @@ describe("Ad4mModel.instancesFromSurrealResult() and SurrealDB integration", ()
892
732
  expect(recipe.timestamp).toBeUndefined();
893
733
  });
894
734
  it("should filter properties when query specifies properties", async () => {
895
- const surrealResults = [
735
+ const queryResults = [
896
736
  {
897
737
  source: "node:abc123",
898
- source_uri: "literal://recipe1",
738
+ source_uri: "literal:recipe1",
899
739
  links: [
900
740
  { predicate: "recipe://name", target: "Pasta", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" },
901
741
  { predicate: "recipe://rating", target: "5", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" },
@@ -904,7 +744,7 @@ describe("Ad4mModel.instancesFromSurrealResult() and SurrealDB integration", ()
904
744
  ]
905
745
  }
906
746
  ];
907
- const result = await Recipe.instancesFromSurrealResult(mockPerspective, { properties: ["name"] }, surrealResults);
747
+ const result = await Recipe.instancesFromQueryResult(mockPerspective, { properties: ["name"] }, queryResults);
908
748
  expect(result.results).toHaveLength(1);
909
749
  const recipe = result.results[0];
910
750
  expect(recipe.name).toBe("Pasta");
@@ -912,7 +752,7 @@ describe("Ad4mModel.instancesFromSurrealResult() and SurrealDB integration", ()
912
752
  expect(recipe.rating).toBeUndefined();
913
753
  });
914
754
  it("should handle results missing base field", async () => {
915
- const surrealResults = [
755
+ const queryResults = [
916
756
  {
917
757
  links: [
918
758
  { predicate: "recipe://name", target: "Pasta", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" },
@@ -921,179 +761,149 @@ describe("Ad4mModel.instancesFromSurrealResult() and SurrealDB integration", ()
921
761
  // Missing source field
922
762
  }
923
763
  ];
924
- const result = await Recipe.instancesFromSurrealResult(mockPerspective, {}, surrealResults);
764
+ const result = await Recipe.instancesFromQueryResult(mockPerspective, {}, queryResults);
925
765
  // Should filter out the invalid result (or handle gracefully)
926
766
  expect(result.results).toHaveLength(0);
927
767
  expect(result.totalCount).toBe(0);
928
768
  });
929
- it("should use SurrealDB by default in findAll()", async () => {
930
- const surrealResults = [
931
- {
932
- source: "node:abc123",
933
- source_uri: "literal://recipe1",
934
- links: [
935
- { predicate: "recipe://name", target: "Pasta", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" },
936
- { predicate: "recipe://rating", target: "5", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" },
937
- { predicate: "recipe://ingredient", target: "pasta", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" }
938
- ]
939
- }
769
+ it("should use SPARQL when engine is 'sparql' in findAll()", async () => {
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" }
940
775
  ];
941
- mockPerspective.querySurrealDB.mockResolvedValue(surrealResults);
942
- const results = await Recipe.findAll(mockPerspective, {});
943
- expect(mockPerspective.querySurrealDB).toHaveBeenCalledTimes(1);
776
+ mockPerspective.querySparql.mockResolvedValue(queryResults);
777
+ const results = await Recipe.findAll(mockPerspective, {}, 'sparql');
778
+ expect(mockPerspective.querySparql).toHaveBeenCalledTimes(1);
944
779
  expect(mockPerspective.infer).not.toHaveBeenCalled();
945
780
  expect(results).toHaveLength(1);
946
781
  expect(results[0].name).toBe("Pasta");
947
782
  });
948
- it("should use Prolog when useSurrealDB is false in findAll()", async () => {
783
+ it("should use Prolog when engine is prolog in findAll()", async () => {
949
784
  const prologResults = [{
950
785
  AllInstances: [
951
- ["literal://recipe1", [["name", "Pasta"]], [["ingredients", ["pasta"]]], "2023-01-01T00:00:00Z", "did:key:alice"]
786
+ ["literal:recipe1", [["name", "Pasta"]], [["ingredients", ["pasta"]]], "2023-01-01T00:00:00Z", "did:key:alice"]
952
787
  ],
953
788
  TotalCount: 1
954
789
  }];
955
790
  mockPerspective.infer.mockResolvedValue(prologResults);
956
791
  const results = await Recipe.findAll(mockPerspective, {}, false);
957
792
  expect(mockPerspective.infer).toHaveBeenCalledTimes(1);
958
- expect(mockPerspective.querySurrealDB).not.toHaveBeenCalled();
793
+ expect(mockPerspective.querySparql).not.toHaveBeenCalled();
959
794
  expect(results).toHaveLength(1);
960
795
  });
961
- it("should use SurrealDB by default in findAllAndCount()", async () => {
962
- const surrealResults = [
963
- {
964
- source: "node:abc123",
965
- source_uri: "literal://recipe1",
966
- links: [
967
- { predicate: "recipe://name", target: "Pasta", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" },
968
- { predicate: "recipe://rating", target: "5", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" },
969
- { predicate: "recipe://ingredient", target: "pasta", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" }
970
- ]
971
- }
796
+ it("should use SPARQL when engine is 'sparql' in findAllAndCount()", async () => {
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" }
972
801
  ];
973
- mockPerspective.querySurrealDB.mockResolvedValue(surrealResults);
974
- const { results, totalCount } = await Recipe.findAllAndCount(mockPerspective, {});
975
- expect(mockPerspective.querySurrealDB).toHaveBeenCalledTimes(1);
802
+ mockPerspective.querySparql.mockResolvedValue(queryResults);
803
+ const { results, totalCount } = await Recipe.findAllAndCount(mockPerspective, {}, 'sparql');
804
+ expect(mockPerspective.querySparql).toHaveBeenCalledTimes(1);
976
805
  expect(mockPerspective.infer).not.toHaveBeenCalled();
977
806
  expect(results).toHaveLength(1);
978
807
  expect(totalCount).toBe(1);
979
808
  });
980
- it("should use SurrealDB by default in paginate()", async () => {
981
- const surrealResults = [
982
- {
983
- source: "node:abc123",
984
- source_uri: "literal://recipe1",
985
- links: [
986
- { predicate: "recipe://name", target: "Pasta", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" },
987
- { predicate: "recipe://rating", target: "5", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" },
988
- { predicate: "recipe://ingredient", target: "pasta", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" }
989
- ]
990
- }
809
+ it("should use SPARQL when engine is 'sparql' in paginate()", async () => {
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" }
991
814
  ];
992
- mockPerspective.querySurrealDB.mockResolvedValue(surrealResults);
993
- const page = await Recipe.paginate(mockPerspective, 10, 1, {});
994
- expect(mockPerspective.querySurrealDB).toHaveBeenCalledTimes(1);
815
+ mockPerspective.querySparql.mockResolvedValue(queryResults);
816
+ const page = await Recipe.paginate(mockPerspective, 10, 1, {}, 'sparql');
817
+ expect(mockPerspective.querySparql).toHaveBeenCalledTimes(1);
995
818
  expect(mockPerspective.infer).not.toHaveBeenCalled();
996
819
  expect(page.results).toHaveLength(1);
997
820
  expect(page.pageSize).toBe(10);
998
821
  expect(page.pageNumber).toBe(1);
999
822
  });
1000
- it("should use SurrealDB by default in count()", async () => {
823
+ it("should use SPARQL when engine is 'sparql' in count()", async () => {
1001
824
  // Since count() uses result.length and GROUP BY returns one row per source,
1002
825
  // mock 5 recipe sources
1003
- const surrealResults = Array.from({ length: 5 }, (_, i) => ({
1004
- source: `node:abc${i + 1}`,
1005
- source_uri: `literal://recipe${i + 1}`,
1006
- links: [
1007
- { predicate: "recipe://name", target: `Recipe ${i + 1}`, author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" },
1008
- { predicate: "recipe://rating", target: "5", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" }
1009
- ]
1010
- }));
1011
- mockPerspective.querySurrealDB.mockResolvedValue(surrealResults);
1012
- const count = await Recipe.count(mockPerspective, {});
1013
- expect(mockPerspective.querySurrealDB).toHaveBeenCalledTimes(1);
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);
1014
835
  expect(mockPerspective.infer).not.toHaveBeenCalled();
1015
836
  expect(count).toBe(5);
1016
837
  });
1017
- it("should use Prolog when useSurrealDB is false in count()", async () => {
838
+ it("should use Prolog when engine is prolog in count()", async () => {
1018
839
  const prologResults = [{ TotalCount: 10 }];
1019
840
  mockPerspective.infer.mockResolvedValue(prologResults);
1020
841
  const count = await Recipe.count(mockPerspective, {}, false);
1021
842
  expect(mockPerspective.infer).toHaveBeenCalledTimes(1);
1022
- expect(mockPerspective.querySurrealDB).not.toHaveBeenCalled();
843
+ expect(mockPerspective.querySparql).not.toHaveBeenCalled();
1023
844
  expect(count).toBe(10);
1024
845
  });
1025
- it("should use SurrealDB by default in ModelQueryBuilder.get()", async () => {
1026
- const surrealResults = [
1027
- {
1028
- source: "node:abc123",
1029
- source_uri: "literal://recipe1",
1030
- links: [
1031
- { predicate: "recipe://name", target: "Pasta", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" },
1032
- { predicate: "recipe://rating", target: "5", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" },
1033
- { predicate: "recipe://ingredient", target: "pasta", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" }
1034
- ]
1035
- }
846
+ it("should use SPARQL when engine is 'sparql' in ModelQueryBuilder.get()", async () => {
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" }
1036
851
  ];
1037
- mockPerspective.querySurrealDB.mockResolvedValue(surrealResults);
852
+ mockPerspective.querySparql.mockResolvedValue(queryResults);
1038
853
  const results = await Recipe.query(mockPerspective)
1039
854
  .where({ name: "Pasta" })
855
+ .engine('sparql')
1040
856
  .get();
1041
- expect(mockPerspective.querySurrealDB).toHaveBeenCalledTimes(1);
857
+ expect(mockPerspective.querySparql).toHaveBeenCalledTimes(1);
1042
858
  expect(mockPerspective.infer).not.toHaveBeenCalled();
1043
859
  expect(results).toHaveLength(1);
1044
860
  expect(results[0].name).toBe("Pasta");
1045
861
  });
1046
- it("should use Prolog when useSurrealDB(false) in ModelQueryBuilder.get()", async () => {
862
+ it("should use Prolog when.engine('prolog') in ModelQueryBuilder.get()", async () => {
1047
863
  const prologResults = [{
1048
864
  AllInstances: [
1049
- ["literal://recipe1", [["name", "Pasta"]], [["ingredients", ["pasta"]]], "2023-01-01T00:00:00Z", "did:key:alice"]
865
+ ["literal:recipe1", [["name", "Pasta"]], [["ingredients", ["pasta"]]], "2023-01-01T00:00:00Z", "did:key:alice"]
1050
866
  ],
1051
867
  TotalCount: 1
1052
868
  }];
1053
869
  mockPerspective.infer.mockResolvedValue(prologResults);
1054
870
  const results = await Recipe.query(mockPerspective)
1055
871
  .where({ name: "Pasta" })
1056
- .useSurrealDB(false)
872
+ .engine('prolog')
1057
873
  .get();
1058
874
  expect(mockPerspective.infer).toHaveBeenCalledTimes(1);
1059
- expect(mockPerspective.querySurrealDB).not.toHaveBeenCalled();
875
+ expect(mockPerspective.querySparql).not.toHaveBeenCalled();
1060
876
  expect(results).toHaveLength(1);
1061
877
  });
1062
- it("should use SurrealDB by default in ModelQueryBuilder.count()", async () => {
878
+ it("should use SPARQL when engine is 'sparql' in ModelQueryBuilder.count()", async () => {
1063
879
  // count() counts the number of rows returned by the query (one row per source)
1064
- const surrealResults = Array.from({ length: 3 }, (_, i) => ({
1065
- source: `node:abc${i + 1}`,
1066
- source_uri: `literal://recipe${i + 1}`,
1067
- links: [
1068
- { predicate: "recipe://name", target: `Recipe ${i + 1}`, author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" },
1069
- { predicate: "recipe://rating", target: "5", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" }
1070
- ]
1071
- }));
1072
- mockPerspective.querySurrealDB.mockResolvedValue(surrealResults);
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);
1073
887
  const count = await Recipe.query(mockPerspective)
1074
888
  .where({ rating: { gt: 4 } })
889
+ .engine('sparql')
1075
890
  .count();
1076
- expect(mockPerspective.querySurrealDB).toHaveBeenCalledTimes(1);
891
+ expect(mockPerspective.querySparql).toHaveBeenCalledTimes(1);
1077
892
  expect(mockPerspective.infer).not.toHaveBeenCalled();
1078
893
  expect(count).toBe(3);
1079
894
  });
1080
- it("should use SurrealDB by default in ModelQueryBuilder.paginate()", async () => {
1081
- const surrealResults = [
1082
- {
1083
- source: "node:abc123",
1084
- source_uri: "literal://recipe1",
1085
- links: [
1086
- { predicate: "recipe://name", target: "Pasta", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" },
1087
- { predicate: "recipe://rating", target: "5", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" },
1088
- { predicate: "recipe://ingredient", target: "pasta", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" }
1089
- ]
1090
- }
895
+ it("should use SPARQL when engine is 'sparql' in ModelQueryBuilder.paginate()", async () => {
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" }
1091
900
  ];
1092
- mockPerspective.querySurrealDB.mockResolvedValue(surrealResults);
901
+ mockPerspective.querySparql.mockResolvedValue(queryResults);
1093
902
  const page = await Recipe.query(mockPerspective)
1094
903
  .where({ rating: { gt: 3 } })
904
+ .engine('sparql')
1095
905
  .paginate(10, 1);
1096
- expect(mockPerspective.querySurrealDB).toHaveBeenCalledTimes(1);
906
+ expect(mockPerspective.querySparql).toHaveBeenCalledTimes(1);
1097
907
  expect(mockPerspective.infer).not.toHaveBeenCalled();
1098
908
  expect(page.results).toHaveLength(1);
1099
909
  expect(page.pageSize).toBe(10);
@@ -1127,7 +937,7 @@ describe("Ad4mModel.count() with advanced where conditions", () => {
1127
937
  ], Recipe);
1128
938
  // Mock perspective
1129
939
  const mockPerspective = {
1130
- querySurrealDB: jest.fn(),
940
+ querySparql: jest.fn(),
1131
941
  infer: jest.fn(),
1132
942
  uuid: 'test-perspective-uuid',
1133
943
  stringOrTemplateObjectToSubjectClassName: jest.fn().mockResolvedValue('Recipe')
@@ -1135,155 +945,139 @@ describe("Ad4mModel.count() with advanced where conditions", () => {
1135
945
  beforeEach(() => {
1136
946
  jest.clearAllMocks();
1137
947
  });
1138
- it("should apply JS-level filtering for gt operator on properties in SurrealDB count()", async () => {
1139
- // Mock SurrealDB results: 5 recipes with ratings 1, 2, 3, 4, 5
1140
- const surrealResults = Array.from({ length: 5 }, (_, i) => ({
1141
- source: `node:abc${i + 1}`,
1142
- source_uri: `literal://recipe${i + 1}`,
1143
- links: [
1144
- { predicate: "recipe://name", target: `Recipe ${i + 1}`, author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" },
1145
- { predicate: "recipe://rating", target: `${i + 1}`, author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" }
1146
- ]
1147
- }));
1148
- mockPerspective.querySurrealDB.mockResolvedValue(surrealResults);
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);
1149
957
  // Count recipes with rating > 3 (should match 2 recipes: rating 4 and 5)
1150
- const count = await Recipe.count(mockPerspective, { where: { rating: { gt: 3 } } });
958
+ const count = await Recipe.count(mockPerspective, { where: { rating: { gt: 3 } } }, 'sparql');
1151
959
  // Verify count matches the number of instances that would be returned by findAll
1152
- const findAllResults = await Recipe.findAll(mockPerspective, { where: { rating: { gt: 3 } } });
960
+ const findAllResults = await Recipe.findAll(mockPerspective, { where: { rating: { gt: 3 } } }, 'sparql');
1153
961
  expect(count).toBe(2);
1154
962
  expect(count).toBe(findAllResults.length);
1155
963
  });
1156
- it("should apply JS-level filtering for between operator on properties in SurrealDB count()", async () => {
1157
- // Mock SurrealDB results: 5 recipes with ratings 1, 2, 3, 4, 5
1158
- const surrealResults = Array.from({ length: 5 }, (_, i) => ({
1159
- source: `node:abc${i + 1}`,
1160
- source_uri: `literal://recipe${i + 1}`,
1161
- links: [
1162
- { predicate: "recipe://name", target: `Recipe ${i + 1}`, author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" },
1163
- { predicate: "recipe://rating", target: `${i + 1}`, author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" }
1164
- ]
1165
- }));
1166
- mockPerspective.querySurrealDB.mockResolvedValue(surrealResults);
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);
1167
973
  // Count recipes with rating between 2 and 4 (should match 3 recipes: rating 2, 3, 4)
1168
- const count = await Recipe.count(mockPerspective, { where: { rating: { between: [2, 4] } } });
974
+ const count = await Recipe.count(mockPerspective, { where: { rating: { between: [2, 4] } } }, 'sparql');
1169
975
  // Verify count matches the number of instances that would be returned by findAll
1170
- const findAllResults = await Recipe.findAll(mockPerspective, { where: { rating: { between: [2, 4] } } });
976
+ const findAllResults = await Recipe.findAll(mockPerspective, { where: { rating: { between: [2, 4] } } }, 'sparql');
1171
977
  expect(count).toBe(3);
1172
978
  expect(count).toBe(findAllResults.length);
1173
979
  });
1174
- it("should apply JS-level filtering for timestamp gt operator in SurrealDB count()", async () => {
1175
- // Mock SurrealDB results: 5 recipes with different timestamps
1176
- const surrealResults = Array.from({ length: 5 }, (_, i) => ({
1177
- source: `node:abc${i + 1}`,
1178
- source_uri: `literal://recipe${i + 1}`,
1179
- links: [
1180
- { predicate: "recipe://name", target: `Recipe ${i + 1}`, author: "did:key:alice", timestamp: `2023-01-0${i + 1}T00:00:00Z` },
1181
- { predicate: "recipe://rating", target: "5", author: "did:key:alice", timestamp: `2023-01-0${i + 1}T00:00:00Z` }
1182
- ]
1183
- }));
1184
- mockPerspective.querySurrealDB.mockResolvedValue(surrealResults);
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);
1185
989
  // Count recipes with timestamp > 2023-01-03 (should match 2 recipes: 2023-01-04 and 2023-01-05)
1186
990
  const targetTimestamp = new Date("2023-01-03T00:00:00Z").getTime();
1187
- const count = await Recipe.count(mockPerspective, { where: { timestamp: { gt: targetTimestamp } } });
991
+ const count = await Recipe.count(mockPerspective, { where: { timestamp: { gt: targetTimestamp } } }, 'sparql');
1188
992
  // Verify count matches the number of instances that would be returned by findAll
1189
- const findAllResults = await Recipe.findAll(mockPerspective, { where: { timestamp: { gt: targetTimestamp } } });
993
+ const findAllResults = await Recipe.findAll(mockPerspective, { where: { timestamp: { gt: targetTimestamp } } }, 'sparql');
1190
994
  expect(count).toBe(2);
1191
995
  expect(count).toBe(findAllResults.length);
1192
996
  });
1193
- it("should apply JS-level filtering for timestamp between operator in SurrealDB count()", async () => {
1194
- // Mock SurrealDB results: 5 recipes with different timestamps
1195
- const surrealResults = Array.from({ length: 5 }, (_, i) => ({
1196
- source: `node:abc${i + 1}`,
1197
- source_uri: `literal://recipe${i + 1}`,
1198
- links: [
1199
- { predicate: "recipe://name", target: `Recipe ${i + 1}`, author: "did:key:alice", timestamp: `2023-01-0${i + 1}T00:00:00Z` },
1200
- { predicate: "recipe://rating", target: "5", author: "did:key:alice", timestamp: `2023-01-0${i + 1}T00:00:00Z` }
1201
- ]
1202
- }));
1203
- mockPerspective.querySurrealDB.mockResolvedValue(surrealResults);
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);
1204
1006
  // Count recipes with timestamp between 2023-01-02 and 2023-01-04
1205
1007
  const startTimestamp = new Date("2023-01-02T00:00:00Z").getTime();
1206
1008
  const endTimestamp = new Date("2023-01-04T00:00:00Z").getTime();
1207
1009
  const count = await Recipe.count(mockPerspective, {
1208
1010
  where: { timestamp: { between: [startTimestamp, endTimestamp] } }
1209
- });
1011
+ }, 'sparql');
1210
1012
  // Verify count matches the number of instances that would be returned by findAll
1211
1013
  const findAllResults = await Recipe.findAll(mockPerspective, {
1212
1014
  where: { timestamp: { between: [startTimestamp, endTimestamp] } }
1213
- });
1015
+ }, 'sparql');
1214
1016
  expect(count).toBe(3);
1215
1017
  expect(count).toBe(findAllResults.length);
1216
1018
  });
1217
- it("should apply JS-level filtering for author filtering in SurrealDB count()", async () => {
1218
- // Mock SurrealDB results: 3 recipes by Alice and 2 by Bob
1219
- const surrealResults = [
1220
- ...Array.from({ length: 3 }, (_, i) => ({
1221
- source: `node:abc${i + 1}`,
1222
- source_uri: `literal://recipe${i + 1}`,
1223
- links: [
1224
- { predicate: "recipe://name", target: `Recipe ${i + 1}`, author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" },
1225
- { predicate: "recipe://rating", target: "5", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" }
1226
- ]
1227
- })),
1228
- ...Array.from({ length: 2 }, (_, i) => ({
1229
- source: `node:def${i + 4}`,
1230
- source_uri: `literal://recipe${i + 4}`,
1231
- links: [
1232
- { predicate: "recipe://name", target: `Recipe ${i + 4}`, author: "did:key:bob", timestamp: "2023-01-02T00:00:00Z" },
1233
- { predicate: "recipe://rating", target: "5", author: "did:key:bob", timestamp: "2023-01-02T00:00:00Z" }
1234
- ]
1235
- }))
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()
1236
1030
  ];
1237
- mockPerspective.querySurrealDB.mockResolvedValue(surrealResults);
1031
+ mockPerspective.querySparql.mockResolvedValue(queryResults);
1238
1032
  // Count recipes by Alice (should match 3 recipes)
1239
- const count = await Recipe.count(mockPerspective, { where: { author: "did:key:alice" } });
1033
+ const count = await Recipe.count(mockPerspective, { where: { author: "did:key:alice" } }, 'sparql');
1240
1034
  // Verify count matches the number of instances that would be returned by findAll
1241
- const findAllResults = await Recipe.findAll(mockPerspective, { where: { author: "did:key:alice" } });
1035
+ const findAllResults = await Recipe.findAll(mockPerspective, { where: { author: "did:key:alice" } }, 'sparql');
1242
1036
  expect(count).toBe(3);
1243
1037
  expect(count).toBe(findAllResults.length);
1244
1038
  });
1245
1039
  it("should apply JS-level filtering in ModelQueryBuilder.count() with gt operator", async () => {
1246
- // Mock SurrealDB results: 5 recipes with ratings 1, 2, 3, 4, 5
1247
- const surrealResults = Array.from({ length: 5 }, (_, i) => ({
1248
- source: `node:abc${i + 1}`,
1249
- source_uri: `literal://recipe${i + 1}`,
1250
- links: [
1251
- { predicate: "recipe://name", target: `Recipe ${i + 1}`, author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" },
1252
- { predicate: "recipe://rating", target: `${i + 1}`, author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" }
1253
- ]
1254
- }));
1255
- mockPerspective.querySurrealDB.mockResolvedValue(surrealResults);
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);
1256
1048
  // Count recipes with rating > 3 using ModelQueryBuilder
1257
1049
  const count = await Recipe.query(mockPerspective)
1258
1050
  .where({ rating: { gt: 3 } })
1051
+ .engine('sparql')
1259
1052
  .count();
1260
1053
  // Verify count matches the number of instances that would be returned by get()
1261
1054
  const getResults = await Recipe.query(mockPerspective)
1262
1055
  .where({ rating: { gt: 3 } })
1056
+ .engine('sparql')
1263
1057
  .get();
1264
1058
  expect(count).toBe(2);
1265
1059
  expect(count).toBe(getResults.length);
1266
1060
  });
1267
1061
  it("should apply JS-level filtering in ModelQueryBuilder.count() with timestamp between", async () => {
1268
- // Mock SurrealDB results: 5 recipes with different timestamps
1269
- const surrealResults = Array.from({ length: 5 }, (_, i) => ({
1270
- source: `node:abc${i + 1}`,
1271
- source_uri: `literal://recipe${i + 1}`,
1272
- links: [
1273
- { predicate: "recipe://name", target: `Recipe ${i + 1}`, author: "did:key:alice", timestamp: `2023-01-0${i + 1}T00:00:00Z` },
1274
- { predicate: "recipe://rating", target: "5", author: "did:key:alice", timestamp: `2023-01-0${i + 1}T00:00:00Z` }
1275
- ]
1276
- }));
1277
- mockPerspective.querySurrealDB.mockResolvedValue(surrealResults);
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);
1278
1070
  const startTimestamp = new Date("2023-01-02T00:00:00Z").getTime();
1279
1071
  const endTimestamp = new Date("2023-01-04T00:00:00Z").getTime();
1280
1072
  // Count using ModelQueryBuilder
1281
1073
  const count = await Recipe.query(mockPerspective)
1282
1074
  .where({ timestamp: { between: [startTimestamp, endTimestamp] } })
1075
+ .engine('sparql')
1283
1076
  .count();
1284
1077
  // Verify count matches the number of instances that would be returned by get()
1285
1078
  const getResults = await Recipe.query(mockPerspective)
1286
1079
  .where({ timestamp: { between: [startTimestamp, endTimestamp] } })
1080
+ .engine('sparql')
1287
1081
  .get();
1288
1082
  expect(count).toBe(3);
1289
1083
  expect(count).toBe(getResults.length);
@@ -1293,7 +1087,7 @@ describe("Ad4mModel.count() with advanced where conditions", () => {
1293
1087
  mockPerspective.infer.mockResolvedValue(prologResults);
1294
1088
  const count = await Recipe.count(mockPerspective, { where: { rating: { gt: 3 } } }, false);
1295
1089
  expect(mockPerspective.infer).toHaveBeenCalledTimes(1);
1296
- expect(mockPerspective.querySurrealDB).not.toHaveBeenCalled();
1090
+ expect(mockPerspective.querySparql).not.toHaveBeenCalled();
1297
1091
  expect(count).toBe(2);
1298
1092
  });
1299
1093
  it("should handle count() with Prolog for timestamp between (legacy)", async () => {
@@ -1303,7 +1097,1214 @@ describe("Ad4mModel.count() with advanced where conditions", () => {
1303
1097
  const endTimestamp = new Date("2023-01-04T00:00:00Z").getTime();
1304
1098
  const count = await Recipe.count(mockPerspective, { where: { timestamp: { between: [startTimestamp, endTimestamp] } } }, false);
1305
1099
  expect(mockPerspective.infer).toHaveBeenCalledTimes(1);
1306
- expect(mockPerspective.querySurrealDB).not.toHaveBeenCalled();
1100
+ expect(mockPerspective.querySparql).not.toHaveBeenCalled();
1307
1101
  expect(count).toBe(3);
1308
1102
  });
1309
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");
1167
+ });
1168
+ });
1169
+ describe("SPARQL comparison filters", () => {
1170
+ let Item = class Item extends Ad4mModel {
1171
+ };
1172
+ __decorate([
1173
+ Property({ through: "item://price", required: true }),
1174
+ __metadata("design:type", String)
1175
+ ], Item.prototype, "price", void 0);
1176
+ __decorate([
1177
+ Property({ through: "item://name", required: true }),
1178
+ __metadata("design:type", String)
1179
+ ], Item.prototype, "name", void 0);
1180
+ Item = __decorate([
1181
+ Model({ name: "Item" })
1182
+ ], Item);
1183
+ it("should generate gt filter", async () => {
1184
+ const mockPersp = { getLinks: jest.fn().mockResolvedValue([]) };
1185
+ const query = await Item.queryToSPARQL(mockPersp, { where: { price: { gt: 10 } } });
1186
+ // gt is now JS post-filter — SPARQL just joins the property
1187
+ expect(query).toContain("item://price");
1188
+ });
1189
+ it("should generate between filter", async () => {
1190
+ const mockPersp = { getLinks: jest.fn().mockResolvedValue([]) };
1191
+ const query = await Item.queryToSPARQL(mockPersp, { where: { price: { between: [5, 20] } } });
1192
+ // between is now JS post-filter
1193
+ expect(query).toContain("item://price");
1194
+ });
1195
+ it("should generate contains filter", async () => {
1196
+ const mockPersp = { getLinks: jest.fn().mockResolvedValue([]) };
1197
+ const query = await Item.queryToSPARQL(mockPersp, { where: { name: { contains: "widget" } } });
1198
+ // contains is now JS post-filter
1199
+ expect(query).toContain("item://name");
1200
+ });
1201
+ });
1202
+ // ──────────────────────────────────────────────────────────
1203
+ // SPARQL Direct Triple Pattern & IRI Tests
1204
+ // ──────────────────────────────────────────────────────────
1205
+ import { buildSPARQLQuery, groupSPARQLResults, formatSPARQLValue, buildSPARQLGetDataQuery } from "./query-sparql";
1206
+ describe("SPARQL direct triple pattern generation", () => {
1207
+ let Channel = class Channel extends Ad4mModel {
1208
+ constructor() {
1209
+ super(...arguments);
1210
+ this.type = "";
1211
+ this.name = "";
1212
+ this.description = "";
1213
+ this.messages = [];
1214
+ }
1215
+ };
1216
+ __decorate([
1217
+ Flag({ through: "flux://entry_type", value: "flux://channel" }),
1218
+ __metadata("design:type", String)
1219
+ ], Channel.prototype, "type", void 0);
1220
+ __decorate([
1221
+ Property({ through: "flux://name", resolveLanguage: "literal", required: true }),
1222
+ __metadata("design:type", String)
1223
+ ], Channel.prototype, "name", void 0);
1224
+ __decorate([
1225
+ Optional({ through: "flux://description" }),
1226
+ __metadata("design:type", String)
1227
+ ], Channel.prototype, "description", void 0);
1228
+ __decorate([
1229
+ HasMany({ through: "flux://has_message" }),
1230
+ __metadata("design:type", Array)
1231
+ ], Channel.prototype, "messages", void 0);
1232
+ Channel = __decorate([
1233
+ Model({ name: "Channel" })
1234
+ ], Channel);
1235
+ const mockPersp = {};
1236
+ it("generates direct triple pattern with ?source ?predicate ?target", async () => {
1237
+ const query = await Channel.queryToSPARQL(mockPersp, {});
1238
+ // Must use direct triple pattern, not link-node reification
1239
+ expect(query).toContain("?source ?predicate ?target");
1240
+ expect(query).not.toContain("rdf:type");
1241
+ expect(query).not.toContain("ad4m:Link");
1242
+ });
1243
+ it("generates Flag filter as ?source <predicate> <value>", async () => {
1244
+ const query = await Channel.queryToSPARQL(mockPersp, {});
1245
+ expect(query).toContain("<flux://entry_type>");
1246
+ expect(query).toContain("<flux://channel>");
1247
+ });
1248
+ it("generates Property binding as ?source <predicate> ?varName", async () => {
1249
+ const query = await Channel.queryToSPARQL(mockPersp, {});
1250
+ expect(query).toContain("<flux://name>");
1251
+ expect(query).toMatch(/\?source\s+<flux:\/\/name>\s+\?cfTarget_name/);
1252
+ });
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 () => {
1260
+ const query = await Channel.queryToSPARQL(mockPersp, {});
1261
+ expect(query).not.toContain("BIND(<<");
1262
+ expect(query).not.toContain("?ann ");
1263
+ });
1264
+ it("uses FILTER(isIRI(?source)) to exclude non-IRI subjects", async () => {
1265
+ const query = await Channel.queryToSPARQL(mockPersp, {});
1266
+ expect(query).toContain("FILTER(isIRI(?source)");
1267
+ });
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
+ });
1315
+ describe("formatSPARQLValue", () => {
1316
+ it("wraps strings in double quotes", () => {
1317
+ expect(formatSPARQLValue("hello")).toBe('"hello"');
1318
+ });
1319
+ it("escapes special characters", () => {
1320
+ expect(formatSPARQLValue('say "hi"')).toBe('"say \\"hi\\""');
1321
+ });
1322
+ it("converts numbers to quoted strings", () => {
1323
+ expect(formatSPARQLValue(42)).toBe('"42"');
1324
+ });
1325
+ });
1326
+ // ──────────────────────────────────────────────────────────
1327
+ // Comprehensive SPARQL migration unit tests
1328
+ // ──────────────────────────────────────────────────────────
1329
+ import { matchesCondition, hydrateFromLinks } from "./hydration";
1330
+ import { Literal } from "../Literal";
1331
+ // Helper: create literal URLs using JSON encoding (which handles all types including booleans)
1332
+ function literalUrl(value) {
1333
+ if (typeof value === 'string')
1334
+ return Literal.from(value).toUrl();
1335
+ // Use JSON encoding for numbers and booleans since Literal.get() doesn't handle boolean: prefix
1336
+ return `literal:json:${encodeURIComponent(JSON.stringify(value))}`;
1337
+ }
1338
+ describe("matchesCondition()", () => {
1339
+ // Simple equality
1340
+ it("simple string equality — match", () => {
1341
+ expect(matchesCondition("hello", "hello")).toBe(true);
1342
+ });
1343
+ it("simple string equality — mismatch", () => {
1344
+ expect(matchesCondition("hello", "world")).toBe(false);
1345
+ });
1346
+ it("simple boolean equality — true", () => {
1347
+ expect(matchesCondition(true, true)).toBe(true);
1348
+ });
1349
+ it("simple boolean equality — false", () => {
1350
+ expect(matchesCondition(false, false)).toBe(true);
1351
+ });
1352
+ it("boolean mismatch", () => {
1353
+ expect(matchesCondition(true, false)).toBe(false);
1354
+ });
1355
+ it("simple number equality", () => {
1356
+ expect(matchesCondition(42, 42)).toBe(true);
1357
+ });
1358
+ it("number mismatch", () => {
1359
+ expect(matchesCondition(42, 99)).toBe(false);
1360
+ });
1361
+ // Array IN clause
1362
+ it("array IN clause — value present", () => {
1363
+ expect(matchesCondition("a", ["a", "b", "c"])).toBe(true);
1364
+ });
1365
+ it("array IN clause — value absent", () => {
1366
+ expect(matchesCondition("d", ["a", "b", "c"])).toBe(false);
1367
+ });
1368
+ // NOT operator
1369
+ it("not operator with string", () => {
1370
+ expect(matchesCondition("bob", { not: "alice" })).toBe(true);
1371
+ expect(matchesCondition("alice", { not: "alice" })).toBe(false);
1372
+ });
1373
+ it("not operator with array (NOT IN)", () => {
1374
+ expect(matchesCondition("a", { not: ["b", "c"] })).toBe(true);
1375
+ expect(matchesCondition("b", { not: ["b", "c"] })).toBe(false);
1376
+ });
1377
+ // Comparison operators
1378
+ it("gt", () => {
1379
+ expect(matchesCondition(10, { gt: 5 })).toBe(true);
1380
+ expect(matchesCondition(5, { gt: 5 })).toBe(false);
1381
+ });
1382
+ it("gte", () => {
1383
+ expect(matchesCondition(5, { gte: 5 })).toBe(true);
1384
+ expect(matchesCondition(4, { gte: 5 })).toBe(false);
1385
+ });
1386
+ it("lt", () => {
1387
+ expect(matchesCondition(3, { lt: 5 })).toBe(true);
1388
+ expect(matchesCondition(5, { lt: 5 })).toBe(false);
1389
+ });
1390
+ it("lte", () => {
1391
+ expect(matchesCondition(5, { lte: 5 })).toBe(true);
1392
+ expect(matchesCondition(6, { lte: 5 })).toBe(false);
1393
+ });
1394
+ it("combined gt + lt (range)", () => {
1395
+ expect(matchesCondition(5, { gt: 3, lt: 7 })).toBe(true);
1396
+ expect(matchesCondition(3, { gt: 3, lt: 7 })).toBe(false);
1397
+ expect(matchesCondition(7, { gt: 3, lt: 7 })).toBe(false);
1398
+ });
1399
+ // Between
1400
+ it("between — inclusive range", () => {
1401
+ expect(matchesCondition(5, { between: [3, 7] })).toBe(true);
1402
+ expect(matchesCondition(3, { between: [3, 7] })).toBe(true);
1403
+ expect(matchesCondition(7, { between: [3, 7] })).toBe(true);
1404
+ expect(matchesCondition(2, { between: [3, 7] })).toBe(false);
1405
+ expect(matchesCondition(8, { between: [3, 7] })).toBe(false);
1406
+ });
1407
+ // Contains
1408
+ it("contains with string", () => {
1409
+ expect(matchesCondition("hello world", { contains: "world" })).toBe(true);
1410
+ expect(matchesCondition("hello world", { contains: "xyz" })).toBe(false);
1411
+ });
1412
+ it("contains with array", () => {
1413
+ expect(matchesCondition(["a", "b", "c"], { contains: "b" })).toBe(true);
1414
+ expect(matchesCondition(["a", "b", "c"], { contains: "d" })).toBe(false);
1415
+ });
1416
+ // Edge cases
1417
+ it("returns false for undefined value with equality check", () => {
1418
+ expect(matchesCondition(undefined, "hello")).toBe(false);
1419
+ });
1420
+ it("returns false for empty string when condition is non-empty", () => {
1421
+ expect(matchesCondition("", "Recipe 2")).toBe(false);
1422
+ });
1423
+ it("returns true for undefined with not operator", () => {
1424
+ expect(matchesCondition(undefined, { not: "hello" })).toBe(true);
1425
+ });
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
+ });
1628
+ describe("buildSPARQLQuery edge cases", () => {
1629
+ let FlagModel = class FlagModel extends Ad4mModel {
1630
+ constructor() {
1631
+ super(...arguments);
1632
+ this.type = "";
1633
+ this.name = "";
1634
+ }
1635
+ };
1636
+ __decorate([
1637
+ Flag({ through: "flag://type", value: "flag://FlagModel" }),
1638
+ __metadata("design:type", String)
1639
+ ], FlagModel.prototype, "type", void 0);
1640
+ __decorate([
1641
+ Property({ through: "flag://name", resolveLanguage: "literal", required: true }),
1642
+ __metadata("design:type", String)
1643
+ ], FlagModel.prototype, "name", void 0);
1644
+ FlagModel = __decorate([
1645
+ Model({ name: "FlagModel" })
1646
+ ], FlagModel);
1647
+ let NoFlagModel = class NoFlagModel extends Ad4mModel {
1648
+ constructor() {
1649
+ super(...arguments);
1650
+ this.title = "";
1651
+ }
1652
+ };
1653
+ __decorate([
1654
+ Property({ through: "noflag://title", resolveLanguage: "literal" }),
1655
+ __metadata("design:type", String)
1656
+ ], NoFlagModel.prototype, "title", void 0);
1657
+ NoFlagModel = __decorate([
1658
+ Model({ name: "NoFlagModel" })
1659
+ ], NoFlagModel);
1660
+ it("adds conformance JOIN for flag + required properties", () => {
1661
+ const metadata = FlagModel.getModelMetadata();
1662
+ const allRelsMeta = {};
1663
+ const sparql = buildSPARQLQuery(metadata, allRelsMeta, {}, FlagModel);
1664
+ // Should contain flag triple pattern
1665
+ expect(sparql).toContain("<flag://type>");
1666
+ expect(sparql).toContain("<flag://FlagModel>");
1667
+ // Should contain required property pattern
1668
+ expect(sparql).toContain("<flag://name>");
1669
+ });
1670
+ it("uses structural subquery when no conformance patterns exist", () => {
1671
+ const metadata = NoFlagModel.getModelMetadata();
1672
+ const allRelsMeta = {};
1673
+ const sparql = buildSPARQLQuery(metadata, allRelsMeta, {}, NoFlagModel);
1674
+ // Should contain structural subquery with DISTINCT
1675
+ expect(sparql).toContain("SELECT DISTINCT ?source");
1676
+ expect(sparql).toContain("<noflag://title>");
1677
+ });
1678
+ it("adds JOIN for where-clause on literal-stored fields", () => {
1679
+ const metadata = FlagModel.getModelMetadata();
1680
+ const allRelsMeta = {};
1681
+ const sparql = buildSPARQLQuery(metadata, allRelsMeta, { where: { name: "test" } }, FlagModel);
1682
+ // Where clause should add a join pattern for name
1683
+ expect(sparql).toContain("flag://name");
1684
+ });
1685
+ it("handles where: {id: 'specific-id'} with FILTER on ?source", () => {
1686
+ const metadata = FlagModel.getModelMetadata();
1687
+ const allRelsMeta = {};
1688
+ const sparql = buildSPARQLQuery(metadata, allRelsMeta, { where: { id: "expr:123" } }, FlagModel);
1689
+ // Should filter by source
1690
+ expect(sparql).toContain("expr:123");
1691
+ });
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
+ });
1772
+ // ── Batch hydration for reverse relations (3.4) ─────────────────────────────
1773
+ describe("Batch hydration for reverse relations", () => {
1774
+ it("batch hydration should correctly group targets by parent instance ID", () => {
1775
+ // Test the grouping logic used in batch SPARQL hydration
1776
+ const sparqlResults = [
1777
+ { target: "inst:1", source: "child:a" },
1778
+ { target: "inst:1", source: "child:b" },
1779
+ { target: "inst:2", source: "child:c" },
1780
+ { target: "inst:3", source: "child:d" },
1781
+ { target: "inst:3", source: "child:e" },
1782
+ { target: "inst:3", source: "child:f" },
1783
+ ];
1784
+ const reverseLinksMap = new Map();
1785
+ for (const row of sparqlResults) {
1786
+ if (!reverseLinksMap.has(row.target))
1787
+ reverseLinksMap.set(row.target, []);
1788
+ reverseLinksMap.get(row.target).push(row.source);
1789
+ }
1790
+ expect(reverseLinksMap.get("inst:1")).toEqual(["child:a", "child:b"]);
1791
+ expect(reverseLinksMap.get("inst:2")).toEqual(["child:c"]);
1792
+ expect(reverseLinksMap.get("inst:3")).toEqual(["child:d", "child:e", "child:f"]);
1793
+ });
1794
+ it("batch hydration should handle empty relation sets without error", () => {
1795
+ const sparqlResults = [];
1796
+ const reverseLinksMap = new Map();
1797
+ for (const row of sparqlResults) {
1798
+ if (!reverseLinksMap.has(row.target))
1799
+ reverseLinksMap.set(row.target, []);
1800
+ reverseLinksMap.get(row.target).push(row.source);
1801
+ }
1802
+ expect(reverseLinksMap.size).toBe(0);
1803
+ expect(reverseLinksMap.get("nonexistent") || []).toEqual([]);
1804
+ });
1805
+ it("batch hydration should return identical results to N+1 hydration (grouping equivalence)", () => {
1806
+ // Simulate N+1: each instance queries separately
1807
+ const instances = [{ id: "inst:1" }, { id: "inst:2" }];
1808
+ const allLinks = [
1809
+ { data: { source: "child:a", predicate: "rel://has", target: "inst:1" } },
1810
+ { data: { source: "child:b", predicate: "rel://has", target: "inst:1" } },
1811
+ { data: { source: "child:c", predicate: "rel://has", target: "inst:2" } },
1812
+ ];
1813
+ // N+1 approach
1814
+ const n1Results = new Map();
1815
+ for (const inst of instances) {
1816
+ const links = allLinks.filter(l => l.data.target === inst.id);
1817
+ n1Results.set(inst.id, links.map(l => l.data.source));
1818
+ }
1819
+ // Batch approach
1820
+ const batchResults = new Map();
1821
+ const sparqlRows = allLinks.map(l => ({ target: l.data.target, source: l.data.source }));
1822
+ for (const row of sparqlRows) {
1823
+ if (!batchResults.has(row.target))
1824
+ batchResults.set(row.target, []);
1825
+ batchResults.get(row.target).push(row.source);
1826
+ }
1827
+ // Results should be identical
1828
+ for (const inst of instances) {
1829
+ expect(batchResults.get(inst.id)).toEqual(n1Results.get(inst.id));
1830
+ }
1831
+ });
1832
+ it("batch hydration with nested includes should use batched queries at each level", () => {
1833
+ // This test verifies the structure: nested includes result in multiple
1834
+ // batch operations, one per relation depth level
1835
+ const depth0Rows = [
1836
+ { target: "root:1", source: "mid:a" },
1837
+ { target: "root:1", source: "mid:b" },
1838
+ ];
1839
+ const depth1Rows = [
1840
+ { target: "mid:a", source: "leaf:x" },
1841
+ { target: "mid:b", source: "leaf:y" },
1842
+ ];
1843
+ // Group each level
1844
+ const level0Map = new Map();
1845
+ for (const r of depth0Rows) {
1846
+ if (!level0Map.has(r.target))
1847
+ level0Map.set(r.target, []);
1848
+ level0Map.get(r.target).push(r.source);
1849
+ }
1850
+ const level1Map = new Map();
1851
+ for (const r of depth1Rows) {
1852
+ if (!level1Map.has(r.target))
1853
+ level1Map.set(r.target, []);
1854
+ level1Map.get(r.target).push(r.source);
1855
+ }
1856
+ expect(level0Map.get("root:1")).toEqual(["mid:a", "mid:b"]);
1857
+ expect(level1Map.get("mid:a")).toEqual(["leaf:x"]);
1858
+ expect(level1Map.get("mid:b")).toEqual(["leaf:y"]);
1859
+ });
1860
+ });
1861
+ // ── Push-down FILTER for literal equality (3.5) ──────────────────────────────
1862
+ describe("Push-down FILTER for literal equality", () => {
1863
+ const mockPerspective = {};
1864
+ let FilterTest = class FilterTest extends Ad4mModel {
1865
+ constructor() {
1866
+ super(...arguments);
1867
+ this.name = "";
1868
+ this.rating = 0;
1869
+ }
1870
+ };
1871
+ __decorate([
1872
+ Property({ through: "ft://name", required: true }),
1873
+ __metadata("design:type", String)
1874
+ ], FilterTest.prototype, "name", void 0);
1875
+ __decorate([
1876
+ Property({ through: "ft://rating", required: true }),
1877
+ __metadata("design:type", Number)
1878
+ ], FilterTest.prototype, "rating", void 0);
1879
+ FilterTest = __decorate([
1880
+ Model({ name: "FilterTest" })
1881
+ ], FilterTest);
1882
+ const normalizeQuery = (q) => q.replace(/\s+/g, " ").trim();
1883
+ it("SPARQL query for where: { name: 'Alice' } should use <ad4m://fn/parse_literal> FILTER", async () => {
1884
+ const query = await FilterTest.queryToSPARQL(mockPerspective, { where: { name: "Alice" } });
1885
+ const norm = normalizeQuery(query);
1886
+ // JOIN pattern exists
1887
+ expect(norm).toContain("?wTarget_name");
1888
+ // parse_literal push-down FILTER is present (using correct SPARQL IRI syntax)
1889
+ expect(norm).toContain("ad4m://fn/parse_literal");
1890
+ expect(norm).not.toContain("fn::parse_literal");
1891
+ });
1892
+ it("SPARQL query for where: { name: ['Alice', 'Bob'] } should use <ad4m://fn/parse_literal> IN FILTER", async () => {
1893
+ const query = await FilterTest.queryToSPARQL(mockPerspective, { where: { name: ["Alice", "Bob"] } });
1894
+ const norm = normalizeQuery(query);
1895
+ expect(norm).toContain("?wTarget_name");
1896
+ expect(norm).toContain("ad4m://fn/parse_literal");
1897
+ expect(norm).not.toContain("fn::parse_literal");
1898
+ });
1899
+ it("SPARQL query for where: { rating: { gt: 5 } } should NOT include parse_literal FILTER", async () => {
1900
+ const query = await FilterTest.queryToSPARQL(mockPerspective, { where: { rating: { gt: 5 } } });
1901
+ const norm = normalizeQuery(query);
1902
+ expect(norm).not.toContain("parse_literal");
1903
+ });
1904
+ it("literal property where clause adds JOIN for JS post-filter", async () => {
1905
+ const query = await FilterTest.queryToSPARQL(mockPerspective, { where: { name: "Alice" } });
1906
+ const norm = normalizeQuery(query);
1907
+ expect(norm).toContain("?wTarget_name");
1908
+ });
1909
+ });
1910
+ // ── Lightweight fingerprint (3.7) ────────────────────────────────────────────
1911
+ describe("Lightweight fingerprint optimization", () => {
1912
+ // Replicate the buildFingerprint logic for testing
1913
+ const buildFingerprint = (results) => {
1914
+ if (results.length === 0)
1915
+ return '0:';
1916
+ const ids = results.map((r) => r.id || '').sort().join(',');
1917
+ const ts = results.map((r) => r.updatedAt || r.timestamp || '').join(',');
1918
+ return `${results.length}:${ids}:${ts}`;
1919
+ };
1920
+ const base = [
1921
+ { id: "a", updatedAt: "100" },
1922
+ { id: "b", updatedAt: "200" },
1923
+ ];
1924
+ it("lightweight fingerprint should detect instance addition", () => {
1925
+ const fp1 = buildFingerprint(base);
1926
+ const fp2 = buildFingerprint([...base, { id: "c", updatedAt: "300" }]);
1927
+ expect(fp1).not.toBe(fp2);
1928
+ });
1929
+ it("lightweight fingerprint should detect instance removal", () => {
1930
+ const fp1 = buildFingerprint(base);
1931
+ const fp2 = buildFingerprint([base[0]]);
1932
+ expect(fp1).not.toBe(fp2);
1933
+ });
1934
+ it("lightweight fingerprint should detect timestamp change", () => {
1935
+ const fp1 = buildFingerprint(base);
1936
+ const fp2 = buildFingerprint([{ id: "a", updatedAt: "999" }, base[1]]);
1937
+ expect(fp1).not.toBe(fp2);
1938
+ });
1939
+ it("lightweight fingerprint should NOT false-positive for identical sets", () => {
1940
+ const fp1 = buildFingerprint(base);
1941
+ const fp2 = buildFingerprint([...base]); // same data, new array
1942
+ expect(fp1).toBe(fp2);
1943
+ });
1944
+ });
1945
+ // ── Native SPARQL getter evaluation ──────────────────────────────────────────
1946
+ describe("Native SPARQL getter evaluation", () => {
1947
+ const { evaluateCustomGettersForInstance } = require("./hydration");
1948
+ const mockPerspective = {
1949
+ getLinks: jest.fn().mockResolvedValue([]),
1950
+ querySparql: jest.fn(),
1951
+ get: jest.fn().mockResolvedValue([]),
1952
+ };
1953
+ beforeEach(() => {
1954
+ jest.clearAllMocks();
1955
+ });
1956
+ it("should execute SELECT getter directly via querySparql", async () => {
1957
+ const metadata = {
1958
+ properties: {
1959
+ replyingTo: {
1960
+ predicate: "flux://has_reply",
1961
+ getter: 'SELECT ?target WHERE { ?target <flux://has_reply> ?source . } LIMIT 1',
1962
+ type: "string",
1963
+ }
1964
+ },
1965
+ relations: {},
1966
+ };
1967
+ mockPerspective.querySparql.mockResolvedValue([
1968
+ { target: { value: "literal:string:msg123" } }
1969
+ ]);
1970
+ const instance = { id: "test://msg1", replyingTo: undefined };
1971
+ await evaluateCustomGettersForInstance(instance, mockPerspective, metadata);
1972
+ expect(mockPerspective.querySparql).toHaveBeenCalledWith(expect.stringContaining("SELECT ?target WHERE"));
1973
+ expect(instance.replyingTo).toBe("literal:string:msg123");
1974
+ });
1975
+ it("should execute ASK getter and return boolean", async () => {
1976
+ const metadata = {
1977
+ properties: {
1978
+ isPopular: {
1979
+ predicate: "flux://is_popular",
1980
+ getter: 'ASK WHERE { SELECT (COUNT(DISTINCT ?reactor) AS ?count) WHERE { ?reactor <flux://reaction> ?source . } HAVING(?count > 5) }',
1981
+ type: "boolean",
1982
+ readOnly: true,
1983
+ }
1984
+ },
1985
+ relations: {},
1986
+ };
1987
+ mockPerspective.querySparql.mockResolvedValue(true);
1988
+ const instance = { id: "test://msg1", isPopular: false };
1989
+ await evaluateCustomGettersForInstance(instance, mockPerspective, metadata);
1990
+ expect(mockPerspective.querySparql).toHaveBeenCalledWith(expect.stringContaining("ASK WHERE"));
1991
+ expect(instance.isPopular).toBe(true);
1992
+ });
1993
+ it("should replace ?source with instance ID in SPARQL getter", async () => {
1994
+ const metadata = {
1995
+ properties: {
1996
+ author: {
1997
+ predicate: "test://author",
1998
+ getter: 'SELECT ?target WHERE { ?source <test://author> ?target . }',
1999
+ type: "string",
2000
+ }
2001
+ },
2002
+ relations: {},
2003
+ };
2004
+ mockPerspective.querySparql.mockResolvedValue([
2005
+ { target: { value: "did:key:abc123" } }
2006
+ ]);
2007
+ const instance = { id: "test://post1", author: undefined };
2008
+ await evaluateCustomGettersForInstance(instance, mockPerspective, metadata);
2009
+ expect(mockPerspective.querySparql).toHaveBeenCalledWith(expect.stringContaining("<test://post1>"));
2010
+ expect(mockPerspective.querySparql).not.toHaveBeenCalledWith(expect.stringContaining("?source"));
2011
+ });
2012
+ it("should handle empty SPARQL results gracefully", async () => {
2013
+ const metadata = {
2014
+ properties: {
2015
+ replyingTo: {
2016
+ predicate: "flux://has_reply",
2017
+ getter: 'SELECT ?target WHERE { ?target <flux://has_reply> ?source . } LIMIT 1',
2018
+ type: "string",
2019
+ }
2020
+ },
2021
+ relations: {},
2022
+ };
2023
+ mockPerspective.querySparql.mockResolvedValue([]);
2024
+ const instance = { id: "test://msg1", replyingTo: "original" };
2025
+ await evaluateCustomGettersForInstance(instance, mockPerspective, metadata);
2026
+ // Should not overwrite with undefined
2027
+ expect(instance.replyingTo).toBe("original");
2028
+ });
2029
+ it("should handle SPARQL getter errors without crashing", async () => {
2030
+ const metadata = {
2031
+ properties: {
2032
+ broken: {
2033
+ predicate: "test://broken",
2034
+ getter: 'SELECT ?target WHERE { INVALID SPARQL }',
2035
+ type: "string",
2036
+ }
2037
+ },
2038
+ relations: {},
2039
+ };
2040
+ mockPerspective.querySparql.mockRejectedValue(new Error("SPARQL parse error"));
2041
+ const instance = { id: "test://msg1", broken: undefined };
2042
+ const consoleSpy = jest.spyOn(console, "warn").mockImplementation();
2043
+ await evaluateCustomGettersForInstance(instance, mockPerspective, metadata);
2044
+ consoleSpy.mockRestore();
2045
+ // Should not throw, should warn
2046
+ expect(instance.broken).toBeUndefined();
2047
+ });
2048
+ it("should execute SPARQL getter for relations", async () => {
2049
+ const metadata = {
2050
+ properties: {},
2051
+ relations: {
2052
+ tags: {
2053
+ predicate: "test://has_tag",
2054
+ getter: 'SELECT ?target WHERE { ?source <test://has_tag> ?target . }',
2055
+ direction: "forward",
2056
+ }
2057
+ },
2058
+ };
2059
+ mockPerspective.querySparql.mockResolvedValue([
2060
+ { target: { value: "tag:a" } },
2061
+ { target: { value: "tag:b" } },
2062
+ ]);
2063
+ const instance = { id: "test://post1", tags: [] };
2064
+ await evaluateCustomGettersForInstance(instance, mockPerspective, metadata);
2065
+ expect(instance.tags).toEqual(["tag:a", "tag:b"]);
2066
+ });
2067
+ it("should warn for legacy SurrealDB-style getter syntax instead of converting", async () => {
2068
+ const metadata = {
2069
+ properties: {
2070
+ legacy: {
2071
+ predicate: "test://legacy",
2072
+ getter: "(<-link[WHERE predicate = 'test://legacy'].in.uri)[0]",
2073
+ type: "string",
2074
+ }
2075
+ },
2076
+ relations: {},
2077
+ };
2078
+ const warnSpy = jest.spyOn(console, 'warn').mockImplementation(() => { });
2079
+ const instance = { id: "test://msg1", legacy: undefined };
2080
+ await evaluateCustomGettersForInstance(instance, mockPerspective, metadata);
2081
+ // Should NOT call querySparql — legacy getters are no longer converted
2082
+ expect(mockPerspective.querySparql).not.toHaveBeenCalled();
2083
+ // Should warn about unsupported syntax
2084
+ expect(warnSpy).toHaveBeenCalledWith(expect.stringContaining("Unsupported legacy getter syntax"));
2085
+ // Value should remain undefined
2086
+ expect(instance.legacy).toBeUndefined();
2087
+ warnSpy.mockRestore();
2088
+ });
2089
+ });
2090
+ // ── Subscribe callback timing ──────────────────────────────────────────
2091
+ describe("ModelQueryBuilder subscribe callback timing", () => {
2092
+ it("subscribe should not invoke callback synchronously before Promise resolves", async () => {
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.
2096
+ const mockPerspective = {
2097
+ getLinks: jest.fn().mockResolvedValue([]),
2098
+ subscribeQuery: jest.fn().mockResolvedValue({
2099
+ result: '[]',
2100
+ onResult: jest.fn(),
2101
+ dispose: jest.fn(),
2102
+ }),
2103
+ querySparql: jest.fn().mockResolvedValue('[]'),
2104
+ };
2105
+ const { Ad4mModel, Model, Property, Flag } = require("./index");
2106
+ let TimingTest = class TimingTest extends Ad4mModel {
2107
+ constructor() {
2108
+ super(...arguments);
2109
+ this.type = "test://timing";
2110
+ this.name = "";
2111
+ }
2112
+ };
2113
+ __decorate([
2114
+ Flag({ through: "test://type", value: "test://timing" }),
2115
+ __metadata("design:type", String)
2116
+ ], TimingTest.prototype, "type", void 0);
2117
+ __decorate([
2118
+ Property({ through: "test://name" }),
2119
+ __metadata("design:type", String)
2120
+ ], TimingTest.prototype, "name", void 0);
2121
+ TimingTest = __decorate([
2122
+ Model({ name: "TimingTest" })
2123
+ ], TimingTest);
2124
+ let callbackInvokedBeforeResolve = false;
2125
+ let promiseResolved = false;
2126
+ const query = TimingTest.query(mockPerspective);
2127
+ const promise = query.subscribe((results) => {
2128
+ if (!promiseResolved) {
2129
+ callbackInvokedBeforeResolve = true;
2130
+ }
2131
+ });
2132
+ // At this point the Promise hasn't resolved yet
2133
+ // The callback should NOT have fired synchronously
2134
+ expect(callbackInvokedBeforeResolve).toBe(false);
2135
+ await promise;
2136
+ promiseResolved = true;
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
2140
+ });
2141
+ });
2142
+ // ============================================================================
2143
+ // Performance Optimisation Tests
2144
+ // ============================================================================
2145
+ import { getCachedResult, setCachedResult, clearQueryCache, queryCacheSize } from "./query-cache";
2146
+ import { getPropertiesMetadata, getRelationsMetadata } from "./decorators";
2147
+ describe("QueryCache", () => {
2148
+ beforeEach(() => clearQueryCache());
2149
+ it("should return undefined for cache miss", () => {
2150
+ expect(getCachedResult("uuid1", "SELECT ?s WHERE {}")).toBeUndefined();
2151
+ });
2152
+ it("should return cached result within TTL", () => {
2153
+ const result = [{ s: "test" }];
2154
+ setCachedResult("uuid1", "SELECT ?s WHERE {}", result);
2155
+ expect(getCachedResult("uuid1", "SELECT ?s WHERE {}")).toBe(result);
2156
+ });
2157
+ it("should expire after TTL", async () => {
2158
+ setCachedResult("uuid1", "SELECT ?s WHERE {}", [{ s: "test" }], 50);
2159
+ await new Promise(r => setTimeout(r, 60));
2160
+ expect(getCachedResult("uuid1", "SELECT ?s WHERE {}")).toBeUndefined();
2161
+ });
2162
+ it("should cache independently per perspective", () => {
2163
+ setCachedResult("uuid1", "SELECT ?s WHERE {}", "result1");
2164
+ setCachedResult("uuid2", "SELECT ?s WHERE {}", "result2");
2165
+ expect(getCachedResult("uuid1", "SELECT ?s WHERE {}")).toBe("result1");
2166
+ expect(getCachedResult("uuid2", "SELECT ?s WHERE {}")).toBe("result2");
2167
+ });
2168
+ it("should cache independently per query", () => {
2169
+ setCachedResult("uuid1", "query1", "r1");
2170
+ setCachedResult("uuid1", "query2", "r2");
2171
+ expect(getCachedResult("uuid1", "query1")).toBe("r1");
2172
+ expect(getCachedResult("uuid1", "query2")).toBe("r2");
2173
+ });
2174
+ it("should clear all entries", () => {
2175
+ setCachedResult("uuid1", "q1", "r1");
2176
+ setCachedResult("uuid2", "q2", "r2");
2177
+ expect(queryCacheSize()).toBe(2);
2178
+ clearQueryCache();
2179
+ expect(queryCacheSize()).toBe(0);
2180
+ });
2181
+ });
2182
+ describe("SHACL Memoisation", () => {
2183
+ it("should memoise generateSHACL() per class", () => {
2184
+ let MemoTest1 = class MemoTest1 extends Ad4mModel {
2185
+ constructor() {
2186
+ super(...arguments);
2187
+ this.name = "";
2188
+ }
2189
+ };
2190
+ __decorate([
2191
+ Property({ through: "test://name" }),
2192
+ __metadata("design:type", String)
2193
+ ], MemoTest1.prototype, "name", void 0);
2194
+ MemoTest1 = __decorate([
2195
+ Model({ name: "MemoTest1" })
2196
+ ], MemoTest1);
2197
+ const result1 = MemoTest1.generateSHACL();
2198
+ const result2 = MemoTest1.generateSHACL();
2199
+ expect(result1).toBe(result2); // Same reference = memoised
2200
+ });
2201
+ it("should memoise getPropertiesMetadata per class", () => {
2202
+ let PropMemoTest = class PropMemoTest extends Ad4mModel {
2203
+ constructor() {
2204
+ super(...arguments);
2205
+ this.x = "";
2206
+ }
2207
+ };
2208
+ __decorate([
2209
+ Property({ through: "test://x" }),
2210
+ __metadata("design:type", String)
2211
+ ], PropMemoTest.prototype, "x", void 0);
2212
+ PropMemoTest = __decorate([
2213
+ Model({ name: "PropMemoTest" })
2214
+ ], PropMemoTest);
2215
+ const r1 = getPropertiesMetadata(PropMemoTest);
2216
+ const r2 = getPropertiesMetadata(PropMemoTest);
2217
+ expect(r1).toBe(r2); // Same reference
2218
+ });
2219
+ it("should memoise getRelationsMetadata per class", () => {
2220
+ let RelMemoTest = class RelMemoTest extends Ad4mModel {
2221
+ constructor() {
2222
+ super(...arguments);
2223
+ this.items = [];
2224
+ }
2225
+ };
2226
+ __decorate([
2227
+ HasMany({ through: "test://items" }),
2228
+ __metadata("design:type", Array)
2229
+ ], RelMemoTest.prototype, "items", void 0);
2230
+ RelMemoTest = __decorate([
2231
+ Model({ name: "RelMemoTest" })
2232
+ ], RelMemoTest);
2233
+ const r1 = getRelationsMetadata(RelMemoTest);
2234
+ const r2 = getRelationsMetadata(RelMemoTest);
2235
+ expect(r1).toBe(r2); // Same reference
2236
+ });
2237
+ it("should return different results for different classes", () => {
2238
+ let ClassA = class ClassA extends Ad4mModel {
2239
+ constructor() {
2240
+ super(...arguments);
2241
+ this.a = "";
2242
+ }
2243
+ };
2244
+ __decorate([
2245
+ Property({ through: "test://a" }),
2246
+ __metadata("design:type", String)
2247
+ ], ClassA.prototype, "a", void 0);
2248
+ ClassA = __decorate([
2249
+ Model({ name: "ClassA" })
2250
+ ], ClassA);
2251
+ let ClassB = class ClassB extends Ad4mModel {
2252
+ constructor() {
2253
+ super(...arguments);
2254
+ this.b = "";
2255
+ }
2256
+ };
2257
+ __decorate([
2258
+ Property({ through: "test://b" }),
2259
+ __metadata("design:type", String)
2260
+ ], ClassB.prototype, "b", void 0);
2261
+ ClassB = __decorate([
2262
+ Model({ name: "ClassB" })
2263
+ ], ClassB);
2264
+ const propsA = getPropertiesMetadata(ClassA);
2265
+ const propsB = getPropertiesMetadata(ClassB);
2266
+ expect(propsA).not.toBe(propsB);
2267
+ expect(propsA).toHaveProperty("a");
2268
+ expect(propsB).toHaveProperty("b");
2269
+ });
2270
+ });
2271
+ describe("Lazy Conformance Filters", () => {
2272
+ it("should defer conformance filter resolution until property access", () => {
2273
+ let LazyTarget2 = class LazyTarget2 extends Ad4mModel {
2274
+ constructor() {
2275
+ super(...arguments);
2276
+ this.type = "test://lazy";
2277
+ this.name = "";
2278
+ }
2279
+ };
2280
+ __decorate([
2281
+ Flag({ through: "test://type", value: "test://lazy" }),
2282
+ __metadata("design:type", String)
2283
+ ], LazyTarget2.prototype, "type", void 0);
2284
+ __decorate([
2285
+ Property({ through: "test://name", required: true }),
2286
+ __metadata("design:type", String)
2287
+ ], LazyTarget2.prototype, "name", void 0);
2288
+ LazyTarget2 = __decorate([
2289
+ Model({ name: "LazyTarget2" })
2290
+ ], LazyTarget2);
2291
+ let LazyParent2 = class LazyParent2 extends Ad4mModel {
2292
+ constructor() {
2293
+ super(...arguments);
2294
+ this.children = [];
2295
+ }
2296
+ };
2297
+ __decorate([
2298
+ HasMany(() => LazyTarget2, { through: "test://children" }),
2299
+ __metadata("design:type", Array)
2300
+ ], LazyParent2.prototype, "children", void 0);
2301
+ LazyParent2 = __decorate([
2302
+ Model({ name: "LazyParent2" })
2303
+ ], LazyParent2);
2304
+ // generateSHACL was called during @Model — the shape exists
2305
+ const shacl = LazyParent2.generateSHACL();
2306
+ expect(shacl).toBeDefined();
2307
+ expect(shacl.shape).toBeDefined();
2308
+ expect(shacl.name).toBe("LazyParent2");
2309
+ });
2310
+ });