@powersync/web 0.0.0-dev-20251127205344 → 0.0.0-dev-20251129133952

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.
@@ -17,6 +17,7 @@ import {
17
17
  */
18
18
  export class WorkerClient {
19
19
  private resolvedPort: WrappedSyncPort | null = null;
20
+ protected resolvedPortPromise: Promise<WrappedSyncPort> | null = null;
20
21
 
21
22
  constructor(
22
23
  private readonly sync: SharedSyncImplementation,
@@ -37,7 +38,15 @@ export class WorkerClient {
37
38
  }
38
39
  });
39
40
 
40
- this.resolvedPort = await this.sync.addPort(this.port);
41
+ /**
42
+ * Keep a reference to the resolved port promise.
43
+ * The init timing is difficult to predict due to the async message passing.
44
+ * We only want to use a port if we are know it's been protected from being closed.
45
+ * The lock based close signal will be added asynchronously. We need to use the
46
+ * added port once the lock is configured.
47
+ */
48
+ this.resolvedPortPromise = this.sync.addPort(this.port);
49
+ this.resolvedPort = await this.resolvedPortPromise;
41
50
  }
42
51
 
43
52
  private async removePort() {
@@ -60,7 +69,19 @@ export class WorkerClient {
60
69
  * When the client tab is closed, its lock will be returned. So when the shared worker attempts to acquire the lock,
61
70
  * it can consider the connection to be closed.
62
71
  */
63
- addLockBasedCloseSignal(name: string) {
72
+ async addLockBasedCloseSignal(name: string) {
73
+ if (!this.resolvedPortPromise) {
74
+ // The init logic above is actually synchronous, so this should not happen.
75
+ this.sync.broadCastLogger.warn('addLockBasedCloseSignal called before port promise registered');
76
+ } else {
77
+ const wrappedPort = await this.resolvedPortPromise;
78
+ /**
79
+ * The client registered a navigator lock. We now can guarantee detecting if the client has closed.
80
+ * E.g. before this point: It's possible some ports might have been created and closed before the
81
+ * lock based close signal is added. We should not trust those ports.
82
+ */
83
+ wrappedPort.isProtectedFromClose = true;
84
+ }
64
85
  getNavigatorLocks().request(name, async () => {
65
86
  await this.removePort();
66
87
  });