@powersync/web 0.0.0-dev-20240506092851

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 (40) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +55 -0
  3. package/lib/src/db/PowerSyncDatabase.d.ts +43 -0
  4. package/lib/src/db/PowerSyncDatabase.js +91 -0
  5. package/lib/src/db/adapters/AbstractWebPowerSyncDatabaseOpenFactory.d.ts +23 -0
  6. package/lib/src/db/adapters/AbstractWebPowerSyncDatabaseOpenFactory.js +56 -0
  7. package/lib/src/db/adapters/SSRDBAdapter.d.ts +29 -0
  8. package/lib/src/db/adapters/SSRDBAdapter.js +85 -0
  9. package/lib/src/db/adapters/wa-sqlite/WASQLiteDBAdapter.d.ts +56 -0
  10. package/lib/src/db/adapters/wa-sqlite/WASQLiteDBAdapter.js +196 -0
  11. package/lib/src/db/adapters/wa-sqlite/WASQLitePowerSyncDatabaseOpenFactory.d.ts +6 -0
  12. package/lib/src/db/adapters/wa-sqlite/WASQLitePowerSyncDatabaseOpenFactory.js +11 -0
  13. package/lib/src/db/sync/SSRWebStreamingSyncImplementation.d.ts +8 -0
  14. package/lib/src/db/sync/SSRWebStreamingSyncImplementation.js +13 -0
  15. package/lib/src/db/sync/SharedWebStreamingSyncImplementation.d.ts +47 -0
  16. package/lib/src/db/sync/SharedWebStreamingSyncImplementation.js +187 -0
  17. package/lib/src/db/sync/WebRemote.d.ts +6 -0
  18. package/lib/src/db/sync/WebRemote.js +133 -0
  19. package/lib/src/db/sync/WebStreamingSyncImplementation.d.ts +11 -0
  20. package/lib/src/db/sync/WebStreamingSyncImplementation.js +15 -0
  21. package/lib/src/index.d.ts +8 -0
  22. package/lib/src/index.js +8 -0
  23. package/lib/src/worker/db/SharedWASQLiteDB.worker.d.ts +1 -0
  24. package/lib/src/worker/db/SharedWASQLiteDB.worker.js +57 -0
  25. package/lib/src/worker/db/WASQLiteDB.worker.d.ts +1 -0
  26. package/lib/src/worker/db/WASQLiteDB.worker.js +12 -0
  27. package/lib/src/worker/db/open-db.d.ts +20 -0
  28. package/lib/src/worker/db/open-db.js +192 -0
  29. package/lib/src/worker/db/open-worker-database.d.ts +11 -0
  30. package/lib/src/worker/db/open-worker-database.js +30 -0
  31. package/lib/src/worker/sync/AbstractSharedSyncClientProvider.d.ts +17 -0
  32. package/lib/src/worker/sync/AbstractSharedSyncClientProvider.js +5 -0
  33. package/lib/src/worker/sync/BroadcastLogger.d.ts +37 -0
  34. package/lib/src/worker/sync/BroadcastLogger.js +107 -0
  35. package/lib/src/worker/sync/SharedSyncImplementation.d.ts +88 -0
  36. package/lib/src/worker/sync/SharedSyncImplementation.js +247 -0
  37. package/lib/src/worker/sync/SharedSyncImplementation.worker.d.ts +1 -0
  38. package/lib/src/worker/sync/SharedSyncImplementation.worker.js +22 -0
  39. package/lib/tsconfig.tsbuildinfo +1 -0
  40. package/package.json +58 -0
@@ -0,0 +1,247 @@
1
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
2
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
3
+ return new (P || (P = Promise))(function (resolve, reject) {
4
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
5
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
6
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
7
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
8
+ });
9
+ };
10
+ import * as Comlink from 'comlink';
11
+ import Logger from 'js-logger';
12
+ import { BaseObserver, SqliteBucketStorage, SyncStatus, AbortOperation } from '@powersync/common';
13
+ import { WebStreamingSyncImplementation } from '../../db/sync/WebStreamingSyncImplementation';
14
+ import { Mutex } from 'async-mutex';
15
+ import { WebRemote } from '../../db/sync/WebRemote';
16
+ import { WASQLiteDBAdapter } from '../../db/adapters/wa-sqlite/WASQLiteDBAdapter';
17
+ import { BroadcastLogger } from './BroadcastLogger';
18
+ /**
19
+ * Manual message events for shared sync clients
20
+ */
21
+ export var SharedSyncClientEvent;
22
+ (function (SharedSyncClientEvent) {
23
+ /**
24
+ * This client requests the shared sync manager should
25
+ * close it's connection to the client.
26
+ */
27
+ SharedSyncClientEvent["CLOSE_CLIENT"] = "close-client";
28
+ })(SharedSyncClientEvent || (SharedSyncClientEvent = {}));
29
+ /**
30
+ * Shared sync implementation which runs inside a shared webworker
31
+ */
32
+ export class SharedSyncImplementation extends BaseObserver {
33
+ constructor() {
34
+ super();
35
+ this.ports = [];
36
+ this.isInitialized = new Promise((resolve) => {
37
+ const callback = this.registerListener({
38
+ initialized: () => {
39
+ resolve();
40
+ callback === null || callback === void 0 ? void 0 : callback();
41
+ }
42
+ });
43
+ });
44
+ this.syncStatus = new SyncStatus({});
45
+ this.broadCastLogger = new BroadcastLogger(this.ports);
46
+ }
47
+ waitForStatus(status) {
48
+ return __awaiter(this, void 0, void 0, function* () {
49
+ yield this.waitForReady();
50
+ return this.syncStreamClient.waitForStatus(status);
51
+ });
52
+ }
53
+ get lastSyncedAt() {
54
+ var _a;
55
+ return (_a = this.syncStreamClient) === null || _a === void 0 ? void 0 : _a.lastSyncedAt;
56
+ }
57
+ get isConnected() {
58
+ var _a, _b;
59
+ return (_b = (_a = this.syncStreamClient) === null || _a === void 0 ? void 0 : _a.isConnected) !== null && _b !== void 0 ? _b : false;
60
+ }
61
+ waitForReady() {
62
+ return __awaiter(this, void 0, void 0, function* () {
63
+ return this.isInitialized;
64
+ });
65
+ }
66
+ /**
67
+ * Configures the DBAdapter connection and a streaming sync client.
68
+ */
69
+ init(dbWorkerPort, params) {
70
+ return __awaiter(this, void 0, void 0, function* () {
71
+ var _a, _b;
72
+ if (this.syncStreamClient) {
73
+ // Cannot modify already existing sync implementation
74
+ return;
75
+ }
76
+ const logger = ((_b = (_a = params.streamOptions) === null || _a === void 0 ? void 0 : _a.flags) === null || _b === void 0 ? void 0 : _b.broadcastLogs) ? this.broadCastLogger : Logger.get('shared-sync');
77
+ self.onerror = (event) => {
78
+ // Share any uncaught events on the broadcast logger
79
+ logger.error('Uncaught exception in PowerSync shared sync worker', event);
80
+ };
81
+ this.syncStreamClient = new WebStreamingSyncImplementation(Object.assign(Object.assign({ adapter: new SqliteBucketStorage(new WASQLiteDBAdapter({
82
+ dbFilename: params.dbName,
83
+ workerPort: dbWorkerPort,
84
+ flags: { enableMultiTabs: true },
85
+ logger
86
+ }), new Mutex(), logger), remote: new WebRemote({
87
+ fetchCredentials: () => __awaiter(this, void 0, void 0, function* () {
88
+ const lastPort = this.ports[this.ports.length - 1];
89
+ return new Promise((resolve, reject) => __awaiter(this, void 0, void 0, function* () {
90
+ const abortController = new AbortController();
91
+ this.fetchCredentialsController = {
92
+ controller: abortController,
93
+ activePort: lastPort
94
+ };
95
+ abortController.signal.onabort = reject;
96
+ try {
97
+ resolve(yield lastPort.clientProvider.fetchCredentials());
98
+ }
99
+ catch (ex) {
100
+ reject(ex);
101
+ }
102
+ finally {
103
+ this.fetchCredentialsController = undefined;
104
+ }
105
+ }));
106
+ })
107
+ }), uploadCrud: () => __awaiter(this, void 0, void 0, function* () {
108
+ const lastPort = this.ports[this.ports.length - 1];
109
+ return new Promise((resolve, reject) => __awaiter(this, void 0, void 0, function* () {
110
+ const abortController = new AbortController();
111
+ this.uploadDataController = {
112
+ controller: abortController,
113
+ activePort: lastPort
114
+ };
115
+ // Resolving will make it retry
116
+ abortController.signal.onabort = () => resolve();
117
+ try {
118
+ resolve(yield lastPort.clientProvider.uploadCrud());
119
+ }
120
+ catch (ex) {
121
+ reject(ex);
122
+ }
123
+ finally {
124
+ this.uploadDataController = undefined;
125
+ }
126
+ }));
127
+ }) }, params.streamOptions), {
128
+ // Logger cannot be transferred just yet
129
+ logger }));
130
+ this.syncStreamClient.registerListener({
131
+ statusChanged: (status) => {
132
+ this.updateAllStatuses(status.toJSON());
133
+ }
134
+ });
135
+ this.iterateListeners((l) => { var _a; return (_a = l.initialized) === null || _a === void 0 ? void 0 : _a.call(l); });
136
+ });
137
+ }
138
+ dispose() {
139
+ return __awaiter(this, void 0, void 0, function* () {
140
+ var _a, _b;
141
+ yield this.waitForReady();
142
+ (_a = this.statusListener) === null || _a === void 0 ? void 0 : _a.call(this);
143
+ return (_b = this.syncStreamClient) === null || _b === void 0 ? void 0 : _b.dispose();
144
+ });
145
+ }
146
+ /**
147
+ * Connects to the PowerSync backend instance.
148
+ * Multiple tabs can safely call this in their initialization.
149
+ * The connection will simply be reconnected whenever a new tab
150
+ * connects.
151
+ */
152
+ connect() {
153
+ return __awaiter(this, void 0, void 0, function* () {
154
+ yield this.waitForReady();
155
+ // This effectively queues connect and disconnect calls. Ensuring multiple tabs' requests are synchronized
156
+ return navigator.locks.request('shared-sync-connect', () => { var _a; return (_a = this.syncStreamClient) === null || _a === void 0 ? void 0 : _a.connect(); });
157
+ });
158
+ }
159
+ disconnect() {
160
+ return __awaiter(this, void 0, void 0, function* () {
161
+ yield this.waitForReady();
162
+ // This effectively queues connect and disconnect calls. Ensuring multiple tabs' requests are synchronized
163
+ return navigator.locks.request('shared-sync-connect', () => { var _a; return (_a = this.syncStreamClient) === null || _a === void 0 ? void 0 : _a.disconnect(); });
164
+ });
165
+ }
166
+ /**
167
+ * Adds a new client tab's message port to the list of connected ports
168
+ */
169
+ addPort(port) {
170
+ var _a;
171
+ const portProvider = {
172
+ port,
173
+ clientProvider: Comlink.wrap(port)
174
+ };
175
+ this.ports.push(portProvider);
176
+ // Give the newly connected client the latest status
177
+ const status = (_a = this.syncStreamClient) === null || _a === void 0 ? void 0 : _a.syncStatus;
178
+ if (status) {
179
+ portProvider.clientProvider.statusChanged(status.toJSON());
180
+ }
181
+ }
182
+ /**
183
+ * Removes a message port client from this manager's managed
184
+ * clients.
185
+ */
186
+ removePort(port) {
187
+ const index = this.ports.findIndex((p) => p.port == port);
188
+ if (index < 0) {
189
+ console.warn(`Could not remove port ${port} since it is not present in active ports.`);
190
+ return;
191
+ }
192
+ const trackedPort = this.ports[index];
193
+ // Release proxy
194
+ trackedPort.clientProvider[Comlink.releaseProxy]();
195
+ this.ports.splice(index, 1);
196
+ /**
197
+ * The port might currently be in use. Any active functions might
198
+ * not resolve. Abort them here.
199
+ */
200
+ [this.fetchCredentialsController, this.uploadDataController].forEach((abortController) => {
201
+ if ((abortController === null || abortController === void 0 ? void 0 : abortController.activePort.port) == port) {
202
+ abortController.controller.abort(new AbortOperation('Closing pending requests after client port is removed'));
203
+ }
204
+ });
205
+ }
206
+ triggerCrudUpload() {
207
+ this.waitForReady().then(() => { var _a; return (_a = this.syncStreamClient) === null || _a === void 0 ? void 0 : _a.triggerCrudUpload(); });
208
+ }
209
+ obtainLock(lockOptions) {
210
+ return __awaiter(this, void 0, void 0, function* () {
211
+ yield this.waitForReady();
212
+ return this.syncStreamClient.obtainLock(lockOptions);
213
+ });
214
+ }
215
+ hasCompletedSync() {
216
+ return __awaiter(this, void 0, void 0, function* () {
217
+ yield this.waitForReady();
218
+ return this.syncStreamClient.hasCompletedSync();
219
+ });
220
+ }
221
+ getWriteCheckpoint() {
222
+ return __awaiter(this, void 0, void 0, function* () {
223
+ yield this.waitForReady();
224
+ return this.syncStreamClient.getWriteCheckpoint();
225
+ });
226
+ }
227
+ /**
228
+ * A method to update the all shared statuses for each
229
+ * client.
230
+ */
231
+ updateAllStatuses(status) {
232
+ this.syncStatus = new SyncStatus(status);
233
+ this.ports.forEach((p) => p.clientProvider.statusChanged(status));
234
+ }
235
+ /**
236
+ * A function only used for unit tests which updates the internal
237
+ * sync stream client and all tab client's sync status
238
+ */
239
+ _testUpdateAllStatuses(status) {
240
+ if (!this.syncStreamClient) {
241
+ console.warn('no stream client has been initialized yet');
242
+ }
243
+ // Only assigning, don't call listeners for this test
244
+ this.syncStreamClient.syncStatus = new SyncStatus(status);
245
+ this.updateAllStatuses(status);
246
+ }
247
+ }
@@ -0,0 +1,22 @@
1
+ import * as Comlink from 'comlink';
2
+ import { SharedSyncImplementation, SharedSyncClientEvent } from './SharedSyncImplementation';
3
+ import Logger from 'js-logger';
4
+ const _self = self;
5
+ Logger.useDefaults();
6
+ const sharedSyncImplementation = new SharedSyncImplementation();
7
+ _self.onconnect = function (event) {
8
+ const port = event.ports[0];
9
+ /**
10
+ * Adds an extra listener which can remove this port
11
+ * from the list of monitored ports.
12
+ */
13
+ port.addEventListener('message', (event) => {
14
+ const payload = event.data;
15
+ if ((payload === null || payload === void 0 ? void 0 : payload.event) == SharedSyncClientEvent.CLOSE_CLIENT) {
16
+ console.log('closing shared for port', port);
17
+ sharedSyncImplementation.removePort(port);
18
+ }
19
+ });
20
+ Comlink.expose(sharedSyncImplementation, port);
21
+ sharedSyncImplementation.addPort(port);
22
+ };