@coasys/ad4m 0.13.1-staging.1 → 0.13.1-staging.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (243) hide show
  1. package/lib/index.cjs +4199 -1221
  2. package/lib/index.js +4189 -1222
  3. package/lib/src/Ad4mClient.d.ts +7 -0
  4. package/lib/src/Ad4mClient.js +9 -0
  5. package/lib/src/apiClient.d.ts +13 -0
  6. package/lib/src/apiClient.js +67 -12
  7. package/lib/src/generated/api/AgentsByDidsRequest.d.ts +3 -0
  8. package/lib/src/generated/api/AuthInfo.d.ts +4 -0
  9. package/lib/src/generated/api/CallSessionInfo.d.ts +23 -0
  10. package/lib/src/generated/api/DiscardBatchRequest.d.ts +3 -0
  11. package/lib/src/generated/api/Events.d.ts +13 -3
  12. package/lib/src/generated/api/Events.js +1 -0
  13. package/lib/src/generated/api/FlowStateChangedEvent.d.ts +38 -0
  14. package/lib/src/generated/api/FlowStateEntry.d.ts +18 -0
  15. package/lib/src/generated/api/FlowStateEntry.js +2 -0
  16. package/lib/src/generated/api/IceServer.d.ts +18 -0
  17. package/lib/src/generated/api/IceServer.js +2 -0
  18. package/lib/src/generated/api/OnlineAgent.d.ts +4 -0
  19. package/lib/src/generated/api/PerspectiveDiscardBatchParams.d.ts +4 -0
  20. package/lib/src/generated/api/PerspectiveDiscardBatchParams.js +2 -0
  21. package/lib/src/generated/api/PerspectiveFlowFiredParams.d.ts +8 -0
  22. package/lib/src/generated/api/PerspectiveFlowFiredParams.js +2 -0
  23. package/lib/src/generated/api/PerspectiveFlowStatesParams.d.ts +11 -0
  24. package/lib/src/generated/api/PerspectiveFlowStatesParams.js +2 -0
  25. package/lib/src/generated/api/PerspectiveGetAllShaclParams.d.ts +7 -0
  26. package/lib/src/generated/api/PerspectiveGetAllShaclParams.js +2 -0
  27. package/lib/src/generated/api/PerspectiveModelQueryParams.d.ts +6 -1
  28. package/lib/src/generated/api/PerspectiveRemoveSubjectParams.d.ts +6 -0
  29. package/lib/src/generated/api/PerspectiveRemoveSubjectParams.js +2 -0
  30. package/lib/src/generated/api/PerspectiveResynced.d.ts +8 -0
  31. package/lib/src/generated/api/PerspectiveResynced.js +2 -0
  32. package/lib/src/generated/api/PerspectiveSubscribed.d.ts +10 -0
  33. package/lib/src/generated/api/PerspectiveSubscribed.js +2 -0
  34. package/lib/src/generated/api/PerspectiveUpdateSubjectParams.d.ts +10 -0
  35. package/lib/src/generated/api/PerspectiveUpdateSubjectParams.js +2 -0
  36. package/lib/src/generated/api/QuerySubscriptionUpdate.d.ts +19 -0
  37. package/lib/src/generated/api/QuerySubscriptionUpdate.js +2 -0
  38. package/lib/src/generated/api/QuerySubscriptionUpdateEvent.d.ts +7 -0
  39. package/lib/src/generated/api/QuerySubscriptionUpdateEvent.js +1 -0
  40. package/lib/src/generated/api/QueryUpdatesLagged.d.ts +7 -0
  41. package/lib/src/generated/api/QueryUpdatesLagged.js +2 -0
  42. package/lib/src/generated/api/RemoveSubjectRequest.d.ts +9 -0
  43. package/lib/src/generated/api/RemoveSubjectRequest.js +2 -0
  44. package/lib/src/generated/api/ResyncSubscriptionRequest.d.ts +3 -0
  45. package/lib/src/generated/api/ResyncSubscriptionRequest.js +2 -0
  46. package/lib/src/generated/api/RpcMethods.d.ts +134 -14
  47. package/lib/src/generated/api/RpcMethods.js +12 -0
  48. package/lib/src/generated/api/RuntimeInfo.d.ts +5 -0
  49. package/lib/src/generated/api/SfuAddIceCandidateParams.d.ts +8 -0
  50. package/lib/src/generated/api/SfuAddIceCandidateParams.js +2 -0
  51. package/lib/src/generated/api/SfuAnswerServerOfferParams.d.ts +8 -0
  52. package/lib/src/generated/api/SfuAnswerServerOfferParams.js +2 -0
  53. package/lib/src/generated/api/SfuCallJoinParams.d.ts +14 -0
  54. package/lib/src/generated/api/SfuCallJoinParams.js +2 -0
  55. package/lib/src/generated/api/SfuCallRenegotiationOffer.d.ts +30 -0
  56. package/lib/src/generated/api/SfuCallRenegotiationOffer.js +1 -0
  57. package/lib/src/generated/api/SfuCascadePipe.d.ts +4 -0
  58. package/lib/src/generated/api/SfuCascadePipe.js +2 -0
  59. package/lib/src/generated/api/SfuCascadeStatus.d.ts +8 -0
  60. package/lib/src/generated/api/SfuCascadeStatus.js +1 -0
  61. package/lib/src/generated/api/SfuConfig.d.ts +52 -0
  62. package/lib/src/generated/api/SfuConfig.js +1 -0
  63. package/lib/src/generated/api/SfuDataMessage.d.ts +24 -0
  64. package/lib/src/generated/api/SfuDataMessage.js +2 -0
  65. package/lib/src/generated/api/SfuEnsureMembershipParams.d.ts +4 -0
  66. package/lib/src/generated/api/SfuEnsureMembershipParams.js +2 -0
  67. package/lib/src/generated/api/SfuMigrateEvent.d.ts +21 -0
  68. package/lib/src/generated/api/SfuMigrateEvent.js +2 -0
  69. package/lib/src/generated/api/SfuNeighbourhoodParams.d.ts +3 -0
  70. package/lib/src/generated/api/SfuNeighbourhoodParams.js +2 -0
  71. package/lib/src/generated/api/SfuParticipantQualityPreference.d.ts +7 -0
  72. package/lib/src/generated/api/SfuParticipantQualityPreference.js +2 -0
  73. package/lib/src/generated/api/SfuPerspectiveParams.d.ts +6 -0
  74. package/lib/src/generated/api/SfuPerspectiveParams.js +2 -0
  75. package/lib/src/generated/api/SfuQualityPreferenceParams.d.ts +8 -0
  76. package/lib/src/generated/api/SfuQualityPreferenceParams.js +2 -0
  77. package/lib/src/generated/api/SfuRoomInfo.d.ts +11 -0
  78. package/lib/src/generated/api/SfuRoomInfo.js +1 -0
  79. package/lib/src/generated/api/SfuRoomParams.d.ts +4 -0
  80. package/lib/src/generated/api/SfuRoomParams.js +2 -0
  81. package/lib/src/generated/api/SfuRoomParticipantInfo.d.ts +11 -0
  82. package/lib/src/generated/api/SfuRoomParticipantInfo.js +2 -0
  83. package/lib/src/generated/api/SfuRoomRoster.d.ts +13 -0
  84. package/lib/src/generated/api/SfuRoomRoster.js +2 -0
  85. package/lib/src/generated/api/SfuSendDataParams.d.ts +10 -0
  86. package/lib/src/generated/api/SfuSendDataParams.js +2 -0
  87. package/lib/src/generated/api/SfuSetConfigParams.d.ts +5 -0
  88. package/lib/src/generated/api/SfuSetConfigParams.js +1 -0
  89. package/lib/src/generated/api/SfuStatus.d.ts +24 -0
  90. package/lib/src/generated/api/SfuStatus.js +2 -0
  91. package/lib/src/generated/api/TrackMapEntry.d.ts +17 -0
  92. package/lib/src/generated/api/TrackMapEntry.js +2 -0
  93. package/lib/src/generated/api/UpdateSubjectRequest.d.ts +12 -0
  94. package/lib/src/generated/api/UpdateSubjectRequest.js +2 -0
  95. package/lib/src/generated/api/index.d.ts +3 -0
  96. package/lib/src/index.d.ts +8 -0
  97. package/lib/src/index.js +5 -0
  98. package/lib/src/model/Ad4mModel.d.ts +84 -0
  99. package/lib/src/model/Ad4mModel.js +279 -22
  100. package/lib/src/model/ModelQueryBuilder.d.ts +23 -38
  101. package/lib/src/model/ModelQueryBuilder.js +97 -274
  102. package/lib/src/model/decorators.d.ts +32 -0
  103. package/lib/src/model/decorators.js +40 -1
  104. package/lib/src/model/query-common.js +7 -1
  105. package/lib/src/model/shacl-gen.d.ts +3 -1
  106. package/lib/src/model/shacl-gen.js +13 -1
  107. package/lib/src/model/types.d.ts +52 -2
  108. package/lib/src/model/types.js +8 -0
  109. package/lib/src/neighbourhood/MeshManager.d.ts +384 -0
  110. package/lib/src/neighbourhood/MeshManager.js +1144 -0
  111. package/lib/src/neighbourhood/NeighbourhoodClient.d.ts +91 -0
  112. package/lib/src/neighbourhood/NeighbourhoodClient.js +196 -0
  113. package/lib/src/neighbourhood/NeighbourhoodProxy.d.ts +55 -1
  114. package/lib/src/neighbourhood/NeighbourhoodProxy.js +170 -3
  115. package/lib/src/neighbourhood/Session.d.ts +105 -0
  116. package/lib/src/neighbourhood/Session.js +412 -0
  117. package/lib/src/neighbourhood/SfuManager.d.ts +174 -0
  118. package/lib/src/neighbourhood/SfuManager.js +619 -0
  119. package/lib/src/neighbourhood/SfuTypes.d.ts +35 -0
  120. package/lib/src/neighbourhood/SfuTypes.js +8 -0
  121. package/lib/src/perspectives/Container.d.ts +41 -0
  122. package/lib/src/perspectives/Container.js +62 -0
  123. package/lib/src/perspectives/FlowInstance.d.ts +63 -24
  124. package/lib/src/perspectives/FlowInstance.js +74 -31
  125. package/lib/src/perspectives/FlowModels.d.ts +0 -16
  126. package/lib/src/perspectives/FlowModels.js +8 -16
  127. package/lib/src/perspectives/LiveQuery.d.ts +49 -0
  128. package/lib/src/perspectives/LiveQuery.js +169 -0
  129. package/lib/src/perspectives/PerspectiveClient.d.ts +24 -15
  130. package/lib/src/perspectives/PerspectiveClient.js +33 -36
  131. package/lib/src/perspectives/PerspectiveProxy.d.ts +71 -168
  132. package/lib/src/perspectives/PerspectiveProxy.js +128 -476
  133. package/lib/src/perspectives/TextContent.d.ts +31 -0
  134. package/lib/src/perspectives/TextContent.js +52 -0
  135. package/lib/src/perspectives/WakerSubscriptionManager.d.ts +111 -6
  136. package/lib/src/perspectives/WakerSubscriptionManager.js +290 -48
  137. package/lib/src/runtime/RuntimeTypes.d.ts +2 -0
  138. package/lib/src/shacl/SHACLFlow.d.ts +7 -4
  139. package/lib/src/shacl/SHACLFlow.js +7 -4
  140. package/lib/src/shacl/SHACLShape.d.ts +9 -0
  141. package/lib/src/shacl/SHACLShape.js +37 -0
  142. package/package.json +2 -2
  143. package/pnpm-workspace.yaml +4 -1
  144. package/src/Ad4mClient.test.ts +90 -18
  145. package/src/Ad4mClient.ts +10 -0
  146. package/src/apiClient.test.ts +128 -2
  147. package/src/apiClient.ts +64 -11
  148. package/src/generated/api/AgentsByDidsRequest.ts +3 -0
  149. package/src/generated/api/AuthInfo.ts +6 -1
  150. package/src/generated/api/CallSessionInfo.ts +20 -0
  151. package/src/generated/api/DiscardBatchRequest.ts +3 -0
  152. package/src/generated/api/Events.ts +14 -3
  153. package/src/generated/api/FlowStateChangedEvent.ts +36 -0
  154. package/src/generated/api/FlowStateEntry.ts +18 -0
  155. package/src/generated/api/IceServer.ts +19 -0
  156. package/src/generated/api/OnlineAgent.ts +6 -1
  157. package/src/generated/api/PerspectiveDiscardBatchParams.ts +3 -0
  158. package/src/generated/api/PerspectiveFlowFiredParams.ts +7 -0
  159. package/src/generated/api/PerspectiveFlowStatesParams.ts +11 -0
  160. package/src/generated/api/PerspectiveGetAllShaclParams.ts +6 -0
  161. package/src/generated/api/PerspectiveModelQueryParams.ts +5 -1
  162. package/src/generated/api/PerspectiveRemoveSubjectParams.ts +3 -0
  163. package/src/generated/api/PerspectiveResynced.ts +7 -0
  164. package/src/generated/api/PerspectiveSubscribed.ts +8 -0
  165. package/src/generated/api/PerspectiveUpdateSubjectParams.ts +7 -0
  166. package/src/generated/api/QuerySubscriptionUpdate.ts +10 -0
  167. package/src/generated/api/QuerySubscriptionUpdateEvent.ts +9 -0
  168. package/src/generated/api/QueryUpdatesLagged.ts +7 -0
  169. package/src/generated/api/RemoveSubjectRequest.ts +7 -0
  170. package/src/generated/api/ResyncSubscriptionRequest.ts +3 -0
  171. package/src/generated/api/RpcMethods.ts +68 -8
  172. package/src/generated/api/RuntimeInfo.ts +6 -1
  173. package/src/generated/api/SfuAddIceCandidateParams.ts +7 -0
  174. package/src/generated/api/SfuAnswerServerOfferParams.ts +7 -0
  175. package/src/generated/api/SfuCallJoinParams.ts +13 -0
  176. package/src/generated/api/SfuCallRenegotiationOffer.ts +29 -0
  177. package/src/generated/api/SfuCascadePipe.ts +3 -0
  178. package/src/generated/api/SfuCascadeStatus.ts +7 -0
  179. package/src/generated/api/SfuConfig.ts +53 -0
  180. package/src/generated/api/SfuDataMessage.ts +23 -0
  181. package/src/generated/api/SfuEnsureMembershipParams.ts +3 -0
  182. package/src/generated/api/SfuMigrateEvent.ts +20 -0
  183. package/src/generated/api/{KeepAliveQueryRequest.ts → SfuNeighbourhoodParams.ts} +1 -1
  184. package/src/generated/api/SfuParticipantQualityPreference.ts +6 -0
  185. package/src/generated/api/{PerspectiveSubscribeQueryResult.ts → SfuPerspectiveParams.ts} +4 -1
  186. package/src/generated/api/SfuQualityPreferenceParams.ts +7 -0
  187. package/src/generated/api/SfuRoomInfo.ts +7 -0
  188. package/src/generated/api/SfuRoomParams.ts +3 -0
  189. package/src/generated/api/SfuRoomParticipantInfo.ts +8 -0
  190. package/src/generated/api/SfuRoomRoster.ts +12 -0
  191. package/src/generated/api/SfuSendDataParams.ts +7 -0
  192. package/src/generated/api/SfuSetConfigParams.ts +4 -0
  193. package/src/generated/api/SfuStatus.ts +24 -0
  194. package/src/generated/api/TrackMapEntry.ts +18 -0
  195. package/src/generated/api/UpdateSubjectRequest.ts +10 -0
  196. package/src/generated/api/index.ts +3 -0
  197. package/src/index.ts +8 -0
  198. package/src/model/Ad4mModel.test.ts +255 -231
  199. package/src/model/Ad4mModel.ts +322 -23
  200. package/src/model/ModelQueryBuilder.ts +112 -316
  201. package/src/model/abstract-classes.test.ts +225 -0
  202. package/src/model/containment-scope.test.ts +104 -0
  203. package/src/model/decorators.ts +81 -0
  204. package/src/model/query-common.ts +10 -1
  205. package/src/model/shacl-gen.ts +13 -0
  206. package/src/model/types.ts +63 -2
  207. package/src/neighbourhood/MeshManager.test.ts +2640 -0
  208. package/src/neighbourhood/MeshManager.ts +1350 -0
  209. package/src/neighbourhood/NeighbourhoodClient.ts +271 -0
  210. package/src/neighbourhood/NeighbourhoodProxy.test.ts +23 -0
  211. package/src/neighbourhood/NeighbourhoodProxy.ts +247 -1
  212. package/src/neighbourhood/Session.test.ts +800 -0
  213. package/src/neighbourhood/Session.ts +525 -0
  214. package/src/neighbourhood/SfuManager.test.ts +677 -0
  215. package/src/neighbourhood/SfuManager.ts +803 -0
  216. package/src/neighbourhood/SfuTypes.ts +40 -0
  217. package/src/perspectives/Container.test.ts +65 -0
  218. package/src/perspectives/Container.ts +46 -0
  219. package/src/perspectives/FlowInstance.ts +108 -31
  220. package/src/perspectives/FlowModels.ts +8 -18
  221. package/src/perspectives/LiveQuery.test.ts +197 -0
  222. package/src/perspectives/LiveQuery.ts +189 -0
  223. package/src/perspectives/PerspectiveClient.ts +51 -51
  224. package/src/perspectives/PerspectiveProxy.test.ts +93 -398
  225. package/src/perspectives/PerspectiveProxy.ts +133 -537
  226. package/src/perspectives/TextContent.test.ts +123 -0
  227. package/src/perspectives/TextContent.ts +36 -0
  228. package/src/perspectives/WakerSubscriptionManager.test.ts +421 -21
  229. package/src/perspectives/WakerSubscriptionManager.ts +349 -62
  230. package/src/runtime/RuntimeTypes.ts +2 -0
  231. package/src/shacl/SHACLFlow.ts +7 -4
  232. package/src/shacl/SHACLShape.test.ts +2 -1
  233. package/src/shacl/SHACLShape.ts +49 -0
  234. package/lib/src/generated/api/KeepAliveQueryRequest.d.ts +0 -3
  235. package/lib/src/generated/api/PerspectiveModelSubscribeResult.d.ts +0 -7
  236. package/lib/src/generated/api/PerspectiveQuerySubscriptionFilter.d.ts +0 -6
  237. package/lib/src/generated/api/PerspectiveSubscribeQueryResult.d.ts +0 -4
  238. package/src/generated/api/PerspectiveModelSubscribeResult.ts +0 -6
  239. package/src/generated/api/PerspectiveQuerySubscriptionFilter.ts +0 -3
  240. /package/lib/src/generated/api/{KeepAliveQueryRequest.js → AgentsByDidsRequest.js} +0 -0
  241. /package/lib/src/generated/api/{PerspectiveModelSubscribeResult.js → CallSessionInfo.js} +0 -0
  242. /package/lib/src/generated/api/{PerspectiveQuerySubscriptionFilter.js → DiscardBatchRequest.js} +0 -0
  243. /package/lib/src/generated/api/{PerspectiveSubscribeQueryResult.js → FlowStateChangedEvent.js} +0 -0
@@ -4,6 +4,7 @@
4
4
  * Allows building queries with a chainable interface and either
5
5
  * running them once or subscribing to real-time updates.
6
6
  */
7
+ import { LiveQuery } from "../perspectives/LiveQuery";
7
8
  /** Query builder for Ad4mModel queries.
8
9
  * Allows building queries with a fluent interface and either running them once
9
10
  * or subscribing to updates.
@@ -25,52 +26,63 @@
25
26
  * ```
26
27
  */
27
28
  export class ModelQueryBuilder {
28
- constructor(perspective, ctor, query) {
29
+ constructor(perspective, ctor, query, unionClasses) {
29
30
  this.queryParams = {};
30
31
  this.modelClassName = null;
31
- /** Tail of the subscribe/dispose chain; see `serialize()`. */
32
- this.subscriptionChain = Promise.resolve();
33
32
  this.perspective = perspective;
34
33
  this.ctor = ctor;
35
34
  if (query)
36
35
  this.queryParams = query;
36
+ if (unionClasses)
37
+ this.unionClasses = unionClasses;
38
+ }
39
+ /** The wire parameters for `params`: one class, or the union's class list. */
40
+ prepare(params) {
41
+ if (this.unionClasses) {
42
+ const { classNames, queryJson } = this.ctor.prepareUnionQueryParams(this.unionClasses, params);
43
+ return { className: classNames, queryJson };
44
+ }
45
+ return this.ctor.prepareModelQueryParams(params, this.modelClassName);
37
46
  }
38
- /**
39
- * Disposes of the current subscription if one exists.
40
- *
41
- * This method:
42
- * 1. Stops the keepalive signals to the subscription
43
- * 2. Unsubscribes from subscription updates
44
- * 3. Notifies the backend to clean up subscription resources
45
- * 4. Clears the subscription reference
46
- *
47
- * Steps 1, 2 and 4 happen synchronously, so `builder.dispose()` without
48
- * `await` is still a complete local cleanup. The returned promise resolves
49
- * once the executor has released this subscriber's hold on the subscription
50
- * (it never rejects). The executor shares one subscription between all
51
- * subscribers of the same query and only drops it when the last one
52
- * disposes, so disposing here does not interrupt another builder's updates.
53
- *
54
- * You should call this method when you're done with a subscription
55
- * to prevent memory leaks and ensure proper cleanup.
56
- */
47
+ /** Run `params` once and build model instances from the rows. */
48
+ execute(params) {
49
+ if (this.unionClasses) {
50
+ return this.ctor.executeUnionQuery(this.perspective, this.unionClasses, params);
51
+ }
52
+ return this.ctor.executeModelQuery(this.perspective, params, this.modelClassName);
53
+ }
54
+ /** Build model instances from a raw result pushed by a subscription. */
55
+ parse(raw) {
56
+ const { include, properties } = this.queryParams;
57
+ if (this.unionClasses) {
58
+ return this.ctor.parseUnionResult(this.unionClasses, this.perspective, raw, include, properties);
59
+ }
60
+ return this.ctor.parseModelResult(this.perspective, raw, include, properties);
61
+ }
62
+ /** Ends the current subscription, if any, on the client and the executor. */
57
63
  dispose() {
58
- const current = this.currentSubscription;
59
- this.currentSubscription = undefined;
60
- return current ? current.dispose() : Promise.resolve();
64
+ if (this.currentSubscription) {
65
+ this.currentSubscription.dispose();
66
+ this.currentSubscription = undefined;
67
+ }
61
68
  }
62
- /**
63
- * Runs one subscribe variant after every earlier one on this builder has
64
- * finished. Each variant disposes the previous subscription (awaiting the
65
- * executor) and then registers its own; two overlapping calls would both
66
- * find no current subscription, both register, and the builder could only
67
- * ever dispose the last one. Serializing keeps exactly one subscription
68
- * per builder.
69
- */
70
- serialize(run) {
71
- const result = this.subscriptionChain.then(run, run);
72
- this.subscriptionChain = result.then(() => { }, () => { });
73
- return result;
69
+ /** Open a live model query for `params` as the current subscription.
70
+ * Resolves with it and the raw initial result; `onResult` gets every later one.
71
+ * A failed open ends only its own query: a later call may already own
72
+ * `currentSubscription`. */
73
+ async live(params, onResult) {
74
+ const { className, queryJson } = this.prepare(params);
75
+ const live = new LiveQuery(this.perspective.client, this.perspective.uuid, () => this.perspective.modelSubscribe(className, queryJson), onResult);
76
+ this.currentSubscription = live;
77
+ try {
78
+ return { live, initial: await live.start() };
79
+ }
80
+ catch (e) {
81
+ live.dispose();
82
+ if (this.currentSubscription === live)
83
+ this.currentSubscription = undefined;
84
+ throw e;
85
+ }
74
86
  }
75
87
  /**
76
88
  * Adds where conditions to the query.
@@ -150,9 +162,10 @@ export class ModelQueryBuilder {
150
162
  * 3. **String id + model class** — same metadata scan (or field lookup if
151
163
  * options include `field`).
152
164
  * 4. **String id + string predicate** — raw escape hatch, no metadata lookup.
153
- *
154
- * Passing a plain string id with no second argument throws because the
155
- * predicate cannot be resolved without a model class.
165
+ * 5. **String id alone** — containment through the built-in `Container`:
166
+ * the id's `ad4m://has_child` targets, and the targets of the `children`
167
+ * relation of every class the id is an instance of. The executor
168
+ * resolves the predicates; nothing is looked up here.
156
169
  *
157
170
  * @param idOrInstance - The parent's expression URI **or** an Ad4mModel instance
158
171
  * @param modelOrPredicate - A model class (predicate auto-resolved) **or** a raw predicate string
@@ -175,6 +188,9 @@ export class ModelQueryBuilder {
175
188
  *
176
189
  * // String id + raw predicate (escape hatch)
177
190
  * Recipe.query(perspective).parent(cookbookId, "cookbook://recipe").get();
191
+ *
192
+ * // String id alone: whatever cookbookId contains
193
+ * Recipe.query(perspective).parent(cookbookId).get();
178
194
  * ```
179
195
  */
180
196
  parent(idOrInstance, modelOrPredicate, options) {
@@ -202,7 +218,8 @@ export class ModelQueryBuilder {
202
218
  this.queryParams.parent = { id, model: idOrInstance.constructor, ...(field && { field }) };
203
219
  }
204
220
  else {
205
- throw new Error('parent() called with a string id requires a second argument: either a model class or a predicate string');
221
+ // String id alone → containment form of Scope
222
+ this.queryParams.parent = { id };
206
223
  }
207
224
  return this;
208
225
  }
@@ -355,7 +372,7 @@ export class ModelQueryBuilder {
355
372
  * Shared query execution logic — routes through the executor-side modelQuery endpoint.
356
373
  */
357
374
  async executeSparqlQuery() {
358
- const { results } = await this.ctor.executeModelQuery(this.perspective, this.queryParams, this.modelClassName);
375
+ const { results } = await this.execute(this.queryParams);
359
376
  return results;
360
377
  }
361
378
  /**
@@ -407,100 +424,27 @@ export class ModelQueryBuilder {
407
424
  * ```
408
425
  *
409
426
  */
410
- subscribe(callback) {
411
- return this.serialize(() => this.subscribeNow(callback));
412
- }
413
- async subscribeNow(callback) {
414
- // Clean up any existing subscription. Awaited so the executor has
415
- // released the previous hold before the new registration arrives: the
416
- // executor hands out one shared id per query, and a dispose landing after
417
- // the re-subscribe would otherwise release the id just handed back.
418
- await this.dispose();
419
- const ctor = this.ctor;
420
- // Build the model query params (className, queryJson). The executor
421
- // resolves the shape from the perspective's SHACL triples.
422
- const { className, queryJson } = ctor.prepareModelQueryParams(this.queryParams, this.modelClassName);
423
- // Register model subscription via Rust — this builds trigger SPARQL internally,
424
- // registers the subscription, and runs the initial query in one call.
425
- const { subscriptionId, result: initialModelResult } = await this.perspective.modelSubscribe(className, queryJson);
426
- // Convert JSON instances to model class instances
427
- const parseResults = (raw) => {
428
- return ctor.parseModelResult(this.perspective, raw, this.queryParams.include, this.queryParams.properties);
429
- };
430
- // Transforms are now applied by the Rust executor during hydration
431
- const initialResults = parseResults(initialModelResult);
432
- // Track last emitted result fingerprint to suppress duplicate callbacks
433
- let lastResultFingerprint = null;
434
- const buildFingerprint = (results) => {
435
- if (results.length === 0)
436
- return '0:';
437
- return JSON.stringify(results, (_, v) => typeof v === 'function' ? undefined : v);
438
- };
439
- lastResultFingerprint = buildFingerprint(initialResults);
440
- // Listen for subscription updates via the same WS-RPC subscription channel.
441
- // When Rust re-runs the model query and finds changed results, it pushes them.
442
- const unsubscribe = this.perspective.client.subscribeToQueryUpdates(subscriptionId, (rawResult) => {
427
+ async subscribe(callback) {
428
+ this.dispose();
429
+ const parseResults = (raw) => this.parse(raw);
430
+ // Suppress callbacks whose parsed results equal the last ones emitted.
431
+ const fingerprint = (results) => JSON.stringify(results, (_, v) => (typeof v === 'function' ? undefined : v));
432
+ let lastFingerprint = null;
433
+ const { initial } = await this.live(this.queryParams, (raw) => {
443
434
  try {
444
- const results = parseResults(rawResult);
445
- const fp = buildFingerprint(results);
446
- if (fp === lastResultFingerprint) {
435
+ const results = parseResults(raw);
436
+ const fp = fingerprint(results);
437
+ if (fp === lastFingerprint)
447
438
  return;
448
- }
449
- lastResultFingerprint = fp;
439
+ lastFingerprint = fp;
450
440
  callback(results);
451
441
  }
452
442
  catch (e) {
453
443
  console.error('Model subscription update parse error:', e);
454
444
  }
455
445
  });
456
- // Set up keepalive with recovery — uses setTimeout loop so we can
457
- // break out and resubscribe when the server evicts the subscription.
458
- let disposed = false;
459
- let keepaliveTimer;
460
- let resubscribeAttempts = 0;
461
- const MAX_RESUBSCRIBE_ATTEMPTS = 5;
462
- const keepaliveLoop = async () => {
463
- if (disposed)
464
- return;
465
- try {
466
- await this.perspective.client.keepAliveQuery(this.perspective.uuid, subscriptionId);
467
- resubscribeAttempts = 0; // Reset on success
468
- }
469
- catch (e) {
470
- console.warn(`Model subscription keepalive failed for ${subscriptionId}:`, e);
471
- if (!disposed && resubscribeAttempts < MAX_RESUBSCRIBE_ATTEMPTS) {
472
- resubscribeAttempts++;
473
- const backoffMs = Math.min(1000 * Math.pow(2, resubscribeAttempts), 60000);
474
- console.warn(`Resubscribing (attempt ${resubscribeAttempts}/${MAX_RESUBSCRIBE_ATTEMPTS}, backoff ${backoffMs}ms)...`);
475
- await new Promise(r => setTimeout(r, backoffMs));
476
- try {
477
- unsubscribe();
478
- await this.subscribe(callback);
479
- }
480
- catch (resubErr) {
481
- console.error('Model subscription resubscribe failed:', resubErr);
482
- }
483
- }
484
- else if (resubscribeAttempts >= MAX_RESUBSCRIBE_ATTEMPTS) {
485
- console.error(`Model subscription ${subscriptionId}: max resubscribe attempts reached, giving up.`);
486
- }
487
- return; // new subscription owns its own keepalive loop
488
- }
489
- if (!disposed) {
490
- keepaliveTimer = setTimeout(keepaliveLoop, 30000);
491
- }
492
- };
493
- keepaliveTimer = setTimeout(keepaliveLoop, 30000);
494
- // Store dispose function
495
- this.currentSubscription = {
496
- dispose: () => {
497
- disposed = true;
498
- if (keepaliveTimer)
499
- clearTimeout(keepaliveTimer);
500
- unsubscribe();
501
- return this.perspective.client.disposeQuerySubscription(this.perspective.uuid, subscriptionId).then(() => { }, () => { });
502
- },
503
- };
446
+ const initialResults = parseResults(initial);
447
+ lastFingerprint = fingerprint(initialResults);
504
448
  // Take snapshots for dirty tracking
505
449
  for (const inst of initialResults) {
506
450
  inst.takeSnapshot?.(this.queryParams.include);
@@ -527,7 +471,7 @@ export class ModelQueryBuilder {
527
471
  * ```
528
472
  */
529
473
  async count() {
530
- const { totalCount } = await this.ctor.executeModelQuery(this.perspective, { ...this.queryParams, limit: 0 }, this.modelClassName);
474
+ const { totalCount } = await this.execute({ ...this.queryParams, limit: 0 });
531
475
  return totalCount;
532
476
  }
533
477
  /**
@@ -565,77 +509,10 @@ export class ModelQueryBuilder {
565
509
  * ```
566
510
  *
567
511
  */
568
- countSubscribe(callback) {
569
- return this.serialize(() => this.countSubscribeNow(callback));
570
- }
571
- async countSubscribeNow(callback) {
572
- // Clean up any existing subscription. Awaited so the executor has
573
- // released the previous hold before the new registration arrives: the
574
- // executor hands out one shared id per query, and a dispose landing after
575
- // the re-subscribe would otherwise release the id just handed back.
576
- await this.dispose();
577
- const countParams = { ...this.queryParams, limit: 0 };
578
- const { className, queryJson } = this.ctor.prepareModelQueryParams(countParams, this.modelClassName);
579
- const { subscriptionId, result: initialModelResult } = await this.perspective.modelSubscribe(className, queryJson);
580
- const parseCount = (raw) => {
581
- const data = typeof raw === 'string' ? JSON.parse(raw) : raw;
582
- return data.totalCount ?? 0;
583
- };
584
- const initialCount = parseCount(initialModelResult);
585
- const unsubscribe = this.perspective.client.subscribeToQueryUpdates(subscriptionId, (rawResult) => {
586
- try {
587
- callback(parseCount(rawResult));
588
- }
589
- catch (e) {
590
- console.error('Count subscription update parse error:', e);
591
- }
592
- });
593
- let disposed = false;
594
- let keepaliveTimer;
595
- let resubscribeAttempts = 0;
596
- const MAX_RESUBSCRIBE_ATTEMPTS = 5;
597
- const keepaliveLoop = async () => {
598
- if (disposed)
599
- return;
600
- try {
601
- await this.perspective.client.keepAliveQuery(this.perspective.uuid, subscriptionId);
602
- resubscribeAttempts = 0;
603
- }
604
- catch (e) {
605
- console.warn(`Count subscription keepalive failed for ${subscriptionId}:`, e);
606
- if (!disposed && resubscribeAttempts < MAX_RESUBSCRIBE_ATTEMPTS) {
607
- resubscribeAttempts++;
608
- const backoffMs = Math.min(1000 * Math.pow(2, resubscribeAttempts), 60000);
609
- console.warn(`Count resubscribing (attempt ${resubscribeAttempts}/${MAX_RESUBSCRIBE_ATTEMPTS}, backoff ${backoffMs}ms)...`);
610
- await new Promise(r => setTimeout(r, backoffMs));
611
- try {
612
- unsubscribe();
613
- await this.countSubscribe(callback);
614
- }
615
- catch (resubErr) {
616
- console.error('Count subscription resubscribe failed:', resubErr);
617
- }
618
- }
619
- else if (resubscribeAttempts >= MAX_RESUBSCRIBE_ATTEMPTS) {
620
- console.error(`Count subscription ${subscriptionId}: max resubscribe attempts reached, giving up.`);
621
- }
622
- return;
623
- }
624
- if (!disposed) {
625
- keepaliveTimer = setTimeout(keepaliveLoop, 30000);
626
- }
627
- };
628
- keepaliveTimer = setTimeout(keepaliveLoop, 30000);
629
- this.currentSubscription = {
630
- dispose: () => {
631
- disposed = true;
632
- if (keepaliveTimer)
633
- clearTimeout(keepaliveTimer);
634
- unsubscribe();
635
- return this.perspective.client.disposeQuerySubscription(this.perspective.uuid, subscriptionId).then(() => { }, () => { });
636
- },
637
- };
638
- return initialCount;
512
+ async countSubscribe(callback) {
513
+ this.dispose();
514
+ const { initial } = await this.live({ ...this.queryParams, limit: 0 }, (raw) => callback(raw.totalCount ?? 0));
515
+ return initial.totalCount ?? 0;
639
516
  }
640
517
  /**
641
518
  * Subscribes to count updates using SPARQL.
@@ -661,7 +538,7 @@ export class ModelQueryBuilder {
661
538
  */
662
539
  async paginate(pageSize, pageNumber) {
663
540
  const paginationQuery = { ...(this.queryParams || {}), limit: pageSize, offset: pageSize * (pageNumber - 1), count: true };
664
- const { results, totalCount } = await this.ctor.executeModelQuery(this.perspective, paginationQuery, this.modelClassName);
541
+ const { results, totalCount } = await this.execute(paginationQuery);
665
542
  return { results, totalCount, pageSize, pageNumber };
666
543
  }
667
544
  /**
@@ -701,24 +578,14 @@ export class ModelQueryBuilder {
701
578
  * ```
702
579
  *
703
580
  */
704
- paginateSubscribe(pageSize, pageNumber, callback) {
705
- return this.serialize(() => this.paginateSubscribeNow(pageSize, pageNumber, callback));
706
- }
707
- async paginateSubscribeNow(pageSize, pageNumber, callback) {
708
- // Clean up any existing subscription. Awaited so the executor has
709
- // released the previous hold before the new registration arrives: the
710
- // executor hands out one shared id per query, and a dispose landing after
711
- // the re-subscribe would otherwise release the id just handed back.
712
- await this.dispose();
713
- const ctor = this.ctor;
581
+ async paginateSubscribe(pageSize, pageNumber, callback) {
582
+ // Clean up any existing subscription
583
+ this.dispose();
714
584
  // Subscribe to the full result set (no limit/offset) so the subscription
715
- // detects changes anywhere in the dataset. Rust builds trigger SPARQL
716
- // from the shape predicates.
585
+ // detects changes anywhere in the dataset; each change re-reads the page.
717
586
  const subscriptionParams = { ...(this.queryParams || {}) };
718
587
  delete subscriptionParams.limit;
719
588
  delete subscriptionParams.offset;
720
- const { className, queryJson } = ctor.prepareModelQueryParams(subscriptionParams, this.modelClassName);
721
- const { subscriptionId } = await this.perspective.modelSubscribe(className, queryJson);
722
589
  // Build the paginated query for Rust endpoint (count: true fetches both results and totalCount in one call)
723
590
  const paginatedQuery = {
724
591
  ...(this.queryParams || {}),
@@ -738,90 +605,46 @@ export class ModelQueryBuilder {
738
605
  let disposed = false;
739
606
  let fetching = false;
740
607
  let pending = false;
741
- let coalesced = 0;
742
608
  const processResults = async () => {
743
609
  if (disposed)
744
610
  return;
745
611
  if (fetching) {
746
612
  pending = true;
747
- coalesced++;
748
613
  return;
749
614
  }
750
615
  fetching = true;
751
616
  try {
752
- const { results, totalCount } = await ctor.executeModelQuery(this.perspective, paginatedQuery, this.modelClassName);
617
+ const { results, totalCount } = await this.execute(paginatedQuery);
753
618
  if (!disposed)
754
619
  callback({ results, totalCount, pageSize, pageNumber });
755
620
  }
756
621
  finally {
757
622
  fetching = false;
758
623
  if (pending) {
759
- const dispatches = coalesced;
760
624
  pending = false;
761
- coalesced = 0;
762
- // Whether a trailing fetch actually starts is decided by the entry
763
- // guard at the top of processResults, which returns when disposed.
764
- // Log only what that guard will let through, or the dispose path
765
- // announces a fetch it then drops.
766
- if (!disposed) {
767
- console.debug(`[ModelQueryBuilder.paginateSubscribe] ${dispatches} dispatch(es) during read for ${subscriptionId}, coalesced into one trailing fetch`);
768
- }
769
625
  // Detached from the caller's promise: needs its own handler, or a
770
626
  // rejection here is unhandled.
771
627
  processResults().catch(e => console.error('Paginate subscription error:', e));
772
628
  }
773
629
  }
774
630
  };
775
- const unsubscribe = this.perspective.client.subscribeToQueryUpdates(subscriptionId, (rawResult) => {
776
- console.debug(`[ModelQueryBuilder.paginateSubscribe] Update received for ${subscriptionId}, re-fetching paginated data...`);
631
+ const { live } = await this.live(subscriptionParams, () => {
777
632
  processResults().catch(e => console.error('Paginate subscription error:', e));
778
633
  });
779
- let keepaliveTimer;
780
- let resubscribeAttempts = 0;
781
- const MAX_RESUBSCRIBE_ATTEMPTS = 5;
782
- const keepaliveLoop = async () => {
783
- if (disposed)
784
- return;
785
- try {
786
- await this.perspective.client.keepAliveQuery(this.perspective.uuid, subscriptionId);
787
- resubscribeAttempts = 0;
788
- }
789
- catch (e) {
790
- console.warn(`Paginate subscription keepalive failed for ${subscriptionId}:`, e);
791
- if (!disposed && resubscribeAttempts < MAX_RESUBSCRIBE_ATTEMPTS) {
792
- resubscribeAttempts++;
793
- const backoffMs = Math.min(1000 * Math.pow(2, resubscribeAttempts), 60000);
794
- console.warn(`Paginate resubscribing (attempt ${resubscribeAttempts}/${MAX_RESUBSCRIBE_ATTEMPTS}, backoff ${backoffMs}ms)...`);
795
- await new Promise(r => setTimeout(r, backoffMs));
796
- try {
797
- unsubscribe();
798
- await this.paginateSubscribe(pageSize, pageNumber, callback);
799
- }
800
- catch (resubErr) {
801
- console.error('Paginate subscription resubscribe failed:', resubErr);
802
- }
803
- }
804
- else if (resubscribeAttempts >= MAX_RESUBSCRIBE_ATTEMPTS) {
805
- console.error(`Paginate subscription ${subscriptionId}: max resubscribe attempts reached, giving up.`);
806
- }
807
- return;
808
- }
809
- if (!disposed) {
810
- keepaliveTimer = setTimeout(keepaliveLoop, 30000);
811
- }
812
- };
813
- keepaliveTimer = setTimeout(keepaliveLoop, 30000);
814
- this.currentSubscription = {
815
- dispose: () => {
816
- disposed = true;
817
- if (keepaliveTimer)
818
- clearTimeout(keepaliveTimer);
819
- unsubscribe();
820
- return this.perspective.client.disposeQuerySubscription(this.perspective.uuid, subscriptionId).then(() => { }, () => { });
821
- },
822
- };
634
+ if (this.currentSubscription === live) {
635
+ this.currentSubscription = {
636
+ dispose: () => {
637
+ disposed = true;
638
+ live.dispose();
639
+ },
640
+ };
641
+ }
642
+ else {
643
+ // Disposed, or overtaken by a later subscribe, while opening: deliver nothing.
644
+ disposed = true;
645
+ }
823
646
  // Initial fetch (single call with count: true)
824
- const { results, totalCount } = await ctor.executeModelQuery(this.perspective, paginatedQuery, this.modelClassName);
647
+ const { results, totalCount } = await this.execute(paginatedQuery);
825
648
  return { results, totalCount, pageSize, pageNumber };
826
649
  }
827
650
  /**
@@ -63,6 +63,8 @@ export interface RelationMetadataEntry {
63
63
  * memoized registry copy.
64
64
  */
65
65
  interpretationHint?: string;
66
+ /** Names for abstract classes — see `RelationOptions.alias`. */
67
+ alias?: Record<string, string>;
66
68
  }
67
69
  /**
68
70
  * Retrieve property metadata for a given class constructor.
@@ -117,6 +119,8 @@ export declare function setRelationRegistryEntry(ctor: Function, relName: string
117
119
  export interface Ad4mModelLike {
118
120
  new (...args: any[]): any;
119
121
  className?: string;
122
+ /** Set by `@Model({ abstract: true })`. */
123
+ isAbstract?: boolean;
120
124
  generateSDNA?: () => any;
121
125
  generateSHACL?: () => any;
122
126
  }
@@ -244,6 +248,13 @@ export interface PropertyOptions {
244
248
  * (e.g. `"xsd://string"`) and enables the hydration decode gate.
245
249
  */
246
250
  datatype?: string;
251
+ /**
252
+ * The name this property answers to through an abstract class, keyed by
253
+ * its name: `alias: { TextContent: "text" }` reads (and writes) `body` as
254
+ * `text` through `TextContent`. Registering fails if the class already
255
+ * uses that name.
256
+ */
257
+ alias?: Record<string, string>;
247
258
  }
248
259
  /**
249
260
  * Convenience decorator for defining optional (not required) properties.
@@ -335,6 +346,21 @@ export interface ModelConfig {
335
346
  * The name of the entity.
336
347
  */
337
348
  name: string;
349
+ /**
350
+ * An abstract class names properties a record has, not what it is.
351
+ * Querying it reads every installed class that has all of its names (or
352
+ * aliases for them), matched by name, never by `through`; rows keep
353
+ * their `__subjectClass`. It cannot be created. `save()` and `delete()`
354
+ * on a row read through it run the setters and destructors of the
355
+ * record's own classes; values are not converted between them.
356
+ */
357
+ abstract?: boolean;
358
+ /**
359
+ * Abstract classes this class is meant to be read through: checked at
360
+ * declaration (every name of each must be a name or alias here). The
361
+ * executor matches by structure, listed or not.
362
+ */
363
+ implements?: Ad4mModelLike[];
338
364
  /**
339
365
  * Natural-language hint that steers the generic LLM extractor when
340
366
  * turning a transcript into instances of this class. Emitted as an
@@ -728,6 +754,12 @@ export interface RelationOptions {
728
754
  * ```
729
755
  */
730
756
  interpretationHint?: string;
757
+ /**
758
+ * The name this relation answers to when its class is read through an
759
+ * abstract class, keyed by the abstract class's name. See
760
+ * `PropertyOptions.alias`.
761
+ */
762
+ alias?: Record<string, string>;
731
763
  }
732
764
  /**
733
765
  * Utility type that describes the auto-generated helper methods for a HasMany
@@ -308,6 +308,37 @@ export function Flag(opts) {
308
308
  Object.defineProperty(target, key, { configurable: true, writable: true });
309
309
  };
310
310
  }
311
+ /**
312
+ * `@Model({ implements })`: every property and relation name of
313
+ * `abstractClass` must be a name or an alias (for it) on `target`.
314
+ */
315
+ function checkImplements(name, target, abstractClass) {
316
+ const abstractName = abstractClass?.className ?? abstractClass?.prototype?.className;
317
+ if (!abstractName || !abstractClass.isAbstract) {
318
+ throw new Error(`${name} implements ${abstractName ?? abstractClass?.name ?? String(abstractClass)}, ` +
319
+ `which is not an abstract class: declare it with @Model({ abstract: true })`);
320
+ }
321
+ const names = (ctor) => {
322
+ const relations = getRelationsMetadata(ctor);
323
+ const properties = Object.keys(getPropertiesMetadata(ctor)).filter(p => !relations[p]);
324
+ return { properties, relations: Object.keys(relations) };
325
+ };
326
+ const answersTo = (entries, keys) => new Set(keys.map(k => entries[k]?.alias?.[abstractName] ?? k));
327
+ const wanted = names(abstractClass);
328
+ const own = names(target);
329
+ const ownProperties = answersTo(getPropertiesMetadata(target), own.properties);
330
+ const ownRelations = answersTo(getRelationsMetadata(target), own.relations);
331
+ for (const p of wanted.properties) {
332
+ if (!ownProperties.has(p)) {
333
+ throw new Error(`${name} implements ${abstractName} but has no property or alias named \`${p}\``);
334
+ }
335
+ }
336
+ for (const r of wanted.relations) {
337
+ if (!ownRelations.has(r)) {
338
+ throw new Error(`${name} implements ${abstractName} but has no relation or alias named \`${r}\``);
339
+ }
340
+ }
341
+ }
311
342
  /**
312
343
  * Decorator for defining model classes in AD4M.
313
344
  *
@@ -368,11 +399,15 @@ export function Model(opts) {
368
399
  return function (target) {
369
400
  target.prototype.className = opts.name;
370
401
  target.className = opts.name;
402
+ target.isAbstract = !!opts.abstract;
403
+ for (const abstractClass of opts.implements ?? []) {
404
+ checkImplements(opts.name, target, abstractClass);
405
+ }
371
406
  target.generateSDNA = function () {
372
407
  return buildSDNA(opts.name, target.prototype, getPropertiesMetadata(target), getRelationsMetadata(target));
373
408
  };
374
409
  target.generateSHACL = function () {
375
- return getMemoizedSHACL(target, (seed) => buildSHACL(opts.name, target, getPropertiesMetadata(target), getRelationsMetadata(target), buildConformanceFilter, seed, opts.interpretationHint));
410
+ return getMemoizedSHACL(target, (seed) => buildSHACL(opts.name, target, getPropertiesMetadata(target), getRelationsMetadata(target), buildConformanceFilter, seed, opts.interpretationHint, !!opts.abstract));
376
411
  };
377
412
  Object.defineProperty(target, 'type', { configurable: true });
378
413
  };
@@ -620,6 +655,7 @@ export function HasMany(first, second) {
620
655
  ...(opts.instantiateAs && { instantiateAs: opts.instantiateAs }),
621
656
  ...(opts.ordering && { ordering: opts.ordering }),
622
657
  ...(opts.interpretationHint && { interpretationHint: opts.interpretationHint }),
658
+ ...(opts.alias && { alias: opts.alias }),
623
659
  ...(opts.readOnly && { readOnly: true }),
624
660
  };
625
661
  const relKey = key;
@@ -666,6 +702,7 @@ export function HasOne(first, second) {
666
702
  ...(opts.instantiateAs && { instantiateAs: opts.instantiateAs }),
667
703
  ...(opts.ordering && { ordering: opts.ordering }),
668
704
  ...(opts.interpretationHint && { interpretationHint: opts.interpretationHint }),
705
+ ...(opts.alias && { alias: opts.alias }),
669
706
  ...(opts.readOnly && { readOnly: true }),
670
707
  };
671
708
  const relKey = key;
@@ -727,6 +764,7 @@ export function BelongsToOne(first, second) {
727
764
  ...(opts.instantiateAs && { instantiateAs: opts.instantiateAs }),
728
765
  ...(opts.ordering && { ordering: opts.ordering }),
729
766
  ...(opts.interpretationHint && { interpretationHint: opts.interpretationHint }),
767
+ ...(opts.alias && { alias: opts.alias }),
730
768
  };
731
769
  if (opts.through) {
732
770
  // Read-only property (the owning side manages the link)
@@ -761,6 +799,7 @@ export function BelongsToMany(first, second) {
761
799
  ...(opts.instantiateAs && { instantiateAs: opts.instantiateAs }),
762
800
  ...(opts.ordering && { ordering: opts.ordering }),
763
801
  ...(opts.interpretationHint && { interpretationHint: opts.interpretationHint }),
802
+ ...(opts.alias && { alias: opts.alias }),
764
803
  };
765
804
  // @BelongsToMany is the inverse/read-only side — do NOT generate add*/remove*/set*
766
805
  // prototype methods. Mutation must go through the owning side's @HasMany decorator.