@coasys/ad4m-connect 0.13.1-staging.5 → 0.13.1-staging.6

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.
package/dist/core.js CHANGED
@@ -39,7 +39,7 @@ var __async = (__this, __arguments, generator) => {
39
39
  };
40
40
 
41
41
  // ../package.json
42
- var version = "0.13.1-staging.5";
42
+ var version = "0.13.1-staging.6";
43
43
 
44
44
  // src/utils.ts
45
45
  function isEmbedded() {
@@ -368,6 +368,18 @@ var INITIAL_RECONNECT_DELAY_MS = 500;
368
368
  var MAX_RECONNECT_DELAY_MS = 3e4;
369
369
  var WATCH_RETRY_DELAY_MS = 1e3;
370
370
  var MAX_WATCH_RETRIES = 5;
371
+ var PING_INTERVAL_MS = 1e4;
372
+ var SLOWEST_LINK_BYTES_PER_MS = 16;
373
+ var PONG_RETURN_MS = 5e3;
374
+ function utf8Length(text) {
375
+ let bytes = text.length;
376
+ for (let i = 0; i < text.length; i++) {
377
+ const unit = text.charCodeAt(i);
378
+ if (unit >= 128)
379
+ bytes += unit < 2048 || unit >= 55296 && unit <= 57343 ? 1 : 2;
380
+ }
381
+ return bytes;
382
+ }
371
383
  var _idCounter2 = 0;
372
384
  function nextId() {
373
385
  return String(++_idCounter2);
@@ -389,12 +401,21 @@ var ApiClient = class {
389
401
  this._wsReconnectTimer = null;
390
402
  this._wsReconnectDelay = INITIAL_RECONNECT_DELAY_MS;
391
403
  this._wsPingTimer = null;
404
+ this._wsPingedAt = null;
405
+ this._wsPingArrivesBy = 0;
406
+ this._wsSentBy = 0;
392
407
  this._watching = "{}";
393
408
  this._watchScheduled = false;
394
409
  this._watchDone = Promise.resolve();
395
410
  this._watchSent = Promise.resolve();
396
411
  this._watchRetries = 0;
397
412
  this._watchRetryTimer = null;
413
+ this._wakeListening = false;
414
+ this._onWake = (event) => {
415
+ if (event.type === "visibilitychange" && typeof document !== "undefined" && document.visibilityState !== "visible")
416
+ return;
417
+ this.reconnectNow();
418
+ };
398
419
  this.baseUrl = baseUrl;
399
420
  this.token = token;
400
421
  this._webSocketImpl = webSocketImpl;
@@ -419,6 +440,7 @@ var ApiClient = class {
419
440
  return;
420
441
  if (this._authFailed !== null)
421
442
  throw new RpcError(401, this._authFailed);
443
+ this._cancelReconnect();
422
444
  const WsImpl = this._webSocketImpl ?? globalThis.WebSocket;
423
445
  const ws = new WsImpl(this._getWsUrl());
424
446
  this._ws = ws;
@@ -439,6 +461,8 @@ var ApiClient = class {
439
461
  this._wsOpen.catch(() => {
440
462
  });
441
463
  ws.onmessage = (event) => {
464
+ if (this._ws === ws)
465
+ this._wsPingedAt = null;
442
466
  let parsed;
443
467
  try {
444
468
  parsed = JSON.parse(event.data);
@@ -461,7 +485,7 @@ var ApiClient = class {
461
485
  this._failAuth(rpcError.body);
462
486
  return;
463
487
  }
464
- if (parsed.type === "pong")
488
+ if (parsed.type === "pong" || this._ws !== ws)
465
489
  return;
466
490
  const perspective = parsed.perspectiveUuid;
467
491
  const regs = this._handlers.get(parsed.type);
@@ -481,13 +505,13 @@ var ApiClient = class {
481
505
  if (this._ws !== ws)
482
506
  return;
483
507
  this._wsReconnectDelay = INITIAL_RECONNECT_DELAY_MS;
484
- this._startPing();
508
+ this._startPing(ws);
485
509
  this._watching = "{}";
486
510
  this._watchRetries = 0;
487
511
  this._flushWatch();
488
512
  for (const pending of this._pendingCalls.values()) {
489
513
  if (!pending.sent) {
490
- ws.send(pending.message);
514
+ this._send(ws, pending.message);
491
515
  pending.sent = true;
492
516
  }
493
517
  }
@@ -532,13 +556,36 @@ var ApiClient = class {
532
556
  for (const cb of [...this._authFailedCallbacks])
533
557
  callSafely(cb, "Error in auth-failed callback:", reason);
534
558
  }
535
- _startPing() {
559
+ _startPing(ws) {
536
560
  this._stopPing();
561
+ this._wsPingedAt = null;
562
+ this._wsSentBy = 0;
537
563
  this._wsPingTimer = setInterval(() => {
538
- if (this._ws?.readyState === 1) {
539
- this._ws.send(JSON.stringify({ type: "ping" }));
564
+ if (this._ws !== ws)
565
+ return;
566
+ const ping = JSON.stringify({ type: "ping" });
567
+ if (this._wsPingedAt === null) {
568
+ this._wsPingedAt = performance.now();
569
+ this._send(ws, ping);
570
+ this._wsPingArrivesBy = this._wsSentBy;
571
+ return;
540
572
  }
541
- }, 3e4);
573
+ if (performance.now() >= Math.max(this._wsPingedAt + PING_INTERVAL_MS, this._wsPingArrivesBy + PONG_RETURN_MS)) {
574
+ this._dropSilentSocket(ws);
575
+ return;
576
+ }
577
+ this._send(ws, ping);
578
+ }, PING_INTERVAL_MS);
579
+ }
580
+ _send(ws, text) {
581
+ if (this._ws === ws)
582
+ this._wsSentBy = Math.max(this._wsSentBy, performance.now()) + utf8Length(text) / SLOWEST_LINK_BYTES_PER_MS;
583
+ ws.send(text);
584
+ }
585
+ _dropSilentSocket(ws) {
586
+ console.warn(`WebSocket silent for ${performance.now() - (this._wsPingedAt ?? performance.now())} ms after a ping; reconnecting`);
587
+ this._onClose(ws);
588
+ ws.close();
542
589
  }
543
590
  _stopPing() {
544
591
  if (this._wsPingTimer) {
@@ -553,8 +600,40 @@ var ApiClient = class {
553
600
  this._wsReconnectDelay = Math.min(this._wsReconnectDelay * 2, MAX_RECONNECT_DELAY_MS);
554
601
  this._wsReconnectTimer = setTimeout(() => {
555
602
  this._wsReconnectTimer = null;
603
+ this._listenForWake(false);
556
604
  this._ensureWs();
557
605
  }, delay);
606
+ this._listenForWake(true);
607
+ }
608
+ _cancelReconnect() {
609
+ if (this._wsReconnectTimer) {
610
+ clearTimeout(this._wsReconnectTimer);
611
+ this._wsReconnectTimer = null;
612
+ }
613
+ this._listenForWake(false);
614
+ }
615
+ reconnectNow() {
616
+ if (!this._wsReconnectTimer || this._ws || this._authFailed !== null)
617
+ return;
618
+ this._cancelReconnect();
619
+ this._wsReconnectDelay = INITIAL_RECONNECT_DELAY_MS;
620
+ this._ensureWs();
621
+ }
622
+ _listenForWake(on) {
623
+ if (on === this._wakeListening)
624
+ return;
625
+ const win = typeof window !== "undefined" ? window : void 0;
626
+ if (typeof win?.addEventListener !== "function")
627
+ return;
628
+ const doc = typeof document !== "undefined" && typeof document.addEventListener === "function" ? document : void 0;
629
+ this._wakeListening = on;
630
+ if (on) {
631
+ win.addEventListener("online", this._onWake);
632
+ doc?.addEventListener("visibilitychange", this._onWake);
633
+ } else {
634
+ win.removeEventListener("online", this._onWake);
635
+ doc?.removeEventListener("visibilitychange", this._onWake);
636
+ }
558
637
  }
559
638
  call(method, params, options) {
560
639
  this._flushWatch();
@@ -586,7 +665,7 @@ var ApiClient = class {
586
665
  }, timeoutMs);
587
666
  const onAbort = () => {
588
667
  if (pending.sent && this._ws?.readyState === 1) {
589
- this._ws.send(JSON.stringify({ id: nextId(), type: "request.cancel", params: { targetId: id } }));
668
+ this._send(this._ws, JSON.stringify({ id: nextId(), type: "request.cancel", params: { targetId: id } }));
590
669
  }
591
670
  settle(() => reject(new DOMException("Aborted", "AbortError")));
592
671
  };
@@ -608,7 +687,7 @@ var ApiClient = class {
608
687
  return;
609
688
  }
610
689
  if (this._ws.readyState === 1) {
611
- this._ws.send(message);
690
+ this._send(this._ws, message);
612
691
  pending.sent = true;
613
692
  }
614
693
  });
@@ -708,10 +787,7 @@ var ApiClient = class {
708
787
  clearTimeout(this._watchRetryTimer);
709
788
  this._watchRetryTimer = null;
710
789
  }
711
- if (this._wsReconnectTimer) {
712
- clearTimeout(this._wsReconnectTimer);
713
- this._wsReconnectTimer = null;
714
- }
790
+ this._cancelReconnect();
715
791
  const ws = this._ws;
716
792
  this._ws = null;
717
793
  this._wsOpen = null;
@@ -4849,10 +4925,23 @@ var _LiveQuery_latest;
4849
4925
  var _LiveQuery_buffer;
4850
4926
  var _LiveQuery_unlisten;
4851
4927
  var _LiveQuery_unreconnect;
4928
+ var _LiveQuery_opening;
4929
+ var _LiveQuery_retryTimer;
4930
+ var _LiveQuery_reopening;
4931
+ var _LiveQuery_statusListeners;
4852
4932
  var _LiveQuery_start;
4933
+ var _LiveQuery_reopen;
4934
+ var _LiveQuery_clearRetry;
4935
+ var _LiveQuery_emit;
4853
4936
  var _LiveQuery_replace;
4854
4937
  var _LiveQuery_receive;
4855
4938
  var _LiveQuery_resync;
4939
+ var REOPEN_BASE_DELAY_MS = 1e3;
4940
+ var REOPEN_MAX_DELAY_MS = 6e4;
4941
+ function reopenDelay(failures, random = Math.random) {
4942
+ const ceiling = Math.min(REOPEN_BASE_DELAY_MS * 2 ** Math.max(0, failures - 1), REOPEN_MAX_DELAY_MS);
4943
+ return ceiling / 2 + random() * ceiling / 2;
4944
+ }
4856
4945
  function applyUpdate(result, update) {
4857
4946
  if ("result" in update)
4858
4947
  return update.result;
@@ -4899,14 +4988,19 @@ var LiveQuery = class {
4899
4988
  _LiveQuery_buffer.set(this, null);
4900
4989
  _LiveQuery_unlisten.set(this, void 0);
4901
4990
  _LiveQuery_unreconnect.set(this, void 0);
4991
+ _LiveQuery_opening.set(this, void 0);
4992
+ _LiveQuery_retryTimer.set(this, void 0);
4993
+ _LiveQuery_reopening.set(this, false);
4994
+ _LiveQuery_statusListeners.set(
4995
+ this,
4996
+ /* @__PURE__ */ new Set()
4997
+ );
4902
4998
  __classPrivateFieldSet$7(this, _LiveQuery_client, client, "f");
4903
4999
  __classPrivateFieldSet$7(this, _LiveQuery_uuid, uuid, "f");
4904
5000
  __classPrivateFieldSet$7(this, _LiveQuery_open, open, "f");
4905
5001
  __classPrivateFieldSet$7(this, _LiveQuery_onResult, onResult, "f");
4906
5002
  __classPrivateFieldSet$7(this, _LiveQuery_unlisten, client.onQueryUpdate((update) => __classPrivateFieldGet$7(this, _LiveQuery_instances, "m", _LiveQuery_receive).call(this, update)), "f");
4907
- __classPrivateFieldSet$7(this, _LiveQuery_unreconnect, client.onReconnect(() => {
4908
- this.start().catch((e) => console.error("Error re-opening live query after reconnect:", e));
4909
- }), "f");
5003
+ __classPrivateFieldSet$7(this, _LiveQuery_unreconnect, client.onReconnect(() => __classPrivateFieldGet$7(this, _LiveQuery_instances, "m", _LiveQuery_reopen).call(this)), "f");
4910
5004
  }
4911
5005
  get id() {
4912
5006
  return __classPrivateFieldGet$7(this, _LiveQuery_id, "f");
@@ -4914,31 +5008,48 @@ var LiveQuery = class {
4914
5008
  get result() {
4915
5009
  return __classPrivateFieldGet$7(this, _LiveQuery_result, "f");
4916
5010
  }
5011
+ get reopening() {
5012
+ return __classPrivateFieldGet$7(this, _LiveQuery_reopening, "f");
5013
+ }
5014
+ onStatus(listener) {
5015
+ __classPrivateFieldGet$7(this, _LiveQuery_statusListeners, "f").add(listener);
5016
+ return () => __classPrivateFieldGet$7(this, _LiveQuery_statusListeners, "f").delete(listener);
5017
+ }
4917
5018
  start() {
4918
5019
  var _a;
5020
+ __classPrivateFieldGet$7(this, _LiveQuery_instances, "m", _LiveQuery_clearRetry).call(this);
4919
5021
  __classPrivateFieldSet$7(this, _LiveQuery_latest, __classPrivateFieldGet$7(this, _LiveQuery_instances, "m", _LiveQuery_start).call(this, __classPrivateFieldSet$7(this, _LiveQuery_generation, (_a = __classPrivateFieldGet$7(this, _LiveQuery_generation, "f"), ++_a), "f")), "f");
4920
5022
  return __classPrivateFieldGet$7(this, _LiveQuery_latest, "f");
4921
5023
  }
4922
- dispose() {
5024
+ dispose(options = {}) {
4923
5025
  var _a;
4924
5026
  __classPrivateFieldSet$7(this, _LiveQuery_disposed, true, "f");
4925
5027
  __classPrivateFieldSet$7(this, _LiveQuery_generation, (_a = __classPrivateFieldGet$7(this, _LiveQuery_generation, "f"), _a++, _a), "f");
5028
+ __classPrivateFieldGet$7(this, _LiveQuery_instances, "m", _LiveQuery_clearRetry).call(this);
5029
+ __classPrivateFieldGet$7(this, _LiveQuery_statusListeners, "f").clear();
4926
5030
  __classPrivateFieldGet$7(this, _LiveQuery_unlisten, "f").call(this);
4927
5031
  __classPrivateFieldGet$7(this, _LiveQuery_unreconnect, "f").call(this);
5032
+ if (options.cancelOpening)
5033
+ __classPrivateFieldGet$7(this, _LiveQuery_opening, "f")?.abort();
4928
5034
  if (__classPrivateFieldGet$7(this, _LiveQuery_id, "f"))
4929
5035
  __classPrivateFieldGet$7(this, _LiveQuery_client, "f").disposeQuerySubscription(__classPrivateFieldGet$7(this, _LiveQuery_uuid, "f"), __classPrivateFieldGet$7(this, _LiveQuery_id, "f")).catch(() => {
4930
5036
  });
4931
5037
  }
4932
5038
  };
4933
- _LiveQuery_client = /* @__PURE__ */ new WeakMap(), _LiveQuery_uuid = /* @__PURE__ */ new WeakMap(), _LiveQuery_open = /* @__PURE__ */ new WeakMap(), _LiveQuery_onResult = /* @__PURE__ */ new WeakMap(), _LiveQuery_id = /* @__PURE__ */ new WeakMap(), _LiveQuery_revision = /* @__PURE__ */ new WeakMap(), _LiveQuery_result = /* @__PURE__ */ new WeakMap(), _LiveQuery_started = /* @__PURE__ */ new WeakMap(), _LiveQuery_disposed = /* @__PURE__ */ new WeakMap(), _LiveQuery_generation = /* @__PURE__ */ new WeakMap(), _LiveQuery_latest = /* @__PURE__ */ new WeakMap(), _LiveQuery_buffer = /* @__PURE__ */ new WeakMap(), _LiveQuery_unlisten = /* @__PURE__ */ new WeakMap(), _LiveQuery_unreconnect = /* @__PURE__ */ new WeakMap(), _LiveQuery_instances = /* @__PURE__ */ new WeakSet(), _LiveQuery_start = async function _LiveQuery_start2(generation) {
5039
+ _LiveQuery_client = /* @__PURE__ */ new WeakMap(), _LiveQuery_uuid = /* @__PURE__ */ new WeakMap(), _LiveQuery_open = /* @__PURE__ */ new WeakMap(), _LiveQuery_onResult = /* @__PURE__ */ new WeakMap(), _LiveQuery_id = /* @__PURE__ */ new WeakMap(), _LiveQuery_revision = /* @__PURE__ */ new WeakMap(), _LiveQuery_result = /* @__PURE__ */ new WeakMap(), _LiveQuery_started = /* @__PURE__ */ new WeakMap(), _LiveQuery_disposed = /* @__PURE__ */ new WeakMap(), _LiveQuery_generation = /* @__PURE__ */ new WeakMap(), _LiveQuery_latest = /* @__PURE__ */ new WeakMap(), _LiveQuery_buffer = /* @__PURE__ */ new WeakMap(), _LiveQuery_unlisten = /* @__PURE__ */ new WeakMap(), _LiveQuery_unreconnect = /* @__PURE__ */ new WeakMap(), _LiveQuery_opening = /* @__PURE__ */ new WeakMap(), _LiveQuery_retryTimer = /* @__PURE__ */ new WeakMap(), _LiveQuery_reopening = /* @__PURE__ */ new WeakMap(), _LiveQuery_statusListeners = /* @__PURE__ */ new WeakMap(), _LiveQuery_instances = /* @__PURE__ */ new WeakSet(), _LiveQuery_start = async function _LiveQuery_start2(generation) {
4934
5040
  __classPrivateFieldSet$7(this, _LiveQuery_buffer, [], "f");
5041
+ const opening = new AbortController();
5042
+ __classPrivateFieldSet$7(this, _LiveQuery_opening, opening, "f");
4935
5043
  let subscribed;
4936
5044
  try {
4937
- subscribed = await __classPrivateFieldGet$7(this, _LiveQuery_open, "f").call(this);
5045
+ subscribed = await __classPrivateFieldGet$7(this, _LiveQuery_open, "f").call(this, opening.signal);
4938
5046
  } catch (e) {
4939
5047
  if (generation === __classPrivateFieldGet$7(this, _LiveQuery_generation, "f"))
4940
5048
  __classPrivateFieldSet$7(this, _LiveQuery_buffer, null, "f");
4941
5049
  throw e;
5050
+ } finally {
5051
+ if (__classPrivateFieldGet$7(this, _LiveQuery_opening, "f") === opening)
5052
+ __classPrivateFieldSet$7(this, _LiveQuery_opening, void 0, "f");
4942
5053
  }
4943
5054
  if (__classPrivateFieldGet$7(this, _LiveQuery_disposed, "f") || generation !== __classPrivateFieldGet$7(this, _LiveQuery_generation, "f")) {
4944
5055
  __classPrivateFieldGet$7(this, _LiveQuery_client, "f").disposeQuerySubscription(__classPrivateFieldGet$7(this, _LiveQuery_uuid, "f"), subscribed.subscriptionId).catch(() => {
@@ -4948,6 +5059,44 @@ _LiveQuery_client = /* @__PURE__ */ new WeakMap(), _LiveQuery_uuid = /* @__PURE_
4948
5059
  __classPrivateFieldSet$7(this, _LiveQuery_id, subscribed.subscriptionId, "f");
4949
5060
  __classPrivateFieldGet$7(this, _LiveQuery_instances, "m", _LiveQuery_replace).call(this, subscribed.revision, subscribed.result);
4950
5061
  return __classPrivateFieldGet$7(this, _LiveQuery_result, "f");
5062
+ }, _LiveQuery_reopen = function _LiveQuery_reopen2(failures = 0) {
5063
+ if (__classPrivateFieldGet$7(this, _LiveQuery_disposed, "f"))
5064
+ return;
5065
+ const reopened = this.start();
5066
+ const generation = __classPrivateFieldGet$7(this, _LiveQuery_generation, "f");
5067
+ reopened.then(() => {
5068
+ if (__classPrivateFieldGet$7(this, _LiveQuery_disposed, "f") || generation !== __classPrivateFieldGet$7(this, _LiveQuery_generation, "f") || !__classPrivateFieldGet$7(this, _LiveQuery_reopening, "f"))
5069
+ return;
5070
+ __classPrivateFieldSet$7(this, _LiveQuery_reopening, false, "f");
5071
+ __classPrivateFieldGet$7(this, _LiveQuery_instances, "m", _LiveQuery_emit).call(this, { state: "open" });
5072
+ }, (error) => {
5073
+ if (__classPrivateFieldGet$7(this, _LiveQuery_disposed, "f") || generation !== __classPrivateFieldGet$7(this, _LiveQuery_generation, "f"))
5074
+ return;
5075
+ const retryInMs = reopenDelay(failures + 1);
5076
+ console.error(`Error re-opening live query (attempt ${failures + 1}), retrying in ${Math.round(retryInMs)}ms:`, error);
5077
+ __classPrivateFieldSet$7(this, _LiveQuery_reopening, true, "f");
5078
+ __classPrivateFieldGet$7(this, _LiveQuery_instances, "m", _LiveQuery_emit).call(this, { state: "reopening", error, retryInMs });
5079
+ const timer = setTimeout(() => {
5080
+ __classPrivateFieldSet$7(this, _LiveQuery_retryTimer, void 0, "f");
5081
+ __classPrivateFieldGet$7(this, _LiveQuery_instances, "m", _LiveQuery_reopen2).call(this, failures + 1);
5082
+ }, retryInMs);
5083
+ if (typeof timer?.unref === "function")
5084
+ timer.unref();
5085
+ __classPrivateFieldSet$7(this, _LiveQuery_retryTimer, timer, "f");
5086
+ });
5087
+ }, _LiveQuery_clearRetry = function _LiveQuery_clearRetry2() {
5088
+ if (__classPrivateFieldGet$7(this, _LiveQuery_retryTimer, "f") === void 0)
5089
+ return;
5090
+ clearTimeout(__classPrivateFieldGet$7(this, _LiveQuery_retryTimer, "f"));
5091
+ __classPrivateFieldSet$7(this, _LiveQuery_retryTimer, void 0, "f");
5092
+ }, _LiveQuery_emit = function _LiveQuery_emit2(status) {
5093
+ for (const listener of [...__classPrivateFieldGet$7(this, _LiveQuery_statusListeners, "f")]) {
5094
+ try {
5095
+ listener(status);
5096
+ } catch (e) {
5097
+ console.error("Error in live query status listener:", e);
5098
+ }
5099
+ }
4951
5100
  }, _LiveQuery_replace = function _LiveQuery_replace2(revision, result) {
4952
5101
  __classPrivateFieldSet$7(this, _LiveQuery_revision, revision, "f");
4953
5102
  __classPrivateFieldSet$7(this, _LiveQuery_result, result, "f");
@@ -4995,7 +5144,7 @@ _LiveQuery_client = /* @__PURE__ */ new WeakMap(), _LiveQuery_uuid = /* @__PURE_
4995
5144
  if (!__classPrivateFieldGet$7(this, _LiveQuery_disposed, "f") && generation === __classPrivateFieldGet$7(this, _LiveQuery_generation, "f")) {
4996
5145
  __classPrivateFieldGet$7(this, _LiveQuery_client, "f").disposeQuerySubscription(__classPrivateFieldGet$7(this, _LiveQuery_uuid, "f"), id).catch(() => {
4997
5146
  });
4998
- this.start().catch((e) => console.error("Error re-opening live query:", e));
5147
+ __classPrivateFieldGet$7(this, _LiveQuery_instances, "m", _LiveQuery_reopen).call(this);
4999
5148
  }
5000
5149
  });
5001
5150
  };
@@ -5501,7 +5650,7 @@ var QuerySubscriptionProxy = class {
5501
5650
  _QuerySubscriptionProxy_initialized.set(this, void 0);
5502
5651
  _QuerySubscriptionProxy_initResolve.set(this, void 0);
5503
5652
  _QuerySubscriptionProxy_initReject.set(this, void 0);
5504
- const open = className === void 0 ? () => client.subscribeQuery(uuid, query) : () => client.modelSubscribe(uuid, className, query);
5653
+ const open = className === void 0 ? (signal) => client.subscribeQuery(uuid, query, { signal }) : (signal) => client.modelSubscribe(uuid, className, query, { signal });
5505
5654
  __classPrivateFieldSet$6(this, _QuerySubscriptionProxy_live, new LiveQuery(client, uuid, open, (result) => __classPrivateFieldGet$6(this, _QuerySubscriptionProxy_instances, "m", _QuerySubscriptionProxy_deliver).call(this, result)), "f");
5506
5655
  __classPrivateFieldSet$6(this, _QuerySubscriptionProxy_initialized, new Promise((resolve, reject) => {
5507
5656
  __classPrivateFieldSet$6(this, _QuerySubscriptionProxy_initResolve, resolve, "f");
@@ -5532,8 +5681,14 @@ var QuerySubscriptionProxy = class {
5532
5681
  __classPrivateFieldGet$6(this, _QuerySubscriptionProxy_callbacks, "f").add(callback);
5533
5682
  return () => __classPrivateFieldGet$6(this, _QuerySubscriptionProxy_callbacks, "f").delete(callback);
5534
5683
  }
5535
- dispose() {
5536
- __classPrivateFieldGet$6(this, _QuerySubscriptionProxy_live, "f").dispose();
5684
+ get reopening() {
5685
+ return __classPrivateFieldGet$6(this, _QuerySubscriptionProxy_live, "f").reopening;
5686
+ }
5687
+ onStatus(listener) {
5688
+ return __classPrivateFieldGet$6(this, _QuerySubscriptionProxy_live, "f").onStatus(listener);
5689
+ }
5690
+ dispose(options = {}) {
5691
+ __classPrivateFieldGet$6(this, _QuerySubscriptionProxy_live, "f").dispose(options);
5537
5692
  __classPrivateFieldGet$6(this, _QuerySubscriptionProxy_callbacks, "f").clear();
5538
5693
  }
5539
5694
  };
@@ -6006,14 +6161,8 @@ var PerspectiveProxy = class {
6006
6161
  async stringOrTemplateObjectToSubjectClassName(subjectClass) {
6007
6162
  if (typeof subjectClass === "string")
6008
6163
  return subjectClass;
6009
- else {
6010
- let subjectClasses = await this.subjectClassesByTemplate(subjectClass);
6011
- if (subjectClasses[0]) {
6012
- return subjectClasses[0];
6013
- } else {
6014
- return subjectClass.className;
6015
- }
6016
- }
6164
+ const obj = subjectClass;
6165
+ return obj.className || obj.constructor?.className || obj.constructor?.prototype?.className || (await this.subjectClassesByTemplate(obj))[0];
6017
6166
  }
6018
6167
  async createSubject(subjectClass, exprAddr, initialValues, batchId) {
6019
6168
  let className;
@@ -6462,7 +6611,12 @@ var PerspectiveProxy = class {
6462
6611
  }
6463
6612
  async subscribeQuery(query) {
6464
6613
  const subscription = new QuerySubscriptionProxy(this.uuid, query, __classPrivateFieldGet$6(this, _PerspectiveProxy_client, "f"));
6465
- await subscription.subscribe();
6614
+ try {
6615
+ await subscription.subscribe();
6616
+ } catch (e) {
6617
+ subscription.dispose({ cancelOpening: true });
6618
+ throw e;
6619
+ }
6466
6620
  return subscription;
6467
6621
  }
6468
6622
  };
@@ -6558,8 +6712,8 @@ var PerspectiveClient = class {
6558
6712
  const result = await __classPrivateFieldGet$5(this, _PerspectiveClient_apiClient, "f").call("perspective.querySparql", { uuid, engine: "sparql", query }, options);
6559
6713
  return JSON.parse(result);
6560
6714
  }
6561
- async subscribeQuery(uuid, query) {
6562
- return __classPrivateFieldGet$5(this, _PerspectiveClient_apiClient, "f").call("perspective.subscribeQuery", { uuid, query });
6715
+ async subscribeQuery(uuid, query, options) {
6716
+ return __classPrivateFieldGet$5(this, _PerspectiveClient_apiClient, "f").call("perspective.subscribeQuery", { uuid, query }, options);
6563
6717
  }
6564
6718
  onQueryUpdate(cb) {
6565
6719
  return __classPrivateFieldGet$5(this, _PerspectiveClient_apiClient, "f").on("query-subscription-update", cb);
@@ -6586,8 +6740,8 @@ var PerspectiveClient = class {
6586
6740
  });
6587
6741
  return JSON.parse(resultJson);
6588
6742
  }
6589
- async modelSubscribe(uuid, className, queryJson) {
6590
- return __classPrivateFieldGet$5(this, _PerspectiveClient_apiClient, "f").call("perspective.modelSubscribe", { uuid, ...classParams(className), query_json: queryJson });
6743
+ async modelSubscribe(uuid, className, queryJson, options) {
6744
+ return __classPrivateFieldGet$5(this, _PerspectiveClient_apiClient, "f").call("perspective.modelSubscribe", { uuid, ...classParams(className), query_json: queryJson }, options);
6591
6745
  }
6592
6746
  async add(name) {
6593
6747
  const handle = await __classPrivateFieldGet$5(this, _PerspectiveClient_apiClient, "f").call("perspective.create", { name });
@@ -12063,6 +12217,7 @@ function buildSPARQLWhereFilters(metadata, _allRelationsMetadata, where) {
12063
12217
  }
12064
12218
  return { joins, filters };
12065
12219
  }
12220
+ var fingerprint = (value) => JSON.stringify(value, (_, v) => typeof v === "function" ? void 0 : v);
12066
12221
  var ModelQueryBuilder = class {
12067
12222
  constructor(perspective, ctor, query, unionClasses) {
12068
12223
  this.queryParams = {};
@@ -12094,6 +12249,9 @@ var ModelQueryBuilder = class {
12094
12249
  }
12095
12250
  return this.ctor.parseModelResult(this.perspective, raw, include, properties);
12096
12251
  }
12252
+ takeSnapshots(instances) {
12253
+ this.ctor.takeSnapshots(instances, this.queryParams.include);
12254
+ }
12097
12255
  dispose() {
12098
12256
  if (this.currentSubscription) {
12099
12257
  this.currentSubscription.dispose();
@@ -12199,7 +12357,6 @@ var ModelQueryBuilder = class {
12199
12357
  async subscribe(callback) {
12200
12358
  this.dispose();
12201
12359
  const parseResults = (raw) => this.parse(raw);
12202
- const fingerprint = (results) => JSON.stringify(results, (_, v) => typeof v === "function" ? void 0 : v);
12203
12360
  let lastFingerprint = null;
12204
12361
  const { initial } = await this.live(this.queryParams, (raw) => {
12205
12362
  try {
@@ -12248,53 +12405,33 @@ var ModelQueryBuilder = class {
12248
12405
  }
12249
12406
  async paginateSubscribe(pageSize, pageNumber, callback) {
12250
12407
  this.dispose();
12251
- const subscriptionParams = { ...this.queryParams || {} };
12252
- delete subscriptionParams.limit;
12253
- delete subscriptionParams.offset;
12254
12408
  const paginatedQuery = {
12255
12409
  ...this.queryParams || {},
12256
12410
  limit: pageSize,
12257
12411
  offset: pageSize * (pageNumber - 1),
12258
12412
  count: true
12259
12413
  };
12260
- let disposed = false;
12261
- let fetching = false;
12262
- let pending = false;
12263
- const processResults = async () => {
12264
- if (disposed)
12265
- return;
12266
- if (fetching) {
12267
- pending = true;
12268
- return;
12269
- }
12270
- fetching = true;
12414
+ let lastFingerprint = null;
12415
+ const toPage = (raw) => {
12416
+ const results = this.parse(raw);
12417
+ const fp2 = fingerprint([results, raw?.totalCount]);
12418
+ this.takeSnapshots(results);
12419
+ return { page: { results, totalCount: raw?.totalCount, pageSize, pageNumber }, fp: fp2 };
12420
+ };
12421
+ const { initial } = await this.live(paginatedQuery, (raw) => {
12271
12422
  try {
12272
- const { results: results2, totalCount: totalCount2 } = await this.execute(paginatedQuery);
12273
- if (!disposed)
12274
- callback({ results: results2, totalCount: totalCount2, pageSize, pageNumber });
12275
- } finally {
12276
- fetching = false;
12277
- if (pending) {
12278
- pending = false;
12279
- processResults().catch((e) => console.error("Paginate subscription error:", e));
12280
- }
12423
+ const { page: page2, fp: fp2 } = toPage(raw);
12424
+ if (fp2 === lastFingerprint)
12425
+ return;
12426
+ lastFingerprint = fp2;
12427
+ callback(page2);
12428
+ } catch (e) {
12429
+ console.error("Paginate subscription error:", e);
12281
12430
  }
12282
- };
12283
- const { live } = await this.live(subscriptionParams, () => {
12284
- processResults().catch((e) => console.error("Paginate subscription error:", e));
12285
12431
  });
12286
- if (this.currentSubscription === live) {
12287
- this.currentSubscription = {
12288
- dispose: () => {
12289
- disposed = true;
12290
- live.dispose();
12291
- }
12292
- };
12293
- } else {
12294
- disposed = true;
12295
- }
12296
- const { results, totalCount } = await this.execute(paginatedQuery);
12297
- return { results, totalCount, pageSize, pageNumber };
12432
+ const { page, fp } = toPage(initial);
12433
+ lastFingerprint = fp;
12434
+ return page;
12298
12435
  }
12299
12436
  async paginateSubscribeSparql(pageSize, pageNumber, callback) {
12300
12437
  return await this.paginateSubscribe(pageSize, pageNumber, callback);
@@ -12891,6 +13028,12 @@ var Ad4mModel = class {
12891
13028
  return [];
12892
13029
  return arr.map((json) => jsonToModelInstance(this, perspective, json, include, properties));
12893
13030
  }
13031
+ static takeSnapshots(instances, include) {
13032
+ const relations = include ? Object.fromEntries(Object.entries(include).filter(([k]) => !k.startsWith("$"))) : void 0;
13033
+ const snapshot = relations && Object.keys(relations).length > 0 ? relations : void 0;
13034
+ for (const inst of instances)
13035
+ inst.takeSnapshot?.(snapshot);
13036
+ }
12894
13037
  static prepareUnionQueryParams(classes, query = {}) {
12895
13038
  if (!classes.length)
12896
13039
  throw new Error("A query over several classes needs at least one class");
@@ -12963,10 +13106,7 @@ var Ad4mModel = class {
12963
13106
  const { classNames, queryJson } = Ad4mModel.prepareUnionQueryParams(classes, query);
12964
13107
  const result = await perspective.modelQuery(classNames, queryJson, options);
12965
13108
  const results = Ad4mModel.parseUnionResult(classes, perspective, result, query.include, query.properties);
12966
- const snapshotRelations = query.include ? Object.fromEntries(Object.entries(query.include).filter(([k]) => !k.startsWith("$"))) : void 0;
12967
- for (const inst of results) {
12968
- inst.takeSnapshot?.(snapshotRelations && Object.keys(snapshotRelations).length > 0 ? snapshotRelations : void 0);
12969
- }
13109
+ Ad4mModel.takeSnapshots(results, query.include);
12970
13110
  return { results, totalCount: result.totalCount };
12971
13111
  }
12972
13112
  static async findAllOf(perspective, classes, query, options) {
@@ -12982,10 +13122,7 @@ var Ad4mModel = class {
12982
13122
  const instances = result.instances.map((json) => {
12983
13123
  return jsonToModelInstance(this, perspective, json, query.include, query.properties);
12984
13124
  });
12985
- const snapshotRelations = query.include ? Object.fromEntries(Object.entries(query.include).filter(([k]) => !k.startsWith("$"))) : void 0;
12986
- for (const inst of instances) {
12987
- inst.takeSnapshot(snapshotRelations && Object.keys(snapshotRelations).length > 0 ? snapshotRelations : void 0);
12988
- }
13125
+ Ad4mModel.takeSnapshots(instances, query.include);
12989
13126
  return {
12990
13127
  results: instances,
12991
13128
  totalCount: result.totalCount
@@ -13538,6 +13675,9 @@ var Ad4mClient = class {
13538
13675
  onAuthFailed(callback) {
13539
13676
  return __classPrivateFieldGet$1(this, _Ad4mClient_apiClient, "f").onAuthFailed(callback);
13540
13677
  }
13678
+ reconnectNow() {
13679
+ __classPrivateFieldGet$1(this, _Ad4mClient_apiClient, "f").reconnectNow();
13680
+ }
13541
13681
  close() {
13542
13682
  __classPrivateFieldGet$1(this, _Ad4mClient_agentClient, "f").clearByDidCache();
13543
13683
  __classPrivateFieldGet$1(this, _Ad4mClient_apiClient, "f").closeAll();