@powersync/web 1.36.0 → 1.37.0

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 (91) hide show
  1. package/dist/index.umd.js +1127 -1235
  2. package/dist/index.umd.js.map +1 -1
  3. package/dist/worker/SharedSyncImplementation.umd.js +481 -3111
  4. package/dist/worker/SharedSyncImplementation.umd.js.map +1 -1
  5. package/dist/worker/WASQLiteDB.umd.js +688 -836
  6. package/dist/worker/WASQLiteDB.umd.js.map +1 -1
  7. package/lib/package.json +2 -3
  8. package/lib/src/db/PowerSyncDatabase.d.ts +1 -2
  9. package/lib/src/db/PowerSyncDatabase.js +3 -4
  10. package/lib/src/db/adapters/AsyncWebAdapter.d.ts +40 -0
  11. package/lib/src/db/adapters/AsyncWebAdapter.js +69 -0
  12. package/lib/src/db/adapters/SSRDBAdapter.d.ts +1 -2
  13. package/lib/src/db/adapters/SSRDBAdapter.js +5 -6
  14. package/lib/src/db/adapters/wa-sqlite/ConcurrentConnection.d.ts +56 -0
  15. package/lib/src/db/adapters/wa-sqlite/ConcurrentConnection.js +121 -0
  16. package/lib/src/db/adapters/wa-sqlite/DatabaseClient.d.ts +54 -0
  17. package/lib/src/db/adapters/wa-sqlite/DatabaseClient.js +227 -0
  18. package/lib/src/db/adapters/wa-sqlite/DatabaseServer.d.ts +47 -0
  19. package/lib/src/db/adapters/wa-sqlite/DatabaseServer.js +146 -0
  20. package/lib/src/db/adapters/wa-sqlite/RawSqliteConnection.d.ts +46 -0
  21. package/lib/src/db/adapters/wa-sqlite/RawSqliteConnection.js +147 -0
  22. package/lib/src/db/adapters/wa-sqlite/WASQLiteOpenFactory.d.ts +14 -6
  23. package/lib/src/db/adapters/wa-sqlite/WASQLiteOpenFactory.js +66 -39
  24. package/lib/src/db/adapters/wa-sqlite/vfs.d.ts +61 -0
  25. package/lib/src/db/adapters/wa-sqlite/vfs.js +91 -0
  26. package/lib/src/db/adapters/web-sql-flags.d.ts +5 -0
  27. package/lib/src/db/sync/SSRWebStreamingSyncImplementation.d.ts +1 -2
  28. package/lib/src/db/sync/SSRWebStreamingSyncImplementation.js +2 -3
  29. package/lib/src/db/sync/SharedWebStreamingSyncImplementation.js +4 -19
  30. package/lib/src/index.d.ts +1 -4
  31. package/lib/src/index.js +1 -4
  32. package/lib/src/shared/tab_close_signal.d.ts +11 -0
  33. package/lib/src/shared/tab_close_signal.js +26 -0
  34. package/lib/src/worker/db/MultiDatabaseServer.d.ts +17 -0
  35. package/lib/src/worker/db/MultiDatabaseServer.js +86 -0
  36. package/lib/src/worker/db/WASQLiteDB.worker.js +9 -48
  37. package/lib/src/worker/db/open-worker-database.d.ts +3 -3
  38. package/lib/src/worker/db/open-worker-database.js +1 -1
  39. package/lib/src/worker/sync/SharedSyncImplementation.d.ts +5 -6
  40. package/lib/src/worker/sync/SharedSyncImplementation.js +92 -54
  41. package/lib/tsconfig.tsbuildinfo +1 -1
  42. package/package.json +3 -4
  43. package/src/db/PowerSyncDatabase.ts +3 -3
  44. package/src/db/adapters/AsyncWebAdapter.ts +91 -0
  45. package/src/db/adapters/SSRDBAdapter.ts +7 -7
  46. package/src/db/adapters/wa-sqlite/ConcurrentConnection.ts +137 -0
  47. package/src/db/adapters/wa-sqlite/DatabaseClient.ts +325 -0
  48. package/src/db/adapters/wa-sqlite/DatabaseServer.ts +201 -0
  49. package/src/db/adapters/wa-sqlite/RawSqliteConnection.ts +191 -0
  50. package/src/db/adapters/wa-sqlite/WASQLiteOpenFactory.ts +87 -43
  51. package/src/db/adapters/wa-sqlite/vfs.ts +112 -0
  52. package/src/db/adapters/web-sql-flags.ts +6 -0
  53. package/src/db/sync/SSRWebStreamingSyncImplementation.ts +2 -3
  54. package/src/db/sync/SharedWebStreamingSyncImplementation.ts +4 -20
  55. package/src/index.ts +1 -4
  56. package/src/shared/tab_close_signal.ts +28 -0
  57. package/src/worker/db/MultiDatabaseServer.ts +104 -0
  58. package/src/worker/db/WASQLiteDB.worker.ts +10 -57
  59. package/src/worker/db/open-worker-database.ts +3 -3
  60. package/src/worker/sync/SharedSyncImplementation.ts +118 -58
  61. package/dist/_journeyapps_wa-sqlite-_journeyapps_wa-sqlite_src_examples_AccessHandlePoolVFS_js-_journeyapp-89f0ba.index.umd.js +0 -1881
  62. package/dist/_journeyapps_wa-sqlite-_journeyapps_wa-sqlite_src_examples_AccessHandlePoolVFS_js-_journeyapp-89f0ba.index.umd.js.map +0 -1
  63. package/dist/_journeyapps_wa-sqlite_src_examples_AccessHandlePoolVFS_js-_journeyapps_wa-sqlite_src_example-97ebe9.index.umd.js +0 -555
  64. package/dist/_journeyapps_wa-sqlite_src_examples_AccessHandlePoolVFS_js-_journeyapps_wa-sqlite_src_example-97ebe9.index.umd.js.map +0 -1
  65. package/lib/src/db/adapters/AbstractWebSQLOpenFactory.d.ts +0 -17
  66. package/lib/src/db/adapters/AbstractWebSQLOpenFactory.js +0 -33
  67. package/lib/src/db/adapters/AsyncDatabaseConnection.d.ts +0 -49
  68. package/lib/src/db/adapters/AsyncDatabaseConnection.js +0 -1
  69. package/lib/src/db/adapters/LockedAsyncDatabaseAdapter.d.ts +0 -109
  70. package/lib/src/db/adapters/LockedAsyncDatabaseAdapter.js +0 -404
  71. package/lib/src/db/adapters/WorkerWrappedAsyncDatabaseConnection.d.ts +0 -59
  72. package/lib/src/db/adapters/WorkerWrappedAsyncDatabaseConnection.js +0 -147
  73. package/lib/src/db/adapters/wa-sqlite/InternalWASQLiteDBAdapter.d.ts +0 -12
  74. package/lib/src/db/adapters/wa-sqlite/InternalWASQLiteDBAdapter.js +0 -19
  75. package/lib/src/db/adapters/wa-sqlite/WASQLiteConnection.d.ts +0 -155
  76. package/lib/src/db/adapters/wa-sqlite/WASQLiteConnection.js +0 -401
  77. package/lib/src/db/adapters/wa-sqlite/WASQLiteDBAdapter.d.ts +0 -32
  78. package/lib/src/db/adapters/wa-sqlite/WASQLiteDBAdapter.js +0 -49
  79. package/lib/src/worker/db/SharedWASQLiteConnection.d.ts +0 -42
  80. package/lib/src/worker/db/SharedWASQLiteConnection.js +0 -90
  81. package/lib/src/worker/db/WorkerWASQLiteConnection.d.ts +0 -9
  82. package/lib/src/worker/db/WorkerWASQLiteConnection.js +0 -12
  83. package/src/db/adapters/AbstractWebSQLOpenFactory.ts +0 -48
  84. package/src/db/adapters/AsyncDatabaseConnection.ts +0 -55
  85. package/src/db/adapters/LockedAsyncDatabaseAdapter.ts +0 -489
  86. package/src/db/adapters/WorkerWrappedAsyncDatabaseConnection.ts +0 -201
  87. package/src/db/adapters/wa-sqlite/InternalWASQLiteDBAdapter.ts +0 -23
  88. package/src/db/adapters/wa-sqlite/WASQLiteConnection.ts +0 -497
  89. package/src/db/adapters/wa-sqlite/WASQLiteDBAdapter.ts +0 -86
  90. package/src/worker/db/SharedWASQLiteConnection.ts +0 -131
  91. package/src/worker/db/WorkerWASQLiteConnection.ts +0 -14
@@ -3,317 +3,6 @@ var sdk_web;
3
3
  /******/ "use strict";
4
4
  /******/ var __webpack_modules__ = ({
5
5
 
6
- /***/ "../../node_modules/.pnpm/async-mutex@0.5.0/node_modules/async-mutex/index.mjs"
7
- /*!*************************************************************************************!*\
8
- !*** ../../node_modules/.pnpm/async-mutex@0.5.0/node_modules/async-mutex/index.mjs ***!
9
- \*************************************************************************************/
10
- (__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) {
11
-
12
- __webpack_require__.r(__webpack_exports__);
13
- /* harmony export */ __webpack_require__.d(__webpack_exports__, {
14
- /* harmony export */ E_ALREADY_LOCKED: () => (/* binding */ E_ALREADY_LOCKED),
15
- /* harmony export */ E_CANCELED: () => (/* binding */ E_CANCELED),
16
- /* harmony export */ E_TIMEOUT: () => (/* binding */ E_TIMEOUT),
17
- /* harmony export */ Mutex: () => (/* binding */ Mutex),
18
- /* harmony export */ Semaphore: () => (/* binding */ Semaphore),
19
- /* harmony export */ tryAcquire: () => (/* binding */ tryAcquire),
20
- /* harmony export */ withTimeout: () => (/* binding */ withTimeout)
21
- /* harmony export */ });
22
- const E_TIMEOUT = new Error('timeout while waiting for mutex to become available');
23
- const E_ALREADY_LOCKED = new Error('mutex already locked');
24
- const E_CANCELED = new Error('request for lock canceled');
25
-
26
- var __awaiter$2 = ( false) || function (thisArg, _arguments, P, generator) {
27
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
28
- return new (P || (P = Promise))(function (resolve, reject) {
29
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
30
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
31
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
32
- step((generator = generator.apply(thisArg, _arguments || [])).next());
33
- });
34
- };
35
- class Semaphore {
36
- constructor(_value, _cancelError = E_CANCELED) {
37
- this._value = _value;
38
- this._cancelError = _cancelError;
39
- this._queue = [];
40
- this._weightedWaiters = [];
41
- }
42
- acquire(weight = 1, priority = 0) {
43
- if (weight <= 0)
44
- throw new Error(`invalid weight ${weight}: must be positive`);
45
- return new Promise((resolve, reject) => {
46
- const task = { resolve, reject, weight, priority };
47
- const i = findIndexFromEnd(this._queue, (other) => priority <= other.priority);
48
- if (i === -1 && weight <= this._value) {
49
- // Needs immediate dispatch, skip the queue
50
- this._dispatchItem(task);
51
- }
52
- else {
53
- this._queue.splice(i + 1, 0, task);
54
- }
55
- });
56
- }
57
- runExclusive(callback_1) {
58
- return __awaiter$2(this, arguments, void 0, function* (callback, weight = 1, priority = 0) {
59
- const [value, release] = yield this.acquire(weight, priority);
60
- try {
61
- return yield callback(value);
62
- }
63
- finally {
64
- release();
65
- }
66
- });
67
- }
68
- waitForUnlock(weight = 1, priority = 0) {
69
- if (weight <= 0)
70
- throw new Error(`invalid weight ${weight}: must be positive`);
71
- if (this._couldLockImmediately(weight, priority)) {
72
- return Promise.resolve();
73
- }
74
- else {
75
- return new Promise((resolve) => {
76
- if (!this._weightedWaiters[weight - 1])
77
- this._weightedWaiters[weight - 1] = [];
78
- insertSorted(this._weightedWaiters[weight - 1], { resolve, priority });
79
- });
80
- }
81
- }
82
- isLocked() {
83
- return this._value <= 0;
84
- }
85
- getValue() {
86
- return this._value;
87
- }
88
- setValue(value) {
89
- this._value = value;
90
- this._dispatchQueue();
91
- }
92
- release(weight = 1) {
93
- if (weight <= 0)
94
- throw new Error(`invalid weight ${weight}: must be positive`);
95
- this._value += weight;
96
- this._dispatchQueue();
97
- }
98
- cancel() {
99
- this._queue.forEach((entry) => entry.reject(this._cancelError));
100
- this._queue = [];
101
- }
102
- _dispatchQueue() {
103
- this._drainUnlockWaiters();
104
- while (this._queue.length > 0 && this._queue[0].weight <= this._value) {
105
- this._dispatchItem(this._queue.shift());
106
- this._drainUnlockWaiters();
107
- }
108
- }
109
- _dispatchItem(item) {
110
- const previousValue = this._value;
111
- this._value -= item.weight;
112
- item.resolve([previousValue, this._newReleaser(item.weight)]);
113
- }
114
- _newReleaser(weight) {
115
- let called = false;
116
- return () => {
117
- if (called)
118
- return;
119
- called = true;
120
- this.release(weight);
121
- };
122
- }
123
- _drainUnlockWaiters() {
124
- if (this._queue.length === 0) {
125
- for (let weight = this._value; weight > 0; weight--) {
126
- const waiters = this._weightedWaiters[weight - 1];
127
- if (!waiters)
128
- continue;
129
- waiters.forEach((waiter) => waiter.resolve());
130
- this._weightedWaiters[weight - 1] = [];
131
- }
132
- }
133
- else {
134
- const queuedPriority = this._queue[0].priority;
135
- for (let weight = this._value; weight > 0; weight--) {
136
- const waiters = this._weightedWaiters[weight - 1];
137
- if (!waiters)
138
- continue;
139
- const i = waiters.findIndex((waiter) => waiter.priority <= queuedPriority);
140
- (i === -1 ? waiters : waiters.splice(0, i))
141
- .forEach((waiter => waiter.resolve()));
142
- }
143
- }
144
- }
145
- _couldLockImmediately(weight, priority) {
146
- return (this._queue.length === 0 || this._queue[0].priority < priority) &&
147
- weight <= this._value;
148
- }
149
- }
150
- function insertSorted(a, v) {
151
- const i = findIndexFromEnd(a, (other) => v.priority <= other.priority);
152
- a.splice(i + 1, 0, v);
153
- }
154
- function findIndexFromEnd(a, predicate) {
155
- for (let i = a.length - 1; i >= 0; i--) {
156
- if (predicate(a[i])) {
157
- return i;
158
- }
159
- }
160
- return -1;
161
- }
162
-
163
- var __awaiter$1 = ( false) || function (thisArg, _arguments, P, generator) {
164
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
165
- return new (P || (P = Promise))(function (resolve, reject) {
166
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
167
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
168
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
169
- step((generator = generator.apply(thisArg, _arguments || [])).next());
170
- });
171
- };
172
- class Mutex {
173
- constructor(cancelError) {
174
- this._semaphore = new Semaphore(1, cancelError);
175
- }
176
- acquire() {
177
- return __awaiter$1(this, arguments, void 0, function* (priority = 0) {
178
- const [, releaser] = yield this._semaphore.acquire(1, priority);
179
- return releaser;
180
- });
181
- }
182
- runExclusive(callback, priority = 0) {
183
- return this._semaphore.runExclusive(() => callback(), 1, priority);
184
- }
185
- isLocked() {
186
- return this._semaphore.isLocked();
187
- }
188
- waitForUnlock(priority = 0) {
189
- return this._semaphore.waitForUnlock(1, priority);
190
- }
191
- release() {
192
- if (this._semaphore.isLocked())
193
- this._semaphore.release();
194
- }
195
- cancel() {
196
- return this._semaphore.cancel();
197
- }
198
- }
199
-
200
- var __awaiter = ( false) || function (thisArg, _arguments, P, generator) {
201
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
202
- return new (P || (P = Promise))(function (resolve, reject) {
203
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
204
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
205
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
206
- step((generator = generator.apply(thisArg, _arguments || [])).next());
207
- });
208
- };
209
- function withTimeout(sync, timeout, timeoutError = E_TIMEOUT) {
210
- return {
211
- acquire: (weightOrPriority, priority) => {
212
- let weight;
213
- if (isSemaphore(sync)) {
214
- weight = weightOrPriority;
215
- }
216
- else {
217
- weight = undefined;
218
- priority = weightOrPriority;
219
- }
220
- if (weight !== undefined && weight <= 0) {
221
- throw new Error(`invalid weight ${weight}: must be positive`);
222
- }
223
- return new Promise((resolve, reject) => __awaiter(this, void 0, void 0, function* () {
224
- let isTimeout = false;
225
- const handle = setTimeout(() => {
226
- isTimeout = true;
227
- reject(timeoutError);
228
- }, timeout);
229
- try {
230
- const ticket = yield (isSemaphore(sync)
231
- ? sync.acquire(weight, priority)
232
- : sync.acquire(priority));
233
- if (isTimeout) {
234
- const release = Array.isArray(ticket) ? ticket[1] : ticket;
235
- release();
236
- }
237
- else {
238
- clearTimeout(handle);
239
- resolve(ticket);
240
- }
241
- }
242
- catch (e) {
243
- if (!isTimeout) {
244
- clearTimeout(handle);
245
- reject(e);
246
- }
247
- }
248
- }));
249
- },
250
- runExclusive(callback, weight, priority) {
251
- return __awaiter(this, void 0, void 0, function* () {
252
- let release = () => undefined;
253
- try {
254
- const ticket = yield this.acquire(weight, priority);
255
- if (Array.isArray(ticket)) {
256
- release = ticket[1];
257
- return yield callback(ticket[0]);
258
- }
259
- else {
260
- release = ticket;
261
- return yield callback();
262
- }
263
- }
264
- finally {
265
- release();
266
- }
267
- });
268
- },
269
- release(weight) {
270
- sync.release(weight);
271
- },
272
- cancel() {
273
- return sync.cancel();
274
- },
275
- waitForUnlock: (weightOrPriority, priority) => {
276
- let weight;
277
- if (isSemaphore(sync)) {
278
- weight = weightOrPriority;
279
- }
280
- else {
281
- weight = undefined;
282
- priority = weightOrPriority;
283
- }
284
- if (weight !== undefined && weight <= 0) {
285
- throw new Error(`invalid weight ${weight}: must be positive`);
286
- }
287
- return new Promise((resolve, reject) => {
288
- const handle = setTimeout(() => reject(timeoutError), timeout);
289
- (isSemaphore(sync)
290
- ? sync.waitForUnlock(weight, priority)
291
- : sync.waitForUnlock(priority)).then(() => {
292
- clearTimeout(handle);
293
- resolve();
294
- });
295
- });
296
- },
297
- isLocked: () => sync.isLocked(),
298
- getValue: () => sync.getValue(),
299
- setValue: (value) => sync.setValue(value),
300
- };
301
- }
302
- function isSemaphore(sync) {
303
- return sync.getValue !== undefined;
304
- }
305
-
306
- // eslint-disable-next-lisne @typescript-eslint/explicit-module-boundary-types
307
- function tryAcquire(sync, alreadyAcquiredError = E_ALREADY_LOCKED) {
308
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
309
- return withTimeout(sync, 0, alreadyAcquiredError);
310
- }
311
-
312
-
313
-
314
-
315
- /***/ },
316
-
317
6
  /***/ "../../node_modules/.pnpm/comlink@4.4.2/node_modules/comlink/dist/esm/comlink.mjs"
318
7
  /*!****************************************************************************************!*\
319
8
  !*** ../../node_modules/.pnpm/comlink@4.4.2/node_modules/comlink/dist/esm/comlink.mjs ***!
@@ -2409,10 +2098,470 @@ const SQLITE_PREPARE_NO_VTAB = 0x04;
2409
2098
 
2410
2099
  /***/ },
2411
2100
 
2412
- /***/ "./lib/src/db/adapters/wa-sqlite/WASQLiteConnection.js"
2413
- /*!*************************************************************!*\
2414
- !*** ./lib/src/db/adapters/wa-sqlite/WASQLiteConnection.js ***!
2415
- \*************************************************************/
2101
+ /***/ "./lib/src/db/adapters/wa-sqlite/ConcurrentConnection.js"
2102
+ /*!***************************************************************!*\
2103
+ !*** ./lib/src/db/adapters/wa-sqlite/ConcurrentConnection.js ***!
2104
+ \***************************************************************/
2105
+ (__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) {
2106
+
2107
+ __webpack_require__.r(__webpack_exports__);
2108
+ /* harmony export */ __webpack_require__.d(__webpack_exports__, {
2109
+ /* harmony export */ ConcurrentSqliteConnection: () => (/* binding */ ConcurrentSqliteConnection),
2110
+ /* harmony export */ ConnectionLeaseToken: () => (/* binding */ ConnectionLeaseToken)
2111
+ /* harmony export */ });
2112
+ /* harmony import */ var _powersync_common__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @powersync/common */ "../common/dist/bundle.mjs");
2113
+
2114
+ /**
2115
+ * A wrapper around a {@link RawSqliteConnection} allowing multiple tabs to access it.
2116
+ *
2117
+ * To allow potentially concurrent accesses from different clients, this requires a local mutex implementation here.
2118
+ *
2119
+ * Note that instances of this class are not safe to proxy across context boundaries with comlink! We need to be able to
2120
+ * rely on mutexes being returned reliably, so additional checks to detect say a client tab closing are required to
2121
+ * avoid deadlocks.
2122
+ */
2123
+ class ConcurrentSqliteConnection {
2124
+ inner;
2125
+ /**
2126
+ * An outer mutex ensuring at most one {@link ConnectionLeaseToken} can exist for this connection at a time.
2127
+ *
2128
+ * If null, we'll use navigator locks instead.
2129
+ */
2130
+ leaseMutex;
2131
+ /**
2132
+ * @param needsNavigatorLocks Whether access to the database needs an additional navigator lock guard.
2133
+ *
2134
+ * While {@link ConcurrentSqliteConnection} prevents concurrent access to a database _connection_, it's possible we
2135
+ * might have multiple connections to the same physical database (e.g. if multiple tabs use dedicated workers).
2136
+ * In those setups, we use navigator locks instead of an internal mutex to guard access..
2137
+ */
2138
+ constructor(inner, needsNavigatorLocks) {
2139
+ this.inner = inner;
2140
+ this.leaseMutex = needsNavigatorLocks ? null : new _powersync_common__WEBPACK_IMPORTED_MODULE_0__.Mutex();
2141
+ }
2142
+ get options() {
2143
+ return this.inner.options;
2144
+ }
2145
+ acquireMutex(abort) {
2146
+ if (this.leaseMutex) {
2147
+ return this.leaseMutex.acquire(abort);
2148
+ }
2149
+ return new Promise((resolve, reject) => {
2150
+ const options = { signal: abort };
2151
+ navigator.locks
2152
+ .request(`db-lock-${this.options.dbFilename}`, options, (_) => {
2153
+ return new Promise((returnLock) => {
2154
+ return resolve(() => {
2155
+ returnLock();
2156
+ });
2157
+ });
2158
+ })
2159
+ .catch(reject);
2160
+ });
2161
+ }
2162
+ // Unsafe, unguarded access to the SQLite connection.
2163
+ unsafeUseInner() {
2164
+ return this.inner;
2165
+ }
2166
+ /**
2167
+ * @returns A {@link ConnectionLeaseToken}. Until that token is returned, no other client can use the database.
2168
+ */
2169
+ async acquireConnection(abort) {
2170
+ const returnMutex = await this.acquireMutex(abort);
2171
+ const token = new ConnectionLeaseToken(returnMutex, this.inner);
2172
+ try {
2173
+ // Assert that the inner connection is initialized at this point, fail early if it's not.
2174
+ this.inner.requireSqlite();
2175
+ // If a previous client was interrupted in the middle of a transaction AND this is a shared worker, it's possible
2176
+ // for the connection to still be in a transaction. To avoid inconsistent state, we roll back connection leases
2177
+ // that haven't been comitted.
2178
+ if (!this.inner.isAutoCommit()) {
2179
+ await this.inner.executeRaw('ROLLBACK');
2180
+ }
2181
+ }
2182
+ catch (e) {
2183
+ returnMutex();
2184
+ throw e;
2185
+ }
2186
+ return token;
2187
+ }
2188
+ async close() {
2189
+ const returnMutex = await this.acquireMutex();
2190
+ try {
2191
+ await this.inner.close();
2192
+ }
2193
+ finally {
2194
+ returnMutex();
2195
+ }
2196
+ }
2197
+ }
2198
+ /**
2199
+ * An instance representing temporary exclusive access to a {@link ConcurrentSqliteConnection}.
2200
+ */
2201
+ class ConnectionLeaseToken {
2202
+ returnMutex;
2203
+ connection;
2204
+ /** Ensures that the client with access to this token can't run statements concurrently. */
2205
+ useMutex = new _powersync_common__WEBPACK_IMPORTED_MODULE_0__.Mutex();
2206
+ closed = false;
2207
+ constructor(returnMutex, connection) {
2208
+ this.returnMutex = returnMutex;
2209
+ this.connection = connection;
2210
+ }
2211
+ /**
2212
+ * Returns this lease, allowing another client to use the database connection.
2213
+ */
2214
+ async returnLease() {
2215
+ await this.useMutex.runExclusive(async () => {
2216
+ if (!this.closed) {
2217
+ this.closed = true;
2218
+ this.returnMutex();
2219
+ }
2220
+ });
2221
+ }
2222
+ /**
2223
+ * This should only be used internally, since the callback must not use the raw connection after resolving.
2224
+ */
2225
+ async use(callback) {
2226
+ return await this.useMutex.runExclusive(async () => {
2227
+ if (this.closed) {
2228
+ throw new Error('lease token has already been closed');
2229
+ }
2230
+ return await callback(this.connection);
2231
+ });
2232
+ }
2233
+ }
2234
+
2235
+
2236
+ /***/ },
2237
+
2238
+ /***/ "./lib/src/db/adapters/wa-sqlite/DatabaseServer.js"
2239
+ /*!*********************************************************!*\
2240
+ !*** ./lib/src/db/adapters/wa-sqlite/DatabaseServer.js ***!
2241
+ \*********************************************************/
2242
+ (__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) {
2243
+
2244
+ __webpack_require__.r(__webpack_exports__);
2245
+ /* harmony export */ __webpack_require__.d(__webpack_exports__, {
2246
+ /* harmony export */ DatabaseServer: () => (/* binding */ DatabaseServer)
2247
+ /* harmony export */ });
2248
+ /**
2249
+ * Access to a WA-sqlite connection that can be shared with multiple clients sending queries over an RPC protocol built
2250
+ * with the Comlink package.
2251
+ */
2252
+ class DatabaseServer {
2253
+ #options;
2254
+ #nextClientId = 0;
2255
+ #activeClients = new Set();
2256
+ // TODO: Don't use a broadcast channel for connections managed by a shared worker.
2257
+ #updateBroadcastChannel;
2258
+ #clientTableListeners = new Set();
2259
+ constructor(options) {
2260
+ this.#options = options;
2261
+ const inner = options.inner;
2262
+ this.#updateBroadcastChannel = new BroadcastChannel(`${inner.options.dbFilename}-table-updates`);
2263
+ this.#updateBroadcastChannel.onmessage = ({ data }) => {
2264
+ this.#pushTableUpdateToClients(data);
2265
+ };
2266
+ }
2267
+ #pushTableUpdateToClients(changedTables) {
2268
+ for (const listener of this.#clientTableListeners) {
2269
+ listener.postMessage(changedTables);
2270
+ }
2271
+ }
2272
+ get #inner() {
2273
+ return this.#options.inner;
2274
+ }
2275
+ get #logger() {
2276
+ return this.#options.logger;
2277
+ }
2278
+ /**
2279
+ * Called by clients when they wish to connect to this database.
2280
+ *
2281
+ * @param lockName A lock that is currently held by the client. When the lock is returned, we know the client is gone
2282
+ * and that we need to clean up resources.
2283
+ */
2284
+ async connect(lockName) {
2285
+ let isOpen = true;
2286
+ const clientId = this.#nextClientId++;
2287
+ this.#activeClients.add(clientId);
2288
+ let connectionLeases = new Map();
2289
+ let currentTableListener;
2290
+ function requireOpen() {
2291
+ if (!isOpen) {
2292
+ throw new Error('Client has already been closed');
2293
+ }
2294
+ }
2295
+ function requireOpenAndLease(lease) {
2296
+ requireOpen();
2297
+ const token = connectionLeases.get(lease);
2298
+ if (!token) {
2299
+ throw new Error('Attempted to use a connection lease that has already been returned.');
2300
+ }
2301
+ return token;
2302
+ }
2303
+ const close = async () => {
2304
+ if (isOpen) {
2305
+ isOpen = false;
2306
+ if (currentTableListener) {
2307
+ this.#clientTableListeners.delete(currentTableListener);
2308
+ }
2309
+ // If the client holds a connection lease it hasn't returned, return that now.
2310
+ for (const { lease } of connectionLeases.values()) {
2311
+ this.#logger.debug(`Closing connection lease that hasn't been returned.`);
2312
+ await lease.returnLease();
2313
+ }
2314
+ this.#activeClients.delete(clientId);
2315
+ if (this.#activeClients.size == 0) {
2316
+ await this.forceClose();
2317
+ }
2318
+ else {
2319
+ this.#logger.debug('Keeping underlying connection active since its used by other clients.');
2320
+ }
2321
+ }
2322
+ };
2323
+ if (lockName) {
2324
+ navigator.locks.request(lockName, {}, () => {
2325
+ close();
2326
+ });
2327
+ }
2328
+ return {
2329
+ close,
2330
+ debugIsAutoCommit: async () => {
2331
+ return this.#inner.unsafeUseInner().isAutoCommit();
2332
+ },
2333
+ requestAccess: async (write, timeoutMs) => {
2334
+ requireOpen();
2335
+ // TODO: Support timeouts, they don't seem to be supported by the async-mutex package.
2336
+ const lease = await this.#inner.acquireConnection();
2337
+ if (!isOpen) {
2338
+ // Race between requestAccess and close(), the connection was closed while we tried to acquire a lease.
2339
+ await lease.returnLease();
2340
+ return requireOpen();
2341
+ }
2342
+ const token = crypto.randomUUID();
2343
+ connectionLeases.set(token, { lease, write });
2344
+ return token;
2345
+ },
2346
+ completeAccess: async (token) => {
2347
+ const lease = requireOpenAndLease(token);
2348
+ connectionLeases.delete(token);
2349
+ try {
2350
+ if (lease.write) {
2351
+ // Collect update hooks invoked while the client had the write connection.
2352
+ const { resultSet } = await lease.lease.use((conn) => conn.execute(`SELECT powersync_update_hooks('get')`));
2353
+ if (resultSet) {
2354
+ const updatedTables = JSON.parse(resultSet.rows[0][0]);
2355
+ if (updatedTables.length) {
2356
+ this.#updateBroadcastChannel.postMessage(updatedTables);
2357
+ this.#pushTableUpdateToClients(updatedTables);
2358
+ }
2359
+ }
2360
+ }
2361
+ }
2362
+ finally {
2363
+ await lease.lease.returnLease();
2364
+ }
2365
+ },
2366
+ execute: async (token, sql, params) => {
2367
+ const { lease } = requireOpenAndLease(token);
2368
+ return await lease.use((db) => db.execute(sql, params));
2369
+ },
2370
+ executeBatch: async (token, sql, params) => {
2371
+ const { lease } = requireOpenAndLease(token);
2372
+ return await lease.use((db) => db.executeBatch(sql, params));
2373
+ },
2374
+ setUpdateListener: async (listener) => {
2375
+ requireOpen();
2376
+ if (currentTableListener) {
2377
+ this.#clientTableListeners.delete(currentTableListener);
2378
+ }
2379
+ currentTableListener = listener;
2380
+ if (listener) {
2381
+ this.#clientTableListeners.add(listener);
2382
+ }
2383
+ }
2384
+ };
2385
+ }
2386
+ async forceClose() {
2387
+ this.#logger.debug(`Closing connection to ${this.#inner.options}.`);
2388
+ const connection = this.#inner;
2389
+ this.#options.onClose();
2390
+ this.#updateBroadcastChannel.close();
2391
+ await connection.close();
2392
+ }
2393
+ }
2394
+
2395
+
2396
+ /***/ },
2397
+
2398
+ /***/ "./lib/src/db/adapters/wa-sqlite/RawSqliteConnection.js"
2399
+ /*!**************************************************************!*\
2400
+ !*** ./lib/src/db/adapters/wa-sqlite/RawSqliteConnection.js ***!
2401
+ \**************************************************************/
2402
+ (__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) {
2403
+
2404
+ __webpack_require__.r(__webpack_exports__);
2405
+ /* harmony export */ __webpack_require__.d(__webpack_exports__, {
2406
+ /* harmony export */ RawSqliteConnection: () => (/* binding */ RawSqliteConnection)
2407
+ /* harmony export */ });
2408
+ /* harmony import */ var _journeyapps_wa_sqlite__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @journeyapps/wa-sqlite */ "../../node_modules/.pnpm/@journeyapps+wa-sqlite@1.5.0/node_modules/@journeyapps/wa-sqlite/src/sqlite-api.js");
2409
+ /* harmony import */ var _vfs_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./vfs.js */ "./lib/src/db/adapters/wa-sqlite/vfs.js");
2410
+
2411
+
2412
+ /**
2413
+ * A small wrapper around WA-sqlite to help with opening databases and running statements by preparing them internally.
2414
+ *
2415
+ * This is an internal class, and it must never be used directly. Wrappers are required to ensure raw connections aren't
2416
+ * used concurrently across tabs.
2417
+ */
2418
+ class RawSqliteConnection {
2419
+ options;
2420
+ _sqliteAPI = null;
2421
+ /**
2422
+ * The `sqlite3*` connection pointer.
2423
+ */
2424
+ db = 0;
2425
+ _moduleFactory;
2426
+ constructor(options) {
2427
+ this.options = options;
2428
+ this._moduleFactory = _vfs_js__WEBPACK_IMPORTED_MODULE_1__.DEFAULT_MODULE_FACTORIES[this.options.vfs];
2429
+ }
2430
+ get isOpen() {
2431
+ return this.db != 0;
2432
+ }
2433
+ async init() {
2434
+ const api = (this._sqliteAPI = await this.openSQLiteAPI());
2435
+ this.db = await api.open_v2(this.options.dbFilename);
2436
+ await this.executeRaw(`PRAGMA temp_store = ${this.options.temporaryStorage};`);
2437
+ if (this.options.encryptionKey) {
2438
+ const escapedKey = this.options.encryptionKey.replace("'", "''");
2439
+ await this.executeRaw(`PRAGMA key = '${escapedKey}'`);
2440
+ }
2441
+ await this.executeRaw(`PRAGMA cache_size = -${this.options.cacheSizeKb};`);
2442
+ await this.executeRaw(`SELECT powersync_update_hooks('install');`);
2443
+ }
2444
+ async openSQLiteAPI() {
2445
+ const { module, vfs } = await this._moduleFactory({
2446
+ dbFileName: this.options.dbFilename,
2447
+ encryptionKey: this.options.encryptionKey
2448
+ });
2449
+ const sqlite3 = (0,_journeyapps_wa_sqlite__WEBPACK_IMPORTED_MODULE_0__.Factory)(module);
2450
+ sqlite3.vfs_register(vfs, true);
2451
+ /**
2452
+ * Register the PowerSync core SQLite extension
2453
+ */
2454
+ module.ccall('powersync_init_static', 'int', []);
2455
+ /**
2456
+ * Create the multiple cipher vfs if an encryption key is provided
2457
+ */
2458
+ if (this.options.encryptionKey) {
2459
+ const createResult = module.ccall('sqlite3mc_vfs_create', 'int', ['string', 'int'], [this.options.dbFilename, 1]);
2460
+ if (createResult !== 0) {
2461
+ throw new Error('Failed to create multiple cipher vfs, Database encryption will not work');
2462
+ }
2463
+ }
2464
+ return sqlite3;
2465
+ }
2466
+ requireSqlite() {
2467
+ if (!this._sqliteAPI) {
2468
+ throw new Error(`Initialization has not completed`);
2469
+ }
2470
+ return this._sqliteAPI;
2471
+ }
2472
+ /**
2473
+ * Checks if the database connection is in autocommit mode.
2474
+ * @returns true if in autocommit mode, false if in a transaction
2475
+ */
2476
+ isAutoCommit() {
2477
+ return this.requireSqlite().get_autocommit(this.db) != 0;
2478
+ }
2479
+ async execute(sql, bindings) {
2480
+ const resultSet = await this.executeSingleStatementRaw(sql, bindings);
2481
+ return this.wrapQueryResults(this.requireSqlite(), resultSet);
2482
+ }
2483
+ async executeBatch(sql, bindings) {
2484
+ const results = [];
2485
+ const api = this.requireSqlite();
2486
+ for await (const stmt of api.statements(this.db, sql)) {
2487
+ let columns;
2488
+ for (const parameterSet of bindings) {
2489
+ const rs = await this.stepThroughStatement(api, stmt, parameterSet, columns, false);
2490
+ results.push(this.wrapQueryResults(api, rs));
2491
+ }
2492
+ // executeBatch can only use a single statement
2493
+ break;
2494
+ }
2495
+ return results;
2496
+ }
2497
+ wrapQueryResults(api, rs) {
2498
+ return {
2499
+ changes: api.changes(this.db),
2500
+ lastInsertRowId: api.last_insert_id(this.db),
2501
+ autocommit: api.get_autocommit(this.db) != 0,
2502
+ resultSet: rs
2503
+ };
2504
+ }
2505
+ /**
2506
+ * This executes a single statement using SQLite3 and returns the results as a {@link RawResultSet}.
2507
+ */
2508
+ async executeSingleStatementRaw(sql, bindings) {
2509
+ const results = await this.executeRaw(sql, bindings);
2510
+ return results.length ? results[0] : undefined;
2511
+ }
2512
+ async executeRaw(sql, bindings) {
2513
+ const results = [];
2514
+ const api = this.requireSqlite();
2515
+ for await (const stmt of api.statements(this.db, sql)) {
2516
+ let columns;
2517
+ const rs = await this.stepThroughStatement(api, stmt, bindings ?? [], columns);
2518
+ columns = rs.columns;
2519
+ if (columns.length) {
2520
+ results.push(rs);
2521
+ }
2522
+ // When binding parameters, only a single statement is executed.
2523
+ if (bindings) {
2524
+ break;
2525
+ }
2526
+ }
2527
+ return results;
2528
+ }
2529
+ async stepThroughStatement(api, stmt, bindings, knownColumns, includeResults = true) {
2530
+ // TODO not sure why this is needed currently, but booleans break
2531
+ bindings.forEach((b, index, arr) => {
2532
+ if (typeof b == 'boolean') {
2533
+ arr[index] = b ? 1 : 0;
2534
+ }
2535
+ });
2536
+ api.reset(stmt);
2537
+ if (bindings) {
2538
+ api.bind_collection(stmt, bindings);
2539
+ }
2540
+ const rows = [];
2541
+ while ((await api.step(stmt)) === _journeyapps_wa_sqlite__WEBPACK_IMPORTED_MODULE_0__.SQLITE_ROW) {
2542
+ if (includeResults) {
2543
+ const row = api.row(stmt);
2544
+ rows.push(row);
2545
+ }
2546
+ }
2547
+ knownColumns ??= api.column_names(stmt);
2548
+ return { columns: knownColumns, rows };
2549
+ }
2550
+ async close() {
2551
+ if (this.isOpen) {
2552
+ await this.requireSqlite().close(this.db);
2553
+ this.db = 0;
2554
+ }
2555
+ }
2556
+ }
2557
+
2558
+
2559
+ /***/ },
2560
+
2561
+ /***/ "./lib/src/db/adapters/wa-sqlite/vfs.js"
2562
+ /*!**********************************************!*\
2563
+ !*** ./lib/src/db/adapters/wa-sqlite/vfs.js ***!
2564
+ \**********************************************/
2416
2565
  (__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) {
2417
2566
 
2418
2567
  __webpack_require__.r(__webpack_exports__);
@@ -2423,14 +2572,8 @@ __webpack_require__.r(__webpack_exports__);
2423
2572
  /* harmony export */ MultiCipherSyncWASQLiteModuleFactory: () => (/* binding */ MultiCipherSyncWASQLiteModuleFactory),
2424
2573
  /* harmony export */ SyncWASQLiteModuleFactory: () => (/* binding */ SyncWASQLiteModuleFactory),
2425
2574
  /* harmony export */ WASQLiteVFS: () => (/* binding */ WASQLiteVFS),
2426
- /* harmony export */ WASqliteConnection: () => (/* binding */ WASqliteConnection)
2575
+ /* harmony export */ vfsRequiresDedicatedWorkers: () => (/* binding */ vfsRequiresDedicatedWorkers)
2427
2576
  /* harmony export */ });
2428
- /* harmony import */ var _journeyapps_wa_sqlite__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @journeyapps/wa-sqlite */ "../../node_modules/.pnpm/@journeyapps+wa-sqlite@1.5.0/node_modules/@journeyapps/wa-sqlite/src/sqlite-api.js");
2429
- /* harmony import */ var _powersync_common__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @powersync/common */ "../common/dist/bundle.mjs");
2430
- /* harmony import */ var async_mutex__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! async-mutex */ "../../node_modules/.pnpm/async-mutex@0.5.0/node_modules/async-mutex/index.mjs");
2431
-
2432
-
2433
-
2434
2577
  /**
2435
2578
  * List of currently tested virtual filesystems
2436
2579
  */
@@ -2440,6 +2583,9 @@ var WASQLiteVFS;
2440
2583
  WASQLiteVFS["OPFSCoopSyncVFS"] = "OPFSCoopSyncVFS";
2441
2584
  WASQLiteVFS["AccessHandlePoolVFS"] = "AccessHandlePoolVFS";
2442
2585
  })(WASQLiteVFS || (WASQLiteVFS = {}));
2586
+ function vfsRequiresDedicatedWorkers(vfs) {
2587
+ return vfs != WASQLiteVFS.IDBBatchAtomicVFS;
2588
+ }
2443
2589
  /**
2444
2590
  * @internal
2445
2591
  */
@@ -2519,316 +2665,6 @@ const DEFAULT_MODULE_FACTORIES = {
2519
2665
  };
2520
2666
  }
2521
2667
  };
2522
- /**
2523
- * @internal
2524
- * WA-SQLite connection which directly interfaces with WA-SQLite.
2525
- * This is usually instantiated inside a worker.
2526
- */
2527
- class WASqliteConnection extends _powersync_common__WEBPACK_IMPORTED_MODULE_1__.BaseObserver {
2528
- options;
2529
- _sqliteAPI = null;
2530
- _dbP = null;
2531
- _moduleFactory;
2532
- updatedTables;
2533
- updateTimer;
2534
- statementMutex;
2535
- broadcastChannel;
2536
- /**
2537
- * Unique id for this specific connection. This is used to prevent broadcast table change
2538
- * notification loops.
2539
- */
2540
- connectionId;
2541
- _holdCounter;
2542
- _holdId;
2543
- constructor(options) {
2544
- super();
2545
- this.options = options;
2546
- this.updatedTables = new Set();
2547
- this.updateTimer = null;
2548
- this.broadcastChannel = null;
2549
- this.connectionId = new Date().valueOf() + Math.random();
2550
- this.statementMutex = new async_mutex__WEBPACK_IMPORTED_MODULE_2__.Mutex();
2551
- this._moduleFactory = DEFAULT_MODULE_FACTORIES[this.options.vfs];
2552
- this._holdCounter = 0;
2553
- this._holdId = null;
2554
- }
2555
- /**
2556
- * Gets the id for the current hold.
2557
- * This can be used to check for invalid states.
2558
- */
2559
- get currentHoldId() {
2560
- return this._holdId;
2561
- }
2562
- get sqliteAPI() {
2563
- if (!this._sqliteAPI) {
2564
- throw new Error(`Initialization has not completed`);
2565
- }
2566
- return this._sqliteAPI;
2567
- }
2568
- get dbP() {
2569
- if (!this._dbP) {
2570
- throw new Error(`Initialization has not completed`);
2571
- }
2572
- return this._dbP;
2573
- }
2574
- /**
2575
- * Checks if the database connection is in autocommit mode.
2576
- * @returns true if in autocommit mode, false if in a transaction
2577
- */
2578
- async isAutoCommit() {
2579
- return this.sqliteAPI.get_autocommit(this.dbP) != 0;
2580
- }
2581
- async markHold() {
2582
- const previousHoldId = this._holdId;
2583
- this._holdId = `${++this._holdCounter}`;
2584
- if (previousHoldId) {
2585
- await this.iterateAsyncListeners(async (cb) => cb.holdOverwritten?.(previousHoldId));
2586
- }
2587
- return this._holdId;
2588
- }
2589
- async releaseHold(holdId) {
2590
- if (holdId != this._holdId) {
2591
- throw new Error(`Invalid hold state, expected ${this._holdId} but got ${holdId}`);
2592
- }
2593
- this._holdId = null;
2594
- }
2595
- async openDB() {
2596
- this._dbP = await this.sqliteAPI.open_v2(this.options.dbFilename);
2597
- return this._dbP;
2598
- }
2599
- async executeEncryptionPragma() {
2600
- if (this.options.encryptionKey) {
2601
- await this.executeSingleStatement(`PRAGMA key = "${this.options.encryptionKey}"`);
2602
- }
2603
- return;
2604
- }
2605
- async openSQLiteAPI() {
2606
- const { module, vfs } = await this._moduleFactory({
2607
- dbFileName: this.options.dbFilename,
2608
- encryptionKey: this.options.encryptionKey
2609
- });
2610
- const sqlite3 = _journeyapps_wa_sqlite__WEBPACK_IMPORTED_MODULE_0__.Factory(module);
2611
- sqlite3.vfs_register(vfs, true);
2612
- /**
2613
- * Register the PowerSync core SQLite extension
2614
- */
2615
- module.ccall('powersync_init_static', 'int', []);
2616
- /**
2617
- * Create the multiple cipher vfs if an encryption key is provided
2618
- */
2619
- if (this.options.encryptionKey) {
2620
- const createResult = module.ccall('sqlite3mc_vfs_create', 'int', ['string', 'int'], [this.options.dbFilename, 1]);
2621
- if (createResult !== 0) {
2622
- throw new Error('Failed to create multiple cipher vfs, Database encryption will not work');
2623
- }
2624
- }
2625
- return sqlite3;
2626
- }
2627
- registerBroadcastListeners() {
2628
- this.broadcastChannel = new BroadcastChannel(`${this.options.dbFilename}-table-updates`);
2629
- this.broadcastChannel.addEventListener('message', (event) => {
2630
- const data = event.data;
2631
- if (this.connectionId == data.connectionId) {
2632
- // Ignore messages from the same connection
2633
- return;
2634
- }
2635
- // Ensuring that we don't rebroadcast the same message
2636
- this.queueTableUpdate(data.changedTables, false);
2637
- });
2638
- }
2639
- queueTableUpdate(tableNames, shouldBroadcast = true) {
2640
- tableNames.forEach((tableName) => this.updatedTables.add(tableName));
2641
- if (this.updateTimer == null) {
2642
- this.updateTimer = setTimeout(() => this.fireUpdates(shouldBroadcast), 0);
2643
- }
2644
- }
2645
- async init() {
2646
- this._sqliteAPI = await this.openSQLiteAPI();
2647
- await this.openDB();
2648
- this.registerBroadcastListeners();
2649
- await this.executeSingleStatement(`PRAGMA temp_store = ${this.options.temporaryStorage};`);
2650
- await this.executeEncryptionPragma();
2651
- await this.executeSingleStatement(`PRAGMA cache_size = -${this.options.cacheSizeKb};`);
2652
- this.sqliteAPI.update_hook(this.dbP, (updateType, dbName, tableName) => {
2653
- if (!tableName) {
2654
- return;
2655
- }
2656
- const changedTables = new Set([tableName]);
2657
- this.queueTableUpdate(changedTables);
2658
- });
2659
- }
2660
- async getConfig() {
2661
- return this.options;
2662
- }
2663
- fireUpdates(shouldBroadcast = true) {
2664
- this.updateTimer = null;
2665
- const event = { tables: [...this.updatedTables], groupedUpdates: {}, rawUpdates: [] };
2666
- // Share to other connections
2667
- if (shouldBroadcast) {
2668
- this.broadcastChannel.postMessage({
2669
- changedTables: this.updatedTables,
2670
- connectionId: this.connectionId
2671
- });
2672
- }
2673
- this.updatedTables.clear();
2674
- this.iterateListeners((cb) => cb.tablesUpdated?.(event));
2675
- }
2676
- /**
2677
- * This executes SQL statements in a batch.
2678
- */
2679
- async executeBatch(sql, bindings) {
2680
- return this.acquireExecuteLock(async () => {
2681
- let affectedRows = 0;
2682
- try {
2683
- await this.executeSingleStatement('BEGIN TRANSACTION');
2684
- const wrappedBindings = bindings ? bindings : [];
2685
- for await (const stmt of this.sqliteAPI.statements(this.dbP, sql)) {
2686
- if (stmt === null) {
2687
- return {
2688
- rowsAffected: 0,
2689
- rows: { _array: [], length: 0 }
2690
- };
2691
- }
2692
- //Prepare statement once
2693
- for (const binding of wrappedBindings) {
2694
- // TODO not sure why this is needed currently, but booleans break
2695
- for (let i = 0; i < binding.length; i++) {
2696
- const b = binding[i];
2697
- if (typeof b == 'boolean') {
2698
- binding[i] = b ? 1 : 0;
2699
- }
2700
- }
2701
- if (bindings) {
2702
- this.sqliteAPI.bind_collection(stmt, binding);
2703
- }
2704
- const result = await this.sqliteAPI.step(stmt);
2705
- if (result === _journeyapps_wa_sqlite__WEBPACK_IMPORTED_MODULE_0__.SQLITE_DONE) {
2706
- //The value returned by sqlite3_changes() immediately after an INSERT, UPDATE or DELETE statement run on a view is always zero.
2707
- affectedRows += this.sqliteAPI.changes(this.dbP);
2708
- }
2709
- this.sqliteAPI.reset(stmt);
2710
- }
2711
- }
2712
- await this.executeSingleStatement('COMMIT');
2713
- }
2714
- catch (err) {
2715
- await this.executeSingleStatement('ROLLBACK');
2716
- return {
2717
- rowsAffected: 0,
2718
- rows: { _array: [], length: 0 }
2719
- };
2720
- }
2721
- const result = {
2722
- rowsAffected: affectedRows,
2723
- rows: { _array: [], length: 0 }
2724
- };
2725
- return result;
2726
- });
2727
- }
2728
- /**
2729
- * This executes single SQL statements inside a requested lock.
2730
- */
2731
- async execute(sql, bindings) {
2732
- // Running multiple statements on the same connection concurrently should not be allowed
2733
- return this.acquireExecuteLock(async () => {
2734
- return this.executeSingleStatement(sql, bindings);
2735
- });
2736
- }
2737
- async executeRaw(sql, bindings) {
2738
- return this.acquireExecuteLock(async () => {
2739
- return this.executeSingleStatementRaw(sql, bindings);
2740
- });
2741
- }
2742
- async close() {
2743
- this.broadcastChannel?.close();
2744
- await this.acquireExecuteLock(async () => {
2745
- /**
2746
- * Running the close operation inside the same execute mutex prevents errors like:
2747
- * ```
2748
- * unable to close due to unfinalized statements or unfinished backups
2749
- * ```
2750
- */
2751
- await this.sqliteAPI.close(this.dbP);
2752
- });
2753
- }
2754
- async registerOnTableChange(callback) {
2755
- return this.registerListener({
2756
- tablesUpdated: (event) => callback(event)
2757
- });
2758
- }
2759
- /**
2760
- * This requests a lock for executing statements.
2761
- * Should only be used internally.
2762
- */
2763
- acquireExecuteLock = (callback) => {
2764
- return this.statementMutex.runExclusive(callback);
2765
- };
2766
- /**
2767
- * This executes a single statement using SQLite3.
2768
- */
2769
- async executeSingleStatement(sql, bindings) {
2770
- const results = await this._execute(sql, bindings);
2771
- const rows = [];
2772
- for (const resultSet of results) {
2773
- for (const row of resultSet.rows) {
2774
- const outRow = {};
2775
- resultSet.columns.forEach((key, index) => {
2776
- outRow[key] = row[index];
2777
- });
2778
- rows.push(outRow);
2779
- }
2780
- }
2781
- const result = {
2782
- insertId: this.sqliteAPI.last_insert_id(this.dbP),
2783
- rowsAffected: this.sqliteAPI.changes(this.dbP),
2784
- rows: {
2785
- _array: rows,
2786
- length: rows.length
2787
- }
2788
- };
2789
- return result;
2790
- }
2791
- /**
2792
- * This executes a single statement using SQLite3 and returns the results as an array of arrays.
2793
- */
2794
- async executeSingleStatementRaw(sql, bindings) {
2795
- const results = await this._execute(sql, bindings);
2796
- return results.flatMap((resultset) => resultset.rows.map((row) => resultset.columns.map((_, index) => row[index])));
2797
- }
2798
- async _execute(sql, bindings) {
2799
- const results = [];
2800
- for await (const stmt of this.sqliteAPI.statements(this.dbP, sql)) {
2801
- let columns;
2802
- const wrappedBindings = bindings ? [bindings] : [[]];
2803
- for (const binding of wrappedBindings) {
2804
- // TODO not sure why this is needed currently, but booleans break
2805
- binding.forEach((b, index, arr) => {
2806
- if (typeof b == 'boolean') {
2807
- arr[index] = b ? 1 : 0;
2808
- }
2809
- });
2810
- this.sqliteAPI.reset(stmt);
2811
- if (bindings) {
2812
- this.sqliteAPI.bind_collection(stmt, binding);
2813
- }
2814
- const rows = [];
2815
- while ((await this.sqliteAPI.step(stmt)) === _journeyapps_wa_sqlite__WEBPACK_IMPORTED_MODULE_0__.SQLITE_ROW) {
2816
- const row = this.sqliteAPI.row(stmt);
2817
- rows.push(row);
2818
- }
2819
- columns = columns ?? this.sqliteAPI.column_names(stmt);
2820
- if (columns.length) {
2821
- results.push({ columns, rows });
2822
- }
2823
- }
2824
- // When binding parameters, only a single statement is executed.
2825
- if (bindings) {
2826
- break;
2827
- }
2828
- }
2829
- return results;
2830
- }
2831
- }
2832
2668
 
2833
2669
 
2834
2670
  /***/ },
@@ -2853,134 +2689,108 @@ const getNavigatorLocks = () => {
2853
2689
 
2854
2690
  /***/ },
2855
2691
 
2856
- /***/ "./lib/src/worker/db/SharedWASQLiteConnection.js"
2857
- /*!*******************************************************!*\
2858
- !*** ./lib/src/worker/db/SharedWASQLiteConnection.js ***!
2859
- \*******************************************************/
2692
+ /***/ "./lib/src/worker/db/MultiDatabaseServer.js"
2693
+ /*!**************************************************!*\
2694
+ !*** ./lib/src/worker/db/MultiDatabaseServer.js ***!
2695
+ \**************************************************/
2860
2696
  (__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) {
2861
2697
 
2862
2698
  __webpack_require__.r(__webpack_exports__);
2863
2699
  /* harmony export */ __webpack_require__.d(__webpack_exports__, {
2864
- /* harmony export */ SharedWASQLiteConnection: () => (/* binding */ SharedWASQLiteConnection)
2700
+ /* harmony export */ MultiDatabaseServer: () => (/* binding */ MultiDatabaseServer),
2701
+ /* harmony export */ isSharedWorker: () => (/* binding */ isSharedWorker)
2865
2702
  /* harmony export */ });
2866
- class SharedWASQLiteConnection {
2867
- options;
2868
- isClosing;
2869
- // Keeps track if this current hold if the shared connection has a hold
2870
- activeHoldId;
2871
- constructor(options) {
2872
- this.options = options;
2873
- // Add this client ID to the set of known clients
2874
- this.clientIds.add(options.clientId);
2875
- this.isClosing = false;
2876
- this.activeHoldId = null;
2877
- }
2878
- get logger() {
2879
- return this.options.logger;
2880
- }
2881
- get dbEntry() {
2882
- return this.options.dbMap.get(this.options.dbFilename);
2883
- }
2884
- get connection() {
2885
- return this.dbEntry.db;
2886
- }
2887
- get clientIds() {
2888
- return this.dbEntry.clientIds;
2889
- }
2890
- async init() {
2891
- // No-op since the connection is already initialized when it was created
2892
- }
2893
- async markHold() {
2894
- this.activeHoldId = await this.connection.markHold();
2895
- return this.activeHoldId;
2896
- }
2897
- async releaseHold(id) {
2898
- try {
2899
- await this.connection.releaseHold(id);
2900
- }
2901
- finally {
2902
- this.activeHoldId = null;
2903
- }
2904
- }
2905
- async isAutoCommit() {
2906
- return this.connection.isAutoCommit();
2907
- }
2908
- /**
2909
- * Handles closing of a shared connection.
2910
- * The connection is only closed if there are no active clients using it.
2911
- */
2912
- async close() {
2913
- // This prevents further statements on this connection from being executed
2914
- this.isClosing = true;
2915
- const { clientIds, logger } = this;
2916
- const { clientId, dbFilename, dbMap } = this.options;
2917
- logger.debug(`Close requested from client ${clientId} of ${[...clientIds]}`);
2918
- clientIds.delete(clientId);
2919
- if (this.activeHoldId) {
2920
- // We can't cleanup here since we're not in a lock context.
2921
- // The cleanup will occur once a new hold is acquired.
2922
- this.logger.info(`Hold ${this.activeHoldId} was still active when the connection was closed. Cleanup will occur once a new hold is acquired.`);
2923
- }
2924
- if (clientIds.size == 0) {
2925
- logger.debug(`Closing connection to ${this.options}.`);
2926
- const connection = this.connection;
2927
- dbMap.delete(dbFilename);
2928
- await connection.close();
2929
- return;
2930
- }
2931
- logger.debug(`Connection to ${dbFilename} not closed yet due to active clients.`);
2932
- return;
2933
- }
2934
- async withClosing(action) {
2935
- if (this.isClosing) {
2936
- throw new Error('Connection is closing');
2937
- }
2938
- return action();
2939
- }
2940
- async execute(sql, params) {
2941
- return this.withClosing(() => this.connection.execute(sql, params));
2942
- }
2943
- async executeRaw(sql, params) {
2944
- return this.withClosing(() => this.connection.executeRaw(sql, params));
2945
- }
2946
- executeBatch(sql, params) {
2947
- return this.withClosing(() => this.connection.executeBatch(sql, params));
2948
- }
2949
- registerOnTableChange(callback) {
2950
- return this.connection.registerOnTableChange(callback);
2951
- }
2952
- getConfig() {
2953
- return this.connection.getConfig();
2954
- }
2955
- }
2956
-
2703
+ /* harmony import */ var comlink__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! comlink */ "../../node_modules/.pnpm/comlink@4.4.2/node_modules/comlink/dist/esm/comlink.mjs");
2704
+ /* harmony import */ var _db_adapters_wa_sqlite_DatabaseServer_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../db/adapters/wa-sqlite/DatabaseServer.js */ "./lib/src/db/adapters/wa-sqlite/DatabaseServer.js");
2705
+ /* harmony import */ var _shared_navigator_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../shared/navigator.js */ "./lib/src/shared/navigator.js");
2706
+ /* harmony import */ var _db_adapters_wa_sqlite_RawSqliteConnection_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../../db/adapters/wa-sqlite/RawSqliteConnection.js */ "./lib/src/db/adapters/wa-sqlite/RawSqliteConnection.js");
2707
+ /* harmony import */ var _db_adapters_wa_sqlite_ConcurrentConnection_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../../db/adapters/wa-sqlite/ConcurrentConnection.js */ "./lib/src/db/adapters/wa-sqlite/ConcurrentConnection.js");
2957
2708
 
2958
- /***/ },
2959
2709
 
2960
- /***/ "./lib/src/worker/db/WorkerWASQLiteConnection.js"
2961
- /*!*******************************************************!*\
2962
- !*** ./lib/src/worker/db/WorkerWASQLiteConnection.js ***!
2963
- \*******************************************************/
2964
- (__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) {
2965
2710
 
2966
- __webpack_require__.r(__webpack_exports__);
2967
- /* harmony export */ __webpack_require__.d(__webpack_exports__, {
2968
- /* harmony export */ WorkerWASQLiteConnection: () => (/* binding */ WorkerWASQLiteConnection)
2969
- /* harmony export */ });
2970
- /* harmony import */ var comlink__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! comlink */ "../../node_modules/.pnpm/comlink@4.4.2/node_modules/comlink/dist/esm/comlink.mjs");
2971
- /* harmony import */ var _db_adapters_wa_sqlite_WASQLiteConnection_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../db/adapters/wa-sqlite/WASQLiteConnection.js */ "./lib/src/db/adapters/wa-sqlite/WASQLiteConnection.js");
2972
2711
 
2973
2712
 
2713
+ const OPEN_DB_LOCK = 'open-wasqlite-db';
2974
2714
  /**
2975
- * A Small proxy wrapper around the WASqliteConnection.
2976
- * This ensures that certain return types are properly proxied.
2715
+ * Shared state to manage multiple database connections hosted by a worker.
2977
2716
  */
2978
- class WorkerWASQLiteConnection extends _db_adapters_wa_sqlite_WASQLiteConnection_js__WEBPACK_IMPORTED_MODULE_1__.WASqliteConnection {
2979
- async registerOnTableChange(callback) {
2980
- // Proxy the callback remove function
2981
- return comlink__WEBPACK_IMPORTED_MODULE_0__.proxy(await super.registerOnTableChange(callback));
2717
+ class MultiDatabaseServer {
2718
+ logger;
2719
+ activeDatabases = new Map();
2720
+ constructor(logger) {
2721
+ this.logger = logger;
2722
+ }
2723
+ async handleConnection(options) {
2724
+ this.logger.setLevel(options.logLevel);
2725
+ return comlink__WEBPACK_IMPORTED_MODULE_0__.proxy(await this.openConnectionLocally(options, options.lockName));
2726
+ }
2727
+ async connectToExisting(name, lockName) {
2728
+ return (0,_shared_navigator_js__WEBPACK_IMPORTED_MODULE_2__.getNavigatorLocks)().request(OPEN_DB_LOCK, async () => {
2729
+ const server = this.activeDatabases.get(name);
2730
+ if (server == null) {
2731
+ throw new Error(`connectToExisting(${name}) failed because the worker doesn't own a database with that name.`);
2732
+ }
2733
+ return comlink__WEBPACK_IMPORTED_MODULE_0__.proxy(await server.connect(lockName));
2734
+ });
2735
+ }
2736
+ async openConnectionLocally(options, lockName) {
2737
+ // Especially on Firefox, we're sometimes seeing "NoModificationAllowedError"s when opening OPFS databases we can
2738
+ // work around by retrying.
2739
+ const maxAttempts = 3;
2740
+ let server;
2741
+ for (let count = 0; count < maxAttempts - 1; count++) {
2742
+ try {
2743
+ server = await this.databaseOpenAttempt(options);
2744
+ }
2745
+ catch (ex) {
2746
+ this.logger.warn(`Attempt ${count + 1} of ${maxAttempts} to open database failed, retrying in 1 second...`, ex);
2747
+ await new Promise((resolve) => setTimeout(resolve, 1000));
2748
+ }
2749
+ }
2750
+ // Final attempt if we haven't been able to open the server - rethrow errors if we still can't open.
2751
+ server ??= await this.databaseOpenAttempt(options);
2752
+ return server.connect(lockName);
2753
+ }
2754
+ async databaseOpenAttempt(options) {
2755
+ return (0,_shared_navigator_js__WEBPACK_IMPORTED_MODULE_2__.getNavigatorLocks)().request(OPEN_DB_LOCK, async () => {
2756
+ const { dbFilename } = options;
2757
+ let server = this.activeDatabases.get(dbFilename);
2758
+ if (server == null) {
2759
+ const needsNavigatorLocks = !isSharedWorker;
2760
+ const connection = new _db_adapters_wa_sqlite_RawSqliteConnection_js__WEBPACK_IMPORTED_MODULE_3__.RawSqliteConnection(options);
2761
+ const withSafeConcurrency = new _db_adapters_wa_sqlite_ConcurrentConnection_js__WEBPACK_IMPORTED_MODULE_4__.ConcurrentSqliteConnection(connection, needsNavigatorLocks);
2762
+ // Initializing the RawSqliteConnection will run some pragmas that might write to the database file, so we want
2763
+ // to do that in an exclusive lock. Note that OPEN_DB_LOCK is not enough for that, as another tab might have
2764
+ // already created a connection (and is thus outside of OPEN_DB_LOCK) while currently writing to it.
2765
+ const returnLease = await withSafeConcurrency.acquireMutex();
2766
+ try {
2767
+ await connection.init();
2768
+ }
2769
+ catch (e) {
2770
+ returnLease();
2771
+ await connection.close();
2772
+ throw e;
2773
+ }
2774
+ returnLease();
2775
+ const onClose = () => this.activeDatabases.delete(dbFilename);
2776
+ server = new _db_adapters_wa_sqlite_DatabaseServer_js__WEBPACK_IMPORTED_MODULE_1__.DatabaseServer({
2777
+ inner: withSafeConcurrency,
2778
+ logger: this.logger,
2779
+ onClose
2780
+ });
2781
+ this.activeDatabases.set(dbFilename, server);
2782
+ }
2783
+ return server;
2784
+ });
2785
+ }
2786
+ closeAll() {
2787
+ const existingDatabases = [...this.activeDatabases.values()];
2788
+ return Promise.all(existingDatabases.map((db) => {
2789
+ db.forceClose();
2790
+ }));
2982
2791
  }
2983
2792
  }
2793
+ const isSharedWorker = 'SharedWorkerGlobalScope' in globalThis;
2984
2794
 
2985
2795
 
2986
2796
  /***/ },
@@ -3052,6 +2862,7 @@ __webpack_require__.r(__webpack_exports__);
3052
2862
  /* harmony export */ MAX_AMOUNT_OF_COLUMNS: () => (/* binding */ MAX_AMOUNT_OF_COLUMNS),
3053
2863
  /* harmony export */ MAX_OP_ID: () => (/* binding */ MAX_OP_ID),
3054
2864
  /* harmony export */ MEMORY_TRIGGER_CLAIM_MANAGER: () => (/* binding */ MEMORY_TRIGGER_CLAIM_MANAGER),
2865
+ /* harmony export */ Mutex: () => (/* binding */ Mutex),
3055
2866
  /* harmony export */ OnChangeQueryProcessor: () => (/* binding */ OnChangeQueryProcessor),
3056
2867
  /* harmony export */ OpType: () => (/* binding */ OpType),
3057
2868
  /* harmony export */ OpTypeEnum: () => (/* binding */ OpTypeEnum),
@@ -3093,15 +2904,12 @@ __webpack_require__.r(__webpack_exports__);
3093
2904
  /* harmony export */ isStreamingSyncCheckpointPartiallyComplete: () => (/* binding */ isStreamingSyncCheckpointPartiallyComplete),
3094
2905
  /* harmony export */ isStreamingSyncData: () => (/* binding */ isStreamingSyncData),
3095
2906
  /* harmony export */ isSyncNewCheckpointRequest: () => (/* binding */ isSyncNewCheckpointRequest),
3096
- /* harmony export */ mutexRunExclusive: () => (/* binding */ mutexRunExclusive),
3097
2907
  /* harmony export */ parseQuery: () => (/* binding */ parseQuery),
3098
2908
  /* harmony export */ runOnSchemaChange: () => (/* binding */ runOnSchemaChange),
3099
2909
  /* harmony export */ sanitizeSQL: () => (/* binding */ sanitizeSQL),
3100
- /* harmony export */ sanitizeUUID: () => (/* binding */ sanitizeUUID)
2910
+ /* harmony export */ sanitizeUUID: () => (/* binding */ sanitizeUUID),
2911
+ /* harmony export */ timeoutSignal: () => (/* binding */ timeoutSignal)
3101
2912
  /* harmony export */ });
3102
- /* harmony import */ var async_mutex__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! async-mutex */ "../../node_modules/.pnpm/async-mutex@0.5.0/node_modules/async-mutex/index.mjs");
3103
-
3104
-
3105
2913
  // https://www.sqlite.org/lang_expr.html#castexpr
3106
2914
  var ColumnType;
3107
2915
  (function (ColumnType) {
@@ -3759,7 +3567,7 @@ class SyncingService {
3759
3567
  updatedAttachments.push(downloaded);
3760
3568
  break;
3761
3569
  case AttachmentState.QUEUED_DELETE:
3762
- const deleted = await this.deleteAttachment(attachment);
3570
+ const deleted = await this.deleteAttachment(attachment, context);
3763
3571
  updatedAttachments.push(deleted);
3764
3572
  break;
3765
3573
  }
@@ -3837,17 +3645,16 @@ class SyncingService {
3837
3645
  * On failure, defers to error handler or archives.
3838
3646
  *
3839
3647
  * @param attachment - The attachment record to delete
3648
+ * @param context - Attachment context for database operations
3840
3649
  * @returns Updated attachment record
3841
3650
  */
3842
- async deleteAttachment(attachment) {
3651
+ async deleteAttachment(attachment, context) {
3843
3652
  try {
3844
3653
  await this.remoteStorage.deleteFile(attachment);
3845
3654
  if (attachment.localUri) {
3846
3655
  await this.localStorage.deleteFile(attachment.localUri);
3847
3656
  }
3848
- await this.attachmentService.withContext(async (ctx) => {
3849
- await ctx.deleteAttachment(attachment.id);
3850
- });
3657
+ await context.deleteAttachment(attachment.id);
3851
3658
  return {
3852
3659
  ...attachment,
3853
3660
  state: AttachmentState.ARCHIVED
@@ -3885,32 +3692,108 @@ class SyncingService {
3885
3692
  }
3886
3693
 
3887
3694
  /**
3888
- * Wrapper for async-mutex runExclusive, which allows for a timeout on each exclusive lock.
3695
+ * An asynchronous mutex implementation.
3696
+ *
3697
+ * @internal This class is meant to be used in PowerSync SDKs only, and is not part of the public API.
3889
3698
  */
3890
- async function mutexRunExclusive(mutex, callback, options) {
3891
- return new Promise((resolve, reject) => {
3892
- const timeout = options?.timeoutMs;
3893
- let timedOut = false;
3894
- const timeoutId = timeout
3895
- ? setTimeout(() => {
3896
- timedOut = true;
3897
- reject(new Error('Timeout waiting for lock'));
3898
- }, timeout)
3899
- : undefined;
3900
- mutex.runExclusive(async () => {
3901
- if (timeoutId) {
3902
- clearTimeout(timeoutId);
3699
+ class Mutex {
3700
+ inCriticalSection = false;
3701
+ // Linked list of waiters. We don't expect the wait list to become particularly large, and this allows removing
3702
+ // aborted waiters from the middle of the list efficiently.
3703
+ firstWaiter;
3704
+ lastWaiter;
3705
+ addWaiter(onAcquire) {
3706
+ const node = {
3707
+ isActive: true,
3708
+ onAcquire,
3709
+ prev: this.lastWaiter
3710
+ };
3711
+ if (this.lastWaiter) {
3712
+ this.lastWaiter.next = node;
3713
+ this.lastWaiter = node;
3714
+ }
3715
+ else {
3716
+ // First waiter
3717
+ this.lastWaiter = this.firstWaiter = node;
3718
+ }
3719
+ return node;
3720
+ }
3721
+ deactivateWaiter(waiter) {
3722
+ const { prev, next } = waiter;
3723
+ waiter.isActive = false;
3724
+ if (prev)
3725
+ prev.next = next;
3726
+ if (next)
3727
+ next.prev = prev;
3728
+ if (waiter == this.firstWaiter)
3729
+ this.firstWaiter = next;
3730
+ if (waiter == this.lastWaiter)
3731
+ this.lastWaiter = prev;
3732
+ }
3733
+ acquire(abort) {
3734
+ return new Promise((resolve, reject) => {
3735
+ function rejectAborted() {
3736
+ reject(abort?.reason ?? new Error('Mutex acquire aborted'));
3903
3737
  }
3904
- if (timedOut)
3905
- return;
3906
- try {
3907
- resolve(await callback());
3738
+ if (abort?.aborted) {
3739
+ return rejectAborted();
3908
3740
  }
3909
- catch (ex) {
3910
- reject(ex);
3741
+ let holdsMutex = false;
3742
+ const markCompleted = () => {
3743
+ if (!holdsMutex)
3744
+ return;
3745
+ holdsMutex = false;
3746
+ const waiter = this.firstWaiter;
3747
+ if (waiter) {
3748
+ this.deactivateWaiter(waiter);
3749
+ // Still in critical section, but owned by next waiter now.
3750
+ waiter.onAcquire();
3751
+ }
3752
+ else {
3753
+ this.inCriticalSection = false;
3754
+ }
3755
+ };
3756
+ if (!this.inCriticalSection) {
3757
+ this.inCriticalSection = true;
3758
+ holdsMutex = true;
3759
+ return resolve(markCompleted);
3760
+ }
3761
+ else {
3762
+ let node;
3763
+ const onAbort = () => {
3764
+ abort?.removeEventListener('abort', onAbort);
3765
+ if (node.isActive) {
3766
+ this.deactivateWaiter(node);
3767
+ rejectAborted();
3768
+ }
3769
+ };
3770
+ node = this.addWaiter(() => {
3771
+ abort?.removeEventListener('abort', onAbort);
3772
+ holdsMutex = true;
3773
+ resolve(markCompleted);
3774
+ });
3775
+ abort?.addEventListener('abort', onAbort);
3911
3776
  }
3912
3777
  });
3913
- });
3778
+ }
3779
+ async runExclusive(fn, abort) {
3780
+ const returnMutex = await this.acquire(abort);
3781
+ try {
3782
+ return await fn();
3783
+ }
3784
+ finally {
3785
+ returnMutex();
3786
+ }
3787
+ }
3788
+ }
3789
+ function timeoutSignal(timeout) {
3790
+ if (timeout == null)
3791
+ return;
3792
+ if ('timeout' in AbortSignal)
3793
+ return AbortSignal.timeout(timeout);
3794
+ const controller = new AbortController();
3795
+ setTimeout(() => controller.abort(new Error('Timeout waiting for lock')), timeout);
3796
+ return controller.signal;
3914
3797
  }
3915
3798
 
3916
3799
  /**
@@ -3922,7 +3805,7 @@ class AttachmentService {
3922
3805
  db;
3923
3806
  logger;
3924
3807
  tableName;
3925
- mutex = new async_mutex__WEBPACK_IMPORTED_MODULE_0__.Mutex();
3808
+ mutex = new Mutex();
3926
3809
  context;
3927
3810
  constructor(db, logger, tableName = 'attachments', archivedCacheLimit = 100) {
3928
3811
  this.db = db;
@@ -3959,7 +3842,7 @@ class AttachmentService {
3959
3842
  * Executes a callback with exclusive access to the attachment context.
3960
3843
  */
3961
3844
  async withContext(callback) {
3962
- return mutexRunExclusive(this.mutex, async () => {
3845
+ return this.mutex.runExclusive(async () => {
3963
3846
  return callback(this.context);
3964
3847
  });
3965
3848
  }
@@ -3995,9 +3878,15 @@ class AttachmentQueue {
3995
3878
  tableName;
3996
3879
  /** Logger instance for diagnostic information */
3997
3880
  logger;
3998
- /** Interval in milliseconds between periodic sync operations. Default: 30000 (30 seconds) */
3881
+ /** Interval in milliseconds between periodic sync operations. Acts as a polling timer to retry
3882
+ * failed uploads/downloads, especially after the app goes offline. Default: 30000 (30 seconds) */
3999
3883
  syncIntervalMs = 30 * 1000;
4000
- /** Duration in milliseconds to throttle sync operations */
3884
+ /** Throttle duration in milliseconds for the reactive watch query on the attachments table.
3885
+ * When attachment records change, a watch query detects the change and triggers a sync.
3886
+ * This throttle prevents the sync from firing too rapidly when many changes happen in
3887
+ * quick succession (e.g., bulk inserts). This is distinct from syncIntervalMs — it controls
3888
+ * how quickly the queue reacts to changes, while syncIntervalMs controls how often it polls
3889
+ * for retries. Default: 30 (from DEFAULT_WATCH_THROTTLE_MS) */
4001
3890
  syncThrottleDuration;
4002
3891
  /** Whether to automatically download remote attachments. Default: true */
4003
3892
  downloadAttachments = true;
@@ -4021,8 +3910,8 @@ class AttachmentQueue {
4021
3910
  * @param options.watchAttachments - Callback for monitoring attachment changes in your data model
4022
3911
  * @param options.tableName - Name of the table to store attachment records. Default: 'ps_attachment_queue'
4023
3912
  * @param options.logger - Logger instance. Defaults to db.logger
4024
- * @param options.syncIntervalMs - Interval between automatic syncs in milliseconds. Default: 30000
4025
- * @param options.syncThrottleDuration - Throttle duration for sync operations in milliseconds. Default: 1000
3913
+ * @param options.syncIntervalMs - Periodic polling interval in milliseconds for retrying failed uploads/downloads. Default: 30000
3914
+ * @param options.syncThrottleDuration - Throttle duration in milliseconds for the reactive watch query that detects attachment changes. Prevents rapid-fire syncs during bulk changes. Default: 30
4026
3915
  * @param options.downloadAttachments - Whether to automatically download remote attachments. Default: true
4027
3916
  * @param options.archivedCacheLimit - Maximum archived attachments before cleanup. Default: 100
4028
3917
  */
@@ -13683,7 +13572,7 @@ function requireDist () {
13683
13572
 
13684
13573
  var distExports = requireDist();
13685
13574
 
13686
- var version = "1.49.0";
13575
+ var version = "1.50.0";
13687
13576
  var PACKAGE = {
13688
13577
  version: version};
13689
13578
 
@@ -16075,7 +15964,7 @@ class AbstractPowerSyncDatabase extends BaseObserver {
16075
15964
  this._schema = schema;
16076
15965
  this.ready = false;
16077
15966
  this.sdkVersion = '';
16078
- this.runExclusiveMutex = new async_mutex__WEBPACK_IMPORTED_MODULE_0__.Mutex();
15967
+ this.runExclusiveMutex = new Mutex();
16079
15968
  // Start async init
16080
15969
  this.subscriptions = {
16081
15970
  firstStatusMatching: (predicate, abort) => this.waitForStatus(predicate, abort),
@@ -16540,6 +16429,10 @@ SELECT * FROM crud_entries;
16540
16429
  * Execute a SQL write (INSERT/UPDATE/DELETE) query
16541
16430
  * and optionally return results.
16542
16431
  *
16432
+ * When using the default client-side [JSON-based view system](https://docs.powersync.com/architecture/client-architecture#client-side-schema-and-sqlite-database-structure),
16433
+ * the returned result's `rowsAffected` may be `0` for successful `UPDATE` and `DELETE` statements.
16434
+ * Use a `RETURNING` clause and inspect `result.rows` when you need to confirm which rows changed.
16435
+ *
16543
16436
  * @param sql The SQL query to execute
16544
16437
  * @param parameters Optional array of parameters to bind to the query
16545
16438
  * @returns The query result as an object with structured key-value pairs
@@ -16636,7 +16529,7 @@ SELECT * FROM crud_entries;
16636
16529
  async readTransaction(callback, lockTimeout = DEFAULT_LOCK_TIMEOUT_MS) {
16637
16530
  await this.waitForReady();
16638
16531
  return this.database.readTransaction(async (tx) => {
16639
- const res = await callback({ ...tx });
16532
+ const res = await callback(tx);
16640
16533
  await tx.rollback();
16641
16534
  return res;
16642
16535
  }, { timeoutMs: lockTimeout });
@@ -17792,9 +17685,7 @@ __webpack_require__.r(__webpack_exports__);
17792
17685
  /* harmony import */ var _journeyapps_wa_sqlite__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @journeyapps/wa-sqlite */ "../../node_modules/.pnpm/@journeyapps+wa-sqlite@1.5.0/node_modules/@journeyapps/wa-sqlite/src/sqlite-api.js");
17793
17686
  /* harmony import */ var _powersync_common__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @powersync/common */ "../common/dist/bundle.mjs");
17794
17687
  /* harmony import */ var comlink__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! comlink */ "../../node_modules/.pnpm/comlink@4.4.2/node_modules/comlink/dist/esm/comlink.mjs");
17795
- /* harmony import */ var _shared_navigator_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../../shared/navigator.js */ "./lib/src/shared/navigator.js");
17796
- /* harmony import */ var _SharedWASQLiteConnection_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./SharedWASQLiteConnection.js */ "./lib/src/worker/db/SharedWASQLiteConnection.js");
17797
- /* harmony import */ var _WorkerWASQLiteConnection_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./WorkerWASQLiteConnection.js */ "./lib/src/worker/db/WorkerWASQLiteConnection.js");
17688
+ /* harmony import */ var _MultiDatabaseServer_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./MultiDatabaseServer.js */ "./lib/src/worker/db/MultiDatabaseServer.js");
17798
17689
  /**
17799
17690
  * Supports both shared and dedicated workers, based on how the worker is constructed (new SharedWorker vs new Worker()).
17800
17691
  */
@@ -17802,67 +17693,28 @@ __webpack_require__.r(__webpack_exports__);
17802
17693
 
17803
17694
 
17804
17695
 
17805
-
17806
-
17807
17696
  const baseLogger = (0,_powersync_common__WEBPACK_IMPORTED_MODULE_1__.createBaseLogger)();
17808
17697
  baseLogger.useDefaults();
17809
17698
  const logger = (0,_powersync_common__WEBPACK_IMPORTED_MODULE_1__.createLogger)('db-worker');
17810
- const DBMap = new Map();
17811
- const OPEN_DB_LOCK = 'open-wasqlite-db';
17812
- let nextClientId = 1;
17813
- const openDBShared = async (options) => {
17814
- // Prevent multiple simultaneous opens from causing race conditions
17815
- return (0,_shared_navigator_js__WEBPACK_IMPORTED_MODULE_3__.getNavigatorLocks)().request(OPEN_DB_LOCK, async () => {
17816
- const clientId = nextClientId++;
17817
- const { dbFilename, logLevel } = options;
17818
- logger.setLevel(logLevel);
17819
- if (!DBMap.has(dbFilename)) {
17820
- const clientIds = new Set();
17821
- // This format returns proxy objects for function callbacks
17822
- const connection = new _WorkerWASQLiteConnection_js__WEBPACK_IMPORTED_MODULE_5__.WorkerWASQLiteConnection(options);
17823
- await connection.init();
17824
- connection.registerListener({
17825
- holdOverwritten: async () => {
17826
- /**
17827
- * The previous hold has been overwritten, without being released.
17828
- * we need to cleanup any resources associated with it.
17829
- * We can perform a rollback to release any potential transactions that were started.
17830
- */
17831
- await connection.execute('ROLLBACK').catch(() => { });
17832
- }
17833
- });
17834
- DBMap.set(dbFilename, {
17835
- clientIds,
17836
- db: connection
17837
- });
17838
- }
17839
- // Associates this clientId with the shared connection entry
17840
- const sharedConnection = new _SharedWASQLiteConnection_js__WEBPACK_IMPORTED_MODULE_4__.SharedWASQLiteConnection({
17841
- dbMap: DBMap,
17842
- dbFilename,
17843
- clientId,
17844
- logger
17845
- });
17846
- return comlink__WEBPACK_IMPORTED_MODULE_2__.proxy(sharedConnection);
17847
- });
17699
+ const server = new _MultiDatabaseServer_js__WEBPACK_IMPORTED_MODULE_3__.MultiDatabaseServer(logger);
17700
+ const exposedFunctions = {
17701
+ connect: (config) => server.handleConnection(config),
17702
+ connectToExisting: ({ identifier, lockName }) => server.connectToExisting(identifier, lockName)
17848
17703
  };
17849
17704
  // Check if we're in a SharedWorker context
17850
- if (typeof SharedWorkerGlobalScope !== 'undefined') {
17705
+ if (_MultiDatabaseServer_js__WEBPACK_IMPORTED_MODULE_3__.isSharedWorker) {
17851
17706
  const _self = self;
17852
17707
  _self.onconnect = function (event) {
17853
17708
  const port = event.ports[0];
17854
- comlink__WEBPACK_IMPORTED_MODULE_2__.expose(openDBShared, port);
17709
+ comlink__WEBPACK_IMPORTED_MODULE_2__.expose(exposedFunctions, port);
17855
17710
  };
17856
17711
  }
17857
17712
  else {
17858
17713
  // A dedicated worker can be shared externally
17859
- comlink__WEBPACK_IMPORTED_MODULE_2__.expose(openDBShared);
17714
+ comlink__WEBPACK_IMPORTED_MODULE_2__.expose(exposedFunctions);
17860
17715
  }
17861
17716
  addEventListener('unload', () => {
17862
- Array.from(DBMap.values()).forEach(async (dbConnection) => {
17863
- const { db } = dbConnection;
17864
- db.close?.();
17865
- });
17717
+ server.closeAll();
17866
17718
  });
17867
17719
 
17868
17720
  })();