@powersync/common 1.50.0 → 1.52.0

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 (45) hide show
  1. package/dist/bundle.cjs +558 -481
  2. package/dist/bundle.cjs.map +1 -1
  3. package/dist/bundle.mjs +558 -480
  4. package/dist/bundle.mjs.map +1 -1
  5. package/dist/bundle.node.cjs +556 -481
  6. package/dist/bundle.node.cjs.map +1 -1
  7. package/dist/bundle.node.mjs +556 -480
  8. package/dist/bundle.node.mjs.map +1 -1
  9. package/dist/index.d.cts +73 -73
  10. package/lib/client/AbstractPowerSyncDatabase.js +3 -3
  11. package/lib/client/AbstractPowerSyncDatabase.js.map +1 -1
  12. package/lib/client/sync/stream/AbstractRemote.d.ts +29 -8
  13. package/lib/client/sync/stream/AbstractRemote.js +154 -177
  14. package/lib/client/sync/stream/AbstractRemote.js.map +1 -1
  15. package/lib/client/sync/stream/AbstractStreamingSyncImplementation.d.ts +1 -0
  16. package/lib/client/sync/stream/AbstractStreamingSyncImplementation.js +69 -88
  17. package/lib/client/sync/stream/AbstractStreamingSyncImplementation.js.map +1 -1
  18. package/lib/index.d.ts +1 -1
  19. package/lib/index.js +0 -1
  20. package/lib/index.js.map +1 -1
  21. package/lib/utils/async.d.ts +0 -9
  22. package/lib/utils/async.js +0 -9
  23. package/lib/utils/async.js.map +1 -1
  24. package/lib/utils/mutex.d.ts +32 -3
  25. package/lib/utils/mutex.js +85 -36
  26. package/lib/utils/mutex.js.map +1 -1
  27. package/lib/utils/queue.d.ts +16 -0
  28. package/lib/utils/queue.js +42 -0
  29. package/lib/utils/queue.js.map +1 -0
  30. package/lib/utils/stream_transform.d.ts +39 -0
  31. package/lib/utils/stream_transform.js +206 -0
  32. package/lib/utils/stream_transform.js.map +1 -0
  33. package/package.json +9 -7
  34. package/src/client/AbstractPowerSyncDatabase.ts +3 -3
  35. package/src/client/sync/stream/AbstractRemote.ts +182 -206
  36. package/src/client/sync/stream/AbstractStreamingSyncImplementation.ts +82 -83
  37. package/src/index.ts +1 -1
  38. package/src/utils/async.ts +0 -11
  39. package/src/utils/mutex.ts +111 -48
  40. package/src/utils/queue.ts +48 -0
  41. package/src/utils/stream_transform.ts +252 -0
  42. package/lib/utils/DataStream.d.ts +0 -62
  43. package/lib/utils/DataStream.js +0 -169
  44. package/lib/utils/DataStream.js.map +0 -1
  45. package/src/utils/DataStream.ts +0 -222
@@ -783,19 +783,69 @@ class SyncingService {
783
783
  }
784
784
 
785
785
  /**
786
- * An asynchronous mutex implementation.
786
+ * A simple fixed-capacity queue implementation.
787
+ *
788
+ * Unlike a naive queue implemented by `array.push()` and `array.shift()`, this avoids moving array elements around
789
+ * and is `O(1)` for {@link addLast} and {@link removeFirst}.
790
+ */
791
+ class Queue {
792
+ table;
793
+ // Index of the first element in the table.
794
+ head;
795
+ // Amount of items currently in the queue.
796
+ _length;
797
+ constructor(initialItems) {
798
+ this.table = [...initialItems];
799
+ this.head = 0;
800
+ this._length = this.table.length;
801
+ }
802
+ get isEmpty() {
803
+ return this.length == 0;
804
+ }
805
+ get length() {
806
+ return this._length;
807
+ }
808
+ removeFirst() {
809
+ if (this.isEmpty) {
810
+ throw new Error('Queue is empty');
811
+ }
812
+ const result = this.table[this.head];
813
+ this._length--;
814
+ this.table[this.head] = undefined;
815
+ this.head = (this.head + 1) % this.table.length;
816
+ return result;
817
+ }
818
+ addLast(element) {
819
+ if (this.length == this.table.length) {
820
+ throw new Error('Queue is full');
821
+ }
822
+ this.table[(this.head + this._length) % this.table.length] = element;
823
+ this._length++;
824
+ }
825
+ }
826
+
827
+ /**
828
+ * An asynchronous semaphore implementation with associated items per lease.
787
829
  *
788
830
  * @internal This class is meant to be used in PowerSync SDKs only, and is not part of the public API.
789
831
  */
790
- class Mutex {
791
- inCriticalSection = false;
832
+ class Semaphore {
833
+ // Available items that are not currently assigned to a waiter.
834
+ available;
835
+ size;
792
836
  // Linked list of waiters. We don't expect the wait list to become particularly large, and this allows removing
793
837
  // aborted waiters from the middle of the list efficiently.
794
838
  firstWaiter;
795
839
  lastWaiter;
796
- addWaiter(onAcquire) {
840
+ constructor(elements) {
841
+ this.available = new Queue(elements);
842
+ this.size = this.available.length;
843
+ }
844
+ addWaiter(requestedItems, onAcquire) {
797
845
  const node = {
798
846
  isActive: true,
847
+ acquiredItems: [],
848
+ remainingItems: requestedItems,
799
849
  onAcquire,
800
850
  prev: this.lastWaiter
801
851
  };
@@ -821,52 +871,92 @@ class Mutex {
821
871
  if (waiter == this.lastWaiter)
822
872
  this.lastWaiter = prev;
823
873
  }
824
- acquire(abort) {
874
+ requestPermits(amount, abort) {
875
+ if (amount <= 0 || amount > this.size) {
876
+ throw new Error(`Invalid amount of items requested (${amount}), must be between 1 and ${this.size}`);
877
+ }
825
878
  return new Promise((resolve, reject) => {
826
879
  function rejectAborted() {
827
- reject(abort?.reason ?? new Error('Mutex acquire aborted'));
880
+ reject(abort?.reason ?? new Error('Semaphore acquire aborted'));
828
881
  }
829
882
  if (abort?.aborted) {
830
883
  return rejectAborted();
831
884
  }
832
- let holdsMutex = false;
885
+ let waiter;
833
886
  const markCompleted = () => {
834
- if (!holdsMutex)
835
- return;
836
- holdsMutex = false;
837
- const waiter = this.firstWaiter;
838
- if (waiter) {
839
- this.deactivateWaiter(waiter);
840
- // Still in critical section, but owned by next waiter now.
841
- waiter.onAcquire();
887
+ const items = waiter.acquiredItems;
888
+ waiter.acquiredItems = []; // Avoid releasing items twice.
889
+ for (const element of items) {
890
+ // Give to next waiter, if possible.
891
+ const nextWaiter = this.firstWaiter;
892
+ if (nextWaiter) {
893
+ nextWaiter.acquiredItems.push(element);
894
+ nextWaiter.remainingItems--;
895
+ if (nextWaiter.remainingItems == 0) {
896
+ nextWaiter.onAcquire();
897
+ }
898
+ }
899
+ else {
900
+ // No pending waiter, return lease into pool.
901
+ this.available.addLast(element);
902
+ }
842
903
  }
843
- else {
844
- this.inCriticalSection = false;
904
+ };
905
+ const onAbort = () => {
906
+ abort?.removeEventListener('abort', onAbort);
907
+ if (waiter.isActive) {
908
+ this.deactivateWaiter(waiter);
909
+ rejectAborted();
845
910
  }
846
911
  };
847
- if (!this.inCriticalSection) {
848
- this.inCriticalSection = true;
849
- holdsMutex = true;
850
- return resolve(markCompleted);
912
+ const resolvePromise = () => {
913
+ this.deactivateWaiter(waiter);
914
+ abort?.removeEventListener('abort', onAbort);
915
+ const items = waiter.acquiredItems;
916
+ resolve({ items, release: markCompleted });
917
+ };
918
+ waiter = this.addWaiter(amount, resolvePromise);
919
+ // If there are items in the pool that haven't been assigned, we can pull them into this waiter. Note that this is
920
+ // only the case if we're the first waiter (otherwise, items would have been assigned to an earlier waiter).
921
+ while (!this.available.isEmpty && waiter.remainingItems > 0) {
922
+ waiter.acquiredItems.push(this.available.removeFirst());
923
+ waiter.remainingItems--;
851
924
  }
852
- else {
853
- let node;
854
- const onAbort = () => {
855
- abort?.removeEventListener('abort', onAbort);
856
- if (node.isActive) {
857
- this.deactivateWaiter(node);
858
- rejectAborted();
859
- }
860
- };
861
- node = this.addWaiter(() => {
862
- abort?.removeEventListener('abort', onAbort);
863
- holdsMutex = true;
864
- resolve(markCompleted);
865
- });
866
- abort?.addEventListener('abort', onAbort);
925
+ if (waiter.remainingItems == 0) {
926
+ return resolvePromise();
867
927
  }
928
+ abort?.addEventListener('abort', onAbort);
868
929
  });
869
930
  }
931
+ /**
932
+ * Requests a single item from the pool.
933
+ *
934
+ * The returned `release` callback must be invoked to return the item into the pool.
935
+ */
936
+ async requestOne(abort) {
937
+ const { items, release } = await this.requestPermits(1, abort);
938
+ return { release, item: items[0] };
939
+ }
940
+ /**
941
+ * Requests access to all items from the pool.
942
+ *
943
+ * The returned `release` callback must be invoked to return items into the pool.
944
+ */
945
+ requestAll(abort) {
946
+ return this.requestPermits(this.size, abort);
947
+ }
948
+ }
949
+ /**
950
+ * An asynchronous mutex implementation.
951
+ *
952
+ * @internal This class is meant to be used in PowerSync SDKs only, and is not part of the public API.
953
+ */
954
+ class Mutex {
955
+ inner = new Semaphore([null]);
956
+ async acquire(abort) {
957
+ const { release } = await this.inner.requestOne(abort);
958
+ return release;
959
+ }
870
960
  async runExclusive(fn, abort) {
871
961
  const returnMutex = await this.acquire(abort);
872
962
  try {
@@ -2165,15 +2255,6 @@ class ControlledExecutor {
2165
2255
  }
2166
2256
  }
2167
2257
 
2168
- /**
2169
- * A ponyfill for `Symbol.asyncIterator` that is compatible with the
2170
- * [recommended polyfill](https://github.com/Azure/azure-sdk-for-js/blob/%40azure/core-asynciterator-polyfill_1.0.2/sdk/core/core-asynciterator-polyfill/src/index.ts#L4-L6)
2171
- * we recommend for React Native.
2172
- *
2173
- * As long as we use this symbol (instead of `for await` and `async *`) in this package, we can be compatible with async
2174
- * iterators without requiring them.
2175
- */
2176
- const symbolAsyncIterator = Symbol.asyncIterator ?? Symbol.for('Symbol.asyncIterator');
2177
2258
  /**
2178
2259
  * Throttle a function to be called at most once every "wait" milliseconds,
2179
2260
  * on the trailing edge.
@@ -8139,177 +8220,10 @@ function requireDist () {
8139
8220
 
8140
8221
  var distExports = requireDist();
8141
8222
 
8142
- var version = "1.50.0";
8223
+ var version = "1.52.0";
8143
8224
  var PACKAGE = {
8144
8225
  version: version};
8145
8226
 
8146
- const DEFAULT_PRESSURE_LIMITS = {
8147
- highWater: 10,
8148
- lowWater: 0
8149
- };
8150
- /**
8151
- * A very basic implementation of a data stream with backpressure support which does not use
8152
- * native JS streams or async iterators.
8153
- * This is handy for environments such as React Native which need polyfills for the above.
8154
- */
8155
- class DataStream extends BaseObserver {
8156
- options;
8157
- dataQueue;
8158
- isClosed;
8159
- processingPromise;
8160
- notifyDataAdded;
8161
- logger;
8162
- mapLine;
8163
- constructor(options) {
8164
- super();
8165
- this.options = options;
8166
- this.processingPromise = null;
8167
- this.isClosed = false;
8168
- this.dataQueue = [];
8169
- this.mapLine = options?.mapLine ?? ((line) => line);
8170
- this.logger = options?.logger ?? Logger.get('DataStream');
8171
- if (options?.closeOnError) {
8172
- const l = this.registerListener({
8173
- error: (ex) => {
8174
- l?.();
8175
- this.close();
8176
- }
8177
- });
8178
- }
8179
- }
8180
- get highWatermark() {
8181
- return this.options?.pressure?.highWaterMark ?? DEFAULT_PRESSURE_LIMITS.highWater;
8182
- }
8183
- get lowWatermark() {
8184
- return this.options?.pressure?.lowWaterMark ?? DEFAULT_PRESSURE_LIMITS.lowWater;
8185
- }
8186
- get closed() {
8187
- return this.isClosed;
8188
- }
8189
- async close() {
8190
- this.isClosed = true;
8191
- await this.processingPromise;
8192
- this.iterateListeners((l) => l.closed?.());
8193
- // Discard any data in the queue
8194
- this.dataQueue = [];
8195
- this.listeners.clear();
8196
- }
8197
- /**
8198
- * Enqueues data for the consumers to read
8199
- */
8200
- enqueueData(data) {
8201
- if (this.isClosed) {
8202
- throw new Error('Cannot enqueue data into closed stream.');
8203
- }
8204
- this.dataQueue.push(data);
8205
- this.notifyDataAdded?.();
8206
- this.processQueue();
8207
- }
8208
- /**
8209
- * Reads data once from the data stream
8210
- * @returns a Data payload or Null if the stream closed.
8211
- */
8212
- async read() {
8213
- if (this.closed) {
8214
- return null;
8215
- }
8216
- // Wait for any pending processing to complete first.
8217
- // This ensures we register our listener before calling processQueue(),
8218
- // avoiding a race where processQueue() sees no reader and returns early.
8219
- if (this.processingPromise) {
8220
- await this.processingPromise;
8221
- }
8222
- // Re-check after await - stream may have closed while we were waiting
8223
- if (this.closed) {
8224
- return null;
8225
- }
8226
- return new Promise((resolve, reject) => {
8227
- const l = this.registerListener({
8228
- data: async (data) => {
8229
- resolve(data);
8230
- // Remove the listener
8231
- l?.();
8232
- },
8233
- closed: () => {
8234
- resolve(null);
8235
- l?.();
8236
- },
8237
- error: (ex) => {
8238
- reject(ex);
8239
- l?.();
8240
- }
8241
- });
8242
- this.processQueue();
8243
- });
8244
- }
8245
- /**
8246
- * Executes a callback for each data item in the stream
8247
- */
8248
- forEach(callback) {
8249
- if (this.dataQueue.length <= this.lowWatermark) {
8250
- this.iterateAsyncErrored(async (l) => l.lowWater?.());
8251
- }
8252
- return this.registerListener({
8253
- data: callback
8254
- });
8255
- }
8256
- processQueue() {
8257
- if (this.processingPromise) {
8258
- return;
8259
- }
8260
- const promise = (this.processingPromise = this._processQueue());
8261
- promise.finally(() => {
8262
- this.processingPromise = null;
8263
- });
8264
- return promise;
8265
- }
8266
- hasDataReader() {
8267
- return Array.from(this.listeners.values()).some((l) => !!l.data);
8268
- }
8269
- async _processQueue() {
8270
- /**
8271
- * Allow listeners to mutate the queue before processing.
8272
- * This allows for operations such as dropping or compressing data
8273
- * on high water or requesting more data on low water.
8274
- */
8275
- if (this.dataQueue.length >= this.highWatermark) {
8276
- await this.iterateAsyncErrored(async (l) => l.highWater?.());
8277
- }
8278
- if (this.isClosed || !this.hasDataReader()) {
8279
- return;
8280
- }
8281
- if (this.dataQueue.length) {
8282
- const data = this.dataQueue.shift();
8283
- const mapped = this.mapLine(data);
8284
- await this.iterateAsyncErrored(async (l) => l.data?.(mapped));
8285
- }
8286
- if (this.dataQueue.length <= this.lowWatermark) {
8287
- const dataAdded = new Promise((resolve) => {
8288
- this.notifyDataAdded = resolve;
8289
- });
8290
- await Promise.race([this.iterateAsyncErrored(async (l) => l.lowWater?.()), dataAdded]);
8291
- this.notifyDataAdded = null;
8292
- }
8293
- if (this.dataQueue.length > 0) {
8294
- setTimeout(() => this.processQueue());
8295
- }
8296
- }
8297
- async iterateAsyncErrored(cb) {
8298
- // Important: We need to copy the listeners, as calling a listener could result in adding another
8299
- // listener, resulting in infinite loops.
8300
- const listeners = Array.from(this.listeners.values());
8301
- for (let i of listeners) {
8302
- try {
8303
- await cb(i);
8304
- }
8305
- catch (ex) {
8306
- this.logger.error(ex);
8307
- this.iterateListeners((l) => l.error?.(ex));
8308
- }
8309
- }
8310
- }
8311
- }
8312
-
8313
8227
  var WebsocketDuplexConnection = {};
8314
8228
 
8315
8229
  var hasRequiredWebsocketDuplexConnection;
@@ -8472,8 +8386,215 @@ class WebsocketClientTransport {
8472
8386
  }
8473
8387
  }
8474
8388
 
8389
+ const doneResult = { done: true, value: undefined };
8390
+ function valueResult(value) {
8391
+ return { done: false, value };
8392
+ }
8393
+ /**
8394
+ * A variant of {@link Array.map} for async iterators.
8395
+ */
8396
+ function map(source, map) {
8397
+ return {
8398
+ next: async () => {
8399
+ const value = await source.next();
8400
+ if (value.done) {
8401
+ return value;
8402
+ }
8403
+ else {
8404
+ return { value: map(value.value) };
8405
+ }
8406
+ }
8407
+ };
8408
+ }
8409
+ /**
8410
+ * Expands a source async iterator by allowing to inject events asynchronously.
8411
+ *
8412
+ * The resulting iterator will emit all events from its source. Additionally though, events can be injected. These
8413
+ * events are dropped once the main iterator completes, but are otherwise forwarded.
8414
+ *
8415
+ * The iterator completes when its source completes, and it supports backpressure by only calling `next()` on the source
8416
+ * in response to a `next()` call from downstream if no pending injected events can be dispatched.
8417
+ */
8418
+ function injectable(source) {
8419
+ let sourceIsDone = false;
8420
+ let waiter = undefined; // An active, waiting next() call.
8421
+ // A pending upstream event that couldn't be dispatched because inject() has been called before it was resolved.
8422
+ let pendingSourceEvent = null;
8423
+ let pendingInjectedEvents = [];
8424
+ const consumeWaiter = () => {
8425
+ const pending = waiter;
8426
+ waiter = undefined;
8427
+ return pending;
8428
+ };
8429
+ const fetchFromSource = () => {
8430
+ const resolveWaiter = (propagate) => {
8431
+ const active = consumeWaiter();
8432
+ if (active) {
8433
+ propagate(active);
8434
+ }
8435
+ else {
8436
+ pendingSourceEvent = propagate;
8437
+ }
8438
+ };
8439
+ const nextFromSource = source.next();
8440
+ nextFromSource.then((value) => {
8441
+ sourceIsDone = value.done == true;
8442
+ resolveWaiter((w) => w.resolve(value));
8443
+ }, (error) => {
8444
+ resolveWaiter((w) => w.reject(error));
8445
+ });
8446
+ };
8447
+ return {
8448
+ next: () => {
8449
+ return new Promise((resolve, reject) => {
8450
+ // First priority: Dispatch ready upstream events.
8451
+ if (sourceIsDone) {
8452
+ return resolve(doneResult);
8453
+ }
8454
+ if (pendingSourceEvent) {
8455
+ pendingSourceEvent({ resolve, reject });
8456
+ pendingSourceEvent = null;
8457
+ return;
8458
+ }
8459
+ // Second priority: Dispatch injected events
8460
+ if (pendingInjectedEvents.length) {
8461
+ return resolve(valueResult(pendingInjectedEvents.shift()));
8462
+ }
8463
+ // Nothing pending? Fetch from source
8464
+ waiter = { resolve, reject };
8465
+ return fetchFromSource();
8466
+ });
8467
+ },
8468
+ inject: (event) => {
8469
+ const pending = consumeWaiter();
8470
+ if (pending != null) {
8471
+ pending.resolve(valueResult(event));
8472
+ }
8473
+ else {
8474
+ pendingInjectedEvents.push(event);
8475
+ }
8476
+ }
8477
+ };
8478
+ }
8479
+ /**
8480
+ * Splits a byte stream at line endings, emitting each line as a string.
8481
+ */
8482
+ function extractJsonLines(source, decoder) {
8483
+ let buffer = '';
8484
+ const pendingLines = [];
8485
+ let isFinalEvent = false;
8486
+ return {
8487
+ next: async () => {
8488
+ while (true) {
8489
+ if (isFinalEvent) {
8490
+ return doneResult;
8491
+ }
8492
+ {
8493
+ const first = pendingLines.shift();
8494
+ if (first) {
8495
+ return { done: false, value: first };
8496
+ }
8497
+ }
8498
+ const { done, value } = await source.next();
8499
+ if (done) {
8500
+ const remaining = buffer.trim();
8501
+ if (remaining.length != 0) {
8502
+ isFinalEvent = true;
8503
+ return { done: false, value: remaining };
8504
+ }
8505
+ return doneResult;
8506
+ }
8507
+ const data = decoder.decode(value, { stream: true });
8508
+ buffer += data;
8509
+ const lines = buffer.split('\n');
8510
+ for (let i = 0; i < lines.length - 1; i++) {
8511
+ const l = lines[i].trim();
8512
+ if (l.length > 0) {
8513
+ pendingLines.push(l);
8514
+ }
8515
+ }
8516
+ buffer = lines[lines.length - 1];
8517
+ }
8518
+ }
8519
+ };
8520
+ }
8521
+ /**
8522
+ * Splits a concatenated stream of BSON objects by emitting individual objects.
8523
+ */
8524
+ function extractBsonObjects(source) {
8525
+ // Fully read but not emitted yet.
8526
+ const completedObjects = [];
8527
+ // Whether source has returned { done: true }. We do the same once completed objects have been emitted.
8528
+ let isDone = false;
8529
+ const lengthBuffer = new DataView(new ArrayBuffer(4));
8530
+ let objectBody = null;
8531
+ // If we're parsing the length field, a number between 1 and 4 (inclusive) describing remaining bytes in the header.
8532
+ // If we're consuming a document, the bytes remaining.
8533
+ let remainingLength = 4;
8534
+ return {
8535
+ async next() {
8536
+ while (true) {
8537
+ // Before fetching new data from upstream, return completed objects.
8538
+ if (completedObjects.length) {
8539
+ return valueResult(completedObjects.shift());
8540
+ }
8541
+ if (isDone) {
8542
+ return doneResult;
8543
+ }
8544
+ const upstreamEvent = await source.next();
8545
+ if (upstreamEvent.done) {
8546
+ isDone = true;
8547
+ if (objectBody || remainingLength != 4) {
8548
+ throw new Error('illegal end of stream in BSON object');
8549
+ }
8550
+ return doneResult;
8551
+ }
8552
+ const chunk = upstreamEvent.value;
8553
+ for (let i = 0; i < chunk.length;) {
8554
+ const availableInData = chunk.length - i;
8555
+ if (objectBody) {
8556
+ // We're in the middle of reading a BSON document.
8557
+ const bytesToRead = Math.min(availableInData, remainingLength);
8558
+ const copySource = new Uint8Array(chunk.buffer, chunk.byteOffset + i, bytesToRead);
8559
+ objectBody.set(copySource, objectBody.length - remainingLength);
8560
+ i += bytesToRead;
8561
+ remainingLength -= bytesToRead;
8562
+ if (remainingLength == 0) {
8563
+ completedObjects.push(objectBody);
8564
+ // Prepare to read another document, starting with its length
8565
+ objectBody = null;
8566
+ remainingLength = 4;
8567
+ }
8568
+ }
8569
+ else {
8570
+ // Copy up to 4 bytes into lengthBuffer, depending on how many we still need.
8571
+ const bytesToRead = Math.min(availableInData, remainingLength);
8572
+ for (let j = 0; j < bytesToRead; j++) {
8573
+ lengthBuffer.setUint8(4 - remainingLength + j, chunk[i + j]);
8574
+ }
8575
+ i += bytesToRead;
8576
+ remainingLength -= bytesToRead;
8577
+ if (remainingLength == 0) {
8578
+ // Transition from reading length header to reading document. Subtracting 4 because the length of the
8579
+ // header is included in length.
8580
+ const length = lengthBuffer.getInt32(0, true /* little endian */);
8581
+ remainingLength = length - 4;
8582
+ if (remainingLength < 1) {
8583
+ throw new Error(`invalid length for bson: ${length}`);
8584
+ }
8585
+ objectBody = new Uint8Array(length);
8586
+ new DataView(objectBody.buffer).setInt32(0, length, true);
8587
+ }
8588
+ }
8589
+ }
8590
+ }
8591
+ }
8592
+ };
8593
+ }
8594
+
8475
8595
  const POWERSYNC_TRAILING_SLASH_MATCH = /\/+$/;
8476
8596
  const POWERSYNC_JS_VERSION = PACKAGE.version;
8597
+ const SYNC_QUEUE_REQUEST_HIGH_WATER = 10;
8477
8598
  const SYNC_QUEUE_REQUEST_LOW_WATER = 5;
8478
8599
  // Keep alive message is sent every period
8479
8600
  const KEEP_ALIVE_MS = 20_000;
@@ -8653,13 +8774,14 @@ class AbstractRemote {
8653
8774
  return new WebSocket(url);
8654
8775
  }
8655
8776
  /**
8656
- * Returns a data stream of sync line data.
8777
+ * Returns a data stream of sync line data, fetched via RSocket-over-WebSocket.
8778
+ *
8779
+ * The only mechanism to abort the returned stream is to use the abort signal in {@link SocketSyncStreamOptions}.
8657
8780
  *
8658
- * @param map Maps received payload frames to the typed event value.
8659
8781
  * @param bson A BSON encoder and decoder. When set, the data stream will be requested with a BSON payload
8660
8782
  * (required for compatibility with older sync services).
8661
8783
  */
8662
- async socketStreamRaw(options, map, bson) {
8784
+ async socketStreamRaw(options, bson) {
8663
8785
  const { path, fetchStrategy = FetchStrategy.Buffered } = options;
8664
8786
  const mimeType = bson == null ? 'application/json' : 'application/bson';
8665
8787
  function toBuffer(js) {
@@ -8674,52 +8796,55 @@ class AbstractRemote {
8674
8796
  }
8675
8797
  const syncQueueRequestSize = fetchStrategy == FetchStrategy.Buffered ? 10 : 1;
8676
8798
  const request = await this.buildRequest(path);
8799
+ const url = this.options.socketUrlTransformer(request.url);
8677
8800
  // Add the user agent in the setup payload - we can't set custom
8678
8801
  // headers with websockets on web. The browser userAgent is however added
8679
8802
  // automatically as a header.
8680
8803
  const userAgent = this.getUserAgent();
8681
- const stream = new DataStream({
8682
- logger: this.logger,
8683
- pressure: {
8684
- lowWaterMark: SYNC_QUEUE_REQUEST_LOW_WATER
8685
- },
8686
- mapLine: map
8687
- });
8804
+ // While we're connecting (a process that can't be aborted in RSocket), the WebSocket instance to close if we wanted
8805
+ // to abort the connection.
8806
+ let pendingSocket = null;
8807
+ let keepAliveTimeout;
8808
+ let rsocket = null;
8809
+ let queue = null;
8810
+ let didClose = false;
8811
+ const abortRequest = () => {
8812
+ if (didClose) {
8813
+ return;
8814
+ }
8815
+ didClose = true;
8816
+ clearTimeout(keepAliveTimeout);
8817
+ if (pendingSocket) {
8818
+ pendingSocket.close();
8819
+ }
8820
+ if (rsocket) {
8821
+ rsocket.close();
8822
+ }
8823
+ if (queue) {
8824
+ queue.stop();
8825
+ }
8826
+ };
8688
8827
  // Handle upstream abort
8689
- if (options.abortSignal?.aborted) {
8828
+ if (options.abortSignal.aborted) {
8690
8829
  throw new AbortOperation('Connection request aborted');
8691
8830
  }
8692
8831
  else {
8693
- options.abortSignal?.addEventListener('abort', () => {
8694
- stream.close();
8695
- }, { once: true });
8832
+ options.abortSignal.addEventListener('abort', abortRequest);
8696
8833
  }
8697
- let keepAliveTimeout;
8698
8834
  const resetTimeout = () => {
8699
8835
  clearTimeout(keepAliveTimeout);
8700
8836
  keepAliveTimeout = setTimeout(() => {
8701
8837
  this.logger.error(`No data received on WebSocket in ${SOCKET_TIMEOUT_MS}ms, closing connection.`);
8702
- stream.close();
8838
+ abortRequest();
8703
8839
  }, SOCKET_TIMEOUT_MS);
8704
8840
  };
8705
8841
  resetTimeout();
8706
- // Typescript complains about this being `never` if it's not assigned here.
8707
- // This is assigned in `wsCreator`.
8708
- let disposeSocketConnectionTimeout = () => { };
8709
- const url = this.options.socketUrlTransformer(request.url);
8710
8842
  const connector = new distExports.RSocketConnector({
8711
8843
  transport: new WebsocketClientTransport({
8712
8844
  url,
8713
8845
  wsCreator: (url) => {
8714
- const socket = this.createSocket(url);
8715
- disposeSocketConnectionTimeout = stream.registerListener({
8716
- closed: () => {
8717
- // Allow closing the underlying WebSocket if the stream was closed before the
8718
- // RSocket connect completed. This should effectively abort the request.
8719
- socket.close();
8720
- }
8721
- });
8722
- socket.addEventListener('message', (event) => {
8846
+ const socket = (pendingSocket = this.createSocket(url));
8847
+ socket.addEventListener('message', () => {
8723
8848
  resetTimeout();
8724
8849
  });
8725
8850
  return socket;
@@ -8739,43 +8864,40 @@ class AbstractRemote {
8739
8864
  }
8740
8865
  }
8741
8866
  });
8742
- let rsocket;
8743
8867
  try {
8744
8868
  rsocket = await connector.connect();
8745
8869
  // The connection is established, we no longer need to monitor the initial timeout
8746
- disposeSocketConnectionTimeout();
8870
+ pendingSocket = null;
8747
8871
  }
8748
8872
  catch (ex) {
8749
8873
  this.logger.error(`Failed to connect WebSocket`, ex);
8750
- clearTimeout(keepAliveTimeout);
8751
- if (!stream.closed) {
8752
- await stream.close();
8753
- }
8874
+ abortRequest();
8754
8875
  throw ex;
8755
8876
  }
8756
8877
  resetTimeout();
8757
- let socketIsClosed = false;
8758
- const closeSocket = () => {
8759
- clearTimeout(keepAliveTimeout);
8760
- if (socketIsClosed) {
8761
- return;
8762
- }
8763
- socketIsClosed = true;
8764
- rsocket.close();
8765
- };
8766
8878
  // Helps to prevent double close scenarios
8767
- rsocket.onClose(() => (socketIsClosed = true));
8768
- // We initially request this amount and expect these to arrive eventually
8769
- let pendingEventsCount = syncQueueRequestSize;
8770
- const disposeClosedListener = stream.registerListener({
8771
- closed: () => {
8772
- closeSocket();
8773
- disposeClosedListener();
8774
- }
8775
- });
8776
- const socket = await new Promise((resolve, reject) => {
8879
+ rsocket.onClose(() => (rsocket = null));
8880
+ return await new Promise((resolve, reject) => {
8777
8881
  let connectionEstablished = false;
8778
- const res = rsocket.requestStream({
8882
+ let pendingEventsCount = syncQueueRequestSize;
8883
+ let paused = false;
8884
+ let res = null;
8885
+ function requestMore() {
8886
+ const delta = syncQueueRequestSize - pendingEventsCount;
8887
+ if (!paused && delta > 0) {
8888
+ res?.request(delta);
8889
+ pendingEventsCount = syncQueueRequestSize;
8890
+ }
8891
+ }
8892
+ const events = new EventIterator((q) => {
8893
+ queue = q;
8894
+ q.on('highWater', () => (paused = true));
8895
+ q.on('lowWater', () => {
8896
+ paused = false;
8897
+ requestMore();
8898
+ });
8899
+ }, { highWaterMark: SYNC_QUEUE_REQUEST_HIGH_WATER, lowWaterMark: SYNC_QUEUE_REQUEST_LOW_WATER })[Symbol.asyncIterator]();
8900
+ res = rsocket.requestStream({
8779
8901
  data: toBuffer(options.data),
8780
8902
  metadata: toBuffer({
8781
8903
  path
@@ -8800,7 +8922,7 @@ class AbstractRemote {
8800
8922
  }
8801
8923
  // RSocket will close the RSocket stream automatically
8802
8924
  // Close the downstream stream as well - this will close the RSocket connection and WebSocket
8803
- stream.close();
8925
+ abortRequest();
8804
8926
  // Handles cases where the connection failed e.g. auth error or connection error
8805
8927
  if (!connectionEstablished) {
8806
8928
  reject(e);
@@ -8810,41 +8932,40 @@ class AbstractRemote {
8810
8932
  // The connection is active
8811
8933
  if (!connectionEstablished) {
8812
8934
  connectionEstablished = true;
8813
- resolve(res);
8935
+ resolve(events);
8814
8936
  }
8815
8937
  const { data } = payload;
8938
+ if (data) {
8939
+ queue.push(data);
8940
+ }
8816
8941
  // Less events are now pending
8817
8942
  pendingEventsCount--;
8818
- if (!data) {
8819
- return;
8820
- }
8821
- stream.enqueueData(data);
8943
+ // Request another event (unless the downstream consumer is paused).
8944
+ requestMore();
8822
8945
  },
8823
8946
  onComplete: () => {
8824
- stream.close();
8947
+ abortRequest(); // this will also emit a done event
8825
8948
  },
8826
8949
  onExtension: () => { }
8827
8950
  });
8828
8951
  });
8829
- const l = stream.registerListener({
8830
- lowWater: async () => {
8831
- // Request to fill up the queue
8832
- const required = syncQueueRequestSize - pendingEventsCount;
8833
- if (required > 0) {
8834
- socket.request(syncQueueRequestSize - pendingEventsCount);
8835
- pendingEventsCount = syncQueueRequestSize;
8836
- }
8837
- },
8838
- closed: () => {
8839
- l();
8840
- }
8841
- });
8842
- return stream;
8843
8952
  }
8844
8953
  /**
8845
- * Connects to the sync/stream http endpoint, mapping and emitting each received string line.
8954
+ * @returns Whether the HTTP implementation on this platform can receive streamed binary responses. This is true on
8955
+ * all platforms except React Native (who would have guessed...), where we must not request BSON responses.
8956
+ *
8957
+ * @see https://github.com/react-native-community/fetch?tab=readme-ov-file#motivation
8958
+ */
8959
+ get supportsStreamingBinaryResponses() {
8960
+ return true;
8961
+ }
8962
+ /**
8963
+ * Posts a `/sync/stream` request, asserts that it completes successfully and returns the streaming response as an
8964
+ * async iterator of byte blobs.
8965
+ *
8966
+ * To cancel the async iterator, use the abort signal from {@link SyncStreamOptions} passed to this method.
8846
8967
  */
8847
- async postStreamRaw(options, mapLine) {
8968
+ async fetchStreamRaw(options) {
8848
8969
  const { data, path, headers, abortSignal } = options;
8849
8970
  const request = await this.buildRequest(path);
8850
8971
  /**
@@ -8856,119 +8977,94 @@ class AbstractRemote {
8856
8977
  * Aborting the active fetch request while it is being consumed seems to throw
8857
8978
  * an unhandled exception on the window level.
8858
8979
  */
8859
- if (abortSignal?.aborted) {
8860
- throw new AbortOperation('Abort request received before making postStreamRaw request');
8980
+ if (abortSignal.aborted) {
8981
+ throw new AbortOperation('Abort request received before making fetchStreamRaw request');
8861
8982
  }
8862
8983
  const controller = new AbortController();
8863
- let requestResolved = false;
8864
- abortSignal?.addEventListener('abort', () => {
8865
- if (!requestResolved) {
8984
+ let reader = null;
8985
+ abortSignal.addEventListener('abort', () => {
8986
+ const reason = abortSignal.reason ??
8987
+ new AbortOperation('Cancelling network request before it resolves. Abort signal has been received.');
8988
+ if (reader == null) {
8866
8989
  // Only abort via the abort controller if the request has not resolved yet
8867
- controller.abort(abortSignal.reason ??
8868
- new AbortOperation('Cancelling network request before it resolves. Abort signal has been received.'));
8990
+ controller.abort(reason);
8991
+ }
8992
+ else {
8993
+ reader.cancel(reason).catch(() => {
8994
+ // Cancelling the reader might rethrow an exception we would have handled by throwing in next(). So we can
8995
+ // ignore it here.
8996
+ });
8869
8997
  }
8870
8998
  });
8871
- const res = await this.fetch(request.url, {
8872
- method: 'POST',
8873
- headers: { ...headers, ...request.headers },
8874
- body: JSON.stringify(data),
8875
- signal: controller.signal,
8876
- cache: 'no-store',
8877
- ...(this.options.fetchOptions ?? {}),
8878
- ...options.fetchOptions
8879
- }).catch((ex) => {
8999
+ let res;
9000
+ let responseIsBson = false;
9001
+ try {
9002
+ const ndJson = 'application/x-ndjson';
9003
+ const bson = 'application/vnd.powersync.bson-stream';
9004
+ res = await this.fetch(request.url, {
9005
+ method: 'POST',
9006
+ headers: {
9007
+ ...headers,
9008
+ ...request.headers,
9009
+ accept: this.supportsStreamingBinaryResponses ? `${bson};q=0.9,${ndJson};q=0.8` : ndJson
9010
+ },
9011
+ body: JSON.stringify(data),
9012
+ signal: controller.signal,
9013
+ cache: 'no-store',
9014
+ ...(this.options.fetchOptions ?? {}),
9015
+ ...options.fetchOptions
9016
+ });
9017
+ if (!res.ok || !res.body) {
9018
+ const text = await res.text();
9019
+ this.logger.error(`Could not POST streaming to ${path} - ${res.status} - ${res.statusText}: ${text}`);
9020
+ const error = new Error(`HTTP ${res.statusText}: ${text}`);
9021
+ error.status = res.status;
9022
+ throw error;
9023
+ }
9024
+ const contentType = res.headers.get('content-type');
9025
+ responseIsBson = contentType == bson;
9026
+ }
9027
+ catch (ex) {
8880
9028
  if (ex.name == 'AbortError') {
8881
9029
  throw new AbortOperation(`Pending fetch request to ${request.url} has been aborted.`);
8882
9030
  }
8883
9031
  throw ex;
8884
- });
8885
- if (!res) {
8886
- throw new Error('Fetch request was aborted');
8887
- }
8888
- requestResolved = true;
8889
- if (!res.ok || !res.body) {
8890
- const text = await res.text();
8891
- this.logger.error(`Could not POST streaming to ${path} - ${res.status} - ${res.statusText}: ${text}`);
8892
- const error = new Error(`HTTP ${res.statusText}: ${text}`);
8893
- error.status = res.status;
8894
- throw error;
8895
9032
  }
8896
- // Create a new stream splitting the response at line endings while also handling cancellations
8897
- // by closing the reader.
8898
- const reader = res.body.getReader();
8899
- let readerReleased = false;
8900
- // This will close the network request and read stream
8901
- const closeReader = async () => {
8902
- try {
8903
- readerReleased = true;
8904
- await reader.cancel();
8905
- }
8906
- catch (ex) {
8907
- // an error will throw if the reader hasn't been used yet
8908
- }
8909
- reader.releaseLock();
8910
- };
8911
- const stream = new DataStream({
8912
- logger: this.logger,
8913
- mapLine: mapLine,
8914
- pressure: {
8915
- highWaterMark: 20,
8916
- lowWaterMark: 10
8917
- }
8918
- });
8919
- abortSignal?.addEventListener('abort', () => {
8920
- closeReader();
8921
- stream.close();
8922
- });
8923
- const decoder = this.createTextDecoder();
8924
- let buffer = '';
8925
- const consumeStream = async () => {
8926
- while (!stream.closed && !abortSignal?.aborted && !readerReleased) {
8927
- const { done, value } = await reader.read();
8928
- if (done) {
8929
- const remaining = buffer.trim();
8930
- if (remaining.length != 0) {
8931
- stream.enqueueData(remaining);
8932
- }
8933
- stream.close();
8934
- await closeReader();
8935
- return;
9033
+ reader = res.body.getReader();
9034
+ const stream = {
9035
+ next: async () => {
9036
+ if (controller.signal.aborted) {
9037
+ return doneResult;
8936
9038
  }
8937
- const data = decoder.decode(value, { stream: true });
8938
- buffer += data;
8939
- const lines = buffer.split('\n');
8940
- for (var i = 0; i < lines.length - 1; i++) {
8941
- var l = lines[i].trim();
8942
- if (l.length > 0) {
8943
- stream.enqueueData(l);
8944
- }
9039
+ try {
9040
+ return await reader.read();
8945
9041
  }
8946
- buffer = lines[lines.length - 1];
8947
- // Implement backpressure by waiting for the low water mark to be reached
8948
- if (stream.dataQueue.length > stream.highWatermark) {
8949
- await new Promise((resolve) => {
8950
- const dispose = stream.registerListener({
8951
- lowWater: async () => {
8952
- resolve();
8953
- dispose();
8954
- },
8955
- closed: () => {
8956
- resolve();
8957
- dispose();
8958
- }
8959
- });
8960
- });
9042
+ catch (ex) {
9043
+ if (controller.signal.aborted) {
9044
+ // .read() completes with an error if we cancel the reader, which we do to disconnect. So this is just
9045
+ // things working as intended, we can return a done event and consider the exception handled.
9046
+ return doneResult;
9047
+ }
9048
+ throw ex;
8961
9049
  }
8962
9050
  }
8963
9051
  };
8964
- consumeStream().catch(ex => this.logger.error('Error consuming stream', ex));
8965
- const l = stream.registerListener({
8966
- closed: () => {
8967
- closeReader();
8968
- l?.();
8969
- }
8970
- });
8971
- return stream;
9052
+ return { isBson: responseIsBson, stream };
9053
+ }
9054
+ /**
9055
+ * Posts a `/sync/stream` request.
9056
+ *
9057
+ * Depending on the `Content-Type` of the response, this returns strings for sync lines or encoded BSON documents as
9058
+ * {@link Uint8Array}s.
9059
+ */
9060
+ async fetchStream(options) {
9061
+ const { isBson, stream } = await this.fetchStreamRaw(options);
9062
+ if (isBson) {
9063
+ return extractBsonObjects(stream);
9064
+ }
9065
+ else {
9066
+ return extractJsonLines(stream, this.createTextDecoder());
9067
+ }
8972
9068
  }
8973
9069
  }
8974
9070
 
@@ -9476,6 +9572,19 @@ The next upload iteration will be delayed.`);
9476
9572
  }
9477
9573
  });
9478
9574
  }
9575
+ async receiveSyncLines(data) {
9576
+ const { options, connection, bson } = data;
9577
+ const remote = this.options.remote;
9578
+ if (connection.connectionMethod == SyncStreamConnectionMethod.HTTP) {
9579
+ return await remote.fetchStream(options);
9580
+ }
9581
+ else {
9582
+ return await this.options.remote.socketStreamRaw({
9583
+ ...options,
9584
+ ...{ fetchStrategy: connection.fetchStrategy }
9585
+ }, bson);
9586
+ }
9587
+ }
9479
9588
  async legacyStreamingSyncIteration(signal, resolvedOptions) {
9480
9589
  const rawTables = resolvedOptions.serializedSchema?.raw_tables;
9481
9590
  if (rawTables != null && rawTables.length) {
@@ -9505,42 +9614,27 @@ The next upload iteration will be delayed.`);
9505
9614
  client_id: clientId
9506
9615
  }
9507
9616
  };
9508
- let stream;
9509
- if (resolvedOptions?.connectionMethod == SyncStreamConnectionMethod.HTTP) {
9510
- stream = await this.options.remote.postStreamRaw(syncOptions, (line) => {
9511
- if (typeof line == 'string') {
9512
- return JSON.parse(line);
9513
- }
9514
- else {
9515
- // Directly enqueued by us
9516
- return line;
9517
- }
9518
- });
9519
- }
9520
- else {
9521
- const bson = await this.options.remote.getBSON();
9522
- stream = await this.options.remote.socketStreamRaw({
9523
- ...syncOptions,
9524
- ...{ fetchStrategy: resolvedOptions.fetchStrategy }
9525
- }, (payload) => {
9526
- if (payload instanceof Uint8Array) {
9527
- return bson.deserialize(payload);
9528
- }
9529
- else {
9530
- // Directly enqueued by us
9531
- return payload;
9532
- }
9533
- }, bson);
9534
- }
9617
+ const bson = await this.options.remote.getBSON();
9618
+ const source = await this.receiveSyncLines({
9619
+ options: syncOptions,
9620
+ connection: resolvedOptions,
9621
+ bson
9622
+ });
9623
+ const stream = injectable(map(source, (line) => {
9624
+ if (typeof line == 'string') {
9625
+ return JSON.parse(line);
9626
+ }
9627
+ else {
9628
+ return bson.deserialize(line);
9629
+ }
9630
+ }));
9535
9631
  this.logger.debug('Stream established. Processing events');
9536
9632
  this.notifyCompletedUploads = () => {
9537
- if (!stream.closed) {
9538
- stream.enqueueData({ crud_upload_completed: null });
9539
- }
9633
+ stream.inject({ crud_upload_completed: null });
9540
9634
  };
9541
- while (!stream.closed) {
9542
- const line = await stream.read();
9543
- if (!line) {
9635
+ while (true) {
9636
+ const { value: line, done } = await stream.next();
9637
+ if (done) {
9544
9638
  // The stream has closed while waiting
9545
9639
  return;
9546
9640
  }
@@ -9719,14 +9813,17 @@ The next upload iteration will be delayed.`);
9719
9813
  const syncImplementation = this;
9720
9814
  const adapter = this.options.adapter;
9721
9815
  const remote = this.options.remote;
9816
+ const controller = new AbortController();
9817
+ const abort = () => {
9818
+ return controller.abort(signal.reason);
9819
+ };
9820
+ signal.addEventListener('abort', abort);
9722
9821
  let receivingLines = null;
9723
9822
  let hadSyncLine = false;
9724
9823
  let hideDisconnectOnRestart = false;
9725
9824
  if (signal.aborted) {
9726
9825
  throw new AbortOperation('Connection request has been aborted');
9727
9826
  }
9728
- const abortController = new AbortController();
9729
- signal.addEventListener('abort', () => abortController.abort());
9730
9827
  // Pending sync lines received from the service, as well as local events that trigger a powersync_control
9731
9828
  // invocation (local events include refreshed tokens and completed uploads).
9732
9829
  // This is a single data stream so that we can handle all control calls from a single place.
@@ -9734,49 +9831,36 @@ The next upload iteration will be delayed.`);
9734
9831
  async function connect(instr) {
9735
9832
  const syncOptions = {
9736
9833
  path: '/sync/stream',
9737
- abortSignal: abortController.signal,
9834
+ abortSignal: controller.signal,
9738
9835
  data: instr.request
9739
9836
  };
9740
- if (resolvedOptions.connectionMethod == SyncStreamConnectionMethod.HTTP) {
9741
- controlInvocations = await remote.postStreamRaw(syncOptions, (line) => {
9742
- if (typeof line == 'string') {
9743
- return {
9744
- command: PowerSyncControlCommand.PROCESS_TEXT_LINE,
9745
- payload: line
9746
- };
9747
- }
9748
- else {
9749
- // Directly enqueued by us
9750
- return line;
9751
- }
9752
- });
9753
- }
9754
- else {
9755
- controlInvocations = await remote.socketStreamRaw({
9756
- ...syncOptions,
9757
- fetchStrategy: resolvedOptions.fetchStrategy
9758
- }, (payload) => {
9759
- if (payload instanceof Uint8Array) {
9760
- return {
9761
- command: PowerSyncControlCommand.PROCESS_BSON_LINE,
9762
- payload: payload
9763
- };
9764
- }
9765
- else {
9766
- // Directly enqueued by us
9767
- return payload;
9768
- }
9769
- });
9770
- }
9837
+ controlInvocations = injectable(map(await syncImplementation.receiveSyncLines({
9838
+ options: syncOptions,
9839
+ connection: resolvedOptions
9840
+ }), (line) => {
9841
+ if (typeof line == 'string') {
9842
+ return {
9843
+ command: PowerSyncControlCommand.PROCESS_TEXT_LINE,
9844
+ payload: line
9845
+ };
9846
+ }
9847
+ else {
9848
+ return {
9849
+ command: PowerSyncControlCommand.PROCESS_BSON_LINE,
9850
+ payload: line
9851
+ };
9852
+ }
9853
+ }));
9771
9854
  // The rust client will set connected: true after the first sync line because that's when it gets invoked, but
9772
9855
  // we're already connected here and can report that.
9773
9856
  syncImplementation.updateSyncStatus({ connected: true });
9774
9857
  try {
9775
- while (!controlInvocations.closed) {
9776
- const line = await controlInvocations.read();
9777
- if (line == null) {
9778
- return;
9858
+ while (true) {
9859
+ let event = await controlInvocations.next();
9860
+ if (event.done) {
9861
+ break;
9779
9862
  }
9863
+ const line = event.value;
9780
9864
  await control(line.command, line.payload);
9781
9865
  if (!hadSyncLine) {
9782
9866
  syncImplementation.triggerCrudUpload();
@@ -9785,12 +9869,8 @@ The next upload iteration will be delayed.`);
9785
9869
  }
9786
9870
  }
9787
9871
  finally {
9788
- const activeInstructions = controlInvocations;
9789
- // We concurrently add events to the active data stream when e.g. a CRUD upload is completed or a token is
9790
- // refreshed. That would throw after closing (and we can't handle those events either way), so set this back
9791
- // to null.
9792
- controlInvocations = null;
9793
- await activeInstructions.close();
9872
+ abort();
9873
+ signal.removeEventListener('abort', abort);
9794
9874
  }
9795
9875
  }
9796
9876
  async function stop() {
@@ -9834,14 +9914,14 @@ The next upload iteration will be delayed.`);
9834
9914
  remote.invalidateCredentials();
9835
9915
  // Restart iteration after the credentials have been refreshed.
9836
9916
  remote.fetchCredentials().then((_) => {
9837
- controlInvocations?.enqueueData({ command: PowerSyncControlCommand.NOTIFY_TOKEN_REFRESHED });
9917
+ controlInvocations?.inject({ command: PowerSyncControlCommand.NOTIFY_TOKEN_REFRESHED });
9838
9918
  }, (err) => {
9839
9919
  syncImplementation.logger.warn('Could not prefetch credentials', err);
9840
9920
  });
9841
9921
  }
9842
9922
  }
9843
9923
  else if ('CloseSyncStream' in instruction) {
9844
- abortController.abort();
9924
+ controller.abort();
9845
9925
  hideDisconnectOnRestart = instruction.CloseSyncStream.hide_disconnect;
9846
9926
  }
9847
9927
  else if ('FlushFileSystem' in instruction) ;
@@ -9870,17 +9950,13 @@ The next upload iteration will be delayed.`);
9870
9950
  }
9871
9951
  await control(PowerSyncControlCommand.START, JSON.stringify(options));
9872
9952
  this.notifyCompletedUploads = () => {
9873
- if (controlInvocations && !controlInvocations?.closed) {
9874
- controlInvocations.enqueueData({ command: PowerSyncControlCommand.NOTIFY_CRUD_UPLOAD_COMPLETED });
9875
- }
9953
+ controlInvocations?.inject({ command: PowerSyncControlCommand.NOTIFY_CRUD_UPLOAD_COMPLETED });
9876
9954
  };
9877
9955
  this.handleActiveStreamsChange = () => {
9878
- if (controlInvocations && !controlInvocations?.closed) {
9879
- controlInvocations.enqueueData({
9880
- command: PowerSyncControlCommand.UPDATE_SUBSCRIPTIONS,
9881
- payload: JSON.stringify(this.activeStreams)
9882
- });
9883
- }
9956
+ controlInvocations?.inject({
9957
+ command: PowerSyncControlCommand.UPDATE_SUBSCRIPTIONS,
9958
+ payload: JSON.stringify(this.activeStreams)
9959
+ });
9884
9960
  };
9885
9961
  await receivingLines;
9886
9962
  }
@@ -10897,7 +10973,7 @@ class AbstractPowerSyncDatabase extends BaseObserver {
10897
10973
  * @returns A transaction of CRUD operations to upload, or null if there are none
10898
10974
  */
10899
10975
  async getNextCrudTransaction() {
10900
- const iterator = this.getCrudTransactions()[symbolAsyncIterator]();
10976
+ const iterator = this.getCrudTransactions()[Symbol.asyncIterator]();
10901
10977
  return (await iterator.next()).value;
10902
10978
  }
10903
10979
  /**
@@ -10933,7 +11009,7 @@ class AbstractPowerSyncDatabase extends BaseObserver {
10933
11009
  */
10934
11010
  getCrudTransactions() {
10935
11011
  return {
10936
- [symbolAsyncIterator]: () => {
11012
+ [Symbol.asyncIterator]: () => {
10937
11013
  let lastCrudItemId = -1;
10938
11014
  const sql = `
10939
11015
  WITH RECURSIVE crud_entries AS (
@@ -12073,5 +12149,5 @@ const parseQuery = (query, parameters) => {
12073
12149
  return { sqlStatement, parameters: parameters };
12074
12150
  };
12075
12151
 
12076
- export { ATTACHMENT_TABLE, AbortOperation, AbstractPowerSyncDatabase, AbstractPowerSyncDatabaseOpenFactory, AbstractQueryProcessor, AbstractRemote, AbstractStreamingSyncImplementation, ArrayComparator, AttachmentContext, AttachmentQueue, AttachmentService, AttachmentState, AttachmentTable, BaseObserver, Column, ColumnType, ConnectionClosedError, ConnectionManager, ControlledExecutor, CrudBatch, CrudEntry, CrudTransaction, DBAdapterDefaultMixin, DBGetUtilsDefaultMixin, DEFAULT_CRUD_BATCH_LIMIT, DEFAULT_CRUD_UPLOAD_THROTTLE_MS, DEFAULT_INDEX_COLUMN_OPTIONS, DEFAULT_INDEX_OPTIONS, DEFAULT_LOCK_TIMEOUT_MS, DEFAULT_POWERSYNC_CLOSE_OPTIONS, DEFAULT_POWERSYNC_DB_OPTIONS, DEFAULT_PRESSURE_LIMITS, DEFAULT_REMOTE_LOGGER, DEFAULT_REMOTE_OPTIONS, DEFAULT_RETRY_DELAY_MS, DEFAULT_ROW_COMPARATOR, DEFAULT_STREAMING_SYNC_OPTIONS, DEFAULT_STREAM_CONNECTION_OPTIONS, DEFAULT_SYNC_CLIENT_IMPLEMENTATION, DEFAULT_TABLE_OPTIONS, DEFAULT_WATCH_QUERY_OPTIONS, DEFAULT_WATCH_THROTTLE_MS, DataStream, DiffTriggerOperation, DifferentialQueryProcessor, EMPTY_DIFFERENTIAL, EncodingType, FalsyComparator, FetchImplementationProvider, FetchStrategy, GetAllQuery, Index, IndexedColumn, InvalidSQLCharacters, LockType, LogLevel, MAX_AMOUNT_OF_COLUMNS, MAX_OP_ID, MEMORY_TRIGGER_CLAIM_MANAGER, Mutex, OnChangeQueryProcessor, OpType, OpTypeEnum, OplogEntry, PSInternalTable, PowerSyncControlCommand, RowUpdateType, Schema, SqliteBucketStorage, SyncClientImplementation, SyncDataBatch, SyncDataBucket, SyncProgress, SyncStatus, SyncStreamConnectionMethod, SyncingService, Table, TableV2, TriggerManagerImpl, UpdateType, UploadQueueStats, WatchedQueryListenerEvent, attachmentFromSql, column, compilableQueryWatch, createBaseLogger, createLogger, extractTableUpdates, isBatchedUpdateNotification, isContinueCheckpointRequest, isDBAdapter, isPowerSyncDatabaseOptionsWithSettings, isSQLOpenFactory, isSQLOpenOptions, isStreamingKeepalive, isStreamingSyncCheckpoint, isStreamingSyncCheckpointComplete, isStreamingSyncCheckpointDiff, isStreamingSyncCheckpointPartiallyComplete, isStreamingSyncData, isSyncNewCheckpointRequest, parseQuery, runOnSchemaChange, sanitizeSQL, sanitizeUUID, timeoutSignal };
12152
+ export { ATTACHMENT_TABLE, AbortOperation, AbstractPowerSyncDatabase, AbstractPowerSyncDatabaseOpenFactory, AbstractQueryProcessor, AbstractRemote, AbstractStreamingSyncImplementation, ArrayComparator, AttachmentContext, AttachmentQueue, AttachmentService, AttachmentState, AttachmentTable, BaseObserver, Column, ColumnType, ConnectionClosedError, ConnectionManager, ControlledExecutor, CrudBatch, CrudEntry, CrudTransaction, DBAdapterDefaultMixin, DBGetUtilsDefaultMixin, DEFAULT_CRUD_BATCH_LIMIT, DEFAULT_CRUD_UPLOAD_THROTTLE_MS, DEFAULT_INDEX_COLUMN_OPTIONS, DEFAULT_INDEX_OPTIONS, DEFAULT_LOCK_TIMEOUT_MS, DEFAULT_POWERSYNC_CLOSE_OPTIONS, DEFAULT_POWERSYNC_DB_OPTIONS, DEFAULT_REMOTE_LOGGER, DEFAULT_REMOTE_OPTIONS, DEFAULT_RETRY_DELAY_MS, DEFAULT_ROW_COMPARATOR, DEFAULT_STREAMING_SYNC_OPTIONS, DEFAULT_STREAM_CONNECTION_OPTIONS, DEFAULT_SYNC_CLIENT_IMPLEMENTATION, DEFAULT_TABLE_OPTIONS, DEFAULT_WATCH_QUERY_OPTIONS, DEFAULT_WATCH_THROTTLE_MS, DiffTriggerOperation, DifferentialQueryProcessor, EMPTY_DIFFERENTIAL, EncodingType, FalsyComparator, FetchImplementationProvider, FetchStrategy, GetAllQuery, Index, IndexedColumn, InvalidSQLCharacters, LockType, LogLevel, MAX_AMOUNT_OF_COLUMNS, MAX_OP_ID, MEMORY_TRIGGER_CLAIM_MANAGER, Mutex, OnChangeQueryProcessor, OpType, OpTypeEnum, OplogEntry, PSInternalTable, PowerSyncControlCommand, RowUpdateType, Schema, Semaphore, SqliteBucketStorage, SyncClientImplementation, SyncDataBatch, SyncDataBucket, SyncProgress, SyncStatus, SyncStreamConnectionMethod, SyncingService, Table, TableV2, TriggerManagerImpl, UpdateType, UploadQueueStats, WatchedQueryListenerEvent, attachmentFromSql, column, compilableQueryWatch, createBaseLogger, createLogger, extractTableUpdates, isBatchedUpdateNotification, isContinueCheckpointRequest, isDBAdapter, isPowerSyncDatabaseOptionsWithSettings, isSQLOpenFactory, isSQLOpenOptions, isStreamingKeepalive, isStreamingSyncCheckpoint, isStreamingSyncCheckpointComplete, isStreamingSyncCheckpointDiff, isStreamingSyncCheckpointPartiallyComplete, isStreamingSyncData, isSyncNewCheckpointRequest, parseQuery, runOnSchemaChange, sanitizeSQL, sanitizeUUID, timeoutSignal };
12077
12153
  //# sourceMappingURL=bundle.node.mjs.map