@powersync/web 0.0.0-dev-20250520135616 → 0.0.0-dev-20250528152729

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