@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
@@ -7,6 +7,7 @@
7
7
 
8
8
  import type { Ad4mModel } from "./Ad4mModel";
9
9
  import type { LinkStatus, PerspectiveProxy } from "../perspectives/PerspectiveProxy";
10
+ import { LiveQuery } from "../perspectives/LiveQuery";
10
11
  import type {
11
12
  Where, Order, IncludeMap, Query,
12
13
  ResultsWithTotalCount, PaginationResult,
@@ -38,53 +39,71 @@ export class ModelQueryBuilder<T extends Ad4mModel> {
38
39
  private queryParams: Query = {};
39
40
  private modelClassName: string | null = null;
40
41
  private ctor: typeof Ad4mModel;
41
- private currentSubscription?: { dispose: () => Promise<void> };
42
- /** Tail of the subscribe/dispose chain; see `serialize()`. */
43
- private subscriptionChain: Promise<void> = Promise.resolve();
42
+ private currentSubscription?: { dispose(): void };
44
43
 
45
- constructor(perspective: PerspectiveProxy, ctor: typeof Ad4mModel, query?: Query) {
44
+ /** Set for a query over several classes (`Ad4mModel.queryOf`, #1238). */
45
+ private unionClasses?: (typeof Ad4mModel)[];
46
+
47
+ constructor(perspective: PerspectiveProxy, ctor: typeof Ad4mModel, query?: Query, unionClasses?: (typeof Ad4mModel)[]) {
46
48
  this.perspective = perspective;
47
49
  this.ctor = ctor;
48
50
  if (query) this.queryParams = query;
51
+ if (unionClasses) this.unionClasses = unionClasses;
49
52
  }
50
53
 
51
- /**
52
- * Disposes of the current subscription if one exists.
53
- *
54
- * This method:
55
- * 1. Stops the keepalive signals to the subscription
56
- * 2. Unsubscribes from subscription updates
57
- * 3. Notifies the backend to clean up subscription resources
58
- * 4. Clears the subscription reference
59
- *
60
- * Steps 1, 2 and 4 happen synchronously, so `builder.dispose()` without
61
- * `await` is still a complete local cleanup. The returned promise resolves
62
- * once the executor has released this subscriber's hold on the subscription
63
- * (it never rejects). The executor shares one subscription between all
64
- * subscribers of the same query and only drops it when the last one
65
- * disposes, so disposing here does not interrupt another builder's updates.
66
- *
67
- * You should call this method when you're done with a subscription
68
- * to prevent memory leaks and ensure proper cleanup.
69
- */
70
- dispose(): Promise<void> {
71
- const current = this.currentSubscription;
72
- this.currentSubscription = undefined;
73
- return current ? current.dispose() : Promise.resolve();
54
+ /** The wire parameters for `params`: one class, or the union's class list. */
55
+ private prepare(params: Query): { className: string | string[]; queryJson: string } {
56
+ if (this.unionClasses) {
57
+ const { classNames, queryJson } = (this.ctor as any).prepareUnionQueryParams(this.unionClasses, params);
58
+ return { className: classNames, queryJson };
59
+ }
60
+ return (this.ctor as any).prepareModelQueryParams(params, this.modelClassName);
74
61
  }
75
62
 
76
- /**
77
- * Runs one subscribe variant after every earlier one on this builder has
78
- * finished. Each variant disposes the previous subscription (awaiting the
79
- * executor) and then registers its own; two overlapping calls would both
80
- * find no current subscription, both register, and the builder could only
81
- * ever dispose the last one. Serializing keeps exactly one subscription
82
- * per builder.
83
- */
84
- private serialize<R>(run: () => Promise<R>): Promise<R> {
85
- const result = this.subscriptionChain.then(run, run);
86
- this.subscriptionChain = result.then(() => {}, () => {});
87
- return result;
63
+ /** Run `params` once and build model instances from the rows. */
64
+ private execute(params: Query): Promise<ResultsWithTotalCount<T>> {
65
+ if (this.unionClasses) {
66
+ return (this.ctor as any).executeUnionQuery(this.perspective, this.unionClasses, params);
67
+ }
68
+ return (this.ctor as any).executeModelQuery(this.perspective, params, this.modelClassName);
69
+ }
70
+
71
+ /** Build model instances from a raw result pushed by a subscription. */
72
+ private parse(raw: any): T[] {
73
+ const { include, properties } = this.queryParams;
74
+ if (this.unionClasses) {
75
+ return (this.ctor as any).parseUnionResult(this.unionClasses, this.perspective, raw, include, properties);
76
+ }
77
+ return (this.ctor as any).parseModelResult(this.perspective, raw, include, properties);
78
+ }
79
+
80
+ /** Ends the current subscription, if any, on the client and the executor. */
81
+ dispose() {
82
+ if (this.currentSubscription) {
83
+ this.currentSubscription.dispose();
84
+ this.currentSubscription = undefined;
85
+ }
86
+ }
87
+
88
+ /** Open a live model query for `params` as the current subscription.
89
+ * Resolves with it and the raw initial result; `onResult` gets every later one.
90
+ * A failed open ends only its own query: a later call may already own
91
+ * `currentSubscription`. */
92
+ private async live(params: Query, onResult: (raw: any) => void): Promise<{ live: LiveQuery; initial: any }> {
93
+ const { className, queryJson } = this.prepare(params);
94
+ const live = new LiveQuery(
95
+ this.perspective.client, this.perspective.uuid,
96
+ () => this.perspective.modelSubscribe(className, queryJson),
97
+ onResult,
98
+ );
99
+ this.currentSubscription = live;
100
+ try {
101
+ return { live, initial: await live.start() };
102
+ } catch (e) {
103
+ live.dispose();
104
+ if (this.currentSubscription === live) this.currentSubscription = undefined;
105
+ throw e;
106
+ }
88
107
  }
89
108
 
90
109
  /**
@@ -388,7 +407,7 @@ export class ModelQueryBuilder<T extends Ad4mModel> {
388
407
  * Shared query execution logic — routes through the executor-side modelQuery endpoint.
389
408
  */
390
409
  private async executeSparqlQuery(): Promise<T[]> {
391
- const { results } = await (this.ctor as any).executeModelQuery(this.perspective, this.queryParams, this.modelClassName);
410
+ const { results } = await this.execute(this.queryParams);
392
411
  return results;
393
412
  }
394
413
 
@@ -442,112 +461,29 @@ export class ModelQueryBuilder<T extends Ad4mModel> {
442
461
  * ```
443
462
  *
444
463
  */
445
- subscribe(callback: (results: T[]) => void): Promise<T[]> {
446
- return this.serialize(() => this.subscribeNow(callback));
447
- }
464
+ async subscribe(callback: (results: T[]) => void): Promise<T[]> {
465
+ this.dispose();
448
466
 
449
- private async subscribeNow(callback: (results: T[]) => void): Promise<T[]> {
450
- // Clean up any existing subscription. Awaited so the executor has
451
- // released the previous hold before the new registration arrives: the
452
- // executor hands out one shared id per query, and a dispose landing after
453
- // the re-subscribe would otherwise release the id just handed back.
454
- await this.dispose();
467
+ const parseResults = (raw: any): T[] => this.parse(raw);
455
468
 
456
- const ctor = this.ctor;
469
+ // Suppress callbacks whose parsed results equal the last ones emitted.
470
+ const fingerprint = (results: any[]) =>
471
+ JSON.stringify(results, (_, v) => (typeof v === 'function' ? undefined : v));
472
+ let lastFingerprint: string | null = null;
457
473
 
458
- // Build the model query params (className, queryJson). The executor
459
- // resolves the shape from the perspective's SHACL triples.
460
- const { className, queryJson } = (ctor as any).prepareModelQueryParams(
461
- this.queryParams, this.modelClassName
462
- );
463
-
464
- // Register model subscription via Rust — this builds trigger SPARQL internally,
465
- // registers the subscription, and runs the initial query in one call.
466
- const { subscriptionId, result: initialModelResult } = await this.perspective.modelSubscribe(
467
- className, queryJson
468
- );
469
-
470
- // Convert JSON instances to model class instances
471
- const parseResults = (raw: any): T[] => {
472
- return (ctor as any).parseModelResult(this.perspective, raw, this.queryParams.include, this.queryParams.properties);
473
- };
474
-
475
- // Transforms are now applied by the Rust executor during hydration
476
- const initialResults = parseResults(initialModelResult);
477
-
478
- // Track last emitted result fingerprint to suppress duplicate callbacks
479
- let lastResultFingerprint: string | null = null;
480
- const buildFingerprint = (results: any[]) => {
481
- if (results.length === 0) return '0:';
482
- return JSON.stringify(results, (_, v) =>
483
- typeof v === 'function' ? undefined : v
484
- );
485
- };
486
- lastResultFingerprint = buildFingerprint(initialResults);
487
-
488
- // Listen for subscription updates via the same WS-RPC subscription channel.
489
- // When Rust re-runs the model query and finds changed results, it pushes them.
490
- const unsubscribe = this.perspective.client.subscribeToQueryUpdates(
491
- subscriptionId,
492
- (rawResult: any) => {
493
- try {
494
- const results = parseResults(rawResult);
495
- const fp = buildFingerprint(results);
496
- if (fp === lastResultFingerprint) {
497
- return;
498
- }
499
- lastResultFingerprint = fp;
500
- callback(results);
501
- } catch (e) {
502
- console.error('Model subscription update parse error:', e);
503
- }
504
- },
505
- );
506
-
507
- // Set up keepalive with recovery — uses setTimeout loop so we can
508
- // break out and resubscribe when the server evicts the subscription.
509
- let disposed = false;
510
- let keepaliveTimer: ReturnType<typeof setTimeout> | undefined;
511
- let resubscribeAttempts = 0;
512
- const MAX_RESUBSCRIBE_ATTEMPTS = 5;
513
- const keepaliveLoop = async () => {
514
- if (disposed) return;
474
+ const { initial } = await this.live(this.queryParams, (raw) => {
515
475
  try {
516
- await this.perspective.client.keepAliveQuery(this.perspective.uuid, subscriptionId);
517
- resubscribeAttempts = 0; // Reset on success
518
- } catch (e: any) {
519
- console.warn(`Model subscription keepalive failed for ${subscriptionId}:`, e);
520
- if (!disposed && resubscribeAttempts < MAX_RESUBSCRIBE_ATTEMPTS) {
521
- resubscribeAttempts++;
522
- const backoffMs = Math.min(1000 * Math.pow(2, resubscribeAttempts), 60000);
523
- console.warn(`Resubscribing (attempt ${resubscribeAttempts}/${MAX_RESUBSCRIBE_ATTEMPTS}, backoff ${backoffMs}ms)...`);
524
- await new Promise(r => setTimeout(r, backoffMs));
525
- try {
526
- unsubscribe();
527
- await this.subscribe(callback);
528
- } catch (resubErr) {
529
- console.error('Model subscription resubscribe failed:', resubErr);
530
- }
531
- } else if (resubscribeAttempts >= MAX_RESUBSCRIBE_ATTEMPTS) {
532
- console.error(`Model subscription ${subscriptionId}: max resubscribe attempts reached, giving up.`);
533
- }
534
- return; // new subscription owns its own keepalive loop
476
+ const results = parseResults(raw);
477
+ const fp = fingerprint(results);
478
+ if (fp === lastFingerprint) return;
479
+ lastFingerprint = fp;
480
+ callback(results);
481
+ } catch (e) {
482
+ console.error('Model subscription update parse error:', e);
535
483
  }
536
- if (!disposed) {
537
- keepaliveTimer = setTimeout(keepaliveLoop, 30000);
538
- }
539
- };
540
- keepaliveTimer = setTimeout(keepaliveLoop, 30000);
541
-
542
- // Store dispose function
543
- this.currentSubscription = {
544
- dispose: () => {
545
- disposed = true;
546
- if (keepaliveTimer) clearTimeout(keepaliveTimer);
547
- unsubscribe();
548
- return this.perspective.client.disposeQuerySubscription(this.perspective.uuid, subscriptionId).then(() => {}, () => {});
549
- },
550
- };
484
+ });
485
+ const initialResults = parseResults(initial);
486
+ lastFingerprint = fingerprint(initialResults);
551
487
 
552
488
  // Take snapshots for dirty tracking
553
489
  for (const inst of initialResults) {
@@ -578,7 +514,7 @@ export class ModelQueryBuilder<T extends Ad4mModel> {
578
514
  * ```
579
515
  */
580
516
  async count(): Promise<number> {
581
- const { totalCount } = await (this.ctor as any).executeModelQuery(this.perspective, { ...this.queryParams, limit: 0 }, this.modelClassName);
517
+ const { totalCount } = await this.execute({ ...this.queryParams, limit: 0 });
582
518
  return totalCount;
583
519
  }
584
520
 
@@ -618,87 +554,10 @@ export class ModelQueryBuilder<T extends Ad4mModel> {
618
554
  * ```
619
555
  *
620
556
  */
621
- countSubscribe(callback: (count: number) => void): Promise<number> {
622
- return this.serialize(() => this.countSubscribeNow(callback));
623
- }
624
-
625
- private async countSubscribeNow(callback: (count: number) => void): Promise<number> {
626
- // Clean up any existing subscription. Awaited so the executor has
627
- // released the previous hold before the new registration arrives: the
628
- // executor hands out one shared id per query, and a dispose landing after
629
- // the re-subscribe would otherwise release the id just handed back.
630
- await this.dispose();
631
-
632
- const countParams = { ...this.queryParams, limit: 0 };
633
- const { className, queryJson } = (this.ctor as any).prepareModelQueryParams(
634
- countParams, this.modelClassName
635
- );
636
-
637
- const { subscriptionId, result: initialModelResult } = await this.perspective.modelSubscribe(
638
- className, queryJson
639
- );
640
-
641
- const parseCount = (raw: any): number => {
642
- const data = typeof raw === 'string' ? JSON.parse(raw) : raw;
643
- return data.totalCount ?? 0;
644
- };
645
-
646
- const initialCount = parseCount(initialModelResult);
647
-
648
- const unsubscribe = this.perspective.client.subscribeToQueryUpdates(
649
- subscriptionId,
650
- (rawResult: any) => {
651
- try {
652
- callback(parseCount(rawResult));
653
- } catch (e) {
654
- console.error('Count subscription update parse error:', e);
655
- }
656
- },
657
- );
658
-
659
- let disposed = false;
660
- let keepaliveTimer: ReturnType<typeof setTimeout> | undefined;
661
- let resubscribeAttempts = 0;
662
- const MAX_RESUBSCRIBE_ATTEMPTS = 5;
663
- const keepaliveLoop = async () => {
664
- if (disposed) return;
665
- try {
666
- await this.perspective.client.keepAliveQuery(this.perspective.uuid, subscriptionId);
667
- resubscribeAttempts = 0;
668
- } catch (e: any) {
669
- console.warn(`Count subscription keepalive failed for ${subscriptionId}:`, e);
670
- if (!disposed && resubscribeAttempts < MAX_RESUBSCRIBE_ATTEMPTS) {
671
- resubscribeAttempts++;
672
- const backoffMs = Math.min(1000 * Math.pow(2, resubscribeAttempts), 60000);
673
- console.warn(`Count resubscribing (attempt ${resubscribeAttempts}/${MAX_RESUBSCRIBE_ATTEMPTS}, backoff ${backoffMs}ms)...`);
674
- await new Promise(r => setTimeout(r, backoffMs));
675
- try {
676
- unsubscribe();
677
- await this.countSubscribe(callback);
678
- } catch (resubErr) {
679
- console.error('Count subscription resubscribe failed:', resubErr);
680
- }
681
- } else if (resubscribeAttempts >= MAX_RESUBSCRIBE_ATTEMPTS) {
682
- console.error(`Count subscription ${subscriptionId}: max resubscribe attempts reached, giving up.`);
683
- }
684
- return;
685
- }
686
- if (!disposed) {
687
- keepaliveTimer = setTimeout(keepaliveLoop, 30000);
688
- }
689
- };
690
- keepaliveTimer = setTimeout(keepaliveLoop, 30000);
691
-
692
- this.currentSubscription = {
693
- dispose: () => {
694
- disposed = true;
695
- if (keepaliveTimer) clearTimeout(keepaliveTimer);
696
- unsubscribe();
697
- return this.perspective.client.disposeQuerySubscription(this.perspective.uuid, subscriptionId).then(() => {}, () => {});
698
- },
699
- };
700
-
701
- return initialCount;
557
+ async countSubscribe(callback: (count: number) => void): Promise<number> {
558
+ this.dispose();
559
+ const { initial } = await this.live({ ...this.queryParams, limit: 0 }, (raw) => callback(raw.totalCount ?? 0));
560
+ return initial.totalCount ?? 0;
702
561
  }
703
562
 
704
563
  /**
@@ -726,7 +585,7 @@ export class ModelQueryBuilder<T extends Ad4mModel> {
726
585
  */
727
586
  async paginate(pageSize: number, pageNumber: number): Promise<PaginationResult<T>> {
728
587
  const paginationQuery = { ...(this.queryParams || {}), limit: pageSize, offset: pageSize * (pageNumber - 1), count: true };
729
- const { results, totalCount } = await (this.ctor as any).executeModelQuery(this.perspective, paginationQuery, this.modelClassName);
588
+ const { results, totalCount } = await this.execute(paginationQuery);
730
589
  return { results, totalCount, pageSize, pageNumber };
731
590
  }
732
591
 
@@ -768,40 +627,19 @@ export class ModelQueryBuilder<T extends Ad4mModel> {
768
627
  * ```
769
628
  *
770
629
  */
771
- paginateSubscribe(
772
- pageSize: number,
773
- pageNumber: number,
774
- callback: (results: PaginationResult<T>) => void
775
- ): Promise<PaginationResult<T>> {
776
- return this.serialize(() => this.paginateSubscribeNow(pageSize, pageNumber, callback));
777
- }
778
-
779
- private async paginateSubscribeNow(
630
+ async paginateSubscribe(
780
631
  pageSize: number,
781
632
  pageNumber: number,
782
633
  callback: (results: PaginationResult<T>) => void
783
634
  ): Promise<PaginationResult<T>> {
784
- // Clean up any existing subscription. Awaited so the executor has
785
- // released the previous hold before the new registration arrives: the
786
- // executor hands out one shared id per query, and a dispose landing after
787
- // the re-subscribe would otherwise release the id just handed back.
788
- await this.dispose();
789
-
790
- const ctor = this.ctor;
635
+ // Clean up any existing subscription
636
+ this.dispose();
791
637
 
792
638
  // Subscribe to the full result set (no limit/offset) so the subscription
793
- // detects changes anywhere in the dataset. Rust builds trigger SPARQL
794
- // from the shape predicates.
639
+ // detects changes anywhere in the dataset; each change re-reads the page.
795
640
  const subscriptionParams = { ...(this.queryParams || {}) };
796
641
  delete subscriptionParams.limit;
797
642
  delete subscriptionParams.offset;
798
- const { className, queryJson } = (ctor as any).prepareModelQueryParams(
799
- subscriptionParams, this.modelClassName
800
- );
801
-
802
- const { subscriptionId } = await this.perspective.modelSubscribe(
803
- className, queryJson
804
- );
805
643
 
806
644
  // Build the paginated query for Rust endpoint (count: true fetches both results and totalCount in one call)
807
645
  const paginatedQuery = {
@@ -823,31 +661,20 @@ export class ModelQueryBuilder<T extends Ad4mModel> {
823
661
  let disposed = false;
824
662
  let fetching = false;
825
663
  let pending = false;
826
- let coalesced = 0;
827
664
  const processResults = async (): Promise<void> => {
828
665
  if (disposed) return;
829
666
  if (fetching) {
830
667
  pending = true;
831
- coalesced++;
832
668
  return;
833
669
  }
834
670
  fetching = true;
835
671
  try {
836
- const { results, totalCount } = await (ctor as any).executeModelQuery(this.perspective, paginatedQuery, this.modelClassName);
672
+ const { results, totalCount } = await this.execute(paginatedQuery);
837
673
  if (!disposed) callback({ results, totalCount, pageSize, pageNumber });
838
674
  } finally {
839
675
  fetching = false;
840
676
  if (pending) {
841
- const dispatches = coalesced;
842
677
  pending = false;
843
- coalesced = 0;
844
- // Whether a trailing fetch actually starts is decided by the entry
845
- // guard at the top of processResults, which returns when disposed.
846
- // Log only what that guard will let through, or the dispose path
847
- // announces a fetch it then drops.
848
- if (!disposed) {
849
- console.debug(`[ModelQueryBuilder.paginateSubscribe] ${dispatches} dispatch(es) during read for ${subscriptionId}, coalesced into one trailing fetch`);
850
- }
851
678
  // Detached from the caller's promise: needs its own handler, or a
852
679
  // rejection here is unhandled.
853
680
  processResults().catch(e => console.error('Paginate subscription error:', e));
@@ -855,57 +682,23 @@ export class ModelQueryBuilder<T extends Ad4mModel> {
855
682
  }
856
683
  };
857
684
 
858
- const unsubscribe = this.perspective.client.subscribeToQueryUpdates(
859
- subscriptionId,
860
- (rawResult: any) => {
861
- console.debug(`[ModelQueryBuilder.paginateSubscribe] Update received for ${subscriptionId}, re-fetching paginated data...`);
862
- processResults().catch(e => console.error('Paginate subscription error:', e));
863
- },
864
- );
865
-
866
- let keepaliveTimer: ReturnType<typeof setTimeout> | undefined;
867
- let resubscribeAttempts = 0;
868
- const MAX_RESUBSCRIBE_ATTEMPTS = 5;
869
- const keepaliveLoop = async () => {
870
- if (disposed) return;
871
- try {
872
- await this.perspective.client.keepAliveQuery(this.perspective.uuid, subscriptionId);
873
- resubscribeAttempts = 0;
874
- } catch (e: any) {
875
- console.warn(`Paginate subscription keepalive failed for ${subscriptionId}:`, e);
876
- if (!disposed && resubscribeAttempts < MAX_RESUBSCRIBE_ATTEMPTS) {
877
- resubscribeAttempts++;
878
- const backoffMs = Math.min(1000 * Math.pow(2, resubscribeAttempts), 60000);
879
- console.warn(`Paginate resubscribing (attempt ${resubscribeAttempts}/${MAX_RESUBSCRIBE_ATTEMPTS}, backoff ${backoffMs}ms)...`);
880
- await new Promise(r => setTimeout(r, backoffMs));
881
- try {
882
- unsubscribe();
883
- await this.paginateSubscribe(pageSize, pageNumber, callback);
884
- } catch (resubErr) {
885
- console.error('Paginate subscription resubscribe failed:', resubErr);
886
- }
887
- } else if (resubscribeAttempts >= MAX_RESUBSCRIBE_ATTEMPTS) {
888
- console.error(`Paginate subscription ${subscriptionId}: max resubscribe attempts reached, giving up.`);
889
- }
890
- return;
891
- }
892
- if (!disposed) {
893
- keepaliveTimer = setTimeout(keepaliveLoop, 30000);
894
- }
895
- };
896
- keepaliveTimer = setTimeout(keepaliveLoop, 30000);
897
-
898
- this.currentSubscription = {
899
- dispose: () => {
900
- disposed = true;
901
- if (keepaliveTimer) clearTimeout(keepaliveTimer);
902
- unsubscribe();
903
- return this.perspective.client.disposeQuerySubscription(this.perspective.uuid, subscriptionId).then(() => {}, () => {});
904
- },
905
- };
685
+ const { live } = await this.live(subscriptionParams, () => {
686
+ processResults().catch(e => console.error('Paginate subscription error:', e));
687
+ });
688
+ if (this.currentSubscription === live) {
689
+ this.currentSubscription = {
690
+ dispose: () => {
691
+ disposed = true;
692
+ live.dispose();
693
+ },
694
+ };
695
+ } else {
696
+ // Disposed, or overtaken by a later subscribe, while opening: deliver nothing.
697
+ disposed = true;
698
+ }
906
699
 
907
700
  // Initial fetch (single call with count: true)
908
- const { results, totalCount } = await (ctor as any).executeModelQuery(this.perspective, paginatedQuery, this.modelClassName);
701
+ const { results, totalCount } = await this.execute(paginatedQuery);
909
702
  return { results, totalCount, pageSize, pageNumber };
910
703
  }
911
704