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

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 (388) hide show
  1. package/README.md +2 -25
  2. package/jest-setup.ts +1 -1
  3. package/lib/index.cjs +5097 -11841
  4. package/lib/index.js +5289 -12104
  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 +7 -2
  153. package/lib/src/index.js +7 -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 +150 -62
  166. package/lib/src/model/Ad4mModel.js +689 -417
  167. package/lib/src/model/Ad4mModel.test.js +1434 -688
  168. package/lib/src/model/ModelQueryBuilder.d.ts +59 -38
  169. package/lib/src/model/ModelQueryBuilder.js +317 -153
  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 +46 -18
  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 +60 -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 +189 -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 +156 -78
  220. package/lib/src/perspectives/PerspectiveProxy.js +474 -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/WakerSubscriptionManager.d.ts +3 -3
  224. package/lib/src/perspectives/WakerSubscriptionManager.js +12 -12
  225. package/lib/src/runtime/RuntimeClient.d.ts +8 -6
  226. package/lib/src/runtime/RuntimeClient.js +97 -454
  227. package/lib/src/runtime/RuntimeResolver.d.ts +14 -0
  228. package/lib/src/runtime/RuntimeResolver.js +84 -0
  229. package/lib/src/runtime/RuntimeTypes.d.ts +101 -0
  230. package/lib/src/runtime/RuntimeTypes.js +45 -0
  231. package/lib/src/schema.gql +14 -1
  232. package/lib/src/shacl/SHACLFlow.d.ts +1 -1
  233. package/lib/src/shacl/SHACLFlow.js +9 -9
  234. package/lib/src/shacl/SHACLShape.d.ts +8 -1
  235. package/lib/src/shacl/SHACLShape.js +57 -38
  236. package/lib/src/shacl/SHACLShape.test.js +82 -0
  237. package/lib/src/typeDefs.js +3 -615
  238. package/lib/src/utils.d.ts +6 -6
  239. package/lib/src/utils.js +6 -6
  240. package/package.json +6 -18
  241. package/rollup.config.js +0 -7
  242. package/src/Ad4mClient.test.ts +1192 -1288
  243. package/src/Ad4mClient.ts +46 -15
  244. package/src/Literal.test.ts +10 -5
  245. package/src/Literal.ts +6 -5
  246. package/src/agent/Agent.ts +0 -99
  247. package/src/agent/AgentClient.ts +238 -467
  248. package/src/agent/AgentStatus.ts +0 -12
  249. package/src/ai/AIClient.ts +96 -296
  250. package/src/ai/AITypes.ts +66 -0
  251. package/src/ai/Tasks.ts +0 -52
  252. package/src/apiClient.ts +287 -0
  253. package/src/cache/PersistentCache.ts +145 -0
  254. package/src/cache/cache.test.ts +713 -0
  255. package/src/expression/Expression.ts +3 -43
  256. package/src/expression/ExpressionClient.ts +148 -77
  257. package/src/expression/ExpressionRef.ts +2 -8
  258. package/src/generated/api/AIModelLoadingStatus.ts +3 -0
  259. package/src/generated/api/AddLinkExpressionRequest.ts +4 -0
  260. package/src/generated/api/AddLinkRequest.ts +4 -0
  261. package/src/generated/api/AddLinksBulkRequest.ts +4 -0
  262. package/src/generated/api/AddSdnaRequest.ts +3 -0
  263. package/src/generated/api/ApplyTemplateRequest.ts +3 -0
  264. package/src/generated/api/AuthInfoInput.ts +4 -0
  265. package/src/generated/api/CapabilityInput.ts +4 -0
  266. package/src/generated/api/CommitBatchRequest.ts +3 -0
  267. package/src/generated/api/ComputeLogEntry.ts +3 -0
  268. package/src/generated/api/CreateExpressionRequest.ts +3 -0
  269. package/src/generated/api/CreatePerspectiveRequest.ts +3 -0
  270. package/src/generated/api/CreateSubjectRequest.ts +3 -0
  271. package/src/generated/api/EmbedRequest.ts +3 -0
  272. package/src/generated/api/EntanglementProofInput.ts +3 -0
  273. package/src/generated/api/ExecuteCommandsRequest.ts +3 -0
  274. package/src/generated/api/ExportRequest.ts +3 -0
  275. package/src/generated/api/ExpressionManyRequest.ts +3 -0
  276. package/src/generated/api/ExpressionProof.ts +3 -0
  277. package/src/generated/api/ExpressionProofInput.ts +3 -0
  278. package/src/generated/api/FriendSendMessageRequest.ts +3 -0
  279. package/src/generated/api/FriendsListRequest.ts +3 -0
  280. package/src/generated/api/GenerateAgentRequest.ts +3 -0
  281. package/src/generated/api/GenerateJwtRequest.ts +3 -0
  282. package/src/generated/api/GetSubjectDataRequest.ts +3 -0
  283. package/src/generated/api/ImportAgentRequest.ts +3 -0
  284. package/src/generated/api/ImportRequest.ts +3 -0
  285. package/src/generated/api/JoinNeighbourhoodRequest.ts +3 -0
  286. package/src/generated/api/LanguageMetaInput.ts +3 -0
  287. package/src/generated/api/Link.ts +3 -0
  288. package/src/generated/api/LinkExpression.ts +6 -0
  289. package/src/generated/api/LinkExpressionInput.ts +6 -0
  290. package/src/generated/api/LinkInput.ts +3 -0
  291. package/src/generated/api/LinkLanguageTemplatesRequest.ts +3 -0
  292. package/src/generated/api/LinkMutations.ts +5 -0
  293. package/src/generated/api/LinkStatus.ts +3 -0
  294. package/src/generated/api/LockAgentRequest.ts +3 -0
  295. package/src/generated/api/ModelType.ts +3 -0
  296. package/src/generated/api/NotificationInput.ts +3 -0
  297. package/src/generated/api/OpenLinkRequest.ts +3 -0
  298. package/src/generated/api/PermitCapabilityRequest.ts +3 -0
  299. package/src/generated/api/PerspectiveInput.ts +4 -0
  300. package/src/generated/api/PromptRequest.ts +3 -0
  301. package/src/generated/api/PublishLanguageRequest.ts +4 -0
  302. package/src/generated/api/PublishNeighbourhoodRequest.ts +4 -0
  303. package/src/generated/api/QueryRequest.ts +6 -0
  304. package/src/generated/api/RemoveLinkRequest.ts +4 -0
  305. package/src/generated/api/RemoveLinksBulkRequest.ts +4 -0
  306. package/src/generated/api/ResourceInput.ts +3 -0
  307. package/src/generated/api/SetDefaultModelRequest.ts +4 -0
  308. package/src/generated/api/SetFreeHostingEnabledRequest.ts +3 -0
  309. package/src/generated/api/SetMultiUserRequest.ts +3 -0
  310. package/src/generated/api/SetStatusRequest.ts +3 -0
  311. package/src/generated/api/SignMessageRequest.ts +3 -0
  312. package/src/generated/api/TrustedAgentsRequest.ts +3 -0
  313. package/src/generated/api/UnlockAgentRequest.ts +3 -0
  314. package/src/generated/api/UpdateLinkRequest.ts +5 -0
  315. package/src/generated/api/UpdatePerspectiveRequest.ts +3 -0
  316. package/src/generated/api/UserStatistics.ts +3 -0
  317. package/src/generated/api/VerificationRequestResult.ts +3 -0
  318. package/src/generated/api/VerifySignatureRequest.ts +3 -0
  319. package/src/generated/api/WriteSettingsRequest.ts +3 -0
  320. package/src/generated/api/index.ts +49 -0
  321. package/src/index.ts +7 -2
  322. package/src/jestSetup.ts +1 -1
  323. package/src/language/Icon.ts +0 -4
  324. package/src/language/Language.ts +51 -248
  325. package/src/language/LanguageClient.ts +21 -132
  326. package/src/language/LanguageHandle.ts +0 -14
  327. package/src/language/LanguageMeta.ts +0 -29
  328. package/src/language/LanguageRef.ts +0 -7
  329. package/src/links/Links.ts +0 -37
  330. package/src/model/Ad4mModel.test.ts +1690 -777
  331. package/src/model/Ad4mModel.ts +749 -477
  332. package/src/model/ModelQueryBuilder.ts +356 -171
  333. package/src/model/decorators.ts +71 -22
  334. package/src/model/hydration.ts +3 -772
  335. package/src/model/index.ts +3 -4
  336. package/src/model/json-schema.ts +2 -2
  337. package/src/model/query-cache.test.ts +54 -0
  338. package/src/model/query-cache.ts +79 -0
  339. package/src/model/query-common.ts +1 -1
  340. package/src/model/query-sparql.test.ts +376 -0
  341. package/src/model/query-sparql.ts +504 -0
  342. package/src/model/query-utils.ts +209 -0
  343. package/src/model/relation-filtering.test.ts +15 -15
  344. package/src/model/sdna.ts +1 -1
  345. package/src/model/shacl-gen.ts +47 -17
  346. package/src/model/types.ts +65 -5
  347. package/src/neighbourhood/Neighbourhood.ts +0 -9
  348. package/src/neighbourhood/NeighbourhoodClient.ts +42 -207
  349. package/src/neighbourhood/NeighbourhoodProxy.test.ts +34 -36
  350. package/src/perspectives/LinkQuery.ts +0 -15
  351. package/src/perspectives/Perspective.ts +1 -12
  352. package/src/perspectives/PerspectiveClient.test.ts +262 -0
  353. package/src/perspectives/PerspectiveClient.ts +254 -468
  354. package/src/perspectives/PerspectiveDiff.ts +0 -8
  355. package/src/perspectives/PerspectiveHandle.ts +1 -12
  356. package/src/perspectives/PerspectiveProxy.test.ts +125 -0
  357. package/src/perspectives/PerspectiveProxy.ts +522 -434
  358. package/src/perspectives/WakerSubscriptionManager.ts +13 -13
  359. package/src/runtime/RuntimeClient.ts +118 -461
  360. package/src/runtime/RuntimeTypes.ts +144 -0
  361. package/src/shacl/SHACLFlow.ts +9 -9
  362. package/src/shacl/SHACLShape.test.ts +94 -0
  363. package/src/shacl/SHACLShape.ts +66 -39
  364. package/src/typeDefs.ts +3 -5
  365. package/src/utils.ts +6 -6
  366. package/tsconfig.json +3 -7
  367. package/lib/src/model/query-surreal.d.ts +0 -44
  368. package/lib/src/model/query-surreal.js +0 -249
  369. package/lib/src/model/surreal-utils.js +0 -128
  370. package/shims/reflect-metadata.ts +0 -0
  371. package/shims/type-graphql.ts +0 -75
  372. package/src/PubSub.ts +0 -17
  373. package/src/agent/AgentResolver.ts +0 -263
  374. package/src/ai/AIResolver.ts +0 -372
  375. package/src/buildSchema.ts +0 -43
  376. package/src/expression/ExpressionResolver.ts +0 -64
  377. package/src/language/LanguageContext.ts +0 -37
  378. package/src/language/LanguageResolver.ts +0 -98
  379. package/src/model/Subject.ts +0 -159
  380. package/src/model/prolog-facts.ts +0 -145
  381. package/src/model/query-prolog.ts +0 -148
  382. package/src/model/query-surreal.ts +0 -280
  383. package/src/model/surreal-utils.ts +0 -147
  384. package/src/neighbourhood/NeighbourhoodResolver.ts +0 -100
  385. package/src/perspectives/PerspectiveResolver.ts +0 -372
  386. package/src/runtime/RuntimeResolver.ts +0 -691
  387. package/src/unwrapApolloResult.ts +0 -16
  388. package/tsconfig-browser.json +0 -82
@@ -1,16 +1,10 @@
1
1
  /**
2
2
  * hydration.ts — Instance hydration helpers extracted from Ad4mModel.
3
3
  *
4
- * Pure / stateless functions that populate Ad4mModel instances from
5
- * raw link arrays, Prolog tuples, or SurrealDB rows. None of these
6
- * functions depend on the `Ad4mModel` class at runtime — they accept
7
- * the instance, metadata, or perspective as explicit parameters.
4
+ * After the Rust model_query pipeline migration, most hydration logic moved
5
+ * to Rust. This file retains:
6
+ * - normalizeValue() — snapshot dirty-tracking
8
7
  */
9
- import { Literal } from "../Literal";
10
- import { LinkQuery } from "../perspectives/LinkQuery";
11
- import { getPropertiesMetadata, getRelationsMetadata, buildConformanceFilter } from "./decorators";
12
- import { escapeSurrealString } from "../utils";
13
- import { formatSurrealValue, compileWhereClause } from "./surreal-utils";
14
8
  // ──────────────────────────────────────────────────────────
15
9
  // Pure helpers
16
10
  // ──────────────────────────────────────────────────────────
@@ -25,685 +19,3 @@ export function normalizeValue(value) {
25
19
  }
26
20
  return value;
27
21
  }
28
- /**
29
- * Checks if a value matches a where-condition (for post-query filtering).
30
- */
31
- export function matchesCondition(value, condition) {
32
- // Handle array values (IN clause)
33
- if (Array.isArray(condition)) {
34
- return condition.includes(value);
35
- }
36
- // Handle operator object
37
- if (typeof condition === 'object' && condition !== null) {
38
- const ops = condition;
39
- // Special case: 'not' operator (exclusive with other operators)
40
- if (ops.not !== undefined) {
41
- if (Array.isArray(ops.not)) {
42
- return !ops.not.includes(value);
43
- }
44
- else {
45
- return value !== ops.not;
46
- }
47
- }
48
- // Special case: 'between' operator (inclusive range, exclusive with gt/gte/lt/lte)
49
- if (ops.between !== undefined && Array.isArray(ops.between) && ops.between.length === 2) {
50
- return value >= ops.between[0] && value <= ops.between[1];
51
- }
52
- // For all other operators (gt, gte, lt, lte, contains), we need to check ALL of them
53
- // and return true only if ALL conditions are satisfied
54
- let allConditionsMet = true;
55
- if (ops.gt !== undefined) {
56
- allConditionsMet = allConditionsMet && (value > ops.gt);
57
- }
58
- if (ops.gte !== undefined) {
59
- allConditionsMet = allConditionsMet && (value >= ops.gte);
60
- }
61
- if (ops.lt !== undefined) {
62
- allConditionsMet = allConditionsMet && (value < ops.lt);
63
- }
64
- if (ops.lte !== undefined) {
65
- allConditionsMet = allConditionsMet && (value <= ops.lte);
66
- }
67
- if (ops.contains !== undefined) {
68
- if (typeof value === 'string') {
69
- allConditionsMet = allConditionsMet && value.includes(String(ops.contains));
70
- }
71
- else if (Array.isArray(value)) {
72
- allConditionsMet = allConditionsMet && value.includes(ops.contains);
73
- }
74
- else {
75
- allConditionsMet = false;
76
- }
77
- }
78
- return allConditionsMet;
79
- }
80
- // Simple equality
81
- return value === condition;
82
- }
83
- // ──────────────────────────────────────────────────────────
84
- // Property / link hydration
85
- // ──────────────────────────────────────────────────────────
86
- /**
87
- * Resolves a single property value from a raw link target string.
88
- *
89
- * Handles expression resolution, literal URI parsing, primitive
90
- * type coercion, and optional transform functions.
91
- *
92
- * @param target - The raw target string from the link
93
- * @param propMeta - Property metadata from the decorator registry
94
- * @param perspective - The perspective for expression resolution
95
- * @param expectedType - Optional JS typeof hint for coercion (e.g. 'number')
96
- * @returns The resolved value
97
- */
98
- export async function hydratePropertyValue(target, propMeta, perspective, expectedType) {
99
- let value = target;
100
- if (target !== undefined && target !== null && target !== '') {
101
- // Non-literal expression resolution
102
- if (propMeta.resolveLanguage != null &&
103
- propMeta.resolveLanguage !== 'literal' &&
104
- typeof target === 'string' &&
105
- !target.startsWith('literal://')) {
106
- try {
107
- const expression = await perspective.getExpression(target);
108
- if (expression) {
109
- try {
110
- value = JSON.parse(expression.data);
111
- }
112
- catch {
113
- value = expression.data;
114
- }
115
- }
116
- }
117
- catch (e) {
118
- console.warn(`hydratePropertyValue: failed to resolve expression for "${propMeta.name}":`, e);
119
- }
120
- }
121
- // Literal URI parsing
122
- else if (propMeta.resolveLanguage === 'literal' &&
123
- typeof target === 'string' &&
124
- target.startsWith('literal://')) {
125
- try {
126
- const parsed = Literal.fromUrl(target).get();
127
- value = parsed.data !== undefined ? parsed.data : parsed;
128
- }
129
- catch {
130
- // Keep raw value
131
- }
132
- }
133
- // Primitive type coercion
134
- else if (typeof target === 'string' && expectedType) {
135
- if (expectedType === 'number')
136
- value = Number(target);
137
- else if (expectedType === 'boolean')
138
- value = target === 'true' || target === '1';
139
- }
140
- }
141
- // Transform function
142
- if (propMeta.transform && typeof propMeta.transform === 'function') {
143
- value = propMeta.transform(value);
144
- }
145
- return value;
146
- }
147
- /**
148
- * Hydrates an instance from an array of raw links.
149
- *
150
- * Processes properties (latest-wins semantics), relations
151
- * (chronological accumulation), and timestamps/author in a single
152
- * pass over the links array.
153
- *
154
- * @param instance - The blank model instance to populate
155
- * @param links - Array of link objects (predicate, target, author?, timestamp?)
156
- * @param metadata - Model metadata from `getModelMetadata()`
157
- * @param perspective - The perspective for expression resolution
158
- * @param requestedProperties - Optional sparse fieldset; when provided, only these
159
- * property names are hydrated (relations are unaffected).
160
- * Omit or pass `undefined` to hydrate all properties.
161
- */
162
- export async function hydrateFromLinks(instance, links, metadata, perspective, requestedProperties) {
163
- if (!links || links.length === 0)
164
- return;
165
- let minTimestamp = null;
166
- let maxTimestamp = null;
167
- let originalAuthor = null;
168
- let latestAuthor = null;
169
- // Build predicate→propName and predicate→relName lookup maps for O(1) matching
170
- // When requestedProperties is provided, only include those properties in the map
171
- const propFilter = requestedProperties && requestedProperties.length > 0
172
- ? new Set(requestedProperties)
173
- : null;
174
- const predToProperty = new Map();
175
- for (const [propName, propMeta] of Object.entries(metadata.properties)) {
176
- if (propMeta.getter)
177
- continue; // Handled via custom getter evaluation
178
- if (propFilter && !propFilter.has(propName))
179
- continue; // Skip unrequested properties
180
- predToProperty.set(propMeta.predicate, [propName, propMeta]);
181
- }
182
- const predToRelation = new Map();
183
- // Two-pass approach: first add all non-getter, non-target-filtered relations,
184
- // then try to add target+filter relations only if their predicate isn't
185
- // already claimed. This prevents predicate collisions (e.g. entries +
186
- // messages sharing the same predicate) while still populating unique-
187
- // predicate relations normally via link hydration.
188
- const deferredTargetRelations = [];
189
- for (const [relName, relMeta] of Object.entries(metadata.relations)) {
190
- if (relMeta.getter)
191
- continue; // Handled via explicit custom getter evaluation
192
- if (relMeta.target && relMeta.filter !== false) {
193
- deferredTargetRelations.push([relName, relMeta]);
194
- continue;
195
- }
196
- predToRelation.set(relMeta.predicate, [relName, relMeta]);
197
- }
198
- // Second pass: add deferred target+filter relations only if their predicate
199
- // is not already claimed by a base relation. When a collision exists, the
200
- // conformance getter will handle the filtered view instead.
201
- for (const [relName, relMeta] of deferredTargetRelations) {
202
- if (!predToRelation.has(relMeta.predicate)) {
203
- predToRelation.set(relMeta.predicate, [relName, relMeta]);
204
- }
205
- }
206
- // Per-property accumulator: track all matching targets so we can pick the last (latest-wins)
207
- const propertyLatest = new Map();
208
- // Per-relation accumulator: ordered targets with metadata for sorting
209
- const relationAccum = new Map();
210
- // Single pass over all links
211
- for (let i = 0; i < links.length; i++) {
212
- const link = links[i];
213
- const { predicate, target, author, timestamp } = link;
214
- if (target === 'None' || target === undefined || target === null)
215
- continue;
216
- // Track timestamps/authors
217
- if (timestamp != null) {
218
- if (minTimestamp == null || timestamp < minTimestamp) {
219
- minTimestamp = timestamp;
220
- originalAuthor = author ?? null;
221
- }
222
- if (maxTimestamp == null || timestamp > maxTimestamp) {
223
- maxTimestamp = timestamp;
224
- latestAuthor = author ?? null;
225
- }
226
- }
227
- // Property match — accumulate for latest-wins
228
- const propEntry = predToProperty.get(predicate);
229
- if (propEntry) {
230
- const existing = propertyLatest.get(propEntry[0]);
231
- // Latest-wins: always overwrite (links are ordered ASC so last = latest)
232
- propertyLatest.set(propEntry[0], { target, timestamp });
233
- continue;
234
- }
235
- // Relation match — accumulate all
236
- const relEntry = predToRelation.get(predicate);
237
- if (relEntry) {
238
- const [relName] = relEntry;
239
- let arr = relationAccum.get(relName);
240
- if (!arr) {
241
- arr = [];
242
- relationAccum.set(relName, arr);
243
- }
244
- arr.push({ target, timestamp: timestamp ?? '', index: i });
245
- }
246
- }
247
- // Resolve properties
248
- for (const [propName, { target }] of propertyLatest) {
249
- const [, propMeta] = predToProperty.get(metadata.properties[propName].predicate);
250
- const expectedType = typeof instance[propName];
251
- instance[propName] = await hydratePropertyValue(target, propMeta, perspective, expectedType !== 'undefined' ? expectedType : undefined);
252
- }
253
- // Resolve relations: sort by timestamp (stable via index tiebreaker), filter empties
254
- for (const [relName, items] of relationAccum) {
255
- items.sort((a, b) => {
256
- const cmp = String(a.timestamp).localeCompare(String(b.timestamp));
257
- return cmp !== 0 ? cmp : a.index - b.index;
258
- });
259
- instance[relName] = items
260
- .map(i => i.target)
261
- .filter((v) => v !== undefined && v !== null && v !== '' && v !== 'None');
262
- }
263
- // Assign author / timestamps
264
- if (originalAuthor)
265
- instance.author = originalAuthor;
266
- if (minTimestamp != null) {
267
- instance.createdAt = typeof minTimestamp === 'string' && minTimestamp.includes('T')
268
- ? new Date(minTimestamp).getTime()
269
- : typeof minTimestamp === 'string'
270
- ? (isNaN(parseInt(minTimestamp, 10)) ? minTimestamp : parseInt(minTimestamp, 10))
271
- : minTimestamp;
272
- }
273
- if (maxTimestamp != null) {
274
- instance.updatedAt = typeof maxTimestamp === 'string' && maxTimestamp.includes('T')
275
- ? new Date(maxTimestamp).getTime()
276
- : typeof maxTimestamp === 'string'
277
- ? (isNaN(parseInt(maxTimestamp, 10)) ? maxTimestamp : parseInt(maxTimestamp, 10))
278
- : maxTimestamp;
279
- }
280
- }
281
- // ──────────────────────────────────────────────────────────
282
- // Prolog result hydration (assignValuesToInstance)
283
- // ──────────────────────────────────────────────────────────
284
- /**
285
- * Assigns decoded Prolog property values to an instance.
286
- *
287
- * Handles UTF-8 byte sequence reconstruction, expression resolution,
288
- * transform functions, and read-only property filtering.
289
- */
290
- export async function assignValuesToInstance(perspective, instance, values) {
291
- // Map properties to object
292
- const propsObject = Object.fromEntries(await Promise.all(values.map(async ([name, value, resolve]) => {
293
- let finalValue = value;
294
- // Handle UTF-8 byte sequences from Prolog URL decoding
295
- if (!resolve && typeof value === 'string') {
296
- // Only attempt reconstruction if the string looks like a byte string (all code points <= 0xFF)
297
- // and contains at least one high byte (>= 0x80). This avoids mangling valid Unicode.
298
- const codePoints = Array.from(value, ch => ch.codePointAt(0));
299
- const looksByteString = codePoints.every(cp => cp <= 0xFF);
300
- const hasHighByte = codePoints.some(cp => cp >= 0x80);
301
- if (looksByteString && hasHighByte) {
302
- try {
303
- const bytes = Uint8Array.from(codePoints);
304
- const decoded = new TextDecoder('utf-8', { fatal: true }).decode(bytes);
305
- if (decoded !== value)
306
- finalValue = decoded;
307
- }
308
- catch (error) {
309
- // If UTF-8 conversion fails, keep the original value
310
- console.warn(`UTF-8 byte reconstruction failed for property "${name}"`, { value, error });
311
- }
312
- }
313
- }
314
- // Resolve the value if necessary
315
- if (resolve) {
316
- let resolvedExpression = await perspective.getExpression(value);
317
- if (resolvedExpression) {
318
- try {
319
- // Attempt to parse the data as JSON
320
- finalValue = JSON.parse(resolvedExpression.data);
321
- }
322
- catch (error) {
323
- // If parsing fails, keep the original data
324
- finalValue = resolvedExpression.data;
325
- }
326
- }
327
- }
328
- // Apply transform function if it exists
329
- const propsMeta = getPropertiesMetadata(instance.constructor);
330
- const transform = propsMeta[name]?.transform;
331
- if (transform && typeof transform === "function") {
332
- finalValue = transform(finalValue);
333
- }
334
- return [name, finalValue];
335
- })));
336
- // Filter out properties that are read-only (getters without setters)
337
- const writableProps = Object.fromEntries(Object.entries(propsObject).filter(([key]) => {
338
- const descriptor = Object.getOwnPropertyDescriptor(Object.getPrototypeOf(instance), key);
339
- if (!descriptor) {
340
- // No descriptor means it's a regular property on the instance, allow it
341
- return true;
342
- }
343
- // Check if it's an accessor descriptor (has get/set) vs data descriptor (has value/writable)
344
- const isAccessor = descriptor.get !== undefined || descriptor.set !== undefined;
345
- if (isAccessor) {
346
- // Accessor descriptor: only allow if it has a setter
347
- return descriptor.set !== undefined;
348
- }
349
- else {
350
- // Data descriptor: only allow if writable is not explicitly false
351
- return descriptor.writable !== false;
352
- }
353
- }));
354
- // Assign properties to instance
355
- Object.assign(instance, writableProps);
356
- }
357
- // ──────────────────────────────────────────────────────────
358
- // SurrealQL custom getter evaluation
359
- // ──────────────────────────────────────────────────────────
360
- /**
361
- * Builds a SurrealQL conformance getter for a relation whose `target` model
362
- * is known but no explicit `getter` string was supplied.
363
- *
364
- * The generated getter traverses outgoing links matching the relation's
365
- * predicate and then filters the target nodes to only those that conform to
366
- * the target model's shape (required properties / flags).
367
- *
368
- * Delegates to the shared `buildConformanceFilter()` utility in decorators.ts
369
- * so the same logic is used at shape-definition time and at query time.
370
- *
371
- * @param relationPredicate - The relation's predicate URI (e.g. "flux://entry_type")
372
- * @param targetClass - The target model class (result of calling the `target()` thunk)
373
- * @returns A SurrealQL expression string, or `undefined` if no conformance
374
- * conditions could be derived from the target model.
375
- */
376
- export function buildConformanceGetter(relationPredicate, targetClass) {
377
- const filter = buildConformanceFilter(relationPredicate, targetClass);
378
- if (!filter) {
379
- const targetName = targetClass?.prototype?.className || targetClass?.name || 'unknown';
380
- console.warn(`[Ad4mModel] buildConformanceGetter: no conditions found for target "${targetName}".`);
381
- return undefined;
382
- }
383
- return filter.getter;
384
- }
385
- /**
386
- * Evaluates custom SurrealQL getters for properties and relations on a specific instance.
387
- *
388
- * For relations that declare a `target` but no explicit `getter`, a conformance
389
- * getter is auto-generated from the target model's metadata (unless `filter: false`).
390
- */
391
- export async function evaluateCustomGettersForInstance(instance, perspective, metadata, options) {
392
- const safeBaseExpression = formatSurrealValue(instance.id);
393
- // Build projection filter — when requestedProperties is active, only
394
- // evaluate getters for fields that are requested (or included).
395
- const projectionActive = options?.requestedProperties && options.requestedProperties.length > 0;
396
- const projectionSet = projectionActive ? new Set(options.requestedProperties) : null;
397
- // Evaluate property getters
398
- for (const [propName, propMeta] of Object.entries(metadata.properties)) {
399
- if (projectionSet && !projectionSet.has(propName))
400
- continue;
401
- if (propMeta.getter) {
402
- try {
403
- // Replace 'Base' placeholder with actual base expression
404
- const query = propMeta.getter.replace(/Base/g, safeBaseExpression);
405
- // Query from node table to have graph traversal context
406
- const result = await perspective.querySurrealDB(`SELECT (${query}) AS value FROM node WHERE uri = ${safeBaseExpression}`);
407
- if (result && result.length > 0 && result[0].value !== undefined && result[0].value !== null && result[0].value !== 'None' && result[0].value !== '') {
408
- instance[propName] = result[0].value;
409
- }
410
- }
411
- catch (error) {
412
- console.warn(`Failed to evaluate getter for ${propName}:`, error);
413
- }
414
- }
415
- }
416
- // Evaluate relation getters (explicit or auto-generated from target)
417
- for (const [relName, relMeta] of Object.entries(metadata.relations)) {
418
- // Skip relations excluded by property projection (unless in include map)
419
- if (projectionSet && !projectionSet.has(relName) && !(options?.include && relName in options.include))
420
- continue;
421
- const meta = relMeta;
422
- // Determine the getter to execute:
423
- // 1. Explicit `getter` always wins
424
- // 2. `where` clause → compile DSL to SurrealQL getter
425
- // 3. If `target` is set and `filter !== false`, auto-generate from target metadata
426
- // BUT skip auto-generation for reverse relations (belongsToMany / belongsToOne)
427
- // because buildConformanceGetter traverses outgoing links (->link) which is
428
- // wrong for reverse relations. Their values are already populated by the
429
- // reverse link lookup in instancesFromSurrealResult / getData.
430
- let getter = meta.getter;
431
- if (!getter && meta.where && meta.direction !== 'reverse') {
432
- try {
433
- const TargetClass = meta.target?.();
434
- const targetMetadata = TargetClass
435
- ? TargetClass.getModelMetadata?.() ?? null
436
- : null;
437
- const conditions = compileWhereClause(meta.where, targetMetadata);
438
- if (conditions.length > 0) {
439
- const escapedPred = escapeSurrealString(meta.predicate);
440
- getter = `(->link[WHERE predicate = '${escapedPred}'].out[WHERE ${conditions.join(' AND ')}].uri)`;
441
- }
442
- }
443
- catch (e) {
444
- // Target metadata may not be available yet
445
- }
446
- }
447
- if (!getter && meta.target && meta.filter !== false && meta.direction !== 'reverse') {
448
- try {
449
- const TargetClass = meta.target();
450
- getter = buildConformanceGetter(meta.predicate, TargetClass);
451
- if (!getter) {
452
- console.warn(`[Ad4mModel] buildConformanceGetter returned undefined for relation "${relName}" (predicate: "${meta.predicate}")`);
453
- }
454
- }
455
- catch (e) {
456
- console.warn(`[Ad4mModel] auto-generation failed for relation "${relName}":`, e);
457
- }
458
- }
459
- if (getter) {
460
- try {
461
- // Replace 'Base' placeholder with actual base expression
462
- const query = getter.replace(/Base/g, safeBaseExpression);
463
- const fullQuery = `SELECT (${query}) AS value FROM node WHERE uri = ${safeBaseExpression}`;
464
- // Query from node table to have graph traversal context
465
- const result = await perspective.querySurrealDB(fullQuery);
466
- if (result && result.length > 0 && result[0].value !== undefined && result[0].value !== null) {
467
- // Filter out 'None' from relation results
468
- const value = result[0].value;
469
- instance[relName] = Array.isArray(value)
470
- ? value.filter((v) => v !== undefined && v !== null && v !== '' && v !== 'None')
471
- : value;
472
- }
473
- }
474
- catch (error) {
475
- console.warn(`Failed to evaluate getter for ${relName}:`, error);
476
- }
477
- }
478
- }
479
- }
480
- /**
481
- * Hydrates relation fields on instances according to the provided IncludeMap.
482
- *
483
- * For each relation listed in `includeMap`, the raw expression-URI strings
484
- * stored on the instance are replaced with fully-hydrated model instances
485
- * (fetched via the relation's `target()` class). Nested IncludeMaps are
486
- * supported for multi-level eager loading.
487
- *
488
- * @param modelClass - The model class whose relation metadata to read
489
- * @param instances - The instances whose relations should be hydrated
490
- * @param perspective - The perspective to fetch related instances from
491
- * @param includeMap - Describes which relations to hydrate
492
- */
493
- export async function hydrateRelations(modelClass, instances, perspective, includeMap) {
494
- if (!includeMap || Object.keys(includeMap).length === 0)
495
- return;
496
- const relMeta = getRelationsMetadata(modelClass);
497
- for (const [relName, includeValue] of Object.entries(includeMap)) {
498
- const meta = relMeta[relName];
499
- if (!meta) {
500
- console.warn(`include: relation "${relName}" not found in metadata, skipping`);
501
- continue;
502
- }
503
- const TargetClass = meta.target();
504
- // Determine if a RelationSubQuery was supplied (object) vs a plain `true`
505
- const subQuery = typeof includeValue === 'object' && includeValue !== null
506
- ? includeValue
507
- : undefined;
508
- const nestedInclude = subQuery?.include;
509
- // ── Reverse relations (belongsToOne / belongsToMany) ──────────────────
510
- // The link goes target→instance, so we query backwards:
511
- // predicate = meta.predicate, target = inst.id → source is the related id
512
- if (meta.kind === 'belongsToOne' || meta.kind === 'belongsToMany') {
513
- // Per-instance reverse lookup (can't batch easily across instances)
514
- for (const inst of instances) {
515
- const reverseLinks = await perspective.get(new LinkQuery({ predicate: meta.predicate, target: inst.id }));
516
- // Defensive filter: perspective.get may return extra results; ensure
517
- // we only use links that genuinely point to this instance.
518
- const sourceIds = reverseLinks
519
- .filter(l => l.data.target === inst.id)
520
- .map(l => l.data.source);
521
- if (meta.kind === 'belongsToOne') {
522
- if (sourceIds.length === 0) {
523
- inst[relName] = null;
524
- continue;
525
- }
526
- const sourceId = sourceIds[sourceIds.length - 1]; // latest-wins
527
- try {
528
- const related = new TargetClass(perspective, sourceId);
529
- await related.get();
530
- inst[relName] = related;
531
- }
532
- catch {
533
- inst[relName] = null;
534
- }
535
- }
536
- else {
537
- // belongsToMany — return array of hydrated instances
538
- let hydrated = [];
539
- // If there's a where/order sub-query, delegate to findAll for filtering
540
- if (subQuery && (subQuery.where || subQuery.order || subQuery.properties)) {
541
- const whereWithIds = {
542
- id: sourceIds,
543
- ...(subQuery.where ?? {}),
544
- };
545
- hydrated = await TargetClass.findAll(perspective, {
546
- where: whereWithIds,
547
- ...(subQuery.order && { order: subQuery.order }),
548
- ...(subQuery.properties && { properties: subQuery.properties }),
549
- });
550
- }
551
- else {
552
- await Promise.all(sourceIds.map(async (sid) => {
553
- try {
554
- const related = new TargetClass(perspective, sid);
555
- await related.get(subQuery?.properties ? { properties: subQuery.properties } : undefined);
556
- hydrated.push(related);
557
- }
558
- catch { /* skip */ }
559
- }));
560
- }
561
- // Apply order (client-side, if not already handled by findAll above)
562
- if (subQuery?.order && !(subQuery.where || subQuery.properties)) {
563
- const orderEntries = Object.entries(subQuery.order);
564
- hydrated = hydrated.sort((a, b) => {
565
- for (const [field, dir] of orderEntries) {
566
- const av = String(a[field] ?? '');
567
- const bv = String(b[field] ?? '');
568
- const diff = av.localeCompare(bv);
569
- if (diff !== 0)
570
- return dir === 'DESC' ? -diff : diff;
571
- }
572
- return 0;
573
- });
574
- }
575
- // Apply offset and limit
576
- if (subQuery?.offset != null || subQuery?.limit != null) {
577
- const start = subQuery.offset ?? 0;
578
- const end = subQuery.limit != null ? start + subQuery.limit : undefined;
579
- hydrated = hydrated.slice(start, end);
580
- }
581
- inst[relName] = hydrated;
582
- // Recurse for nested includes
583
- if (nestedInclude && hydrated.length > 0) {
584
- await hydrateRelations(TargetClass, hydrated, perspective, nestedInclude);
585
- }
586
- }
587
- }
588
- continue; // skip the forward-relation path below
589
- }
590
- // ── Forward relations (hasMany / hasOne) ──────────────────────────────
591
- // Collect all unique URIs across all instances for batch-friendly lookup.
592
- // IMPORTANT: We cache each instance's raw value NOW (before the async
593
- // findAll) so that concurrent getData() calls on the same instance can't
594
- // overwrite the relation field between the uriSet relation and the
595
- // post-await assignment loop. Without this cache, a concurrent call
596
- // can replace the raw URI strings with hydrated model objects, causing
597
- // the `typeof v === 'string'` check to fail and the array to end up empty.
598
- const uriSet = new Set();
599
- const rawCache = new Map();
600
- for (const inst of instances) {
601
- const raw = inst[relName];
602
- rawCache.set(inst, Array.isArray(raw) ? [...raw] : raw);
603
- if (raw == null)
604
- continue;
605
- if (Array.isArray(raw)) {
606
- for (const v of raw) {
607
- if (typeof v === 'string')
608
- uriSet.add(v);
609
- // Handle already-hydrated instances (from a concurrent call)
610
- else if (v && typeof v === 'object' && typeof v.id === 'string')
611
- uriSet.add(v.id);
612
- }
613
- }
614
- else if (typeof raw === 'string') {
615
- uriSet.add(raw);
616
- }
617
- else if (raw && typeof raw === 'object' && typeof raw.id === 'string') {
618
- uriSet.add(raw.id);
619
- }
620
- }
621
- if (uriSet.size === 0)
622
- continue;
623
- // Hydrate related instances using findAll to ensure conformance checking.
624
- // findAll validates model membership via graph traversal (required predicates / flags),
625
- // so non-conforming linked URIs are silently dropped — matching the documented behaviour.
626
- const hydrated = new Map();
627
- const whereWithIds = {
628
- id: Array.from(uriSet),
629
- ...(subQuery?.where ?? {}),
630
- };
631
- const fetchQuery = {
632
- where: whereWithIds,
633
- ...(subQuery?.order && { order: subQuery.order }),
634
- ...(subQuery?.properties && { properties: subQuery.properties }),
635
- };
636
- const results = await TargetClass.findAll(perspective, fetchQuery);
637
- for (const result of results) {
638
- hydrated.set(result.id, result);
639
- }
640
- // Replace raw URIs with hydrated instances on each parent instance.
641
- // Use the cached raw values captured BEFORE the async findAll to avoid
642
- // the race condition where a concurrent getData() already replaced the
643
- // strings with hydrated objects.
644
- for (const inst of instances) {
645
- const raw = rawCache.get(inst);
646
- if (raw == null)
647
- continue;
648
- if (Array.isArray(raw)) {
649
- // Map URIs → instances; handle both raw strings and already-hydrated objects
650
- let resolved = raw
651
- .map((v) => {
652
- if (typeof v === 'string') {
653
- return hydrated.has(v) ? hydrated.get(v) : null;
654
- }
655
- // Already a hydrated model instance (from a concurrent call)
656
- if (v && typeof v === 'object' && typeof v.id === 'string') {
657
- return hydrated.has(v.id) ? hydrated.get(v.id) : v;
658
- }
659
- return null;
660
- })
661
- .filter((v) => v !== null);
662
- // Per-instance sort (client-side, after filtering)
663
- if (subQuery?.order) {
664
- const orderEntries = Object.entries(subQuery.order);
665
- resolved = resolved.sort((a, b) => {
666
- for (const [field, dir] of orderEntries) {
667
- const av = String(a[field] ?? '');
668
- const bv = String(b[field] ?? '');
669
- const diff = av.localeCompare(bv);
670
- if (diff !== 0)
671
- return dir === 'DESC' ? -diff : diff;
672
- }
673
- return 0;
674
- });
675
- }
676
- // Per-instance limit / offset
677
- if (subQuery?.offset != null || subQuery?.limit != null) {
678
- const start = subQuery.offset ?? 0;
679
- const end = subQuery.limit != null ? start + subQuery.limit : undefined;
680
- resolved = resolved.slice(start, end);
681
- }
682
- // Enforce maxCount guard — single-valued relations keep only the last item
683
- if (meta.maxCount === 1) {
684
- if (resolved.length > 1) {
685
- console.warn(`include: relation "${relName}" has maxCount 1 but ${resolved.length} values found; keeping the last`);
686
- }
687
- inst[relName] = resolved.length > 0
688
- ? resolved[resolved.length - 1]
689
- : null;
690
- }
691
- else {
692
- inst[relName] = resolved;
693
- }
694
- }
695
- else if (typeof raw === 'string' && hydrated.has(raw)) {
696
- inst[relName] = hydrated.get(raw);
697
- }
698
- else if (raw && typeof raw === 'object' && typeof raw.id === 'string') {
699
- // Already-hydrated object — look up refreshed version or keep as-is
700
- inst[relName] = hydrated.has(raw.id) ? hydrated.get(raw.id) : raw;
701
- }
702
- }
703
- // Recurse for nested includes
704
- if (nestedInclude) {
705
- const hydratedInstances = Array.from(hydrated.values());
706
- await hydrateRelations(TargetClass, hydratedInstances, perspective, nestedInclude);
707
- }
708
- }
709
- }