@powersync/web 0.0.0-dev-20250526133243 → 0.0.0-dev-20250529141956

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.umd.js CHANGED
@@ -38223,9 +38223,6 @@ class PowerSyncDatabase extends _powersync_common__WEBPACK_IMPORTED_MODULE_0__.A
38223
38223
  disconnect: options.disconnect ?? !this.resolvedFlags.enableMultiTabs
38224
38224
  });
38225
38225
  }
38226
- async connectExclusive(callback) {
38227
- await this.runExclusive(callback);
38228
- }
38229
38226
  generateBucketStorageAdapter() {
38230
38227
  return new _powersync_common__WEBPACK_IMPORTED_MODULE_0__.SqliteBucketStorage(this.database, _powersync_common__WEBPACK_IMPORTED_MODULE_0__.AbstractPowerSyncDatabase.transactionMutex);
38231
38228
  }
@@ -39749,9 +39746,6 @@ class SharedWebStreamingSyncImplementation extends _WebStreamingSyncImplementati
39749
39746
  */
39750
39747
  async connect(options) {
39751
39748
  await this.waitForReady();
39752
- // This is needed since a new tab won't have any reference to the
39753
- // shared worker sync implementation since that is only created on the first call to `connect`.
39754
- await this.disconnect();
39755
39749
  return this.syncManager.connect(options);
39756
39750
  }
39757
39751
  async disconnect() {
@@ -39767,12 +39761,21 @@ class SharedWebStreamingSyncImplementation extends _WebStreamingSyncImplementati
39767
39761
  }
39768
39762
  async dispose() {
39769
39763
  await this.waitForReady();
39770
- // Signal the shared worker that this client is closing its connection to the worker
39771
- const closeMessagePayload = {
39772
- event: _worker_sync_SharedSyncImplementation__WEBPACK_IMPORTED_MODULE_2__.SharedSyncClientEvent.CLOSE_CLIENT,
39773
- data: {}
39774
- };
39775
- this.messagePort.postMessage(closeMessagePayload);
39764
+ await new Promise((resolve) => {
39765
+ // Listen for the close acknowledgment from the worker
39766
+ this.messagePort.addEventListener('message', (event) => {
39767
+ const payload = event.data;
39768
+ if (payload?.event === _worker_sync_SharedSyncImplementation__WEBPACK_IMPORTED_MODULE_2__.SharedSyncClientEvent.CLOSE_ACK) {
39769
+ resolve();
39770
+ }
39771
+ });
39772
+ // Signal the shared worker that this client is closing its connection to the worker
39773
+ const closeMessagePayload = {
39774
+ event: _worker_sync_SharedSyncImplementation__WEBPACK_IMPORTED_MODULE_2__.SharedSyncClientEvent.CLOSE_CLIENT,
39775
+ data: {}
39776
+ };
39777
+ this.messagePort.postMessage(closeMessagePayload);
39778
+ });
39776
39779
  // Release the proxy
39777
39780
  this.syncManager[comlink__WEBPACK_IMPORTED_MODULE_0__.releaseProxy]();
39778
39781
  this.messagePort.close();
@@ -40250,9 +40253,7 @@ __webpack_require__.r(__webpack_exports__);
40250
40253
  /* harmony import */ var _db_sync_WebStreamingSyncImplementation__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../../db/sync/WebStreamingSyncImplementation */ "./lib/src/db/sync/WebStreamingSyncImplementation.js");
40251
40254
  /* harmony import */ var _db_adapters_LockedAsyncDatabaseAdapter__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../../db/adapters/LockedAsyncDatabaseAdapter */ "./lib/src/db/adapters/LockedAsyncDatabaseAdapter.js");
40252
40255
  /* harmony import */ var _db_adapters_WorkerWrappedAsyncDatabaseConnection__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../../db/adapters/WorkerWrappedAsyncDatabaseConnection */ "./lib/src/db/adapters/WorkerWrappedAsyncDatabaseConnection.js");
40253
- /* harmony import */ var _shared_navigator__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ../../shared/navigator */ "./lib/src/shared/navigator.js");
40254
- /* harmony import */ var _BroadcastLogger__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ./BroadcastLogger */ "./lib/src/worker/sync/BroadcastLogger.js");
40255
-
40256
+ /* harmony import */ var _BroadcastLogger__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./BroadcastLogger */ "./lib/src/worker/sync/BroadcastLogger.js");
40256
40257
 
40257
40258
 
40258
40259
 
@@ -40262,6 +40263,7 @@ __webpack_require__.r(__webpack_exports__);
40262
40263
 
40263
40264
 
40264
40265
  /**
40266
+ * @internal
40265
40267
  * Manual message events for shared sync clients
40266
40268
  */
40267
40269
  var SharedSyncClientEvent;
@@ -40271,14 +40273,20 @@ var SharedSyncClientEvent;
40271
40273
  * close it's connection to the client.
40272
40274
  */
40273
40275
  SharedSyncClientEvent["CLOSE_CLIENT"] = "close-client";
40276
+ SharedSyncClientEvent["CLOSE_ACK"] = "close-ack";
40274
40277
  })(SharedSyncClientEvent || (SharedSyncClientEvent = {}));
40278
+ /**
40279
+ * HACK: The shared implementation wraps and provides its own
40280
+ * PowerSyncBackendConnector when generating the streaming sync implementation.
40281
+ * We provide this unused placeholder when connecting with the ConnectionManager.
40282
+ */
40283
+ const CONNECTOR_PLACEHOLDER = {};
40275
40284
  /**
40276
40285
  * @internal
40277
40286
  * Shared sync implementation which runs inside a shared webworker
40278
40287
  */
40279
40288
  class SharedSyncImplementation extends _powersync_common__WEBPACK_IMPORTED_MODULE_0__.BaseObserver {
40280
40289
  ports;
40281
- syncStreamClient;
40282
40290
  isInitialized;
40283
40291
  statusListener;
40284
40292
  fetchCredentialsController;
@@ -40287,6 +40295,8 @@ class SharedSyncImplementation extends _powersync_common__WEBPACK_IMPORTED_MODUL
40287
40295
  syncParams;
40288
40296
  logger;
40289
40297
  lastConnectOptions;
40298
+ portMutex;
40299
+ connectionManager;
40290
40300
  syncStatus;
40291
40301
  broadCastLogger;
40292
40302
  constructor() {
@@ -40294,9 +40304,9 @@ class SharedSyncImplementation extends _powersync_common__WEBPACK_IMPORTED_MODUL
40294
40304
  this.ports = [];
40295
40305
  this.dbAdapter = null;
40296
40306
  this.syncParams = null;
40297
- this.syncStreamClient = null;
40298
40307
  this.logger = (0,_powersync_common__WEBPACK_IMPORTED_MODULE_0__.createLogger)('shared-sync');
40299
40308
  this.lastConnectOptions = undefined;
40309
+ this.portMutex = new async_mutex__WEBPACK_IMPORTED_MODULE_1__.Mutex();
40300
40310
  this.isInitialized = new Promise((resolve) => {
40301
40311
  const callback = this.registerListener({
40302
40312
  initialized: () => {
@@ -40306,21 +40316,44 @@ class SharedSyncImplementation extends _powersync_common__WEBPACK_IMPORTED_MODUL
40306
40316
  });
40307
40317
  });
40308
40318
  this.syncStatus = new _powersync_common__WEBPACK_IMPORTED_MODULE_0__.SyncStatus({});
40309
- this.broadCastLogger = new _BroadcastLogger__WEBPACK_IMPORTED_MODULE_8__.BroadcastLogger(this.ports);
40310
- }
40311
- async waitForStatus(status) {
40312
- await this.waitForReady();
40313
- return this.syncStreamClient.waitForStatus(status);
40314
- }
40315
- async waitUntilStatusMatches(predicate) {
40316
- await this.waitForReady();
40317
- return this.syncStreamClient.waitUntilStatusMatches(predicate);
40319
+ this.broadCastLogger = new _BroadcastLogger__WEBPACK_IMPORTED_MODULE_7__.BroadcastLogger(this.ports);
40320
+ this.connectionManager = new _powersync_common__WEBPACK_IMPORTED_MODULE_0__.ConnectionManager({
40321
+ createSyncImplementation: async () => {
40322
+ return this.portMutex.runExclusive(async () => {
40323
+ await this.waitForReady();
40324
+ if (!this.dbAdapter) {
40325
+ await this.openInternalDB();
40326
+ }
40327
+ const sync = this.generateStreamingImplementation();
40328
+ const onDispose = sync.registerListener({
40329
+ statusChanged: (status) => {
40330
+ this.updateAllStatuses(status.toJSON());
40331
+ }
40332
+ });
40333
+ return {
40334
+ sync,
40335
+ onDispose
40336
+ };
40337
+ });
40338
+ },
40339
+ logger: this.logger
40340
+ });
40318
40341
  }
40319
40342
  get lastSyncedAt() {
40320
- return this.syncStreamClient?.lastSyncedAt;
40343
+ return this.connectionManager.syncStreamImplementation?.lastSyncedAt;
40321
40344
  }
40322
40345
  get isConnected() {
40323
- return this.syncStreamClient?.isConnected ?? false;
40346
+ return this.connectionManager.syncStreamImplementation?.isConnected ?? false;
40347
+ }
40348
+ async waitForStatus(status) {
40349
+ return this.withSyncImplementation(async (sync) => {
40350
+ return sync.waitForStatus(status);
40351
+ });
40352
+ }
40353
+ async waitUntilStatusMatches(predicate) {
40354
+ return this.withSyncImplementation(async (sync) => {
40355
+ return sync.waitUntilStatusMatches(predicate);
40356
+ });
40324
40357
  }
40325
40358
  async waitForReady() {
40326
40359
  return this.isInitialized;
@@ -40333,25 +40366,34 @@ class SharedSyncImplementation extends _powersync_common__WEBPACK_IMPORTED_MODUL
40333
40366
  * Configures the DBAdapter connection and a streaming sync client.
40334
40367
  */
40335
40368
  async setParams(params) {
40336
- if (this.syncParams) {
40337
- // Cannot modify already existing sync implementation
40338
- return;
40339
- }
40340
- this.syncParams = params;
40341
- if (params.streamOptions?.flags?.broadcastLogs) {
40342
- this.logger = this.broadCastLogger;
40343
- }
40344
- self.onerror = (event) => {
40345
- // Share any uncaught events on the broadcast logger
40346
- this.logger.error('Uncaught exception in PowerSync shared sync worker', event);
40347
- };
40348
- await this.openInternalDB();
40349
- this.iterateListeners((l) => l.initialized?.());
40369
+ await this.portMutex.runExclusive(async () => {
40370
+ if (this.syncParams) {
40371
+ // Cannot modify already existing sync implementation params
40372
+ // But we can ask for a DB adapter, if required, at this point.
40373
+ if (!this.dbAdapter) {
40374
+ await this.openInternalDB();
40375
+ }
40376
+ return;
40377
+ }
40378
+ // First time setting params
40379
+ this.syncParams = params;
40380
+ if (params.streamOptions?.flags?.broadcastLogs) {
40381
+ this.logger = this.broadCastLogger;
40382
+ }
40383
+ self.onerror = (event) => {
40384
+ // Share any uncaught events on the broadcast logger
40385
+ this.logger.error('Uncaught exception in PowerSync shared sync worker', event);
40386
+ };
40387
+ if (!this.dbAdapter) {
40388
+ await this.openInternalDB();
40389
+ }
40390
+ this.iterateListeners((l) => l.initialized?.());
40391
+ });
40350
40392
  }
40351
40393
  async dispose() {
40352
40394
  await this.waitForReady();
40353
40395
  this.statusListener?.();
40354
- return this.syncStreamClient?.dispose();
40396
+ return this.connectionManager.close();
40355
40397
  }
40356
40398
  /**
40357
40399
  * Connects to the PowerSync backend instance.
@@ -40360,99 +40402,110 @@ class SharedSyncImplementation extends _powersync_common__WEBPACK_IMPORTED_MODUL
40360
40402
  * connects.
40361
40403
  */
40362
40404
  async connect(options) {
40363
- await this.waitForReady();
40364
- // This effectively queues connect and disconnect calls. Ensuring multiple tabs' requests are synchronized
40365
- return (0,_shared_navigator__WEBPACK_IMPORTED_MODULE_7__.getNavigatorLocks)().request('shared-sync-connect', async () => {
40366
- if (!this.dbAdapter) {
40367
- await this.openInternalDB();
40368
- }
40369
- this.syncStreamClient = this.generateStreamingImplementation();
40370
- this.lastConnectOptions = options;
40371
- this.syncStreamClient.registerListener({
40372
- statusChanged: (status) => {
40373
- this.updateAllStatuses(status.toJSON());
40374
- }
40375
- });
40376
- await this.syncStreamClient.connect(options);
40377
- });
40405
+ this.lastConnectOptions = options;
40406
+ return this.connectionManager.connect(CONNECTOR_PLACEHOLDER, options);
40378
40407
  }
40379
40408
  async disconnect() {
40380
- await this.waitForReady();
40381
- // This effectively queues connect and disconnect calls. Ensuring multiple tabs' requests are synchronized
40382
- return (0,_shared_navigator__WEBPACK_IMPORTED_MODULE_7__.getNavigatorLocks)().request('shared-sync-connect', async () => {
40383
- await this.syncStreamClient?.disconnect();
40384
- await this.syncStreamClient?.dispose();
40385
- this.syncStreamClient = null;
40386
- });
40409
+ return this.connectionManager.disconnect();
40387
40410
  }
40388
40411
  /**
40389
40412
  * Adds a new client tab's message port to the list of connected ports
40390
40413
  */
40391
- addPort(port) {
40392
- const portProvider = {
40393
- port,
40394
- clientProvider: comlink__WEBPACK_IMPORTED_MODULE_2__.wrap(port)
40395
- };
40396
- this.ports.push(portProvider);
40397
- // Give the newly connected client the latest status
40398
- const status = this.syncStreamClient?.syncStatus;
40399
- if (status) {
40400
- portProvider.clientProvider.statusChanged(status.toJSON());
40401
- }
40414
+ async addPort(port) {
40415
+ await this.portMutex.runExclusive(() => {
40416
+ const portProvider = {
40417
+ port,
40418
+ clientProvider: comlink__WEBPACK_IMPORTED_MODULE_2__.wrap(port)
40419
+ };
40420
+ this.ports.push(portProvider);
40421
+ // Give the newly connected client the latest status
40422
+ const status = this.connectionManager.syncStreamImplementation?.syncStatus;
40423
+ if (status) {
40424
+ portProvider.clientProvider.statusChanged(status.toJSON());
40425
+ }
40426
+ });
40402
40427
  }
40403
40428
  /**
40404
40429
  * Removes a message port client from this manager's managed
40405
40430
  * clients.
40406
40431
  */
40407
40432
  async removePort(port) {
40408
- const index = this.ports.findIndex((p) => p.port == port);
40409
- if (index < 0) {
40410
- this.logger.warn(`Could not remove port ${port} since it is not present in active ports.`);
40411
- return;
40412
- }
40413
- const trackedPort = this.ports[index];
40414
- // Remove from the list of active ports
40415
- this.ports.splice(index, 1);
40416
- /**
40417
- * The port might currently be in use. Any active functions might
40418
- * not resolve. Abort them here.
40419
- */
40420
- [this.fetchCredentialsController, this.uploadDataController].forEach((abortController) => {
40421
- if (abortController?.activePort.port == port) {
40422
- abortController.controller.abort(new _powersync_common__WEBPACK_IMPORTED_MODULE_0__.AbortOperation('Closing pending requests after client port is removed'));
40433
+ // Remove the port within a mutex context.
40434
+ // Warns if the port is not found. This should not happen in practice.
40435
+ // We return early if the port is not found.
40436
+ const { trackedPort, shouldReconnect } = await this.portMutex.runExclusive(async () => {
40437
+ const index = this.ports.findIndex((p) => p.port == port);
40438
+ if (index < 0) {
40439
+ this.logger.warn(`Could not remove port ${port} since it is not present in active ports.`);
40440
+ return {};
40423
40441
  }
40442
+ const trackedPort = this.ports[index];
40443
+ // Remove from the list of active ports
40444
+ this.ports.splice(index, 1);
40445
+ /**
40446
+ * The port might currently be in use. Any active functions might
40447
+ * not resolve. Abort them here.
40448
+ */
40449
+ [this.fetchCredentialsController, this.uploadDataController].forEach((abortController) => {
40450
+ if (abortController?.activePort.port == port) {
40451
+ abortController.controller.abort(new _powersync_common__WEBPACK_IMPORTED_MODULE_0__.AbortOperation('Closing pending requests after client port is removed'));
40452
+ }
40453
+ });
40454
+ const shouldReconnect = !!this.connectionManager.syncStreamImplementation && this.ports.length > 0;
40455
+ return {
40456
+ shouldReconnect,
40457
+ trackedPort
40458
+ };
40424
40459
  });
40425
- const shouldReconnect = !!this.syncStreamClient;
40460
+ if (!trackedPort) {
40461
+ // We could not find the port to remove
40462
+ return () => { };
40463
+ }
40426
40464
  if (this.dbAdapter && this.dbAdapter == trackedPort.db) {
40427
40465
  if (shouldReconnect) {
40428
- await this.disconnect();
40466
+ await this.connectionManager.disconnect();
40429
40467
  }
40430
40468
  // Clearing the adapter will result in a new one being opened in connect
40431
40469
  this.dbAdapter = null;
40432
40470
  if (shouldReconnect) {
40433
- await this.connect(this.lastConnectOptions);
40471
+ await this.connectionManager.connect(CONNECTOR_PLACEHOLDER, this.lastConnectOptions);
40434
40472
  }
40435
40473
  }
40436
40474
  if (trackedPort.db) {
40437
- trackedPort.db.close();
40475
+ await trackedPort.db.close();
40438
40476
  }
40439
40477
  // Release proxy
40440
- trackedPort.clientProvider[comlink__WEBPACK_IMPORTED_MODULE_2__.releaseProxy]();
40478
+ return () => trackedPort.clientProvider[comlink__WEBPACK_IMPORTED_MODULE_2__.releaseProxy]();
40441
40479
  }
40442
40480
  triggerCrudUpload() {
40443
- this.waitForReady().then(() => this.syncStreamClient?.triggerCrudUpload());
40444
- }
40445
- async obtainLock(lockOptions) {
40446
- await this.waitForReady();
40447
- return this.syncStreamClient.obtainLock(lockOptions);
40481
+ this.withSyncImplementation(async (sync) => {
40482
+ sync.triggerCrudUpload();
40483
+ });
40448
40484
  }
40449
40485
  async hasCompletedSync() {
40450
- await this.waitForReady();
40451
- return this.syncStreamClient.hasCompletedSync();
40486
+ return this.withSyncImplementation(async (sync) => {
40487
+ return sync.hasCompletedSync();
40488
+ });
40452
40489
  }
40453
40490
  async getWriteCheckpoint() {
40491
+ return this.withSyncImplementation(async (sync) => {
40492
+ return sync.getWriteCheckpoint();
40493
+ });
40494
+ }
40495
+ async withSyncImplementation(callback) {
40454
40496
  await this.waitForReady();
40455
- return this.syncStreamClient.getWriteCheckpoint();
40497
+ if (this.connectionManager.syncStreamImplementation) {
40498
+ return callback(this.connectionManager.syncStreamImplementation);
40499
+ }
40500
+ const sync = await new Promise((resolve) => {
40501
+ const dispose = this.connectionManager.registerListener({
40502
+ syncStreamCreated: (sync) => {
40503
+ resolve(sync);
40504
+ dispose?.();
40505
+ }
40506
+ });
40507
+ });
40508
+ return callback(sync);
40456
40509
  }
40457
40510
  generateStreamingImplementation() {
40458
40511
  // This should only be called after initialization has completed
@@ -40555,13 +40608,13 @@ class SharedSyncImplementation extends _powersync_common__WEBPACK_IMPORTED_MODUL
40555
40608
  * A function only used for unit tests which updates the internal
40556
40609
  * sync stream client and all tab client's sync status
40557
40610
  */
40558
- _testUpdateAllStatuses(status) {
40559
- if (!this.syncStreamClient) {
40611
+ async _testUpdateAllStatuses(status) {
40612
+ if (!this.connectionManager.syncStreamImplementation) {
40560
40613
  // This is just for testing purposes
40561
- this.syncStreamClient = this.generateStreamingImplementation();
40614
+ this.connectionManager.syncStreamImplementation = this.generateStreamingImplementation();
40562
40615
  }
40563
40616
  // Only assigning, don't call listeners for this test
40564
- this.syncStreamClient.syncStatus = new _powersync_common__WEBPACK_IMPORTED_MODULE_0__.SyncStatus(status);
40617
+ this.connectionManager.syncStreamImplementation.syncStatus = new _powersync_common__WEBPACK_IMPORTED_MODULE_0__.SyncStatus(status);
40565
40618
  this.updateAllStatuses(status);
40566
40619
  }
40567
40620
  }