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

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 (222) hide show
  1. package/lib/index.cjs +3789 -1192
  2. package/lib/index.js +3783 -1193
  3. package/lib/src/generated/api/AgentsByDidsRequest.d.ts +3 -0
  4. package/lib/src/generated/api/CallSessionInfo.d.ts +23 -0
  5. package/lib/src/generated/api/DiscardBatchRequest.d.ts +3 -0
  6. package/lib/src/generated/api/Events.d.ts +13 -3
  7. package/lib/src/generated/api/Events.js +1 -0
  8. package/lib/src/generated/api/FlowStateChangedEvent.d.ts +38 -0
  9. package/lib/src/generated/api/FlowStateEntry.d.ts +18 -0
  10. package/lib/src/generated/api/FlowStateEntry.js +2 -0
  11. package/lib/src/generated/api/IceServer.d.ts +18 -0
  12. package/lib/src/generated/api/IceServer.js +2 -0
  13. package/lib/src/generated/api/OnlineAgent.d.ts +4 -0
  14. package/lib/src/generated/api/PerspectiveDiscardBatchParams.d.ts +4 -0
  15. package/lib/src/generated/api/PerspectiveDiscardBatchParams.js +2 -0
  16. package/lib/src/generated/api/PerspectiveFlowFiredParams.d.ts +8 -0
  17. package/lib/src/generated/api/PerspectiveFlowFiredParams.js +2 -0
  18. package/lib/src/generated/api/PerspectiveFlowStatesParams.d.ts +11 -0
  19. package/lib/src/generated/api/PerspectiveFlowStatesParams.js +2 -0
  20. package/lib/src/generated/api/PerspectiveGetAllShaclParams.d.ts +7 -0
  21. package/lib/src/generated/api/PerspectiveGetAllShaclParams.js +2 -0
  22. package/lib/src/generated/api/PerspectiveModelQueryParams.d.ts +6 -1
  23. package/lib/src/generated/api/PerspectiveRemoveSubjectParams.d.ts +6 -0
  24. package/lib/src/generated/api/PerspectiveRemoveSubjectParams.js +2 -0
  25. package/lib/src/generated/api/PerspectiveResynced.d.ts +8 -0
  26. package/lib/src/generated/api/PerspectiveResynced.js +2 -0
  27. package/lib/src/generated/api/PerspectiveSubscribed.d.ts +10 -0
  28. package/lib/src/generated/api/PerspectiveSubscribed.js +2 -0
  29. package/lib/src/generated/api/PerspectiveUpdateSubjectParams.d.ts +10 -0
  30. package/lib/src/generated/api/PerspectiveUpdateSubjectParams.js +2 -0
  31. package/lib/src/generated/api/QuerySubscriptionUpdate.d.ts +19 -0
  32. package/lib/src/generated/api/QuerySubscriptionUpdate.js +2 -0
  33. package/lib/src/generated/api/QuerySubscriptionUpdateEvent.d.ts +7 -0
  34. package/lib/src/generated/api/QuerySubscriptionUpdateEvent.js +1 -0
  35. package/lib/src/generated/api/QueryUpdatesLagged.d.ts +7 -0
  36. package/lib/src/generated/api/QueryUpdatesLagged.js +2 -0
  37. package/lib/src/generated/api/RemoveSubjectRequest.d.ts +9 -0
  38. package/lib/src/generated/api/RemoveSubjectRequest.js +2 -0
  39. package/lib/src/generated/api/ResyncSubscriptionRequest.d.ts +3 -0
  40. package/lib/src/generated/api/ResyncSubscriptionRequest.js +2 -0
  41. package/lib/src/generated/api/RpcMethods.d.ts +134 -14
  42. package/lib/src/generated/api/RpcMethods.js +12 -0
  43. package/lib/src/generated/api/SfuAddIceCandidateParams.d.ts +8 -0
  44. package/lib/src/generated/api/SfuAddIceCandidateParams.js +2 -0
  45. package/lib/src/generated/api/SfuAnswerServerOfferParams.d.ts +8 -0
  46. package/lib/src/generated/api/SfuAnswerServerOfferParams.js +2 -0
  47. package/lib/src/generated/api/SfuCallJoinParams.d.ts +14 -0
  48. package/lib/src/generated/api/SfuCallJoinParams.js +2 -0
  49. package/lib/src/generated/api/SfuCallRenegotiationOffer.d.ts +30 -0
  50. package/lib/src/generated/api/SfuCallRenegotiationOffer.js +1 -0
  51. package/lib/src/generated/api/SfuCascadePipe.d.ts +4 -0
  52. package/lib/src/generated/api/SfuCascadePipe.js +2 -0
  53. package/lib/src/generated/api/SfuCascadeStatus.d.ts +8 -0
  54. package/lib/src/generated/api/SfuCascadeStatus.js +1 -0
  55. package/lib/src/generated/api/SfuConfig.d.ts +52 -0
  56. package/lib/src/generated/api/SfuConfig.js +1 -0
  57. package/lib/src/generated/api/SfuDataMessage.d.ts +24 -0
  58. package/lib/src/generated/api/SfuDataMessage.js +2 -0
  59. package/lib/src/generated/api/SfuEnsureMembershipParams.d.ts +4 -0
  60. package/lib/src/generated/api/SfuEnsureMembershipParams.js +2 -0
  61. package/lib/src/generated/api/SfuMigrateEvent.d.ts +21 -0
  62. package/lib/src/generated/api/SfuMigrateEvent.js +2 -0
  63. package/lib/src/generated/api/SfuNeighbourhoodParams.d.ts +3 -0
  64. package/lib/src/generated/api/SfuNeighbourhoodParams.js +2 -0
  65. package/lib/src/generated/api/SfuParticipantQualityPreference.d.ts +7 -0
  66. package/lib/src/generated/api/SfuParticipantQualityPreference.js +2 -0
  67. package/lib/src/generated/api/SfuPerspectiveParams.d.ts +6 -0
  68. package/lib/src/generated/api/SfuPerspectiveParams.js +2 -0
  69. package/lib/src/generated/api/SfuQualityPreferenceParams.d.ts +8 -0
  70. package/lib/src/generated/api/SfuQualityPreferenceParams.js +2 -0
  71. package/lib/src/generated/api/SfuRoomInfo.d.ts +11 -0
  72. package/lib/src/generated/api/SfuRoomInfo.js +1 -0
  73. package/lib/src/generated/api/SfuRoomParams.d.ts +4 -0
  74. package/lib/src/generated/api/SfuRoomParams.js +2 -0
  75. package/lib/src/generated/api/SfuRoomParticipantInfo.d.ts +11 -0
  76. package/lib/src/generated/api/SfuRoomParticipantInfo.js +2 -0
  77. package/lib/src/generated/api/SfuRoomRoster.d.ts +13 -0
  78. package/lib/src/generated/api/SfuRoomRoster.js +2 -0
  79. package/lib/src/generated/api/SfuSendDataParams.d.ts +10 -0
  80. package/lib/src/generated/api/SfuSendDataParams.js +2 -0
  81. package/lib/src/generated/api/SfuSetConfigParams.d.ts +5 -0
  82. package/lib/src/generated/api/SfuSetConfigParams.js +1 -0
  83. package/lib/src/generated/api/SfuStatus.d.ts +24 -0
  84. package/lib/src/generated/api/SfuStatus.js +2 -0
  85. package/lib/src/generated/api/TrackMapEntry.d.ts +17 -0
  86. package/lib/src/generated/api/TrackMapEntry.js +2 -0
  87. package/lib/src/generated/api/UpdateSubjectRequest.d.ts +12 -0
  88. package/lib/src/generated/api/UpdateSubjectRequest.js +2 -0
  89. package/lib/src/generated/api/index.d.ts +3 -0
  90. package/lib/src/index.d.ts +7 -0
  91. package/lib/src/index.js +4 -0
  92. package/lib/src/model/Ad4mModel.d.ts +84 -0
  93. package/lib/src/model/Ad4mModel.js +234 -4
  94. package/lib/src/model/ModelQueryBuilder.d.ts +16 -35
  95. package/lib/src/model/ModelQueryBuilder.js +88 -270
  96. package/lib/src/model/decorators.d.ts +32 -0
  97. package/lib/src/model/decorators.js +40 -1
  98. package/lib/src/model/shacl-gen.d.ts +3 -1
  99. package/lib/src/model/shacl-gen.js +13 -1
  100. package/lib/src/model/types.d.ts +7 -0
  101. package/lib/src/neighbourhood/MeshManager.d.ts +384 -0
  102. package/lib/src/neighbourhood/MeshManager.js +1144 -0
  103. package/lib/src/neighbourhood/NeighbourhoodClient.d.ts +91 -0
  104. package/lib/src/neighbourhood/NeighbourhoodClient.js +196 -0
  105. package/lib/src/neighbourhood/NeighbourhoodProxy.d.ts +55 -1
  106. package/lib/src/neighbourhood/NeighbourhoodProxy.js +170 -3
  107. package/lib/src/neighbourhood/Session.d.ts +105 -0
  108. package/lib/src/neighbourhood/Session.js +412 -0
  109. package/lib/src/neighbourhood/SfuManager.d.ts +174 -0
  110. package/lib/src/neighbourhood/SfuManager.js +619 -0
  111. package/lib/src/neighbourhood/SfuTypes.d.ts +35 -0
  112. package/lib/src/neighbourhood/SfuTypes.js +8 -0
  113. package/lib/src/perspectives/FlowInstance.d.ts +63 -24
  114. package/lib/src/perspectives/FlowInstance.js +74 -31
  115. package/lib/src/perspectives/FlowModels.d.ts +0 -16
  116. package/lib/src/perspectives/FlowModels.js +8 -16
  117. package/lib/src/perspectives/LiveQuery.d.ts +49 -0
  118. package/lib/src/perspectives/LiveQuery.js +169 -0
  119. package/lib/src/perspectives/PerspectiveClient.d.ts +24 -15
  120. package/lib/src/perspectives/PerspectiveClient.js +33 -36
  121. package/lib/src/perspectives/PerspectiveProxy.d.ts +67 -167
  122. package/lib/src/perspectives/PerspectiveProxy.js +121 -475
  123. package/lib/src/perspectives/TextContent.d.ts +31 -0
  124. package/lib/src/perspectives/TextContent.js +52 -0
  125. package/lib/src/perspectives/WakerSubscriptionManager.d.ts +23 -0
  126. package/lib/src/perspectives/WakerSubscriptionManager.js +58 -17
  127. package/lib/src/shacl/SHACLFlow.d.ts +7 -4
  128. package/lib/src/shacl/SHACLFlow.js +7 -4
  129. package/lib/src/shacl/SHACLShape.d.ts +9 -0
  130. package/lib/src/shacl/SHACLShape.js +37 -0
  131. package/package.json +2 -2
  132. package/pnpm-workspace.yaml +4 -1
  133. package/src/Ad4mClient.test.ts +89 -17
  134. package/src/generated/api/AgentsByDidsRequest.ts +3 -0
  135. package/src/generated/api/CallSessionInfo.ts +20 -0
  136. package/src/generated/api/DiscardBatchRequest.ts +3 -0
  137. package/src/generated/api/Events.ts +14 -3
  138. package/src/generated/api/FlowStateChangedEvent.ts +36 -0
  139. package/src/generated/api/FlowStateEntry.ts +18 -0
  140. package/src/generated/api/IceServer.ts +19 -0
  141. package/src/generated/api/OnlineAgent.ts +6 -1
  142. package/src/generated/api/PerspectiveDiscardBatchParams.ts +3 -0
  143. package/src/generated/api/PerspectiveFlowFiredParams.ts +7 -0
  144. package/src/generated/api/PerspectiveFlowStatesParams.ts +11 -0
  145. package/src/generated/api/PerspectiveGetAllShaclParams.ts +6 -0
  146. package/src/generated/api/PerspectiveModelQueryParams.ts +5 -1
  147. package/src/generated/api/PerspectiveRemoveSubjectParams.ts +3 -0
  148. package/src/generated/api/PerspectiveResynced.ts +7 -0
  149. package/src/generated/api/PerspectiveSubscribed.ts +8 -0
  150. package/src/generated/api/PerspectiveUpdateSubjectParams.ts +7 -0
  151. package/src/generated/api/QuerySubscriptionUpdate.ts +10 -0
  152. package/src/generated/api/QuerySubscriptionUpdateEvent.ts +9 -0
  153. package/src/generated/api/QueryUpdatesLagged.ts +7 -0
  154. package/src/generated/api/RemoveSubjectRequest.ts +7 -0
  155. package/src/generated/api/ResyncSubscriptionRequest.ts +3 -0
  156. package/src/generated/api/RpcMethods.ts +68 -8
  157. package/src/generated/api/SfuAddIceCandidateParams.ts +7 -0
  158. package/src/generated/api/SfuAnswerServerOfferParams.ts +7 -0
  159. package/src/generated/api/SfuCallJoinParams.ts +13 -0
  160. package/src/generated/api/SfuCallRenegotiationOffer.ts +29 -0
  161. package/src/generated/api/SfuCascadePipe.ts +3 -0
  162. package/src/generated/api/SfuCascadeStatus.ts +7 -0
  163. package/src/generated/api/SfuConfig.ts +53 -0
  164. package/src/generated/api/SfuDataMessage.ts +23 -0
  165. package/src/generated/api/SfuEnsureMembershipParams.ts +3 -0
  166. package/src/generated/api/SfuMigrateEvent.ts +20 -0
  167. package/src/generated/api/{KeepAliveQueryRequest.ts → SfuNeighbourhoodParams.ts} +1 -1
  168. package/src/generated/api/SfuParticipantQualityPreference.ts +6 -0
  169. package/src/generated/api/{PerspectiveSubscribeQueryResult.ts → SfuPerspectiveParams.ts} +4 -1
  170. package/src/generated/api/SfuQualityPreferenceParams.ts +7 -0
  171. package/src/generated/api/SfuRoomInfo.ts +7 -0
  172. package/src/generated/api/SfuRoomParams.ts +3 -0
  173. package/src/generated/api/SfuRoomParticipantInfo.ts +8 -0
  174. package/src/generated/api/SfuRoomRoster.ts +12 -0
  175. package/src/generated/api/SfuSendDataParams.ts +7 -0
  176. package/src/generated/api/SfuSetConfigParams.ts +4 -0
  177. package/src/generated/api/SfuStatus.ts +24 -0
  178. package/src/generated/api/TrackMapEntry.ts +18 -0
  179. package/src/generated/api/UpdateSubjectRequest.ts +10 -0
  180. package/src/generated/api/index.ts +3 -0
  181. package/src/index.ts +7 -0
  182. package/src/model/Ad4mModel.test.ts +255 -231
  183. package/src/model/Ad4mModel.ts +271 -4
  184. package/src/model/ModelQueryBuilder.ts +103 -310
  185. package/src/model/abstract-classes.test.ts +225 -0
  186. package/src/model/decorators.ts +81 -0
  187. package/src/model/shacl-gen.ts +13 -0
  188. package/src/model/types.ts +7 -0
  189. package/src/neighbourhood/MeshManager.test.ts +2640 -0
  190. package/src/neighbourhood/MeshManager.ts +1350 -0
  191. package/src/neighbourhood/NeighbourhoodClient.ts +271 -0
  192. package/src/neighbourhood/NeighbourhoodProxy.test.ts +23 -0
  193. package/src/neighbourhood/NeighbourhoodProxy.ts +247 -1
  194. package/src/neighbourhood/Session.test.ts +800 -0
  195. package/src/neighbourhood/Session.ts +525 -0
  196. package/src/neighbourhood/SfuManager.test.ts +677 -0
  197. package/src/neighbourhood/SfuManager.ts +803 -0
  198. package/src/neighbourhood/SfuTypes.ts +40 -0
  199. package/src/perspectives/FlowInstance.ts +108 -31
  200. package/src/perspectives/FlowModels.ts +8 -18
  201. package/src/perspectives/LiveQuery.test.ts +197 -0
  202. package/src/perspectives/LiveQuery.ts +189 -0
  203. package/src/perspectives/PerspectiveClient.ts +51 -51
  204. package/src/perspectives/PerspectiveProxy.test.ts +85 -401
  205. package/src/perspectives/PerspectiveProxy.ts +126 -536
  206. package/src/perspectives/TextContent.test.ts +123 -0
  207. package/src/perspectives/TextContent.ts +36 -0
  208. package/src/perspectives/WakerSubscriptionManager.test.ts +88 -6
  209. package/src/perspectives/WakerSubscriptionManager.ts +69 -18
  210. package/src/shacl/SHACLFlow.ts +7 -4
  211. package/src/shacl/SHACLShape.test.ts +2 -1
  212. package/src/shacl/SHACLShape.ts +49 -0
  213. package/lib/src/generated/api/KeepAliveQueryRequest.d.ts +0 -3
  214. package/lib/src/generated/api/PerspectiveModelSubscribeResult.d.ts +0 -7
  215. package/lib/src/generated/api/PerspectiveQuerySubscriptionFilter.d.ts +0 -6
  216. package/lib/src/generated/api/PerspectiveSubscribeQueryResult.d.ts +0 -4
  217. package/src/generated/api/PerspectiveModelSubscribeResult.ts +0 -6
  218. package/src/generated/api/PerspectiveQuerySubscriptionFilter.ts +0 -3
  219. /package/lib/src/generated/api/{KeepAliveQueryRequest.js → AgentsByDidsRequest.js} +0 -0
  220. /package/lib/src/generated/api/{PerspectiveModelSubscribeResult.js → CallSessionInfo.js} +0 -0
  221. /package/lib/src/generated/api/{PerspectiveQuerySubscriptionFilter.js → DiscardBatchRequest.js} +0 -0
  222. /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.
@@ -355,7 +367,7 @@ export class ModelQueryBuilder {
355
367
  * Shared query execution logic — routes through the executor-side modelQuery endpoint.
356
368
  */
357
369
  async executeSparqlQuery() {
358
- const { results } = await this.ctor.executeModelQuery(this.perspective, this.queryParams, this.modelClassName);
370
+ const { results } = await this.execute(this.queryParams);
359
371
  return results;
360
372
  }
361
373
  /**
@@ -407,100 +419,27 @@ export class ModelQueryBuilder {
407
419
  * ```
408
420
  *
409
421
  */
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) => {
422
+ async subscribe(callback) {
423
+ this.dispose();
424
+ const parseResults = (raw) => this.parse(raw);
425
+ // Suppress callbacks whose parsed results equal the last ones emitted.
426
+ const fingerprint = (results) => JSON.stringify(results, (_, v) => (typeof v === 'function' ? undefined : v));
427
+ let lastFingerprint = null;
428
+ const { initial } = await this.live(this.queryParams, (raw) => {
443
429
  try {
444
- const results = parseResults(rawResult);
445
- const fp = buildFingerprint(results);
446
- if (fp === lastResultFingerprint) {
430
+ const results = parseResults(raw);
431
+ const fp = fingerprint(results);
432
+ if (fp === lastFingerprint)
447
433
  return;
448
- }
449
- lastResultFingerprint = fp;
434
+ lastFingerprint = fp;
450
435
  callback(results);
451
436
  }
452
437
  catch (e) {
453
438
  console.error('Model subscription update parse error:', e);
454
439
  }
455
440
  });
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
- };
441
+ const initialResults = parseResults(initial);
442
+ lastFingerprint = fingerprint(initialResults);
504
443
  // Take snapshots for dirty tracking
505
444
  for (const inst of initialResults) {
506
445
  inst.takeSnapshot?.(this.queryParams.include);
@@ -527,7 +466,7 @@ export class ModelQueryBuilder {
527
466
  * ```
528
467
  */
529
468
  async count() {
530
- const { totalCount } = await this.ctor.executeModelQuery(this.perspective, { ...this.queryParams, limit: 0 }, this.modelClassName);
469
+ const { totalCount } = await this.execute({ ...this.queryParams, limit: 0 });
531
470
  return totalCount;
532
471
  }
533
472
  /**
@@ -565,77 +504,10 @@ export class ModelQueryBuilder {
565
504
  * ```
566
505
  *
567
506
  */
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;
507
+ async countSubscribe(callback) {
508
+ this.dispose();
509
+ const { initial } = await this.live({ ...this.queryParams, limit: 0 }, (raw) => callback(raw.totalCount ?? 0));
510
+ return initial.totalCount ?? 0;
639
511
  }
640
512
  /**
641
513
  * Subscribes to count updates using SPARQL.
@@ -661,7 +533,7 @@ export class ModelQueryBuilder {
661
533
  */
662
534
  async paginate(pageSize, pageNumber) {
663
535
  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);
536
+ const { results, totalCount } = await this.execute(paginationQuery);
665
537
  return { results, totalCount, pageSize, pageNumber };
666
538
  }
667
539
  /**
@@ -701,24 +573,14 @@ export class ModelQueryBuilder {
701
573
  * ```
702
574
  *
703
575
  */
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;
576
+ async paginateSubscribe(pageSize, pageNumber, callback) {
577
+ // Clean up any existing subscription
578
+ this.dispose();
714
579
  // 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.
580
+ // detects changes anywhere in the dataset; each change re-reads the page.
717
581
  const subscriptionParams = { ...(this.queryParams || {}) };
718
582
  delete subscriptionParams.limit;
719
583
  delete subscriptionParams.offset;
720
- const { className, queryJson } = ctor.prepareModelQueryParams(subscriptionParams, this.modelClassName);
721
- const { subscriptionId } = await this.perspective.modelSubscribe(className, queryJson);
722
584
  // Build the paginated query for Rust endpoint (count: true fetches both results and totalCount in one call)
723
585
  const paginatedQuery = {
724
586
  ...(this.queryParams || {}),
@@ -738,90 +600,46 @@ export class ModelQueryBuilder {
738
600
  let disposed = false;
739
601
  let fetching = false;
740
602
  let pending = false;
741
- let coalesced = 0;
742
603
  const processResults = async () => {
743
604
  if (disposed)
744
605
  return;
745
606
  if (fetching) {
746
607
  pending = true;
747
- coalesced++;
748
608
  return;
749
609
  }
750
610
  fetching = true;
751
611
  try {
752
- const { results, totalCount } = await ctor.executeModelQuery(this.perspective, paginatedQuery, this.modelClassName);
612
+ const { results, totalCount } = await this.execute(paginatedQuery);
753
613
  if (!disposed)
754
614
  callback({ results, totalCount, pageSize, pageNumber });
755
615
  }
756
616
  finally {
757
617
  fetching = false;
758
618
  if (pending) {
759
- const dispatches = coalesced;
760
619
  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
620
  // Detached from the caller's promise: needs its own handler, or a
770
621
  // rejection here is unhandled.
771
622
  processResults().catch(e => console.error('Paginate subscription error:', e));
772
623
  }
773
624
  }
774
625
  };
775
- const unsubscribe = this.perspective.client.subscribeToQueryUpdates(subscriptionId, (rawResult) => {
776
- console.debug(`[ModelQueryBuilder.paginateSubscribe] Update received for ${subscriptionId}, re-fetching paginated data...`);
626
+ const { live } = await this.live(subscriptionParams, () => {
777
627
  processResults().catch(e => console.error('Paginate subscription error:', e));
778
628
  });
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
- };
629
+ if (this.currentSubscription === live) {
630
+ this.currentSubscription = {
631
+ dispose: () => {
632
+ disposed = true;
633
+ live.dispose();
634
+ },
635
+ };
636
+ }
637
+ else {
638
+ // Disposed, or overtaken by a later subscribe, while opening: deliver nothing.
639
+ disposed = true;
640
+ }
823
641
  // Initial fetch (single call with count: true)
824
- const { results, totalCount } = await ctor.executeModelQuery(this.perspective, paginatedQuery, this.modelClassName);
642
+ const { results, totalCount } = await this.execute(paginatedQuery);
825
643
  return { results, totalCount, pageSize, pageNumber };
826
644
  }
827
645
  /**
@@ -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.
@@ -46,7 +46,9 @@ seedCache?: (partial: {
46
46
  * this class. Attached to the SHACL shape node and re-emitted as
47
47
  * an `ad4m://interpretation_hint` link by `SHACLShape.toLinks()`.
48
48
  */
49
- interpretationHint?: string): {
49
+ interpretationHint?: string,
50
+ /** `@Model({ abstract: true })`: emitted as one `ad4m://abstract` link. */
51
+ isAbstract?: boolean): {
50
52
  shape: SHACLShape;
51
53
  name: string;
52
54
  };