@coasys/ad4m 0.13.0-test-8-profile-cache-fix → 0.13.0-test-9

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 (221) hide show
  1. package/lib/index.cjs +136 -18
  2. package/lib/index.js +136 -18
  3. package/lib/src/generated/rest/AIModelLoadingStatus.d.ts +7 -0
  4. package/lib/src/generated/rest/AIModelLoadingStatus.js +2 -0
  5. package/lib/src/generated/rest/AddAgentInfosRequest.d.ts +3 -0
  6. package/lib/src/generated/rest/AddAgentInfosRequest.js +2 -0
  7. package/lib/src/generated/rest/AddLinkExpressionRequest.d.ts +6 -0
  8. package/lib/src/generated/rest/AddLinkExpressionRequest.js +1 -0
  9. package/lib/src/generated/rest/AddLinkRequest.d.ts +6 -0
  10. package/lib/src/generated/rest/AddLinkRequest.js +1 -0
  11. package/lib/src/generated/rest/AddLinksBulkRequest.d.ts +6 -0
  12. package/lib/src/generated/rest/AddLinksBulkRequest.js +1 -0
  13. package/lib/src/generated/rest/AddSdnaRequest.d.ts +6 -0
  14. package/lib/src/generated/rest/AddSdnaRequest.js +2 -0
  15. package/lib/src/generated/rest/ApplyTemplateRequest.d.ts +4 -0
  16. package/lib/src/generated/rest/ApplyTemplateRequest.js +2 -0
  17. package/lib/src/generated/rest/AuthInfoInput.d.ts +10 -0
  18. package/lib/src/generated/rest/AuthInfoInput.js +1 -0
  19. package/lib/src/generated/rest/BroadcastRequest.d.ts +6 -0
  20. package/lib/src/generated/rest/BroadcastRequest.js +1 -0
  21. package/lib/src/generated/rest/CapabilityInput.d.ts +5 -0
  22. package/lib/src/generated/rest/CapabilityInput.js +1 -0
  23. package/lib/src/generated/rest/CommitBatchRequest.d.ts +3 -0
  24. package/lib/src/generated/rest/CommitBatchRequest.js +2 -0
  25. package/lib/src/generated/rest/ComputeLogEntry.d.ts +9 -0
  26. package/lib/src/generated/rest/ComputeLogEntry.js +2 -0
  27. package/lib/src/generated/rest/CreateExpressionRequest.d.ts +4 -0
  28. package/lib/src/generated/rest/CreateExpressionRequest.js +2 -0
  29. package/lib/src/generated/rest/CreatePerspectiveRequest.d.ts +3 -0
  30. package/lib/src/generated/rest/CreatePerspectiveRequest.js +2 -0
  31. package/lib/src/generated/rest/CreateSubjectRequest.d.ts +6 -0
  32. package/lib/src/generated/rest/CreateSubjectRequest.js +2 -0
  33. package/lib/src/generated/rest/CreateUserRequest.d.ts +4 -0
  34. package/lib/src/generated/rest/CreateUserRequest.js +2 -0
  35. package/lib/src/generated/rest/CreateUserResponse.d.ts +5 -0
  36. package/lib/src/generated/rest/CreateUserResponse.js +2 -0
  37. package/lib/src/generated/rest/DecoratedExpressionProof.d.ts +6 -0
  38. package/lib/src/generated/rest/DecoratedExpressionProof.js +2 -0
  39. package/lib/src/generated/rest/DecoratedLinkExpression.d.ts +10 -0
  40. package/lib/src/generated/rest/DecoratedLinkExpression.js +1 -0
  41. package/lib/src/generated/rest/DisposeQueryRequest.d.ts +3 -0
  42. package/lib/src/generated/rest/DisposeQueryRequest.js +2 -0
  43. package/lib/src/generated/rest/EmailTestRequest.d.ts +6 -0
  44. package/lib/src/generated/rest/EmailTestRequest.js +2 -0
  45. package/lib/src/generated/rest/EmbedRequest.d.ts +4 -0
  46. package/lib/src/generated/rest/EmbedRequest.js +2 -0
  47. package/lib/src/generated/rest/EntanglementProofInput.d.ts +6 -0
  48. package/lib/src/generated/rest/EntanglementProofInput.js +2 -0
  49. package/lib/src/generated/rest/EntanglementProofPreflightRequest.d.ts +4 -0
  50. package/lib/src/generated/rest/EntanglementProofPreflightRequest.js +2 -0
  51. package/lib/src/generated/rest/ExecuteCommandsRequest.d.ts +4 -0
  52. package/lib/src/generated/rest/ExecuteCommandsRequest.js +2 -0
  53. package/lib/src/generated/rest/ExportRequest.d.ts +5 -0
  54. package/lib/src/generated/rest/ExportRequest.js +2 -0
  55. package/lib/src/generated/rest/ExpressionManyRequest.d.ts +3 -0
  56. package/lib/src/generated/rest/ExpressionManyRequest.js +2 -0
  57. package/lib/src/generated/rest/ExpressionProof.d.ts +4 -0
  58. package/lib/src/generated/rest/ExpressionProof.js +2 -0
  59. package/lib/src/generated/rest/ExpressionProofInput.d.ts +6 -0
  60. package/lib/src/generated/rest/ExpressionProofInput.js +2 -0
  61. package/lib/src/generated/rest/FriendSendMessageRequest.d.ts +3 -0
  62. package/lib/src/generated/rest/FriendSendMessageRequest.js +2 -0
  63. package/lib/src/generated/rest/FriendsListRequest.d.ts +3 -0
  64. package/lib/src/generated/rest/FriendsListRequest.js +2 -0
  65. package/lib/src/generated/rest/GenerateAgentRequest.d.ts +3 -0
  66. package/lib/src/generated/rest/GenerateAgentRequest.js +2 -0
  67. package/lib/src/generated/rest/GenerateJwtRequest.d.ts +4 -0
  68. package/lib/src/generated/rest/GenerateJwtRequest.js +2 -0
  69. package/lib/src/generated/rest/GetSubjectDataRequest.d.ts +4 -0
  70. package/lib/src/generated/rest/GetSubjectDataRequest.js +2 -0
  71. package/lib/src/generated/rest/HostingInfoResponse.d.ts +5 -0
  72. package/lib/src/generated/rest/HostingInfoResponse.js +2 -0
  73. package/lib/src/generated/rest/HostingWalletResponse.d.ts +4 -0
  74. package/lib/src/generated/rest/HostingWalletResponse.js +2 -0
  75. package/lib/src/generated/rest/ImportAgentRequest.d.ts +6 -0
  76. package/lib/src/generated/rest/ImportAgentRequest.js +2 -0
  77. package/lib/src/generated/rest/ImportRequest.d.ts +4 -0
  78. package/lib/src/generated/rest/ImportRequest.js +2 -0
  79. package/lib/src/generated/rest/JoinNeighbourhoodRequest.d.ts +3 -0
  80. package/lib/src/generated/rest/JoinNeighbourhoodRequest.js +2 -0
  81. package/lib/src/generated/rest/KeepAliveQueryRequest.d.ts +3 -0
  82. package/lib/src/generated/rest/KeepAliveQueryRequest.js +2 -0
  83. package/lib/src/generated/rest/LanguageMetaInput.d.ts +6 -0
  84. package/lib/src/generated/rest/LanguageMetaInput.js +2 -0
  85. package/lib/src/generated/rest/Link.d.ts +5 -0
  86. package/lib/src/generated/rest/Link.js +2 -0
  87. package/lib/src/generated/rest/LinkExpression.d.ts +10 -0
  88. package/lib/src/generated/rest/LinkExpression.js +1 -0
  89. package/lib/src/generated/rest/LinkExpressionInput.d.ts +10 -0
  90. package/lib/src/generated/rest/LinkExpressionInput.js +1 -0
  91. package/lib/src/generated/rest/LinkInput.d.ts +5 -0
  92. package/lib/src/generated/rest/LinkInput.js +2 -0
  93. package/lib/src/generated/rest/LinkLanguageTemplatesRequest.d.ts +3 -0
  94. package/lib/src/generated/rest/LinkLanguageTemplatesRequest.js +2 -0
  95. package/lib/src/generated/rest/LinkMutationRequest.d.ts +12 -0
  96. package/lib/src/generated/rest/LinkMutationRequest.js +1 -0
  97. package/lib/src/generated/rest/LinkMutationResponse.d.ts +9 -0
  98. package/lib/src/generated/rest/LinkMutationResponse.js +1 -0
  99. package/lib/src/generated/rest/LinkMutations.d.ts +6 -0
  100. package/lib/src/generated/rest/LinkMutations.js +1 -0
  101. package/lib/src/generated/rest/LinkMutationsRequest.d.ts +5 -0
  102. package/lib/src/generated/rest/LinkMutationsRequest.js +1 -0
  103. package/lib/src/generated/rest/LinkStatus.d.ts +1 -0
  104. package/lib/src/generated/rest/LinkStatus.js +2 -0
  105. package/lib/src/generated/rest/LinkUpdateInput.d.ts +5 -0
  106. package/lib/src/generated/rest/LinkUpdateInput.js +1 -0
  107. package/lib/src/generated/rest/LockAgentRequest.d.ts +3 -0
  108. package/lib/src/generated/rest/LockAgentRequest.js +2 -0
  109. package/lib/src/generated/rest/LoginUserRequest.d.ts +5 -0
  110. package/lib/src/generated/rest/LoginUserRequest.js +2 -0
  111. package/lib/src/generated/rest/ModelType.d.ts +1 -0
  112. package/lib/src/generated/rest/ModelType.js +2 -0
  113. package/lib/src/generated/rest/NotificationGrantRequest.d.ts +3 -0
  114. package/lib/src/generated/rest/NotificationGrantRequest.js +2 -0
  115. package/lib/src/generated/rest/NotificationInput.d.ts +10 -0
  116. package/lib/src/generated/rest/NotificationInput.js +2 -0
  117. package/lib/src/generated/rest/OpenLinkRequest.d.ts +3 -0
  118. package/lib/src/generated/rest/OpenLinkRequest.js +2 -0
  119. package/lib/src/generated/rest/PermitCapabilityRequest.d.ts +3 -0
  120. package/lib/src/generated/rest/PermitCapabilityRequest.js +2 -0
  121. package/lib/src/generated/rest/PerspectiveInput.d.ts +4 -0
  122. package/lib/src/generated/rest/PerspectiveInput.js +1 -0
  123. package/lib/src/generated/rest/PromptRequest.d.ts +4 -0
  124. package/lib/src/generated/rest/PromptRequest.js +2 -0
  125. package/lib/src/generated/rest/PublicPerspectiveInput.d.ts +4 -0
  126. package/lib/src/generated/rest/PublicPerspectiveInput.js +1 -0
  127. package/lib/src/generated/rest/PublishLanguageRequest.d.ts +5 -0
  128. package/lib/src/generated/rest/PublishLanguageRequest.js +1 -0
  129. package/lib/src/generated/rest/PublishNeighbourhoodRequest.d.ts +6 -0
  130. package/lib/src/generated/rest/PublishNeighbourhoodRequest.js +1 -0
  131. package/lib/src/generated/rest/QueryRequest.d.ts +7 -0
  132. package/lib/src/generated/rest/QueryRequest.js +2 -0
  133. package/lib/src/generated/rest/RemoveLinkRequest.d.ts +5 -0
  134. package/lib/src/generated/rest/RemoveLinkRequest.js +1 -0
  135. package/lib/src/generated/rest/RemoveLinksBulkRequest.d.ts +5 -0
  136. package/lib/src/generated/rest/RemoveLinksBulkRequest.js +1 -0
  137. package/lib/src/generated/rest/RequestCapabilityRequest.d.ts +4 -0
  138. package/lib/src/generated/rest/RequestCapabilityRequest.js +1 -0
  139. package/lib/src/generated/rest/RequestPaymentRequest.d.ts +3 -0
  140. package/lib/src/generated/rest/RequestPaymentRequest.js +2 -0
  141. package/lib/src/generated/rest/RequestVerificationRequest.d.ts +4 -0
  142. package/lib/src/generated/rest/RequestVerificationRequest.js +2 -0
  143. package/lib/src/generated/rest/ResourceInput.d.ts +4 -0
  144. package/lib/src/generated/rest/ResourceInput.js +2 -0
  145. package/lib/src/generated/rest/SetDefaultModelRequest.d.ts +4 -0
  146. package/lib/src/generated/rest/SetDefaultModelRequest.js +1 -0
  147. package/lib/src/generated/rest/SetFreeHostingEnabledRequest.d.ts +3 -0
  148. package/lib/src/generated/rest/SetFreeHostingEnabledRequest.js +2 -0
  149. package/lib/src/generated/rest/SetHotWalletAddressRequest.d.ts +3 -0
  150. package/lib/src/generated/rest/SetHotWalletAddressRequest.js +2 -0
  151. package/lib/src/generated/rest/SetMultiUserRequest.d.ts +3 -0
  152. package/lib/src/generated/rest/SetMultiUserRequest.js +2 -0
  153. package/lib/src/generated/rest/SetOnlineStatusRequest.d.ts +5 -0
  154. package/lib/src/generated/rest/SetOnlineStatusRequest.js +1 -0
  155. package/lib/src/generated/rest/SetStatusRequest.d.ts +3 -0
  156. package/lib/src/generated/rest/SetStatusRequest.js +2 -0
  157. package/lib/src/generated/rest/SetUserFreeAccessRequest.d.ts +4 -0
  158. package/lib/src/generated/rest/SetUserFreeAccessRequest.js +2 -0
  159. package/lib/src/generated/rest/SignMessageRequest.d.ts +3 -0
  160. package/lib/src/generated/rest/SignMessageRequest.js +2 -0
  161. package/lib/src/generated/rest/SignalRequest.d.ts +6 -0
  162. package/lib/src/generated/rest/SignalRequest.js +1 -0
  163. package/lib/src/generated/rest/SubscribeQueryRequest.d.ts +3 -0
  164. package/lib/src/generated/rest/SubscribeQueryRequest.js +2 -0
  165. package/lib/src/generated/rest/SubscribeQueryResponse.d.ts +4 -0
  166. package/lib/src/generated/rest/SubscribeQueryResponse.js +2 -0
  167. package/lib/src/generated/rest/TrustedAgentsRequest.d.ts +3 -0
  168. package/lib/src/generated/rest/TrustedAgentsRequest.js +2 -0
  169. package/lib/src/generated/rest/UnlockAgentRequest.d.ts +4 -0
  170. package/lib/src/generated/rest/UnlockAgentRequest.js +2 -0
  171. package/lib/src/generated/rest/UpdateLinkRequest.d.ts +7 -0
  172. package/lib/src/generated/rest/UpdateLinkRequest.js +1 -0
  173. package/lib/src/generated/rest/UpdatePerspectiveRequest.d.ts +3 -0
  174. package/lib/src/generated/rest/UpdatePerspectiveRequest.js +2 -0
  175. package/lib/src/generated/rest/UpdateProfileRequest.d.ts +5 -0
  176. package/lib/src/generated/rest/UpdateProfileRequest.js +1 -0
  177. package/lib/src/generated/rest/UserStatistics.d.ts +9 -0
  178. package/lib/src/generated/rest/UserStatistics.js +2 -0
  179. package/lib/src/generated/rest/VerificationRequestResult.d.ts +6 -0
  180. package/lib/src/generated/rest/VerificationRequestResult.js +2 -0
  181. package/lib/src/generated/rest/VerifyEmailRequest.d.ts +6 -0
  182. package/lib/src/generated/rest/VerifyEmailRequest.js +2 -0
  183. package/lib/src/generated/rest/VerifySignatureRequest.d.ts +5 -0
  184. package/lib/src/generated/rest/VerifySignatureRequest.js +2 -0
  185. package/lib/src/generated/rest/WriteSettingsRequest.d.ts +3 -0
  186. package/lib/src/generated/rest/WriteSettingsRequest.js +2 -0
  187. package/lib/src/generated/rest/index.d.ts +73 -0
  188. package/lib/src/generated/rest/index.js +8 -0
  189. package/lib/src/generated/rest/routes.d.ts +587 -0
  190. package/lib/src/generated/rest/routes.js +3 -0
  191. package/lib/src/model/Ad4mModel.test.js +735 -480
  192. package/lib/src/model/decorators.d.ts +20 -1
  193. package/lib/src/model/decorators.js +33 -2
  194. package/lib/src/model/query-sparql.d.ts +1 -0
  195. package/lib/src/model/query-sparql.js +13 -0
  196. package/lib/src/model/query-sparql.test.js +10 -92
  197. package/lib/src/model/query-surreal.d.ts +44 -0
  198. package/lib/src/model/query-surreal.js +249 -0
  199. package/lib/src/model/shacl-gen.d.ts +15 -1
  200. package/lib/src/model/shacl-gen.js +23 -1
  201. package/lib/src/model/surreal-utils.d.ts +42 -0
  202. package/lib/src/model/surreal-utils.js +128 -0
  203. package/lib/src/model/types.d.ts +14 -3
  204. package/lib/src/neighbourhood/NeighbourhoodProxy.test.js +33 -33
  205. package/lib/src/perspectives/PerspectiveProxy.d.ts +17 -0
  206. package/lib/src/perspectives/PerspectiveProxy.js +67 -15
  207. package/lib/src/perspectives/PerspectiveProxy.test.d.ts +1 -0
  208. package/lib/src/perspectives/PerspectiveProxy.test.js +34 -0
  209. package/lib/src/restClient.d.ts +52 -0
  210. package/lib/src/restClient.js +227 -0
  211. package/lib/src/shacl/SHACLShape.test.js +0 -82
  212. package/package.json +11 -8
  213. package/src/model/Ad4mModel.test.ts +103 -0
  214. package/src/model/decorators.ts +37 -3
  215. package/src/model/query-sparql.test.ts +148 -0
  216. package/src/model/query-sparql.ts +15 -0
  217. package/src/model/shacl-gen.ts +23 -0
  218. package/src/model/types.ts +28 -6
  219. package/src/perspectives/PerspectiveProxy.ts +73 -20
  220. package/lib/src/model/model-manifest.d.ts +0 -41
  221. package/lib/src/model/model-manifest.js +0 -11
@@ -50,8 +50,27 @@ export declare function getPropertiesMetadata(ctor: Function): Record<string, Pr
50
50
  export declare function getRelationsMetadata(ctor: Function): Record<string, RelationMetadataEntry>;
51
51
  /**
52
52
  * Get or compute memoised SHACL for a class. Used by @Model decorator.
53
+ *
54
+ * The `compute` callback receives a `seed(partial)` function: calling
55
+ * it stores `partial` in the cache *before* `compute` returns, so any
56
+ * re-entrant `getMemoizedSHACL(target, …)` call from inside `compute`
57
+ * observes the in-progress shape instead of re-entering `compute`
58
+ * infinitely.
59
+ *
60
+ * This matters for self-referential models — e.g.
61
+ *
62
+ * @Model({ name: "Channel" })
63
+ * class Channel extends Ad4mModel {
64
+ * @HasMany({ predicate: "…/child", target: () => Channel })
65
+ * childChannels!: Channel[];
66
+ * }
67
+ *
68
+ * Without the seed, building the SHACL shape for `Channel` invokes
69
+ * `Channel.generateSHACL()` while walking the `childChannels`
70
+ * relation's target (shacl-gen.ts ~line 327), which re-enters this
71
+ * function with an empty cache, blowing the stack.
53
72
  */
54
- export declare function getMemoizedSHACL(target: Function, compute: () => any): any;
73
+ export declare function getMemoizedSHACL(target: Function, compute: (seed: (partial: any) => void) => any): any;
55
74
  /**
56
75
  * Programmatically register property metadata for a given constructor.
57
76
  * Used by `fromJSONSchema()` and other dynamic model builders.
@@ -62,12 +62,43 @@ export function getRelationsMetadata(ctor) {
62
62
  }
63
63
  /**
64
64
  * Get or compute memoised SHACL for a class. Used by @Model decorator.
65
+ *
66
+ * The `compute` callback receives a `seed(partial)` function: calling
67
+ * it stores `partial` in the cache *before* `compute` returns, so any
68
+ * re-entrant `getMemoizedSHACL(target, …)` call from inside `compute`
69
+ * observes the in-progress shape instead of re-entering `compute`
70
+ * infinitely.
71
+ *
72
+ * This matters for self-referential models — e.g.
73
+ *
74
+ * @Model({ name: "Channel" })
75
+ * class Channel extends Ad4mModel {
76
+ * @HasMany({ predicate: "…/child", target: () => Channel })
77
+ * childChannels!: Channel[];
78
+ * }
79
+ *
80
+ * Without the seed, building the SHACL shape for `Channel` invokes
81
+ * `Channel.generateSHACL()` while walking the `childChannels`
82
+ * relation's target (shacl-gen.ts ~line 327), which re-enters this
83
+ * function with an empty cache, blowing the stack.
65
84
  */
66
85
  export function getMemoizedSHACL(target, compute) {
67
86
  const cached = shaclCache.get(target);
68
87
  if (cached)
69
88
  return cached;
70
- const result = compute();
89
+ const seed = (partial) => {
90
+ shaclCache.set(target, partial);
91
+ };
92
+ let result;
93
+ try {
94
+ result = compute(seed);
95
+ }
96
+ catch (e) {
97
+ // If compute throws after seeding, evict the half-built entry
98
+ // so a later retry can rebuild from scratch.
99
+ shaclCache.delete(target);
100
+ throw e;
101
+ }
71
102
  shaclCache.set(target, result);
72
103
  return result;
73
104
  }
@@ -339,7 +370,7 @@ export function Model(opts) {
339
370
  return buildSDNA(opts.name, target.prototype, getPropertiesMetadata(target), getRelationsMetadata(target));
340
371
  };
341
372
  target.generateSHACL = function () {
342
- return getMemoizedSHACL(target, () => buildSHACL(opts.name, target, getPropertiesMetadata(target), getRelationsMetadata(target), buildConformanceFilter));
373
+ return getMemoizedSHACL(target, (seed) => buildSHACL(opts.name, target, getPropertiesMetadata(target), getRelationsMetadata(target), buildConformanceFilter, seed));
343
374
  };
344
375
  Object.defineProperty(target, 'type', { configurable: true });
345
376
  };
@@ -20,6 +20,7 @@ import type { Where, Query, ModelMetadata } from "./types";
20
20
  * - Literal-stored properties (equality, comparison, contains, etc.)
21
21
  * - Reverse relations (belongsToOne / belongsToMany)
22
22
  * - author / timestamp filters (skipped by buildSPARQLWhereFilters)
23
+ * - OR / AND / NOT combinators (skipped by buildSPARQLWhereFilters — see below)
23
24
  *
24
25
  * When JS-only filters exist, SPARQL-level LIMIT/OFFSET must NOT be applied
25
26
  * because the database would cap the candidate set before JS filters run,
@@ -20,6 +20,7 @@ import { resolveParentPredicate } from "./query-common";
20
20
  * - Literal-stored properties (equality, comparison, contains, etc.)
21
21
  * - Reverse relations (belongsToOne / belongsToMany)
22
22
  * - author / timestamp filters (skipped by buildSPARQLWhereFilters)
23
+ * - OR / AND / NOT combinators (skipped by buildSPARQLWhereFilters — see below)
23
24
  *
24
25
  * When JS-only filters exist, SPARQL-level LIMIT/OFFSET must NOT be applied
25
26
  * because the database would cap the candidate set before JS filters run,
@@ -31,6 +32,14 @@ export function hasJsOnlyWhereFilters(metadata, allRelationsMetadata, where) {
31
32
  for (const [propertyName, condition] of Object.entries(where)) {
32
33
  if (propertyName === "base" || propertyName === "id")
33
34
  continue;
35
+ // OR/AND/NOT: buildSPARQLWhereFilters never emits a SPARQL translation
36
+ // for these regardless of what their branches contain, so their mere
37
+ // presence — not just JS-only conditions within a branch — must block
38
+ // SPARQL-level pagination. Otherwise LIMIT/OFFSET would be applied
39
+ // before the (Rust-side, post-hydration) combinator filter ever runs.
40
+ if (propertyName === "OR" || propertyName === "AND" || propertyName === "NOT") {
41
+ return true;
42
+ }
34
43
  // author/timestamp filters are handled in JS
35
44
  if (propertyName === "author" || propertyName === "timestamp")
36
45
  return true;
@@ -339,6 +348,10 @@ function buildSPARQLWhereFilters(metadata, _allRelationsMetadata, where) {
339
348
  const joins = [];
340
349
  const filters = [];
341
350
  for (const [propertyName, condition] of Object.entries(where)) {
351
+ // OR/AND/NOT are evaluated Rust-side after hydration; no SPARQL emission needed.
352
+ if (propertyName === "OR" || propertyName === "AND" || propertyName === "NOT") {
353
+ continue;
354
+ }
342
355
  // 'base' maps to ?source
343
356
  if (propertyName === "base" || propertyName === "id") {
344
357
  if (Array.isArray(condition)) {
@@ -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;
@@ -0,0 +1,249 @@
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 { escapeSurrealString } from "../utils";
15
+ import { formatSurrealValue } from "./surreal-utils";
16
+ import { resolveParentPredicate } from "./query-common";
17
+ // ─── Graph Traversal WHERE Clause ────────────────────────────────────────────
18
+ /**
19
+ * Builds WHERE clause filters using SurrealDB graph traversal syntax.
20
+ *
21
+ * Translates where conditions into `->link[WHERE ...]` / `<-link[WHERE ...]`
22
+ * filters that SurrealDB can optimize via graph indexes.
23
+ *
24
+ * @param metadata - Model metadata from `getModelMetadata()`
25
+ * @param allRelationsMetadata - Full relation metadata (needed for belongs-to
26
+ * direction detection)
27
+ * @param where - User-supplied where conditions
28
+ * @returns Combined AND-joined condition string, or empty string
29
+ */
30
+ export function buildGraphTraversalWhereClause(metadata, allRelationsMetadata, where) {
31
+ if (!where)
32
+ return '';
33
+ const conditions = [];
34
+ for (const [propertyName, condition] of Object.entries(where)) {
35
+ const isSpecial = ['id', 'author', 'timestamp'].includes(propertyName);
36
+ if (isSpecial) {
37
+ if (propertyName === 'author' || propertyName === 'timestamp') {
38
+ continue; // Filtered post-query in JS
39
+ }
40
+ const columnName = 'uri';
41
+ if (Array.isArray(condition)) {
42
+ const formattedValues = condition.map(v => formatSurrealValue(v)).join(', ');
43
+ conditions.push(`${columnName} IN [${formattedValues}]`);
44
+ }
45
+ else if (typeof condition === 'object' && condition !== null) {
46
+ const ops = condition;
47
+ if (ops.not !== undefined) {
48
+ if (Array.isArray(ops.not)) {
49
+ const formattedValues = ops.not.map(v => formatSurrealValue(v)).join(', ');
50
+ conditions.push(`${columnName} NOT IN [${formattedValues}]`);
51
+ }
52
+ else {
53
+ conditions.push(`${columnName} != ${formatSurrealValue(ops.not)}`);
54
+ }
55
+ }
56
+ if (ops.between !== undefined && Array.isArray(ops.between) && ops.between.length === 2) {
57
+ conditions.push(`${columnName} >= ${formatSurrealValue(ops.between[0])} AND ${columnName} <= ${formatSurrealValue(ops.between[1])}`);
58
+ }
59
+ if (ops.gt !== undefined) {
60
+ conditions.push(`${columnName} > ${formatSurrealValue(ops.gt)}`);
61
+ }
62
+ if (ops.gte !== undefined) {
63
+ conditions.push(`${columnName} >= ${formatSurrealValue(ops.gte)}`);
64
+ }
65
+ if (ops.lt !== undefined) {
66
+ conditions.push(`${columnName} < ${formatSurrealValue(ops.lt)}`);
67
+ }
68
+ if (ops.lte !== undefined) {
69
+ conditions.push(`${columnName} <= ${formatSurrealValue(ops.lte)}`);
70
+ }
71
+ if (ops.contains !== undefined) {
72
+ conditions.push(`${columnName} CONTAINS ${formatSurrealValue(ops.contains)}`);
73
+ }
74
+ }
75
+ else {
76
+ conditions.push(`${columnName} = ${formatSurrealValue(condition)}`);
77
+ }
78
+ }
79
+ else {
80
+ // Regular properties — check relation metadata first for direction
81
+ const relMeta = allRelationsMetadata[propertyName];
82
+ const isBelongs = relMeta?.kind === 'belongsToOne' || relMeta?.kind === 'belongsToMany';
83
+ if (relMeta) {
84
+ const predicate = escapeSurrealString(relMeta.predicate);
85
+ if (Array.isArray(condition)) {
86
+ const formattedValues = condition.map(v => formatSurrealValue(v)).join(', ');
87
+ if (isBelongs) {
88
+ conditions.push(`count(<-link[WHERE predicate = '${predicate}' AND in.uri IN [${formattedValues}]]) > 0`);
89
+ }
90
+ else {
91
+ conditions.push(`count(->link[WHERE predicate = '${predicate}' AND out.uri IN [${formattedValues}]]) > 0`);
92
+ }
93
+ }
94
+ else if (typeof condition === 'object' && condition !== null) {
95
+ const ops = condition;
96
+ if (ops.not !== undefined) {
97
+ if (Array.isArray(ops.not)) {
98
+ const formattedValues = ops.not.map(v => formatSurrealValue(v)).join(', ');
99
+ if (isBelongs) {
100
+ conditions.push(`count(<-link[WHERE predicate = '${predicate}' AND in.uri IN [${formattedValues}]]) = 0`);
101
+ }
102
+ else {
103
+ conditions.push(`count(->link[WHERE predicate = '${predicate}' AND out.uri IN [${formattedValues}]]) = 0`);
104
+ }
105
+ }
106
+ else {
107
+ if (isBelongs) {
108
+ conditions.push(`count(<-link[WHERE predicate = '${predicate}' AND in.uri = ${formatSurrealValue(ops.not)}]) = 0`);
109
+ }
110
+ else {
111
+ conditions.push(`count(->link[WHERE predicate = '${predicate}' AND out.uri = ${formatSurrealValue(ops.not)}]) = 0`);
112
+ }
113
+ }
114
+ }
115
+ }
116
+ else {
117
+ if (isBelongs) {
118
+ conditions.push(`count(<-link[WHERE predicate = '${predicate}' AND in.uri = ${formatSurrealValue(condition)}]) > 0`);
119
+ }
120
+ else {
121
+ conditions.push(`count(->link[WHERE predicate = '${predicate}' AND out.uri = ${formatSurrealValue(condition)}]) > 0`);
122
+ }
123
+ }
124
+ continue;
125
+ }
126
+ const propMeta = metadata.properties[propertyName];
127
+ if (!propMeta)
128
+ continue;
129
+ const predicate = escapeSurrealString(propMeta.predicate);
130
+ const targetField = propMeta.resolveLanguage === 'literal' ? 'fn::parse_literal(out.uri)' : 'out.uri';
131
+ if (Array.isArray(condition)) {
132
+ const formattedValues = condition.map(v => formatSurrealValue(v)).join(', ');
133
+ conditions.push(`count(->link[WHERE predicate = '${predicate}' AND ${targetField} IN [${formattedValues}]]) > 0`);
134
+ }
135
+ else if (typeof condition === 'object' && condition !== null) {
136
+ const ops = condition;
137
+ if (ops.not !== undefined) {
138
+ if (Array.isArray(ops.not)) {
139
+ const formattedValues = ops.not.map(v => formatSurrealValue(v)).join(', ');
140
+ conditions.push(`count(->link[WHERE predicate = '${predicate}' AND ${targetField} IN [${formattedValues}]]) = 0`);
141
+ }
142
+ else {
143
+ conditions.push(`count(->link[WHERE predicate = '${predicate}' AND ${targetField} = ${formatSurrealValue(ops.not)}]) = 0`);
144
+ }
145
+ }
146
+ const hasComparisonOps = ops.gt !== undefined || ops.gte !== undefined ||
147
+ ops.lt !== undefined || ops.lte !== undefined ||
148
+ ops.between !== undefined || ops.contains !== undefined;
149
+ if (hasComparisonOps) {
150
+ conditions.push(`count(->link[WHERE predicate = '${predicate}']) > 0`);
151
+ }
152
+ }
153
+ else {
154
+ conditions.push(`count(->link[WHERE predicate = '${predicate}' AND ${targetField} = ${formatSurrealValue(condition)}]) > 0`);
155
+ }
156
+ }
157
+ }
158
+ return conditions.join(' AND ');
159
+ }
160
+ // ─── Main Query Builder ─────────────────────────────────────────────────────
161
+ /**
162
+ * Builds a complete SurrealQL query from a Query object and model metadata.
163
+ *
164
+ * This is the core implementation behind `Ad4mModel.queryToSurrealQL()`.
165
+ * It produces a graph-traversal query that:
166
+ * 1. Filters nodes by required predicates (conformance check)
167
+ * 2. Applies user WHERE conditions
168
+ * 3. Fetches all outgoing links for hydration
169
+ *
170
+ * @param metadata - Model metadata from `getModelMetadata()`
171
+ * @param allRelationsMetadata - Full relation registry (for belongs-to detection)
172
+ * @param query - Query parameters
173
+ * @param modelClass - The model class (for `resolveParentPredicate`)
174
+ * @returns Complete SurrealQL query string
175
+ */
176
+ export function buildSurrealQLQuery(metadata, allRelationsMetadata, query, modelClass) {
177
+ const { where } = query;
178
+ // Build graph traversal filters for required predicates
179
+ const graphTraversalFilters = [];
180
+ // Parent filter
181
+ if (query.parent) {
182
+ const parentPredicate = resolveParentPredicate(query.parent, modelClass);
183
+ graphTraversalFilters.push(`count(<-link[WHERE in.uri = ${formatSurrealValue(query.parent.id)} AND predicate = '${escapeSurrealString(parentPredicate)}']) > 0`);
184
+ }
185
+ // Required property filters
186
+ for (const [, propMeta] of Object.entries(metadata.properties)) {
187
+ if (propMeta.required) {
188
+ if (propMeta.getter)
189
+ continue;
190
+ if (propMeta.flag && propMeta.initial) {
191
+ graphTraversalFilters.push(`count(->link[WHERE predicate = '${escapeSurrealString(propMeta.predicate)}' AND out.uri = '${escapeSurrealString(propMeta.initial)}']) > 0`);
192
+ }
193
+ else {
194
+ graphTraversalFilters.push(`count(->link[WHERE predicate = '${escapeSurrealString(propMeta.predicate)}']) > 0`);
195
+ }
196
+ }
197
+ }
198
+ // Fallback: initial-value filters
199
+ if (graphTraversalFilters.length === 0) {
200
+ for (const [, propMeta] of Object.entries(metadata.properties)) {
201
+ if (propMeta.initial) {
202
+ if (propMeta.flag) {
203
+ graphTraversalFilters.push(`count(->link[WHERE predicate = '${escapeSurrealString(propMeta.predicate)}' AND out.uri = '${escapeSurrealString(propMeta.initial)}']) > 0`);
204
+ }
205
+ else {
206
+ graphTraversalFilters.push(`count(->link[WHERE predicate = '${escapeSurrealString(propMeta.predicate)}']) > 0`);
207
+ }
208
+ break;
209
+ }
210
+ }
211
+ }
212
+ // Fallback: open-world structural matching
213
+ if (graphTraversalFilters.length === 0) {
214
+ const structuralPredicates = [];
215
+ for (const [, propMeta] of Object.entries(metadata.properties)) {
216
+ if (propMeta.predicate) {
217
+ structuralPredicates.push(`predicate = '${escapeSurrealString(propMeta.predicate)}'`);
218
+ }
219
+ }
220
+ if (metadata.relations) {
221
+ for (const [, relMeta] of Object.entries(metadata.relations)) {
222
+ if (relMeta.predicate) {
223
+ structuralPredicates.push(`predicate = '${escapeSurrealString(relMeta.predicate)}'`);
224
+ }
225
+ }
226
+ }
227
+ if (structuralPredicates.length > 0) {
228
+ graphTraversalFilters.push(`count(->link[WHERE (${structuralPredicates.join(' OR ')})]) > 0`);
229
+ }
230
+ }
231
+ // User WHERE clause
232
+ const userWhereClause = buildGraphTraversalWhereClause(metadata, allRelationsMetadata, where);
233
+ const whereConditions = [];
234
+ whereConditions.push(...graphTraversalFilters);
235
+ if (userWhereClause) {
236
+ whereConditions.push(userWhereClause);
237
+ }
238
+ whereConditions.push(`count(->link) > 0`);
239
+ const fullQuery = `
240
+ SELECT
241
+ id AS source,
242
+ uri AS source_uri,
243
+ ->link AS links
244
+ FROM node
245
+ WHERE ${whereConditions.join(' AND ')}
246
+ FETCH links
247
+ `.trim();
248
+ return fullQuery;
249
+ }
@@ -25,7 +25,21 @@ export type ConformanceFilterFn = (relationPredicate: string, targetClass: Ad4mM
25
25
  * @param conformanceFilterFn - Injected conformance-filter builder
26
26
  * (avoids circular dependency back into decorators.ts)
27
27
  */
28
- export declare function buildSHACL(subjectName: string, target: any, properties: Record<string, PropertyMetadataEntry>, allRelationsMeta: Record<string, RelationMetadataEntry>, conformanceFilterFn: ConformanceFilterFn): {
28
+ export declare function buildSHACL(subjectName: string, target: any, properties: Record<string, PropertyMetadataEntry>, allRelationsMeta: Record<string, RelationMetadataEntry>, conformanceFilterFn: ConformanceFilterFn,
29
+ /**
30
+ * Optional early-cache seeding callback. When invoked with a
31
+ * partial `{ shape, name }`, any re-entrant `generateSHACL()`
32
+ * call on the same target — which happens when a relation's
33
+ * `target: () => SameClass` points at us, directly or
34
+ * transitively — observes the in-progress shape rather than
35
+ * re-entering this function infinitely. Provided by `@Model` via
36
+ * `getMemoizedSHACL`; safe to omit when calling `buildSHACL`
37
+ * directly (e.g. from a one-off SDNA build tool).
38
+ */
39
+ seedCache?: (partial: {
40
+ shape: SHACLShape;
41
+ name: string;
42
+ }) => void): {
29
43
  shape: SHACLShape;
30
44
  name: string;
31
45
  };
@@ -19,7 +19,18 @@ import { propertyNameToSetterName } from "./util";
19
19
  * @param conformanceFilterFn - Injected conformance-filter builder
20
20
  * (avoids circular dependency back into decorators.ts)
21
21
  */
22
- export function buildSHACL(subjectName, target, properties, allRelationsMeta, conformanceFilterFn) {
22
+ export function buildSHACL(subjectName, target, properties, allRelationsMeta, conformanceFilterFn,
23
+ /**
24
+ * Optional early-cache seeding callback. When invoked with a
25
+ * partial `{ shape, name }`, any re-entrant `generateSHACL()`
26
+ * call on the same target — which happens when a relation's
27
+ * `target: () => SameClass` points at us, directly or
28
+ * transitively — observes the in-progress shape rather than
29
+ * re-entering this function infinitely. Provided by `@Model` via
30
+ * `getMemoizedSHACL`; safe to omit when calling `buildSHACL`
31
+ * directly (e.g. from a one-off SDNA build tool).
32
+ */
33
+ seedCache) {
23
34
  const obj = target.prototype;
24
35
  // ── Determine namespace from first property or relation ─────────────
25
36
  let namespace = "ad4m://";
@@ -47,6 +58,17 @@ export function buildSHACL(subjectName, target, properties, allRelationsMeta, co
47
58
  const shapeUri = `${namespace}${subjectName}Shape`;
48
59
  const targetClass = `${namespace}${subjectName}`;
49
60
  const shape = new SHACLShape(shapeUri, targetClass);
61
+ // ── Seed the memoisation cache while we keep building ──────────────
62
+ // Any subsequent `target.generateSHACL()` call from inside this
63
+ // function (typically when walking a self-referential or
64
+ // mutually-recursive relation target) will now observe the
65
+ // already-allocated `shape` rather than re-entering `buildSHACL`
66
+ // and overflowing the stack. The shape is mutated in place as we
67
+ // populate it below, so the eventual cached value and the value
68
+ // recursive callers see are the same object.
69
+ if (seedCache) {
70
+ seedCache({ shape, name: subjectName });
71
+ }
50
72
  // Detect @Model inheritance — if the parent class also has
51
73
  // generateSHACL it is itself a @Model and we reference its shape
52
74
  // via sh:node so SHACL validators can walk the hierarchy.