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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (264) hide show
  1. package/lib/index.cjs +1109 -828
  2. package/lib/index.js +1096 -828
  3. package/lib/src/Ad4mClient.d.ts +4 -1
  4. package/lib/src/Ad4mClient.js +2 -2
  5. package/lib/src/agent/AgentClient.js +17 -0
  6. package/lib/src/ai/AIClient.js +1 -1
  7. package/lib/src/apiClient.d.ts +5 -1
  8. package/lib/src/apiClient.js +14 -6
  9. package/lib/src/generated/rest/AIModelLoadingStatus.d.ts +7 -0
  10. package/lib/src/generated/rest/AIModelLoadingStatus.js +2 -0
  11. package/lib/src/generated/rest/AddAgentInfosRequest.d.ts +3 -0
  12. package/lib/src/generated/rest/AddAgentInfosRequest.js +2 -0
  13. package/lib/src/generated/rest/AddLinkExpressionRequest.d.ts +6 -0
  14. package/lib/src/generated/rest/AddLinkExpressionRequest.js +1 -0
  15. package/lib/src/generated/rest/AddLinkRequest.d.ts +6 -0
  16. package/lib/src/generated/rest/AddLinkRequest.js +1 -0
  17. package/lib/src/generated/rest/AddLinksBulkRequest.d.ts +6 -0
  18. package/lib/src/generated/rest/AddLinksBulkRequest.js +1 -0
  19. package/lib/src/generated/rest/AddSdnaRequest.d.ts +6 -0
  20. package/lib/src/generated/rest/AddSdnaRequest.js +2 -0
  21. package/lib/src/generated/rest/ApplyTemplateRequest.d.ts +4 -0
  22. package/lib/src/generated/rest/ApplyTemplateRequest.js +2 -0
  23. package/lib/src/generated/rest/AuthInfoInput.d.ts +10 -0
  24. package/lib/src/generated/rest/AuthInfoInput.js +1 -0
  25. package/lib/src/generated/rest/BroadcastRequest.d.ts +6 -0
  26. package/lib/src/generated/rest/BroadcastRequest.js +1 -0
  27. package/lib/src/generated/rest/CapabilityInput.d.ts +5 -0
  28. package/lib/src/generated/rest/CapabilityInput.js +1 -0
  29. package/lib/src/generated/rest/CommitBatchRequest.d.ts +3 -0
  30. package/lib/src/generated/rest/CommitBatchRequest.js +2 -0
  31. package/lib/src/generated/rest/ComputeLogEntry.d.ts +9 -0
  32. package/lib/src/generated/rest/ComputeLogEntry.js +2 -0
  33. package/lib/src/generated/rest/CreateExpressionRequest.d.ts +4 -0
  34. package/lib/src/generated/rest/CreateExpressionRequest.js +2 -0
  35. package/lib/src/generated/rest/CreatePerspectiveRequest.d.ts +3 -0
  36. package/lib/src/generated/rest/CreatePerspectiveRequest.js +2 -0
  37. package/lib/src/generated/rest/CreateSubjectRequest.d.ts +6 -0
  38. package/lib/src/generated/rest/CreateSubjectRequest.js +2 -0
  39. package/lib/src/generated/rest/CreateUserRequest.d.ts +4 -0
  40. package/lib/src/generated/rest/CreateUserRequest.js +2 -0
  41. package/lib/src/generated/rest/CreateUserResponse.d.ts +5 -0
  42. package/lib/src/generated/rest/CreateUserResponse.js +2 -0
  43. package/lib/src/generated/rest/DecoratedExpressionProof.d.ts +6 -0
  44. package/lib/src/generated/rest/DecoratedExpressionProof.js +2 -0
  45. package/lib/src/generated/rest/DecoratedLinkExpression.d.ts +10 -0
  46. package/lib/src/generated/rest/DecoratedLinkExpression.js +1 -0
  47. package/lib/src/generated/rest/DisposeQueryRequest.d.ts +3 -0
  48. package/lib/src/generated/rest/DisposeQueryRequest.js +2 -0
  49. package/lib/src/generated/rest/EmailTestRequest.d.ts +6 -0
  50. package/lib/src/generated/rest/EmailTestRequest.js +2 -0
  51. package/lib/src/generated/rest/EmbedRequest.d.ts +4 -0
  52. package/lib/src/generated/rest/EmbedRequest.js +2 -0
  53. package/lib/src/generated/rest/EntanglementProofInput.d.ts +6 -0
  54. package/lib/src/generated/rest/EntanglementProofInput.js +2 -0
  55. package/lib/src/generated/rest/EntanglementProofPreflightRequest.d.ts +4 -0
  56. package/lib/src/generated/rest/EntanglementProofPreflightRequest.js +2 -0
  57. package/lib/src/generated/rest/ExecuteCommandsRequest.d.ts +4 -0
  58. package/lib/src/generated/rest/ExecuteCommandsRequest.js +2 -0
  59. package/lib/src/generated/rest/ExportRequest.d.ts +5 -0
  60. package/lib/src/generated/rest/ExportRequest.js +2 -0
  61. package/lib/src/generated/rest/ExpressionManyRequest.d.ts +3 -0
  62. package/lib/src/generated/rest/ExpressionManyRequest.js +2 -0
  63. package/lib/src/generated/rest/ExpressionProof.d.ts +4 -0
  64. package/lib/src/generated/rest/ExpressionProof.js +2 -0
  65. package/lib/src/generated/rest/ExpressionProofInput.d.ts +6 -0
  66. package/lib/src/generated/rest/ExpressionProofInput.js +2 -0
  67. package/lib/src/generated/rest/FriendSendMessageRequest.d.ts +3 -0
  68. package/lib/src/generated/rest/FriendSendMessageRequest.js +2 -0
  69. package/lib/src/generated/rest/FriendsListRequest.d.ts +3 -0
  70. package/lib/src/generated/rest/FriendsListRequest.js +2 -0
  71. package/lib/src/generated/rest/GenerateAgentRequest.d.ts +3 -0
  72. package/lib/src/generated/rest/GenerateAgentRequest.js +2 -0
  73. package/lib/src/generated/rest/GenerateJwtRequest.d.ts +4 -0
  74. package/lib/src/generated/rest/GenerateJwtRequest.js +2 -0
  75. package/lib/src/generated/rest/GetSubjectDataRequest.d.ts +4 -0
  76. package/lib/src/generated/rest/GetSubjectDataRequest.js +2 -0
  77. package/lib/src/generated/rest/HostingInfoResponse.d.ts +5 -0
  78. package/lib/src/generated/rest/HostingInfoResponse.js +2 -0
  79. package/lib/src/generated/rest/HostingWalletResponse.d.ts +4 -0
  80. package/lib/src/generated/rest/HostingWalletResponse.js +2 -0
  81. package/lib/src/generated/rest/ImportAgentRequest.d.ts +6 -0
  82. package/lib/src/generated/rest/ImportAgentRequest.js +2 -0
  83. package/lib/src/generated/rest/ImportRequest.d.ts +4 -0
  84. package/lib/src/generated/rest/ImportRequest.js +2 -0
  85. package/lib/src/generated/rest/JoinNeighbourhoodRequest.d.ts +3 -0
  86. package/lib/src/generated/rest/JoinNeighbourhoodRequest.js +2 -0
  87. package/lib/src/generated/rest/KeepAliveQueryRequest.d.ts +3 -0
  88. package/lib/src/generated/rest/KeepAliveQueryRequest.js +2 -0
  89. package/lib/src/generated/rest/LanguageMetaInput.d.ts +6 -0
  90. package/lib/src/generated/rest/LanguageMetaInput.js +2 -0
  91. package/lib/src/generated/rest/Link.d.ts +5 -0
  92. package/lib/src/generated/rest/Link.js +2 -0
  93. package/lib/src/generated/rest/LinkExpression.d.ts +10 -0
  94. package/lib/src/generated/rest/LinkExpression.js +1 -0
  95. package/lib/src/generated/rest/LinkExpressionInput.d.ts +10 -0
  96. package/lib/src/generated/rest/LinkExpressionInput.js +1 -0
  97. package/lib/src/generated/rest/LinkInput.d.ts +5 -0
  98. package/lib/src/generated/rest/LinkInput.js +2 -0
  99. package/lib/src/generated/rest/LinkLanguageTemplatesRequest.d.ts +3 -0
  100. package/lib/src/generated/rest/LinkLanguageTemplatesRequest.js +2 -0
  101. package/lib/src/generated/rest/LinkMutationRequest.d.ts +12 -0
  102. package/lib/src/generated/rest/LinkMutationRequest.js +1 -0
  103. package/lib/src/generated/rest/LinkMutationResponse.d.ts +9 -0
  104. package/lib/src/generated/rest/LinkMutationResponse.js +1 -0
  105. package/lib/src/generated/rest/LinkMutations.d.ts +6 -0
  106. package/lib/src/generated/rest/LinkMutations.js +1 -0
  107. package/lib/src/generated/rest/LinkMutationsRequest.d.ts +5 -0
  108. package/lib/src/generated/rest/LinkMutationsRequest.js +1 -0
  109. package/lib/src/generated/rest/LinkStatus.d.ts +1 -0
  110. package/lib/src/generated/rest/LinkStatus.js +2 -0
  111. package/lib/src/generated/rest/LinkUpdateInput.d.ts +5 -0
  112. package/lib/src/generated/rest/LinkUpdateInput.js +1 -0
  113. package/lib/src/generated/rest/LockAgentRequest.d.ts +3 -0
  114. package/lib/src/generated/rest/LockAgentRequest.js +2 -0
  115. package/lib/src/generated/rest/LoginUserRequest.d.ts +5 -0
  116. package/lib/src/generated/rest/LoginUserRequest.js +2 -0
  117. package/lib/src/generated/rest/ModelType.d.ts +1 -0
  118. package/lib/src/generated/rest/ModelType.js +2 -0
  119. package/lib/src/generated/rest/NotificationGrantRequest.d.ts +3 -0
  120. package/lib/src/generated/rest/NotificationGrantRequest.js +2 -0
  121. package/lib/src/generated/rest/NotificationInput.d.ts +10 -0
  122. package/lib/src/generated/rest/NotificationInput.js +2 -0
  123. package/lib/src/generated/rest/OpenLinkRequest.d.ts +3 -0
  124. package/lib/src/generated/rest/OpenLinkRequest.js +2 -0
  125. package/lib/src/generated/rest/PermitCapabilityRequest.d.ts +3 -0
  126. package/lib/src/generated/rest/PermitCapabilityRequest.js +2 -0
  127. package/lib/src/generated/rest/PerspectiveInput.d.ts +4 -0
  128. package/lib/src/generated/rest/PerspectiveInput.js +1 -0
  129. package/lib/src/generated/rest/PromptRequest.d.ts +4 -0
  130. package/lib/src/generated/rest/PromptRequest.js +2 -0
  131. package/lib/src/generated/rest/PublicPerspectiveInput.d.ts +4 -0
  132. package/lib/src/generated/rest/PublicPerspectiveInput.js +1 -0
  133. package/lib/src/generated/rest/PublishLanguageRequest.d.ts +5 -0
  134. package/lib/src/generated/rest/PublishLanguageRequest.js +1 -0
  135. package/lib/src/generated/rest/PublishNeighbourhoodRequest.d.ts +6 -0
  136. package/lib/src/generated/rest/PublishNeighbourhoodRequest.js +1 -0
  137. package/lib/src/generated/rest/QueryRequest.d.ts +7 -0
  138. package/lib/src/generated/rest/QueryRequest.js +2 -0
  139. package/lib/src/generated/rest/RemoveLinkRequest.d.ts +5 -0
  140. package/lib/src/generated/rest/RemoveLinkRequest.js +1 -0
  141. package/lib/src/generated/rest/RemoveLinksBulkRequest.d.ts +5 -0
  142. package/lib/src/generated/rest/RemoveLinksBulkRequest.js +1 -0
  143. package/lib/src/generated/rest/RequestCapabilityRequest.d.ts +4 -0
  144. package/lib/src/generated/rest/RequestCapabilityRequest.js +1 -0
  145. package/lib/src/generated/rest/RequestPaymentRequest.d.ts +3 -0
  146. package/lib/src/generated/rest/RequestPaymentRequest.js +2 -0
  147. package/lib/src/generated/rest/RequestVerificationRequest.d.ts +4 -0
  148. package/lib/src/generated/rest/RequestVerificationRequest.js +2 -0
  149. package/lib/src/generated/rest/ResourceInput.d.ts +4 -0
  150. package/lib/src/generated/rest/ResourceInput.js +2 -0
  151. package/lib/src/generated/rest/SetDefaultModelRequest.d.ts +4 -0
  152. package/lib/src/generated/rest/SetDefaultModelRequest.js +1 -0
  153. package/lib/src/generated/rest/SetFreeHostingEnabledRequest.d.ts +3 -0
  154. package/lib/src/generated/rest/SetFreeHostingEnabledRequest.js +2 -0
  155. package/lib/src/generated/rest/SetHotWalletAddressRequest.d.ts +3 -0
  156. package/lib/src/generated/rest/SetHotWalletAddressRequest.js +2 -0
  157. package/lib/src/generated/rest/SetMultiUserRequest.d.ts +3 -0
  158. package/lib/src/generated/rest/SetMultiUserRequest.js +2 -0
  159. package/lib/src/generated/rest/SetOnlineStatusRequest.d.ts +5 -0
  160. package/lib/src/generated/rest/SetOnlineStatusRequest.js +1 -0
  161. package/lib/src/generated/rest/SetStatusRequest.d.ts +3 -0
  162. package/lib/src/generated/rest/SetStatusRequest.js +2 -0
  163. package/lib/src/generated/rest/SetUserFreeAccessRequest.d.ts +4 -0
  164. package/lib/src/generated/rest/SetUserFreeAccessRequest.js +2 -0
  165. package/lib/src/generated/rest/SignMessageRequest.d.ts +3 -0
  166. package/lib/src/generated/rest/SignMessageRequest.js +2 -0
  167. package/lib/src/generated/rest/SignalRequest.d.ts +6 -0
  168. package/lib/src/generated/rest/SignalRequest.js +1 -0
  169. package/lib/src/generated/rest/SubscribeQueryRequest.d.ts +3 -0
  170. package/lib/src/generated/rest/SubscribeQueryRequest.js +2 -0
  171. package/lib/src/generated/rest/SubscribeQueryResponse.d.ts +4 -0
  172. package/lib/src/generated/rest/SubscribeQueryResponse.js +2 -0
  173. package/lib/src/generated/rest/TrustedAgentsRequest.d.ts +3 -0
  174. package/lib/src/generated/rest/TrustedAgentsRequest.js +2 -0
  175. package/lib/src/generated/rest/UnlockAgentRequest.d.ts +4 -0
  176. package/lib/src/generated/rest/UnlockAgentRequest.js +2 -0
  177. package/lib/src/generated/rest/UpdateLinkRequest.d.ts +7 -0
  178. package/lib/src/generated/rest/UpdateLinkRequest.js +1 -0
  179. package/lib/src/generated/rest/UpdatePerspectiveRequest.d.ts +3 -0
  180. package/lib/src/generated/rest/UpdatePerspectiveRequest.js +2 -0
  181. package/lib/src/generated/rest/UpdateProfileRequest.d.ts +5 -0
  182. package/lib/src/generated/rest/UpdateProfileRequest.js +1 -0
  183. package/lib/src/generated/rest/UserStatistics.d.ts +9 -0
  184. package/lib/src/generated/rest/UserStatistics.js +2 -0
  185. package/lib/src/generated/rest/VerificationRequestResult.d.ts +6 -0
  186. package/lib/src/generated/rest/VerificationRequestResult.js +2 -0
  187. package/lib/src/generated/rest/VerifyEmailRequest.d.ts +6 -0
  188. package/lib/src/generated/rest/VerifyEmailRequest.js +2 -0
  189. package/lib/src/generated/rest/VerifySignatureRequest.d.ts +5 -0
  190. package/lib/src/generated/rest/VerifySignatureRequest.js +2 -0
  191. package/lib/src/generated/rest/WriteSettingsRequest.d.ts +3 -0
  192. package/lib/src/generated/rest/WriteSettingsRequest.js +2 -0
  193. package/lib/src/generated/rest/index.d.ts +73 -0
  194. package/lib/src/generated/rest/index.js +8 -0
  195. package/lib/src/generated/rest/routes.d.ts +587 -0
  196. package/lib/src/generated/rest/routes.js +3 -0
  197. package/lib/src/index.d.ts +4 -0
  198. package/lib/src/index.js +4 -0
  199. package/lib/src/model/Ad4mModel.d.ts +30 -36
  200. package/lib/src/model/Ad4mModel.js +93 -382
  201. package/lib/src/model/Ad4mModel.test.js +735 -480
  202. package/lib/src/model/ModelQueryBuilder.d.ts +5 -10
  203. package/lib/src/model/ModelQueryBuilder.js +142 -62
  204. package/lib/src/model/decorators.d.ts +7 -4
  205. package/lib/src/model/decorators.js +0 -7
  206. package/lib/src/model/query-sparql.d.ts +0 -10
  207. package/lib/src/model/query-sparql.js +10 -15
  208. package/lib/src/model/query-sparql.test.js +10 -92
  209. package/lib/src/model/query-surreal.d.ts +44 -0
  210. package/lib/src/model/query-surreal.js +249 -0
  211. package/lib/src/model/shacl-gen.js +120 -47
  212. package/lib/src/model/surreal-utils.d.ts +42 -0
  213. package/lib/src/model/surreal-utils.js +128 -0
  214. package/lib/src/model/types.d.ts +140 -4
  215. package/lib/src/neighbourhood/NeighbourhoodProxy.test.js +33 -33
  216. package/lib/src/perspectives/PerspectiveClient.d.ts +13 -4
  217. package/lib/src/perspectives/PerspectiveClient.js +22 -6
  218. package/lib/src/perspectives/PerspectiveProxy.d.ts +27 -7
  219. package/lib/src/perspectives/PerspectiveProxy.js +60 -12
  220. package/lib/src/perspectives/PerspectiveProxy.test.d.ts +1 -0
  221. package/lib/src/perspectives/PerspectiveProxy.test.js +34 -0
  222. package/lib/src/perspectives/SparqlBindings.d.ts +47 -0
  223. package/lib/src/perspectives/SparqlBindings.js +65 -0
  224. package/lib/src/perspectives/WakerSubscriptionManager.js +5 -4
  225. package/lib/src/restClient.d.ts +52 -0
  226. package/lib/src/restClient.js +227 -0
  227. package/lib/src/shacl/NodeExpression.d.ts +44 -0
  228. package/lib/src/shacl/NodeExpression.js +39 -0
  229. package/lib/src/shacl/SHACLShape.d.ts +23 -0
  230. package/lib/src/shacl/SHACLShape.js +115 -1
  231. package/lib/src/shacl/SHACLShape.test.js +0 -82
  232. package/lib/src/shacl/builders.d.ts +58 -0
  233. package/lib/src/shacl/builders.js +76 -0
  234. package/lib/src/shacl/index.d.ts +36 -0
  235. package/lib/src/shacl/index.js +33 -0
  236. package/package.json +11 -8
  237. package/src/Ad4mClient.ts +7 -2
  238. package/src/agent/AgentClient.ts +23 -0
  239. package/src/ai/AIClient.ts +1 -1
  240. package/src/apiClient.ts +17 -6
  241. package/src/index.ts +4 -0
  242. package/src/model/Ad4mModel.test.ts +274 -72
  243. package/src/model/Ad4mModel.ts +140 -420
  244. package/src/model/ModelQueryBuilder.ts +136 -71
  245. package/src/model/decorators.ts +7 -13
  246. package/src/model/query-sparql.test.ts +35 -19
  247. package/src/model/query-sparql.ts +10 -16
  248. package/src/model/relation-filtering.test.ts +46 -39
  249. package/src/model/shacl-gen.ts +128 -54
  250. package/src/model/shacl-roundtrip.test.ts +197 -0
  251. package/src/model/types-typed-query.test.ts +360 -0
  252. package/src/model/types.ts +196 -4
  253. package/src/perspectives/PerspectiveClient.ts +24 -8
  254. package/src/perspectives/PerspectiveProxy.test.ts +85 -1
  255. package/src/perspectives/PerspectiveProxy.ts +65 -20
  256. package/src/perspectives/SparqlBindings.ts +79 -0
  257. package/src/perspectives/WakerSubscriptionManager.ts +5 -4
  258. package/src/shacl/NodeExpression.ts +54 -0
  259. package/src/shacl/SHACLShape.test.ts +172 -0
  260. package/src/shacl/SHACLShape.ts +173 -1
  261. package/src/shacl/builders.ts +86 -0
  262. package/src/shacl/index.ts +72 -0
  263. package/lib/src/model/model-manifest.d.ts +0 -41
  264. package/lib/src/model/model-manifest.js +0 -11
@@ -6,7 +6,7 @@
6
6
  */
7
7
  import type { Ad4mModel } from "./Ad4mModel";
8
8
  import type { PerspectiveProxy } from "../perspectives/PerspectiveProxy";
9
- import type { Where, Order, IncludeMap, Query, PaginationResult } from "./types";
9
+ import type { Query, PaginationResult, TypedWhere, TypedOrder, TypedIncludeMap, PropertyKeysOf } from "./types";
10
10
  /** Query builder for Ad4mModel queries.
11
11
  * Allows building queries with a fluent interface and either running them once
12
12
  * or subscribing to updates.
@@ -63,7 +63,7 @@ export declare class ModelQueryBuilder<T extends Ad4mModel> {
63
63
  * })
64
64
  * ```
65
65
  */
66
- where(conditions: Where): ModelQueryBuilder<T>;
66
+ where(conditions: TypedWhere<T>): ModelQueryBuilder<T>;
67
67
  /**
68
68
  * Sets the order for the query results.
69
69
  *
@@ -75,7 +75,7 @@ export declare class ModelQueryBuilder<T extends Ad4mModel> {
75
75
  * .order({ createdAt: "DESC" })
76
76
  * ```
77
77
  */
78
- order(orderBy: Order): ModelQueryBuilder<T>;
78
+ order(orderBy: TypedOrder<T>): ModelQueryBuilder<T>;
79
79
  /**
80
80
  * Sets the maximum number of results to return.
81
81
  *
@@ -156,7 +156,7 @@ export declare class ModelQueryBuilder<T extends Ad4mModel> {
156
156
  * .properties(["name", "description", "rating"])
157
157
  * ```
158
158
  */
159
- properties(properties: string[]): ModelQueryBuilder<T>;
159
+ properties(properties: PropertyKeysOf<T>[] | string[]): ModelQueryBuilder<T>;
160
160
  /**
161
161
  * Controls whether SPARQL property getters are evaluated during hydration.
162
162
  *
@@ -202,13 +202,8 @@ export declare class ModelQueryBuilder<T extends Ad4mModel> {
202
202
  * .run();
203
203
  * ```
204
204
  */
205
- include(map: IncludeMap): ModelQueryBuilder<T>;
205
+ include(map: TypedIncludeMap<T>): ModelQueryBuilder<T>;
206
206
  overrideModelClassName(className: string): ModelQueryBuilder<T>;
207
- /**
208
- * Sets the query engine to use.
209
- * @deprecated Prolog engine has been removed. All queries use SPARQL/Rust.
210
- */
211
- engine(_eng: 'sparql' | 'prolog'): ModelQueryBuilder<T>;
212
207
  /**
213
208
  * Executes the query once and returns the results.
214
209
  *
@@ -256,13 +256,6 @@ export class ModelQueryBuilder {
256
256
  this.modelClassName = className;
257
257
  return this;
258
258
  }
259
- /**
260
- * Sets the query engine to use.
261
- * @deprecated Prolog engine has been removed. All queries use SPARQL/Rust.
262
- */
263
- engine(_eng) {
264
- return this;
265
- }
266
259
  /**
267
260
  * Executes the query once and returns the results.
268
261
  *
@@ -306,8 +299,10 @@ export class ModelQueryBuilder {
306
299
  * ```
307
300
  */
308
301
  async first() {
302
+ const savedLimit = this.queryParams.limit;
309
303
  this.queryParams.limit = 1;
310
304
  const results = await this.get();
305
+ this.queryParams.limit = savedLimit;
311
306
  return results[0] ?? null;
312
307
  }
313
308
  /**
@@ -342,23 +337,18 @@ export class ModelQueryBuilder {
342
337
  // Clean up any existing subscription
343
338
  this.dispose();
344
339
  const ctor = this.ctor;
345
- // Build the model query params (className, queryJson, shapeJson)
346
- const { className, queryJson, shapeJson } = ctor.prepareModelQueryParams(this.queryParams, this.modelClassName);
340
+ // Build the model query params (className, queryJson). The executor
341
+ // resolves the shape from the perspective's SHACL triples.
342
+ const { className, queryJson } = ctor.prepareModelQueryParams(this.queryParams, this.modelClassName);
347
343
  // Register model subscription via Rust — this builds trigger SPARQL internally,
348
344
  // registers the subscription, and runs the initial query in one call.
349
- const { subscriptionId, result: initialModelResult } = await this.perspective.modelSubscribe(className, queryJson, shapeJson);
345
+ const { subscriptionId, result: initialModelResult } = await this.perspective.modelSubscribe(className, queryJson);
350
346
  // Convert JSON instances to model class instances
351
347
  const parseResults = (raw) => {
352
348
  return ctor.parseModelResult(this.perspective, raw, this.queryParams.include, this.queryParams.properties);
353
349
  };
354
- // Resolve non-literal (file-language) properties — handles both raw URI strings
355
- // and already-resolved FileData objects returned by the Rust executor.
356
- const resolveAndReturn = async (instances) => {
357
- await ctor.resolveNonLiteralProps(this.perspective, instances);
358
- return instances;
359
- };
360
- // Parse initial results (with non-literal resolution)
361
- const initialResults = await resolveAndReturn(parseResults(initialModelResult));
350
+ // Transforms are now applied by the Rust executor during hydration
351
+ const initialResults = parseResults(initialModelResult);
362
352
  // Track last emitted result fingerprint to suppress duplicate callbacks
363
353
  let lastResultFingerprint = null;
364
354
  const buildFingerprint = (results) => {
@@ -371,34 +361,65 @@ export class ModelQueryBuilder {
371
361
  // When Rust re-runs the model query and finds changed results, it pushes them.
372
362
  const unsubscribe = this.perspective.client.subscribeToQueryUpdates(subscriptionId, (rawResult) => {
373
363
  try {
374
- resolveAndReturn(parseResults(rawResult)).then((results) => {
375
- const fp = buildFingerprint(results);
376
- if (fp === lastResultFingerprint)
377
- return;
378
- lastResultFingerprint = fp;
379
- callback(results);
380
- }).catch((e) => {
381
- console.error('Model subscription update resolve error:', e);
382
- });
364
+ const results = parseResults(rawResult);
365
+ console.debug(`[ModelQueryBuilder.subscribe] Update received for ${subscriptionId}: ${results.length} instances`);
366
+ const fp = buildFingerprint(results);
367
+ if (fp === lastResultFingerprint) {
368
+ console.debug(`[ModelQueryBuilder.subscribe] Fingerprint unchanged, skipping callback`);
369
+ return;
370
+ }
371
+ console.debug(`[ModelQueryBuilder.subscribe] Fingerprint changed, calling callback with ${results.length} results`);
372
+ lastResultFingerprint = fp;
373
+ callback(results);
383
374
  }
384
375
  catch (e) {
385
376
  console.error('Model subscription update parse error:', e);
386
377
  }
387
378
  });
388
- // Set up keepalive with failure tracking
389
- let keepaliveFailures = 0;
390
- const keepaliveTimer = setInterval(() => {
391
- this.perspective.client.keepAliveQuery(this.perspective.uuid, subscriptionId).then(() => {
392
- keepaliveFailures = 0;
393
- }).catch((e) => {
394
- keepaliveFailures++;
395
- console.warn(`Model subscription keepalive failed (attempt ${keepaliveFailures}) for ${subscriptionId}:`, e);
396
- });
397
- }, 30000);
379
+ // Set up keepalive with recovery — uses setTimeout loop so we can
380
+ // break out and resubscribe when the server evicts the subscription.
381
+ let disposed = false;
382
+ let keepaliveTimer;
383
+ let resubscribeAttempts = 0;
384
+ const MAX_RESUBSCRIBE_ATTEMPTS = 5;
385
+ const keepaliveLoop = async () => {
386
+ if (disposed)
387
+ return;
388
+ try {
389
+ await this.perspective.client.keepAliveQuery(this.perspective.uuid, subscriptionId);
390
+ resubscribeAttempts = 0; // Reset on success
391
+ }
392
+ catch (e) {
393
+ console.warn(`Model subscription keepalive failed for ${subscriptionId}:`, e);
394
+ if (!disposed && resubscribeAttempts < MAX_RESUBSCRIBE_ATTEMPTS) {
395
+ resubscribeAttempts++;
396
+ const backoffMs = Math.min(1000 * Math.pow(2, resubscribeAttempts), 60000);
397
+ console.warn(`Resubscribing (attempt ${resubscribeAttempts}/${MAX_RESUBSCRIBE_ATTEMPTS}, backoff ${backoffMs}ms)...`);
398
+ await new Promise(r => setTimeout(r, backoffMs));
399
+ try {
400
+ unsubscribe();
401
+ await this.subscribe(callback);
402
+ }
403
+ catch (resubErr) {
404
+ console.error('Model subscription resubscribe failed:', resubErr);
405
+ }
406
+ }
407
+ else if (resubscribeAttempts >= MAX_RESUBSCRIBE_ATTEMPTS) {
408
+ console.error(`Model subscription ${subscriptionId}: max resubscribe attempts reached, giving up.`);
409
+ }
410
+ return; // new subscription owns its own keepalive loop
411
+ }
412
+ if (!disposed) {
413
+ keepaliveTimer = setTimeout(keepaliveLoop, 30000);
414
+ }
415
+ };
416
+ keepaliveTimer = setTimeout(keepaliveLoop, 30000);
398
417
  // Store dispose function
399
418
  this.currentSubscription = {
400
419
  dispose: () => {
401
- clearInterval(keepaliveTimer);
420
+ disposed = true;
421
+ if (keepaliveTimer)
422
+ clearTimeout(keepaliveTimer);
402
423
  unsubscribe();
403
424
  this.perspective.client.disposeQuerySubscription(this.perspective.uuid, subscriptionId).catch(() => { });
404
425
  },
@@ -471,8 +492,8 @@ export class ModelQueryBuilder {
471
492
  // Clean up any existing subscription
472
493
  this.dispose();
473
494
  const countParams = { ...this.queryParams, limit: 0 };
474
- const { className, queryJson, shapeJson } = this.ctor.prepareModelQueryParams(countParams, this.modelClassName);
475
- const { subscriptionId, result: initialModelResult } = await this.perspective.modelSubscribe(className, queryJson, shapeJson);
495
+ const { className, queryJson } = this.ctor.prepareModelQueryParams(countParams, this.modelClassName);
496
+ const { subscriptionId, result: initialModelResult } = await this.perspective.modelSubscribe(className, queryJson);
476
497
  const parseCount = (raw) => {
477
498
  const data = typeof raw === 'string' ? JSON.parse(raw) : raw;
478
499
  return data.totalCount ?? 0;
@@ -486,18 +507,47 @@ export class ModelQueryBuilder {
486
507
  console.error('Count subscription update parse error:', e);
487
508
  }
488
509
  });
489
- let keepaliveFailures = 0;
490
- const keepaliveTimer = setInterval(() => {
491
- this.perspective.client.keepAliveQuery(this.perspective.uuid, subscriptionId).then(() => {
492
- keepaliveFailures = 0;
493
- }).catch((e) => {
494
- keepaliveFailures++;
495
- console.warn(`Count subscription keepalive failed (attempt ${keepaliveFailures}) for ${subscriptionId}:`, e);
496
- });
497
- }, 30000);
510
+ let disposed = false;
511
+ let keepaliveTimer;
512
+ let resubscribeAttempts = 0;
513
+ const MAX_RESUBSCRIBE_ATTEMPTS = 5;
514
+ const keepaliveLoop = async () => {
515
+ if (disposed)
516
+ return;
517
+ try {
518
+ await this.perspective.client.keepAliveQuery(this.perspective.uuid, subscriptionId);
519
+ resubscribeAttempts = 0;
520
+ }
521
+ catch (e) {
522
+ console.warn(`Count subscription keepalive failed for ${subscriptionId}:`, e);
523
+ if (!disposed && resubscribeAttempts < MAX_RESUBSCRIBE_ATTEMPTS) {
524
+ resubscribeAttempts++;
525
+ const backoffMs = Math.min(1000 * Math.pow(2, resubscribeAttempts), 60000);
526
+ console.warn(`Count resubscribing (attempt ${resubscribeAttempts}/${MAX_RESUBSCRIBE_ATTEMPTS}, backoff ${backoffMs}ms)...`);
527
+ await new Promise(r => setTimeout(r, backoffMs));
528
+ try {
529
+ unsubscribe();
530
+ await this.countSubscribe(callback);
531
+ }
532
+ catch (resubErr) {
533
+ console.error('Count subscription resubscribe failed:', resubErr);
534
+ }
535
+ }
536
+ else if (resubscribeAttempts >= MAX_RESUBSCRIBE_ATTEMPTS) {
537
+ console.error(`Count subscription ${subscriptionId}: max resubscribe attempts reached, giving up.`);
538
+ }
539
+ return;
540
+ }
541
+ if (!disposed) {
542
+ keepaliveTimer = setTimeout(keepaliveLoop, 30000);
543
+ }
544
+ };
545
+ keepaliveTimer = setTimeout(keepaliveLoop, 30000);
498
546
  this.currentSubscription = {
499
547
  dispose: () => {
500
- clearInterval(keepaliveTimer);
548
+ disposed = true;
549
+ if (keepaliveTimer)
550
+ clearTimeout(keepaliveTimer);
501
551
  unsubscribe();
502
552
  this.perspective.client.disposeQuerySubscription(this.perspective.uuid, subscriptionId).catch(() => { });
503
553
  },
@@ -578,8 +628,8 @@ export class ModelQueryBuilder {
578
628
  const subscriptionParams = { ...(this.queryParams || {}) };
579
629
  delete subscriptionParams.limit;
580
630
  delete subscriptionParams.offset;
581
- const { className, queryJson, shapeJson } = ctor.prepareModelQueryParams(subscriptionParams, this.modelClassName);
582
- const { subscriptionId } = await this.perspective.modelSubscribe(className, queryJson, shapeJson);
631
+ const { className, queryJson } = ctor.prepareModelQueryParams(subscriptionParams, this.modelClassName);
632
+ const { subscriptionId } = await this.perspective.modelSubscribe(className, queryJson);
583
633
  // Build the paginated query for Rust endpoint (count: true fetches both results and totalCount in one call)
584
634
  const paginatedQuery = {
585
635
  ...(this.queryParams || {}),
@@ -592,20 +642,50 @@ export class ModelQueryBuilder {
592
642
  callback({ results, totalCount, pageSize, pageNumber });
593
643
  };
594
644
  const unsubscribe = this.perspective.client.subscribeToQueryUpdates(subscriptionId, (rawResult) => {
645
+ console.debug(`[ModelQueryBuilder.paginateSubscribe] Update received for ${subscriptionId}, re-fetching paginated data...`);
595
646
  processResults().catch(e => console.error('Paginate subscription error:', e));
596
647
  });
597
- let keepaliveFailures = 0;
598
- const keepaliveTimer = setInterval(() => {
599
- this.perspective.client.keepAliveQuery(this.perspective.uuid, subscriptionId).then(() => {
600
- keepaliveFailures = 0;
601
- }).catch((e) => {
602
- keepaliveFailures++;
603
- console.warn(`Paginate subscription keepalive failed (attempt ${keepaliveFailures}) for ${subscriptionId}:`, e);
604
- });
605
- }, 30000);
648
+ let disposed = false;
649
+ let keepaliveTimer;
650
+ let resubscribeAttempts = 0;
651
+ const MAX_RESUBSCRIBE_ATTEMPTS = 5;
652
+ const keepaliveLoop = async () => {
653
+ if (disposed)
654
+ return;
655
+ try {
656
+ await this.perspective.client.keepAliveQuery(this.perspective.uuid, subscriptionId);
657
+ resubscribeAttempts = 0;
658
+ }
659
+ catch (e) {
660
+ console.warn(`Paginate subscription keepalive failed for ${subscriptionId}:`, e);
661
+ if (!disposed && resubscribeAttempts < MAX_RESUBSCRIBE_ATTEMPTS) {
662
+ resubscribeAttempts++;
663
+ const backoffMs = Math.min(1000 * Math.pow(2, resubscribeAttempts), 60000);
664
+ console.warn(`Paginate resubscribing (attempt ${resubscribeAttempts}/${MAX_RESUBSCRIBE_ATTEMPTS}, backoff ${backoffMs}ms)...`);
665
+ await new Promise(r => setTimeout(r, backoffMs));
666
+ try {
667
+ unsubscribe();
668
+ await this.paginateSubscribe(pageSize, pageNumber, callback);
669
+ }
670
+ catch (resubErr) {
671
+ console.error('Paginate subscription resubscribe failed:', resubErr);
672
+ }
673
+ }
674
+ else if (resubscribeAttempts >= MAX_RESUBSCRIBE_ATTEMPTS) {
675
+ console.error(`Paginate subscription ${subscriptionId}: max resubscribe attempts reached, giving up.`);
676
+ }
677
+ return;
678
+ }
679
+ if (!disposed) {
680
+ keepaliveTimer = setTimeout(keepaliveLoop, 30000);
681
+ }
682
+ };
683
+ keepaliveTimer = setTimeout(keepaliveLoop, 30000);
606
684
  this.currentSubscription = {
607
685
  dispose: () => {
608
- clearInterval(keepaliveTimer);
686
+ disposed = true;
687
+ if (keepaliveTimer)
688
+ clearTimeout(keepaliveTimer);
609
689
  unsubscribe();
610
690
  this.perspective.client.disposeQuerySubscription(this.perspective.uuid, subscriptionId).catch(() => { });
611
691
  },
@@ -130,11 +130,14 @@ export interface PropertyOptions {
130
130
  */
131
131
  local?: boolean;
132
132
  /**
133
- * Optional transform function to modify the property value after it is retrieved.
134
- * This is useful for transforming raw data into a more usable format.
135
- * The function takes the raw value as input and returns the transformed value.
133
+ * Optional transform expression to modify the property value.
134
+ * This is a SHACL-AF Node Expression that runs in the Rust model query engine.
135
+ * Examples: `fileToDataUri`, `concat(literal('prefix_'), focus())`, etc.
136
+ * Builders (`focus`, `literal`, `path`, `exists`, `ifExpr`, `concat`,
137
+ * `coalesce`, `fn`) and the `fileToDataUri` built-in are exported from
138
+ * the package root: `import { concat, literal, focus } from '@coasys/ad4m'`.
136
139
  */
137
- transform?: (value: any) => any;
140
+ transform?: import('../shacl/NodeExpression').NodeExpression;
138
141
  /**
139
142
  * Allowed values for this property (enum constraint).
140
143
  * Maps to SHACL `sh:in`. Each entry has a `value` (the stored RDF term)
@@ -521,15 +521,8 @@ function resolveRelationArgs(first, second) {
521
521
  return opts;
522
522
  }
523
523
  export function HasMany(first, second) {
524
- const explicitThrough = typeof first === 'function' ? second?.through : first.through;
525
524
  const opts = resolveRelationArgs(first, second);
526
525
  return function (target, key) {
527
- if (!explicitThrough && !opts.getter) {
528
- const className = (target.constructor?.name) ?? 'unknown';
529
- console.warn(`@HasMany on ${className}.${String(key)} has no 'through' predicate — defaulting to 'ad4m://has_child'. ` +
530
- `Add { through: 'ad4m://has_child' } to silence this warning, or use a semantic predicate ` +
531
- `like { through: 'myns://has_${String(key)}' } for efficient targeted queries.`);
532
- }
533
526
  // --- relation registry ---
534
527
  const ctor = target.constructor;
535
528
  if (!relationRegistry.has(ctor))
@@ -38,16 +38,6 @@ export declare function formatSPARQLValue(value: any): string;
38
38
  * with named graph storage and metadata keyed by graph IRI.
39
39
  */
40
40
  export declare function buildSPARQLQuery(metadata: ModelMetadata, allRelationsMetadata: Record<string, RelationMetadataEntry>, query: Query, modelClass: any): string;
41
- /**
42
- * Build ORDER BY / LIMIT / OFFSET clauses for the SPARQL query.
43
- *
44
- * NOTE: The outer SELECT returns multiple rows per instance (one per link),
45
- * so LIMIT/OFFSET at the outer level would cut off links mid-instance.
46
- * This function is kept for backward compatibility and always returns "".
47
- * SPARQL-level pagination is handled via a subquery in buildSPARQLQuery
48
- * using buildPaginationSubquery().
49
- */
50
- export declare function buildSPARQLOrderLimitOffset(_metadata: ModelMetadata, query: Query): string;
51
41
  /**
52
42
  * Build an inner subquery that selects DISTINCT ?source URIs with
53
43
  * ORDER BY, LIMIT, and OFFSET applied at the instance level.
@@ -109,7 +109,9 @@ function escapeSPARQL(value) {
109
109
  .replace(/"/g, '\\"')
110
110
  .replace(/\n/g, "\\n")
111
111
  .replace(/\r/g, "\\r")
112
- .replace(/\t/g, "\\t");
112
+ .replace(/\t/g, "\\t")
113
+ .replace(/\0/g, "")
114
+ .replace(/\f/g, "\\u000C");
113
115
  }
114
116
  /**
115
117
  * Format a value as a SPARQL string literal (double-quoted).
@@ -124,8 +126,14 @@ export function formatSPARQLValue(value) {
124
126
  * Format an AD4M URI as an RDF IRI for use in SPARQL triple patterns.
125
127
  * All AD4M link source/predicate/target values become IRIs in angle brackets.
126
128
  * The Rust SPARQL service transparently transforms these to valid IRI format.
129
+ *
130
+ * Rejects characters that would break or inject into a SPARQL IRI token,
131
+ * matching the Rust-side `validate_iri()` function.
127
132
  */
128
133
  function iri(value) {
134
+ if (/[<>{}" ]/.test(value)) {
135
+ throw new Error(`Invalid IRI component: '${value}'`);
136
+ }
129
137
  return `<${value}>`;
130
138
  }
131
139
  /**
@@ -271,21 +279,8 @@ export function buildSPARQLQuery(metadata, allRelationsMetadata, query, modelCla
271
279
  ?_reifier <ad4m://ontology/timestamp> ?timestamp .
272
280
  ${filterClause}
273
281
  }
274
- ${buildSPARQLOrderLimitOffset(metadata, query)}
275
282
  `.trim();
276
283
  }
277
- /**
278
- * Build ORDER BY / LIMIT / OFFSET clauses for the SPARQL query.
279
- *
280
- * NOTE: The outer SELECT returns multiple rows per instance (one per link),
281
- * so LIMIT/OFFSET at the outer level would cut off links mid-instance.
282
- * This function is kept for backward compatibility and always returns "".
283
- * SPARQL-level pagination is handled via a subquery in buildSPARQLQuery
284
- * using buildPaginationSubquery().
285
- */
286
- export function buildSPARQLOrderLimitOffset(_metadata, query) {
287
- return "";
288
- }
289
284
  /**
290
285
  * Build an inner subquery that selects DISTINCT ?source URIs with
291
286
  * ORDER BY, LIMIT, and OFFSET applied at the instance level.
@@ -332,7 +327,7 @@ export function buildPaginationSubquery(joinPatterns, filterExpressions, metadat
332
327
  { SELECT DISTINCT ?source${tsSelect} WHERE {${innerJoin}${orderJoinPatterns.join('')}${tsPattern}
333
328
  FILTER(isIRI(?source))
334
329
  ${innerFilter}
335
- } GROUP BY ?source ${orderByClause} ${limitClause} ${offsetClause} }\n`;
330
+ } ${orderByClause} ${limitClause} ${offsetClause} }\n`;
336
331
  }
337
332
  /**
338
333
  * Build SPARQL FILTER expressions from user `where` conditions.
@@ -53,28 +53,26 @@ describe('hasJsOnlyWhereFilters', () => {
53
53
  expect(hasJsOnlyWhereFilters(meta, relMeta, { parent: 'some://id' })).toBe(true);
54
54
  });
55
55
  });
56
- describe('buildSPARQLQuery — SPARQL-level pagination via subquery', () => {
56
+ describe('buildSPARQLQuery — pagination handled in JS, not SPARQL', () => {
57
57
  const modelClass = {};
58
- it('includes LIMIT/OFFSET in a pagination subquery when query has them and no JS-only filters', () => {
58
+ it('does NOT include LIMIT/OFFSET in SPARQL even when query has them', () => {
59
59
  const query = { limit: 10, offset: 0, where: { category: 'some://uri' } };
60
60
  const sparql = buildSPARQLQuery(richMetadata, emptyRelations, query, modelClass);
61
- // SPARQL should contain LIMIT inside the pagination subquery
62
- expect(sparql).toContain('LIMIT 10');
61
+ // SPARQL should NOT contain LIMIT/OFFSET — pagination is done in JS
62
+ expect(sparql).not.toContain('LIMIT');
63
+ expect(sparql).not.toContain('OFFSET');
63
64
  // The outer query should still exist
64
65
  expect(sparql).toContain('SELECT ?source ?predicate ?target');
65
- // Should have a subquery pattern
66
- expect(sparql).toContain('SELECT DISTINCT ?source');
67
66
  });
68
- it('does NOT include LIMIT/OFFSET when JS-only where filters exist', () => {
69
- // author is a JS-only filter
70
- const query = { limit: 10, offset: 0, where: { author: 'did:key:abc' } };
67
+ it('does NOT include LIMIT/OFFSET even with JS-only where filters', () => {
68
+ const query = { limit: 10, offset: 0, where: { name: 'Pasta' } };
71
69
  const sparql = buildSPARQLQuery(richMetadata, emptyRelations, query, modelClass);
72
70
  expect(sparql).not.toContain('LIMIT');
73
71
  expect(sparql).not.toContain('OFFSET');
74
72
  });
75
73
  });
76
74
  describe('buildSPARQLOrderLimitOffset', () => {
77
- it('always returns empty string (pagination uses subquery pattern instead)', () => {
75
+ it('always returns empty string (pagination is handled in JS)', () => {
78
76
  expect(buildSPARQLOrderLimitOffset(emptyMetadata, {})).toBe('');
79
77
  expect(buildSPARQLOrderLimitOffset(emptyMetadata, { limit: 50 })).toBe('');
80
78
  expect(buildSPARQLOrderLimitOffset(emptyMetadata, { limit: 50, offset: 100 })).toBe('');
@@ -134,9 +132,8 @@ describe('buildSPARQLQuery — structural correctness', () => {
134
132
  };
135
133
  const sparql = buildSPARQLQuery(richMetadata, emptyRelations, query, modelClass);
136
134
  expect(sparql).toContain('<flux://channel-123>');
137
- // SPARQL-level pagination via subquery
138
- expect(sparql).toContain('LIMIT 50');
139
- expect(sparql).toContain('SELECT DISTINCT ?source');
135
+ // No SPARQL-level pagination
136
+ expect(sparql).not.toContain('LIMIT');
140
137
  });
141
138
  it('does not allow injection through where clause IRI values', () => {
142
139
  const query = {
@@ -211,67 +208,6 @@ describe('buildSPARQLQuery — IRI correctness', () => {
211
208
  expect(sparql).not.toContain('fn::parse_literal');
212
209
  });
213
210
  });
214
- // ──────────────────────────────────────────────────────────
215
- // SPARQL-level pagination (LIMIT/OFFSET in generated queries)
216
- // ──────────────────────────────────────────────────────────
217
- describe('SPARQL-level pagination', () => {
218
- const modelClass = {};
219
- it('includes LIMIT in SPARQL when query specifies limit', () => {
220
- const query = { limit: 30 };
221
- const sparql = buildSPARQLQuery(emptyMetadata, emptyRelations, query, modelClass);
222
- expect(sparql).toContain('LIMIT 30');
223
- expect(sparql).toContain('SELECT DISTINCT ?source');
224
- });
225
- it('includes OFFSET in SPARQL when query specifies offset > 0', () => {
226
- const query = { limit: 20, offset: 40 };
227
- const sparql = buildSPARQLQuery(emptyMetadata, emptyRelations, query, modelClass);
228
- expect(sparql).toContain('LIMIT 20');
229
- expect(sparql).toContain('OFFSET 40');
230
- });
231
- it('does NOT include OFFSET when offset is 0', () => {
232
- const query = { limit: 10, offset: 0 };
233
- const sparql = buildSPARQLQuery(emptyMetadata, emptyRelations, query, modelClass);
234
- expect(sparql).toContain('LIMIT 10');
235
- expect(sparql).not.toContain('OFFSET');
236
- });
237
- it('includes ORDER BY in subquery when query.order is specified', () => {
238
- const query = { limit: 10, order: { name: 'DESC' } };
239
- const sparql = buildSPARQLQuery(richMetadata, emptyRelations, query, modelClass);
240
- expect(sparql).toContain('ORDER BY DESC(');
241
- expect(sparql).toContain('LIMIT 10');
242
- });
243
- it('does NOT default to ORDER BY timestamp when paginating without explicit order', () => {
244
- const query = { limit: 30 };
245
- const sparql = buildSPARQLQuery(emptyMetadata, emptyRelations, query, modelClass);
246
- expect(sparql).not.toContain('ORDER BY');
247
- expect(sparql).not.toContain('pg_minTs');
248
- });
249
- it('does NOT push pagination to SPARQL when JS-only where filters exist (author)', () => {
250
- const query = { limit: 10, where: { author: 'did:key:abc' } };
251
- const sparql = buildSPARQLQuery(emptyMetadata, emptyRelations, query, modelClass);
252
- expect(sparql).not.toContain('LIMIT');
253
- expect(sparql).not.toContain('OFFSET');
254
- });
255
- it('does NOT push pagination to SPARQL when JS-only where filters exist (gt operator)', () => {
256
- const meta = {
257
- properties: {
258
- rating: { name: 'rating', predicate: 'flux://rating', required: true, resolveLanguage: 'literal' },
259
- },
260
- relations: {},
261
- };
262
- const query = { limit: 10, where: { rating: { gt: 5 } } };
263
- const sparql = buildSPARQLQuery(meta, emptyRelations, query, modelClass);
264
- expect(sparql).not.toContain('LIMIT');
265
- });
266
- it('wraps pagination in a subquery (outer SELECT fetches all links for the page)', () => {
267
- const query = { limit: 5, offset: 10 };
268
- const sparql = buildSPARQLQuery(emptyMetadata, emptyRelations, query, modelClass);
269
- expect(sparql).toContain('SELECT ?source ?predicate ?target ?author ?timestamp');
270
- expect(sparql).toContain('SELECT DISTINCT ?source');
271
- expect(sparql).toContain('LIMIT 5');
272
- expect(sparql).toContain('OFFSET 10');
273
- });
274
- });
275
211
  describe('buildSPARQLQuery — set-difference patterns', () => {
276
212
  const modelClass = {};
277
213
  // Subgroups are grandchildren of channels (channel → conversation → subgroup).
@@ -292,21 +228,3 @@ describe('buildSPARQLQuery — set-difference patterns', () => {
292
228
  expect(sparql).toContain('SELECT ?source ?predicate ?target');
293
229
  });
294
230
  });
295
- describe('buildSPARQLQuery — RDF 1.2 reifier patterns', () => {
296
- const modelClass = {};
297
- it('uses rdf:reifies instead of GRAPH for link metadata', () => {
298
- const query = { limit: 10 };
299
- const sparql = buildSPARQLQuery(richMetadata, emptyRelations, query, modelClass);
300
- expect(sparql).toContain('<http://www.w3.org/1999/02/22-rdf-syntax-ns#reifies>');
301
- expect(sparql).toContain('<http://www.w3.org/1999/02/22-rdf-syntax-ns#reifies> <<(');
302
- expect(sparql).toContain('?_reifier');
303
- expect(sparql).not.toContain('GRAPH');
304
- expect(sparql).not.toContain('?linkGraph');
305
- });
306
- it('binds author and timestamp on the reifier node', () => {
307
- const query = {};
308
- const sparql = buildSPARQLQuery(richMetadata, emptyRelations, query, modelClass);
309
- expect(sparql).toContain('?_reifier <ad4m://ontology/author> ?author');
310
- expect(sparql).toContain('?_reifier <ad4m://ontology/timestamp> ?timestamp');
311
- });
312
- });
@@ -0,0 +1,44 @@
1
+ /**
2
+ * SurrealQL query building utilities for Ad4mModel.
3
+ *
4
+ * Contains the graph-traversal WHERE clause builder, legacy
5
+ * subquery-based clause builders, SELECT-field builders, and
6
+ * the main `buildSurrealQLQuery()` function that produces a
7
+ * complete SurrealQL query string from a `Query` object.
8
+ *
9
+ * All functions are stateless — model metadata and relation metadata
10
+ * are passed in as parameters instead of accessed via `this`.
11
+ *
12
+ * @module
13
+ */
14
+ import type { RelationMetadataEntry } from "./decorators";
15
+ import type { Where, Query, ModelMetadata } from "./types";
16
+ /**
17
+ * Builds WHERE clause filters using SurrealDB graph traversal syntax.
18
+ *
19
+ * Translates where conditions into `->link[WHERE ...]` / `<-link[WHERE ...]`
20
+ * filters that SurrealDB can optimize via graph indexes.
21
+ *
22
+ * @param metadata - Model metadata from `getModelMetadata()`
23
+ * @param allRelationsMetadata - Full relation metadata (needed for belongs-to
24
+ * direction detection)
25
+ * @param where - User-supplied where conditions
26
+ * @returns Combined AND-joined condition string, or empty string
27
+ */
28
+ export declare function buildGraphTraversalWhereClause(metadata: ModelMetadata, allRelationsMetadata: Record<string, RelationMetadataEntry>, where?: Where): string;
29
+ /**
30
+ * Builds a complete SurrealQL query from a Query object and model metadata.
31
+ *
32
+ * This is the core implementation behind `Ad4mModel.queryToSurrealQL()`.
33
+ * It produces a graph-traversal query that:
34
+ * 1. Filters nodes by required predicates (conformance check)
35
+ * 2. Applies user WHERE conditions
36
+ * 3. Fetches all outgoing links for hydration
37
+ *
38
+ * @param metadata - Model metadata from `getModelMetadata()`
39
+ * @param allRelationsMetadata - Full relation registry (for belongs-to detection)
40
+ * @param query - Query parameters
41
+ * @param modelClass - The model class (for `resolveParentPredicate`)
42
+ * @returns Complete SurrealQL query string
43
+ */
44
+ export declare function buildSurrealQLQuery(metadata: ModelMetadata, allRelationsMetadata: Record<string, RelationMetadataEntry>, query: Query, modelClass: any): string;