@powersync/web 0.0.0-dev-20250915110424 → 0.0.0-dev-20250922104723

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/lib/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@powersync/web",
3
- "version": "1.26.1",
3
+ "version": "1.26.2",
4
4
  "description": "PowerSync web SDK. Sync Postgres, MongoDB or MySQL with SQLite in your web app",
5
5
  "main": "lib/src/index.js",
6
6
  "types": "lib/src/index.d.ts",
@@ -61,7 +61,7 @@
61
61
  "license": "Apache-2.0",
62
62
  "peerDependencies": {
63
63
  "@journeyapps/wa-sqlite": "^1.3.1",
64
- "@powersync/common": "workspace:^1.38.0"
64
+ "@powersync/common": "workspace:^1.38.1"
65
65
  },
66
66
  "dependencies": {
67
67
  "@powersync/common": "workspace:*",
@@ -94,8 +94,7 @@ export class PowerSyncDatabase extends AbstractPowerSyncDatabase {
94
94
  const remote = new WebRemote(connector, this.logger);
95
95
  const syncOptions = {
96
96
  ...this.options,
97
- retryDelayMs: options.retryDelayMs,
98
- crudUploadThrottleMs: options.crudUploadThrottleMs,
97
+ ...options,
99
98
  flags: this.resolvedFlags,
100
99
  adapter: this.bucketStorageAdapter,
101
100
  remote,
@@ -41,4 +41,8 @@ export declare class SSRStreamingSyncImplementation extends BaseObserver impleme
41
41
  * This is a no-op in SSR mode.
42
42
  */
43
43
  triggerCrudUpload(): void;
44
+ /**
45
+ * No-op in SSR mode.
46
+ */
47
+ updateSubscriptions(): void;
44
48
  }
@@ -58,4 +58,8 @@ export class SSRStreamingSyncImplementation extends BaseObserver {
58
58
  * This is a no-op in SSR mode.
59
59
  */
60
60
  triggerCrudUpload() { }
61
+ /**
62
+ * No-op in SSR mode.
63
+ */
64
+ updateSubscriptions() { }
61
65
  }
@@ -1,9 +1,9 @@
1
- import { PowerSyncConnectionOptions, PowerSyncCredentials, SyncStatusOptions } from '@powersync/common';
1
+ import { PowerSyncConnectionOptions, PowerSyncCredentials, SubscribedStream, SyncStatusOptions } from '@powersync/common';
2
2
  import * as Comlink from 'comlink';
3
3
  import { AbstractSharedSyncClientProvider } from '../../worker/sync/AbstractSharedSyncClientProvider';
4
- import { SharedSyncImplementation } from '../../worker/sync/SharedSyncImplementation';
5
4
  import { WebDBAdapter } from '../adapters/WebDBAdapter';
6
5
  import { WebStreamingSyncImplementation, WebStreamingSyncImplementationOptions } from './WebStreamingSyncImplementation';
6
+ import { WorkerClient } from '../../worker/sync/WorkerClient';
7
7
  /**
8
8
  * The shared worker will trigger methods on this side of the message port
9
9
  * via this client provider.
@@ -30,12 +30,16 @@ declare class SharedSyncClientProvider extends AbstractSharedSyncClientProvider
30
30
  export interface SharedWebStreamingSyncImplementationOptions extends WebStreamingSyncImplementationOptions {
31
31
  db: WebDBAdapter;
32
32
  }
33
+ /**
34
+ * The local part of the sync implementation on the web, which talks to a sync implementation hosted in a shared worker.
35
+ */
33
36
  export declare class SharedWebStreamingSyncImplementation extends WebStreamingSyncImplementation {
34
- protected syncManager: Comlink.Remote<SharedSyncImplementation>;
37
+ protected syncManager: Comlink.Remote<WorkerClient>;
35
38
  protected clientProvider: SharedSyncClientProvider;
36
39
  protected messagePort: MessagePort;
37
40
  protected isInitialized: Promise<void>;
38
41
  protected dbAdapter: WebDBAdapter;
42
+ private abortOnClose;
39
43
  constructor(options: SharedWebStreamingSyncImplementationOptions);
40
44
  /**
41
45
  * Starts the sync process, this effectively acts as a call to
@@ -47,6 +51,7 @@ export declare class SharedWebStreamingSyncImplementation extends WebStreamingSy
47
51
  hasCompletedSync(): Promise<boolean>;
48
52
  dispose(): Promise<void>;
49
53
  waitForReady(): Promise<void>;
54
+ updateSubscriptions(subscriptions: SubscribedStream[]): void;
50
55
  /**
51
56
  * Used in tests to force a connection states
52
57
  */
@@ -3,6 +3,7 @@ import { AbstractSharedSyncClientProvider } from '../../worker/sync/AbstractShar
3
3
  import { SharedSyncClientEvent } from '../../worker/sync/SharedSyncImplementation';
4
4
  import { DEFAULT_CACHE_SIZE_KB, resolveWebSQLFlags, TemporaryStorageOption } from '../adapters/web-sql-flags';
5
5
  import { WebStreamingSyncImplementation } from './WebStreamingSyncImplementation';
6
+ import { getNavigatorLocks } from '../../shared/navigator';
6
7
  /**
7
8
  * The shared worker will trigger methods on this side of the message port
8
9
  * via this client provider.
@@ -75,12 +76,16 @@ class SharedSyncClientProvider extends AbstractSharedSyncClientProvider {
75
76
  this.logger?.timeEnd(label);
76
77
  }
77
78
  }
79
+ /**
80
+ * The local part of the sync implementation on the web, which talks to a sync implementation hosted in a shared worker.
81
+ */
78
82
  export class SharedWebStreamingSyncImplementation extends WebStreamingSyncImplementation {
79
83
  syncManager;
80
84
  clientProvider;
81
85
  messagePort;
82
86
  isInitialized;
83
87
  dbAdapter;
88
+ abortOnClose = new AbortController();
84
89
  constructor(options) {
85
90
  super(options);
86
91
  this.dbAdapter = options.db;
@@ -133,7 +138,7 @@ export class SharedWebStreamingSyncImplementation extends WebStreamingSyncImplem
133
138
  retryDelayMs,
134
139
  flags: flags
135
140
  }
136
- });
141
+ }, options.subscriptions);
137
142
  /**
138
143
  * Pass along any sync status updates to this listener
139
144
  */
@@ -146,6 +151,17 @@ export class SharedWebStreamingSyncImplementation extends WebStreamingSyncImplem
146
151
  * This performs bi-directional method calling.
147
152
  */
148
153
  Comlink.expose(this.clientProvider, this.messagePort);
154
+ // Request a random lock until this client is disposed. The name of the lock is sent to the shared worker, which
155
+ // will also attempt to acquire it. Since the lock is returned when the tab is closed, this allows the share worker
156
+ // to free resources associated with this tab.
157
+ getNavigatorLocks().request(`tab-close-signal-${crypto.randomUUID()}`, async (lock) => {
158
+ if (!this.abortOnClose.signal.aborted) {
159
+ this.syncManager.addLockBasedCloseSignal(lock.name);
160
+ await new Promise((r) => {
161
+ this.abortOnClose.signal.onabort = () => r();
162
+ });
163
+ }
164
+ });
149
165
  }
150
166
  /**
151
167
  * Starts the sync process, this effectively acts as a call to
@@ -184,6 +200,7 @@ export class SharedWebStreamingSyncImplementation extends WebStreamingSyncImplem
184
200
  };
185
201
  this.messagePort.postMessage(closeMessagePayload);
186
202
  });
203
+ this.abortOnClose.abort();
187
204
  // Release the proxy
188
205
  this.syncManager[Comlink.releaseProxy]();
189
206
  this.messagePort.close();
@@ -191,11 +208,14 @@ export class SharedWebStreamingSyncImplementation extends WebStreamingSyncImplem
191
208
  async waitForReady() {
192
209
  return this.isInitialized;
193
210
  }
211
+ updateSubscriptions(subscriptions) {
212
+ this.syncManager.updateSubscriptions(subscriptions);
213
+ }
194
214
  /**
195
215
  * Used in tests to force a connection states
196
216
  */
197
217
  async _testUpdateStatus(status) {
198
218
  await this.isInitialized;
199
- return this.syncManager['_testUpdateAllStatuses'](status.toJSON());
219
+ return this.syncManager._testUpdateAllStatuses(status.toJSON());
200
220
  }
201
221
  }
@@ -1,4 +1,4 @@
1
- import { type ILogger, type ILogLevel, type PowerSyncConnectionOptions, type StreamingSyncImplementation, type StreamingSyncImplementationListener, type SyncStatusOptions, BaseObserver, ConnectionManager, DBAdapter, SyncStatus } from '@powersync/common';
1
+ import { type ILogger, type ILogLevel, type PowerSyncConnectionOptions, type StreamingSyncImplementation, type StreamingSyncImplementationListener, type SyncStatusOptions, BaseObserver, ConnectionManager, DBAdapter, SubscribedStream, SyncStatus } from '@powersync/common';
2
2
  import { Mutex } from 'async-mutex';
3
3
  import * as Comlink from 'comlink';
4
4
  import { WebStreamingSyncImplementation, WebStreamingSyncImplementationOptions } from '../../db/sync/WebStreamingSyncImplementation';
@@ -27,7 +27,7 @@ export type ManualSharedSyncPayload = {
27
27
  * @internal
28
28
  */
29
29
  export type SharedSyncInitOptions = {
30
- streamOptions: Omit<WebStreamingSyncImplementationOptions, 'adapter' | 'uploadCrud' | 'remote'>;
30
+ streamOptions: Omit<WebStreamingSyncImplementationOptions, 'adapter' | 'uploadCrud' | 'remote' | 'subscriptions'>;
31
31
  dbParams: ResolvedWebSQLOpenOptions;
32
32
  };
33
33
  /**
@@ -43,6 +43,7 @@ export type WrappedSyncPort = {
43
43
  port: MessagePort;
44
44
  clientProvider: Comlink.Remote<AbstractSharedSyncClientProvider>;
45
45
  db?: DBAdapter;
46
+ currentSubscriptions: SubscribedStream[];
46
47
  };
47
48
  /**
48
49
  * @internal
@@ -55,7 +56,7 @@ export type RemoteOperationAbortController = {
55
56
  * @internal
56
57
  * Shared sync implementation which runs inside a shared webworker
57
58
  */
58
- export declare class SharedSyncImplementation extends BaseObserver<SharedSyncImplementationListener> implements StreamingSyncImplementation {
59
+ export declare class SharedSyncImplementation extends BaseObserver<SharedSyncImplementationListener> {
59
60
  protected ports: WrappedSyncPort[];
60
61
  protected isInitialized: Promise<void>;
61
62
  protected statusListener?: () => void;
@@ -66,6 +67,7 @@ export declare class SharedSyncImplementation extends BaseObserver<SharedSyncImp
66
67
  protected logger: ILogger;
67
68
  protected lastConnectOptions: PowerSyncConnectionOptions | undefined;
68
69
  protected portMutex: Mutex;
70
+ private subscriptions;
69
71
  protected connectionManager: ConnectionManager;
70
72
  syncStatus: SyncStatus;
71
73
  broadCastLogger: ILogger;
@@ -75,6 +77,8 @@ export declare class SharedSyncImplementation extends BaseObserver<SharedSyncImp
75
77
  waitForStatus(status: SyncStatusOptions): Promise<void>;
76
78
  waitUntilStatusMatches(predicate: (status: SyncStatus) => boolean): Promise<void>;
77
79
  waitForReady(): Promise<void>;
80
+ private collectActiveSubscriptions;
81
+ updateSubscriptions(port: WrappedSyncPort, subscriptions: SubscribedStream[]): void;
78
82
  setLogLevel(level: ILogLevel): void;
79
83
  /**
80
84
  * Configures the DBAdapter connection and a streaming sync client.
@@ -92,12 +96,16 @@ export declare class SharedSyncImplementation extends BaseObserver<SharedSyncImp
92
96
  /**
93
97
  * Adds a new client tab's message port to the list of connected ports
94
98
  */
95
- addPort(port: MessagePort): Promise<void>;
99
+ addPort(port: MessagePort): Promise<{
100
+ port: MessagePort;
101
+ clientProvider: Comlink.Remote<AbstractSharedSyncClientProvider>;
102
+ currentSubscriptions: never[];
103
+ }>;
96
104
  /**
97
105
  * Removes a message port client from this manager's managed
98
106
  * clients.
99
107
  */
100
- removePort(port: MessagePort): Promise<() => void>;
108
+ removePort(port: WrappedSyncPort): Promise<() => void>;
101
109
  triggerCrudUpload(): void;
102
110
  hasCompletedSync(): Promise<boolean>;
103
111
  getWriteCheckpoint(): Promise<string>;
@@ -113,5 +121,5 @@ export declare class SharedSyncImplementation extends BaseObserver<SharedSyncImp
113
121
  * A function only used for unit tests which updates the internal
114
122
  * sync stream client and all tab client's sync status
115
123
  */
116
- private _testUpdateAllStatuses;
124
+ _testUpdateAllStatuses(status: SyncStatusOptions): Promise<void>;
117
125
  }
@@ -40,6 +40,7 @@ export class SharedSyncImplementation extends BaseObserver {
40
40
  logger;
41
41
  lastConnectOptions;
42
42
  portMutex;
43
+ subscriptions = [];
43
44
  connectionManager;
44
45
  syncStatus;
45
46
  broadCastLogger;
@@ -102,6 +103,23 @@ export class SharedSyncImplementation extends BaseObserver {
102
103
  async waitForReady() {
103
104
  return this.isInitialized;
104
105
  }
106
+ collectActiveSubscriptions() {
107
+ this.logger.debug('Collecting active stream subscriptions across tabs');
108
+ const active = new Map();
109
+ for (const port of this.ports) {
110
+ for (const stream of port.currentSubscriptions) {
111
+ const serializedKey = JSON.stringify(stream);
112
+ active.set(serializedKey, stream);
113
+ }
114
+ }
115
+ this.subscriptions = [...active.values()];
116
+ this.logger.debug('Collected stream subscriptions', this.subscriptions);
117
+ this.connectionManager.syncStreamImplementation?.updateSubscriptions(this.subscriptions);
118
+ }
119
+ updateSubscriptions(port, subscriptions) {
120
+ port.currentSubscriptions = subscriptions;
121
+ this.collectActiveSubscriptions();
122
+ }
105
123
  setLogLevel(level) {
106
124
  this.logger.setLevel(level);
107
125
  this.broadCastLogger.setLevel(level);
@@ -111,6 +129,7 @@ export class SharedSyncImplementation extends BaseObserver {
111
129
  */
112
130
  async setParams(params) {
113
131
  await this.portMutex.runExclusive(async () => {
132
+ this.collectActiveSubscriptions();
114
133
  if (this.syncParams) {
115
134
  // Cannot modify already existing sync implementation params
116
135
  // But we can ask for a DB adapter, if required, at this point.
@@ -156,10 +175,11 @@ export class SharedSyncImplementation extends BaseObserver {
156
175
  * Adds a new client tab's message port to the list of connected ports
157
176
  */
158
177
  async addPort(port) {
159
- await this.portMutex.runExclusive(() => {
178
+ return await this.portMutex.runExclusive(() => {
160
179
  const portProvider = {
161
180
  port,
162
- clientProvider: Comlink.wrap(port)
181
+ clientProvider: Comlink.wrap(port),
182
+ currentSubscriptions: []
163
183
  };
164
184
  this.ports.push(portProvider);
165
185
  // Give the newly connected client the latest status
@@ -167,6 +187,7 @@ export class SharedSyncImplementation extends BaseObserver {
167
187
  if (status) {
168
188
  portProvider.clientProvider.statusChanged(status.toJSON());
169
189
  }
190
+ return portProvider;
170
191
  });
171
192
  }
172
193
  /**
@@ -178,7 +199,7 @@ export class SharedSyncImplementation extends BaseObserver {
178
199
  // Warns if the port is not found. This should not happen in practice.
179
200
  // We return early if the port is not found.
180
201
  const { trackedPort, shouldReconnect } = await this.portMutex.runExclusive(async () => {
181
- const index = this.ports.findIndex((p) => p.port == port);
202
+ const index = this.ports.findIndex((p) => p == port);
182
203
  if (index < 0) {
183
204
  this.logger.warn(`Could not remove port ${port} since it is not present in active ports.`);
184
205
  return {};
@@ -191,7 +212,7 @@ export class SharedSyncImplementation extends BaseObserver {
191
212
  * not resolve. Abort them here.
192
213
  */
193
214
  [this.fetchCredentialsController, this.uploadDataController].forEach((abortController) => {
194
- if (abortController?.activePort.port == port) {
215
+ if (abortController?.activePort == port) {
195
216
  abortController.controller.abort(new AbortOperation('Closing pending requests after client port is removed'));
196
217
  }
197
218
  });
@@ -218,6 +239,8 @@ export class SharedSyncImplementation extends BaseObserver {
218
239
  if (trackedPort.db) {
219
240
  await trackedPort.db.close();
220
241
  }
242
+ // Re-index subscriptions, the subscriptions of the removed port would no longer be considered.
243
+ this.collectActiveSubscriptions();
221
244
  // Release proxy
222
245
  return () => trackedPort.clientProvider[Comlink.releaseProxy]();
223
246
  }
@@ -312,6 +335,7 @@ export class SharedSyncImplementation extends BaseObserver {
312
335
  });
313
336
  },
314
337
  ...syncParams.streamOptions,
338
+ subscriptions: this.subscriptions,
315
339
  // Logger cannot be transferred just yet
316
340
  logger: this.logger
317
341
  });
@@ -1,27 +1,11 @@
1
1
  import { createBaseLogger } from '@powersync/common';
2
- import * as Comlink from 'comlink';
3
- import { SharedSyncClientEvent, SharedSyncImplementation } from './SharedSyncImplementation';
2
+ import { SharedSyncImplementation } from './SharedSyncImplementation';
3
+ import { WorkerClient } from './WorkerClient';
4
4
  const _self = self;
5
5
  const logger = createBaseLogger();
6
6
  logger.useDefaults();
7
7
  const sharedSyncImplementation = new SharedSyncImplementation();
8
8
  _self.onconnect = async function (event) {
9
9
  const port = event.ports[0];
10
- /**
11
- * Adds an extra listener which can remove this port
12
- * from the list of monitored ports.
13
- */
14
- port.addEventListener('message', async (event) => {
15
- const payload = event.data;
16
- if (payload?.event == SharedSyncClientEvent.CLOSE_CLIENT) {
17
- const release = await sharedSyncImplementation.removePort(port);
18
- port.postMessage({
19
- event: SharedSyncClientEvent.CLOSE_ACK,
20
- data: {}
21
- });
22
- release?.();
23
- }
24
- });
25
- await sharedSyncImplementation.addPort(port);
26
- Comlink.expose(sharedSyncImplementation, port);
10
+ await new WorkerClient(sharedSyncImplementation, port).initialize();
27
11
  };
@@ -0,0 +1,32 @@
1
+ import { SharedSyncImplementation, SharedSyncInitOptions } from './SharedSyncImplementation';
2
+ import { ILogLevel, PowerSyncConnectionOptions, SubscribedStream, SyncStatusOptions } from '@powersync/common';
3
+ /**
4
+ * A client to the shared sync worker.
5
+ *
6
+ * The shared sync implementation needs a per-client view of subscriptions so that subscriptions of closed tabs can
7
+ * automatically be evicted later.
8
+ */
9
+ export declare class WorkerClient {
10
+ private readonly sync;
11
+ private readonly port;
12
+ private resolvedPort;
13
+ constructor(sync: SharedSyncImplementation, port: MessagePort);
14
+ initialize(): Promise<void>;
15
+ private removePort;
16
+ /**
17
+ * Called by a client after obtaining a lock with a random name.
18
+ *
19
+ * When the client tab is closed, its lock will be returned. So when the shared worker attempts to acquire the lock,
20
+ * it can consider the connection to be closed.
21
+ */
22
+ addLockBasedCloseSignal(name: string): void;
23
+ setLogLevel(level: ILogLevel): void;
24
+ triggerCrudUpload(): void;
25
+ setParams(params: SharedSyncInitOptions, subscriptions: SubscribedStream[]): Promise<void>;
26
+ getWriteCheckpoint(): Promise<string>;
27
+ hasCompletedSync(): Promise<boolean>;
28
+ connect(options?: PowerSyncConnectionOptions): Promise<void>;
29
+ updateSubscriptions(subscriptions: SubscribedStream[]): void;
30
+ disconnect(): Promise<void>;
31
+ _testUpdateAllStatuses(status: SyncStatusOptions): Promise<void>;
32
+ }
@@ -0,0 +1,84 @@
1
+ import * as Comlink from 'comlink';
2
+ import { SharedSyncClientEvent } from './SharedSyncImplementation';
3
+ import { getNavigatorLocks } from '../../shared/navigator';
4
+ /**
5
+ * A client to the shared sync worker.
6
+ *
7
+ * The shared sync implementation needs a per-client view of subscriptions so that subscriptions of closed tabs can
8
+ * automatically be evicted later.
9
+ */
10
+ export class WorkerClient {
11
+ sync;
12
+ port;
13
+ resolvedPort = null;
14
+ constructor(sync, port) {
15
+ this.sync = sync;
16
+ this.port = port;
17
+ }
18
+ async initialize() {
19
+ /**
20
+ * Adds an extra listener which can remove this port
21
+ * from the list of monitored ports.
22
+ */
23
+ this.port.addEventListener('message', async (event) => {
24
+ const payload = event.data;
25
+ if (payload?.event == SharedSyncClientEvent.CLOSE_CLIENT) {
26
+ await this.removePort();
27
+ }
28
+ });
29
+ this.resolvedPort = await this.sync.addPort(this.port);
30
+ Comlink.expose(this, this.port);
31
+ }
32
+ async removePort() {
33
+ if (this.resolvedPort) {
34
+ const release = await this.sync.removePort(this.resolvedPort);
35
+ this.resolvedPort = null;
36
+ this.port.postMessage({
37
+ event: SharedSyncClientEvent.CLOSE_ACK,
38
+ data: {}
39
+ });
40
+ release?.();
41
+ }
42
+ }
43
+ /**
44
+ * Called by a client after obtaining a lock with a random name.
45
+ *
46
+ * When the client tab is closed, its lock will be returned. So when the shared worker attempts to acquire the lock,
47
+ * it can consider the connection to be closed.
48
+ */
49
+ addLockBasedCloseSignal(name) {
50
+ getNavigatorLocks().request(name, async () => {
51
+ await this.removePort();
52
+ });
53
+ }
54
+ setLogLevel(level) {
55
+ this.sync.setLogLevel(level);
56
+ }
57
+ triggerCrudUpload() {
58
+ return this.sync.triggerCrudUpload();
59
+ }
60
+ setParams(params, subscriptions) {
61
+ this.resolvedPort.currentSubscriptions = subscriptions;
62
+ return this.sync.setParams(params);
63
+ }
64
+ getWriteCheckpoint() {
65
+ return this.sync.getWriteCheckpoint();
66
+ }
67
+ hasCompletedSync() {
68
+ return this.sync.hasCompletedSync();
69
+ }
70
+ connect(options) {
71
+ return this.sync.connect(options);
72
+ }
73
+ updateSubscriptions(subscriptions) {
74
+ if (this.resolvedPort) {
75
+ this.sync.updateSubscriptions(this.resolvedPort, subscriptions);
76
+ }
77
+ }
78
+ disconnect() {
79
+ return this.sync.disconnect();
80
+ }
81
+ async _testUpdateAllStatuses(status) {
82
+ return this.sync._testUpdateAllStatuses(status);
83
+ }
84
+ }