@electric-sql/client 1.0.3 → 1.0.5

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/index.mjs CHANGED
@@ -267,6 +267,12 @@ function isControlMessage(message) {
267
267
  function isUpToDateMessage(message) {
268
268
  return isControlMessage(message) && message.headers.control === `up-to-date`;
269
269
  }
270
+ function getOffset(message) {
271
+ const lsn = Number(message.headers.global_last_seen_lsn);
272
+ if (lsn && !isNaN(lsn)) {
273
+ return `${lsn}_0`;
274
+ }
275
+ }
270
276
 
271
277
  // src/constants.ts
272
278
  var LIVE_CACHE_BUSTER_HEADER = `electric-cursor`;
@@ -283,7 +289,9 @@ var TABLE_QUERY_PARAM = `table`;
283
289
  var WHERE_QUERY_PARAM = `where`;
284
290
  var REPLICA_PARAM = `replica`;
285
291
  var WHERE_PARAMS_PARAM = `params`;
292
+ var EXPERIMENTAL_LIVE_SSE_QUERY_PARAM = `experimental_live_sse`;
286
293
  var FORCE_DISCONNECT_AND_REFRESH = `force-disconnect-and-refresh`;
294
+ var PAUSE_STREAM = `pause-stream`;
287
295
 
288
296
  // src/fetch.ts
289
297
  var HTTP_RETRY_STATUS_CODES = [429];
@@ -292,7 +300,7 @@ var BackoffDefaults = {
292
300
  maxDelay: 1e4,
293
301
  multiplier: 1.3
294
302
  };
295
- function createFetchWithBackoff(fetchClient, backoffOptions = BackoffDefaults) {
303
+ function createFetchWithBackoff(fetchClient, backoffOptions = BackoffDefaults, sseMode = false) {
296
304
  const {
297
305
  initialDelay,
298
306
  maxDelay,
@@ -310,7 +318,11 @@ function createFetchWithBackoff(fetchClient, backoffOptions = BackoffDefaults) {
310
318
  try {
311
319
  const result = yield fetchClient(...args);
312
320
  if (result.ok) return result;
313
- else throw yield FetchError.fromResponse(result, url.toString());
321
+ const err = yield FetchError.fromResponse(result, url.toString());
322
+ if (err.status === 409 && sseMode) {
323
+ err.json = [err.json];
324
+ }
325
+ throw err;
314
326
  } catch (e) {
315
327
  onFailedAttempt == null ? void 0 : onFailedAttempt();
316
328
  if ((_a = options == null ? void 0 : options.signal) == null ? void 0 : _a.aborted) {
@@ -508,6 +520,9 @@ function noop() {
508
520
  }
509
521
 
510
522
  // src/client.ts
523
+ import {
524
+ fetchEventSource
525
+ } from "@microsoft/fetch-event-source";
511
526
  var RESERVED_PARAMS = /* @__PURE__ */ new Set([
512
527
  LIVE_CACHE_BUSTER_QUERY_PARAM,
513
528
  SHAPE_HANDLE_QUERY_PARAM,
@@ -552,15 +567,18 @@ function resolveHeaders(headers) {
552
567
  return Object.fromEntries(resolvedEntries);
553
568
  });
554
569
  }
555
- var _error, _fetchClient2, _messageParser, _subscribers, _started, _lastOffset, _liveCacheBuster, _lastSyncedAt, _isUpToDate, _connected, _shapeHandle, _schema, _onError, _requestAbortController, _isRefreshing, _tickPromise, _tickPromiseResolver, _tickPromiseRejecter, _ShapeStream_instances, start_fn, nextTick_fn, publish_fn, sendErrorToSubscribers_fn, reset_fn;
570
+ var _error, _fetchClient2, _sseFetchClient, _messageParser, _subscribers, _started, _state, _lastOffset, _liveCacheBuster, _lastSyncedAt, _isUpToDate, _connected, _shapeHandle, _schema, _onError, _requestAbortController, _isRefreshing, _tickPromise, _tickPromiseResolver, _tickPromiseRejecter, _messageChain, _ShapeStream_instances, start_fn, requestShape_fn, constructUrl_fn, createAbortListener_fn, onInitialResponse_fn, onMessages_fn, fetchShape_fn, requestShapeLongPoll_fn, requestShapeSSE_fn, pause_fn, resume_fn, nextTick_fn, publish_fn, sendErrorToSubscribers_fn, subscribeToVisibilityChanges_fn, reset_fn;
556
571
  var ShapeStream = class {
572
+ // promise chain for incoming messages
557
573
  constructor(options) {
558
574
  __privateAdd(this, _ShapeStream_instances);
559
575
  __privateAdd(this, _error, null);
560
576
  __privateAdd(this, _fetchClient2);
577
+ __privateAdd(this, _sseFetchClient);
561
578
  __privateAdd(this, _messageParser);
562
579
  __privateAdd(this, _subscribers, /* @__PURE__ */ new Map());
563
580
  __privateAdd(this, _started, false);
581
+ __privateAdd(this, _state, `active`);
564
582
  __privateAdd(this, _lastOffset);
565
583
  __privateAdd(this, _liveCacheBuster);
566
584
  // Seconds since our Electric Epoch 😎
@@ -576,6 +594,7 @@ var ShapeStream = class {
576
594
  __privateAdd(this, _tickPromise);
577
595
  __privateAdd(this, _tickPromiseResolver);
578
596
  __privateAdd(this, _tickPromiseRejecter);
597
+ __privateAdd(this, _messageChain, Promise.resolve([]));
579
598
  var _a, _b, _c;
580
599
  this.options = __spreadValues({ subscribe: true }, options);
581
600
  validateOptions(this.options);
@@ -585,18 +604,31 @@ var ShapeStream = class {
585
604
  __privateSet(this, _messageParser, new MessageParser(options.parser));
586
605
  __privateSet(this, _onError, this.options.onError);
587
606
  const baseFetchClient = (_b = options.fetchClient) != null ? _b : (...args) => fetch(...args);
588
- const fetchWithBackoffClient = createFetchWithBackoff(baseFetchClient, __spreadProps(__spreadValues({}, (_c = options.backoffOptions) != null ? _c : BackoffDefaults), {
607
+ const backOffOpts = __spreadProps(__spreadValues({}, (_c = options.backoffOptions) != null ? _c : BackoffDefaults), {
589
608
  onFailedAttempt: () => {
590
609
  var _a2, _b2;
591
610
  __privateSet(this, _connected, false);
592
611
  (_b2 = (_a2 = options.backoffOptions) == null ? void 0 : _a2.onFailedAttempt) == null ? void 0 : _b2.call(_a2);
593
612
  }
594
- }));
613
+ });
614
+ const fetchWithBackoffClient = createFetchWithBackoff(
615
+ baseFetchClient,
616
+ backOffOpts
617
+ );
595
618
  __privateSet(this, _fetchClient2, createFetchWithConsumedMessages(
596
619
  createFetchWithResponseHeadersCheck(
597
620
  createFetchWithChunkBuffer(fetchWithBackoffClient)
598
621
  )
599
622
  ));
623
+ const sseFetchWithBackoffClient = createFetchWithBackoff(
624
+ baseFetchClient,
625
+ backOffOpts,
626
+ true
627
+ );
628
+ __privateSet(this, _sseFetchClient, createFetchWithResponseHeadersCheck(
629
+ createFetchWithChunkBuffer(sseFetchWithBackoffClient)
630
+ ));
631
+ __privateMethod(this, _ShapeStream_instances, subscribeToVisibilityChanges_fn).call(this);
600
632
  }
601
633
  get shapeHandle() {
602
634
  return __privateGet(this, _shapeHandle);
@@ -642,6 +674,9 @@ var ShapeStream = class {
642
674
  hasStarted() {
643
675
  return __privateGet(this, _started);
644
676
  }
677
+ isPaused() {
678
+ return __privateGet(this, _state) === `paused`;
679
+ }
645
680
  /**
646
681
  * Refreshes the shape stream.
647
682
  * This preemptively aborts any ongoing long poll and reconnects without
@@ -662,9 +697,11 @@ var ShapeStream = class {
662
697
  };
663
698
  _error = new WeakMap();
664
699
  _fetchClient2 = new WeakMap();
700
+ _sseFetchClient = new WeakMap();
665
701
  _messageParser = new WeakMap();
666
702
  _subscribers = new WeakMap();
667
703
  _started = new WeakMap();
704
+ _state = new WeakMap();
668
705
  _lastOffset = new WeakMap();
669
706
  _liveCacheBuster = new WeakMap();
670
707
  _lastSyncedAt = new WeakMap();
@@ -678,134 +715,14 @@ _isRefreshing = new WeakMap();
678
715
  _tickPromise = new WeakMap();
679
716
  _tickPromiseResolver = new WeakMap();
680
717
  _tickPromiseRejecter = new WeakMap();
718
+ _messageChain = new WeakMap();
681
719
  _ShapeStream_instances = new WeakSet();
682
720
  start_fn = function() {
683
721
  return __async(this, null, function* () {
684
- var _a, _b, _c, _d, _e;
685
- if (__privateGet(this, _started)) throw new Error(`Cannot start stream twice`);
722
+ var _a;
686
723
  __privateSet(this, _started, true);
687
724
  try {
688
- while (!((_a = this.options.signal) == null ? void 0 : _a.aborted) && !__privateGet(this, _isUpToDate) || this.options.subscribe) {
689
- const { url, signal } = this.options;
690
- const [requestHeaders, params] = yield Promise.all([
691
- resolveHeaders(this.options.headers),
692
- this.options.params ? toInternalParams(convertWhereParamsToObj(this.options.params)) : void 0
693
- ]);
694
- if (params) {
695
- validateParams(params);
696
- }
697
- const fetchUrl = new URL(url);
698
- if (params) {
699
- if (params.table)
700
- setQueryParam(fetchUrl, TABLE_QUERY_PARAM, params.table);
701
- if (params.where)
702
- setQueryParam(fetchUrl, WHERE_QUERY_PARAM, params.where);
703
- if (params.columns)
704
- setQueryParam(fetchUrl, COLUMNS_QUERY_PARAM, params.columns);
705
- if (params.replica)
706
- setQueryParam(fetchUrl, REPLICA_PARAM, params.replica);
707
- if (params.params)
708
- setQueryParam(fetchUrl, WHERE_PARAMS_PARAM, params.params);
709
- const customParams = __spreadValues({}, params);
710
- delete customParams.table;
711
- delete customParams.where;
712
- delete customParams.columns;
713
- delete customParams.replica;
714
- delete customParams.params;
715
- for (const [key, value] of Object.entries(customParams)) {
716
- setQueryParam(fetchUrl, key, value);
717
- }
718
- }
719
- fetchUrl.searchParams.set(OFFSET_QUERY_PARAM, __privateGet(this, _lastOffset));
720
- if (__privateGet(this, _isUpToDate)) {
721
- if (!__privateGet(this, _isRefreshing)) {
722
- fetchUrl.searchParams.set(LIVE_QUERY_PARAM, `true`);
723
- }
724
- fetchUrl.searchParams.set(
725
- LIVE_CACHE_BUSTER_QUERY_PARAM,
726
- __privateGet(this, _liveCacheBuster)
727
- );
728
- }
729
- if (__privateGet(this, _shapeHandle)) {
730
- fetchUrl.searchParams.set(
731
- SHAPE_HANDLE_QUERY_PARAM,
732
- __privateGet(this, _shapeHandle)
733
- );
734
- }
735
- fetchUrl.searchParams.sort();
736
- __privateSet(this, _requestAbortController, new AbortController());
737
- let abortListener;
738
- if (signal) {
739
- abortListener = () => {
740
- var _a2;
741
- (_a2 = __privateGet(this, _requestAbortController)) == null ? void 0 : _a2.abort(signal.reason);
742
- };
743
- signal.addEventListener(`abort`, abortListener, { once: true });
744
- if (signal.aborted) {
745
- (_b = __privateGet(this, _requestAbortController)) == null ? void 0 : _b.abort(signal.reason);
746
- }
747
- }
748
- let response;
749
- try {
750
- response = yield __privateGet(this, _fetchClient2).call(this, fetchUrl.toString(), {
751
- signal: __privateGet(this, _requestAbortController).signal,
752
- headers: requestHeaders
753
- });
754
- __privateSet(this, _connected, true);
755
- } catch (e) {
756
- if ((e instanceof FetchError || e instanceof FetchBackoffAbortError) && __privateGet(this, _requestAbortController).signal.aborted && __privateGet(this, _requestAbortController).signal.reason === FORCE_DISCONNECT_AND_REFRESH) {
757
- continue;
758
- }
759
- if (e instanceof FetchBackoffAbortError) break;
760
- if (!(e instanceof FetchError)) throw e;
761
- if (e.status == 409) {
762
- const newShapeHandle = e.headers[SHAPE_HANDLE_HEADER];
763
- __privateMethod(this, _ShapeStream_instances, reset_fn).call(this, newShapeHandle);
764
- yield __privateMethod(this, _ShapeStream_instances, publish_fn).call(this, e.json);
765
- continue;
766
- } else {
767
- __privateMethod(this, _ShapeStream_instances, sendErrorToSubscribers_fn).call(this, e);
768
- throw e;
769
- }
770
- } finally {
771
- if (abortListener && signal) {
772
- signal.removeEventListener(`abort`, abortListener);
773
- }
774
- __privateSet(this, _requestAbortController, void 0);
775
- }
776
- const { headers, status } = response;
777
- const shapeHandle = headers.get(SHAPE_HANDLE_HEADER);
778
- if (shapeHandle) {
779
- __privateSet(this, _shapeHandle, shapeHandle);
780
- }
781
- const lastOffset = headers.get(CHUNK_LAST_OFFSET_HEADER);
782
- if (lastOffset) {
783
- __privateSet(this, _lastOffset, lastOffset);
784
- }
785
- const liveCacheBuster = headers.get(LIVE_CACHE_BUSTER_HEADER);
786
- if (liveCacheBuster) {
787
- __privateSet(this, _liveCacheBuster, liveCacheBuster);
788
- }
789
- const getSchema = () => {
790
- const schemaHeader = headers.get(SHAPE_SCHEMA_HEADER);
791
- return schemaHeader ? JSON.parse(schemaHeader) : {};
792
- };
793
- __privateSet(this, _schema, (_c = __privateGet(this, _schema)) != null ? _c : getSchema());
794
- if (status === 204) {
795
- __privateSet(this, _lastSyncedAt, Date.now());
796
- }
797
- const messages = (yield response.text()) || `[]`;
798
- const batch = __privateGet(this, _messageParser).parse(messages, __privateGet(this, _schema));
799
- if (batch.length > 0) {
800
- const lastMessage = batch[batch.length - 1];
801
- if (isUpToDateMessage(lastMessage)) {
802
- __privateSet(this, _lastSyncedAt, Date.now());
803
- __privateSet(this, _isUpToDate, true);
804
- }
805
- yield __privateMethod(this, _ShapeStream_instances, publish_fn).call(this, batch);
806
- }
807
- (_d = __privateGet(this, _tickPromiseResolver)) == null ? void 0 : _d.call(this);
808
- }
725
+ yield __privateMethod(this, _ShapeStream_instances, requestShape_fn).call(this);
809
726
  } catch (err) {
810
727
  __privateSet(this, _error, err);
811
728
  if (__privateGet(this, _onError)) {
@@ -826,10 +743,241 @@ start_fn = function() {
826
743
  throw err;
827
744
  } finally {
828
745
  __privateSet(this, _connected, false);
829
- (_e = __privateGet(this, _tickPromiseRejecter)) == null ? void 0 : _e.call(this);
746
+ (_a = __privateGet(this, _tickPromiseRejecter)) == null ? void 0 : _a.call(this);
747
+ }
748
+ });
749
+ };
750
+ requestShape_fn = function() {
751
+ return __async(this, null, function* () {
752
+ var _a, _b;
753
+ if (__privateGet(this, _state) === `pause-requested`) {
754
+ __privateSet(this, _state, `paused`);
755
+ return;
756
+ }
757
+ if (!this.options.subscribe && (((_a = this.options.signal) == null ? void 0 : _a.aborted) || __privateGet(this, _isUpToDate))) {
758
+ return;
759
+ }
760
+ const resumingFromPause = __privateGet(this, _state) === `paused`;
761
+ __privateSet(this, _state, `active`);
762
+ const { url, signal } = this.options;
763
+ const { fetchUrl, requestHeaders } = yield __privateMethod(this, _ShapeStream_instances, constructUrl_fn).call(this, url, resumingFromPause);
764
+ const abortListener = yield __privateMethod(this, _ShapeStream_instances, createAbortListener_fn).call(this, signal);
765
+ const requestAbortController = __privateGet(this, _requestAbortController);
766
+ try {
767
+ yield __privateMethod(this, _ShapeStream_instances, fetchShape_fn).call(this, {
768
+ fetchUrl,
769
+ requestAbortController,
770
+ headers: requestHeaders,
771
+ resumingFromPause: true
772
+ });
773
+ } catch (e) {
774
+ if ((e instanceof FetchError || e instanceof FetchBackoffAbortError) && requestAbortController.signal.aborted && requestAbortController.signal.reason === FORCE_DISCONNECT_AND_REFRESH) {
775
+ return __privateMethod(this, _ShapeStream_instances, requestShape_fn).call(this);
776
+ }
777
+ if (e instanceof FetchBackoffAbortError) {
778
+ if (requestAbortController.signal.aborted && requestAbortController.signal.reason === PAUSE_STREAM) {
779
+ __privateSet(this, _state, `paused`);
780
+ }
781
+ return;
782
+ }
783
+ if (!(e instanceof FetchError)) throw e;
784
+ if (e.status == 409) {
785
+ const newShapeHandle = e.headers[SHAPE_HANDLE_HEADER];
786
+ __privateMethod(this, _ShapeStream_instances, reset_fn).call(this, newShapeHandle);
787
+ yield __privateMethod(this, _ShapeStream_instances, publish_fn).call(this, e.json);
788
+ return __privateMethod(this, _ShapeStream_instances, requestShape_fn).call(this);
789
+ } else {
790
+ __privateMethod(this, _ShapeStream_instances, sendErrorToSubscribers_fn).call(this, e);
791
+ throw e;
792
+ }
793
+ } finally {
794
+ if (abortListener && signal) {
795
+ signal.removeEventListener(`abort`, abortListener);
796
+ }
797
+ __privateSet(this, _requestAbortController, void 0);
798
+ }
799
+ (_b = __privateGet(this, _tickPromiseResolver)) == null ? void 0 : _b.call(this);
800
+ return __privateMethod(this, _ShapeStream_instances, requestShape_fn).call(this);
801
+ });
802
+ };
803
+ constructUrl_fn = function(url, resumingFromPause) {
804
+ return __async(this, null, function* () {
805
+ const [requestHeaders, params] = yield Promise.all([
806
+ resolveHeaders(this.options.headers),
807
+ this.options.params ? toInternalParams(convertWhereParamsToObj(this.options.params)) : void 0
808
+ ]);
809
+ if (params) {
810
+ validateParams(params);
811
+ }
812
+ const fetchUrl = new URL(url);
813
+ if (params) {
814
+ if (params.table) setQueryParam(fetchUrl, TABLE_QUERY_PARAM, params.table);
815
+ if (params.where) setQueryParam(fetchUrl, WHERE_QUERY_PARAM, params.where);
816
+ if (params.columns)
817
+ setQueryParam(fetchUrl, COLUMNS_QUERY_PARAM, params.columns);
818
+ if (params.replica) setQueryParam(fetchUrl, REPLICA_PARAM, params.replica);
819
+ if (params.params)
820
+ setQueryParam(fetchUrl, WHERE_PARAMS_PARAM, params.params);
821
+ const customParams = __spreadValues({}, params);
822
+ delete customParams.table;
823
+ delete customParams.where;
824
+ delete customParams.columns;
825
+ delete customParams.replica;
826
+ delete customParams.params;
827
+ for (const [key, value] of Object.entries(customParams)) {
828
+ setQueryParam(fetchUrl, key, value);
829
+ }
830
+ }
831
+ fetchUrl.searchParams.set(OFFSET_QUERY_PARAM, __privateGet(this, _lastOffset));
832
+ if (__privateGet(this, _isUpToDate)) {
833
+ if (!__privateGet(this, _isRefreshing) && !resumingFromPause) {
834
+ fetchUrl.searchParams.set(LIVE_QUERY_PARAM, `true`);
835
+ }
836
+ fetchUrl.searchParams.set(
837
+ LIVE_CACHE_BUSTER_QUERY_PARAM,
838
+ __privateGet(this, _liveCacheBuster)
839
+ );
840
+ }
841
+ if (__privateGet(this, _shapeHandle)) {
842
+ fetchUrl.searchParams.set(SHAPE_HANDLE_QUERY_PARAM, __privateGet(this, _shapeHandle));
843
+ }
844
+ fetchUrl.searchParams.sort();
845
+ return {
846
+ fetchUrl,
847
+ requestHeaders
848
+ };
849
+ });
850
+ };
851
+ createAbortListener_fn = function(signal) {
852
+ return __async(this, null, function* () {
853
+ var _a;
854
+ __privateSet(this, _requestAbortController, new AbortController());
855
+ if (signal) {
856
+ const abortListener = () => {
857
+ var _a2;
858
+ (_a2 = __privateGet(this, _requestAbortController)) == null ? void 0 : _a2.abort(signal.reason);
859
+ };
860
+ signal.addEventListener(`abort`, abortListener, { once: true });
861
+ if (signal.aborted) {
862
+ (_a = __privateGet(this, _requestAbortController)) == null ? void 0 : _a.abort(signal.reason);
863
+ }
864
+ return abortListener;
865
+ }
866
+ });
867
+ };
868
+ onInitialResponse_fn = function(response) {
869
+ return __async(this, null, function* () {
870
+ var _a;
871
+ const { headers, status } = response;
872
+ const shapeHandle = headers.get(SHAPE_HANDLE_HEADER);
873
+ if (shapeHandle) {
874
+ __privateSet(this, _shapeHandle, shapeHandle);
875
+ }
876
+ const lastOffset = headers.get(CHUNK_LAST_OFFSET_HEADER);
877
+ if (lastOffset) {
878
+ __privateSet(this, _lastOffset, lastOffset);
879
+ }
880
+ const liveCacheBuster = headers.get(LIVE_CACHE_BUSTER_HEADER);
881
+ if (liveCacheBuster) {
882
+ __privateSet(this, _liveCacheBuster, liveCacheBuster);
883
+ }
884
+ const getSchema = () => {
885
+ const schemaHeader = headers.get(SHAPE_SCHEMA_HEADER);
886
+ return schemaHeader ? JSON.parse(schemaHeader) : {};
887
+ };
888
+ __privateSet(this, _schema, (_a = __privateGet(this, _schema)) != null ? _a : getSchema());
889
+ if (status === 204) {
890
+ __privateSet(this, _lastSyncedAt, Date.now());
891
+ }
892
+ });
893
+ };
894
+ onMessages_fn = function(messages, schema, isSseMessage = false) {
895
+ return __async(this, null, function* () {
896
+ const batch = __privateGet(this, _messageParser).parse(messages, schema);
897
+ if (batch.length > 0) {
898
+ const lastMessage = batch[batch.length - 1];
899
+ if (isUpToDateMessage(lastMessage)) {
900
+ if (isSseMessage) {
901
+ const offset = getOffset(lastMessage);
902
+ if (offset) {
903
+ __privateSet(this, _lastOffset, offset);
904
+ }
905
+ }
906
+ __privateSet(this, _lastSyncedAt, Date.now());
907
+ __privateSet(this, _isUpToDate, true);
908
+ }
909
+ yield __privateMethod(this, _ShapeStream_instances, publish_fn).call(this, batch);
910
+ }
911
+ });
912
+ };
913
+ fetchShape_fn = function(opts) {
914
+ return __async(this, null, function* () {
915
+ if (__privateGet(this, _isUpToDate) && this.options.experimentalLiveSse && !__privateGet(this, _isRefreshing) && !opts.resumingFromPause) {
916
+ opts.fetchUrl.searchParams.set(EXPERIMENTAL_LIVE_SSE_QUERY_PARAM, `true`);
917
+ return __privateMethod(this, _ShapeStream_instances, requestShapeSSE_fn).call(this, opts);
918
+ }
919
+ return __privateMethod(this, _ShapeStream_instances, requestShapeLongPoll_fn).call(this, opts);
920
+ });
921
+ };
922
+ requestShapeLongPoll_fn = function(opts) {
923
+ return __async(this, null, function* () {
924
+ const { fetchUrl, requestAbortController, headers } = opts;
925
+ const response = yield __privateGet(this, _fetchClient2).call(this, fetchUrl.toString(), {
926
+ signal: requestAbortController.signal,
927
+ headers
928
+ });
929
+ __privateSet(this, _connected, true);
930
+ yield __privateMethod(this, _ShapeStream_instances, onInitialResponse_fn).call(this, response);
931
+ const schema = __privateGet(this, _schema);
932
+ const res = yield response.text();
933
+ const messages = res || `[]`;
934
+ yield __privateMethod(this, _ShapeStream_instances, onMessages_fn).call(this, messages, schema);
935
+ });
936
+ };
937
+ requestShapeSSE_fn = function(opts) {
938
+ return __async(this, null, function* () {
939
+ const { fetchUrl, requestAbortController, headers } = opts;
940
+ const fetch2 = __privateGet(this, _sseFetchClient);
941
+ try {
942
+ yield fetchEventSource(fetchUrl.toString(), {
943
+ headers,
944
+ fetch: fetch2,
945
+ onopen: (response) => __async(this, null, function* () {
946
+ __privateSet(this, _connected, true);
947
+ yield __privateMethod(this, _ShapeStream_instances, onInitialResponse_fn).call(this, response);
948
+ }),
949
+ onmessage: (event) => {
950
+ if (event.data) {
951
+ const messages = `[${event.data}]`;
952
+ const schema = __privateGet(this, _schema);
953
+ __privateMethod(this, _ShapeStream_instances, onMessages_fn).call(this, messages, schema, true);
954
+ }
955
+ },
956
+ onerror: (error) => {
957
+ throw error;
958
+ },
959
+ signal: requestAbortController.signal
960
+ });
961
+ } catch (error) {
962
+ if (requestAbortController.signal.aborted) {
963
+ throw new FetchBackoffAbortError();
964
+ }
965
+ throw error;
830
966
  }
831
967
  });
832
968
  };
969
+ pause_fn = function() {
970
+ var _a;
971
+ if (__privateGet(this, _started) && __privateGet(this, _state) === `active`) {
972
+ __privateSet(this, _state, `pause-requested`);
973
+ (_a = __privateGet(this, _requestAbortController)) == null ? void 0 : _a.abort(PAUSE_STREAM);
974
+ }
975
+ };
976
+ resume_fn = function() {
977
+ if (__privateGet(this, _started) && __privateGet(this, _state) === `paused`) {
978
+ __privateMethod(this, _ShapeStream_instances, start_fn).call(this);
979
+ }
980
+ };
833
981
  nextTick_fn = function() {
834
982
  return __async(this, null, function* () {
835
983
  if (__privateGet(this, _tickPromise)) {
@@ -849,17 +997,20 @@ nextTick_fn = function() {
849
997
  };
850
998
  publish_fn = function(messages) {
851
999
  return __async(this, null, function* () {
852
- yield Promise.all(
853
- Array.from(__privateGet(this, _subscribers).values()).map((_0) => __async(this, [_0], function* ([callback, __]) {
854
- try {
855
- yield callback(messages);
856
- } catch (err) {
857
- queueMicrotask(() => {
858
- throw err;
859
- });
860
- }
861
- }))
862
- );
1000
+ __privateSet(this, _messageChain, __privateGet(this, _messageChain).then(
1001
+ () => Promise.all(
1002
+ Array.from(__privateGet(this, _subscribers).values()).map((_0) => __async(this, [_0], function* ([callback, __]) {
1003
+ try {
1004
+ yield callback(messages);
1005
+ } catch (err) {
1006
+ queueMicrotask(() => {
1007
+ throw err;
1008
+ });
1009
+ }
1010
+ }))
1011
+ )
1012
+ ));
1013
+ return __privateGet(this, _messageChain);
863
1014
  });
864
1015
  };
865
1016
  sendErrorToSubscribers_fn = function(error) {
@@ -867,6 +1018,18 @@ sendErrorToSubscribers_fn = function(error) {
867
1018
  errorFn == null ? void 0 : errorFn(error);
868
1019
  });
869
1020
  };
1021
+ subscribeToVisibilityChanges_fn = function() {
1022
+ if (typeof document === `object` && typeof document.hidden === `boolean` && typeof document.addEventListener === `function`) {
1023
+ const visibilityHandler = () => {
1024
+ if (document.hidden) {
1025
+ __privateMethod(this, _ShapeStream_instances, pause_fn).call(this);
1026
+ } else {
1027
+ __privateMethod(this, _ShapeStream_instances, resume_fn).call(this);
1028
+ }
1029
+ };
1030
+ document.addEventListener(`visibilitychange`, visibilityHandler);
1031
+ }
1032
+ };
870
1033
  /**
871
1034
  * Resets the state of the stream, optionally with a provided
872
1035
  * shape handle