@coasys/ad4m 0.12.1-dev → 0.13.0-postmessage-ws-proxy.3

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 (393) hide show
  1. package/README.md +2 -25
  2. package/jest-setup.ts +1 -1
  3. package/lib/index.cjs +8677 -15318
  4. package/lib/index.js +14507 -21223
  5. package/lib/src/Ad4mClient.d.ts +9 -3
  6. package/lib/src/Ad4mClient.js +40 -13
  7. package/lib/src/Literal.js +6 -5
  8. package/lib/src/agent/Agent.js +26 -272
  9. package/lib/src/agent/AgentClient.d.ts +33 -21
  10. package/lib/src/agent/AgentClient.js +180 -374
  11. package/lib/src/agent/AgentStatus.js +2 -37
  12. package/lib/src/ai/AIClient.d.ts +12 -4
  13. package/lib/src/ai/AIClient.js +81 -285
  14. package/lib/src/ai/AITypes.d.ts +55 -0
  15. package/lib/src/ai/AITypes.js +18 -0
  16. package/lib/src/ai/Tasks.js +10 -133
  17. package/lib/src/apiClient.d.ts +53 -0
  18. package/lib/src/apiClient.js +234 -0
  19. package/lib/src/cache/PersistentCache.d.ts +40 -0
  20. package/lib/src/cache/PersistentCache.js +139 -0
  21. package/lib/src/expression/Expression.d.ts +1 -1
  22. package/lib/src/expression/Expression.js +13 -122
  23. package/lib/src/expression/ExpressionClient.d.ts +11 -3
  24. package/lib/src/expression/ExpressionClient.js +120 -75
  25. package/lib/src/expression/ExpressionRef.js +4 -27
  26. package/lib/src/generated/api/AIModelLoadingStatus.d.ts +7 -0
  27. package/lib/src/generated/api/AIModelLoadingStatus.js +2 -0
  28. package/lib/src/generated/api/AddLinkExpressionRequest.d.ts +6 -0
  29. package/lib/src/generated/api/AddLinkExpressionRequest.js +1 -0
  30. package/lib/src/generated/api/AddLinkRequest.d.ts +6 -0
  31. package/lib/src/generated/api/AddLinkRequest.js +1 -0
  32. package/lib/src/generated/api/AddLinksBulkRequest.d.ts +6 -0
  33. package/lib/src/generated/api/AddLinksBulkRequest.js +1 -0
  34. package/lib/src/generated/api/AddSdnaRequest.d.ts +6 -0
  35. package/lib/src/generated/api/AddSdnaRequest.js +2 -0
  36. package/lib/src/generated/api/ApplyTemplateRequest.d.ts +4 -0
  37. package/lib/src/generated/api/ApplyTemplateRequest.js +2 -0
  38. package/lib/src/generated/api/AuthInfoInput.d.ts +10 -0
  39. package/lib/src/generated/api/AuthInfoInput.js +1 -0
  40. package/lib/src/generated/api/CapabilityInput.d.ts +5 -0
  41. package/lib/src/generated/api/CapabilityInput.js +1 -0
  42. package/lib/src/generated/api/CommitBatchRequest.d.ts +3 -0
  43. package/lib/src/generated/api/CommitBatchRequest.js +2 -0
  44. package/lib/src/generated/api/ComputeLogEntry.d.ts +9 -0
  45. package/lib/src/generated/api/ComputeLogEntry.js +2 -0
  46. package/lib/src/generated/api/CreateExpressionRequest.d.ts +4 -0
  47. package/lib/src/generated/api/CreateExpressionRequest.js +2 -0
  48. package/lib/src/generated/api/CreatePerspectiveRequest.d.ts +3 -0
  49. package/lib/src/generated/api/CreatePerspectiveRequest.js +2 -0
  50. package/lib/src/generated/api/CreateSubjectRequest.d.ts +6 -0
  51. package/lib/src/generated/api/CreateSubjectRequest.js +2 -0
  52. package/lib/src/generated/api/EmbedRequest.d.ts +4 -0
  53. package/lib/src/generated/api/EmbedRequest.js +2 -0
  54. package/lib/src/generated/api/EntanglementProofInput.d.ts +6 -0
  55. package/lib/src/generated/api/EntanglementProofInput.js +2 -0
  56. package/lib/src/generated/api/ExecuteCommandsRequest.d.ts +4 -0
  57. package/lib/src/generated/api/ExecuteCommandsRequest.js +2 -0
  58. package/lib/src/generated/api/ExportRequest.d.ts +5 -0
  59. package/lib/src/generated/api/ExportRequest.js +2 -0
  60. package/lib/src/generated/api/ExpressionManyRequest.d.ts +3 -0
  61. package/lib/src/generated/api/ExpressionManyRequest.js +2 -0
  62. package/lib/src/generated/api/ExpressionProof.d.ts +4 -0
  63. package/lib/src/generated/api/ExpressionProof.js +2 -0
  64. package/lib/src/generated/api/ExpressionProofInput.d.ts +6 -0
  65. package/lib/src/generated/api/ExpressionProofInput.js +2 -0
  66. package/lib/src/generated/api/FriendSendMessageRequest.d.ts +3 -0
  67. package/lib/src/generated/api/FriendSendMessageRequest.js +2 -0
  68. package/lib/src/generated/api/FriendsListRequest.d.ts +3 -0
  69. package/lib/src/generated/api/FriendsListRequest.js +2 -0
  70. package/lib/src/generated/api/GenerateAgentRequest.d.ts +3 -0
  71. package/lib/src/generated/api/GenerateAgentRequest.js +2 -0
  72. package/lib/src/generated/api/GenerateJwtRequest.d.ts +4 -0
  73. package/lib/src/generated/api/GenerateJwtRequest.js +2 -0
  74. package/lib/src/generated/api/GetSubjectDataRequest.d.ts +4 -0
  75. package/lib/src/generated/api/GetSubjectDataRequest.js +2 -0
  76. package/lib/src/generated/api/ImportAgentRequest.d.ts +6 -0
  77. package/lib/src/generated/api/ImportAgentRequest.js +2 -0
  78. package/lib/src/generated/api/ImportRequest.d.ts +4 -0
  79. package/lib/src/generated/api/ImportRequest.js +2 -0
  80. package/lib/src/generated/api/JoinNeighbourhoodRequest.d.ts +3 -0
  81. package/lib/src/generated/api/JoinNeighbourhoodRequest.js +2 -0
  82. package/lib/src/generated/api/LanguageMetaInput.d.ts +6 -0
  83. package/lib/src/generated/api/LanguageMetaInput.js +2 -0
  84. package/lib/src/generated/api/Link.d.ts +5 -0
  85. package/lib/src/generated/api/Link.js +2 -0
  86. package/lib/src/generated/api/LinkExpression.d.ts +10 -0
  87. package/lib/src/generated/api/LinkExpression.js +1 -0
  88. package/lib/src/generated/api/LinkExpressionInput.d.ts +10 -0
  89. package/lib/src/generated/api/LinkExpressionInput.js +1 -0
  90. package/lib/src/generated/api/LinkInput.d.ts +5 -0
  91. package/lib/src/generated/api/LinkInput.js +2 -0
  92. package/lib/src/generated/api/LinkLanguageTemplatesRequest.d.ts +3 -0
  93. package/lib/src/generated/api/LinkLanguageTemplatesRequest.js +2 -0
  94. package/lib/src/generated/api/LinkMutations.d.ts +6 -0
  95. package/lib/src/generated/api/LinkMutations.js +1 -0
  96. package/lib/src/generated/api/LinkStatus.d.ts +1 -0
  97. package/lib/src/generated/api/LinkStatus.js +2 -0
  98. package/lib/src/generated/api/LockAgentRequest.d.ts +3 -0
  99. package/lib/src/generated/api/LockAgentRequest.js +2 -0
  100. package/lib/src/generated/api/ModelType.d.ts +1 -0
  101. package/lib/src/generated/api/ModelType.js +2 -0
  102. package/lib/src/generated/api/NotificationInput.d.ts +10 -0
  103. package/lib/src/generated/api/NotificationInput.js +2 -0
  104. package/lib/src/generated/api/OpenLinkRequest.d.ts +3 -0
  105. package/lib/src/generated/api/OpenLinkRequest.js +2 -0
  106. package/lib/src/generated/api/PermitCapabilityRequest.d.ts +3 -0
  107. package/lib/src/generated/api/PermitCapabilityRequest.js +2 -0
  108. package/lib/src/generated/api/PerspectiveInput.d.ts +4 -0
  109. package/lib/src/generated/api/PerspectiveInput.js +1 -0
  110. package/lib/src/generated/api/PromptRequest.d.ts +4 -0
  111. package/lib/src/generated/api/PromptRequest.js +2 -0
  112. package/lib/src/generated/api/PublishLanguageRequest.d.ts +5 -0
  113. package/lib/src/generated/api/PublishLanguageRequest.js +1 -0
  114. package/lib/src/generated/api/PublishNeighbourhoodRequest.d.ts +6 -0
  115. package/lib/src/generated/api/PublishNeighbourhoodRequest.js +1 -0
  116. package/lib/src/generated/api/QueryRequest.d.ts +7 -0
  117. package/lib/src/generated/api/QueryRequest.js +2 -0
  118. package/lib/src/generated/api/RemoveLinkRequest.d.ts +5 -0
  119. package/lib/src/generated/api/RemoveLinkRequest.js +1 -0
  120. package/lib/src/generated/api/RemoveLinksBulkRequest.d.ts +5 -0
  121. package/lib/src/generated/api/RemoveLinksBulkRequest.js +1 -0
  122. package/lib/src/generated/api/ResourceInput.d.ts +4 -0
  123. package/lib/src/generated/api/ResourceInput.js +2 -0
  124. package/lib/src/generated/api/SetDefaultModelRequest.d.ts +4 -0
  125. package/lib/src/generated/api/SetDefaultModelRequest.js +1 -0
  126. package/lib/src/generated/api/SetFreeHostingEnabledRequest.d.ts +3 -0
  127. package/lib/src/generated/api/SetFreeHostingEnabledRequest.js +2 -0
  128. package/lib/src/generated/api/SetMultiUserRequest.d.ts +3 -0
  129. package/lib/src/generated/api/SetMultiUserRequest.js +2 -0
  130. package/lib/src/generated/api/SetStatusRequest.d.ts +3 -0
  131. package/lib/src/generated/api/SetStatusRequest.js +2 -0
  132. package/lib/src/generated/api/SignMessageRequest.d.ts +3 -0
  133. package/lib/src/generated/api/SignMessageRequest.js +2 -0
  134. package/lib/src/generated/api/TrustedAgentsRequest.d.ts +3 -0
  135. package/lib/src/generated/api/TrustedAgentsRequest.js +2 -0
  136. package/lib/src/generated/api/UnlockAgentRequest.d.ts +4 -0
  137. package/lib/src/generated/api/UnlockAgentRequest.js +2 -0
  138. package/lib/src/generated/api/UpdateLinkRequest.d.ts +7 -0
  139. package/lib/src/generated/api/UpdateLinkRequest.js +1 -0
  140. package/lib/src/generated/api/UpdatePerspectiveRequest.d.ts +3 -0
  141. package/lib/src/generated/api/UpdatePerspectiveRequest.js +2 -0
  142. package/lib/src/generated/api/UserStatistics.d.ts +9 -0
  143. package/lib/src/generated/api/UserStatistics.js +2 -0
  144. package/lib/src/generated/api/VerificationRequestResult.d.ts +6 -0
  145. package/lib/src/generated/api/VerificationRequestResult.js +2 -0
  146. package/lib/src/generated/api/VerifySignatureRequest.d.ts +5 -0
  147. package/lib/src/generated/api/VerifySignatureRequest.js +2 -0
  148. package/lib/src/generated/api/WriteSettingsRequest.d.ts +3 -0
  149. package/lib/src/generated/api/WriteSettingsRequest.js +2 -0
  150. package/lib/src/generated/api/index.d.ts +42 -0
  151. package/lib/src/generated/api/index.js +7 -0
  152. package/lib/src/index.d.ts +8 -2
  153. package/lib/src/index.js +8 -2
  154. package/lib/src/jestSetup.d.ts +0 -1
  155. package/lib/src/jestSetup.js +1 -1
  156. package/lib/src/language/Icon.js +2 -21
  157. package/lib/src/language/Language.d.ts +26 -176
  158. package/lib/src/language/Language.js +32 -72
  159. package/lib/src/language/LanguageClient.d.ts +2 -2
  160. package/lib/src/language/LanguageClient.js +15 -105
  161. package/lib/src/language/LanguageHandle.js +2 -41
  162. package/lib/src/language/LanguageMeta.js +4 -75
  163. package/lib/src/language/LanguageRef.js +2 -25
  164. package/lib/src/links/Links.js +14 -111
  165. package/lib/src/model/Ad4mModel.d.ts +143 -63
  166. package/lib/src/model/Ad4mModel.js +583 -425
  167. package/lib/src/model/Ad4mModel.test.js +1434 -688
  168. package/lib/src/model/ModelQueryBuilder.d.ts +61 -45
  169. package/lib/src/model/ModelQueryBuilder.js +315 -157
  170. package/lib/src/model/Subject.js +6 -6
  171. package/lib/src/model/decorators.d.ts +36 -8
  172. package/lib/src/model/decorators.js +41 -14
  173. package/lib/src/model/hydration-batch.d.ts +34 -0
  174. package/lib/src/model/hydration-batch.js +147 -0
  175. package/lib/src/model/hydration-batching.test.d.ts +7 -0
  176. package/lib/src/model/hydration-batching.test.js +456 -0
  177. package/lib/src/model/hydration.d.ts +3 -92
  178. package/lib/src/model/hydration.js +3 -691
  179. package/lib/src/model/index.d.ts +3 -4
  180. package/lib/src/model/index.js +3 -4
  181. package/lib/src/model/json-schema.js +2 -2
  182. package/lib/src/model/model-manifest.d.ts +41 -0
  183. package/lib/src/model/model-manifest.js +11 -0
  184. package/lib/src/model/query-cache.d.ts +30 -0
  185. package/lib/src/model/query-cache.js +66 -0
  186. package/lib/src/model/query-cache.test.d.ts +1 -0
  187. package/lib/src/model/query-cache.test.js +43 -0
  188. package/lib/src/model/query-common.d.ts +1 -1
  189. package/lib/src/model/query-common.js +1 -1
  190. package/lib/src/model/query-sparql-batch.d.ts +17 -0
  191. package/lib/src/model/query-sparql-batch.js +260 -0
  192. package/lib/src/model/query-sparql.d.ts +51 -0
  193. package/lib/src/model/query-sparql.js +466 -0
  194. package/lib/src/model/query-sparql.test.d.ts +1 -0
  195. package/lib/src/model/query-sparql.test.js +312 -0
  196. package/lib/src/model/{surreal-utils.d.ts → query-utils.d.ts} +13 -9
  197. package/lib/src/model/query-utils.js +189 -0
  198. package/lib/src/model/relation-filtering.test.js +15 -15
  199. package/lib/src/model/sdna.js +1 -1
  200. package/lib/src/model/shacl-gen.js +154 -57
  201. package/lib/src/model/subscription-delta.test.d.ts +24 -0
  202. package/lib/src/model/subscription-delta.test.js +180 -0
  203. package/lib/src/model/subscription-pool.d.ts +39 -0
  204. package/lib/src/model/subscription-pool.js +165 -0
  205. package/lib/src/model/types.d.ts +195 -5
  206. package/lib/src/model/types.js +5 -2
  207. package/lib/src/neighbourhood/Neighbourhood.js +4 -32
  208. package/lib/src/neighbourhood/NeighbourhoodClient.d.ts +3 -3
  209. package/lib/src/neighbourhood/NeighbourhoodClient.js +40 -203
  210. package/lib/src/perspectives/LinkQuery.js +2 -42
  211. package/lib/src/perspectives/Perspective.d.ts +1 -1
  212. package/lib/src/perspectives/Perspective.js +10 -52
  213. package/lib/src/perspectives/PerspectiveClient.d.ts +22 -32
  214. package/lib/src/perspectives/PerspectiveClient.js +188 -454
  215. package/lib/src/perspectives/PerspectiveClient.test.d.ts +1 -0
  216. package/lib/src/perspectives/PerspectiveClient.test.js +224 -0
  217. package/lib/src/perspectives/PerspectiveDiff.js +4 -31
  218. package/lib/src/perspectives/PerspectiveHandle.js +3 -43
  219. package/lib/src/perspectives/PerspectiveProxy.d.ts +157 -78
  220. package/lib/src/perspectives/PerspectiveProxy.js +475 -389
  221. package/lib/src/perspectives/PerspectiveResolver.d.ts +0 -1
  222. package/lib/src/perspectives/PerspectiveResolver.js +0 -11
  223. package/lib/src/perspectives/SparqlBindings.d.ts +47 -0
  224. package/lib/src/perspectives/SparqlBindings.js +65 -0
  225. package/lib/src/perspectives/WakerSubscriptionManager.d.ts +3 -3
  226. package/lib/src/perspectives/WakerSubscriptionManager.js +12 -12
  227. package/lib/src/runtime/RuntimeClient.d.ts +8 -6
  228. package/lib/src/runtime/RuntimeClient.js +97 -454
  229. package/lib/src/runtime/RuntimeResolver.d.ts +14 -0
  230. package/lib/src/runtime/RuntimeResolver.js +84 -0
  231. package/lib/src/runtime/RuntimeTypes.d.ts +101 -0
  232. package/lib/src/runtime/RuntimeTypes.js +45 -0
  233. package/lib/src/schema.gql +14 -1
  234. package/lib/src/shacl/SHACLFlow.d.ts +1 -1
  235. package/lib/src/shacl/SHACLFlow.js +9 -9
  236. package/lib/src/shacl/SHACLShape.d.ts +26 -1
  237. package/lib/src/shacl/SHACLShape.js +140 -38
  238. package/lib/src/shacl/SHACLShape.test.js +82 -0
  239. package/lib/src/typeDefs.js +3 -615
  240. package/lib/src/utils.d.ts +6 -6
  241. package/lib/src/utils.js +6 -6
  242. package/package.json +9 -24
  243. package/rollup.config.js +0 -7
  244. package/src/Ad4mClient.test.ts +1192 -1288
  245. package/src/Ad4mClient.ts +46 -15
  246. package/src/Literal.test.ts +10 -5
  247. package/src/Literal.ts +6 -5
  248. package/src/agent/Agent.ts +0 -99
  249. package/src/agent/AgentClient.ts +238 -467
  250. package/src/agent/AgentStatus.ts +0 -12
  251. package/src/ai/AIClient.ts +96 -296
  252. package/src/ai/AITypes.ts +66 -0
  253. package/src/ai/Tasks.ts +0 -52
  254. package/src/apiClient.ts +287 -0
  255. package/src/cache/PersistentCache.ts +145 -0
  256. package/src/cache/cache.test.ts +713 -0
  257. package/src/expression/Expression.ts +3 -43
  258. package/src/expression/ExpressionClient.ts +148 -77
  259. package/src/expression/ExpressionRef.ts +2 -8
  260. package/src/generated/api/AIModelLoadingStatus.ts +3 -0
  261. package/src/generated/api/AddLinkExpressionRequest.ts +4 -0
  262. package/src/generated/api/AddLinkRequest.ts +4 -0
  263. package/src/generated/api/AddLinksBulkRequest.ts +4 -0
  264. package/src/generated/api/AddSdnaRequest.ts +3 -0
  265. package/src/generated/api/ApplyTemplateRequest.ts +3 -0
  266. package/src/generated/api/AuthInfoInput.ts +4 -0
  267. package/src/generated/api/CapabilityInput.ts +4 -0
  268. package/src/generated/api/CommitBatchRequest.ts +3 -0
  269. package/src/generated/api/ComputeLogEntry.ts +3 -0
  270. package/src/generated/api/CreateExpressionRequest.ts +3 -0
  271. package/src/generated/api/CreatePerspectiveRequest.ts +3 -0
  272. package/src/generated/api/CreateSubjectRequest.ts +3 -0
  273. package/src/generated/api/EmbedRequest.ts +3 -0
  274. package/src/generated/api/EntanglementProofInput.ts +3 -0
  275. package/src/generated/api/ExecuteCommandsRequest.ts +3 -0
  276. package/src/generated/api/ExportRequest.ts +3 -0
  277. package/src/generated/api/ExpressionManyRequest.ts +3 -0
  278. package/src/generated/api/ExpressionProof.ts +3 -0
  279. package/src/generated/api/ExpressionProofInput.ts +3 -0
  280. package/src/generated/api/FriendSendMessageRequest.ts +3 -0
  281. package/src/generated/api/FriendsListRequest.ts +3 -0
  282. package/src/generated/api/GenerateAgentRequest.ts +3 -0
  283. package/src/generated/api/GenerateJwtRequest.ts +3 -0
  284. package/src/generated/api/GetSubjectDataRequest.ts +3 -0
  285. package/src/generated/api/ImportAgentRequest.ts +3 -0
  286. package/src/generated/api/ImportRequest.ts +3 -0
  287. package/src/generated/api/JoinNeighbourhoodRequest.ts +3 -0
  288. package/src/generated/api/LanguageMetaInput.ts +3 -0
  289. package/src/generated/api/Link.ts +3 -0
  290. package/src/generated/api/LinkExpression.ts +6 -0
  291. package/src/generated/api/LinkExpressionInput.ts +6 -0
  292. package/src/generated/api/LinkInput.ts +3 -0
  293. package/src/generated/api/LinkLanguageTemplatesRequest.ts +3 -0
  294. package/src/generated/api/LinkMutations.ts +5 -0
  295. package/src/generated/api/LinkStatus.ts +3 -0
  296. package/src/generated/api/LockAgentRequest.ts +3 -0
  297. package/src/generated/api/ModelType.ts +3 -0
  298. package/src/generated/api/NotificationInput.ts +3 -0
  299. package/src/generated/api/OpenLinkRequest.ts +3 -0
  300. package/src/generated/api/PermitCapabilityRequest.ts +3 -0
  301. package/src/generated/api/PerspectiveInput.ts +4 -0
  302. package/src/generated/api/PromptRequest.ts +3 -0
  303. package/src/generated/api/PublishLanguageRequest.ts +4 -0
  304. package/src/generated/api/PublishNeighbourhoodRequest.ts +4 -0
  305. package/src/generated/api/QueryRequest.ts +6 -0
  306. package/src/generated/api/RemoveLinkRequest.ts +4 -0
  307. package/src/generated/api/RemoveLinksBulkRequest.ts +4 -0
  308. package/src/generated/api/ResourceInput.ts +3 -0
  309. package/src/generated/api/SetDefaultModelRequest.ts +4 -0
  310. package/src/generated/api/SetFreeHostingEnabledRequest.ts +3 -0
  311. package/src/generated/api/SetMultiUserRequest.ts +3 -0
  312. package/src/generated/api/SetStatusRequest.ts +3 -0
  313. package/src/generated/api/SignMessageRequest.ts +3 -0
  314. package/src/generated/api/TrustedAgentsRequest.ts +3 -0
  315. package/src/generated/api/UnlockAgentRequest.ts +3 -0
  316. package/src/generated/api/UpdateLinkRequest.ts +5 -0
  317. package/src/generated/api/UpdatePerspectiveRequest.ts +3 -0
  318. package/src/generated/api/UserStatistics.ts +3 -0
  319. package/src/generated/api/VerificationRequestResult.ts +3 -0
  320. package/src/generated/api/VerifySignatureRequest.ts +3 -0
  321. package/src/generated/api/WriteSettingsRequest.ts +3 -0
  322. package/src/generated/api/index.ts +49 -0
  323. package/src/index.ts +8 -2
  324. package/src/jestSetup.ts +1 -1
  325. package/src/language/Icon.ts +0 -4
  326. package/src/language/Language.ts +51 -248
  327. package/src/language/LanguageClient.ts +21 -132
  328. package/src/language/LanguageHandle.ts +0 -14
  329. package/src/language/LanguageMeta.ts +0 -29
  330. package/src/language/LanguageRef.ts +0 -7
  331. package/src/links/Links.ts +0 -37
  332. package/src/model/Ad4mModel.test.ts +1664 -792
  333. package/src/model/Ad4mModel.ts +664 -499
  334. package/src/model/ModelQueryBuilder.ts +362 -183
  335. package/src/model/decorators.ts +71 -22
  336. package/src/model/hydration.ts +3 -772
  337. package/src/model/index.ts +3 -4
  338. package/src/model/json-schema.ts +2 -2
  339. package/src/model/query-cache.test.ts +54 -0
  340. package/src/model/query-cache.ts +79 -0
  341. package/src/model/query-common.ts +1 -1
  342. package/src/model/query-sparql.test.ts +376 -0
  343. package/src/model/query-sparql.ts +504 -0
  344. package/src/model/query-utils.ts +209 -0
  345. package/src/model/relation-filtering.test.ts +60 -53
  346. package/src/model/sdna.ts +1 -1
  347. package/src/model/shacl-gen.ts +163 -64
  348. package/src/model/shacl-roundtrip.test.ts +197 -0
  349. package/src/model/types-typed-query.test.ts +360 -0
  350. package/src/model/types.ts +256 -5
  351. package/src/neighbourhood/Neighbourhood.ts +0 -9
  352. package/src/neighbourhood/NeighbourhoodClient.ts +42 -207
  353. package/src/neighbourhood/NeighbourhoodProxy.test.ts +34 -36
  354. package/src/perspectives/LinkQuery.ts +0 -15
  355. package/src/perspectives/Perspective.ts +1 -12
  356. package/src/perspectives/PerspectiveClient.test.ts +262 -0
  357. package/src/perspectives/PerspectiveClient.ts +252 -468
  358. package/src/perspectives/PerspectiveDiff.ts +0 -8
  359. package/src/perspectives/PerspectiveHandle.ts +1 -12
  360. package/src/perspectives/PerspectiveProxy.test.ts +125 -0
  361. package/src/perspectives/PerspectiveProxy.ts +522 -434
  362. package/src/perspectives/SparqlBindings.ts +79 -0
  363. package/src/perspectives/WakerSubscriptionManager.ts +13 -13
  364. package/src/runtime/RuntimeClient.ts +118 -461
  365. package/src/runtime/RuntimeTypes.ts +144 -0
  366. package/src/shacl/SHACLFlow.ts +9 -9
  367. package/src/shacl/SHACLShape.test.ts +204 -0
  368. package/src/shacl/SHACLShape.ts +191 -39
  369. package/src/typeDefs.ts +3 -5
  370. package/src/utils.ts +6 -6
  371. package/tsconfig.json +3 -7
  372. package/lib/src/model/query-surreal.d.ts +0 -44
  373. package/lib/src/model/query-surreal.js +0 -249
  374. package/lib/src/model/surreal-utils.js +0 -128
  375. package/shims/reflect-metadata.ts +0 -0
  376. package/shims/type-graphql.ts +0 -75
  377. package/src/PubSub.ts +0 -17
  378. package/src/agent/AgentResolver.ts +0 -263
  379. package/src/ai/AIResolver.ts +0 -372
  380. package/src/buildSchema.ts +0 -43
  381. package/src/expression/ExpressionResolver.ts +0 -64
  382. package/src/language/LanguageContext.ts +0 -37
  383. package/src/language/LanguageResolver.ts +0 -98
  384. package/src/model/Subject.ts +0 -159
  385. package/src/model/prolog-facts.ts +0 -145
  386. package/src/model/query-prolog.ts +0 -148
  387. package/src/model/query-surreal.ts +0 -280
  388. package/src/model/surreal-utils.ts +0 -147
  389. package/src/neighbourhood/NeighbourhoodResolver.ts +0 -100
  390. package/src/perspectives/PerspectiveResolver.ts +0 -372
  391. package/src/runtime/RuntimeResolver.ts +0 -691
  392. package/src/unwrapApolloResult.ts +0 -16
  393. package/tsconfig-browser.json +0 -82
@@ -1,5 +1,6 @@
1
1
  import { Ad4mModel } from "./Ad4mModel";
2
- import { Model, Property, Optional, ReadOnly, HasMany, Flag } from "./decorators";
2
+ import { isIncludeProjection } from "./types";
3
+ import { Model, Property, Optional, ReadOnly, HasMany, HasOne, Flag } from "./decorators";
3
4
 
4
5
  describe("Ad4mModel.getModelMetadata()", () => {
5
6
  it("should extract basic model metadata with className", () => {
@@ -430,16 +431,16 @@ describe("Ad4mModel.fromJSONSchema() with getModelMetadata()", () => {
430
431
  });
431
432
  });
432
433
 
433
- describe("Ad4mModel.queryToSurrealQL()", () => {
434
- // Mock perspective proxy (minimal since queryToSurrealQL doesn't actually call it)
434
+
435
+
436
+
437
+ describe("Ad4mModel.queryToSPARQL()", () => {
435
438
  const mockPerspective = {} as any;
436
439
 
437
- // Helper function to normalize whitespace in queries for easier comparison
438
440
  function normalizeQuery(query: string): string {
439
441
  return query.replace(/\s+/g, ' ').trim();
440
442
  }
441
443
 
442
- // Test Recipe model — explicit required: true to test required-property query filters
443
444
  @Model({ name: "Recipe" })
444
445
  class Recipe extends Ad4mModel {
445
446
  @Property({ through: "recipe://name", required: true })
@@ -452,403 +453,172 @@ describe("Ad4mModel.queryToSurrealQL()", () => {
452
453
  ingredients: string[] = [];
453
454
  }
454
455
 
455
- it("should generate basic query with no filters", async () => {
456
- const query = await Recipe.queryToSurrealQL(mockPerspective, {});
456
+ it("should generate basic SPARQL query with no filters", async () => {
457
+ const query = await (Recipe as any).queryToSPARQL(mockPerspective, {});
458
+ const norm = normalizeQuery(query);
457
459
 
458
- expect(query).toContain("id AS source");
459
- expect(query).toContain("uri AS source_uri");
460
- expect(query).toContain("FROM node");
461
- expect(query).toContain("->link AS links");
462
- expect(query).toContain("WHERE");
463
- // Should have graph traversal filters for required properties
464
- expect(query).toContain("count(->link[WHERE");
460
+ // Must be a SPARQL SELECT
461
+ expect(norm).toContain("SELECT ?source ?predicate ?target ?author ?timestamp");
462
+ // Must have conformance JOIN for required properties using direct triple patterns
463
+ expect(norm).toContain("cfTarget_name");
464
+ expect(norm).toContain("recipe://name");
465
465
  });
466
466
 
467
467
  it("should generate query with simple property filter", async () => {
468
- const query = await Recipe.queryToSurrealQL(mockPerspective, { where: { name: "Pasta" } });
469
-
470
- // Should have graph traversal filters for required properties and user filter
471
- expect(query).toContain("count(->link[WHERE predicate = 'recipe://name']) > 0");
472
- expect(query).toContain("count(->link[WHERE predicate = 'recipe://rating']) > 0");
473
- expect(query).toContain("count(->link[WHERE predicate = 'recipe://name' AND fn::parse_literal(out.uri) = 'Pasta']) > 0");
474
- });
475
-
476
- it("should generate query with multiple property filters", async () => {
477
- const query = await Recipe.queryToSurrealQL(mockPerspective, { where: { name: "Pasta", rating: 5 } });
478
-
479
- expect(query).toContain("WHERE");
480
- expect(query).toContain("count(->link[WHERE predicate = 'recipe://name' AND fn::parse_literal(out.uri) = 'Pasta']) > 0");
481
- expect(query).toContain("count(->link[WHERE predicate = 'recipe://rating' AND fn::parse_literal(out.uri) = 5]) > 0");
482
- expect(query).toContain("AND");
483
- });
484
-
485
- it("should handle gt operator (filtered in JavaScript, not SQL)", async () => {
486
- const query = await Recipe.queryToSurrealQL(mockPerspective, { where: { rating: { gt: 4 } } });
487
-
488
- // Comparison operators for regular properties are now filtered in JavaScript post-query
489
- // The SQL just filters on the predicate existing
490
- expect(query).toContain("FROM node");
491
-
492
- // Should NOT contain comparison operators in SQL for regular properties
493
- expect(query).not.toContain("target > 4");
494
- });
495
-
496
- it("should handle lt operator (filtered in JavaScript, not SQL)", async () => {
497
- const query = await Recipe.queryToSurrealQL(mockPerspective, { where: { rating: { lt: 3 } } });
498
-
499
- // Comparison operators are filtered in JavaScript post-query
500
- expect(query).toContain("FROM node");
501
- expect(query).not.toContain("target < 3");
502
- });
503
-
504
- it("should handle gte and lte operators (filtered in JavaScript, not SQL)", async () => {
505
- const query = await Recipe.queryToSurrealQL(mockPerspective, { where: { rating: { gte: 3, lte: 5 } } });
506
-
507
- // Comparison operators are filtered in JavaScript post-query
508
- expect(query).toContain("FROM node");
509
- expect(query).not.toContain("target >= 3");
510
- expect(query).not.toContain("target <= 5");
511
- });
512
-
513
- it("should handle not operator with single value", async () => {
514
- const query = await Recipe.queryToSurrealQL(mockPerspective, { where: { name: { not: "Salad" } } });
515
-
516
- // Not operator uses graph traversal with count = 0
517
- expect(query).toContain("count(->link[WHERE predicate = 'recipe://name' AND fn::parse_literal(out.uri) = 'Salad']) = 0");
518
- });
519
-
520
- it("should handle not operator with array (NOT IN)", async () => {
521
- const query = await Recipe.queryToSurrealQL(mockPerspective, { where: { name: { not: ["Salad", "Soup"] } } });
522
-
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
-
527
- it("should handle between operator (filtered in JavaScript, not SQL)", async () => {
528
- const query = await Recipe.queryToSurrealQL(mockPerspective, { where: { rating: { between: [3, 5] } } });
529
-
530
- // Between operator for regular properties is now filtered in JavaScript post-query
531
- expect(query).toContain("FROM node");
532
- expect(query).not.toContain("target >= 3");
533
- expect(query).not.toContain("target <= 5");
534
- });
535
-
536
- it("should handle contains operator on string property (filtered in JavaScript, not SQL)", async () => {
537
- const query = await Recipe.queryToSurrealQL(mockPerspective, { where: { name: { contains: "Past" } } });
538
-
539
- // Contains operator for regular properties is now filtered in JavaScript post-query
540
- expect(query).toContain("FROM node");
541
- expect(query).not.toContain("target CONTAINS 'Past'");
542
- });
543
-
544
- it("should handle contains operator on regular property with substring (filtered in JavaScript, not SQL)", async () => {
545
- const query = await Recipe.queryToSurrealQL(mockPerspective, { where: { name: { contains: "Salad" } } });
546
-
547
- // Contains operator is filtered in JavaScript post-query
548
- expect(query).toContain("FROM node");
549
- expect(query).not.toContain("target CONTAINS 'Salad'");
550
- });
551
-
552
- it.skip("should handle contains operator on special field (author)", async () => {
553
- const query = await Recipe.queryToSurrealQL(mockPerspective, { where: { author: { contains: "alice" } } });
554
-
555
- expect(query).toContain("WHERE author CONTAINS 'alice'");
556
- // Should not use a subquery pattern
557
- expect(query).not.toContain("SELECT source FROM node");
558
- });
559
-
560
- it.skip("should handle contains operator on special field (id)", async () => {
561
- const query = await Recipe.queryToSurrealQL(mockPerspective, { where: { id: { contains: "test" } } });
562
-
563
- expect(query).toContain("WHERE source CONTAINS 'test'");
564
- });
565
-
566
- it("should handle array values (IN clause)", async () => {
567
- const query = await Recipe.queryToSurrealQL(mockPerspective, { where: { name: ["Pasta", "Pizza"] } });
568
-
569
- expect(query).toContain("count(->link[WHERE predicate = 'recipe://name' AND fn::parse_literal(out.uri) IN ['Pasta', 'Pizza']]) > 0");
570
- });
571
-
572
- it.skip("should handle special fields (author, timestamp) without subqueries", async () => {
573
- const query = await Recipe.queryToSurrealQL(mockPerspective, { where: { author: "did:key:alice" } });
574
-
575
- expect(query).toContain("WHERE author = 'did:key:alice'");
576
- // Ensure it's NOT using a subquery pattern for author in WHERE clause
577
- expect(normalizeQuery(query)).not.toMatch(/WHERE.*source IN.*SELECT source FROM node.*author/);
578
- });
579
-
580
- it("should not generate ORDER BY clause in SQL (handled in JavaScript)", async () => {
581
- const query = await Recipe.queryToSurrealQL(mockPerspective, { order: { timestamp: "DESC" } });
582
-
583
- // ORDER BY is now handled in JavaScript post-query
584
- expect(query).toContain("FROM node");
585
- expect(query).not.toContain("ORDER BY");
586
- });
468
+ const query = await (Recipe as any).queryToSPARQL(mockPerspective, { where: { name: "Pasta" } });
469
+ const norm = normalizeQuery(query);
587
470
 
588
- it("should not generate LIMIT clause in SQL (handled in JavaScript)", async () => {
589
- const query = await Recipe.queryToSurrealQL(mockPerspective, { limit: 10 });
590
-
591
- // LIMIT is now handled in JavaScript post-query
592
- expect(query).toContain("FROM node");
593
- expect(query).not.toContain("LIMIT");
471
+ expect(norm).toContain("SELECT ?source ?predicate ?target ?author ?timestamp");
472
+ // For literal-stored properties, SPARQL only adds a JOIN (no FILTER value) — filtering is in JS
473
+ expect(norm).toContain("recipe://name");
474
+ // Value should NOT be in SPARQL — filtering happens in JS post-filter
475
+ expect(norm).toContain("?wTarget_name");
594
476
  });
595
477
 
596
- it("should not generate START clause in SQL (handled in JavaScript)", async () => {
597
- const query = await Recipe.queryToSurrealQL(mockPerspective, { offset: 20 });
478
+ it("should generate query with NOT operator", async () => {
479
+ const query = await (Recipe as any).queryToSPARQL(mockPerspective, { where: { name: { not: "Salad" } } });
480
+ const norm = normalizeQuery(query);
598
481
 
599
- // START/offset is now handled in JavaScript post-query
600
- expect(query).toContain("FROM node");
601
- expect(query).not.toContain("START");
482
+ // For literal-stored properties, NOT filtering is done in JS — no NOT EXISTS in SPARQL
483
+ expect(norm).toContain("recipe://name");
602
484
  });
603
485
 
604
- it("should generate complete query with all options (ORDER BY, LIMIT, START handled in JS)", async () => {
605
- const query = await Recipe.queryToSurrealQL(mockPerspective, {
606
- where: { name: "Pasta", rating: { gt: 4 } },
607
- order: { timestamp: "DESC" },
608
- limit: 10,
609
- offset: 20
610
- });
486
+ it("should generate query with NOT IN operator (array)", async () => {
487
+ const query = await (Recipe as any).queryToSPARQL(mockPerspective, { where: { name: { not: ["Salad", "Soup"] } } });
488
+ const norm = normalizeQuery(query);
611
489
 
612
- // WHERE clause uses graph traversal filters
613
- expect(query).toContain("WHERE");
614
- expect(query).toContain("count(->link[WHERE predicate = 'recipe://name' AND fn::parse_literal(out.uri) = 'Pasta']) > 0");
615
- // Comparison operators (gt) are filtered in JavaScript, not SQL
616
- expect(query).not.toContain("out.uri > 4");
617
- expect(query).not.toContain("target > 4");
618
- // ORDER BY, LIMIT, START are now handled in JavaScript post-query
619
- expect(query).not.toContain("ORDER BY");
620
- expect(query).not.toContain("LIMIT");
621
- expect(query).not.toContain("START");
490
+ // For literal-stored properties, NOT IN filtering is done in JS — no filter values in SPARQL
491
+ expect(norm).toContain("recipe://name");
622
492
  });
623
493
 
624
- it("should only select requested properties", async () => {
625
- const query = await Recipe.queryToSurrealQL(mockPerspective, { properties: ["name"] });
494
+ it("should generate query with IN clause (array values)", async () => {
495
+ const query = await (Recipe as any).queryToSPARQL(mockPerspective, { where: { name: ["Pasta", "Pizza"] } });
496
+ const norm = normalizeQuery(query);
626
497
 
627
- // With array::group(), all link data is selected, filtering happens in instancesFromSurrealResult
628
- expect(query).toContain("->link AS links");
629
-
498
+ // For literal-stored properties, IN filtering is done in JS — only a JOIN exists
499
+ expect(norm).toContain("recipe://name");
500
+ expect(norm).toContain("?wTarget_name");
630
501
  });
631
502
 
632
- it("should select all link data for relations", async () => {
633
- @Model({ name: "MultiRelationModel" })
634
- class MultiRelationModel extends Ad4mModel {
635
- @HasMany({ through: "test://coll1" })
636
- coll1: string[] = [];
637
-
638
- @HasMany({ through: "test://coll2" })
639
- coll2: string[] = [];
640
- }
641
-
642
- const query = await MultiRelationModel.queryToSurrealQL(mockPerspective, {});
503
+ it("should generate query with base filter", async () => {
504
+ const query = await (Recipe as any).queryToSPARQL(mockPerspective, { where: { base: "ad4m://test123" } });
505
+ const norm = normalizeQuery(query);
643
506
 
644
- // With array::group(), all link data is selected
645
- expect(query).toContain("->link AS links");
646
-
507
+ expect(norm).toContain("?source =");
508
+ expect(norm).toContain("ad4m://test123");
647
509
  });
648
510
 
649
- it("should escape single quotes in string values", async () => {
650
- const query = await Recipe.queryToSurrealQL(mockPerspective, { where: { name: "O'Brien's Recipe" } });
651
-
652
- // Single quotes are escaped with backslash in SurrealDB
653
- expect(query).toContain("O\\'Brien\\'s Recipe");
654
- });
511
+ it("should escape special characters in SPARQL strings", async () => {
512
+ const query = await (Recipe as any).queryToSPARQL(mockPerspective, { where: { name: 'O\'Brien' } });
513
+ const norm = normalizeQuery(query);
655
514
 
656
- it("should handle numeric values without quotes", async () => {
657
- const query = await Recipe.queryToSurrealQL(mockPerspective, { where: { rating: 5 } });
658
-
659
- // Numeric values should not have quotes around them
660
- expect(query).toContain("fn::parse_literal(out.uri) = 5");
661
- expect(query).not.toContain("fn::parse_literal(out.uri) = '5'");
515
+ // Should not break the query
516
+ expect(norm).toContain("SELECT ?source");
662
517
  });
663
518
 
664
- it("should handle complex nested query (comparisons, ORDER BY, LIMIT handled in JS)", async () => {
665
- const query = await Recipe.queryToSurrealQL(mockPerspective, {
666
- where: {
667
- name: "Pasta",
668
- rating: { gte: 4, lte: 5 },
669
- author: "did:key:alice"
670
- },
671
- order: { rating: "DESC" },
672
- limit: 5
673
- });
519
+ // =========================================================================
520
+ // Additional models for thorough SPARQL structure tests
521
+ // =========================================================================
674
522
 
675
- const normalized = normalizeQuery(query);
523
+ @Model({ name: "Task" })
524
+ class Task extends Ad4mModel {
525
+ @Property({ through: "task://title", resolveLanguage: "literal", required: true })
526
+ title: string = "";
676
527
 
677
- // Verify graph traversal filters are present
678
- expect(normalized).toContain("count(->link[WHERE predicate = 'recipe://name' AND fn::parse_literal(out.uri) = 'Pasta']) > 0");
679
- // Comparison operators (gte, lte) are filtered in JavaScript, not SQL
680
- expect(normalized).not.toContain("out.uri >= 4");
681
- expect(normalized).not.toContain("target >= 4");
682
- expect(normalized).not.toContain("out.uri <= 5");
683
- expect(normalized).not.toContain("target <= 5");
684
- // author and timestamp filtering is done in JavaScript post-query
685
- expect(normalized).not.toContain("author = 'did:key:alice'");
528
+ @Property({ through: "task://priority", resolveLanguage: "literal" })
529
+ priority: number = 0;
686
530
 
687
- // ORDER BY and LIMIT are handled in JavaScript post-query
688
- expect(normalized).not.toContain("ORDER BY");
689
- expect(normalized).not.toContain("LIMIT");
531
+ @Property({ through: "task://done", resolveLanguage: "literal" })
532
+ done: boolean = false;
690
533
 
691
- // Verify query structure (FROM node, no GROUP BY)
692
- expect(normalized).toContain("FROM node");
693
- });
534
+ @Optional({ through: "task://description" })
535
+ description: string = "";
694
536
 
695
- it("should handle empty query object", async () => {
696
- const query = await Recipe.queryToSurrealQL(mockPerspective, {});
697
-
698
- // Should generate valid query with WHERE clause for required properties (name and rating)
699
- expect(query).toContain("id AS source");
700
- expect(query).toContain("uri AS source_uri");
701
- expect(query).toContain("FROM node");
702
-
703
- // Should have WHERE clause filtering for required properties using graph traversal
704
- expect(query).toContain("WHERE");
705
- expect(query).toContain("count(->link[WHERE predicate = 'recipe://name']) > 0");
706
- expect(query).toContain("count(->link[WHERE predicate = 'recipe://rating']) > 0");
707
- expect(query).not.toContain("ORDER BY");
708
- expect(query).not.toContain("START");
709
- });
537
+ @HasMany({ through: "task://tag" })
538
+ tags: string[] = [];
710
539
 
711
- it("should handle id special field", async () => {
712
- const query = await Recipe.queryToSurrealQL(mockPerspective, { where: { id: "literal://test" } });
713
-
714
- expect(query).toContain("uri = 'literal://test'");
715
- });
540
+ @HasMany({ through: "task://assignee" })
541
+ assignees: string[] = [];
542
+ }
716
543
 
717
- it("should handle id special field with array (IN clause)", async () => {
718
- const query = await Recipe.queryToSurrealQL(mockPerspective, { where: { id: ["literal://test1", "literal://test2"] } });
719
-
720
- expect(query).toContain("uri IN ['literal://test1', 'literal://test2']");
721
- });
544
+ @Model({ name: "EmptyModel" })
545
+ class EmptyModel extends Ad4mModel {
546
+ @Optional({ through: "empty://optField" })
547
+ optField: string = "";
548
+ }
722
549
 
723
- it("should handle id special field with not operator", async () => {
724
- const query = await Recipe.queryToSurrealQL(mockPerspective, { where: { id: { not: "literal://test" } } });
725
-
726
- expect(query).toContain("uri != 'literal://test'");
727
- });
550
+ // ---- Comparison operators (gt, lt, gte, lte, between, contains) ----
551
+ // These are handled in JS post-processing, NOT in SPARQL.
552
+ // The tests verify that the SPARQL still generates valid output (conformance filters)
553
+ // but does NOT inject FILTER clauses for these operators.
728
554
 
729
- it("should handle id special field with not operator and array (NOT IN)", async () => {
730
- const query = await Recipe.queryToSurrealQL(mockPerspective, { where: { id: { not: ["literal://test1", "literal://test2"] } } });
731
-
732
- expect(query).toContain("uri NOT IN ['literal://test1', 'literal://test2']");
555
+ it("should inject SPARQL FILTER for gt operator", async () => {
556
+ const query = await (Recipe as any).queryToSPARQL(mockPerspective, { where: { rating: { gt: 3 } } });
557
+ const norm = normalizeQuery(query);
558
+ expect(norm).toContain("SELECT ?source");
559
+ // gt is now handled via JS post-filter — SPARQL just joins the property
560
+ expect(norm).toContain("wTarget_cmp_rating");
733
561
  });
734
562
 
735
- it("should handle id special field with between operator", async () => {
736
- const query = await Recipe.queryToSurrealQL(mockPerspective, { where: { id: { between: ["literal://a", "literal://z"] } } } as any);
737
-
738
- const normalized = normalizeQuery(query);
739
- expect(normalized).toContain("uri >= 'literal://a' AND uri <= 'literal://z'");
563
+ it("should inject SPARQL FILTER for lt operator", async () => {
564
+ const query = await (Recipe as any).queryToSPARQL(mockPerspective, { where: { rating: { lt: 5 } } });
565
+ const norm = normalizeQuery(query);
566
+ expect(norm).toContain("SELECT ?source");
567
+ // lt is now handled via JS post-filter
568
+ expect(norm).toContain("wTarget_cmp_rating");
740
569
  });
741
570
 
742
- it("should handle id special field with gt operator", async () => {
743
- const query = await Recipe.queryToSurrealQL(mockPerspective, { where: { id: { gt: "literal://m" } } } as any);
744
-
745
- expect(query).toContain("uri > 'literal://m'");
571
+ it("should inject SPARQL FILTER for gte/lte combined", async () => {
572
+ const query = await (Recipe as any).queryToSPARQL(mockPerspective, { where: { rating: { gte: 2, lte: 8 } } });
573
+ const norm = normalizeQuery(query);
574
+ expect(norm).toContain("SELECT ?source");
575
+ // gte/lte are now handled via JS post-filter
576
+ expect(norm).toContain("wTarget_cmp_rating");
746
577
  });
747
578
 
748
- it("should handle id special field with gte and lte operators", async () => {
749
- const query = await Recipe.queryToSurrealQL(mockPerspective, { where: { id: { gte: "literal://a", lte: "literal://z" } } } as any);
750
-
751
- const normalized = normalizeQuery(query);
752
- expect(normalized).toContain("uri >= 'literal://a'");
753
- expect(normalized).toContain("uri <= 'literal://z'");
579
+ it("should inject SPARQL FILTER for between operator", async () => {
580
+ const query = await (Recipe as any).queryToSPARQL(mockPerspective, { where: { rating: { between: [1, 10] } } });
581
+ const norm = normalizeQuery(query);
582
+ expect(norm).toContain("SELECT ?source");
583
+ // between is now handled via JS post-filter
584
+ expect(norm).toContain("wTarget_cmp_rating");
754
585
  });
755
586
 
756
- it("should handle timestamp special field with gt operator (filtered in JavaScript)", async () => {
757
- const query = await Recipe.queryToSurrealQL(mockPerspective, { where: { timestamp: { gt: 1234567890 } } });
758
-
759
- // timestamp filtering is done in JavaScript post-query
760
- expect(query).toContain("FROM node");
761
- expect(query).not.toContain("timestamp > 1234567890");
587
+ it("should inject SPARQL FILTER for contains operator", async () => {
588
+ const query = await (Recipe as any).queryToSPARQL(mockPerspective, { where: { name: { contains: "pasta" } } });
589
+ const norm = normalizeQuery(query);
590
+ expect(norm).toContain("SELECT ?source");
591
+ // contains is now handled via JS post-filter
592
+ expect(norm).toContain("wTarget_cmp_name");
762
593
  });
763
594
 
764
- it("should handle multiple special fields (filtered in JavaScript)", async () => {
765
- const query = await Recipe.queryToSurrealQL(mockPerspective, {
766
- where: {
767
- author: "did:key:alice",
768
- timestamp: { gt: 1000 }
769
- }
770
- });
771
-
772
- // author and timestamp filtering is done in JavaScript post-query
773
- expect(query).toContain("FROM node");
774
- expect(query).not.toContain("author = 'did:key:alice'");
775
- expect(query).not.toContain("timestamp > 1000");
776
- });
595
+ // ---- Multiple property filters combined ----
777
596
 
778
- it("should handle mixed special and regular properties", async () => {
779
- const query = await Recipe.queryToSurrealQL(mockPerspective, {
780
- where: {
781
- name: "Pasta",
782
- author: "did:key:alice",
783
- rating: { gt: 4 }
784
- }
597
+ it("should combine multiple property equality filters with &&", async () => {
598
+ const query = await (Recipe as any).queryToSPARQL(mockPerspective, {
599
+ where: { name: "Pasta", rating: ["4", "5"] }
785
600
  });
786
-
787
- const normalized = normalizeQuery(query);
788
- // Regular properties use graph traversal filters
789
- expect(normalized).toContain("count(->link[WHERE predicate = 'recipe://name' AND fn::parse_literal(out.uri) = 'Pasta']) > 0");
790
- // Comparison operators (gt) are filtered in JavaScript, not SQL
791
- expect(normalized).not.toContain("out.uri > 4");
792
- expect(normalized).not.toContain("target > 4");
793
- // author filtering is done in JavaScript post-query
794
- expect(normalized).not.toContain("author = 'did:key:alice'");
795
- });
796
-
797
- it("should handle boolean values", async () => {
798
- @Model({ name: "Task" })
799
- class Task extends Ad4mModel {
800
- @Property({ through: "task://completed" })
801
- completed: boolean = false;
802
- }
803
-
804
- const query = await Task.queryToSurrealQL(mockPerspective, { where: { completed: true } });
805
-
806
- expect(query).toContain("fn::parse_literal(out.uri) = true");
807
- });
808
-
809
- it("should handle array of numbers", async () => {
810
- const query = await Recipe.queryToSurrealQL(mockPerspective, { where: { rating: [4, 5] } });
811
-
812
- expect(query).toContain("count(->link[WHERE predicate = 'recipe://rating' AND fn::parse_literal(out.uri) IN [4, 5]]) > 0");
813
- });
814
-
815
- it("should skip unknown properties in where clause", async () => {
816
- const query = await Recipe.queryToSurrealQL(mockPerspective, { where: { unknownProp: "value" } as any });
817
-
818
- // Should not throw error, just skip the unknown property
819
- expect(query).toContain("source");
820
-
821
- // Should not contain any condition for unknownProp
822
- expect(query).not.toContain("unknownProp");
823
- });
824
-
825
- it.skip("should skip unknown properties in select clause", async () => {
826
- const query = await Recipe.queryToSurrealQL(mockPerspective, { properties: ["name", "unknownProp"] as any });
827
-
828
- // Should include name using aggregation
829
- expect(query).toContain("array::first(target[WHERE predicate = 'recipe://name']) AS name");
830
- // Should not error on unknownProp, just skip it
831
- expect(query).not.toContain("unknownProp");
601
+ const norm = normalizeQuery(query);
602
+ // Should have EXISTS blocks for both name and rating
603
+ expect(norm).toContain("recipe://name");
604
+ expect(norm).toContain("recipe://rating");
605
+ expect(norm).toContain("&&");
832
606
  });
833
607
 
834
- it("should handle order by regular property (handled in JavaScript)", async () => {
835
- const query = await Recipe.queryToSurrealQL(mockPerspective, { order: { name: "ASC" } });
608
+ // ---- ORDER BY, LIMIT, OFFSET are JS post-processed ----
836
609
 
837
- // ORDER BY is now handled in JavaScript post-query
838
- expect(query).toContain("FROM node");
839
- expect(query).not.toContain("ORDER BY");
840
- });
841
-
842
- it("should generate query with only properties specified", async () => {
843
- const query = await Recipe.queryToSurrealQL(mockPerspective, { properties: ["name", "rating"] });
844
-
845
- // With array::group(), all link data is selected, filtering happens in instancesFromSurrealResult
846
- expect(query).toContain("->link AS links");
847
-
610
+ it("should include ORDER BY/LIMIT/OFFSET in SPARQL pagination subquery", async () => {
611
+ const query = await (Recipe as any).queryToSPARQL(mockPerspective, { order: { name: "ASC" }, limit: 10, offset: 5 });
612
+ const norm = normalizeQuery(query);
613
+ expect(norm).toContain("SELECT ?source");
614
+ // SPARQL-level pagination via subquery
615
+ expect(norm).toContain("ORDER BY");
616
+ expect(norm).toContain("LIMIT 10");
617
+ expect(norm).toContain("OFFSET 5");
618
+ expect(norm).toContain("SELECT DISTINCT ?source");
848
619
  });
849
620
  });
850
-
851
- describe("Ad4mModel.instancesFromSurrealResult() and SurrealDB integration", () => {
621
+ describe("Ad4mModel query methods (modelQuery integration)", () => {
852
622
  // Test Recipe model
853
623
  @Model({ name: "Recipe" })
854
624
  class Recipe extends Ad4mModel {
@@ -862,9 +632,10 @@ describe("Ad4mModel.instancesFromSurrealResult() and SurrealDB integration", ()
862
632
  ingredients: string[] = [];
863
633
  }
864
634
 
865
- // Mock perspective with both querySurrealDB and infer methods
635
+ // Mock perspective with querySparql, modelQuery, and infer methods
866
636
  const mockPerspective = {
867
- querySurrealDB: jest.fn(),
637
+ querySparql: jest.fn(),
638
+ modelQuery: jest.fn(),
868
639
  infer: jest.fn(),
869
640
  uuid: 'test-perspective-uuid',
870
641
  stringOrTemplateObjectToSubjectClassName: jest.fn().mockResolvedValue('Recipe')
@@ -874,337 +645,128 @@ describe("Ad4mModel.instancesFromSurrealResult() and SurrealDB integration", ()
874
645
  jest.clearAllMocks();
875
646
  });
876
647
 
877
- it("should convert empty SurrealDB results correctly", async () => {
878
- const result = await Recipe.instancesFromSurrealResult(mockPerspective, {}, []);
879
-
880
- expect(result.results).toEqual([]);
881
- expect(result.totalCount).toBe(0);
882
- });
883
-
884
- it("should convert SurrealDB results to model instances", async () => {
885
- const surrealResults = [
886
- {
887
- source: "node:abc123",
888
- source_uri: "literal://recipe1",
889
- links: [
890
- { predicate: "recipe://name", target: "Pasta", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" },
891
- { predicate: "recipe://rating", target: "5", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" },
892
- { predicate: "recipe://ingredient", target: "pasta", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" },
893
- { predicate: "recipe://ingredient", target: "tomato", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" },
894
- { predicate: "recipe://ingredient", target: "cheese", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" }
895
- ]
896
- },
897
- {
898
- source: "node:def456",
899
- source_uri: "literal://recipe2",
900
- links: [
901
- { predicate: "recipe://name", target: "Pizza", author: "did:key:bob", timestamp: "2023-01-02T00:00:00Z" },
902
- { predicate: "recipe://rating", target: "4", author: "did:key:bob", timestamp: "2023-01-02T00:00:00Z" },
903
- { predicate: "recipe://ingredient", target: "dough", author: "did:key:bob", timestamp: "2023-01-02T00:00:00Z" },
904
- { predicate: "recipe://ingredient", target: "cheese", author: "did:key:bob", timestamp: "2023-01-02T00:00:00Z" },
905
- { predicate: "recipe://ingredient", target: "tomato", author: "did:key:bob", timestamp: "2023-01-02T00:00:00Z" }
906
- ]
907
- }
908
- ];
909
-
910
- const result = await Recipe.instancesFromSurrealResult(mockPerspective, {}, surrealResults);
911
-
912
- expect(result.results).toHaveLength(2);
913
- expect(result.totalCount).toBe(2);
914
-
915
- const recipe1 = result.results[0];
916
- expect(recipe1).toBeInstanceOf(Recipe);
917
- expect(recipe1.name).toBe("Pasta");
918
- expect(recipe1.rating).toBe(5);
919
- expect(recipe1.ingredients).toEqual(["pasta", "tomato", "cheese"]);
920
-
921
- const recipe2 = result.results[1];
922
- expect(recipe2).toBeInstanceOf(Recipe);
923
- expect(recipe2.name).toBe("Pizza");
924
- expect(recipe2.rating).toBe(4);
925
- });
926
-
927
- it("should filter properties when query specifies properties", async () => {
928
- const surrealResults = [
929
- {
930
- source: "node:abc123",
931
- source_uri: "literal://recipe1",
932
- links: [
933
- { predicate: "recipe://name", target: "Pasta", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" },
934
- { predicate: "recipe://rating", target: "5", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" },
935
- { predicate: "recipe://ingredient", target: "pasta", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" },
936
- { predicate: "recipe://ingredient", target: "tomato", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" }
937
- ]
938
- }
939
- ];
940
-
941
- const result = await Recipe.instancesFromSurrealResult(
942
- mockPerspective,
943
- { properties: ["name"] },
944
- surrealResults
945
- );
946
-
947
- expect(result.results).toHaveLength(1);
948
- const recipe = result.results[0];
949
- expect(recipe.name).toBe("Pasta");
950
- // rating and ingredients should be removed since only "name" was requested
951
- expect(recipe.rating).toBeUndefined();
952
- expect(recipe.ingredients).toBeUndefined();
953
- // author, createdAt, updatedAt are also stripped unless explicitly requested
954
- expect(recipe.author).toBeUndefined();
955
- expect(recipe.timestamp).toBeUndefined();
956
- });
957
-
958
- it("should filter properties when query specifies properties", async () => {
959
- const surrealResults = [
960
- {
961
- source: "node:abc123",
962
- source_uri: "literal://recipe1",
963
- links: [
964
- { predicate: "recipe://name", target: "Pasta", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" },
965
- { predicate: "recipe://rating", target: "5", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" },
966
- { predicate: "recipe://ingredient", target: "pasta", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" },
967
- { predicate: "recipe://ingredient", target: "tomato", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" }
968
- ]
969
- }
970
- ];
971
-
972
- const result = await Recipe.instancesFromSurrealResult(
973
- mockPerspective,
974
- { properties: ["name"] },
975
- surrealResults
976
- );
977
-
978
- expect(result.results).toHaveLength(1);
979
- const recipe = result.results[0];
980
- expect(recipe.name).toBe("Pasta");
981
- // rating and ingredients should be removed since only "name" was requested
982
- expect(recipe.rating).toBeUndefined();
983
- });
984
-
985
- it("should handle results missing base field", async () => {
986
- const surrealResults = [
987
- {
988
- links: [
989
- { predicate: "recipe://name", target: "Pasta", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" },
990
- { predicate: "recipe://rating", target: "5", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" }
991
- ]
992
- // Missing source field
993
- } as any
994
- ];
995
-
996
- const result = await Recipe.instancesFromSurrealResult(mockPerspective, {}, surrealResults);
997
-
998
- // Should filter out the invalid result (or handle gracefully)
999
- expect(result.results).toHaveLength(0);
1000
- expect(result.totalCount).toBe(0);
1001
- });
1002
-
1003
- it("should use SurrealDB by default in findAll()", async () => {
1004
- const surrealResults = [
1005
- {
1006
- source: "node:abc123",
1007
- source_uri: "literal://recipe1",
1008
- links: [
1009
- { predicate: "recipe://name", target: "Pasta", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" },
1010
- { predicate: "recipe://rating", target: "5", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" },
1011
- { predicate: "recipe://ingredient", target: "pasta", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" }
1012
- ]
1013
- }
1014
- ];
1015
-
1016
- mockPerspective.querySurrealDB.mockResolvedValue(surrealResults);
648
+ it("routes findAll() through modelQuery", async () => {
649
+ mockPerspective.modelQuery.mockResolvedValue({
650
+ instances: [
651
+ { id: "literal:recipe1", name: "Pasta", rating: 5, ingredients: ["pasta"] }
652
+ ],
653
+ totalCount: 1
654
+ });
1017
655
 
1018
- const results = await Recipe.findAll(mockPerspective, {});
656
+ const results = await Recipe.findAll(mockPerspective);
1019
657
 
1020
- expect(mockPerspective.querySurrealDB).toHaveBeenCalledTimes(1);
658
+ expect(mockPerspective.modelQuery).toHaveBeenCalledTimes(1);
1021
659
  expect(mockPerspective.infer).not.toHaveBeenCalled();
1022
660
  expect(results).toHaveLength(1);
1023
661
  expect(results[0].name).toBe("Pasta");
1024
662
  });
1025
663
 
1026
- it("should use Prolog when useSurrealDB is false in findAll()", async () => {
1027
- const prologResults = [{
1028
- AllInstances: [
1029
- ["literal://recipe1", [["name", "Pasta"]], [["ingredients", ["pasta"]]], "2023-01-01T00:00:00Z", "did:key:alice"]
664
+ it("should use SPARQL when engine is 'sparql' in findAllAndCount()", async () => {
665
+ mockPerspective.modelQuery.mockResolvedValue({
666
+ instances: [
667
+ { id: "literal:recipe1", name: "Pasta", rating: 5, ingredients: ["pasta"] }
1030
668
  ],
1031
- TotalCount: 1
1032
- }];
1033
-
1034
- mockPerspective.infer.mockResolvedValue(prologResults);
1035
-
1036
- const results = await Recipe.findAll(mockPerspective, {}, false);
1037
-
1038
- expect(mockPerspective.infer).toHaveBeenCalledTimes(1);
1039
- expect(mockPerspective.querySurrealDB).not.toHaveBeenCalled();
1040
- expect(results).toHaveLength(1);
1041
- });
1042
-
1043
- it("should use SurrealDB by default in findAllAndCount()", async () => {
1044
- const surrealResults = [
1045
- {
1046
- source: "node:abc123",
1047
- source_uri: "literal://recipe1",
1048
- links: [
1049
- { predicate: "recipe://name", target: "Pasta", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" },
1050
- { predicate: "recipe://rating", target: "5", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" },
1051
- { predicate: "recipe://ingredient", target: "pasta", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" }
1052
- ]
1053
- }
1054
- ];
1055
-
1056
- mockPerspective.querySurrealDB.mockResolvedValue(surrealResults);
669
+ totalCount: 1
670
+ });
1057
671
 
1058
672
  const { results, totalCount } = await Recipe.findAllAndCount(mockPerspective, {});
1059
673
 
1060
- expect(mockPerspective.querySurrealDB).toHaveBeenCalledTimes(1);
674
+ expect(mockPerspective.modelQuery).toHaveBeenCalledTimes(1);
1061
675
  expect(mockPerspective.infer).not.toHaveBeenCalled();
1062
676
  expect(results).toHaveLength(1);
1063
677
  expect(totalCount).toBe(1);
1064
678
  });
1065
679
 
1066
- it("should use SurrealDB by default in paginate()", async () => {
1067
- const surrealResults = [
1068
- {
1069
- source: "node:abc123",
1070
- source_uri: "literal://recipe1",
1071
- links: [
1072
- { predicate: "recipe://name", target: "Pasta", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" },
1073
- { predicate: "recipe://rating", target: "5", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" },
1074
- { predicate: "recipe://ingredient", target: "pasta", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" }
1075
- ]
1076
- }
1077
- ];
1078
-
1079
- mockPerspective.querySurrealDB.mockResolvedValue(surrealResults);
680
+ it("should use SPARQL when engine is 'sparql' in paginate()", async () => {
681
+ mockPerspective.modelQuery.mockResolvedValue({
682
+ instances: [
683
+ { id: "literal:recipe1", name: "Pasta", rating: 5, ingredients: ["pasta"] }
684
+ ],
685
+ totalCount: 1
686
+ });
1080
687
 
1081
688
  const page = await Recipe.paginate(mockPerspective, 10, 1, {});
1082
689
 
1083
- expect(mockPerspective.querySurrealDB).toHaveBeenCalledTimes(1);
690
+ expect(mockPerspective.modelQuery).toHaveBeenCalledTimes(1);
1084
691
  expect(mockPerspective.infer).not.toHaveBeenCalled();
1085
692
  expect(page.results).toHaveLength(1);
1086
693
  expect(page.pageSize).toBe(10);
1087
694
  expect(page.pageNumber).toBe(1);
695
+ expect(page.totalCount).toBe(1);
1088
696
  });
1089
697
 
1090
- it("should use SurrealDB by default in count()", async () => {
1091
- // Since count() uses result.length and GROUP BY returns one row per source,
1092
- // mock 5 recipe sources
1093
- const surrealResults = Array.from({ length: 5 }, (_, i) => ({
1094
- source: `node:abc${i+1}`,
1095
- source_uri: `literal://recipe${i+1}`,
1096
- links: [
1097
- { predicate: "recipe://name", target: `Recipe ${i+1}`, author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" },
1098
- { predicate: "recipe://rating", target: "5", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" }
1099
- ]
1100
- }));
1101
-
1102
- mockPerspective.querySurrealDB.mockResolvedValue(surrealResults);
698
+ it("should use SPARQL in count()", async () => {
699
+ mockPerspective.modelQuery.mockResolvedValue({
700
+ instances: [],
701
+ totalCount: 5
702
+ });
1103
703
 
1104
704
  const count = await Recipe.count(mockPerspective, {});
1105
705
 
1106
- expect(mockPerspective.querySurrealDB).toHaveBeenCalledTimes(1);
706
+ expect(mockPerspective.modelQuery).toHaveBeenCalledTimes(1);
1107
707
  expect(mockPerspective.infer).not.toHaveBeenCalled();
1108
708
  expect(count).toBe(5);
1109
709
  });
1110
710
 
1111
- it("should use Prolog when useSurrealDB is false in count()", async () => {
1112
- const prologResults = [{ TotalCount: 10 }];
1113
- mockPerspective.infer.mockResolvedValue(prologResults);
711
+ it("should return count from modelQuery", async () => {
712
+ mockPerspective.modelQuery.mockResolvedValue({
713
+ instances: [],
714
+ totalCount: 10
715
+ });
1114
716
 
1115
- const count = await Recipe.count(mockPerspective, {}, false);
717
+ const count = await Recipe.count(mockPerspective, {});
1116
718
 
1117
- expect(mockPerspective.infer).toHaveBeenCalledTimes(1);
1118
- expect(mockPerspective.querySurrealDB).not.toHaveBeenCalled();
719
+ expect(mockPerspective.modelQuery).toHaveBeenCalledTimes(1);
720
+ expect(mockPerspective.querySparql).not.toHaveBeenCalled();
1119
721
  expect(count).toBe(10);
1120
722
  });
1121
723
 
1122
- it("should use SurrealDB by default in ModelQueryBuilder.get()", async () => {
1123
- const surrealResults = [
1124
- {
1125
- source: "node:abc123",
1126
- source_uri: "literal://recipe1",
1127
- links: [
1128
- { predicate: "recipe://name", target: "Pasta", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" },
1129
- { predicate: "recipe://rating", target: "5", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" },
1130
- { predicate: "recipe://ingredient", target: "pasta", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" }
1131
- ]
1132
- }
1133
- ];
1134
-
1135
- mockPerspective.querySurrealDB.mockResolvedValue(surrealResults);
724
+ it("routes ModelQueryBuilder.get() through modelQuery", async () => {
725
+ mockPerspective.modelQuery.mockResolvedValue({
726
+ instances: [
727
+ { id: "literal:recipe1", name: "Pasta", rating: 5, ingredients: ["pasta"] }
728
+ ],
729
+ totalCount: 1
730
+ });
1136
731
 
1137
732
  const results = await Recipe.query(mockPerspective)
1138
733
  .where({ name: "Pasta" })
1139
734
  .get();
1140
735
 
1141
- expect(mockPerspective.querySurrealDB).toHaveBeenCalledTimes(1);
736
+ expect(mockPerspective.modelQuery).toHaveBeenCalledTimes(1);
1142
737
  expect(mockPerspective.infer).not.toHaveBeenCalled();
1143
738
  expect(results).toHaveLength(1);
1144
739
  expect(results[0].name).toBe("Pasta");
1145
740
  });
1146
741
 
1147
- it("should use Prolog when useSurrealDB(false) in ModelQueryBuilder.get()", async () => {
1148
- const prologResults = [{
1149
- AllInstances: [
1150
- ["literal://recipe1", [["name", "Pasta"]], [["ingredients", ["pasta"]]], "2023-01-01T00:00:00Z", "did:key:alice"]
1151
- ],
1152
- TotalCount: 1
1153
- }];
1154
-
1155
- mockPerspective.infer.mockResolvedValue(prologResults);
1156
-
1157
- const results = await Recipe.query(mockPerspective)
1158
- .where({ name: "Pasta" })
1159
- .useSurrealDB(false)
1160
- .get();
1161
-
1162
- expect(mockPerspective.infer).toHaveBeenCalledTimes(1);
1163
- expect(mockPerspective.querySurrealDB).not.toHaveBeenCalled();
1164
- expect(results).toHaveLength(1);
1165
- });
1166
-
1167
- it("should use SurrealDB by default in ModelQueryBuilder.count()", async () => {
1168
- // count() counts the number of rows returned by the query (one row per source)
1169
- const surrealResults = Array.from({ length: 3 }, (_, i) => ({
1170
- source: `node:abc${i+1}`,
1171
- source_uri: `literal://recipe${i+1}`,
1172
- links: [
1173
- { predicate: "recipe://name", target: `Recipe ${i+1}`, author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" },
1174
- { predicate: "recipe://rating", target: "5", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" }
1175
- ]
1176
- }));
1177
- mockPerspective.querySurrealDB.mockResolvedValue(surrealResults);
742
+ it("routes ModelQueryBuilder.count() through modelQuery", async () => {
743
+ mockPerspective.modelQuery.mockResolvedValue({
744
+ instances: [],
745
+ totalCount: 3
746
+ });
1178
747
 
1179
748
  const count = await Recipe.query(mockPerspective)
1180
749
  .where({ rating: { gt: 4 } })
1181
750
  .count();
1182
751
 
1183
- expect(mockPerspective.querySurrealDB).toHaveBeenCalledTimes(1);
752
+ expect(mockPerspective.modelQuery).toHaveBeenCalledTimes(1);
1184
753
  expect(mockPerspective.infer).not.toHaveBeenCalled();
1185
754
  expect(count).toBe(3);
1186
755
  });
1187
756
 
1188
- it("should use SurrealDB by default in ModelQueryBuilder.paginate()", async () => {
1189
- const surrealResults = [
1190
- {
1191
- source: "node:abc123",
1192
- source_uri: "literal://recipe1",
1193
- links: [
1194
- { predicate: "recipe://name", target: "Pasta", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" },
1195
- { predicate: "recipe://rating", target: "5", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" },
1196
- { predicate: "recipe://ingredient", target: "pasta", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" }
1197
- ]
1198
- }
1199
- ];
1200
-
1201
- mockPerspective.querySurrealDB.mockResolvedValue(surrealResults);
757
+ it("routes ModelQueryBuilder.paginate() through modelQuery", async () => {
758
+ mockPerspective.modelQuery.mockResolvedValue({
759
+ instances: [
760
+ { id: "literal:recipe1", name: "Pasta", rating: 5, ingredients: ["pasta"] }
761
+ ],
762
+ totalCount: 1
763
+ });
1202
764
 
1203
765
  const page = await Recipe.query(mockPerspective)
1204
766
  .where({ rating: { gt: 3 } })
1205
767
  .paginate(10, 1);
1206
768
 
1207
- expect(mockPerspective.querySurrealDB).toHaveBeenCalledTimes(1);
769
+ expect(mockPerspective.modelQuery).toHaveBeenCalledTimes(1);
1208
770
  expect(mockPerspective.infer).not.toHaveBeenCalled();
1209
771
  expect(page.results).toHaveLength(1);
1210
772
  expect(page.pageSize).toBe(10);
@@ -1228,7 +790,8 @@ describe("Ad4mModel.count() with advanced where conditions", () => {
1228
790
 
1229
791
  // Mock perspective
1230
792
  const mockPerspective = {
1231
- querySurrealDB: jest.fn(),
793
+ querySparql: jest.fn(),
794
+ modelQuery: jest.fn(),
1232
795
  infer: jest.fn(),
1233
796
  uuid: 'test-perspective-uuid',
1234
797
  stringOrTemplateObjectToSubjectClassName: jest.fn().mockResolvedValue('Recipe')
@@ -1238,177 +801,95 @@ describe("Ad4mModel.count() with advanced where conditions", () => {
1238
801
  jest.clearAllMocks();
1239
802
  });
1240
803
 
1241
- it("should apply JS-level filtering for gt operator on properties in SurrealDB count()", async () => {
1242
- // Mock SurrealDB results: 5 recipes with ratings 1, 2, 3, 4, 5
1243
- const surrealResults = Array.from({ length: 5 }, (_, i) => ({
1244
- source: `node:abc${i+1}`,
1245
- source_uri: `literal://recipe${i+1}`,
1246
- links: [
1247
- { predicate: "recipe://name", target: `Recipe ${i+1}`, author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" },
1248
- { predicate: "recipe://rating", target: `${i+1}`, author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" }
1249
- ]
1250
- }));
1251
-
1252
- mockPerspective.querySurrealDB.mockResolvedValue(surrealResults);
804
+ it("should apply filtering for gt operator on properties in SPARQL count()", async () => {
805
+ // With the new modelQuery endpoint, filtering happens server-side in Rust
806
+ mockPerspective.modelQuery.mockResolvedValue({
807
+ instances: [],
808
+ totalCount: 2
809
+ });
1253
810
 
1254
811
  // Count recipes with rating > 3 (should match 2 recipes: rating 4 and 5)
1255
812
  const count = await Recipe.count(mockPerspective, { where: { rating: { gt: 3 } } });
1256
813
 
1257
- // Verify count matches the number of instances that would be returned by findAll
1258
- const findAllResults = await Recipe.findAll(mockPerspective, { where: { rating: { gt: 3 } } });
1259
-
1260
814
  expect(count).toBe(2);
1261
- expect(count).toBe(findAllResults.length);
1262
- });
1263
-
1264
- it("should apply JS-level filtering for between operator on properties in SurrealDB count()", async () => {
1265
- // Mock SurrealDB results: 5 recipes with ratings 1, 2, 3, 4, 5
1266
- const surrealResults = Array.from({ length: 5 }, (_, i) => ({
1267
- source: `node:abc${i+1}`,
1268
- source_uri: `literal://recipe${i+1}`,
1269
- links: [
1270
- { predicate: "recipe://name", target: `Recipe ${i+1}`, author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" },
1271
- { predicate: "recipe://rating", target: `${i+1}`, author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" }
1272
- ]
1273
- }));
1274
-
1275
- mockPerspective.querySurrealDB.mockResolvedValue(surrealResults);
815
+ expect(mockPerspective.modelQuery).toHaveBeenCalled();
816
+ });
817
+
818
+ it("should apply filtering for between operator on properties in SPARQL count()", async () => {
819
+ mockPerspective.modelQuery.mockResolvedValue({
820
+ instances: [],
821
+ totalCount: 3
822
+ });
1276
823
 
1277
824
  // Count recipes with rating between 2 and 4 (should match 3 recipes: rating 2, 3, 4)
1278
825
  const count = await Recipe.count(mockPerspective, { where: { rating: { between: [2, 4] } } });
1279
826
 
1280
- // Verify count matches the number of instances that would be returned by findAll
1281
- const findAllResults = await Recipe.findAll(mockPerspective, { where: { rating: { between: [2, 4] } } });
1282
-
1283
827
  expect(count).toBe(3);
1284
- expect(count).toBe(findAllResults.length);
1285
- });
1286
-
1287
- it("should apply JS-level filtering for timestamp gt operator in SurrealDB count()", async () => {
1288
- // Mock SurrealDB results: 5 recipes with different timestamps
1289
- const surrealResults = Array.from({ length: 5 }, (_, i) => ({
1290
- source: `node:abc${i+1}`,
1291
- source_uri: `literal://recipe${i+1}`,
1292
- links: [
1293
- { predicate: "recipe://name", target: `Recipe ${i+1}`, author: "did:key:alice", timestamp: `2023-01-0${i+1}T00:00:00Z` },
1294
- { predicate: "recipe://rating", target: "5", author: "did:key:alice", timestamp: `2023-01-0${i+1}T00:00:00Z` }
1295
- ]
1296
- }));
1297
-
1298
- mockPerspective.querySurrealDB.mockResolvedValue(surrealResults);
828
+ expect(mockPerspective.modelQuery).toHaveBeenCalled();
829
+ });
830
+
831
+ it("should apply filtering for timestamp gt operator in SPARQL count()", async () => {
832
+ mockPerspective.modelQuery.mockResolvedValue({
833
+ instances: [],
834
+ totalCount: 2
835
+ });
1299
836
 
1300
- // Count recipes with timestamp > 2023-01-03 (should match 2 recipes: 2023-01-04 and 2023-01-05)
1301
837
  const targetTimestamp = new Date("2023-01-03T00:00:00Z").getTime();
1302
838
  const count = await Recipe.count(mockPerspective, { where: { timestamp: { gt: targetTimestamp } } });
1303
839
 
1304
- // Verify count matches the number of instances that would be returned by findAll
1305
- const findAllResults = await Recipe.findAll(mockPerspective, { where: { timestamp: { gt: targetTimestamp } } });
1306
-
1307
840
  expect(count).toBe(2);
1308
- expect(count).toBe(findAllResults.length);
1309
- });
1310
-
1311
- it("should apply JS-level filtering for timestamp between operator in SurrealDB count()", async () => {
1312
- // Mock SurrealDB results: 5 recipes with different timestamps
1313
- const surrealResults = Array.from({ length: 5 }, (_, i) => ({
1314
- source: `node:abc${i+1}`,
1315
- source_uri: `literal://recipe${i+1}`,
1316
- links: [
1317
- { predicate: "recipe://name", target: `Recipe ${i+1}`, author: "did:key:alice", timestamp: `2023-01-0${i+1}T00:00:00Z` },
1318
- { predicate: "recipe://rating", target: "5", author: "did:key:alice", timestamp: `2023-01-0${i+1}T00:00:00Z` }
1319
- ]
1320
- }));
1321
-
1322
- mockPerspective.querySurrealDB.mockResolvedValue(surrealResults);
841
+ expect(mockPerspective.modelQuery).toHaveBeenCalled();
842
+ });
843
+
844
+ it("should apply filtering for timestamp between operator in SPARQL count()", async () => {
845
+ mockPerspective.modelQuery.mockResolvedValue({
846
+ instances: [],
847
+ totalCount: 3
848
+ });
1323
849
 
1324
- // Count recipes with timestamp between 2023-01-02 and 2023-01-04
1325
850
  const startTimestamp = new Date("2023-01-02T00:00:00Z").getTime();
1326
851
  const endTimestamp = new Date("2023-01-04T00:00:00Z").getTime();
1327
852
  const count = await Recipe.count(mockPerspective, {
1328
853
  where: { timestamp: { between: [startTimestamp, endTimestamp] } }
1329
854
  });
1330
855
 
1331
- // Verify count matches the number of instances that would be returned by findAll
1332
- const findAllResults = await Recipe.findAll(mockPerspective, {
1333
- where: { timestamp: { between: [startTimestamp, endTimestamp] } }
1334
- });
1335
-
1336
856
  expect(count).toBe(3);
1337
- expect(count).toBe(findAllResults.length);
1338
- });
1339
-
1340
- it("should apply JS-level filtering for author filtering in SurrealDB count()", async () => {
1341
- // Mock SurrealDB results: 3 recipes by Alice and 2 by Bob
1342
- const surrealResults = [
1343
- ...Array.from({ length: 3 }, (_, i) => ({
1344
- source: `node:abc${i+1}`,
1345
- source_uri: `literal://recipe${i+1}`,
1346
- links: [
1347
- { predicate: "recipe://name", target: `Recipe ${i+1}`, author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" },
1348
- { predicate: "recipe://rating", target: "5", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" }
1349
- ]
1350
- })),
1351
- ...Array.from({ length: 2 }, (_, i) => ({
1352
- source: `node:def${i+4}`,
1353
- source_uri: `literal://recipe${i+4}`,
1354
- links: [
1355
- { predicate: "recipe://name", target: `Recipe ${i+4}`, author: "did:key:bob", timestamp: "2023-01-02T00:00:00Z" },
1356
- { predicate: "recipe://rating", target: "5", author: "did:key:bob", timestamp: "2023-01-02T00:00:00Z" }
1357
- ]
1358
- }))
1359
- ];
1360
-
1361
- mockPerspective.querySurrealDB.mockResolvedValue(surrealResults);
857
+ expect(mockPerspective.modelQuery).toHaveBeenCalled();
858
+ });
859
+
860
+ it("should apply filtering for author filtering in SPARQL count()", async () => {
861
+ mockPerspective.modelQuery.mockResolvedValue({
862
+ instances: [],
863
+ totalCount: 3
864
+ });
1362
865
 
1363
866
  // Count recipes by Alice (should match 3 recipes)
1364
867
  const count = await Recipe.count(mockPerspective, { where: { author: "did:key:alice" } });
1365
868
 
1366
- // Verify count matches the number of instances that would be returned by findAll
1367
- const findAllResults = await Recipe.findAll(mockPerspective, { where: { author: "did:key:alice" } });
1368
-
1369
869
  expect(count).toBe(3);
1370
- expect(count).toBe(findAllResults.length);
1371
- });
1372
-
1373
- it("should apply JS-level filtering in ModelQueryBuilder.count() with gt operator", async () => {
1374
- // Mock SurrealDB results: 5 recipes with ratings 1, 2, 3, 4, 5
1375
- const surrealResults = Array.from({ length: 5 }, (_, i) => ({
1376
- source: `node:abc${i+1}`,
1377
- source_uri: `literal://recipe${i+1}`,
1378
- links: [
1379
- { predicate: "recipe://name", target: `Recipe ${i+1}`, author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" },
1380
- { predicate: "recipe://rating", target: `${i+1}`, author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" }
1381
- ]
1382
- }));
1383
-
1384
- mockPerspective.querySurrealDB.mockResolvedValue(surrealResults);
870
+ expect(mockPerspective.modelQuery).toHaveBeenCalled();
871
+ });
872
+
873
+ it("should apply filtering in ModelQueryBuilder.count() with gt operator", async () => {
874
+ mockPerspective.modelQuery.mockResolvedValue({
875
+ instances: [],
876
+ totalCount: 2
877
+ });
1385
878
 
1386
879
  // Count recipes with rating > 3 using ModelQueryBuilder
1387
880
  const count = await Recipe.query(mockPerspective)
1388
881
  .where({ rating: { gt: 3 } })
1389
882
  .count();
1390
883
 
1391
- // Verify count matches the number of instances that would be returned by get()
1392
- const getResults = await Recipe.query(mockPerspective)
1393
- .where({ rating: { gt: 3 } })
1394
- .get();
1395
-
1396
884
  expect(count).toBe(2);
1397
- expect(count).toBe(getResults.length);
1398
- });
1399
-
1400
- it("should apply JS-level filtering in ModelQueryBuilder.count() with timestamp between", async () => {
1401
- // Mock SurrealDB results: 5 recipes with different timestamps
1402
- const surrealResults = Array.from({ length: 5 }, (_, i) => ({
1403
- source: `node:abc${i+1}`,
1404
- source_uri: `literal://recipe${i+1}`,
1405
- links: [
1406
- { predicate: "recipe://name", target: `Recipe ${i+1}`, author: "did:key:alice", timestamp: `2023-01-0${i+1}T00:00:00Z` },
1407
- { predicate: "recipe://rating", target: "5", author: "did:key:alice", timestamp: `2023-01-0${i+1}T00:00:00Z` }
1408
- ]
1409
- }));
1410
-
1411
- mockPerspective.querySurrealDB.mockResolvedValue(surrealResults);
885
+ expect(mockPerspective.modelQuery).toHaveBeenCalled();
886
+ });
887
+
888
+ it("should apply filtering in ModelQueryBuilder.count() with timestamp between", async () => {
889
+ mockPerspective.modelQuery.mockResolvedValue({
890
+ instances: [],
891
+ totalCount: 3
892
+ });
1412
893
 
1413
894
  const startTimestamp = new Date("2023-01-02T00:00:00Z").getTime();
1414
895
  const endTimestamp = new Date("2023-01-04T00:00:00Z").getTime();
@@ -1418,42 +899,1433 @@ describe("Ad4mModel.count() with advanced where conditions", () => {
1418
899
  .where({ timestamp: { between: [startTimestamp, endTimestamp] } })
1419
900
  .count();
1420
901
 
1421
- // Verify count matches the number of instances that would be returned by get()
1422
- const getResults = await Recipe.query(mockPerspective)
1423
- .where({ timestamp: { between: [startTimestamp, endTimestamp] } })
1424
- .get();
1425
-
1426
902
  expect(count).toBe(3);
1427
- expect(count).toBe(getResults.length);
903
+ expect(mockPerspective.modelQuery).toHaveBeenCalled();
1428
904
  });
1429
905
 
1430
- it("should handle count() with Prolog for gt operator (legacy)", async () => {
1431
- const prologResults = [{ TotalCount: 2 }];
1432
- mockPerspective.infer.mockResolvedValue(prologResults);
906
+ });
1433
907
 
1434
- const count = await Recipe.count(mockPerspective, { where: { rating: { gt: 3 } } }, false);
1435
-
1436
- expect(mockPerspective.infer).toHaveBeenCalledTimes(1);
1437
- expect(mockPerspective.querySurrealDB).not.toHaveBeenCalled();
1438
- expect(count).toBe(2);
908
+
909
+ describe("SPARQL comparison filters", () => {
910
+ @Model({ name: "Item" })
911
+ class Item extends Ad4mModel {
912
+ @Property({ through: "item://price", required: true })
913
+ price!: string;
914
+
915
+ @Property({ through: "item://name", required: true })
916
+ name!: string;
917
+ }
918
+
919
+ it("should generate gt filter", async () => {
920
+ const mockPersp = { getLinks: jest.fn().mockResolvedValue([]) } as any;
921
+ const query = await (Item as any).queryToSPARQL(mockPersp, { where: { price: { gt: 10 } } });
922
+ // gt is now JS post-filter — SPARQL just joins the property
923
+ expect(query).toContain("item://price");
1439
924
  });
1440
925
 
1441
- it("should handle count() with Prolog for timestamp between (legacy)", async () => {
1442
- const prologResults = [{ TotalCount: 3 }];
1443
- mockPerspective.infer.mockResolvedValue(prologResults);
926
+ it("should generate between filter", async () => {
927
+ const mockPersp = { getLinks: jest.fn().mockResolvedValue([]) } as any;
928
+ const query = await (Item as any).queryToSPARQL(mockPersp, { where: { price: { between: [5, 20] } } });
929
+ // between is now JS post-filter
930
+ expect(query).toContain("item://price");
931
+ });
1444
932
 
1445
- const startTimestamp = new Date("2023-01-02T00:00:00Z").getTime();
1446
- const endTimestamp = new Date("2023-01-04T00:00:00Z").getTime();
1447
-
1448
- const count = await Recipe.count(
1449
- mockPerspective,
1450
- { where: { timestamp: { between: [startTimestamp, endTimestamp] } } },
1451
- false
1452
- );
1453
-
1454
- expect(mockPerspective.infer).toHaveBeenCalledTimes(1);
1455
- expect(mockPerspective.querySurrealDB).not.toHaveBeenCalled();
1456
- expect(count).toBe(3);
933
+ it("should generate contains filter", async () => {
934
+ const mockPersp = { getLinks: jest.fn().mockResolvedValue([]) } as any;
935
+ const query = await (Item as any).queryToSPARQL(mockPersp, { where: { name: { contains: "widget" } } });
936
+ // contains is now JS post-filter
937
+ expect(query).toContain("item://name");
938
+ });
939
+ });
940
+
941
+ // ──────────────────────────────────────────────────────────
942
+ // SPARQL Direct Triple Pattern & IRI Tests
943
+ // ──────────────────────────────────────────────────────────
944
+
945
+ import { buildSPARQLQuery, formatSPARQLValue } from "./query-sparql";
946
+ import { SHACLShape } from "../shacl/SHACLShape";
947
+
948
+ describe("SPARQL direct triple pattern generation", () => {
949
+ @Model({ name: "Channel" })
950
+ class Channel extends Ad4mModel {
951
+ @Flag({ through: "flux://entry_type", value: "flux://channel" })
952
+ type: string = "";
953
+
954
+ @Property({ through: "flux://name", resolveLanguage: "literal", required: true })
955
+ name: string = "";
956
+
957
+ @Optional({ through: "flux://description" })
958
+ description: string = "";
959
+
960
+ @HasMany({ through: "flux://has_message" })
961
+ messages: string[] = [];
962
+ }
963
+
964
+ const mockPersp = {} as any;
965
+
966
+ it("generates direct triple pattern with ?source ?predicate ?target", async () => {
967
+ const query = await (Channel as any).queryToSPARQL(mockPersp, {});
968
+ // Must use direct triple pattern, not link-node reification
969
+ expect(query).toContain("?source ?predicate ?target");
970
+ expect(query).not.toContain("rdf:type");
971
+ expect(query).not.toContain("ad4m:Link");
972
+ });
973
+
974
+ it("generates Flag filter as ?source <predicate> <value>", async () => {
975
+ const query = await (Channel as any).queryToSPARQL(mockPersp, {});
976
+ expect(query).toContain("<flux://entry_type>");
977
+ expect(query).toContain("<flux://channel>");
978
+ });
979
+
980
+ it("generates Property binding as ?source <predicate> ?varName", async () => {
981
+ const query = await (Channel as any).queryToSPARQL(mockPersp, {});
982
+ expect(query).toContain("<flux://name>");
983
+ expect(query).toMatch(/\?source\s+<flux:\/\/name>\s+\?cfTarget_name/);
984
+ });
985
+
986
+ it("uses RDF 1.2 reifier pattern for author/timestamp", async () => {
987
+ const query = await (Channel as any).queryToSPARQL(mockPersp, {});
988
+ expect(query).toContain("<http://www.w3.org/1999/02/22-rdf-syntax-ns#reifies>");
989
+ expect(query).toContain("?source ?predicate ?target .");
990
+ expect(query).toContain("?_reifier <http://www.w3.org/1999/02/22-rdf-syntax-ns#reifies> <<( ?source ?predicate ?target )>>");
991
+ expect(query).toContain("?_reifier <ad4m://ontology/author> ?author");
992
+ expect(query).toContain("?_reifier <ad4m://ontology/timestamp> ?timestamp");
993
+ expect(query).not.toContain("GRAPH");
994
+ });
995
+
996
+ it("uses FILTER(isIRI(?source)) to exclude non-IRI subjects", async () => {
997
+ const query = await (Channel as any).queryToSPARQL(mockPersp, {});
998
+ expect(query).toContain("FILTER(isIRI(?source)");
1457
999
  });
1458
1000
  });
1459
1001
 
1002
+
1003
+
1004
+ describe("formatSPARQLValue", () => {
1005
+ it("wraps strings in double quotes", () => {
1006
+ expect(formatSPARQLValue("hello")).toBe('"hello"');
1007
+ });
1008
+
1009
+ it("escapes special characters", () => {
1010
+ expect(formatSPARQLValue('say "hi"')).toBe('"say \\"hi\\""');
1011
+ });
1012
+
1013
+ it("converts numbers to quoted strings", () => {
1014
+ expect(formatSPARQLValue(42)).toBe('"42"');
1015
+ });
1016
+ });
1017
+
1018
+ // ──────────────────────────────────────────────────────────
1019
+ // Comprehensive SPARQL migration unit tests
1020
+ // ──────────────────────────────────────────────────────────
1021
+
1022
+ import { Literal } from "../Literal";
1023
+
1024
+ // Helper: create literal URLs using JSON encoding (which handles all types including booleans)
1025
+ function literalUrl(value: any): string {
1026
+ if (typeof value === 'string') return Literal.from(value).toUrl();
1027
+ // Use JSON encoding for numbers and booleans since Literal.get() doesn't handle boolean: prefix
1028
+ return `literal:json:${encodeURIComponent(JSON.stringify(value))}`;
1029
+ }
1030
+
1031
+ describe("buildSPARQLQuery edge cases", () => {
1032
+ @Model({ name: "FlagModel" })
1033
+ class FlagModel extends Ad4mModel {
1034
+ @Flag({ through: "flag://type", value: "flag://FlagModel" })
1035
+ type: string = "";
1036
+
1037
+ @Property({ through: "flag://name", resolveLanguage: "literal", required: true })
1038
+ name: string = "";
1039
+ }
1040
+
1041
+ @Model({ name: "NoFlagModel" })
1042
+ class NoFlagModel extends Ad4mModel {
1043
+ @Property({ through: "noflag://title", resolveLanguage: "literal" })
1044
+ title: string = "";
1045
+ }
1046
+
1047
+ it("adds conformance JOIN for flag + required properties", () => {
1048
+ const metadata = FlagModel.getModelMetadata();
1049
+ const allRelsMeta = {} as any;
1050
+ const sparql = buildSPARQLQuery(metadata, allRelsMeta, {}, FlagModel);
1051
+ // Should contain flag triple pattern
1052
+ expect(sparql).toContain("<flag://type>");
1053
+ expect(sparql).toContain("<flag://FlagModel>");
1054
+ // Should contain required property pattern
1055
+ expect(sparql).toContain("<flag://name>");
1056
+ });
1057
+
1058
+ it("uses structural subquery when no conformance patterns exist", () => {
1059
+ const metadata = NoFlagModel.getModelMetadata();
1060
+ const allRelsMeta = {} as any;
1061
+ const sparql = buildSPARQLQuery(metadata, allRelsMeta, {}, NoFlagModel);
1062
+ // Should contain structural subquery with DISTINCT
1063
+ expect(sparql).toContain("SELECT DISTINCT ?source");
1064
+ expect(sparql).toContain("<noflag://title>");
1065
+ });
1066
+
1067
+ it("adds JOIN for where-clause on literal-stored fields", () => {
1068
+ const metadata = FlagModel.getModelMetadata();
1069
+ const allRelsMeta = {} as any;
1070
+ const sparql = buildSPARQLQuery(metadata, allRelsMeta, { where: { name: "test" } }, FlagModel);
1071
+ // Where clause should add a join pattern for name
1072
+ expect(sparql).toContain("flag://name");
1073
+ });
1074
+
1075
+ it("handles where: {id: 'specific-id'} with FILTER on ?source", () => {
1076
+ const metadata = FlagModel.getModelMetadata();
1077
+ const allRelsMeta = {} as any;
1078
+ const sparql = buildSPARQLQuery(metadata, allRelsMeta, { where: { id: "expr:123" } as any }, FlagModel);
1079
+ // Should filter by source
1080
+ expect(sparql).toContain("expr:123");
1081
+ });
1082
+ });
1083
+
1084
+ // ── Batch hydration for reverse relations (3.4) ─────────────────────────────
1085
+ describe("Batch hydration for reverse relations", () => {
1086
+ it("batch hydration should correctly group targets by parent instance ID", () => {
1087
+ // Test the grouping logic used in batch SPARQL hydration
1088
+ const sparqlResults = [
1089
+ { target: "inst:1", source: "child:a" },
1090
+ { target: "inst:1", source: "child:b" },
1091
+ { target: "inst:2", source: "child:c" },
1092
+ { target: "inst:3", source: "child:d" },
1093
+ { target: "inst:3", source: "child:e" },
1094
+ { target: "inst:3", source: "child:f" },
1095
+ ];
1096
+
1097
+ const reverseLinksMap = new Map<string, string[]>();
1098
+ for (const row of sparqlResults) {
1099
+ if (!reverseLinksMap.has(row.target)) reverseLinksMap.set(row.target, []);
1100
+ reverseLinksMap.get(row.target)!.push(row.source);
1101
+ }
1102
+
1103
+ expect(reverseLinksMap.get("inst:1")).toEqual(["child:a", "child:b"]);
1104
+ expect(reverseLinksMap.get("inst:2")).toEqual(["child:c"]);
1105
+ expect(reverseLinksMap.get("inst:3")).toEqual(["child:d", "child:e", "child:f"]);
1106
+ });
1107
+
1108
+ it("batch hydration should handle empty relation sets without error", () => {
1109
+ const sparqlResults: any[] = [];
1110
+ const reverseLinksMap = new Map<string, string[]>();
1111
+ for (const row of sparqlResults) {
1112
+ if (!reverseLinksMap.has(row.target)) reverseLinksMap.set(row.target, []);
1113
+ reverseLinksMap.get(row.target)!.push(row.source);
1114
+ }
1115
+
1116
+ expect(reverseLinksMap.size).toBe(0);
1117
+ expect(reverseLinksMap.get("nonexistent") || []).toEqual([]);
1118
+ });
1119
+
1120
+ it("batch hydration should return identical results to N+1 hydration (grouping equivalence)", () => {
1121
+ // Simulate N+1: each instance queries separately
1122
+ const instances = [{ id: "inst:1" }, { id: "inst:2" }];
1123
+ const allLinks = [
1124
+ { data: { source: "child:a", predicate: "rel://has", target: "inst:1" } },
1125
+ { data: { source: "child:b", predicate: "rel://has", target: "inst:1" } },
1126
+ { data: { source: "child:c", predicate: "rel://has", target: "inst:2" } },
1127
+ ];
1128
+
1129
+ // N+1 approach
1130
+ const n1Results = new Map<string, string[]>();
1131
+ for (const inst of instances) {
1132
+ const links = allLinks.filter(l => l.data.target === inst.id);
1133
+ n1Results.set(inst.id, links.map(l => l.data.source));
1134
+ }
1135
+
1136
+ // Batch approach
1137
+ const batchResults = new Map<string, string[]>();
1138
+ const sparqlRows = allLinks.map(l => ({ target: l.data.target, source: l.data.source }));
1139
+ for (const row of sparqlRows) {
1140
+ if (!batchResults.has(row.target)) batchResults.set(row.target, []);
1141
+ batchResults.get(row.target)!.push(row.source);
1142
+ }
1143
+
1144
+ // Results should be identical
1145
+ for (const inst of instances) {
1146
+ expect(batchResults.get(inst.id)).toEqual(n1Results.get(inst.id));
1147
+ }
1148
+ });
1149
+
1150
+ it("batch hydration with nested includes should use batched queries at each level", () => {
1151
+ // This test verifies the structure: nested includes result in multiple
1152
+ // batch operations, one per relation depth level
1153
+ const depth0Rows = [
1154
+ { target: "root:1", source: "mid:a" },
1155
+ { target: "root:1", source: "mid:b" },
1156
+ ];
1157
+ const depth1Rows = [
1158
+ { target: "mid:a", source: "leaf:x" },
1159
+ { target: "mid:b", source: "leaf:y" },
1160
+ ];
1161
+
1162
+ // Group each level
1163
+ const level0Map = new Map<string, string[]>();
1164
+ for (const r of depth0Rows) {
1165
+ if (!level0Map.has(r.target)) level0Map.set(r.target, []);
1166
+ level0Map.get(r.target)!.push(r.source);
1167
+ }
1168
+
1169
+ const level1Map = new Map<string, string[]>();
1170
+ for (const r of depth1Rows) {
1171
+ if (!level1Map.has(r.target)) level1Map.set(r.target, []);
1172
+ level1Map.get(r.target)!.push(r.source);
1173
+ }
1174
+
1175
+ expect(level0Map.get("root:1")).toEqual(["mid:a", "mid:b"]);
1176
+ expect(level1Map.get("mid:a")).toEqual(["leaf:x"]);
1177
+ expect(level1Map.get("mid:b")).toEqual(["leaf:y"]);
1178
+ });
1179
+ });
1180
+
1181
+ // ── Push-down FILTER for literal equality (3.5) ──────────────────────────────
1182
+ describe("Push-down FILTER for literal equality", () => {
1183
+ const mockPerspective = {} as any;
1184
+
1185
+ @Model({ name: "FilterTest" })
1186
+ class FilterTest extends Ad4mModel {
1187
+ @Property({ through: "ft://name", required: true })
1188
+ name: string = "";
1189
+ @Property({ through: "ft://rating", required: true })
1190
+ rating: number = 0;
1191
+ }
1192
+
1193
+ const normalizeQuery = (q: string) => q.replace(/\s+/g, " ").trim();
1194
+
1195
+ it("SPARQL query for where: { name: 'Alice' } should use <ad4m://fn/parse_literal> FILTER", async () => {
1196
+ const query = await (FilterTest as any).queryToSPARQL(mockPerspective, { where: { name: "Alice" } });
1197
+ const norm = normalizeQuery(query);
1198
+ // JOIN pattern exists
1199
+ expect(norm).toContain("?wTarget_name");
1200
+ // parse_literal push-down FILTER is present (using correct SPARQL IRI syntax)
1201
+ expect(norm).toContain("ad4m://fn/parse_literal");
1202
+ expect(norm).not.toContain("fn::parse_literal");
1203
+ });
1204
+
1205
+ it("SPARQL query for where: { name: ['Alice', 'Bob'] } should use <ad4m://fn/parse_literal> IN FILTER", async () => {
1206
+ const query = await (FilterTest as any).queryToSPARQL(mockPerspective, { where: { name: ["Alice", "Bob"] } });
1207
+ const norm = normalizeQuery(query);
1208
+ expect(norm).toContain("?wTarget_name");
1209
+ expect(norm).toContain("ad4m://fn/parse_literal");
1210
+ expect(norm).not.toContain("fn::parse_literal");
1211
+ });
1212
+
1213
+ it("SPARQL query for where: { rating: { gt: 5 } } should NOT include parse_literal FILTER", async () => {
1214
+ const query = await (FilterTest as any).queryToSPARQL(mockPerspective, { where: { rating: { gt: 5 } } });
1215
+ const norm = normalizeQuery(query);
1216
+ expect(norm).not.toContain("parse_literal");
1217
+ });
1218
+
1219
+ it("literal property where clause adds JOIN for JS post-filter", async () => {
1220
+ const query = await (FilterTest as any).queryToSPARQL(mockPerspective, { where: { name: "Alice" } });
1221
+ const norm = normalizeQuery(query);
1222
+ expect(norm).toContain("?wTarget_name");
1223
+ });
1224
+ });
1225
+
1226
+ // ── Lightweight fingerprint (3.7) ────────────────────────────────────────────
1227
+ describe("Lightweight fingerprint optimization", () => {
1228
+ // Replicate the buildFingerprint logic for testing
1229
+ const buildFingerprint = (results: any[]) => {
1230
+ if (results.length === 0) return '0:';
1231
+ const ids = results.map((r: any) => r.id || '').sort().join(',');
1232
+ const ts = results.map((r: any) => r.updatedAt || r.timestamp || '').join(',');
1233
+ return `${results.length}:${ids}:${ts}`;
1234
+ };
1235
+
1236
+ const base = [
1237
+ { id: "a", updatedAt: "100" },
1238
+ { id: "b", updatedAt: "200" },
1239
+ ];
1240
+
1241
+ it("lightweight fingerprint should detect instance addition", () => {
1242
+ const fp1 = buildFingerprint(base);
1243
+ const fp2 = buildFingerprint([...base, { id: "c", updatedAt: "300" }]);
1244
+ expect(fp1).not.toBe(fp2);
1245
+ });
1246
+
1247
+ it("lightweight fingerprint should detect instance removal", () => {
1248
+ const fp1 = buildFingerprint(base);
1249
+ const fp2 = buildFingerprint([base[0]]);
1250
+ expect(fp1).not.toBe(fp2);
1251
+ });
1252
+
1253
+ it("lightweight fingerprint should detect timestamp change", () => {
1254
+ const fp1 = buildFingerprint(base);
1255
+ const fp2 = buildFingerprint([{ id: "a", updatedAt: "999" }, base[1]]);
1256
+ expect(fp1).not.toBe(fp2);
1257
+ });
1258
+
1259
+ it("lightweight fingerprint should NOT false-positive for identical sets", () => {
1260
+ const fp1 = buildFingerprint(base);
1261
+ const fp2 = buildFingerprint([...base]); // same data, new array
1262
+ expect(fp1).toBe(fp2);
1263
+ });
1264
+ });
1265
+
1266
+
1267
+
1268
+ // ── Subscribe callback timing ──────────────────────────────────────────
1269
+ describe("ModelQueryBuilder subscribe callback timing", () => {
1270
+ it("subscribe should not invoke callback synchronously before Promise resolves", async () => {
1271
+ // This test verifies that subscribe() uses the Rust model subscription endpoint
1272
+ // and properly handles the subscription lifecycle.
1273
+
1274
+ const mockSubscriptionId = "test-sub-123";
1275
+ let updateCallback: ((result: any) => void) | null = null;
1276
+
1277
+ const mockClient = {
1278
+ modelSubscribe: jest.fn().mockResolvedValue({
1279
+ subscriptionId: mockSubscriptionId,
1280
+ result: { instances: [], totalCount: 0 },
1281
+ }),
1282
+ subscribeToQueryUpdates: jest.fn().mockImplementation((_id: string, cb: any) => {
1283
+ updateCallback = cb;
1284
+ return () => {}; // unsubscribe function
1285
+ }),
1286
+ keepAliveQuery: jest.fn().mockResolvedValue(true),
1287
+ disposeQuerySubscription: jest.fn().mockResolvedValue(true),
1288
+ };
1289
+
1290
+ const mockPerspective = {
1291
+ uuid: "test-uuid",
1292
+ client: mockClient,
1293
+ modelSubscribe: jest.fn().mockImplementation(async (className: string, queryJson: string) => {
1294
+ return mockClient.modelSubscribe("test-uuid", className, queryJson);
1295
+ }),
1296
+ getLinks: jest.fn().mockResolvedValue([]),
1297
+ modelQuery: jest.fn().mockResolvedValue({ instances: [], totalCount: 0 }),
1298
+ } as any;
1299
+
1300
+ const { Ad4mModel, Model, Property, Flag } = require("./index");
1301
+
1302
+ @Model({ name: "TimingTest" })
1303
+ class TimingTest extends Ad4mModel {
1304
+ @Flag({ through: "test://type", value: "test://timing" })
1305
+ type: string = "test://timing";
1306
+ @Property({ through: "test://name" })
1307
+ name: string = "";
1308
+ }
1309
+
1310
+ let callbackInvokedBeforeResolve = false;
1311
+ let promiseResolved = false;
1312
+
1313
+ const query = TimingTest.query(mockPerspective);
1314
+ const promise = query.subscribe((results: any[]) => {
1315
+ if (!promiseResolved) {
1316
+ callbackInvokedBeforeResolve = true;
1317
+ }
1318
+ });
1319
+
1320
+ // At this point the Promise hasn't resolved yet
1321
+ // The callback should NOT have fired synchronously
1322
+ expect(callbackInvokedBeforeResolve).toBe(false);
1323
+
1324
+ const initialResults = await promise;
1325
+ promiseResolved = true;
1326
+
1327
+ expect(initialResults).toEqual([]);
1328
+ expect(mockPerspective.modelSubscribe).toHaveBeenCalled();
1329
+ });
1330
+ });
1331
+
1332
+ describe("ModelQueryBuilder paginateSubscribe", () => {
1333
+ it("paginateSubscribe should use a single query with count: true", async () => {
1334
+ const mockSubscriptionId = "paginate-sub-123";
1335
+
1336
+ const mockClient = {
1337
+ modelSubscribe: jest.fn().mockResolvedValue({
1338
+ subscriptionId: mockSubscriptionId,
1339
+ result: { instances: [], totalCount: 0 },
1340
+ }),
1341
+ subscribeToQueryUpdates: jest.fn().mockImplementation((_id: string, _cb: any) => {
1342
+ return () => {};
1343
+ }),
1344
+ keepAliveQuery: jest.fn().mockResolvedValue(true),
1345
+ disposeQuerySubscription: jest.fn().mockResolvedValue(true),
1346
+ };
1347
+
1348
+ const mockPerspective = {
1349
+ uuid: "test-uuid",
1350
+ client: mockClient,
1351
+ modelSubscribe: jest.fn().mockImplementation(async (className: string, queryJson: string) => {
1352
+ return mockClient.modelSubscribe("test-uuid", className, queryJson);
1353
+ }),
1354
+ modelQuery: jest.fn().mockResolvedValue({ instances: [{ id: "item1", type: "test://paginate" }], totalCount: 42 }),
1355
+ } as any;
1356
+
1357
+ const { Ad4mModel, Model, Flag, Property } = require("./index");
1358
+
1359
+ @Model({ name: "PaginateTest" })
1360
+ class PaginateTest extends Ad4mModel {
1361
+ @Flag({ through: "test://type", value: "test://paginate" })
1362
+ type: string = "test://paginate";
1363
+ @Property({ through: "test://name" })
1364
+ name: string = "";
1365
+ }
1366
+
1367
+ const builder = PaginateTest.query(mockPerspective);
1368
+ const result = await builder.paginateSubscribe(10, 1, () => {});
1369
+
1370
+ // Should return paginated result structure
1371
+ expect(result).toHaveProperty("results");
1372
+ expect(result).toHaveProperty("totalCount");
1373
+ expect(result).toHaveProperty("pageSize", 10);
1374
+ expect(result).toHaveProperty("pageNumber", 1);
1375
+
1376
+ // modelQuery should be called exactly once (not twice — no separate count query)
1377
+ expect(mockPerspective.modelQuery).toHaveBeenCalledTimes(1);
1378
+
1379
+ // The query should have count: true
1380
+ const callArgs = mockPerspective.modelQuery.mock.calls[0];
1381
+ const queryJson = JSON.parse(callArgs[1]);
1382
+ expect(queryJson.count).toBe(true);
1383
+ expect(queryJson.limit).toBe(10);
1384
+ expect(queryJson.offset).toBe(0);
1385
+ });
1386
+
1387
+ it("paginateSubscribe should re-fetch on real subscription updates", async () => {
1388
+ const mockSubscriptionId = "paginate-update-sub";
1389
+ let capturedCallback: ((result: any) => void) | null = null;
1390
+
1391
+ const mockClient = {
1392
+ modelSubscribe: jest.fn().mockResolvedValue({
1393
+ subscriptionId: mockSubscriptionId,
1394
+ result: { instances: [], totalCount: 0 },
1395
+ }),
1396
+ subscribeToQueryUpdates: jest.fn().mockImplementation((_id: string, cb: any) => {
1397
+ capturedCallback = cb;
1398
+ return () => {};
1399
+ }),
1400
+ keepAliveQuery: jest.fn().mockResolvedValue(true),
1401
+ disposeQuerySubscription: jest.fn().mockResolvedValue(true),
1402
+ };
1403
+
1404
+ let modelQueryCallCount = 0;
1405
+ const mockPerspective = {
1406
+ uuid: "test-uuid",
1407
+ client: mockClient,
1408
+ modelSubscribe: jest.fn().mockImplementation(async (className: string, queryJson: string) => {
1409
+ return mockClient.modelSubscribe("test-uuid", className, queryJson);
1410
+ }),
1411
+ modelQuery: jest.fn().mockImplementation(async () => {
1412
+ modelQueryCallCount++;
1413
+ return { instances: [{ id: "new-item", type: "test://update" }], totalCount: 1 };
1414
+ }),
1415
+ } as any;
1416
+
1417
+ const { Ad4mModel, Model, Flag, Property } = require("./index");
1418
+
1419
+ @Model({ name: "UpdateTest" })
1420
+ class UpdateTest extends Ad4mModel {
1421
+ @Flag({ through: "test://type", value: "test://update" })
1422
+ type: string = "test://update";
1423
+ @Property({ through: "test://name" })
1424
+ name: string = "";
1425
+ }
1426
+
1427
+ const userCallback = jest.fn();
1428
+ const builder = UpdateTest.query(mockPerspective);
1429
+ await builder.paginateSubscribe(10, 1, userCallback);
1430
+
1431
+ const initialCallCount = modelQueryCallCount;
1432
+
1433
+ // Simulate a subscription update
1434
+ capturedCallback!({ instances: [{ id: "new-item" }], totalCount: 1 });
1435
+
1436
+ // Wait for async processing
1437
+ await new Promise(r => setTimeout(r, 100));
1438
+
1439
+ // modelQuery should have been called again for the re-fetch
1440
+ expect(modelQueryCallCount).toBeGreaterThan(initialCallCount);
1441
+ // User callback should have been invoked with paginated results
1442
+ expect(userCallback).toHaveBeenCalled();
1443
+ const callArg = userCallback.mock.calls[0][0];
1444
+ expect(callArg).toHaveProperty("totalCount");
1445
+ expect(callArg).toHaveProperty("pageSize", 10);
1446
+ expect(callArg).toHaveProperty("pageNumber", 1);
1447
+ });
1448
+ });
1449
+
1450
+ // ============================================================================
1451
+ // Subscription keepalive recovery tests
1452
+ // ============================================================================
1453
+
1454
+ describe("ModelQueryBuilder keepalive recovery", () => {
1455
+ beforeEach(() => jest.useFakeTimers());
1456
+ afterEach(() => jest.useRealTimers());
1457
+
1458
+ /**
1459
+ * Helper: build a mock perspective whose keepAliveQuery rejects after
1460
+ * `failAfter` successful calls, simulating a server-side subscription
1461
+ * eviction (returns "Subscription not found"). On resubscribe (a second
1462
+ * modelSubscribe call) it returns a *new* subscription ID.
1463
+ */
1464
+ function buildMocks(failAfter = 0) {
1465
+ let keepaliveCallCount = 0;
1466
+ let modelSubscribeCallCount = 0;
1467
+
1468
+ const mockClient = {
1469
+ modelSubscribe: jest.fn().mockImplementation(async () => {
1470
+ modelSubscribeCallCount++;
1471
+ return {
1472
+ subscriptionId: `sub-${modelSubscribeCallCount}`,
1473
+ result: { instances: [], totalCount: 0 },
1474
+ };
1475
+ }),
1476
+ subscribeToQueryUpdates: jest.fn().mockImplementation((_id: string, _cb: any) => {
1477
+ return () => {};
1478
+ }),
1479
+ keepAliveQuery: jest.fn().mockImplementation(async () => {
1480
+ keepaliveCallCount++;
1481
+ if (keepaliveCallCount > failAfter) {
1482
+ throw new Error("RPC error 500: Subscription not found");
1483
+ }
1484
+ return true;
1485
+ }),
1486
+ disposeQuerySubscription: jest.fn().mockResolvedValue(true),
1487
+ };
1488
+
1489
+ const mockPerspective = {
1490
+ uuid: "test-uuid",
1491
+ client: mockClient,
1492
+ modelSubscribe: jest.fn().mockImplementation(
1493
+ async (className: string, queryJson: string) =>
1494
+ mockClient.modelSubscribe("test-uuid", className, queryJson)
1495
+ ),
1496
+ modelQuery: jest.fn().mockResolvedValue({ instances: [], totalCount: 0 }),
1497
+ getLinks: jest.fn().mockResolvedValue([]),
1498
+ } as any;
1499
+
1500
+ return { mockClient, mockPerspective, getKeepaliveCount: () => keepaliveCallCount, getSubscribeCount: () => modelSubscribeCallCount };
1501
+ }
1502
+
1503
+ it("subscribe: resubscribes when keepalive gets 'Subscription not found'", async () => {
1504
+ const { mockClient, mockPerspective, getSubscribeCount } = buildMocks(/* failAfter */ 1);
1505
+
1506
+ const { Ad4mModel, Model, Flag, Property } = require("./index");
1507
+
1508
+ @Model({ name: "KeepaliveRecoveryTest" })
1509
+ class KeepaliveRecoveryTest extends Ad4mModel {
1510
+ @Flag({ through: "test://type", value: "test://ka" })
1511
+ type: string = "test://ka";
1512
+ @Property({ through: "test://name" })
1513
+ name: string = "";
1514
+ }
1515
+
1516
+ const builder = KeepaliveRecoveryTest.query(mockPerspective);
1517
+ await builder.subscribe(() => {});
1518
+
1519
+ // Initial subscription
1520
+ expect(getSubscribeCount()).toBe(1);
1521
+
1522
+ // First keepalive at 30s — succeeds (failAfter=1)
1523
+ await jest.advanceTimersByTimeAsync(30_000);
1524
+ expect(mockClient.keepAliveQuery).toHaveBeenCalledTimes(1);
1525
+
1526
+ // Second keepalive at 60s — fails → should trigger resubscribe
1527
+ await jest.advanceTimersByTimeAsync(30_000);
1528
+ expect(mockClient.keepAliveQuery).toHaveBeenCalledTimes(2);
1529
+
1530
+ // Allow exponential backoff (2000ms for first retry) + microtask queue to settle
1531
+ await jest.advanceTimersByTimeAsync(2500);
1532
+
1533
+ // A second modelSubscribe call means recovery happened
1534
+ expect(getSubscribeCount()).toBe(2);
1535
+
1536
+ // Clean up
1537
+ builder.dispose();
1538
+ });
1539
+
1540
+ it("countSubscribe: resubscribes when keepalive gets 'Subscription not found'", async () => {
1541
+ const { mockClient, mockPerspective, getSubscribeCount } = buildMocks(0); // fail immediately
1542
+
1543
+ const { Ad4mModel, Model, Flag, Property } = require("./index");
1544
+
1545
+ @Model({ name: "CountKeepaliveTest" })
1546
+ class CountKeepaliveTest extends Ad4mModel {
1547
+ @Flag({ through: "test://type", value: "test://cka" })
1548
+ type: string = "test://cka";
1549
+ @Property({ through: "test://name" })
1550
+ name: string = "";
1551
+ }
1552
+
1553
+ const builder = CountKeepaliveTest.query(mockPerspective);
1554
+ await builder.countSubscribe(() => {});
1555
+
1556
+ expect(getSubscribeCount()).toBe(1);
1557
+
1558
+ // First keepalive at 30s — fails immediately → should trigger resubscribe
1559
+ await jest.advanceTimersByTimeAsync(30_000);
1560
+ // Allow exponential backoff (2000ms for first retry) + microtask queue to settle
1561
+ await jest.advanceTimersByTimeAsync(2500);
1562
+
1563
+ expect(getSubscribeCount()).toBe(2);
1564
+
1565
+ builder.dispose();
1566
+ });
1567
+
1568
+ it("paginateSubscribe: resubscribes when keepalive gets 'Subscription not found'", async () => {
1569
+ const { mockClient, mockPerspective, getSubscribeCount } = buildMocks(0);
1570
+
1571
+ const { Ad4mModel, Model, Flag, Property } = require("./index");
1572
+
1573
+ @Model({ name: "PaginateKeepaliveTest" })
1574
+ class PaginateKeepaliveTest extends Ad4mModel {
1575
+ @Flag({ through: "test://type", value: "test://pka" })
1576
+ type: string = "test://pka";
1577
+ @Property({ through: "test://name" })
1578
+ name: string = "";
1579
+ }
1580
+
1581
+ const builder = PaginateKeepaliveTest.query(mockPerspective);
1582
+ await builder.paginateSubscribe(10, 1, () => {});
1583
+
1584
+ expect(getSubscribeCount()).toBe(1);
1585
+
1586
+ await jest.advanceTimersByTimeAsync(30_000);
1587
+ // Allow exponential backoff (2000ms for first retry) + microtask queue to settle
1588
+ await jest.advanceTimersByTimeAsync(2500);
1589
+
1590
+ expect(getSubscribeCount()).toBe(2);
1591
+
1592
+ builder.dispose();
1593
+ });
1594
+
1595
+ it("subscribe: stops retrying after dispose()", async () => {
1596
+ const { mockClient, mockPerspective } = buildMocks(Infinity); // keepalive always succeeds
1597
+
1598
+ const { Ad4mModel, Model, Flag, Property } = require("./index");
1599
+
1600
+ @Model({ name: "DisposeTest" })
1601
+ class DisposeTest extends Ad4mModel {
1602
+ @Flag({ through: "test://type", value: "test://disp" })
1603
+ type: string = "test://disp";
1604
+ @Property({ through: "test://name" })
1605
+ name: string = "";
1606
+ }
1607
+
1608
+ const builder = DisposeTest.query(mockPerspective);
1609
+ await builder.subscribe(() => {});
1610
+
1611
+ builder.dispose();
1612
+
1613
+ // Advance well past multiple keepalive intervals
1614
+ await jest.advanceTimersByTimeAsync(120_000);
1615
+
1616
+ // No keepalive calls should have happened after dispose
1617
+ expect(mockClient.keepAliveQuery).toHaveBeenCalledTimes(0);
1618
+ });
1619
+ });
1620
+
1621
+ // ============================================================================
1622
+ // Performance Optimisation Tests
1623
+ // ============================================================================
1624
+
1625
+ import { getCachedResult, setCachedResult, clearQueryCache, queryCacheSize } from "./query-cache";
1626
+ import { getPropertiesMetadata, getRelationsMetadata, getMemoizedSHACL } from "./decorators";
1627
+
1628
+ describe("QueryCache", () => {
1629
+ beforeEach(() => clearQueryCache());
1630
+
1631
+ it("should return undefined for cache miss", () => {
1632
+ expect(getCachedResult("uuid1", "SELECT ?s WHERE {}")).toBeUndefined();
1633
+ });
1634
+
1635
+ it("should return cached result within TTL", () => {
1636
+ const result = [{ s: "test" }];
1637
+ setCachedResult("uuid1", "SELECT ?s WHERE {}", result);
1638
+ expect(getCachedResult("uuid1", "SELECT ?s WHERE {}")).toBe(result);
1639
+ });
1640
+
1641
+ it("should expire after TTL", async () => {
1642
+ setCachedResult("uuid1", "SELECT ?s WHERE {}", [{ s: "test" }], 50);
1643
+ await new Promise(r => setTimeout(r, 60));
1644
+ expect(getCachedResult("uuid1", "SELECT ?s WHERE {}")).toBeUndefined();
1645
+ });
1646
+
1647
+ it("should cache independently per perspective", () => {
1648
+ setCachedResult("uuid1", "SELECT ?s WHERE {}", "result1");
1649
+ setCachedResult("uuid2", "SELECT ?s WHERE {}", "result2");
1650
+ expect(getCachedResult("uuid1", "SELECT ?s WHERE {}")).toBe("result1");
1651
+ expect(getCachedResult("uuid2", "SELECT ?s WHERE {}")).toBe("result2");
1652
+ });
1653
+
1654
+ it("should cache independently per query", () => {
1655
+ setCachedResult("uuid1", "query1", "r1");
1656
+ setCachedResult("uuid1", "query2", "r2");
1657
+ expect(getCachedResult("uuid1", "query1")).toBe("r1");
1658
+ expect(getCachedResult("uuid1", "query2")).toBe("r2");
1659
+ });
1660
+
1661
+ it("should clear all entries", () => {
1662
+ setCachedResult("uuid1", "q1", "r1");
1663
+ setCachedResult("uuid2", "q2", "r2");
1664
+ expect(queryCacheSize()).toBe(2);
1665
+ clearQueryCache();
1666
+ expect(queryCacheSize()).toBe(0);
1667
+ });
1668
+ });
1669
+
1670
+ describe("SHACL Memoisation", () => {
1671
+ it("should memoise generateSHACL() per class", () => {
1672
+ @Model({ name: "MemoTest1" })
1673
+ class MemoTest1 extends Ad4mModel {
1674
+ @Property({ through: "test://name" })
1675
+ name: string = "";
1676
+ }
1677
+
1678
+ const result1 = (MemoTest1 as any).generateSHACL();
1679
+ const result2 = (MemoTest1 as any).generateSHACL();
1680
+ expect(result1).toBe(result2); // Same reference = memoised
1681
+ });
1682
+
1683
+ it("should memoise getPropertiesMetadata per class", () => {
1684
+ @Model({ name: "PropMemoTest" })
1685
+ class PropMemoTest extends Ad4mModel {
1686
+ @Property({ through: "test://x" })
1687
+ x: string = "";
1688
+ }
1689
+
1690
+ const r1 = getPropertiesMetadata(PropMemoTest);
1691
+ const r2 = getPropertiesMetadata(PropMemoTest);
1692
+ expect(r1).toBe(r2); // Same reference
1693
+ });
1694
+
1695
+ it("should memoise getRelationsMetadata per class", () => {
1696
+ @Model({ name: "RelMemoTest" })
1697
+ class RelMemoTest extends Ad4mModel {
1698
+ @HasMany({ through: "test://items" })
1699
+ items: string[] = [];
1700
+ }
1701
+
1702
+ const r1 = getRelationsMetadata(RelMemoTest);
1703
+ const r2 = getRelationsMetadata(RelMemoTest);
1704
+ expect(r1).toBe(r2); // Same reference
1705
+ });
1706
+
1707
+ it("should return different results for different classes", () => {
1708
+ @Model({ name: "ClassA" })
1709
+ class ClassA extends Ad4mModel {
1710
+ @Property({ through: "test://a" })
1711
+ a: string = "";
1712
+ }
1713
+
1714
+ @Model({ name: "ClassB" })
1715
+ class ClassB extends Ad4mModel {
1716
+ @Property({ through: "test://b" })
1717
+ b: string = "";
1718
+ }
1719
+
1720
+ const propsA = getPropertiesMetadata(ClassA);
1721
+ const propsB = getPropertiesMetadata(ClassB);
1722
+ expect(propsA).not.toBe(propsB);
1723
+ expect(propsA).toHaveProperty("a");
1724
+ expect(propsB).toHaveProperty("b");
1725
+ });
1726
+ });
1727
+
1728
+ describe("Lazy Conformance Filters", () => {
1729
+ it("should defer conformance filter resolution until property access", () => {
1730
+ @Model({ name: "LazyTarget2" })
1731
+ class LazyTarget2 extends Ad4mModel {
1732
+ @Flag({ through: "test://type", value: "test://lazy" })
1733
+ type: string = "test://lazy";
1734
+ @Property({ through: "test://name", required: true })
1735
+ name: string = "";
1736
+ }
1737
+
1738
+ @Model({ name: "LazyParent2" })
1739
+ class LazyParent2 extends Ad4mModel {
1740
+ @HasMany(() => LazyTarget2, { through: "test://children" })
1741
+ children: string[] = [];
1742
+ }
1743
+
1744
+ // generateSHACL was called during @Model — the shape exists
1745
+ const shacl = (LazyParent2 as any).generateSHACL();
1746
+ expect(shacl).toBeDefined();
1747
+ expect(shacl.shape).toBeDefined();
1748
+ expect(shacl.name).toBe("LazyParent2");
1749
+ });
1750
+ });
1751
+
1752
+ // ──────────────────────────────────────────────────────────
1753
+ // deepQuery — getter evaluation on collection queries
1754
+ // ──────────────────────────────────────────────────────────
1755
+
1756
+ describe("deepQuery — getter evaluation", () => {
1757
+ @Model({ name: "DeepQueryTestMessage" })
1758
+ class DeepQueryTestMessage extends Ad4mModel {
1759
+ @Flag({ through: "flux://entry_type", value: "flux://message" })
1760
+ type: string = "";
1761
+
1762
+ @Property({ through: "flux://body", resolveLanguage: "literal" })
1763
+ body: string = "";
1764
+
1765
+ @Property({
1766
+ through: "flux://has_reply",
1767
+ getter: `SELECT ?target WHERE { ?source <flux://has_reply> ?target . } LIMIT 1`,
1768
+ })
1769
+ replyingTo?: string;
1770
+
1771
+ @ReadOnly({
1772
+ through: "flux://is_popular",
1773
+ getter: `ASK WHERE { ?source <flux://is_popular> "true" . }`,
1774
+ })
1775
+ isPopular: boolean = false;
1776
+
1777
+ @HasMany({ through: "flux://reaction" })
1778
+ reactions: string[] = [];
1779
+ }
1780
+
1781
+ let sparqlCalls: string[];
1782
+ const mockPerspective: any = {
1783
+ uuid: "test-uuid",
1784
+ modelQuery: jest.fn(async (className: string, queryJson: string) => {
1785
+ // Return a basic result for the single-instance getData() path
1786
+ const query = JSON.parse(queryJson);
1787
+ const id = query?.where?.id;
1788
+ if (id) {
1789
+ return {
1790
+ instances: [{ id, body: "Hello" }],
1791
+ totalCount: 1,
1792
+ };
1793
+ }
1794
+ return { instances: [], totalCount: 0 };
1795
+ }),
1796
+ evaluateGetters: jest.fn(async (className: string, instanceIds: string[], propertyNames?: string[]) => {
1797
+ // Return empty results by default — tests can override this mock
1798
+ const result: Record<string, Record<string, any>> = {};
1799
+ return result;
1800
+ }),
1801
+ querySparql: jest.fn(async (q: string) => {
1802
+ sparqlCalls.push(q);
1803
+ return [];
1804
+ }),
1805
+ get: jest.fn().mockResolvedValue([]),
1806
+ getExpression: jest.fn().mockResolvedValue(null),
1807
+ stringOrTemplateObjectToSubjectClassName: jest.fn().mockResolvedValue("DeepQueryTestMessage"),
1808
+ };
1809
+
1810
+ beforeEach(() => {
1811
+ sparqlCalls = [];
1812
+ mockPerspective.querySparql.mockClear();
1813
+ mockPerspective.evaluateGetters.mockClear();
1814
+ mockPerspective.modelQuery.mockClear();
1815
+ mockPerspective.get.mockClear();
1816
+ });
1817
+
1818
+ function makeInstances(count: number): InstanceType<typeof DeepQueryTestMessage>[] {
1819
+ return Array.from({ length: count }, (_, i) =>
1820
+ new DeepQueryTestMessage(mockPerspective, `flux://msg-${i}`)
1821
+ );
1822
+ }
1823
+
1824
+ it("single-instance get() delegates getter evaluation to Rust (no JS-side SPARQL)", async () => {
1825
+ const instance = new DeepQueryTestMessage(mockPerspective, "flux://msg-single");
1826
+ mockPerspective.querySparql.mockImplementation(async (q: string) => {
1827
+ sparqlCalls.push(q);
1828
+ if (q.includes("flux://msg-single") && !q.includes("flux://has_reply") && !q.includes("flux://is_popular")) {
1829
+ return [
1830
+ { source: "flux://msg-single", predicate: "flux://entry_type", target: "flux://message", author: "did:key:a", timestamp: "3000" },
1831
+ { source: "flux://msg-single", predicate: "flux://body", target: "literal:string:Hello", author: "did:key:a", timestamp: "3000" },
1832
+ ];
1833
+ }
1834
+ return [];
1835
+ });
1836
+
1837
+ await instance.get();
1838
+ // Getter evaluation now happens Rust-side via evaluate_getters() — no JS SPARQL calls
1839
+ const getterCalls = sparqlCalls.filter(
1840
+ (q) => q.includes("flux://has_reply") || q.includes("flux://is_popular")
1841
+ );
1842
+ expect(getterCalls.length).toBe(0);
1843
+ });
1844
+
1845
+ describe("Ad4mModel.evaluateGetters()", () => {
1846
+ it("resolves getters for a batch of instances via single RPC", async () => {
1847
+ const instances = makeInstances(4);
1848
+
1849
+ await DeepQueryTestMessage.evaluateGetters(instances.slice(0, 2), mockPerspective, ["replyingTo"]);
1850
+
1851
+ // Should make exactly 1 RPC call via perspective.evaluateGetters
1852
+ expect(mockPerspective.evaluateGetters).toHaveBeenCalledTimes(1);
1853
+ const [className, instanceIds, propertyNames] = mockPerspective.evaluateGetters.mock.calls[0];
1854
+ expect(className).toBe("DeepQueryTestMessage");
1855
+ expect(instanceIds).toEqual(["flux://msg-0", "flux://msg-1"]);
1856
+ expect(propertyNames).toEqual(["replyingTo"]);
1857
+ // No querySparql calls — all done in-process
1858
+ expect(sparqlCalls.length).toBe(0);
1859
+ });
1860
+
1861
+ it("evaluates all getters when propertyNames is omitted", async () => {
1862
+ const instances = makeInstances(2);
1863
+
1864
+ await DeepQueryTestMessage.evaluateGetters(instances, mockPerspective);
1865
+
1866
+ expect(mockPerspective.evaluateGetters).toHaveBeenCalledTimes(1);
1867
+ const [className, instanceIds, propertyNames] = mockPerspective.evaluateGetters.mock.calls[0];
1868
+ expect(className).toBe("DeepQueryTestMessage");
1869
+ expect(instanceIds).toEqual(["flux://msg-0", "flux://msg-1"]);
1870
+ expect(propertyNames).toBeUndefined();
1871
+ });
1872
+
1873
+ it("applies results to instances and syncs snapshots", async () => {
1874
+ const instances = makeInstances(2);
1875
+ // Simulate Rust returning getter results
1876
+ mockPerspective.evaluateGetters.mockResolvedValueOnce({
1877
+ "flux://msg-0": { replyingTo: "flux://msg-99" },
1878
+ "flux://msg-1": { replyingTo: "flux://msg-88" },
1879
+ });
1880
+
1881
+ await DeepQueryTestMessage.evaluateGetters(instances, mockPerspective, ["replyingTo"]);
1882
+
1883
+ expect((instances[0] as any).replyingTo).toBe("flux://msg-99");
1884
+ expect((instances[1] as any).replyingTo).toBe("flux://msg-88");
1885
+ });
1886
+
1887
+ it("handles empty array gracefully", async () => {
1888
+ await DeepQueryTestMessage.evaluateGetters([], mockPerspective);
1889
+ expect(mockPerspective.evaluateGetters).not.toHaveBeenCalled();
1890
+ });
1891
+ });
1892
+
1893
+ describe("deepQuery via ModelQueryBuilder", () => {
1894
+ it("deepQuery() method sets deepQuery flag on queryParams", () => {
1895
+ const builder = DeepQueryTestMessage.query(mockPerspective);
1896
+ (builder as any).deepQuery();
1897
+ expect((builder as any).queryParams.deepQuery).toBe(true);
1898
+ });
1899
+
1900
+ it("deepQuery defaults to true when not explicitly set", async () => {
1901
+ mockPerspective.modelQuery.mockResolvedValueOnce({ instances: [], totalCount: 0 });
1902
+ await DeepQueryTestMessage.query(mockPerspective).get();
1903
+
1904
+ expect(mockPerspective.modelQuery).toHaveBeenCalledTimes(1);
1905
+ const [, queryJson] = mockPerspective.modelQuery.mock.calls[0];
1906
+ const qi = JSON.parse(queryJson);
1907
+ expect(qi.deepQuery).toBe(true);
1908
+ });
1909
+
1910
+ it("deepQuery can be explicitly set to false", async () => {
1911
+ mockPerspective.modelQuery.mockResolvedValueOnce({ instances: [], totalCount: 0 });
1912
+ await DeepQueryTestMessage.query(mockPerspective).deepQuery(false).get();
1913
+
1914
+ expect(mockPerspective.modelQuery).toHaveBeenCalledTimes(1);
1915
+ const [, queryJson] = mockPerspective.modelQuery.mock.calls[0];
1916
+ const qi = JSON.parse(queryJson);
1917
+ expect(qi.deepQuery).toBe(false);
1918
+ });
1919
+ });
1920
+ });
1921
+
1922
+ // ─── Ad4mModel.fromSHACL() ───────────────────────────────────────────────────
1923
+
1924
+ describe("Ad4mModel.fromSHACL()", () => {
1925
+ function makeShape(targetClass: string, props: Array<import("../shacl/SHACLShape").SHACLPropertyShape>) {
1926
+ const shape = new SHACLShape(targetClass);
1927
+ for (const p of props) shape.addProperty(p);
1928
+ return shape;
1929
+ }
1930
+
1931
+ it("assigns the given name as className", () => {
1932
+ const shape = makeShape("flux://Channel", []);
1933
+ const Cls = Ad4mModel.fromSHACL(shape, "Channel");
1934
+ expect((Cls as any).className).toBe("Channel");
1935
+ expect((new (Cls as any)({}, "flux://1")).className).toBe("Channel");
1936
+ });
1937
+
1938
+ it("registers scalar property (maxCount=1) via setPropertyRegistryEntry", () => {
1939
+ const shape = makeShape("flux://Channel", [
1940
+ { name: "title", path: "flux://has_title", maxCount: 1, writable: true },
1941
+ ]);
1942
+ const Cls = Ad4mModel.fromSHACL(shape, "Channel");
1943
+ const meta = Cls.getModelMetadata();
1944
+ expect(meta.properties["title"]).toBeDefined();
1945
+ expect(meta.properties["title"].predicate).toBe("flux://has_title");
1946
+ expect(meta.properties["title"].readOnly).toBe(false);
1947
+ });
1948
+
1949
+ it("registers collection property (no maxCount) as hasMany relation", () => {
1950
+ const shape = makeShape("flux://Channel", [
1951
+ { name: "messages", path: "flux://has_message" },
1952
+ ]);
1953
+ const Cls = Ad4mModel.fromSHACL(shape, "Channel");
1954
+ const meta = Cls.getModelMetadata();
1955
+ expect(meta.relations["messages"]).toBeDefined();
1956
+ expect(meta.relations["messages"].predicate).toBe("flux://has_message");
1957
+ expect(meta.relations["messages"].direction).toBe("forward");
1958
+ });
1959
+
1960
+ it("registers collection property (maxCount=5) as hasMany relation", () => {
1961
+ const shape = makeShape("flux://Channel", [
1962
+ { name: "participants", path: "flux://participant", maxCount: 5 },
1963
+ ]);
1964
+ const Cls = Ad4mModel.fromSHACL(shape, "Channel");
1965
+ const meta = Cls.getModelMetadata();
1966
+ expect(meta.relations["participants"]).toBeDefined();
1967
+ expect(meta.relations["participants"].direction).toBe("forward");
1968
+ });
1969
+
1970
+ it("propagates resolveLanguage onto scalar properties", () => {
1971
+ const shape = makeShape("flux://Post", [
1972
+ { name: "body", path: "flux://body", maxCount: 1, resolveLanguage: "literal" },
1973
+ ]);
1974
+ const Cls = Ad4mModel.fromSHACL(shape, "Post");
1975
+ const meta = Cls.getModelMetadata();
1976
+ expect(meta.properties["body"].resolveLanguage).toBe("literal");
1977
+ });
1978
+
1979
+ it("defaults writable to true when not specified", () => {
1980
+ const shape = makeShape("flux://Post", [
1981
+ { name: "body", path: "flux://body", maxCount: 1 },
1982
+ ]);
1983
+ const Cls = Ad4mModel.fromSHACL(shape, "Post");
1984
+ const meta = Cls.getModelMetadata();
1985
+ expect(meta.properties["body"].readOnly).toBe(false);
1986
+ });
1987
+
1988
+ it("respects writable:false", () => {
1989
+ const shape = makeShape("flux://Post", [
1990
+ { name: "id", path: "flux://id", maxCount: 1, writable: false },
1991
+ ]);
1992
+ const Cls = Ad4mModel.fromSHACL(shape, "Post");
1993
+ const meta = Cls.getModelMetadata();
1994
+ expect(meta.properties["id"].readOnly).toBe(true);
1995
+ });
1996
+
1997
+ it("registers flag properties (hasValue) as type-discrimination entries", () => {
1998
+ const shape = makeShape("flux://Message", [
1999
+ { name: "type", path: "flux://entry_type", hasValue: "flux://message" },
2000
+ { name: "body", path: "flux://body", maxCount: 1 },
2001
+ ]);
2002
+ const Cls = Ad4mModel.fromSHACL(shape, "Message");
2003
+ const meta = Cls.getModelMetadata();
2004
+ expect(meta.properties["type"]).toBeDefined();
2005
+ expect(meta.properties["type"].predicate).toBe("flux://entry_type");
2006
+ expect(meta.properties["type"].flag).toBe(true);
2007
+ expect(meta.properties["type"].required).toBe(true);
2008
+ expect(meta.properties["type"].initial).toBe("flux://message");
2009
+ expect(meta.properties["body"]).toBeDefined();
2010
+ });
2011
+
2012
+ it("flag property from fromSHACL produces SPARQL type-discriminator triple", () => {
2013
+ const shape = makeShape("flux://Message", [
2014
+ { name: "type", path: "flux://entry_type", hasValue: "flux://message" },
2015
+ { name: "body", path: "flux://body", maxCount: 1 },
2016
+ ]);
2017
+ const Cls = Ad4mModel.fromSHACL(shape, "Message");
2018
+ const meta = Cls.getModelMetadata();
2019
+ const allRelsMeta = {} as any;
2020
+ const sparql = buildSPARQLQuery(meta, allRelsMeta, {}, Cls);
2021
+ expect(sparql).toContain("<flux://entry_type>");
2022
+ expect(sparql).toContain("<flux://message>");
2023
+ });
2024
+
2025
+ it("recovers flag value from constructor_actions (backward-compat for old shapes)", () => {
2026
+ const shape = new SHACLShape("flux://Channel");
2027
+ // An old shape: property has NO hasValue, but constructor_actions carries it
2028
+ shape.addProperty({ name: "type", path: "flux://entry_type", maxCount: 1 });
2029
+ shape.addProperty({ name: "name", path: "flux://name", maxCount: 1 });
2030
+ shape.constructor_actions = [
2031
+ { action: "addLink", source: "this", predicate: "flux://entry_type", target: "flux://channel" },
2032
+ ];
2033
+ const Cls = Ad4mModel.fromSHACL(shape, "Channel");
2034
+ const meta = Cls.getModelMetadata();
2035
+ expect(meta.properties["type"]).toBeDefined();
2036
+ expect(meta.properties["type"].flag).toBe(true);
2037
+ expect(meta.properties["type"].initial).toBe("flux://channel");
2038
+ });
2039
+
2040
+ it("skips properties without a name field", () => {
2041
+ const shape = makeShape("flux://Message", [
2042
+ { path: "flux://anonymous" } as any,
2043
+ { name: "body", path: "flux://body", maxCount: 1 },
2044
+ ]);
2045
+ const Cls = Ad4mModel.fromSHACL(shape, "Message");
2046
+ const meta = Cls.getModelMetadata();
2047
+ expect(Object.keys(meta.properties)).toEqual(["body"]);
2048
+ });
2049
+
2050
+ it("propagates local flag onto relations", () => {
2051
+ const shape = makeShape("flux://Channel", [
2052
+ { name: "drafts", path: "flux://draft", local: true },
2053
+ ]);
2054
+ const Cls = Ad4mModel.fromSHACL(shape, "Channel");
2055
+ const meta = Cls.getModelMetadata();
2056
+ expect(meta.relations["drafts"].local).toBe(true);
2057
+ });
2058
+
2059
+ it("applies Model decorator so generateSHACL and generateSDNA are available", () => {
2060
+ const shape = makeShape("flux://Channel", [
2061
+ { name: "title", path: "flux://has_title", maxCount: 1 },
2062
+ ]);
2063
+ const Cls = Ad4mModel.fromSHACL(shape, "Channel");
2064
+ expect(typeof (Cls as any).generateSDNA).toBe("function");
2065
+ expect(typeof (Cls as any).generateSHACL).toBe("function");
2066
+ });
2067
+
2068
+ it("handles shapes with no properties", () => {
2069
+ const shape = makeShape("flux://Empty", []);
2070
+ const Cls = Ad4mModel.fromSHACL(shape, "Empty");
2071
+ const meta = Cls.getModelMetadata();
2072
+ expect(Object.keys(meta.properties)).toHaveLength(0);
2073
+ expect(Object.keys(meta.relations)).toHaveLength(0);
2074
+ });
2075
+ });
2076
+
2077
+ // ---------------------------------------------------------------------------
2078
+ // IncludeProjection — key splitting and query routing
2079
+ // ---------------------------------------------------------------------------
2080
+
2081
+ describe("IncludeProjection type guard and key splitting", () => {
2082
+ // Shared test models
2083
+ @Model({ name: "Signal" })
2084
+ class Signal extends Ad4mModel {
2085
+ @Property({ through: "signal://type" })
2086
+ signalTypeId: string = "";
2087
+
2088
+ @Property({ through: "signal://author" })
2089
+ author: string = "";
2090
+ }
2091
+
2092
+ @Model({ name: "Post" })
2093
+ class Post extends Ad4mModel {
2094
+ @Property({ through: "post://title" })
2095
+ title: string = "";
2096
+
2097
+ @HasMany({ through: "post://signal", target: () => Signal })
2098
+ signals: Signal[] = [];
2099
+
2100
+ @HasMany({ through: "post://comment" })
2101
+ comments: string[] = [];
2102
+ }
2103
+
2104
+ const mockPerspective = {
2105
+ querySparql: jest.fn(),
2106
+ modelQuery: jest.fn(),
2107
+ infer: jest.fn(),
2108
+ uuid: "test-perspective-uuid",
2109
+ stringOrTemplateObjectToSubjectClassName: jest.fn().mockResolvedValue("Post"),
2110
+ } as any;
2111
+
2112
+ beforeEach(() => {
2113
+ jest.clearAllMocks();
2114
+ mockPerspective.modelQuery.mockResolvedValue({
2115
+ instances: [{ id: "post://1", title: "Hello", $signalCount: 3 }],
2116
+ totalCount: 1,
2117
+ });
2118
+ });
2119
+
2120
+ // --- isIncludeProjection type guard ---
2121
+
2122
+ it("isIncludeProjection returns true for objects with a 'from' field", () => {
2123
+ expect(isIncludeProjection({ from: "signals", count: true })).toBe(true);
2124
+ expect(isIncludeProjection({ from: "comments", limit: 1 })).toBe(true);
2125
+ });
2126
+
2127
+ it("isIncludeProjection returns false for non-projection values", () => {
2128
+ expect(isIncludeProjection(true)).toBe(false);
2129
+ expect(isIncludeProjection(false)).toBe(false);
2130
+ expect(isIncludeProjection(null)).toBe(false);
2131
+ expect(isIncludeProjection(undefined)).toBe(false);
2132
+ expect(isIncludeProjection(42)).toBe(false);
2133
+ // RelationSubQuery (has no 'from' key)
2134
+ expect(isIncludeProjection({ limit: 5, order: { timestamp: "DESC" } })).toBe(false);
2135
+ });
2136
+
2137
+ // --- $-key splitting ---
2138
+
2139
+ it("routes $-prefixed keys to queryInput.projections, not queryInput.include", async () => {
2140
+ await Post.findAll(mockPerspective, {
2141
+ include: {
2142
+ $signalCount: { from: "signals", count: true },
2143
+ comments: true,
2144
+ },
2145
+ });
2146
+
2147
+ const [, queryJson] = mockPerspective.modelQuery.mock.calls[0];
2148
+ const qi = JSON.parse(queryJson);
2149
+
2150
+ // Normal relation goes to include
2151
+ expect(qi.include?.comments).toBe(true);
2152
+ expect(qi.include?.$signalCount).toBeUndefined();
2153
+
2154
+ // Projection goes to projections
2155
+ expect(qi.projections?.$signalCount).toMatchObject({ from: "signals", count: true });
2156
+ expect(qi.projections?.comments).toBeUndefined();
2157
+ });
2158
+
2159
+ it("routes $-prefixed IncludeProjection values to projections ($ prefix required)", async () => {
2160
+ await Post.findAll(mockPerspective, {
2161
+ include: {
2162
+ $mySignals: { from: "signals", limit: 1 },
2163
+ comments: true,
2164
+ },
2165
+ });
2166
+
2167
+ const [, queryJson] = mockPerspective.modelQuery.mock.calls[0];
2168
+ const qi = JSON.parse(queryJson);
2169
+
2170
+ expect(qi.projections?.$mySignals).toMatchObject({ from: "signals", limit: 1 });
2171
+ expect(qi.include?.comments).toBe(true);
2172
+ });
2173
+
2174
+ it("does NOT route non-$ keys to projections even if value has 'from' shape", async () => {
2175
+ // $ prefix is required — a key without it goes to include, not projections
2176
+ await Post.findAll(mockPerspective, {
2177
+ include: {
2178
+ mySignals: { from: "signals", limit: 1 } as any,
2179
+ comments: true,
2180
+ },
2181
+ });
2182
+
2183
+ const [, queryJson] = mockPerspective.modelQuery.mock.calls[0];
2184
+ const qi = JSON.parse(queryJson);
2185
+
2186
+ // Without $ prefix it stays in include (behaviour is undefined/broken but not silently rerouted)
2187
+ expect(qi.projections?.mySignals).toBeUndefined();
2188
+ expect(qi.include?.mySignals).toBeDefined();
2189
+ });
2190
+
2191
+ it("omits queryInput.include when all keys are projections", async () => {
2192
+ await Post.findAll(mockPerspective, {
2193
+ include: {
2194
+ $count: { from: "signals", count: true },
2195
+ },
2196
+ });
2197
+
2198
+ const [, queryJson] = mockPerspective.modelQuery.mock.calls[0];
2199
+ const qi = JSON.parse(queryJson);
2200
+
2201
+ expect(qi.include).toBeUndefined();
2202
+ expect(qi.projections?.$count).toMatchObject({ from: "signals", count: true });
2203
+ });
2204
+
2205
+ it("omits queryInput.projections when all keys are normal includes", async () => {
2206
+ await Post.findAll(mockPerspective, {
2207
+ include: { comments: true },
2208
+ });
2209
+
2210
+ const [, queryJson] = mockPerspective.modelQuery.mock.calls[0];
2211
+ const qi = JSON.parse(queryJson);
2212
+
2213
+ expect(qi.projections).toBeUndefined();
2214
+ expect(qi.include?.comments).toBe(true);
2215
+ });
2216
+
2217
+ it("tags projection with targetClassName when relation target is registered", async () => {
2218
+ await Post.findAll(mockPerspective, {
2219
+ include: {
2220
+ $signalCount: { from: "signals", count: true },
2221
+ },
2222
+ });
2223
+
2224
+ const [, queryJson] = mockPerspective.modelQuery.mock.calls[0];
2225
+ const qi = JSON.parse(queryJson);
2226
+
2227
+ // targetClassName drives the executor's cache lookup for the target shape.
2228
+ expect(qi.projections?.$signalCount?.targetClassName).toBe("Signal");
2229
+ });
2230
+
2231
+ it("leaves targetClassName absent when relation has no target decorator", async () => {
2232
+ await Post.findAll(mockPerspective, {
2233
+ include: {
2234
+ $commentCount: { from: "comments", count: true },
2235
+ },
2236
+ });
2237
+
2238
+ const [, queryJson] = mockPerspective.modelQuery.mock.calls[0];
2239
+ const qi = JSON.parse(queryJson);
2240
+
2241
+ // 'comments' HasMany has no target() thunk → no targetClassName
2242
+ expect(qi.projections?.$commentCount?.targetClassName).toBeUndefined();
2243
+ });
2244
+
2245
+ // --- result passthrough ---
2246
+
2247
+ it("returns $-keyed projection values attached by Rust on instances", async () => {
2248
+ mockPerspective.modelQuery.mockResolvedValue({
2249
+ instances: [{ id: "post://1", title: "Hello", $signalCount: 7 }],
2250
+ totalCount: 1,
2251
+ });
2252
+
2253
+ const results = await Post.findAll(mockPerspective, {
2254
+ include: { $signalCount: { from: "signals", count: true } },
2255
+ });
2256
+
2257
+ expect((results[0] as any).$signalCount).toBe(7);
2258
+ });
2259
+
2260
+ // --- hydration of non-count projections ---
2261
+
2262
+ it("passes through scalar non-count projection value hydrated by Rust", async () => {
2263
+ // Rust hydrates projection targets in-process and returns full JSON objects.
2264
+ // The TS layer receives an already-hydrated object and passes it through.
2265
+ mockPerspective.modelQuery.mockResolvedValueOnce({
2266
+ instances: [{ id: "post://1", title: "Hello", $mySignal: { id: "signal://abc", signalTypeId: "type1" } }],
2267
+ totalCount: 1,
2268
+ });
2269
+
2270
+ const results = await Post.findAll(mockPerspective, {
2271
+ include: { $mySignal: { from: "signals", limit: 1 } },
2272
+ });
2273
+
2274
+ const mySignal = (results[0] as any).$mySignal;
2275
+ expect(mySignal).toMatchObject({ id: "signal://abc", signalTypeId: "type1" });
2276
+ });
2277
+
2278
+ it("passes through array non-count projection values hydrated by Rust", async () => {
2279
+ // Rust hydrates all IRIs in the list and returns full JSON objects.
2280
+ mockPerspective.modelQuery.mockResolvedValueOnce({
2281
+ instances: [{
2282
+ id: "post://1", title: "Hello",
2283
+ $recentSignals: [
2284
+ { id: "signal://a", signalTypeId: "type1" },
2285
+ { id: "signal://b", signalTypeId: "type2" },
2286
+ ],
2287
+ }],
2288
+ totalCount: 1,
2289
+ });
2290
+
2291
+ const results = await Post.findAll(mockPerspective, {
2292
+ include: { $recentSignals: { from: "signals" } },
2293
+ });
2294
+
2295
+ const sigs = (results[0] as any).$recentSignals;
2296
+ expect(Array.isArray(sigs)).toBe(true);
2297
+ expect(sigs).toHaveLength(2);
2298
+ expect(sigs[0]).toMatchObject({ id: "signal://a", signalTypeId: "type1" });
2299
+ expect(sigs[1]).toMatchObject({ id: "signal://b", signalTypeId: "type2" });
2300
+ });
2301
+
2302
+ it("passes through raw IRI when Rust cannot hydrate the projection target", async () => {
2303
+ // When the target cannot be resolved, Rust keeps the raw IRI string.
2304
+ mockPerspective.modelQuery.mockResolvedValueOnce({
2305
+ instances: [{ id: "post://1", title: "Hello", $mySignal: "signal://unknown" }],
2306
+ totalCount: 1,
2307
+ });
2308
+
2309
+ const results = await Post.findAll(mockPerspective, {
2310
+ include: { $mySignal: { from: "signals", limit: 1 } },
2311
+ });
2312
+
2313
+ // Raw IRI preserved when no matching target instance exists in the store.
2314
+ expect((results[0] as any).$mySignal).toBe("signal://unknown");
2315
+ });
2316
+
2317
+ it("does NOT attempt hydration for count projections (they return numbers)", async () => {
2318
+ mockPerspective.modelQuery.mockResolvedValueOnce({
2319
+ instances: [{ id: "post://1", $signalCount: 5 }],
2320
+ totalCount: 1,
2321
+ });
2322
+
2323
+ const results = await Post.findAll(mockPerspective, {
2324
+ include: { $signalCount: { from: "signals", count: true } },
2325
+ });
2326
+
2327
+ // Only one modelQuery call — no follow-up findAll for count projections.
2328
+ expect(mockPerspective.modelQuery).toHaveBeenCalledTimes(1);
2329
+ expect((results[0] as any).$signalCount).toBe(5);
2330
+ });
2331
+ });